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

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_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg.pt +3 -0
  5. ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg_sq.pt +3 -0
  6. ckpts/universal/global_step60/zero/22.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
  7. ckpts/universal/global_step60/zero/7.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  8. venv/lib/python3.10/site-packages/numpy/_utils/__init__.py +29 -0
  9. venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_convertions.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_inspect.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/numpy/_utils/_convertions.py +18 -0
  12. venv/lib/python3.10/site-packages/numpy/_utils/_inspect.py +191 -0
  13. venv/lib/python3.10/site-packages/numpy/_utils/_pep440.py +487 -0
  14. venv/lib/python3.10/site-packages/numpy/linalg/__init__.py +80 -0
  15. venv/lib/python3.10/site-packages/numpy/linalg/__init__.pyi +30 -0
  16. venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so +0 -0
  19. venv/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so +0 -0
  20. venv/lib/python3.10/site-packages/numpy/linalg/linalg.py +2836 -0
  21. venv/lib/python3.10/site-packages/numpy/linalg/linalg.pyi +297 -0
  22. venv/lib/python3.10/site-packages/numpy/linalg/tests/__init__.py +0 -0
  23. venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/numpy/linalg/tests/test_deprecations.py +20 -0
  28. venv/lib/python3.10/site-packages/numpy/linalg/tests/test_linalg.py +2198 -0
  29. venv/lib/python3.10/site-packages/numpy/linalg/tests/test_regression.py +145 -0
  30. venv/lib/python3.10/site-packages/numpy/ma/LICENSE +24 -0
  31. venv/lib/python3.10/site-packages/numpy/ma/README.rst +236 -0
  32. venv/lib/python3.10/site-packages/numpy/ma/__init__.py +54 -0
  33. venv/lib/python3.10/site-packages/numpy/ma/__init__.pyi +234 -0
  34. venv/lib/python3.10/site-packages/numpy/ma/__pycache__/__init__.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/numpy/ma/__pycache__/extras.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/numpy/ma/__pycache__/mrecords.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/numpy/ma/__pycache__/setup.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/numpy/ma/__pycache__/testutils.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/numpy/ma/__pycache__/timer_comparison.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/numpy/ma/core.py +0 -0
  42. venv/lib/python3.10/site-packages/numpy/ma/core.pyi +471 -0
  43. venv/lib/python3.10/site-packages/numpy/ma/extras.pyi +85 -0
  44. venv/lib/python3.10/site-packages/numpy/ma/mrecords.pyi +90 -0
  45. venv/lib/python3.10/site-packages/numpy/ma/tests/__init__.py +0 -0
  46. venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_deprecations.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_extras.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_mrecords.cpython-310.pyc +0 -0
ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c5cf66504193ddfc2f1a66aab0560cd5eaa7453205ac8c09ac87876001e734b
3
+ size 33555612
ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38d6824ac47b721ab1a9e34448572f832bc7e5e60f18216cafb57b38fafe9fcc
3
+ size 33555627
ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfc7a15498a589c0fdde19f3e022679301f6ca0f35e7a901ac863216f9c03b3b
3
+ size 33555533
ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27da9c6159be5e36247fd7e2e11deff175a7b49a0396079364f9422b1c34aca3
3
+ size 16778396
ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d0385130c0db44568b7d1560887bb48b2c29039dd0d362e48106aa24ba14d5e
3
+ size 16778411
ckpts/universal/global_step60/zero/22.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6917da9b2c7e936632420afb61a22f551a9b5fba59e43be876f844343826482
3
+ size 33555612
ckpts/universal/global_step60/zero/7.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f9a59fbed1ed282cf87f7cea6ad615a54b186e8853e8abe12d7294a2f88efe8
3
+ size 33555627
venv/lib/python3.10/site-packages/numpy/_utils/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This is a module for defining private helpers which do not depend on the
3
+ rest of NumPy.
4
+
5
+ Everything in here must be self-contained so that it can be
6
+ imported anywhere else without creating circular imports.
7
+ If a utility requires the import of NumPy, it probably belongs
8
+ in ``numpy.core``.
9
+ """
10
+
11
+ from ._convertions import asunicode, asbytes
12
+
13
+
14
+ def set_module(module):
15
+ """Private decorator for overriding __module__ on a function or class.
16
+
17
+ Example usage::
18
+
19
+ @set_module('numpy')
20
+ def example():
21
+ pass
22
+
23
+ assert example.__module__ == 'numpy'
24
+ """
25
+ def decorator(func):
26
+ if module is not None:
27
+ func.__module__ = module
28
+ return func
29
+ return decorator
venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_convertions.cpython-310.pyc ADDED
Binary file (622 Bytes). View file
 
venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_inspect.cpython-310.pyc ADDED
Binary file (7.62 kB). View file
 
venv/lib/python3.10/site-packages/numpy/_utils/_convertions.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A set of methods retained from np.compat module that
3
+ are still used across codebase.
4
+ """
5
+
6
+ __all__ = ["asunicode", "asbytes"]
7
+
8
+
9
+ def asunicode(s):
10
+ if isinstance(s, bytes):
11
+ return s.decode('latin1')
12
+ return str(s)
13
+
14
+
15
+ def asbytes(s):
16
+ if isinstance(s, bytes):
17
+ return s
18
+ return str(s).encode('latin1')
venv/lib/python3.10/site-packages/numpy/_utils/_inspect.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Subset of inspect module from upstream python
2
+
3
+ We use this instead of upstream because upstream inspect is slow to import, and
4
+ significantly contributes to numpy import times. Importing this copy has almost
5
+ no overhead.
6
+
7
+ """
8
+ import types
9
+
10
+ __all__ = ['getargspec', 'formatargspec']
11
+
12
+ # ----------------------------------------------------------- type-checking
13
+ def ismethod(object):
14
+ """Return true if the object is an instance method.
15
+
16
+ Instance method objects provide these attributes:
17
+ __doc__ documentation string
18
+ __name__ name with which this method was defined
19
+ im_class class object in which this method belongs
20
+ im_func function object containing implementation of method
21
+ im_self instance to which this method is bound, or None
22
+
23
+ """
24
+ return isinstance(object, types.MethodType)
25
+
26
+ def isfunction(object):
27
+ """Return true if the object is a user-defined function.
28
+
29
+ Function objects provide these attributes:
30
+ __doc__ documentation string
31
+ __name__ name with which this function was defined
32
+ func_code code object containing compiled function bytecode
33
+ func_defaults tuple of any default values for arguments
34
+ func_doc (same as __doc__)
35
+ func_globals global namespace in which this function was defined
36
+ func_name (same as __name__)
37
+
38
+ """
39
+ return isinstance(object, types.FunctionType)
40
+
41
+ def iscode(object):
42
+ """Return true if the object is a code object.
43
+
44
+ Code objects provide these attributes:
45
+ co_argcount number of arguments (not including * or ** args)
46
+ co_code string of raw compiled bytecode
47
+ co_consts tuple of constants used in the bytecode
48
+ co_filename name of file in which this code object was created
49
+ co_firstlineno number of first line in Python source code
50
+ co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
51
+ co_lnotab encoded mapping of line numbers to bytecode indices
52
+ co_name name with which this code object was defined
53
+ co_names tuple of names of local variables
54
+ co_nlocals number of local variables
55
+ co_stacksize virtual machine stack space required
56
+ co_varnames tuple of names of arguments and local variables
57
+
58
+ """
59
+ return isinstance(object, types.CodeType)
60
+
61
+ # ------------------------------------------------ argument list extraction
62
+ # These constants are from Python's compile.h.
63
+ CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
64
+
65
+ def getargs(co):
66
+ """Get information about the arguments accepted by a code object.
67
+
68
+ Three things are returned: (args, varargs, varkw), where 'args' is
69
+ a list of argument names (possibly containing nested lists), and
70
+ 'varargs' and 'varkw' are the names of the * and ** arguments or None.
71
+
72
+ """
73
+
74
+ if not iscode(co):
75
+ raise TypeError('arg is not a code object')
76
+
77
+ nargs = co.co_argcount
78
+ names = co.co_varnames
79
+ args = list(names[:nargs])
80
+
81
+ # The following acrobatics are for anonymous (tuple) arguments.
82
+ # Which we do not need to support, so remove to avoid importing
83
+ # the dis module.
84
+ for i in range(nargs):
85
+ if args[i][:1] in ['', '.']:
86
+ raise TypeError("tuple function arguments are not supported")
87
+ varargs = None
88
+ if co.co_flags & CO_VARARGS:
89
+ varargs = co.co_varnames[nargs]
90
+ nargs = nargs + 1
91
+ varkw = None
92
+ if co.co_flags & CO_VARKEYWORDS:
93
+ varkw = co.co_varnames[nargs]
94
+ return args, varargs, varkw
95
+
96
+ def getargspec(func):
97
+ """Get the names and default values of a function's arguments.
98
+
99
+ A tuple of four things is returned: (args, varargs, varkw, defaults).
100
+ 'args' is a list of the argument names (it may contain nested lists).
101
+ 'varargs' and 'varkw' are the names of the * and ** arguments or None.
102
+ 'defaults' is an n-tuple of the default values of the last n arguments.
103
+
104
+ """
105
+
106
+ if ismethod(func):
107
+ func = func.__func__
108
+ if not isfunction(func):
109
+ raise TypeError('arg is not a Python function')
110
+ args, varargs, varkw = getargs(func.__code__)
111
+ return args, varargs, varkw, func.__defaults__
112
+
113
+ def getargvalues(frame):
114
+ """Get information about arguments passed into a particular frame.
115
+
116
+ A tuple of four things is returned: (args, varargs, varkw, locals).
117
+ 'args' is a list of the argument names (it may contain nested lists).
118
+ 'varargs' and 'varkw' are the names of the * and ** arguments or None.
119
+ 'locals' is the locals dictionary of the given frame.
120
+
121
+ """
122
+ args, varargs, varkw = getargs(frame.f_code)
123
+ return args, varargs, varkw, frame.f_locals
124
+
125
+ def joinseq(seq):
126
+ if len(seq) == 1:
127
+ return '(' + seq[0] + ',)'
128
+ else:
129
+ return '(' + ', '.join(seq) + ')'
130
+
131
+ def strseq(object, convert, join=joinseq):
132
+ """Recursively walk a sequence, stringifying each element.
133
+
134
+ """
135
+ if type(object) in [list, tuple]:
136
+ return join([strseq(_o, convert, join) for _o in object])
137
+ else:
138
+ return convert(object)
139
+
140
+ def formatargspec(args, varargs=None, varkw=None, defaults=None,
141
+ formatarg=str,
142
+ formatvarargs=lambda name: '*' + name,
143
+ formatvarkw=lambda name: '**' + name,
144
+ formatvalue=lambda value: '=' + repr(value),
145
+ join=joinseq):
146
+ """Format an argument spec from the 4 values returned by getargspec.
147
+
148
+ The first four arguments are (args, varargs, varkw, defaults). The
149
+ other four arguments are the corresponding optional formatting functions
150
+ that are called to turn names and values into strings. The ninth
151
+ argument is an optional function to format the sequence of arguments.
152
+
153
+ """
154
+ specs = []
155
+ if defaults:
156
+ firstdefault = len(args) - len(defaults)
157
+ for i in range(len(args)):
158
+ spec = strseq(args[i], formatarg, join)
159
+ if defaults and i >= firstdefault:
160
+ spec = spec + formatvalue(defaults[i - firstdefault])
161
+ specs.append(spec)
162
+ if varargs is not None:
163
+ specs.append(formatvarargs(varargs))
164
+ if varkw is not None:
165
+ specs.append(formatvarkw(varkw))
166
+ return '(' + ', '.join(specs) + ')'
167
+
168
+ def formatargvalues(args, varargs, varkw, locals,
169
+ formatarg=str,
170
+ formatvarargs=lambda name: '*' + name,
171
+ formatvarkw=lambda name: '**' + name,
172
+ formatvalue=lambda value: '=' + repr(value),
173
+ join=joinseq):
174
+ """Format an argument spec from the 4 values returned by getargvalues.
175
+
176
+ The first four arguments are (args, varargs, varkw, locals). The
177
+ next four arguments are the corresponding optional formatting functions
178
+ that are called to turn names and values into strings. The ninth
179
+ argument is an optional function to format the sequence of arguments.
180
+
181
+ """
182
+ def convert(name, locals=locals,
183
+ formatarg=formatarg, formatvalue=formatvalue):
184
+ return formatarg(name) + formatvalue(locals[name])
185
+ specs = [strseq(arg, convert, join) for arg in args]
186
+
187
+ if varargs:
188
+ specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
189
+ if varkw:
190
+ specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
191
+ return '(' + ', '.join(specs) + ')'
venv/lib/python3.10/site-packages/numpy/_utils/_pep440.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility to compare pep440 compatible version strings.
2
+
3
+ The LooseVersion and StrictVersion classes that distutils provides don't
4
+ work; they don't recognize anything like alpha/beta/rc/dev versions.
5
+ """
6
+
7
+ # Copyright (c) Donald Stufft and individual contributors.
8
+ # All rights reserved.
9
+
10
+ # Redistribution and use in source and binary forms, with or without
11
+ # modification, are permitted provided that the following conditions are met:
12
+
13
+ # 1. Redistributions of source code must retain the above copyright notice,
14
+ # this list of conditions and the following disclaimer.
15
+
16
+ # 2. Redistributions in binary form must reproduce the above copyright
17
+ # notice, this list of conditions and the following disclaimer in the
18
+ # documentation and/or other materials provided with the distribution.
19
+
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ # POSSIBILITY OF SUCH DAMAGE.
31
+
32
+ import collections
33
+ import itertools
34
+ import re
35
+
36
+
37
+ __all__ = [
38
+ "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN",
39
+ ]
40
+
41
+
42
+ # BEGIN packaging/_structures.py
43
+
44
+
45
+ class Infinity:
46
+ def __repr__(self):
47
+ return "Infinity"
48
+
49
+ def __hash__(self):
50
+ return hash(repr(self))
51
+
52
+ def __lt__(self, other):
53
+ return False
54
+
55
+ def __le__(self, other):
56
+ return False
57
+
58
+ def __eq__(self, other):
59
+ return isinstance(other, self.__class__)
60
+
61
+ def __ne__(self, other):
62
+ return not isinstance(other, self.__class__)
63
+
64
+ def __gt__(self, other):
65
+ return True
66
+
67
+ def __ge__(self, other):
68
+ return True
69
+
70
+ def __neg__(self):
71
+ return NegativeInfinity
72
+
73
+
74
+ Infinity = Infinity()
75
+
76
+
77
+ class NegativeInfinity:
78
+ def __repr__(self):
79
+ return "-Infinity"
80
+
81
+ def __hash__(self):
82
+ return hash(repr(self))
83
+
84
+ def __lt__(self, other):
85
+ return True
86
+
87
+ def __le__(self, other):
88
+ return True
89
+
90
+ def __eq__(self, other):
91
+ return isinstance(other, self.__class__)
92
+
93
+ def __ne__(self, other):
94
+ return not isinstance(other, self.__class__)
95
+
96
+ def __gt__(self, other):
97
+ return False
98
+
99
+ def __ge__(self, other):
100
+ return False
101
+
102
+ def __neg__(self):
103
+ return Infinity
104
+
105
+
106
+ # BEGIN packaging/version.py
107
+
108
+
109
+ NegativeInfinity = NegativeInfinity()
110
+
111
+ _Version = collections.namedtuple(
112
+ "_Version",
113
+ ["epoch", "release", "dev", "pre", "post", "local"],
114
+ )
115
+
116
+
117
+ def parse(version):
118
+ """
119
+ Parse the given version string and return either a :class:`Version` object
120
+ or a :class:`LegacyVersion` object depending on if the given version is
121
+ a valid PEP 440 version or a legacy version.
122
+ """
123
+ try:
124
+ return Version(version)
125
+ except InvalidVersion:
126
+ return LegacyVersion(version)
127
+
128
+
129
+ class InvalidVersion(ValueError):
130
+ """
131
+ An invalid version was found, users should refer to PEP 440.
132
+ """
133
+
134
+
135
+ class _BaseVersion:
136
+
137
+ def __hash__(self):
138
+ return hash(self._key)
139
+
140
+ def __lt__(self, other):
141
+ return self._compare(other, lambda s, o: s < o)
142
+
143
+ def __le__(self, other):
144
+ return self._compare(other, lambda s, o: s <= o)
145
+
146
+ def __eq__(self, other):
147
+ return self._compare(other, lambda s, o: s == o)
148
+
149
+ def __ge__(self, other):
150
+ return self._compare(other, lambda s, o: s >= o)
151
+
152
+ def __gt__(self, other):
153
+ return self._compare(other, lambda s, o: s > o)
154
+
155
+ def __ne__(self, other):
156
+ return self._compare(other, lambda s, o: s != o)
157
+
158
+ def _compare(self, other, method):
159
+ if not isinstance(other, _BaseVersion):
160
+ return NotImplemented
161
+
162
+ return method(self._key, other._key)
163
+
164
+
165
+ class LegacyVersion(_BaseVersion):
166
+
167
+ def __init__(self, version):
168
+ self._version = str(version)
169
+ self._key = _legacy_cmpkey(self._version)
170
+
171
+ def __str__(self):
172
+ return self._version
173
+
174
+ def __repr__(self):
175
+ return "<LegacyVersion({0})>".format(repr(str(self)))
176
+
177
+ @property
178
+ def public(self):
179
+ return self._version
180
+
181
+ @property
182
+ def base_version(self):
183
+ return self._version
184
+
185
+ @property
186
+ def local(self):
187
+ return None
188
+
189
+ @property
190
+ def is_prerelease(self):
191
+ return False
192
+
193
+ @property
194
+ def is_postrelease(self):
195
+ return False
196
+
197
+
198
+ _legacy_version_component_re = re.compile(
199
+ r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
200
+ )
201
+
202
+ _legacy_version_replacement_map = {
203
+ "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
204
+ }
205
+
206
+
207
+ def _parse_version_parts(s):
208
+ for part in _legacy_version_component_re.split(s):
209
+ part = _legacy_version_replacement_map.get(part, part)
210
+
211
+ if not part or part == ".":
212
+ continue
213
+
214
+ if part[:1] in "0123456789":
215
+ # pad for numeric comparison
216
+ yield part.zfill(8)
217
+ else:
218
+ yield "*" + part
219
+
220
+ # ensure that alpha/beta/candidate are before final
221
+ yield "*final"
222
+
223
+
224
+ def _legacy_cmpkey(version):
225
+ # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch
226
+ # greater than or equal to 0. This will effectively put the LegacyVersion,
227
+ # which uses the defacto standard originally implemented by setuptools,
228
+ # as before all PEP 440 versions.
229
+ epoch = -1
230
+
231
+ # This scheme is taken from pkg_resources.parse_version setuptools prior to
232
+ # its adoption of the packaging library.
233
+ parts = []
234
+ for part in _parse_version_parts(version.lower()):
235
+ if part.startswith("*"):
236
+ # remove "-" before a prerelease tag
237
+ if part < "*final":
238
+ while parts and parts[-1] == "*final-":
239
+ parts.pop()
240
+
241
+ # remove trailing zeros from each series of numeric parts
242
+ while parts and parts[-1] == "00000000":
243
+ parts.pop()
244
+
245
+ parts.append(part)
246
+ parts = tuple(parts)
247
+
248
+ return epoch, parts
249
+
250
+
251
+ # Deliberately not anchored to the start and end of the string, to make it
252
+ # easier for 3rd party code to reuse
253
+ VERSION_PATTERN = r"""
254
+ v?
255
+ (?:
256
+ (?:(?P<epoch>[0-9]+)!)? # epoch
257
+ (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
258
+ (?P<pre> # pre-release
259
+ [-_\.]?
260
+ (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
261
+ [-_\.]?
262
+ (?P<pre_n>[0-9]+)?
263
+ )?
264
+ (?P<post> # post release
265
+ (?:-(?P<post_n1>[0-9]+))
266
+ |
267
+ (?:
268
+ [-_\.]?
269
+ (?P<post_l>post|rev|r)
270
+ [-_\.]?
271
+ (?P<post_n2>[0-9]+)?
272
+ )
273
+ )?
274
+ (?P<dev> # dev release
275
+ [-_\.]?
276
+ (?P<dev_l>dev)
277
+ [-_\.]?
278
+ (?P<dev_n>[0-9]+)?
279
+ )?
280
+ )
281
+ (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
282
+ """
283
+
284
+
285
+ class Version(_BaseVersion):
286
+
287
+ _regex = re.compile(
288
+ r"^\s*" + VERSION_PATTERN + r"\s*$",
289
+ re.VERBOSE | re.IGNORECASE,
290
+ )
291
+
292
+ def __init__(self, version):
293
+ # Validate the version and parse it into pieces
294
+ match = self._regex.search(version)
295
+ if not match:
296
+ raise InvalidVersion("Invalid version: '{0}'".format(version))
297
+
298
+ # Store the parsed out pieces of the version
299
+ self._version = _Version(
300
+ epoch=int(match.group("epoch")) if match.group("epoch") else 0,
301
+ release=tuple(int(i) for i in match.group("release").split(".")),
302
+ pre=_parse_letter_version(
303
+ match.group("pre_l"),
304
+ match.group("pre_n"),
305
+ ),
306
+ post=_parse_letter_version(
307
+ match.group("post_l"),
308
+ match.group("post_n1") or match.group("post_n2"),
309
+ ),
310
+ dev=_parse_letter_version(
311
+ match.group("dev_l"),
312
+ match.group("dev_n"),
313
+ ),
314
+ local=_parse_local_version(match.group("local")),
315
+ )
316
+
317
+ # Generate a key which will be used for sorting
318
+ self._key = _cmpkey(
319
+ self._version.epoch,
320
+ self._version.release,
321
+ self._version.pre,
322
+ self._version.post,
323
+ self._version.dev,
324
+ self._version.local,
325
+ )
326
+
327
+ def __repr__(self):
328
+ return "<Version({0})>".format(repr(str(self)))
329
+
330
+ def __str__(self):
331
+ parts = []
332
+
333
+ # Epoch
334
+ if self._version.epoch != 0:
335
+ parts.append("{0}!".format(self._version.epoch))
336
+
337
+ # Release segment
338
+ parts.append(".".join(str(x) for x in self._version.release))
339
+
340
+ # Pre-release
341
+ if self._version.pre is not None:
342
+ parts.append("".join(str(x) for x in self._version.pre))
343
+
344
+ # Post-release
345
+ if self._version.post is not None:
346
+ parts.append(".post{0}".format(self._version.post[1]))
347
+
348
+ # Development release
349
+ if self._version.dev is not None:
350
+ parts.append(".dev{0}".format(self._version.dev[1]))
351
+
352
+ # Local version segment
353
+ if self._version.local is not None:
354
+ parts.append(
355
+ "+{0}".format(".".join(str(x) for x in self._version.local))
356
+ )
357
+
358
+ return "".join(parts)
359
+
360
+ @property
361
+ def public(self):
362
+ return str(self).split("+", 1)[0]
363
+
364
+ @property
365
+ def base_version(self):
366
+ parts = []
367
+
368
+ # Epoch
369
+ if self._version.epoch != 0:
370
+ parts.append("{0}!".format(self._version.epoch))
371
+
372
+ # Release segment
373
+ parts.append(".".join(str(x) for x in self._version.release))
374
+
375
+ return "".join(parts)
376
+
377
+ @property
378
+ def local(self):
379
+ version_string = str(self)
380
+ if "+" in version_string:
381
+ return version_string.split("+", 1)[1]
382
+
383
+ @property
384
+ def is_prerelease(self):
385
+ return bool(self._version.dev or self._version.pre)
386
+
387
+ @property
388
+ def is_postrelease(self):
389
+ return bool(self._version.post)
390
+
391
+
392
+ def _parse_letter_version(letter, number):
393
+ if letter:
394
+ # We assume there is an implicit 0 in a pre-release if there is
395
+ # no numeral associated with it.
396
+ if number is None:
397
+ number = 0
398
+
399
+ # We normalize any letters to their lower-case form
400
+ letter = letter.lower()
401
+
402
+ # We consider some words to be alternate spellings of other words and
403
+ # in those cases we want to normalize the spellings to our preferred
404
+ # spelling.
405
+ if letter == "alpha":
406
+ letter = "a"
407
+ elif letter == "beta":
408
+ letter = "b"
409
+ elif letter in ["c", "pre", "preview"]:
410
+ letter = "rc"
411
+ elif letter in ["rev", "r"]:
412
+ letter = "post"
413
+
414
+ return letter, int(number)
415
+ if not letter and number:
416
+ # We assume that if we are given a number but not given a letter,
417
+ # then this is using the implicit post release syntax (e.g., 1.0-1)
418
+ letter = "post"
419
+
420
+ return letter, int(number)
421
+
422
+
423
+ _local_version_seperators = re.compile(r"[\._-]")
424
+
425
+
426
+ def _parse_local_version(local):
427
+ """
428
+ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
429
+ """
430
+ if local is not None:
431
+ return tuple(
432
+ part.lower() if not part.isdigit() else int(part)
433
+ for part in _local_version_seperators.split(local)
434
+ )
435
+
436
+
437
+ def _cmpkey(epoch, release, pre, post, dev, local):
438
+ # When we compare a release version, we want to compare it with all of the
439
+ # trailing zeros removed. So we'll use a reverse the list, drop all the now
440
+ # leading zeros until we come to something non-zero, then take the rest,
441
+ # re-reverse it back into the correct order, and make it a tuple and use
442
+ # that for our sorting key.
443
+ release = tuple(
444
+ reversed(list(
445
+ itertools.dropwhile(
446
+ lambda x: x == 0,
447
+ reversed(release),
448
+ )
449
+ ))
450
+ )
451
+
452
+ # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
453
+ # We'll do this by abusing the pre-segment, but we _only_ want to do this
454
+ # if there is no pre- or a post-segment. If we have one of those, then
455
+ # the normal sorting rules will handle this case correctly.
456
+ if pre is None and post is None and dev is not None:
457
+ pre = -Infinity
458
+ # Versions without a pre-release (except as noted above) should sort after
459
+ # those with one.
460
+ elif pre is None:
461
+ pre = Infinity
462
+
463
+ # Versions without a post-segment should sort before those with one.
464
+ if post is None:
465
+ post = -Infinity
466
+
467
+ # Versions without a development segment should sort after those with one.
468
+ if dev is None:
469
+ dev = Infinity
470
+
471
+ if local is None:
472
+ # Versions without a local segment should sort before those with one.
473
+ local = -Infinity
474
+ else:
475
+ # Versions with a local segment need that segment parsed to implement
476
+ # the sorting rules in PEP440.
477
+ # - Alphanumeric segments sort before numeric segments
478
+ # - Alphanumeric segments sort lexicographically
479
+ # - Numeric segments sort numerically
480
+ # - Shorter versions sort before longer versions when the prefixes
481
+ # match exactly
482
+ local = tuple(
483
+ (i, "") if isinstance(i, int) else (-Infinity, i)
484
+ for i in local
485
+ )
486
+
487
+ return epoch, release, pre, post, dev, local
venv/lib/python3.10/site-packages/numpy/linalg/__init__.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ``numpy.linalg``
3
+ ================
4
+
5
+ The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient
6
+ low level implementations of standard linear algebra algorithms. Those
7
+ libraries may be provided by NumPy itself using C versions of a subset of their
8
+ reference implementations but, when possible, highly optimized libraries that
9
+ take advantage of specialized processor functionality are preferred. Examples
10
+ of such libraries are OpenBLAS, MKL (TM), and ATLAS. Because those libraries
11
+ are multithreaded and processor dependent, environmental variables and external
12
+ packages such as threadpoolctl may be needed to control the number of threads
13
+ or specify the processor architecture.
14
+
15
+ - OpenBLAS: https://www.openblas.net/
16
+ - threadpoolctl: https://github.com/joblib/threadpoolctl
17
+
18
+ Please note that the most-used linear algebra functions in NumPy are present in
19
+ the main ``numpy`` namespace rather than in ``numpy.linalg``. There are:
20
+ ``dot``, ``vdot``, ``inner``, ``outer``, ``matmul``, ``tensordot``, ``einsum``,
21
+ ``einsum_path`` and ``kron``.
22
+
23
+ Functions present in numpy.linalg are listed below.
24
+
25
+
26
+ Matrix and vector products
27
+ --------------------------
28
+
29
+ multi_dot
30
+ matrix_power
31
+
32
+ Decompositions
33
+ --------------
34
+
35
+ cholesky
36
+ qr
37
+ svd
38
+
39
+ Matrix eigenvalues
40
+ ------------------
41
+
42
+ eig
43
+ eigh
44
+ eigvals
45
+ eigvalsh
46
+
47
+ Norms and other numbers
48
+ -----------------------
49
+
50
+ norm
51
+ cond
52
+ det
53
+ matrix_rank
54
+ slogdet
55
+
56
+ Solving equations and inverting matrices
57
+ ----------------------------------------
58
+
59
+ solve
60
+ tensorsolve
61
+ lstsq
62
+ inv
63
+ pinv
64
+ tensorinv
65
+
66
+ Exceptions
67
+ ----------
68
+
69
+ LinAlgError
70
+
71
+ """
72
+ # To get sub-modules
73
+ from . import linalg
74
+ from .linalg import *
75
+
76
+ __all__ = linalg.__all__.copy()
77
+
78
+ from numpy._pytesttester import PytestTester
79
+ test = PytestTester(__name__)
80
+ del PytestTester
venv/lib/python3.10/site-packages/numpy/linalg/__init__.pyi ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy.linalg.linalg import (
2
+ matrix_power as matrix_power,
3
+ solve as solve,
4
+ tensorsolve as tensorsolve,
5
+ tensorinv as tensorinv,
6
+ inv as inv,
7
+ cholesky as cholesky,
8
+ eigvals as eigvals,
9
+ eigvalsh as eigvalsh,
10
+ pinv as pinv,
11
+ slogdet as slogdet,
12
+ det as det,
13
+ svd as svd,
14
+ eig as eig,
15
+ eigh as eigh,
16
+ lstsq as lstsq,
17
+ norm as norm,
18
+ qr as qr,
19
+ cond as cond,
20
+ matrix_rank as matrix_rank,
21
+ multi_dot as multi_dot,
22
+ )
23
+
24
+ from numpy._pytesttester import PytestTester
25
+
26
+ __all__: list[str]
27
+ __path__: list[str]
28
+ test: PytestTester
29
+
30
+ class LinAlgError(Exception): ...
venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc ADDED
Binary file (83.6 kB). View file
 
venv/lib/python3.10/site-packages/numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (217 kB). View file
 
venv/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (29.8 kB). View file
 
venv/lib/python3.10/site-packages/numpy/linalg/linalg.py ADDED
@@ -0,0 +1,2836 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lite version of scipy.linalg.
2
+
3
+ Notes
4
+ -----
5
+ This module is a lite version of the linalg.py module in SciPy which
6
+ contains high-level Python interface to the LAPACK library. The lite
7
+ version only accesses the following LAPACK functions: dgesv, zgesv,
8
+ dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf,
9
+ zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr.
10
+ """
11
+
12
+ __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',
13
+ 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det',
14
+ 'svd', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond', 'matrix_rank',
15
+ 'LinAlgError', 'multi_dot']
16
+
17
+ import functools
18
+ import operator
19
+ import warnings
20
+ from typing import NamedTuple, Any
21
+
22
+ from .._utils import set_module
23
+ from numpy.core import (
24
+ array, asarray, zeros, empty, empty_like, intc, single, double,
25
+ csingle, cdouble, inexact, complexfloating, newaxis, all, Inf, dot,
26
+ add, multiply, sqrt, sum, isfinite,
27
+ finfo, errstate, geterrobj, moveaxis, amin, amax, prod, abs,
28
+ atleast_2d, intp, asanyarray, object_, matmul,
29
+ swapaxes, divide, count_nonzero, isnan, sign, argsort, sort,
30
+ reciprocal
31
+ )
32
+ from numpy.core.multiarray import normalize_axis_index
33
+ from numpy.core import overrides
34
+ from numpy.lib.twodim_base import triu, eye
35
+ from numpy.linalg import _umath_linalg
36
+
37
+ from numpy._typing import NDArray
38
+
39
+ class EigResult(NamedTuple):
40
+ eigenvalues: NDArray[Any]
41
+ eigenvectors: NDArray[Any]
42
+
43
+ class EighResult(NamedTuple):
44
+ eigenvalues: NDArray[Any]
45
+ eigenvectors: NDArray[Any]
46
+
47
+ class QRResult(NamedTuple):
48
+ Q: NDArray[Any]
49
+ R: NDArray[Any]
50
+
51
+ class SlogdetResult(NamedTuple):
52
+ sign: NDArray[Any]
53
+ logabsdet: NDArray[Any]
54
+
55
+ class SVDResult(NamedTuple):
56
+ U: NDArray[Any]
57
+ S: NDArray[Any]
58
+ Vh: NDArray[Any]
59
+
60
+ array_function_dispatch = functools.partial(
61
+ overrides.array_function_dispatch, module='numpy.linalg')
62
+
63
+
64
+ fortran_int = intc
65
+
66
+
67
+ @set_module('numpy.linalg')
68
+ class LinAlgError(ValueError):
69
+ """
70
+ Generic Python-exception-derived object raised by linalg functions.
71
+
72
+ General purpose exception class, derived from Python's ValueError
73
+ class, programmatically raised in linalg functions when a Linear
74
+ Algebra-related condition would prevent further correct execution of the
75
+ function.
76
+
77
+ Parameters
78
+ ----------
79
+ None
80
+
81
+ Examples
82
+ --------
83
+ >>> from numpy import linalg as LA
84
+ >>> LA.inv(np.zeros((2,2)))
85
+ Traceback (most recent call last):
86
+ File "<stdin>", line 1, in <module>
87
+ File "...linalg.py", line 350,
88
+ in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
89
+ File "...linalg.py", line 249,
90
+ in solve
91
+ raise LinAlgError('Singular matrix')
92
+ numpy.linalg.LinAlgError: Singular matrix
93
+
94
+ """
95
+
96
+
97
+ def _determine_error_states():
98
+ errobj = geterrobj()
99
+ bufsize = errobj[0]
100
+
101
+ with errstate(invalid='call', over='ignore',
102
+ divide='ignore', under='ignore'):
103
+ invalid_call_errmask = geterrobj()[1]
104
+
105
+ return [bufsize, invalid_call_errmask, None]
106
+
107
+ # Dealing with errors in _umath_linalg
108
+ _linalg_error_extobj = _determine_error_states()
109
+ del _determine_error_states
110
+
111
+ def _raise_linalgerror_singular(err, flag):
112
+ raise LinAlgError("Singular matrix")
113
+
114
+ def _raise_linalgerror_nonposdef(err, flag):
115
+ raise LinAlgError("Matrix is not positive definite")
116
+
117
+ def _raise_linalgerror_eigenvalues_nonconvergence(err, flag):
118
+ raise LinAlgError("Eigenvalues did not converge")
119
+
120
+ def _raise_linalgerror_svd_nonconvergence(err, flag):
121
+ raise LinAlgError("SVD did not converge")
122
+
123
+ def _raise_linalgerror_lstsq(err, flag):
124
+ raise LinAlgError("SVD did not converge in Linear Least Squares")
125
+
126
+ def _raise_linalgerror_qr(err, flag):
127
+ raise LinAlgError("Incorrect argument found while performing "
128
+ "QR factorization")
129
+
130
+ def get_linalg_error_extobj(callback):
131
+ extobj = list(_linalg_error_extobj) # make a copy
132
+ extobj[2] = callback
133
+ return extobj
134
+
135
+ def _makearray(a):
136
+ new = asarray(a)
137
+ wrap = getattr(a, "__array_prepare__", new.__array_wrap__)
138
+ return new, wrap
139
+
140
+ def isComplexType(t):
141
+ return issubclass(t, complexfloating)
142
+
143
+ _real_types_map = {single : single,
144
+ double : double,
145
+ csingle : single,
146
+ cdouble : double}
147
+
148
+ _complex_types_map = {single : csingle,
149
+ double : cdouble,
150
+ csingle : csingle,
151
+ cdouble : cdouble}
152
+
153
+ def _realType(t, default=double):
154
+ return _real_types_map.get(t, default)
155
+
156
+ def _complexType(t, default=cdouble):
157
+ return _complex_types_map.get(t, default)
158
+
159
+ def _commonType(*arrays):
160
+ # in lite version, use higher precision (always double or cdouble)
161
+ result_type = single
162
+ is_complex = False
163
+ for a in arrays:
164
+ type_ = a.dtype.type
165
+ if issubclass(type_, inexact):
166
+ if isComplexType(type_):
167
+ is_complex = True
168
+ rt = _realType(type_, default=None)
169
+ if rt is double:
170
+ result_type = double
171
+ elif rt is None:
172
+ # unsupported inexact scalar
173
+ raise TypeError("array type %s is unsupported in linalg" %
174
+ (a.dtype.name,))
175
+ else:
176
+ result_type = double
177
+ if is_complex:
178
+ result_type = _complex_types_map[result_type]
179
+ return cdouble, result_type
180
+ else:
181
+ return double, result_type
182
+
183
+
184
+ def _to_native_byte_order(*arrays):
185
+ ret = []
186
+ for arr in arrays:
187
+ if arr.dtype.byteorder not in ('=', '|'):
188
+ ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('=')))
189
+ else:
190
+ ret.append(arr)
191
+ if len(ret) == 1:
192
+ return ret[0]
193
+ else:
194
+ return ret
195
+
196
+
197
+ def _assert_2d(*arrays):
198
+ for a in arrays:
199
+ if a.ndim != 2:
200
+ raise LinAlgError('%d-dimensional array given. Array must be '
201
+ 'two-dimensional' % a.ndim)
202
+
203
+ def _assert_stacked_2d(*arrays):
204
+ for a in arrays:
205
+ if a.ndim < 2:
206
+ raise LinAlgError('%d-dimensional array given. Array must be '
207
+ 'at least two-dimensional' % a.ndim)
208
+
209
+ def _assert_stacked_square(*arrays):
210
+ for a in arrays:
211
+ m, n = a.shape[-2:]
212
+ if m != n:
213
+ raise LinAlgError('Last 2 dimensions of the array must be square')
214
+
215
+ def _assert_finite(*arrays):
216
+ for a in arrays:
217
+ if not isfinite(a).all():
218
+ raise LinAlgError("Array must not contain infs or NaNs")
219
+
220
+ def _is_empty_2d(arr):
221
+ # check size first for efficiency
222
+ return arr.size == 0 and prod(arr.shape[-2:]) == 0
223
+
224
+
225
+ def transpose(a):
226
+ """
227
+ Transpose each matrix in a stack of matrices.
228
+
229
+ Unlike np.transpose, this only swaps the last two axes, rather than all of
230
+ them
231
+
232
+ Parameters
233
+ ----------
234
+ a : (...,M,N) array_like
235
+
236
+ Returns
237
+ -------
238
+ aT : (...,N,M) ndarray
239
+ """
240
+ return swapaxes(a, -1, -2)
241
+
242
+ # Linear equations
243
+
244
+ def _tensorsolve_dispatcher(a, b, axes=None):
245
+ return (a, b)
246
+
247
+
248
+ @array_function_dispatch(_tensorsolve_dispatcher)
249
+ def tensorsolve(a, b, axes=None):
250
+ """
251
+ Solve the tensor equation ``a x = b`` for x.
252
+
253
+ It is assumed that all indices of `x` are summed over in the product,
254
+ together with the rightmost indices of `a`, as is done in, for example,
255
+ ``tensordot(a, x, axes=x.ndim)``.
256
+
257
+ Parameters
258
+ ----------
259
+ a : array_like
260
+ Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
261
+ the shape of that sub-tensor of `a` consisting of the appropriate
262
+ number of its rightmost indices, and must be such that
263
+ ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
264
+ 'square').
265
+ b : array_like
266
+ Right-hand tensor, which can be of any shape.
267
+ axes : tuple of ints, optional
268
+ Axes in `a` to reorder to the right, before inversion.
269
+ If None (default), no reordering is done.
270
+
271
+ Returns
272
+ -------
273
+ x : ndarray, shape Q
274
+
275
+ Raises
276
+ ------
277
+ LinAlgError
278
+ If `a` is singular or not 'square' (in the above sense).
279
+
280
+ See Also
281
+ --------
282
+ numpy.tensordot, tensorinv, numpy.einsum
283
+
284
+ Examples
285
+ --------
286
+ >>> a = np.eye(2*3*4)
287
+ >>> a.shape = (2*3, 4, 2, 3, 4)
288
+ >>> b = np.random.randn(2*3, 4)
289
+ >>> x = np.linalg.tensorsolve(a, b)
290
+ >>> x.shape
291
+ (2, 3, 4)
292
+ >>> np.allclose(np.tensordot(a, x, axes=3), b)
293
+ True
294
+
295
+ """
296
+ a, wrap = _makearray(a)
297
+ b = asarray(b)
298
+ an = a.ndim
299
+
300
+ if axes is not None:
301
+ allaxes = list(range(0, an))
302
+ for k in axes:
303
+ allaxes.remove(k)
304
+ allaxes.insert(an, k)
305
+ a = a.transpose(allaxes)
306
+
307
+ oldshape = a.shape[-(an-b.ndim):]
308
+ prod = 1
309
+ for k in oldshape:
310
+ prod *= k
311
+
312
+ if a.size != prod ** 2:
313
+ raise LinAlgError(
314
+ "Input arrays must satisfy the requirement \
315
+ prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim])"
316
+ )
317
+
318
+ a = a.reshape(prod, prod)
319
+ b = b.ravel()
320
+ res = wrap(solve(a, b))
321
+ res.shape = oldshape
322
+ return res
323
+
324
+
325
+ def _solve_dispatcher(a, b):
326
+ return (a, b)
327
+
328
+
329
+ @array_function_dispatch(_solve_dispatcher)
330
+ def solve(a, b):
331
+ """
332
+ Solve a linear matrix equation, or system of linear scalar equations.
333
+
334
+ Computes the "exact" solution, `x`, of the well-determined, i.e., full
335
+ rank, linear matrix equation `ax = b`.
336
+
337
+ Parameters
338
+ ----------
339
+ a : (..., M, M) array_like
340
+ Coefficient matrix.
341
+ b : {(..., M,), (..., M, K)}, array_like
342
+ Ordinate or "dependent variable" values.
343
+
344
+ Returns
345
+ -------
346
+ x : {(..., M,), (..., M, K)} ndarray
347
+ Solution to the system a x = b. Returned shape is identical to `b`.
348
+
349
+ Raises
350
+ ------
351
+ LinAlgError
352
+ If `a` is singular or not square.
353
+
354
+ See Also
355
+ --------
356
+ scipy.linalg.solve : Similar function in SciPy.
357
+
358
+ Notes
359
+ -----
360
+
361
+ .. versionadded:: 1.8.0
362
+
363
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
364
+ details.
365
+
366
+ The solutions are computed using LAPACK routine ``_gesv``.
367
+
368
+ `a` must be square and of full-rank, i.e., all rows (or, equivalently,
369
+ columns) must be linearly independent; if either is not true, use
370
+ `lstsq` for the least-squares best "solution" of the
371
+ system/equation.
372
+
373
+ References
374
+ ----------
375
+ .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
376
+ FL, Academic Press, Inc., 1980, pg. 22.
377
+
378
+ Examples
379
+ --------
380
+ Solve the system of equations ``x0 + 2 * x1 = 1`` and ``3 * x0 + 5 * x1 = 2``:
381
+
382
+ >>> a = np.array([[1, 2], [3, 5]])
383
+ >>> b = np.array([1, 2])
384
+ >>> x = np.linalg.solve(a, b)
385
+ >>> x
386
+ array([-1., 1.])
387
+
388
+ Check that the solution is correct:
389
+
390
+ >>> np.allclose(np.dot(a, x), b)
391
+ True
392
+
393
+ """
394
+ a, _ = _makearray(a)
395
+ _assert_stacked_2d(a)
396
+ _assert_stacked_square(a)
397
+ b, wrap = _makearray(b)
398
+ t, result_t = _commonType(a, b)
399
+
400
+ # We use the b = (..., M,) logic, only if the number of extra dimensions
401
+ # match exactly
402
+ if b.ndim == a.ndim - 1:
403
+ gufunc = _umath_linalg.solve1
404
+ else:
405
+ gufunc = _umath_linalg.solve
406
+
407
+ signature = 'DD->D' if isComplexType(t) else 'dd->d'
408
+ extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
409
+ r = gufunc(a, b, signature=signature, extobj=extobj)
410
+
411
+ return wrap(r.astype(result_t, copy=False))
412
+
413
+
414
+ def _tensorinv_dispatcher(a, ind=None):
415
+ return (a,)
416
+
417
+
418
+ @array_function_dispatch(_tensorinv_dispatcher)
419
+ def tensorinv(a, ind=2):
420
+ """
421
+ Compute the 'inverse' of an N-dimensional array.
422
+
423
+ The result is an inverse for `a` relative to the tensordot operation
424
+ ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy,
425
+ ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the
426
+ tensordot operation.
427
+
428
+ Parameters
429
+ ----------
430
+ a : array_like
431
+ Tensor to 'invert'. Its shape must be 'square', i. e.,
432
+ ``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
433
+ ind : int, optional
434
+ Number of first indices that are involved in the inverse sum.
435
+ Must be a positive integer, default is 2.
436
+
437
+ Returns
438
+ -------
439
+ b : ndarray
440
+ `a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``.
441
+
442
+ Raises
443
+ ------
444
+ LinAlgError
445
+ If `a` is singular or not 'square' (in the above sense).
446
+
447
+ See Also
448
+ --------
449
+ numpy.tensordot, tensorsolve
450
+
451
+ Examples
452
+ --------
453
+ >>> a = np.eye(4*6)
454
+ >>> a.shape = (4, 6, 8, 3)
455
+ >>> ainv = np.linalg.tensorinv(a, ind=2)
456
+ >>> ainv.shape
457
+ (8, 3, 4, 6)
458
+ >>> b = np.random.randn(4, 6)
459
+ >>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
460
+ True
461
+
462
+ >>> a = np.eye(4*6)
463
+ >>> a.shape = (24, 8, 3)
464
+ >>> ainv = np.linalg.tensorinv(a, ind=1)
465
+ >>> ainv.shape
466
+ (8, 3, 24)
467
+ >>> b = np.random.randn(24)
468
+ >>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
469
+ True
470
+
471
+ """
472
+ a = asarray(a)
473
+ oldshape = a.shape
474
+ prod = 1
475
+ if ind > 0:
476
+ invshape = oldshape[ind:] + oldshape[:ind]
477
+ for k in oldshape[ind:]:
478
+ prod *= k
479
+ else:
480
+ raise ValueError("Invalid ind argument.")
481
+ a = a.reshape(prod, -1)
482
+ ia = inv(a)
483
+ return ia.reshape(*invshape)
484
+
485
+
486
+ # Matrix inversion
487
+
488
+ def _unary_dispatcher(a):
489
+ return (a,)
490
+
491
+
492
+ @array_function_dispatch(_unary_dispatcher)
493
+ def inv(a):
494
+ """
495
+ Compute the (multiplicative) inverse of a matrix.
496
+
497
+ Given a square matrix `a`, return the matrix `ainv` satisfying
498
+ ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.
499
+
500
+ Parameters
501
+ ----------
502
+ a : (..., M, M) array_like
503
+ Matrix to be inverted.
504
+
505
+ Returns
506
+ -------
507
+ ainv : (..., M, M) ndarray or matrix
508
+ (Multiplicative) inverse of the matrix `a`.
509
+
510
+ Raises
511
+ ------
512
+ LinAlgError
513
+ If `a` is not square or inversion fails.
514
+
515
+ See Also
516
+ --------
517
+ scipy.linalg.inv : Similar function in SciPy.
518
+
519
+ Notes
520
+ -----
521
+
522
+ .. versionadded:: 1.8.0
523
+
524
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
525
+ details.
526
+
527
+ Examples
528
+ --------
529
+ >>> from numpy.linalg import inv
530
+ >>> a = np.array([[1., 2.], [3., 4.]])
531
+ >>> ainv = inv(a)
532
+ >>> np.allclose(np.dot(a, ainv), np.eye(2))
533
+ True
534
+ >>> np.allclose(np.dot(ainv, a), np.eye(2))
535
+ True
536
+
537
+ If a is a matrix object, then the return value is a matrix as well:
538
+
539
+ >>> ainv = inv(np.matrix(a))
540
+ >>> ainv
541
+ matrix([[-2. , 1. ],
542
+ [ 1.5, -0.5]])
543
+
544
+ Inverses of several matrices can be computed at once:
545
+
546
+ >>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
547
+ >>> inv(a)
548
+ array([[[-2. , 1. ],
549
+ [ 1.5 , -0.5 ]],
550
+ [[-1.25, 0.75],
551
+ [ 0.75, -0.25]]])
552
+
553
+ """
554
+ a, wrap = _makearray(a)
555
+ _assert_stacked_2d(a)
556
+ _assert_stacked_square(a)
557
+ t, result_t = _commonType(a)
558
+
559
+ signature = 'D->D' if isComplexType(t) else 'd->d'
560
+ extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
561
+ ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
562
+ return wrap(ainv.astype(result_t, copy=False))
563
+
564
+
565
+ def _matrix_power_dispatcher(a, n):
566
+ return (a,)
567
+
568
+
569
+ @array_function_dispatch(_matrix_power_dispatcher)
570
+ def matrix_power(a, n):
571
+ """
572
+ Raise a square matrix to the (integer) power `n`.
573
+
574
+ For positive integers `n`, the power is computed by repeated matrix
575
+ squarings and matrix multiplications. If ``n == 0``, the identity matrix
576
+ of the same shape as M is returned. If ``n < 0``, the inverse
577
+ is computed and then raised to the ``abs(n)``.
578
+
579
+ .. note:: Stacks of object matrices are not currently supported.
580
+
581
+ Parameters
582
+ ----------
583
+ a : (..., M, M) array_like
584
+ Matrix to be "powered".
585
+ n : int
586
+ The exponent can be any integer or long integer, positive,
587
+ negative, or zero.
588
+
589
+ Returns
590
+ -------
591
+ a**n : (..., M, M) ndarray or matrix object
592
+ The return value is the same shape and type as `M`;
593
+ if the exponent is positive or zero then the type of the
594
+ elements is the same as those of `M`. If the exponent is
595
+ negative the elements are floating-point.
596
+
597
+ Raises
598
+ ------
599
+ LinAlgError
600
+ For matrices that are not square or that (for negative powers) cannot
601
+ be inverted numerically.
602
+
603
+ Examples
604
+ --------
605
+ >>> from numpy.linalg import matrix_power
606
+ >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
607
+ >>> matrix_power(i, 3) # should = -i
608
+ array([[ 0, -1],
609
+ [ 1, 0]])
610
+ >>> matrix_power(i, 0)
611
+ array([[1, 0],
612
+ [0, 1]])
613
+ >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
614
+ array([[ 0., 1.],
615
+ [-1., 0.]])
616
+
617
+ Somewhat more sophisticated example
618
+
619
+ >>> q = np.zeros((4, 4))
620
+ >>> q[0:2, 0:2] = -i
621
+ >>> q[2:4, 2:4] = i
622
+ >>> q # one of the three quaternion units not equal to 1
623
+ array([[ 0., -1., 0., 0.],
624
+ [ 1., 0., 0., 0.],
625
+ [ 0., 0., 0., 1.],
626
+ [ 0., 0., -1., 0.]])
627
+ >>> matrix_power(q, 2) # = -np.eye(4)
628
+ array([[-1., 0., 0., 0.],
629
+ [ 0., -1., 0., 0.],
630
+ [ 0., 0., -1., 0.],
631
+ [ 0., 0., 0., -1.]])
632
+
633
+ """
634
+ a = asanyarray(a)
635
+ _assert_stacked_2d(a)
636
+ _assert_stacked_square(a)
637
+
638
+ try:
639
+ n = operator.index(n)
640
+ except TypeError as e:
641
+ raise TypeError("exponent must be an integer") from e
642
+
643
+ # Fall back on dot for object arrays. Object arrays are not supported by
644
+ # the current implementation of matmul using einsum
645
+ if a.dtype != object:
646
+ fmatmul = matmul
647
+ elif a.ndim == 2:
648
+ fmatmul = dot
649
+ else:
650
+ raise NotImplementedError(
651
+ "matrix_power not supported for stacks of object arrays")
652
+
653
+ if n == 0:
654
+ a = empty_like(a)
655
+ a[...] = eye(a.shape[-2], dtype=a.dtype)
656
+ return a
657
+
658
+ elif n < 0:
659
+ a = inv(a)
660
+ n = abs(n)
661
+
662
+ # short-cuts.
663
+ if n == 1:
664
+ return a
665
+
666
+ elif n == 2:
667
+ return fmatmul(a, a)
668
+
669
+ elif n == 3:
670
+ return fmatmul(fmatmul(a, a), a)
671
+
672
+ # Use binary decomposition to reduce the number of matrix multiplications.
673
+ # Here, we iterate over the bits of n, from LSB to MSB, raise `a` to
674
+ # increasing powers of 2, and multiply into the result as needed.
675
+ z = result = None
676
+ while n > 0:
677
+ z = a if z is None else fmatmul(z, z)
678
+ n, bit = divmod(n, 2)
679
+ if bit:
680
+ result = z if result is None else fmatmul(result, z)
681
+
682
+ return result
683
+
684
+
685
+ # Cholesky decomposition
686
+
687
+
688
+ @array_function_dispatch(_unary_dispatcher)
689
+ def cholesky(a):
690
+ """
691
+ Cholesky decomposition.
692
+
693
+ Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`,
694
+ where `L` is lower-triangular and .H is the conjugate transpose operator
695
+ (which is the ordinary transpose if `a` is real-valued). `a` must be
696
+ Hermitian (symmetric if real-valued) and positive-definite. No
697
+ checking is performed to verify whether `a` is Hermitian or not.
698
+ In addition, only the lower-triangular and diagonal elements of `a`
699
+ are used. Only `L` is actually returned.
700
+
701
+ Parameters
702
+ ----------
703
+ a : (..., M, M) array_like
704
+ Hermitian (symmetric if all elements are real), positive-definite
705
+ input matrix.
706
+
707
+ Returns
708
+ -------
709
+ L : (..., M, M) array_like
710
+ Lower-triangular Cholesky factor of `a`. Returns a matrix object if
711
+ `a` is a matrix object.
712
+
713
+ Raises
714
+ ------
715
+ LinAlgError
716
+ If the decomposition fails, for example, if `a` is not
717
+ positive-definite.
718
+
719
+ See Also
720
+ --------
721
+ scipy.linalg.cholesky : Similar function in SciPy.
722
+ scipy.linalg.cholesky_banded : Cholesky decompose a banded Hermitian
723
+ positive-definite matrix.
724
+ scipy.linalg.cho_factor : Cholesky decomposition of a matrix, to use in
725
+ `scipy.linalg.cho_solve`.
726
+
727
+ Notes
728
+ -----
729
+
730
+ .. versionadded:: 1.8.0
731
+
732
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
733
+ details.
734
+
735
+ The Cholesky decomposition is often used as a fast way of solving
736
+
737
+ .. math:: A \\mathbf{x} = \\mathbf{b}
738
+
739
+ (when `A` is both Hermitian/symmetric and positive-definite).
740
+
741
+ First, we solve for :math:`\\mathbf{y}` in
742
+
743
+ .. math:: L \\mathbf{y} = \\mathbf{b},
744
+
745
+ and then for :math:`\\mathbf{x}` in
746
+
747
+ .. math:: L.H \\mathbf{x} = \\mathbf{y}.
748
+
749
+ Examples
750
+ --------
751
+ >>> A = np.array([[1,-2j],[2j,5]])
752
+ >>> A
753
+ array([[ 1.+0.j, -0.-2.j],
754
+ [ 0.+2.j, 5.+0.j]])
755
+ >>> L = np.linalg.cholesky(A)
756
+ >>> L
757
+ array([[1.+0.j, 0.+0.j],
758
+ [0.+2.j, 1.+0.j]])
759
+ >>> np.dot(L, L.T.conj()) # verify that L * L.H = A
760
+ array([[1.+0.j, 0.-2.j],
761
+ [0.+2.j, 5.+0.j]])
762
+ >>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
763
+ >>> np.linalg.cholesky(A) # an ndarray object is returned
764
+ array([[1.+0.j, 0.+0.j],
765
+ [0.+2.j, 1.+0.j]])
766
+ >>> # But a matrix object is returned if A is a matrix object
767
+ >>> np.linalg.cholesky(np.matrix(A))
768
+ matrix([[ 1.+0.j, 0.+0.j],
769
+ [ 0.+2.j, 1.+0.j]])
770
+
771
+ """
772
+ extobj = get_linalg_error_extobj(_raise_linalgerror_nonposdef)
773
+ gufunc = _umath_linalg.cholesky_lo
774
+ a, wrap = _makearray(a)
775
+ _assert_stacked_2d(a)
776
+ _assert_stacked_square(a)
777
+ t, result_t = _commonType(a)
778
+ signature = 'D->D' if isComplexType(t) else 'd->d'
779
+ r = gufunc(a, signature=signature, extobj=extobj)
780
+ return wrap(r.astype(result_t, copy=False))
781
+
782
+
783
+ # QR decomposition
784
+
785
+ def _qr_dispatcher(a, mode=None):
786
+ return (a,)
787
+
788
+
789
+ @array_function_dispatch(_qr_dispatcher)
790
+ def qr(a, mode='reduced'):
791
+ """
792
+ Compute the qr factorization of a matrix.
793
+
794
+ Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is
795
+ upper-triangular.
796
+
797
+ Parameters
798
+ ----------
799
+ a : array_like, shape (..., M, N)
800
+ An array-like object with the dimensionality of at least 2.
801
+ mode : {'reduced', 'complete', 'r', 'raw'}, optional
802
+ If K = min(M, N), then
803
+
804
+ * 'reduced' : returns Q, R with dimensions (..., M, K), (..., K, N) (default)
805
+ * 'complete' : returns Q, R with dimensions (..., M, M), (..., M, N)
806
+ * 'r' : returns R only with dimensions (..., K, N)
807
+ * 'raw' : returns h, tau with dimensions (..., N, M), (..., K,)
808
+
809
+ The options 'reduced', 'complete, and 'raw' are new in numpy 1.8,
810
+ see the notes for more information. The default is 'reduced', and to
811
+ maintain backward compatibility with earlier versions of numpy both
812
+ it and the old default 'full' can be omitted. Note that array h
813
+ returned in 'raw' mode is transposed for calling Fortran. The
814
+ 'economic' mode is deprecated. The modes 'full' and 'economic' may
815
+ be passed using only the first letter for backwards compatibility,
816
+ but all others must be spelled out. See the Notes for more
817
+ explanation.
818
+
819
+
820
+ Returns
821
+ -------
822
+ When mode is 'reduced' or 'complete', the result will be a namedtuple with
823
+ the attributes `Q` and `R`.
824
+
825
+ Q : ndarray of float or complex, optional
826
+ A matrix with orthonormal columns. When mode = 'complete' the
827
+ result is an orthogonal/unitary matrix depending on whether or not
828
+ a is real/complex. The determinant may be either +/- 1 in that
829
+ case. In case the number of dimensions in the input array is
830
+ greater than 2 then a stack of the matrices with above properties
831
+ is returned.
832
+ R : ndarray of float or complex, optional
833
+ The upper-triangular matrix or a stack of upper-triangular
834
+ matrices if the number of dimensions in the input array is greater
835
+ than 2.
836
+ (h, tau) : ndarrays of np.double or np.cdouble, optional
837
+ The array h contains the Householder reflectors that generate q
838
+ along with r. The tau array contains scaling factors for the
839
+ reflectors. In the deprecated 'economic' mode only h is returned.
840
+
841
+ Raises
842
+ ------
843
+ LinAlgError
844
+ If factoring fails.
845
+
846
+ See Also
847
+ --------
848
+ scipy.linalg.qr : Similar function in SciPy.
849
+ scipy.linalg.rq : Compute RQ decomposition of a matrix.
850
+
851
+ Notes
852
+ -----
853
+ This is an interface to the LAPACK routines ``dgeqrf``, ``zgeqrf``,
854
+ ``dorgqr``, and ``zungqr``.
855
+
856
+ For more information on the qr factorization, see for example:
857
+ https://en.wikipedia.org/wiki/QR_factorization
858
+
859
+ Subclasses of `ndarray` are preserved except for the 'raw' mode. So if
860
+ `a` is of type `matrix`, all the return values will be matrices too.
861
+
862
+ New 'reduced', 'complete', and 'raw' options for mode were added in
863
+ NumPy 1.8.0 and the old option 'full' was made an alias of 'reduced'. In
864
+ addition the options 'full' and 'economic' were deprecated. Because
865
+ 'full' was the previous default and 'reduced' is the new default,
866
+ backward compatibility can be maintained by letting `mode` default.
867
+ The 'raw' option was added so that LAPACK routines that can multiply
868
+ arrays by q using the Householder reflectors can be used. Note that in
869
+ this case the returned arrays are of type np.double or np.cdouble and
870
+ the h array is transposed to be FORTRAN compatible. No routines using
871
+ the 'raw' return are currently exposed by numpy, but some are available
872
+ in lapack_lite and just await the necessary work.
873
+
874
+ Examples
875
+ --------
876
+ >>> a = np.random.randn(9, 6)
877
+ >>> Q, R = np.linalg.qr(a)
878
+ >>> np.allclose(a, np.dot(Q, R)) # a does equal QR
879
+ True
880
+ >>> R2 = np.linalg.qr(a, mode='r')
881
+ >>> np.allclose(R, R2) # mode='r' returns the same R as mode='full'
882
+ True
883
+ >>> a = np.random.normal(size=(3, 2, 2)) # Stack of 2 x 2 matrices as input
884
+ >>> Q, R = np.linalg.qr(a)
885
+ >>> Q.shape
886
+ (3, 2, 2)
887
+ >>> R.shape
888
+ (3, 2, 2)
889
+ >>> np.allclose(a, np.matmul(Q, R))
890
+ True
891
+
892
+ Example illustrating a common use of `qr`: solving of least squares
893
+ problems
894
+
895
+ What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for
896
+ the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points
897
+ and you'll see that it should be y0 = 0, m = 1.) The answer is provided
898
+ by solving the over-determined matrix equation ``Ax = b``, where::
899
+
900
+ A = array([[0, 1], [1, 1], [1, 1], [2, 1]])
901
+ x = array([[y0], [m]])
902
+ b = array([[1], [0], [2], [1]])
903
+
904
+ If A = QR such that Q is orthonormal (which is always possible via
905
+ Gram-Schmidt), then ``x = inv(R) * (Q.T) * b``. (In numpy practice,
906
+ however, we simply use `lstsq`.)
907
+
908
+ >>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
909
+ >>> A
910
+ array([[0, 1],
911
+ [1, 1],
912
+ [1, 1],
913
+ [2, 1]])
914
+ >>> b = np.array([1, 2, 2, 3])
915
+ >>> Q, R = np.linalg.qr(A)
916
+ >>> p = np.dot(Q.T, b)
917
+ >>> np.dot(np.linalg.inv(R), p)
918
+ array([ 1., 1.])
919
+
920
+ """
921
+ if mode not in ('reduced', 'complete', 'r', 'raw'):
922
+ if mode in ('f', 'full'):
923
+ # 2013-04-01, 1.8
924
+ msg = "".join((
925
+ "The 'full' option is deprecated in favor of 'reduced'.\n",
926
+ "For backward compatibility let mode default."))
927
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
928
+ mode = 'reduced'
929
+ elif mode in ('e', 'economic'):
930
+ # 2013-04-01, 1.8
931
+ msg = "The 'economic' option is deprecated."
932
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
933
+ mode = 'economic'
934
+ else:
935
+ raise ValueError(f"Unrecognized mode '{mode}'")
936
+
937
+ a, wrap = _makearray(a)
938
+ _assert_stacked_2d(a)
939
+ m, n = a.shape[-2:]
940
+ t, result_t = _commonType(a)
941
+ a = a.astype(t, copy=True)
942
+ a = _to_native_byte_order(a)
943
+ mn = min(m, n)
944
+
945
+ if m <= n:
946
+ gufunc = _umath_linalg.qr_r_raw_m
947
+ else:
948
+ gufunc = _umath_linalg.qr_r_raw_n
949
+
950
+ signature = 'D->D' if isComplexType(t) else 'd->d'
951
+ extobj = get_linalg_error_extobj(_raise_linalgerror_qr)
952
+ tau = gufunc(a, signature=signature, extobj=extobj)
953
+
954
+ # handle modes that don't return q
955
+ if mode == 'r':
956
+ r = triu(a[..., :mn, :])
957
+ r = r.astype(result_t, copy=False)
958
+ return wrap(r)
959
+
960
+ if mode == 'raw':
961
+ q = transpose(a)
962
+ q = q.astype(result_t, copy=False)
963
+ tau = tau.astype(result_t, copy=False)
964
+ return wrap(q), tau
965
+
966
+ if mode == 'economic':
967
+ a = a.astype(result_t, copy=False)
968
+ return wrap(a)
969
+
970
+ # mc is the number of columns in the resulting q
971
+ # matrix. If the mode is complete then it is
972
+ # same as number of rows, and if the mode is reduced,
973
+ # then it is the minimum of number of rows and columns.
974
+ if mode == 'complete' and m > n:
975
+ mc = m
976
+ gufunc = _umath_linalg.qr_complete
977
+ else:
978
+ mc = mn
979
+ gufunc = _umath_linalg.qr_reduced
980
+
981
+ signature = 'DD->D' if isComplexType(t) else 'dd->d'
982
+ extobj = get_linalg_error_extobj(_raise_linalgerror_qr)
983
+ q = gufunc(a, tau, signature=signature, extobj=extobj)
984
+ r = triu(a[..., :mc, :])
985
+
986
+ q = q.astype(result_t, copy=False)
987
+ r = r.astype(result_t, copy=False)
988
+
989
+ return QRResult(wrap(q), wrap(r))
990
+
991
+ # Eigenvalues
992
+
993
+
994
+ @array_function_dispatch(_unary_dispatcher)
995
+ def eigvals(a):
996
+ """
997
+ Compute the eigenvalues of a general matrix.
998
+
999
+ Main difference between `eigvals` and `eig`: the eigenvectors aren't
1000
+ returned.
1001
+
1002
+ Parameters
1003
+ ----------
1004
+ a : (..., M, M) array_like
1005
+ A complex- or real-valued matrix whose eigenvalues will be computed.
1006
+
1007
+ Returns
1008
+ -------
1009
+ w : (..., M,) ndarray
1010
+ The eigenvalues, each repeated according to its multiplicity.
1011
+ They are not necessarily ordered, nor are they necessarily
1012
+ real for real matrices.
1013
+
1014
+ Raises
1015
+ ------
1016
+ LinAlgError
1017
+ If the eigenvalue computation does not converge.
1018
+
1019
+ See Also
1020
+ --------
1021
+ eig : eigenvalues and right eigenvectors of general arrays
1022
+ eigvalsh : eigenvalues of real symmetric or complex Hermitian
1023
+ (conjugate symmetric) arrays.
1024
+ eigh : eigenvalues and eigenvectors of real symmetric or complex
1025
+ Hermitian (conjugate symmetric) arrays.
1026
+ scipy.linalg.eigvals : Similar function in SciPy.
1027
+
1028
+ Notes
1029
+ -----
1030
+
1031
+ .. versionadded:: 1.8.0
1032
+
1033
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
1034
+ details.
1035
+
1036
+ This is implemented using the ``_geev`` LAPACK routines which compute
1037
+ the eigenvalues and eigenvectors of general square arrays.
1038
+
1039
+ Examples
1040
+ --------
1041
+ Illustration, using the fact that the eigenvalues of a diagonal matrix
1042
+ are its diagonal elements, that multiplying a matrix on the left
1043
+ by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose
1044
+ of `Q`), preserves the eigenvalues of the "middle" matrix. In other words,
1045
+ if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as
1046
+ ``A``:
1047
+
1048
+ >>> from numpy import linalg as LA
1049
+ >>> x = np.random.random()
1050
+ >>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])
1051
+ >>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :])
1052
+ (1.0, 1.0, 0.0)
1053
+
1054
+ Now multiply a diagonal matrix by ``Q`` on one side and by ``Q.T`` on the other:
1055
+
1056
+ >>> D = np.diag((-1,1))
1057
+ >>> LA.eigvals(D)
1058
+ array([-1., 1.])
1059
+ >>> A = np.dot(Q, D)
1060
+ >>> A = np.dot(A, Q.T)
1061
+ >>> LA.eigvals(A)
1062
+ array([ 1., -1.]) # random
1063
+
1064
+ """
1065
+ a, wrap = _makearray(a)
1066
+ _assert_stacked_2d(a)
1067
+ _assert_stacked_square(a)
1068
+ _assert_finite(a)
1069
+ t, result_t = _commonType(a)
1070
+
1071
+ extobj = get_linalg_error_extobj(
1072
+ _raise_linalgerror_eigenvalues_nonconvergence)
1073
+ signature = 'D->D' if isComplexType(t) else 'd->D'
1074
+ w = _umath_linalg.eigvals(a, signature=signature, extobj=extobj)
1075
+
1076
+ if not isComplexType(t):
1077
+ if all(w.imag == 0):
1078
+ w = w.real
1079
+ result_t = _realType(result_t)
1080
+ else:
1081
+ result_t = _complexType(result_t)
1082
+
1083
+ return w.astype(result_t, copy=False)
1084
+
1085
+
1086
+ def _eigvalsh_dispatcher(a, UPLO=None):
1087
+ return (a,)
1088
+
1089
+
1090
+ @array_function_dispatch(_eigvalsh_dispatcher)
1091
+ def eigvalsh(a, UPLO='L'):
1092
+ """
1093
+ Compute the eigenvalues of a complex Hermitian or real symmetric matrix.
1094
+
1095
+ Main difference from eigh: the eigenvectors are not computed.
1096
+
1097
+ Parameters
1098
+ ----------
1099
+ a : (..., M, M) array_like
1100
+ A complex- or real-valued matrix whose eigenvalues are to be
1101
+ computed.
1102
+ UPLO : {'L', 'U'}, optional
1103
+ Specifies whether the calculation is done with the lower triangular
1104
+ part of `a` ('L', default) or the upper triangular part ('U').
1105
+ Irrespective of this value only the real parts of the diagonal will
1106
+ be considered in the computation to preserve the notion of a Hermitian
1107
+ matrix. It therefore follows that the imaginary part of the diagonal
1108
+ will always be treated as zero.
1109
+
1110
+ Returns
1111
+ -------
1112
+ w : (..., M,) ndarray
1113
+ The eigenvalues in ascending order, each repeated according to
1114
+ its multiplicity.
1115
+
1116
+ Raises
1117
+ ------
1118
+ LinAlgError
1119
+ If the eigenvalue computation does not converge.
1120
+
1121
+ See Also
1122
+ --------
1123
+ eigh : eigenvalues and eigenvectors of real symmetric or complex Hermitian
1124
+ (conjugate symmetric) arrays.
1125
+ eigvals : eigenvalues of general real or complex arrays.
1126
+ eig : eigenvalues and right eigenvectors of general real or complex
1127
+ arrays.
1128
+ scipy.linalg.eigvalsh : Similar function in SciPy.
1129
+
1130
+ Notes
1131
+ -----
1132
+
1133
+ .. versionadded:: 1.8.0
1134
+
1135
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
1136
+ details.
1137
+
1138
+ The eigenvalues are computed using LAPACK routines ``_syevd``, ``_heevd``.
1139
+
1140
+ Examples
1141
+ --------
1142
+ >>> from numpy import linalg as LA
1143
+ >>> a = np.array([[1, -2j], [2j, 5]])
1144
+ >>> LA.eigvalsh(a)
1145
+ array([ 0.17157288, 5.82842712]) # may vary
1146
+
1147
+ >>> # demonstrate the treatment of the imaginary part of the diagonal
1148
+ >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
1149
+ >>> a
1150
+ array([[5.+2.j, 9.-2.j],
1151
+ [0.+2.j, 2.-1.j]])
1152
+ >>> # with UPLO='L' this is numerically equivalent to using LA.eigvals()
1153
+ >>> # with:
1154
+ >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
1155
+ >>> b
1156
+ array([[5.+0.j, 0.-2.j],
1157
+ [0.+2.j, 2.+0.j]])
1158
+ >>> wa = LA.eigvalsh(a)
1159
+ >>> wb = LA.eigvals(b)
1160
+ >>> wa; wb
1161
+ array([1., 6.])
1162
+ array([6.+0.j, 1.+0.j])
1163
+
1164
+ """
1165
+ UPLO = UPLO.upper()
1166
+ if UPLO not in ('L', 'U'):
1167
+ raise ValueError("UPLO argument must be 'L' or 'U'")
1168
+
1169
+ extobj = get_linalg_error_extobj(
1170
+ _raise_linalgerror_eigenvalues_nonconvergence)
1171
+ if UPLO == 'L':
1172
+ gufunc = _umath_linalg.eigvalsh_lo
1173
+ else:
1174
+ gufunc = _umath_linalg.eigvalsh_up
1175
+
1176
+ a, wrap = _makearray(a)
1177
+ _assert_stacked_2d(a)
1178
+ _assert_stacked_square(a)
1179
+ t, result_t = _commonType(a)
1180
+ signature = 'D->d' if isComplexType(t) else 'd->d'
1181
+ w = gufunc(a, signature=signature, extobj=extobj)
1182
+ return w.astype(_realType(result_t), copy=False)
1183
+
1184
+ def _convertarray(a):
1185
+ t, result_t = _commonType(a)
1186
+ a = a.astype(t).T.copy()
1187
+ return a, t, result_t
1188
+
1189
+
1190
+ # Eigenvectors
1191
+
1192
+
1193
+ @array_function_dispatch(_unary_dispatcher)
1194
+ def eig(a):
1195
+ """
1196
+ Compute the eigenvalues and right eigenvectors of a square array.
1197
+
1198
+ Parameters
1199
+ ----------
1200
+ a : (..., M, M) array
1201
+ Matrices for which the eigenvalues and right eigenvectors will
1202
+ be computed
1203
+
1204
+ Returns
1205
+ -------
1206
+ A namedtuple with the following attributes:
1207
+
1208
+ eigenvalues : (..., M) array
1209
+ The eigenvalues, each repeated according to its multiplicity.
1210
+ The eigenvalues are not necessarily ordered. The resulting
1211
+ array will be of complex type, unless the imaginary part is
1212
+ zero in which case it will be cast to a real type. When `a`
1213
+ is real the resulting eigenvalues will be real (0 imaginary
1214
+ part) or occur in conjugate pairs
1215
+
1216
+ eigenvectors : (..., M, M) array
1217
+ The normalized (unit "length") eigenvectors, such that the
1218
+ column ``eigenvectors[:,i]`` is the eigenvector corresponding to the
1219
+ eigenvalue ``eigenvalues[i]``.
1220
+
1221
+ Raises
1222
+ ------
1223
+ LinAlgError
1224
+ If the eigenvalue computation does not converge.
1225
+
1226
+ See Also
1227
+ --------
1228
+ eigvals : eigenvalues of a non-symmetric array.
1229
+ eigh : eigenvalues and eigenvectors of a real symmetric or complex
1230
+ Hermitian (conjugate symmetric) array.
1231
+ eigvalsh : eigenvalues of a real symmetric or complex Hermitian
1232
+ (conjugate symmetric) array.
1233
+ scipy.linalg.eig : Similar function in SciPy that also solves the
1234
+ generalized eigenvalue problem.
1235
+ scipy.linalg.schur : Best choice for unitary and other non-Hermitian
1236
+ normal matrices.
1237
+
1238
+ Notes
1239
+ -----
1240
+
1241
+ .. versionadded:: 1.8.0
1242
+
1243
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
1244
+ details.
1245
+
1246
+ This is implemented using the ``_geev`` LAPACK routines which compute
1247
+ the eigenvalues and eigenvectors of general square arrays.
1248
+
1249
+ The number `w` is an eigenvalue of `a` if there exists a vector `v` such
1250
+ that ``a @ v = w * v``. Thus, the arrays `a`, `eigenvalues`, and
1251
+ `eigenvectors` satisfy the equations ``a @ eigenvectors[:,i] =
1252
+ eigenvalues[i] * eigenvalues[:,i]`` for :math:`i \\in \\{0,...,M-1\\}`.
1253
+
1254
+ The array `eigenvectors` may not be of maximum rank, that is, some of the
1255
+ columns may be linearly dependent, although round-off error may obscure
1256
+ that fact. If the eigenvalues are all different, then theoretically the
1257
+ eigenvectors are linearly independent and `a` can be diagonalized by a
1258
+ similarity transformation using `eigenvectors`, i.e, ``inv(eigenvectors) @
1259
+ a @ eigenvectors`` is diagonal.
1260
+
1261
+ For non-Hermitian normal matrices the SciPy function `scipy.linalg.schur`
1262
+ is preferred because the matrix `eigenvectors` is guaranteed to be
1263
+ unitary, which is not the case when using `eig`. The Schur factorization
1264
+ produces an upper triangular matrix rather than a diagonal matrix, but for
1265
+ normal matrices only the diagonal of the upper triangular matrix is
1266
+ needed, the rest is roundoff error.
1267
+
1268
+ Finally, it is emphasized that `eigenvectors` consists of the *right* (as
1269
+ in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``y.T @ a
1270
+ = z * y.T`` for some number `z` is called a *left* eigenvector of `a`,
1271
+ and, in general, the left and right eigenvectors of a matrix are not
1272
+ necessarily the (perhaps conjugate) transposes of each other.
1273
+
1274
+ References
1275
+ ----------
1276
+ G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
1277
+ Academic Press, Inc., 1980, Various pp.
1278
+
1279
+ Examples
1280
+ --------
1281
+ >>> from numpy import linalg as LA
1282
+
1283
+ (Almost) trivial example with real eigenvalues and eigenvectors.
1284
+
1285
+ >>> eigenvalues, eigenvectors = LA.eig(np.diag((1, 2, 3)))
1286
+ >>> eigenvalues
1287
+ array([1., 2., 3.])
1288
+ >>> eigenvectors
1289
+ array([[1., 0., 0.],
1290
+ [0., 1., 0.],
1291
+ [0., 0., 1.]])
1292
+
1293
+ Real matrix possessing complex eigenvalues and eigenvectors; note that the
1294
+ eigenvalues are complex conjugates of each other.
1295
+
1296
+ >>> eigenvalues, eigenvectors = LA.eig(np.array([[1, -1], [1, 1]]))
1297
+ >>> eigenvalues
1298
+ array([1.+1.j, 1.-1.j])
1299
+ >>> eigenvectors
1300
+ array([[0.70710678+0.j , 0.70710678-0.j ],
1301
+ [0. -0.70710678j, 0. +0.70710678j]])
1302
+
1303
+ Complex-valued matrix with real eigenvalues (but complex-valued eigenvectors);
1304
+ note that ``a.conj().T == a``, i.e., `a` is Hermitian.
1305
+
1306
+ >>> a = np.array([[1, 1j], [-1j, 1]])
1307
+ >>> eigenvalues, eigenvectors = LA.eig(a)
1308
+ >>> eigenvalues
1309
+ array([2.+0.j, 0.+0.j])
1310
+ >>> eigenvectors
1311
+ array([[ 0. +0.70710678j, 0.70710678+0.j ], # may vary
1312
+ [ 0.70710678+0.j , -0. +0.70710678j]])
1313
+
1314
+ Be careful about round-off error!
1315
+
1316
+ >>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
1317
+ >>> # Theor. eigenvalues are 1 +/- 1e-9
1318
+ >>> eigenvalues, eigenvectors = LA.eig(a)
1319
+ >>> eigenvalues
1320
+ array([1., 1.])
1321
+ >>> eigenvectors
1322
+ array([[1., 0.],
1323
+ [0., 1.]])
1324
+
1325
+ """
1326
+ a, wrap = _makearray(a)
1327
+ _assert_stacked_2d(a)
1328
+ _assert_stacked_square(a)
1329
+ _assert_finite(a)
1330
+ t, result_t = _commonType(a)
1331
+
1332
+ extobj = get_linalg_error_extobj(
1333
+ _raise_linalgerror_eigenvalues_nonconvergence)
1334
+ signature = 'D->DD' if isComplexType(t) else 'd->DD'
1335
+ w, vt = _umath_linalg.eig(a, signature=signature, extobj=extobj)
1336
+
1337
+ if not isComplexType(t) and all(w.imag == 0.0):
1338
+ w = w.real
1339
+ vt = vt.real
1340
+ result_t = _realType(result_t)
1341
+ else:
1342
+ result_t = _complexType(result_t)
1343
+
1344
+ vt = vt.astype(result_t, copy=False)
1345
+ return EigResult(w.astype(result_t, copy=False), wrap(vt))
1346
+
1347
+
1348
+ @array_function_dispatch(_eigvalsh_dispatcher)
1349
+ def eigh(a, UPLO='L'):
1350
+ """
1351
+ Return the eigenvalues and eigenvectors of a complex Hermitian
1352
+ (conjugate symmetric) or a real symmetric matrix.
1353
+
1354
+ Returns two objects, a 1-D array containing the eigenvalues of `a`, and
1355
+ a 2-D square array or matrix (depending on the input type) of the
1356
+ corresponding eigenvectors (in columns).
1357
+
1358
+ Parameters
1359
+ ----------
1360
+ a : (..., M, M) array
1361
+ Hermitian or real symmetric matrices whose eigenvalues and
1362
+ eigenvectors are to be computed.
1363
+ UPLO : {'L', 'U'}, optional
1364
+ Specifies whether the calculation is done with the lower triangular
1365
+ part of `a` ('L', default) or the upper triangular part ('U').
1366
+ Irrespective of this value only the real parts of the diagonal will
1367
+ be considered in the computation to preserve the notion of a Hermitian
1368
+ matrix. It therefore follows that the imaginary part of the diagonal
1369
+ will always be treated as zero.
1370
+
1371
+ Returns
1372
+ -------
1373
+ A namedtuple with the following attributes:
1374
+
1375
+ eigenvalues : (..., M) ndarray
1376
+ The eigenvalues in ascending order, each repeated according to
1377
+ its multiplicity.
1378
+ eigenvectors : {(..., M, M) ndarray, (..., M, M) matrix}
1379
+ The column ``eigenvectors[:, i]`` is the normalized eigenvector
1380
+ corresponding to the eigenvalue ``eigenvalues[i]``. Will return a
1381
+ matrix object if `a` is a matrix object.
1382
+
1383
+ Raises
1384
+ ------
1385
+ LinAlgError
1386
+ If the eigenvalue computation does not converge.
1387
+
1388
+ See Also
1389
+ --------
1390
+ eigvalsh : eigenvalues of real symmetric or complex Hermitian
1391
+ (conjugate symmetric) arrays.
1392
+ eig : eigenvalues and right eigenvectors for non-symmetric arrays.
1393
+ eigvals : eigenvalues of non-symmetric arrays.
1394
+ scipy.linalg.eigh : Similar function in SciPy (but also solves the
1395
+ generalized eigenvalue problem).
1396
+
1397
+ Notes
1398
+ -----
1399
+
1400
+ .. versionadded:: 1.8.0
1401
+
1402
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
1403
+ details.
1404
+
1405
+ The eigenvalues/eigenvectors are computed using LAPACK routines ``_syevd``,
1406
+ ``_heevd``.
1407
+
1408
+ The eigenvalues of real symmetric or complex Hermitian matrices are always
1409
+ real. [1]_ The array `eigenvalues` of (column) eigenvectors is unitary and
1410
+ `a`, `eigenvalues`, and `eigenvectors` satisfy the equations ``dot(a,
1411
+ eigenvectors[:, i]) = eigenvalues[i] * eigenvectors[:, i]``.
1412
+
1413
+ References
1414
+ ----------
1415
+ .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
1416
+ FL, Academic Press, Inc., 1980, pg. 222.
1417
+
1418
+ Examples
1419
+ --------
1420
+ >>> from numpy import linalg as LA
1421
+ >>> a = np.array([[1, -2j], [2j, 5]])
1422
+ >>> a
1423
+ array([[ 1.+0.j, -0.-2.j],
1424
+ [ 0.+2.j, 5.+0.j]])
1425
+ >>> eigenvalues, eigenvectors = LA.eigh(a)
1426
+ >>> eigenvalues
1427
+ array([0.17157288, 5.82842712])
1428
+ >>> eigenvectors
1429
+ array([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
1430
+ [ 0. +0.38268343j, 0. -0.92387953j]])
1431
+
1432
+ >>> np.dot(a, eigenvectors[:, 0]) - eigenvalues[0] * eigenvectors[:, 0] # verify 1st eigenval/vec pair
1433
+ array([5.55111512e-17+0.0000000e+00j, 0.00000000e+00+1.2490009e-16j])
1434
+ >>> np.dot(a, eigenvectors[:, 1]) - eigenvalues[1] * eigenvectors[:, 1] # verify 2nd eigenval/vec pair
1435
+ array([0.+0.j, 0.+0.j])
1436
+
1437
+ >>> A = np.matrix(a) # what happens if input is a matrix object
1438
+ >>> A
1439
+ matrix([[ 1.+0.j, -0.-2.j],
1440
+ [ 0.+2.j, 5.+0.j]])
1441
+ >>> eigenvalues, eigenvectors = LA.eigh(A)
1442
+ >>> eigenvalues
1443
+ array([0.17157288, 5.82842712])
1444
+ >>> eigenvectors
1445
+ matrix([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
1446
+ [ 0. +0.38268343j, 0. -0.92387953j]])
1447
+
1448
+ >>> # demonstrate the treatment of the imaginary part of the diagonal
1449
+ >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
1450
+ >>> a
1451
+ array([[5.+2.j, 9.-2.j],
1452
+ [0.+2.j, 2.-1.j]])
1453
+ >>> # with UPLO='L' this is numerically equivalent to using LA.eig() with:
1454
+ >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
1455
+ >>> b
1456
+ array([[5.+0.j, 0.-2.j],
1457
+ [0.+2.j, 2.+0.j]])
1458
+ >>> wa, va = LA.eigh(a)
1459
+ >>> wb, vb = LA.eig(b)
1460
+ >>> wa; wb
1461
+ array([1., 6.])
1462
+ array([6.+0.j, 1.+0.j])
1463
+ >>> va; vb
1464
+ array([[-0.4472136 +0.j , -0.89442719+0.j ], # may vary
1465
+ [ 0. +0.89442719j, 0. -0.4472136j ]])
1466
+ array([[ 0.89442719+0.j , -0. +0.4472136j],
1467
+ [-0. +0.4472136j, 0.89442719+0.j ]])
1468
+
1469
+ """
1470
+ UPLO = UPLO.upper()
1471
+ if UPLO not in ('L', 'U'):
1472
+ raise ValueError("UPLO argument must be 'L' or 'U'")
1473
+
1474
+ a, wrap = _makearray(a)
1475
+ _assert_stacked_2d(a)
1476
+ _assert_stacked_square(a)
1477
+ t, result_t = _commonType(a)
1478
+
1479
+ extobj = get_linalg_error_extobj(
1480
+ _raise_linalgerror_eigenvalues_nonconvergence)
1481
+ if UPLO == 'L':
1482
+ gufunc = _umath_linalg.eigh_lo
1483
+ else:
1484
+ gufunc = _umath_linalg.eigh_up
1485
+
1486
+ signature = 'D->dD' if isComplexType(t) else 'd->dd'
1487
+ w, vt = gufunc(a, signature=signature, extobj=extobj)
1488
+ w = w.astype(_realType(result_t), copy=False)
1489
+ vt = vt.astype(result_t, copy=False)
1490
+ return EighResult(w, wrap(vt))
1491
+
1492
+
1493
+ # Singular value decomposition
1494
+
1495
+ def _svd_dispatcher(a, full_matrices=None, compute_uv=None, hermitian=None):
1496
+ return (a,)
1497
+
1498
+
1499
+ @array_function_dispatch(_svd_dispatcher)
1500
+ def svd(a, full_matrices=True, compute_uv=True, hermitian=False):
1501
+ """
1502
+ Singular Value Decomposition.
1503
+
1504
+ When `a` is a 2D array, and ``full_matrices=False``, then it is
1505
+ factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where
1506
+ `u` and the Hermitian transpose of `vh` are 2D arrays with
1507
+ orthonormal columns and `s` is a 1D array of `a`'s singular
1508
+ values. When `a` is higher-dimensional, SVD is applied in
1509
+ stacked mode as explained below.
1510
+
1511
+ Parameters
1512
+ ----------
1513
+ a : (..., M, N) array_like
1514
+ A real or complex array with ``a.ndim >= 2``.
1515
+ full_matrices : bool, optional
1516
+ If True (default), `u` and `vh` have the shapes ``(..., M, M)`` and
1517
+ ``(..., N, N)``, respectively. Otherwise, the shapes are
1518
+ ``(..., M, K)`` and ``(..., K, N)``, respectively, where
1519
+ ``K = min(M, N)``.
1520
+ compute_uv : bool, optional
1521
+ Whether or not to compute `u` and `vh` in addition to `s`. True
1522
+ by default.
1523
+ hermitian : bool, optional
1524
+ If True, `a` is assumed to be Hermitian (symmetric if real-valued),
1525
+ enabling a more efficient method for finding singular values.
1526
+ Defaults to False.
1527
+
1528
+ .. versionadded:: 1.17.0
1529
+
1530
+ Returns
1531
+ -------
1532
+ When `compute_uv` is True, the result is a namedtuple with the following
1533
+ attribute names:
1534
+
1535
+ U : { (..., M, M), (..., M, K) } array
1536
+ Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
1537
+ size as those of the input `a`. The size of the last two dimensions
1538
+ depends on the value of `full_matrices`. Only returned when
1539
+ `compute_uv` is True.
1540
+ S : (..., K) array
1541
+ Vector(s) with the singular values, within each vector sorted in
1542
+ descending order. The first ``a.ndim - 2`` dimensions have the same
1543
+ size as those of the input `a`.
1544
+ Vh : { (..., N, N), (..., K, N) } array
1545
+ Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
1546
+ size as those of the input `a`. The size of the last two dimensions
1547
+ depends on the value of `full_matrices`. Only returned when
1548
+ `compute_uv` is True.
1549
+
1550
+ Raises
1551
+ ------
1552
+ LinAlgError
1553
+ If SVD computation does not converge.
1554
+
1555
+ See Also
1556
+ --------
1557
+ scipy.linalg.svd : Similar function in SciPy.
1558
+ scipy.linalg.svdvals : Compute singular values of a matrix.
1559
+
1560
+ Notes
1561
+ -----
1562
+
1563
+ .. versionchanged:: 1.8.0
1564
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
1565
+ details.
1566
+
1567
+ The decomposition is performed using LAPACK routine ``_gesdd``.
1568
+
1569
+ SVD is usually described for the factorization of a 2D matrix :math:`A`.
1570
+ The higher-dimensional case will be discussed below. In the 2D case, SVD is
1571
+ written as :math:`A = U S V^H`, where :math:`A = a`, :math:`U= u`,
1572
+ :math:`S= \\mathtt{np.diag}(s)` and :math:`V^H = vh`. The 1D array `s`
1573
+ contains the singular values of `a` and `u` and `vh` are unitary. The rows
1574
+ of `vh` are the eigenvectors of :math:`A^H A` and the columns of `u` are
1575
+ the eigenvectors of :math:`A A^H`. In both cases the corresponding
1576
+ (possibly non-zero) eigenvalues are given by ``s**2``.
1577
+
1578
+ If `a` has more than two dimensions, then broadcasting rules apply, as
1579
+ explained in :ref:`routines.linalg-broadcasting`. This means that SVD is
1580
+ working in "stacked" mode: it iterates over all indices of the first
1581
+ ``a.ndim - 2`` dimensions and for each combination SVD is applied to the
1582
+ last two indices. The matrix `a` can be reconstructed from the
1583
+ decomposition with either ``(u * s[..., None, :]) @ vh`` or
1584
+ ``u @ (s[..., None] * vh)``. (The ``@`` operator can be replaced by the
1585
+ function ``np.matmul`` for python versions below 3.5.)
1586
+
1587
+ If `a` is a ``matrix`` object (as opposed to an ``ndarray``), then so are
1588
+ all the return values.
1589
+
1590
+ Examples
1591
+ --------
1592
+ >>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)
1593
+ >>> b = np.random.randn(2, 7, 8, 3) + 1j*np.random.randn(2, 7, 8, 3)
1594
+
1595
+ Reconstruction based on full SVD, 2D case:
1596
+
1597
+ >>> U, S, Vh = np.linalg.svd(a, full_matrices=True)
1598
+ >>> U.shape, S.shape, Vh.shape
1599
+ ((9, 9), (6,), (6, 6))
1600
+ >>> np.allclose(a, np.dot(U[:, :6] * S, Vh))
1601
+ True
1602
+ >>> smat = np.zeros((9, 6), dtype=complex)
1603
+ >>> smat[:6, :6] = np.diag(S)
1604
+ >>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
1605
+ True
1606
+
1607
+ Reconstruction based on reduced SVD, 2D case:
1608
+
1609
+ >>> U, S, Vh = np.linalg.svd(a, full_matrices=False)
1610
+ >>> U.shape, S.shape, Vh.shape
1611
+ ((9, 6), (6,), (6, 6))
1612
+ >>> np.allclose(a, np.dot(U * S, Vh))
1613
+ True
1614
+ >>> smat = np.diag(S)
1615
+ >>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
1616
+ True
1617
+
1618
+ Reconstruction based on full SVD, 4D case:
1619
+
1620
+ >>> U, S, Vh = np.linalg.svd(b, full_matrices=True)
1621
+ >>> U.shape, S.shape, Vh.shape
1622
+ ((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))
1623
+ >>> np.allclose(b, np.matmul(U[..., :3] * S[..., None, :], Vh))
1624
+ True
1625
+ >>> np.allclose(b, np.matmul(U[..., :3], S[..., None] * Vh))
1626
+ True
1627
+
1628
+ Reconstruction based on reduced SVD, 4D case:
1629
+
1630
+ >>> U, S, Vh = np.linalg.svd(b, full_matrices=False)
1631
+ >>> U.shape, S.shape, Vh.shape
1632
+ ((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))
1633
+ >>> np.allclose(b, np.matmul(U * S[..., None, :], Vh))
1634
+ True
1635
+ >>> np.allclose(b, np.matmul(U, S[..., None] * Vh))
1636
+ True
1637
+
1638
+ """
1639
+ import numpy as _nx
1640
+ a, wrap = _makearray(a)
1641
+
1642
+ if hermitian:
1643
+ # note: lapack svd returns eigenvalues with s ** 2 sorted descending,
1644
+ # but eig returns s sorted ascending, so we re-order the eigenvalues
1645
+ # and related arrays to have the correct order
1646
+ if compute_uv:
1647
+ s, u = eigh(a)
1648
+ sgn = sign(s)
1649
+ s = abs(s)
1650
+ sidx = argsort(s)[..., ::-1]
1651
+ sgn = _nx.take_along_axis(sgn, sidx, axis=-1)
1652
+ s = _nx.take_along_axis(s, sidx, axis=-1)
1653
+ u = _nx.take_along_axis(u, sidx[..., None, :], axis=-1)
1654
+ # singular values are unsigned, move the sign into v
1655
+ vt = transpose(u * sgn[..., None, :]).conjugate()
1656
+ return SVDResult(wrap(u), s, wrap(vt))
1657
+ else:
1658
+ s = eigvalsh(a)
1659
+ s = abs(s)
1660
+ return sort(s)[..., ::-1]
1661
+
1662
+ _assert_stacked_2d(a)
1663
+ t, result_t = _commonType(a)
1664
+
1665
+ extobj = get_linalg_error_extobj(_raise_linalgerror_svd_nonconvergence)
1666
+
1667
+ m, n = a.shape[-2:]
1668
+ if compute_uv:
1669
+ if full_matrices:
1670
+ if m < n:
1671
+ gufunc = _umath_linalg.svd_m_f
1672
+ else:
1673
+ gufunc = _umath_linalg.svd_n_f
1674
+ else:
1675
+ if m < n:
1676
+ gufunc = _umath_linalg.svd_m_s
1677
+ else:
1678
+ gufunc = _umath_linalg.svd_n_s
1679
+
1680
+ signature = 'D->DdD' if isComplexType(t) else 'd->ddd'
1681
+ u, s, vh = gufunc(a, signature=signature, extobj=extobj)
1682
+ u = u.astype(result_t, copy=False)
1683
+ s = s.astype(_realType(result_t), copy=False)
1684
+ vh = vh.astype(result_t, copy=False)
1685
+ return SVDResult(wrap(u), s, wrap(vh))
1686
+ else:
1687
+ if m < n:
1688
+ gufunc = _umath_linalg.svd_m
1689
+ else:
1690
+ gufunc = _umath_linalg.svd_n
1691
+
1692
+ signature = 'D->d' if isComplexType(t) else 'd->d'
1693
+ s = gufunc(a, signature=signature, extobj=extobj)
1694
+ s = s.astype(_realType(result_t), copy=False)
1695
+ return s
1696
+
1697
+
1698
+ def _cond_dispatcher(x, p=None):
1699
+ return (x,)
1700
+
1701
+
1702
+ @array_function_dispatch(_cond_dispatcher)
1703
+ def cond(x, p=None):
1704
+ """
1705
+ Compute the condition number of a matrix.
1706
+
1707
+ This function is capable of returning the condition number using
1708
+ one of seven different norms, depending on the value of `p` (see
1709
+ Parameters below).
1710
+
1711
+ Parameters
1712
+ ----------
1713
+ x : (..., M, N) array_like
1714
+ The matrix whose condition number is sought.
1715
+ p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
1716
+ Order of the norm used in the condition number computation:
1717
+
1718
+ ===== ============================
1719
+ p norm for matrices
1720
+ ===== ============================
1721
+ None 2-norm, computed directly using the ``SVD``
1722
+ 'fro' Frobenius norm
1723
+ inf max(sum(abs(x), axis=1))
1724
+ -inf min(sum(abs(x), axis=1))
1725
+ 1 max(sum(abs(x), axis=0))
1726
+ -1 min(sum(abs(x), axis=0))
1727
+ 2 2-norm (largest sing. value)
1728
+ -2 smallest singular value
1729
+ ===== ============================
1730
+
1731
+ inf means the `numpy.inf` object, and the Frobenius norm is
1732
+ the root-of-sum-of-squares norm.
1733
+
1734
+ Returns
1735
+ -------
1736
+ c : {float, inf}
1737
+ The condition number of the matrix. May be infinite.
1738
+
1739
+ See Also
1740
+ --------
1741
+ numpy.linalg.norm
1742
+
1743
+ Notes
1744
+ -----
1745
+ The condition number of `x` is defined as the norm of `x` times the
1746
+ norm of the inverse of `x` [1]_; the norm can be the usual L2-norm
1747
+ (root-of-sum-of-squares) or one of a number of other matrix norms.
1748
+
1749
+ References
1750
+ ----------
1751
+ .. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL,
1752
+ Academic Press, Inc., 1980, pg. 285.
1753
+
1754
+ Examples
1755
+ --------
1756
+ >>> from numpy import linalg as LA
1757
+ >>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
1758
+ >>> a
1759
+ array([[ 1, 0, -1],
1760
+ [ 0, 1, 0],
1761
+ [ 1, 0, 1]])
1762
+ >>> LA.cond(a)
1763
+ 1.4142135623730951
1764
+ >>> LA.cond(a, 'fro')
1765
+ 3.1622776601683795
1766
+ >>> LA.cond(a, np.inf)
1767
+ 2.0
1768
+ >>> LA.cond(a, -np.inf)
1769
+ 1.0
1770
+ >>> LA.cond(a, 1)
1771
+ 2.0
1772
+ >>> LA.cond(a, -1)
1773
+ 1.0
1774
+ >>> LA.cond(a, 2)
1775
+ 1.4142135623730951
1776
+ >>> LA.cond(a, -2)
1777
+ 0.70710678118654746 # may vary
1778
+ >>> min(LA.svd(a, compute_uv=False))*min(LA.svd(LA.inv(a), compute_uv=False))
1779
+ 0.70710678118654746 # may vary
1780
+
1781
+ """
1782
+ x = asarray(x) # in case we have a matrix
1783
+ if _is_empty_2d(x):
1784
+ raise LinAlgError("cond is not defined on empty arrays")
1785
+ if p is None or p == 2 or p == -2:
1786
+ s = svd(x, compute_uv=False)
1787
+ with errstate(all='ignore'):
1788
+ if p == -2:
1789
+ r = s[..., -1] / s[..., 0]
1790
+ else:
1791
+ r = s[..., 0] / s[..., -1]
1792
+ else:
1793
+ # Call inv(x) ignoring errors. The result array will
1794
+ # contain nans in the entries where inversion failed.
1795
+ _assert_stacked_2d(x)
1796
+ _assert_stacked_square(x)
1797
+ t, result_t = _commonType(x)
1798
+ signature = 'D->D' if isComplexType(t) else 'd->d'
1799
+ with errstate(all='ignore'):
1800
+ invx = _umath_linalg.inv(x, signature=signature)
1801
+ r = norm(x, p, axis=(-2, -1)) * norm(invx, p, axis=(-2, -1))
1802
+ r = r.astype(result_t, copy=False)
1803
+
1804
+ # Convert nans to infs unless the original array had nan entries
1805
+ r = asarray(r)
1806
+ nan_mask = isnan(r)
1807
+ if nan_mask.any():
1808
+ nan_mask &= ~isnan(x).any(axis=(-2, -1))
1809
+ if r.ndim > 0:
1810
+ r[nan_mask] = Inf
1811
+ elif nan_mask:
1812
+ r[()] = Inf
1813
+
1814
+ # Convention is to return scalars instead of 0d arrays
1815
+ if r.ndim == 0:
1816
+ r = r[()]
1817
+
1818
+ return r
1819
+
1820
+
1821
+ def _matrix_rank_dispatcher(A, tol=None, hermitian=None):
1822
+ return (A,)
1823
+
1824
+
1825
+ @array_function_dispatch(_matrix_rank_dispatcher)
1826
+ def matrix_rank(A, tol=None, hermitian=False):
1827
+ """
1828
+ Return matrix rank of array using SVD method
1829
+
1830
+ Rank of the array is the number of singular values of the array that are
1831
+ greater than `tol`.
1832
+
1833
+ .. versionchanged:: 1.14
1834
+ Can now operate on stacks of matrices
1835
+
1836
+ Parameters
1837
+ ----------
1838
+ A : {(M,), (..., M, N)} array_like
1839
+ Input vector or stack of matrices.
1840
+ tol : (...) array_like, float, optional
1841
+ Threshold below which SVD values are considered zero. If `tol` is
1842
+ None, and ``S`` is an array with singular values for `M`, and
1843
+ ``eps`` is the epsilon value for datatype of ``S``, then `tol` is
1844
+ set to ``S.max() * max(M, N) * eps``.
1845
+
1846
+ .. versionchanged:: 1.14
1847
+ Broadcasted against the stack of matrices
1848
+ hermitian : bool, optional
1849
+ If True, `A` is assumed to be Hermitian (symmetric if real-valued),
1850
+ enabling a more efficient method for finding singular values.
1851
+ Defaults to False.
1852
+
1853
+ .. versionadded:: 1.14
1854
+
1855
+ Returns
1856
+ -------
1857
+ rank : (...) array_like
1858
+ Rank of A.
1859
+
1860
+ Notes
1861
+ -----
1862
+ The default threshold to detect rank deficiency is a test on the magnitude
1863
+ of the singular values of `A`. By default, we identify singular values less
1864
+ than ``S.max() * max(M, N) * eps`` as indicating rank deficiency (with
1865
+ the symbols defined above). This is the algorithm MATLAB uses [1]. It also
1866
+ appears in *Numerical recipes* in the discussion of SVD solutions for linear
1867
+ least squares [2].
1868
+
1869
+ This default threshold is designed to detect rank deficiency accounting for
1870
+ the numerical errors of the SVD computation. Imagine that there is a column
1871
+ in `A` that is an exact (in floating point) linear combination of other
1872
+ columns in `A`. Computing the SVD on `A` will not produce a singular value
1873
+ exactly equal to 0 in general: any difference of the smallest SVD value from
1874
+ 0 will be caused by numerical imprecision in the calculation of the SVD.
1875
+ Our threshold for small SVD values takes this numerical imprecision into
1876
+ account, and the default threshold will detect such numerical rank
1877
+ deficiency. The threshold may declare a matrix `A` rank deficient even if
1878
+ the linear combination of some columns of `A` is not exactly equal to
1879
+ another column of `A` but only numerically very close to another column of
1880
+ `A`.
1881
+
1882
+ We chose our default threshold because it is in wide use. Other thresholds
1883
+ are possible. For example, elsewhere in the 2007 edition of *Numerical
1884
+ recipes* there is an alternative threshold of ``S.max() *
1885
+ np.finfo(A.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe
1886
+ this threshold as being based on "expected roundoff error" (p 71).
1887
+
1888
+ The thresholds above deal with floating point roundoff error in the
1889
+ calculation of the SVD. However, you may have more information about the
1890
+ sources of error in `A` that would make you consider other tolerance values
1891
+ to detect *effective* rank deficiency. The most useful measure of the
1892
+ tolerance depends on the operations you intend to use on your matrix. For
1893
+ example, if your data come from uncertain measurements with uncertainties
1894
+ greater than floating point epsilon, choosing a tolerance near that
1895
+ uncertainty may be preferable. The tolerance may be absolute if the
1896
+ uncertainties are absolute rather than relative.
1897
+
1898
+ References
1899
+ ----------
1900
+ .. [1] MATLAB reference documentation, "Rank"
1901
+ https://www.mathworks.com/help/techdoc/ref/rank.html
1902
+ .. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
1903
+ "Numerical Recipes (3rd edition)", Cambridge University Press, 2007,
1904
+ page 795.
1905
+
1906
+ Examples
1907
+ --------
1908
+ >>> from numpy.linalg import matrix_rank
1909
+ >>> matrix_rank(np.eye(4)) # Full rank matrix
1910
+ 4
1911
+ >>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix
1912
+ >>> matrix_rank(I)
1913
+ 3
1914
+ >>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0
1915
+ 1
1916
+ >>> matrix_rank(np.zeros((4,)))
1917
+ 0
1918
+ """
1919
+ A = asarray(A)
1920
+ if A.ndim < 2:
1921
+ return int(not all(A==0))
1922
+ S = svd(A, compute_uv=False, hermitian=hermitian)
1923
+ if tol is None:
1924
+ tol = S.max(axis=-1, keepdims=True) * max(A.shape[-2:]) * finfo(S.dtype).eps
1925
+ else:
1926
+ tol = asarray(tol)[..., newaxis]
1927
+ return count_nonzero(S > tol, axis=-1)
1928
+
1929
+
1930
+ # Generalized inverse
1931
+
1932
+ def _pinv_dispatcher(a, rcond=None, hermitian=None):
1933
+ return (a,)
1934
+
1935
+
1936
+ @array_function_dispatch(_pinv_dispatcher)
1937
+ def pinv(a, rcond=1e-15, hermitian=False):
1938
+ """
1939
+ Compute the (Moore-Penrose) pseudo-inverse of a matrix.
1940
+
1941
+ Calculate the generalized inverse of a matrix using its
1942
+ singular-value decomposition (SVD) and including all
1943
+ *large* singular values.
1944
+
1945
+ .. versionchanged:: 1.14
1946
+ Can now operate on stacks of matrices
1947
+
1948
+ Parameters
1949
+ ----------
1950
+ a : (..., M, N) array_like
1951
+ Matrix or stack of matrices to be pseudo-inverted.
1952
+ rcond : (...) array_like of float
1953
+ Cutoff for small singular values.
1954
+ Singular values less than or equal to
1955
+ ``rcond * largest_singular_value`` are set to zero.
1956
+ Broadcasts against the stack of matrices.
1957
+ hermitian : bool, optional
1958
+ If True, `a` is assumed to be Hermitian (symmetric if real-valued),
1959
+ enabling a more efficient method for finding singular values.
1960
+ Defaults to False.
1961
+
1962
+ .. versionadded:: 1.17.0
1963
+
1964
+ Returns
1965
+ -------
1966
+ B : (..., N, M) ndarray
1967
+ The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so
1968
+ is `B`.
1969
+
1970
+ Raises
1971
+ ------
1972
+ LinAlgError
1973
+ If the SVD computation does not converge.
1974
+
1975
+ See Also
1976
+ --------
1977
+ scipy.linalg.pinv : Similar function in SciPy.
1978
+ scipy.linalg.pinvh : Compute the (Moore-Penrose) pseudo-inverse of a
1979
+ Hermitian matrix.
1980
+
1981
+ Notes
1982
+ -----
1983
+ The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
1984
+ defined as: "the matrix that 'solves' [the least-squares problem]
1985
+ :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then
1986
+ :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`.
1987
+
1988
+ It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular
1989
+ value decomposition of A, then
1990
+ :math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
1991
+ orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting
1992
+ of A's so-called singular values, (followed, typically, by
1993
+ zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix
1994
+ consisting of the reciprocals of A's singular values
1995
+ (again, followed by zeros). [1]_
1996
+
1997
+ References
1998
+ ----------
1999
+ .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
2000
+ FL, Academic Press, Inc., 1980, pp. 139-142.
2001
+
2002
+ Examples
2003
+ --------
2004
+ The following example checks that ``a * a+ * a == a`` and
2005
+ ``a+ * a * a+ == a+``:
2006
+
2007
+ >>> a = np.random.randn(9, 6)
2008
+ >>> B = np.linalg.pinv(a)
2009
+ >>> np.allclose(a, np.dot(a, np.dot(B, a)))
2010
+ True
2011
+ >>> np.allclose(B, np.dot(B, np.dot(a, B)))
2012
+ True
2013
+
2014
+ """
2015
+ a, wrap = _makearray(a)
2016
+ rcond = asarray(rcond)
2017
+ if _is_empty_2d(a):
2018
+ m, n = a.shape[-2:]
2019
+ res = empty(a.shape[:-2] + (n, m), dtype=a.dtype)
2020
+ return wrap(res)
2021
+ a = a.conjugate()
2022
+ u, s, vt = svd(a, full_matrices=False, hermitian=hermitian)
2023
+
2024
+ # discard small singular values
2025
+ cutoff = rcond[..., newaxis] * amax(s, axis=-1, keepdims=True)
2026
+ large = s > cutoff
2027
+ s = divide(1, s, where=large, out=s)
2028
+ s[~large] = 0
2029
+
2030
+ res = matmul(transpose(vt), multiply(s[..., newaxis], transpose(u)))
2031
+ return wrap(res)
2032
+
2033
+
2034
+ # Determinant
2035
+
2036
+
2037
+ @array_function_dispatch(_unary_dispatcher)
2038
+ def slogdet(a):
2039
+ """
2040
+ Compute the sign and (natural) logarithm of the determinant of an array.
2041
+
2042
+ If an array has a very small or very large determinant, then a call to
2043
+ `det` may overflow or underflow. This routine is more robust against such
2044
+ issues, because it computes the logarithm of the determinant rather than
2045
+ the determinant itself.
2046
+
2047
+ Parameters
2048
+ ----------
2049
+ a : (..., M, M) array_like
2050
+ Input array, has to be a square 2-D array.
2051
+
2052
+ Returns
2053
+ -------
2054
+ A namedtuple with the following attributes:
2055
+
2056
+ sign : (...) array_like
2057
+ A number representing the sign of the determinant. For a real matrix,
2058
+ this is 1, 0, or -1. For a complex matrix, this is a complex number
2059
+ with absolute value 1 (i.e., it is on the unit circle), or else 0.
2060
+ logabsdet : (...) array_like
2061
+ The natural log of the absolute value of the determinant.
2062
+
2063
+ If the determinant is zero, then `sign` will be 0 and `logabsdet` will be
2064
+ -Inf. In all cases, the determinant is equal to ``sign * np.exp(logabsdet)``.
2065
+
2066
+ See Also
2067
+ --------
2068
+ det
2069
+
2070
+ Notes
2071
+ -----
2072
+
2073
+ .. versionadded:: 1.8.0
2074
+
2075
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
2076
+ details.
2077
+
2078
+ .. versionadded:: 1.6.0
2079
+
2080
+ The determinant is computed via LU factorization using the LAPACK
2081
+ routine ``z/dgetrf``.
2082
+
2083
+
2084
+ Examples
2085
+ --------
2086
+ The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``:
2087
+
2088
+ >>> a = np.array([[1, 2], [3, 4]])
2089
+ >>> (sign, logabsdet) = np.linalg.slogdet(a)
2090
+ >>> (sign, logabsdet)
2091
+ (-1, 0.69314718055994529) # may vary
2092
+ >>> sign * np.exp(logabsdet)
2093
+ -2.0
2094
+
2095
+ Computing log-determinants for a stack of matrices:
2096
+
2097
+ >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
2098
+ >>> a.shape
2099
+ (3, 2, 2)
2100
+ >>> sign, logabsdet = np.linalg.slogdet(a)
2101
+ >>> (sign, logabsdet)
2102
+ (array([-1., -1., -1.]), array([ 0.69314718, 1.09861229, 2.07944154]))
2103
+ >>> sign * np.exp(logabsdet)
2104
+ array([-2., -3., -8.])
2105
+
2106
+ This routine succeeds where ordinary `det` does not:
2107
+
2108
+ >>> np.linalg.det(np.eye(500) * 0.1)
2109
+ 0.0
2110
+ >>> np.linalg.slogdet(np.eye(500) * 0.1)
2111
+ (1, -1151.2925464970228)
2112
+
2113
+ """
2114
+ a = asarray(a)
2115
+ _assert_stacked_2d(a)
2116
+ _assert_stacked_square(a)
2117
+ t, result_t = _commonType(a)
2118
+ real_t = _realType(result_t)
2119
+ signature = 'D->Dd' if isComplexType(t) else 'd->dd'
2120
+ sign, logdet = _umath_linalg.slogdet(a, signature=signature)
2121
+ sign = sign.astype(result_t, copy=False)
2122
+ logdet = logdet.astype(real_t, copy=False)
2123
+ return SlogdetResult(sign, logdet)
2124
+
2125
+
2126
+ @array_function_dispatch(_unary_dispatcher)
2127
+ def det(a):
2128
+ """
2129
+ Compute the determinant of an array.
2130
+
2131
+ Parameters
2132
+ ----------
2133
+ a : (..., M, M) array_like
2134
+ Input array to compute determinants for.
2135
+
2136
+ Returns
2137
+ -------
2138
+ det : (...) array_like
2139
+ Determinant of `a`.
2140
+
2141
+ See Also
2142
+ --------
2143
+ slogdet : Another way to represent the determinant, more suitable
2144
+ for large matrices where underflow/overflow may occur.
2145
+ scipy.linalg.det : Similar function in SciPy.
2146
+
2147
+ Notes
2148
+ -----
2149
+
2150
+ .. versionadded:: 1.8.0
2151
+
2152
+ Broadcasting rules apply, see the `numpy.linalg` documentation for
2153
+ details.
2154
+
2155
+ The determinant is computed via LU factorization using the LAPACK
2156
+ routine ``z/dgetrf``.
2157
+
2158
+ Examples
2159
+ --------
2160
+ The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:
2161
+
2162
+ >>> a = np.array([[1, 2], [3, 4]])
2163
+ >>> np.linalg.det(a)
2164
+ -2.0 # may vary
2165
+
2166
+ Computing determinants for a stack of matrices:
2167
+
2168
+ >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
2169
+ >>> a.shape
2170
+ (3, 2, 2)
2171
+ >>> np.linalg.det(a)
2172
+ array([-2., -3., -8.])
2173
+
2174
+ """
2175
+ a = asarray(a)
2176
+ _assert_stacked_2d(a)
2177
+ _assert_stacked_square(a)
2178
+ t, result_t = _commonType(a)
2179
+ signature = 'D->D' if isComplexType(t) else 'd->d'
2180
+ r = _umath_linalg.det(a, signature=signature)
2181
+ r = r.astype(result_t, copy=False)
2182
+ return r
2183
+
2184
+
2185
+ # Linear Least Squares
2186
+
2187
+ def _lstsq_dispatcher(a, b, rcond=None):
2188
+ return (a, b)
2189
+
2190
+
2191
+ @array_function_dispatch(_lstsq_dispatcher)
2192
+ def lstsq(a, b, rcond="warn"):
2193
+ r"""
2194
+ Return the least-squares solution to a linear matrix equation.
2195
+
2196
+ Computes the vector `x` that approximately solves the equation
2197
+ ``a @ x = b``. The equation may be under-, well-, or over-determined
2198
+ (i.e., the number of linearly independent rows of `a` can be less than,
2199
+ equal to, or greater than its number of linearly independent columns).
2200
+ If `a` is square and of full rank, then `x` (but for round-off error)
2201
+ is the "exact" solution of the equation. Else, `x` minimizes the
2202
+ Euclidean 2-norm :math:`||b - ax||`. If there are multiple minimizing
2203
+ solutions, the one with the smallest 2-norm :math:`||x||` is returned.
2204
+
2205
+ Parameters
2206
+ ----------
2207
+ a : (M, N) array_like
2208
+ "Coefficient" matrix.
2209
+ b : {(M,), (M, K)} array_like
2210
+ Ordinate or "dependent variable" values. If `b` is two-dimensional,
2211
+ the least-squares solution is calculated for each of the `K` columns
2212
+ of `b`.
2213
+ rcond : float, optional
2214
+ Cut-off ratio for small singular values of `a`.
2215
+ For the purposes of rank determination, singular values are treated
2216
+ as zero if they are smaller than `rcond` times the largest singular
2217
+ value of `a`.
2218
+
2219
+ .. versionchanged:: 1.14.0
2220
+ If not set, a FutureWarning is given. The previous default
2221
+ of ``-1`` will use the machine precision as `rcond` parameter,
2222
+ the new default will use the machine precision times `max(M, N)`.
2223
+ To silence the warning and use the new default, use ``rcond=None``,
2224
+ to keep using the old behavior, use ``rcond=-1``.
2225
+
2226
+ Returns
2227
+ -------
2228
+ x : {(N,), (N, K)} ndarray
2229
+ Least-squares solution. If `b` is two-dimensional,
2230
+ the solutions are in the `K` columns of `x`.
2231
+ residuals : {(1,), (K,), (0,)} ndarray
2232
+ Sums of squared residuals: Squared Euclidean 2-norm for each column in
2233
+ ``b - a @ x``.
2234
+ If the rank of `a` is < N or M <= N, this is an empty array.
2235
+ If `b` is 1-dimensional, this is a (1,) shape array.
2236
+ Otherwise the shape is (K,).
2237
+ rank : int
2238
+ Rank of matrix `a`.
2239
+ s : (min(M, N),) ndarray
2240
+ Singular values of `a`.
2241
+
2242
+ Raises
2243
+ ------
2244
+ LinAlgError
2245
+ If computation does not converge.
2246
+
2247
+ See Also
2248
+ --------
2249
+ scipy.linalg.lstsq : Similar function in SciPy.
2250
+
2251
+ Notes
2252
+ -----
2253
+ If `b` is a matrix, then all array results are returned as matrices.
2254
+
2255
+ Examples
2256
+ --------
2257
+ Fit a line, ``y = mx + c``, through some noisy data-points:
2258
+
2259
+ >>> x = np.array([0, 1, 2, 3])
2260
+ >>> y = np.array([-1, 0.2, 0.9, 2.1])
2261
+
2262
+ By examining the coefficients, we see that the line should have a
2263
+ gradient of roughly 1 and cut the y-axis at, more or less, -1.
2264
+
2265
+ We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
2266
+ and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`:
2267
+
2268
+ >>> A = np.vstack([x, np.ones(len(x))]).T
2269
+ >>> A
2270
+ array([[ 0., 1.],
2271
+ [ 1., 1.],
2272
+ [ 2., 1.],
2273
+ [ 3., 1.]])
2274
+
2275
+ >>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]
2276
+ >>> m, c
2277
+ (1.0 -0.95) # may vary
2278
+
2279
+ Plot the data along with the fitted line:
2280
+
2281
+ >>> import matplotlib.pyplot as plt
2282
+ >>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10)
2283
+ >>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line')
2284
+ >>> _ = plt.legend()
2285
+ >>> plt.show()
2286
+
2287
+ """
2288
+ a, _ = _makearray(a)
2289
+ b, wrap = _makearray(b)
2290
+ is_1d = b.ndim == 1
2291
+ if is_1d:
2292
+ b = b[:, newaxis]
2293
+ _assert_2d(a, b)
2294
+ m, n = a.shape[-2:]
2295
+ m2, n_rhs = b.shape[-2:]
2296
+ if m != m2:
2297
+ raise LinAlgError('Incompatible dimensions')
2298
+
2299
+ t, result_t = _commonType(a, b)
2300
+ result_real_t = _realType(result_t)
2301
+
2302
+ # Determine default rcond value
2303
+ if rcond == "warn":
2304
+ # 2017-08-19, 1.14.0
2305
+ warnings.warn("`rcond` parameter will change to the default of "
2306
+ "machine precision times ``max(M, N)`` where M and N "
2307
+ "are the input matrix dimensions.\n"
2308
+ "To use the future default and silence this warning "
2309
+ "we advise to pass `rcond=None`, to keep using the old, "
2310
+ "explicitly pass `rcond=-1`.",
2311
+ FutureWarning, stacklevel=2)
2312
+ rcond = -1
2313
+ if rcond is None:
2314
+ rcond = finfo(t).eps * max(n, m)
2315
+
2316
+ if m <= n:
2317
+ gufunc = _umath_linalg.lstsq_m
2318
+ else:
2319
+ gufunc = _umath_linalg.lstsq_n
2320
+
2321
+ signature = 'DDd->Ddid' if isComplexType(t) else 'ddd->ddid'
2322
+ extobj = get_linalg_error_extobj(_raise_linalgerror_lstsq)
2323
+ if n_rhs == 0:
2324
+ # lapack can't handle n_rhs = 0 - so allocate the array one larger in that axis
2325
+ b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype)
2326
+ x, resids, rank, s = gufunc(a, b, rcond, signature=signature, extobj=extobj)
2327
+ if m == 0:
2328
+ x[...] = 0
2329
+ if n_rhs == 0:
2330
+ # remove the item we added
2331
+ x = x[..., :n_rhs]
2332
+ resids = resids[..., :n_rhs]
2333
+
2334
+ # remove the axis we added
2335
+ if is_1d:
2336
+ x = x.squeeze(axis=-1)
2337
+ # we probably should squeeze resids too, but we can't
2338
+ # without breaking compatibility.
2339
+
2340
+ # as documented
2341
+ if rank != n or m <= n:
2342
+ resids = array([], result_real_t)
2343
+
2344
+ # coerce output arrays
2345
+ s = s.astype(result_real_t, copy=False)
2346
+ resids = resids.astype(result_real_t, copy=False)
2347
+ x = x.astype(result_t, copy=True) # Copying lets the memory in r_parts be freed
2348
+ return wrap(x), wrap(resids), rank, s
2349
+
2350
+
2351
+ def _multi_svd_norm(x, row_axis, col_axis, op):
2352
+ """Compute a function of the singular values of the 2-D matrices in `x`.
2353
+
2354
+ This is a private utility function used by `numpy.linalg.norm()`.
2355
+
2356
+ Parameters
2357
+ ----------
2358
+ x : ndarray
2359
+ row_axis, col_axis : int
2360
+ The axes of `x` that hold the 2-D matrices.
2361
+ op : callable
2362
+ This should be either numpy.amin or `numpy.amax` or `numpy.sum`.
2363
+
2364
+ Returns
2365
+ -------
2366
+ result : float or ndarray
2367
+ If `x` is 2-D, the return values is a float.
2368
+ Otherwise, it is an array with ``x.ndim - 2`` dimensions.
2369
+ The return values are either the minimum or maximum or sum of the
2370
+ singular values of the matrices, depending on whether `op`
2371
+ is `numpy.amin` or `numpy.amax` or `numpy.sum`.
2372
+
2373
+ """
2374
+ y = moveaxis(x, (row_axis, col_axis), (-2, -1))
2375
+ result = op(svd(y, compute_uv=False), axis=-1)
2376
+ return result
2377
+
2378
+
2379
+ def _norm_dispatcher(x, ord=None, axis=None, keepdims=None):
2380
+ return (x,)
2381
+
2382
+
2383
+ @array_function_dispatch(_norm_dispatcher)
2384
+ def norm(x, ord=None, axis=None, keepdims=False):
2385
+ """
2386
+ Matrix or vector norm.
2387
+
2388
+ This function is able to return one of eight different matrix norms,
2389
+ or one of an infinite number of vector norms (described below), depending
2390
+ on the value of the ``ord`` parameter.
2391
+
2392
+ Parameters
2393
+ ----------
2394
+ x : array_like
2395
+ Input array. If `axis` is None, `x` must be 1-D or 2-D, unless `ord`
2396
+ is None. If both `axis` and `ord` are None, the 2-norm of
2397
+ ``x.ravel`` will be returned.
2398
+ ord : {non-zero int, inf, -inf, 'fro', 'nuc'}, optional
2399
+ Order of the norm (see table under ``Notes``). inf means numpy's
2400
+ `inf` object. The default is None.
2401
+ axis : {None, int, 2-tuple of ints}, optional.
2402
+ If `axis` is an integer, it specifies the axis of `x` along which to
2403
+ compute the vector norms. If `axis` is a 2-tuple, it specifies the
2404
+ axes that hold 2-D matrices, and the matrix norms of these matrices
2405
+ are computed. If `axis` is None then either a vector norm (when `x`
2406
+ is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default
2407
+ is None.
2408
+
2409
+ .. versionadded:: 1.8.0
2410
+
2411
+ keepdims : bool, optional
2412
+ If this is set to True, the axes which are normed over are left in the
2413
+ result as dimensions with size one. With this option the result will
2414
+ broadcast correctly against the original `x`.
2415
+
2416
+ .. versionadded:: 1.10.0
2417
+
2418
+ Returns
2419
+ -------
2420
+ n : float or ndarray
2421
+ Norm of the matrix or vector(s).
2422
+
2423
+ See Also
2424
+ --------
2425
+ scipy.linalg.norm : Similar function in SciPy.
2426
+
2427
+ Notes
2428
+ -----
2429
+ For values of ``ord < 1``, the result is, strictly speaking, not a
2430
+ mathematical 'norm', but it may still be useful for various numerical
2431
+ purposes.
2432
+
2433
+ The following norms can be calculated:
2434
+
2435
+ ===== ============================ ==========================
2436
+ ord norm for matrices norm for vectors
2437
+ ===== ============================ ==========================
2438
+ None Frobenius norm 2-norm
2439
+ 'fro' Frobenius norm --
2440
+ 'nuc' nuclear norm --
2441
+ inf max(sum(abs(x), axis=1)) max(abs(x))
2442
+ -inf min(sum(abs(x), axis=1)) min(abs(x))
2443
+ 0 -- sum(x != 0)
2444
+ 1 max(sum(abs(x), axis=0)) as below
2445
+ -1 min(sum(abs(x), axis=0)) as below
2446
+ 2 2-norm (largest sing. value) as below
2447
+ -2 smallest singular value as below
2448
+ other -- sum(abs(x)**ord)**(1./ord)
2449
+ ===== ============================ ==========================
2450
+
2451
+ The Frobenius norm is given by [1]_:
2452
+
2453
+ :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
2454
+
2455
+ The nuclear norm is the sum of the singular values.
2456
+
2457
+ Both the Frobenius and nuclear norm orders are only defined for
2458
+ matrices and raise a ValueError when ``x.ndim != 2``.
2459
+
2460
+ References
2461
+ ----------
2462
+ .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
2463
+ Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
2464
+
2465
+ Examples
2466
+ --------
2467
+ >>> from numpy import linalg as LA
2468
+ >>> a = np.arange(9) - 4
2469
+ >>> a
2470
+ array([-4, -3, -2, ..., 2, 3, 4])
2471
+ >>> b = a.reshape((3, 3))
2472
+ >>> b
2473
+ array([[-4, -3, -2],
2474
+ [-1, 0, 1],
2475
+ [ 2, 3, 4]])
2476
+
2477
+ >>> LA.norm(a)
2478
+ 7.745966692414834
2479
+ >>> LA.norm(b)
2480
+ 7.745966692414834
2481
+ >>> LA.norm(b, 'fro')
2482
+ 7.745966692414834
2483
+ >>> LA.norm(a, np.inf)
2484
+ 4.0
2485
+ >>> LA.norm(b, np.inf)
2486
+ 9.0
2487
+ >>> LA.norm(a, -np.inf)
2488
+ 0.0
2489
+ >>> LA.norm(b, -np.inf)
2490
+ 2.0
2491
+
2492
+ >>> LA.norm(a, 1)
2493
+ 20.0
2494
+ >>> LA.norm(b, 1)
2495
+ 7.0
2496
+ >>> LA.norm(a, -1)
2497
+ -4.6566128774142013e-010
2498
+ >>> LA.norm(b, -1)
2499
+ 6.0
2500
+ >>> LA.norm(a, 2)
2501
+ 7.745966692414834
2502
+ >>> LA.norm(b, 2)
2503
+ 7.3484692283495345
2504
+
2505
+ >>> LA.norm(a, -2)
2506
+ 0.0
2507
+ >>> LA.norm(b, -2)
2508
+ 1.8570331885190563e-016 # may vary
2509
+ >>> LA.norm(a, 3)
2510
+ 5.8480354764257312 # may vary
2511
+ >>> LA.norm(a, -3)
2512
+ 0.0
2513
+
2514
+ Using the `axis` argument to compute vector norms:
2515
+
2516
+ >>> c = np.array([[ 1, 2, 3],
2517
+ ... [-1, 1, 4]])
2518
+ >>> LA.norm(c, axis=0)
2519
+ array([ 1.41421356, 2.23606798, 5. ])
2520
+ >>> LA.norm(c, axis=1)
2521
+ array([ 3.74165739, 4.24264069])
2522
+ >>> LA.norm(c, ord=1, axis=1)
2523
+ array([ 6., 6.])
2524
+
2525
+ Using the `axis` argument to compute matrix norms:
2526
+
2527
+ >>> m = np.arange(8).reshape(2,2,2)
2528
+ >>> LA.norm(m, axis=(1,2))
2529
+ array([ 3.74165739, 11.22497216])
2530
+ >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :])
2531
+ (3.7416573867739413, 11.224972160321824)
2532
+
2533
+ """
2534
+ x = asarray(x)
2535
+
2536
+ if not issubclass(x.dtype.type, (inexact, object_)):
2537
+ x = x.astype(float)
2538
+
2539
+ # Immediately handle some default, simple, fast, and common cases.
2540
+ if axis is None:
2541
+ ndim = x.ndim
2542
+ if ((ord is None) or
2543
+ (ord in ('f', 'fro') and ndim == 2) or
2544
+ (ord == 2 and ndim == 1)):
2545
+
2546
+ x = x.ravel(order='K')
2547
+ if isComplexType(x.dtype.type):
2548
+ x_real = x.real
2549
+ x_imag = x.imag
2550
+ sqnorm = x_real.dot(x_real) + x_imag.dot(x_imag)
2551
+ else:
2552
+ sqnorm = x.dot(x)
2553
+ ret = sqrt(sqnorm)
2554
+ if keepdims:
2555
+ ret = ret.reshape(ndim*[1])
2556
+ return ret
2557
+
2558
+ # Normalize the `axis` argument to a tuple.
2559
+ nd = x.ndim
2560
+ if axis is None:
2561
+ axis = tuple(range(nd))
2562
+ elif not isinstance(axis, tuple):
2563
+ try:
2564
+ axis = int(axis)
2565
+ except Exception as e:
2566
+ raise TypeError("'axis' must be None, an integer or a tuple of integers") from e
2567
+ axis = (axis,)
2568
+
2569
+ if len(axis) == 1:
2570
+ if ord == Inf:
2571
+ return abs(x).max(axis=axis, keepdims=keepdims)
2572
+ elif ord == -Inf:
2573
+ return abs(x).min(axis=axis, keepdims=keepdims)
2574
+ elif ord == 0:
2575
+ # Zero norm
2576
+ return (x != 0).astype(x.real.dtype).sum(axis=axis, keepdims=keepdims)
2577
+ elif ord == 1:
2578
+ # special case for speedup
2579
+ return add.reduce(abs(x), axis=axis, keepdims=keepdims)
2580
+ elif ord is None or ord == 2:
2581
+ # special case for speedup
2582
+ s = (x.conj() * x).real
2583
+ return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
2584
+ # None of the str-type keywords for ord ('fro', 'nuc')
2585
+ # are valid for vectors
2586
+ elif isinstance(ord, str):
2587
+ raise ValueError(f"Invalid norm order '{ord}' for vectors")
2588
+ else:
2589
+ absx = abs(x)
2590
+ absx **= ord
2591
+ ret = add.reduce(absx, axis=axis, keepdims=keepdims)
2592
+ ret **= reciprocal(ord, dtype=ret.dtype)
2593
+ return ret
2594
+ elif len(axis) == 2:
2595
+ row_axis, col_axis = axis
2596
+ row_axis = normalize_axis_index(row_axis, nd)
2597
+ col_axis = normalize_axis_index(col_axis, nd)
2598
+ if row_axis == col_axis:
2599
+ raise ValueError('Duplicate axes given.')
2600
+ if ord == 2:
2601
+ ret = _multi_svd_norm(x, row_axis, col_axis, amax)
2602
+ elif ord == -2:
2603
+ ret = _multi_svd_norm(x, row_axis, col_axis, amin)
2604
+ elif ord == 1:
2605
+ if col_axis > row_axis:
2606
+ col_axis -= 1
2607
+ ret = add.reduce(abs(x), axis=row_axis).max(axis=col_axis)
2608
+ elif ord == Inf:
2609
+ if row_axis > col_axis:
2610
+ row_axis -= 1
2611
+ ret = add.reduce(abs(x), axis=col_axis).max(axis=row_axis)
2612
+ elif ord == -1:
2613
+ if col_axis > row_axis:
2614
+ col_axis -= 1
2615
+ ret = add.reduce(abs(x), axis=row_axis).min(axis=col_axis)
2616
+ elif ord == -Inf:
2617
+ if row_axis > col_axis:
2618
+ row_axis -= 1
2619
+ ret = add.reduce(abs(x), axis=col_axis).min(axis=row_axis)
2620
+ elif ord in [None, 'fro', 'f']:
2621
+ ret = sqrt(add.reduce((x.conj() * x).real, axis=axis))
2622
+ elif ord == 'nuc':
2623
+ ret = _multi_svd_norm(x, row_axis, col_axis, sum)
2624
+ else:
2625
+ raise ValueError("Invalid norm order for matrices.")
2626
+ if keepdims:
2627
+ ret_shape = list(x.shape)
2628
+ ret_shape[axis[0]] = 1
2629
+ ret_shape[axis[1]] = 1
2630
+ ret = ret.reshape(ret_shape)
2631
+ return ret
2632
+ else:
2633
+ raise ValueError("Improper number of dimensions to norm.")
2634
+
2635
+
2636
+ # multi_dot
2637
+
2638
+ def _multidot_dispatcher(arrays, *, out=None):
2639
+ yield from arrays
2640
+ yield out
2641
+
2642
+
2643
+ @array_function_dispatch(_multidot_dispatcher)
2644
+ def multi_dot(arrays, *, out=None):
2645
+ """
2646
+ Compute the dot product of two or more arrays in a single function call,
2647
+ while automatically selecting the fastest evaluation order.
2648
+
2649
+ `multi_dot` chains `numpy.dot` and uses optimal parenthesization
2650
+ of the matrices [1]_ [2]_. Depending on the shapes of the matrices,
2651
+ this can speed up the multiplication a lot.
2652
+
2653
+ If the first argument is 1-D it is treated as a row vector.
2654
+ If the last argument is 1-D it is treated as a column vector.
2655
+ The other arguments must be 2-D.
2656
+
2657
+ Think of `multi_dot` as::
2658
+
2659
+ def multi_dot(arrays): return functools.reduce(np.dot, arrays)
2660
+
2661
+
2662
+ Parameters
2663
+ ----------
2664
+ arrays : sequence of array_like
2665
+ If the first argument is 1-D it is treated as row vector.
2666
+ If the last argument is 1-D it is treated as column vector.
2667
+ The other arguments must be 2-D.
2668
+ out : ndarray, optional
2669
+ Output argument. This must have the exact kind that would be returned
2670
+ if it was not used. In particular, it must have the right type, must be
2671
+ C-contiguous, and its dtype must be the dtype that would be returned
2672
+ for `dot(a, b)`. This is a performance feature. Therefore, if these
2673
+ conditions are not met, an exception is raised, instead of attempting
2674
+ to be flexible.
2675
+
2676
+ .. versionadded:: 1.19.0
2677
+
2678
+ Returns
2679
+ -------
2680
+ output : ndarray
2681
+ Returns the dot product of the supplied arrays.
2682
+
2683
+ See Also
2684
+ --------
2685
+ numpy.dot : dot multiplication with two arguments.
2686
+
2687
+ References
2688
+ ----------
2689
+
2690
+ .. [1] Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378
2691
+ .. [2] https://en.wikipedia.org/wiki/Matrix_chain_multiplication
2692
+
2693
+ Examples
2694
+ --------
2695
+ `multi_dot` allows you to write::
2696
+
2697
+ >>> from numpy.linalg import multi_dot
2698
+ >>> # Prepare some data
2699
+ >>> A = np.random.random((10000, 100))
2700
+ >>> B = np.random.random((100, 1000))
2701
+ >>> C = np.random.random((1000, 5))
2702
+ >>> D = np.random.random((5, 333))
2703
+ >>> # the actual dot multiplication
2704
+ >>> _ = multi_dot([A, B, C, D])
2705
+
2706
+ instead of::
2707
+
2708
+ >>> _ = np.dot(np.dot(np.dot(A, B), C), D)
2709
+ >>> # or
2710
+ >>> _ = A.dot(B).dot(C).dot(D)
2711
+
2712
+ Notes
2713
+ -----
2714
+ The cost for a matrix multiplication can be calculated with the
2715
+ following function::
2716
+
2717
+ def cost(A, B):
2718
+ return A.shape[0] * A.shape[1] * B.shape[1]
2719
+
2720
+ Assume we have three matrices
2721
+ :math:`A_{10x100}, B_{100x5}, C_{5x50}`.
2722
+
2723
+ The costs for the two different parenthesizations are as follows::
2724
+
2725
+ cost((AB)C) = 10*100*5 + 10*5*50 = 5000 + 2500 = 7500
2726
+ cost(A(BC)) = 10*100*50 + 100*5*50 = 50000 + 25000 = 75000
2727
+
2728
+ """
2729
+ n = len(arrays)
2730
+ # optimization only makes sense for len(arrays) > 2
2731
+ if n < 2:
2732
+ raise ValueError("Expecting at least two arrays.")
2733
+ elif n == 2:
2734
+ return dot(arrays[0], arrays[1], out=out)
2735
+
2736
+ arrays = [asanyarray(a) for a in arrays]
2737
+
2738
+ # save original ndim to reshape the result array into the proper form later
2739
+ ndim_first, ndim_last = arrays[0].ndim, arrays[-1].ndim
2740
+ # Explicitly convert vectors to 2D arrays to keep the logic of the internal
2741
+ # _multi_dot_* functions as simple as possible.
2742
+ if arrays[0].ndim == 1:
2743
+ arrays[0] = atleast_2d(arrays[0])
2744
+ if arrays[-1].ndim == 1:
2745
+ arrays[-1] = atleast_2d(arrays[-1]).T
2746
+ _assert_2d(*arrays)
2747
+
2748
+ # _multi_dot_three is much faster than _multi_dot_matrix_chain_order
2749
+ if n == 3:
2750
+ result = _multi_dot_three(arrays[0], arrays[1], arrays[2], out=out)
2751
+ else:
2752
+ order = _multi_dot_matrix_chain_order(arrays)
2753
+ result = _multi_dot(arrays, order, 0, n - 1, out=out)
2754
+
2755
+ # return proper shape
2756
+ if ndim_first == 1 and ndim_last == 1:
2757
+ return result[0, 0] # scalar
2758
+ elif ndim_first == 1 or ndim_last == 1:
2759
+ return result.ravel() # 1-D
2760
+ else:
2761
+ return result
2762
+
2763
+
2764
+ def _multi_dot_three(A, B, C, out=None):
2765
+ """
2766
+ Find the best order for three arrays and do the multiplication.
2767
+
2768
+ For three arguments `_multi_dot_three` is approximately 15 times faster
2769
+ than `_multi_dot_matrix_chain_order`
2770
+
2771
+ """
2772
+ a0, a1b0 = A.shape
2773
+ b1c0, c1 = C.shape
2774
+ # cost1 = cost((AB)C) = a0*a1b0*b1c0 + a0*b1c0*c1
2775
+ cost1 = a0 * b1c0 * (a1b0 + c1)
2776
+ # cost2 = cost(A(BC)) = a1b0*b1c0*c1 + a0*a1b0*c1
2777
+ cost2 = a1b0 * c1 * (a0 + b1c0)
2778
+
2779
+ if cost1 < cost2:
2780
+ return dot(dot(A, B), C, out=out)
2781
+ else:
2782
+ return dot(A, dot(B, C), out=out)
2783
+
2784
+
2785
+ def _multi_dot_matrix_chain_order(arrays, return_costs=False):
2786
+ """
2787
+ Return a np.array that encodes the optimal order of mutiplications.
2788
+
2789
+ The optimal order array is then used by `_multi_dot()` to do the
2790
+ multiplication.
2791
+
2792
+ Also return the cost matrix if `return_costs` is `True`
2793
+
2794
+ The implementation CLOSELY follows Cormen, "Introduction to Algorithms",
2795
+ Chapter 15.2, p. 370-378. Note that Cormen uses 1-based indices.
2796
+
2797
+ cost[i, j] = min([
2798
+ cost[prefix] + cost[suffix] + cost_mult(prefix, suffix)
2799
+ for k in range(i, j)])
2800
+
2801
+ """
2802
+ n = len(arrays)
2803
+ # p stores the dimensions of the matrices
2804
+ # Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50]
2805
+ p = [a.shape[0] for a in arrays] + [arrays[-1].shape[1]]
2806
+ # m is a matrix of costs of the subproblems
2807
+ # m[i,j]: min number of scalar multiplications needed to compute A_{i..j}
2808
+ m = zeros((n, n), dtype=double)
2809
+ # s is the actual ordering
2810
+ # s[i, j] is the value of k at which we split the product A_i..A_j
2811
+ s = empty((n, n), dtype=intp)
2812
+
2813
+ for l in range(1, n):
2814
+ for i in range(n - l):
2815
+ j = i + l
2816
+ m[i, j] = Inf
2817
+ for k in range(i, j):
2818
+ q = m[i, k] + m[k+1, j] + p[i]*p[k+1]*p[j+1]
2819
+ if q < m[i, j]:
2820
+ m[i, j] = q
2821
+ s[i, j] = k # Note that Cormen uses 1-based index
2822
+
2823
+ return (s, m) if return_costs else s
2824
+
2825
+
2826
+ def _multi_dot(arrays, order, i, j, out=None):
2827
+ """Actually do the multiplication with the given order."""
2828
+ if i == j:
2829
+ # the initial call with non-None out should never get here
2830
+ assert out is None
2831
+
2832
+ return arrays[i]
2833
+ else:
2834
+ return dot(_multi_dot(arrays, order, i, order[i, j]),
2835
+ _multi_dot(arrays, order, order[i, j] + 1, j),
2836
+ out=out)
venv/lib/python3.10/site-packages/numpy/linalg/linalg.pyi ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import (
3
+ Literal as L,
4
+ overload,
5
+ TypeVar,
6
+ Any,
7
+ SupportsIndex,
8
+ SupportsInt,
9
+ NamedTuple,
10
+ Generic,
11
+ )
12
+
13
+ from numpy import (
14
+ generic,
15
+ floating,
16
+ complexfloating,
17
+ int32,
18
+ float64,
19
+ complex128,
20
+ )
21
+
22
+ from numpy.linalg import LinAlgError as LinAlgError
23
+
24
+ from numpy._typing import (
25
+ NDArray,
26
+ ArrayLike,
27
+ _ArrayLikeInt_co,
28
+ _ArrayLikeFloat_co,
29
+ _ArrayLikeComplex_co,
30
+ _ArrayLikeTD64_co,
31
+ _ArrayLikeObject_co,
32
+ )
33
+
34
+ _T = TypeVar("_T")
35
+ _ArrayType = TypeVar("_ArrayType", bound=NDArray[Any])
36
+ _SCT = TypeVar("_SCT", bound=generic, covariant=True)
37
+ _SCT2 = TypeVar("_SCT2", bound=generic, covariant=True)
38
+
39
+ _2Tuple = tuple[_T, _T]
40
+ _ModeKind = L["reduced", "complete", "r", "raw"]
41
+
42
+ __all__: list[str]
43
+
44
+ class EigResult(NamedTuple):
45
+ eigenvalues: NDArray[Any]
46
+ eigenvectors: NDArray[Any]
47
+
48
+ class EighResult(NamedTuple):
49
+ eigenvalues: NDArray[Any]
50
+ eigenvectors: NDArray[Any]
51
+
52
+ class QRResult(NamedTuple):
53
+ Q: NDArray[Any]
54
+ R: NDArray[Any]
55
+
56
+ class SlogdetResult(NamedTuple):
57
+ # TODO: `sign` and `logabsdet` are scalars for input 2D arrays and
58
+ # a `(x.ndim - 2)`` dimensionl arrays otherwise
59
+ sign: Any
60
+ logabsdet: Any
61
+
62
+ class SVDResult(NamedTuple):
63
+ U: NDArray[Any]
64
+ S: NDArray[Any]
65
+ Vh: NDArray[Any]
66
+
67
+ @overload
68
+ def tensorsolve(
69
+ a: _ArrayLikeInt_co,
70
+ b: _ArrayLikeInt_co,
71
+ axes: None | Iterable[int] =...,
72
+ ) -> NDArray[float64]: ...
73
+ @overload
74
+ def tensorsolve(
75
+ a: _ArrayLikeFloat_co,
76
+ b: _ArrayLikeFloat_co,
77
+ axes: None | Iterable[int] =...,
78
+ ) -> NDArray[floating[Any]]: ...
79
+ @overload
80
+ def tensorsolve(
81
+ a: _ArrayLikeComplex_co,
82
+ b: _ArrayLikeComplex_co,
83
+ axes: None | Iterable[int] =...,
84
+ ) -> NDArray[complexfloating[Any, Any]]: ...
85
+
86
+ @overload
87
+ def solve(
88
+ a: _ArrayLikeInt_co,
89
+ b: _ArrayLikeInt_co,
90
+ ) -> NDArray[float64]: ...
91
+ @overload
92
+ def solve(
93
+ a: _ArrayLikeFloat_co,
94
+ b: _ArrayLikeFloat_co,
95
+ ) -> NDArray[floating[Any]]: ...
96
+ @overload
97
+ def solve(
98
+ a: _ArrayLikeComplex_co,
99
+ b: _ArrayLikeComplex_co,
100
+ ) -> NDArray[complexfloating[Any, Any]]: ...
101
+
102
+ @overload
103
+ def tensorinv(
104
+ a: _ArrayLikeInt_co,
105
+ ind: int = ...,
106
+ ) -> NDArray[float64]: ...
107
+ @overload
108
+ def tensorinv(
109
+ a: _ArrayLikeFloat_co,
110
+ ind: int = ...,
111
+ ) -> NDArray[floating[Any]]: ...
112
+ @overload
113
+ def tensorinv(
114
+ a: _ArrayLikeComplex_co,
115
+ ind: int = ...,
116
+ ) -> NDArray[complexfloating[Any, Any]]: ...
117
+
118
+ @overload
119
+ def inv(a: _ArrayLikeInt_co) -> NDArray[float64]: ...
120
+ @overload
121
+ def inv(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
122
+ @overload
123
+ def inv(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
124
+
125
+ # TODO: The supported input and output dtypes are dependent on the value of `n`.
126
+ # For example: `n < 0` always casts integer types to float64
127
+ def matrix_power(
128
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
129
+ n: SupportsIndex,
130
+ ) -> NDArray[Any]: ...
131
+
132
+ @overload
133
+ def cholesky(a: _ArrayLikeInt_co) -> NDArray[float64]: ...
134
+ @overload
135
+ def cholesky(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
136
+ @overload
137
+ def cholesky(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
138
+
139
+ @overload
140
+ def qr(a: _ArrayLikeInt_co, mode: _ModeKind = ...) -> QRResult: ...
141
+ @overload
142
+ def qr(a: _ArrayLikeFloat_co, mode: _ModeKind = ...) -> QRResult: ...
143
+ @overload
144
+ def qr(a: _ArrayLikeComplex_co, mode: _ModeKind = ...) -> QRResult: ...
145
+
146
+ @overload
147
+ def eigvals(a: _ArrayLikeInt_co) -> NDArray[float64] | NDArray[complex128]: ...
148
+ @overload
149
+ def eigvals(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]] | NDArray[complexfloating[Any, Any]]: ...
150
+ @overload
151
+ def eigvals(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
152
+
153
+ @overload
154
+ def eigvalsh(a: _ArrayLikeInt_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[float64]: ...
155
+ @overload
156
+ def eigvalsh(a: _ArrayLikeComplex_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[floating[Any]]: ...
157
+
158
+ @overload
159
+ def eig(a: _ArrayLikeInt_co) -> EigResult: ...
160
+ @overload
161
+ def eig(a: _ArrayLikeFloat_co) -> EigResult: ...
162
+ @overload
163
+ def eig(a: _ArrayLikeComplex_co) -> EigResult: ...
164
+
165
+ @overload
166
+ def eigh(
167
+ a: _ArrayLikeInt_co,
168
+ UPLO: L["L", "U", "l", "u"] = ...,
169
+ ) -> EighResult: ...
170
+ @overload
171
+ def eigh(
172
+ a: _ArrayLikeFloat_co,
173
+ UPLO: L["L", "U", "l", "u"] = ...,
174
+ ) -> EighResult: ...
175
+ @overload
176
+ def eigh(
177
+ a: _ArrayLikeComplex_co,
178
+ UPLO: L["L", "U", "l", "u"] = ...,
179
+ ) -> EighResult: ...
180
+
181
+ @overload
182
+ def svd(
183
+ a: _ArrayLikeInt_co,
184
+ full_matrices: bool = ...,
185
+ compute_uv: L[True] = ...,
186
+ hermitian: bool = ...,
187
+ ) -> SVDResult: ...
188
+ @overload
189
+ def svd(
190
+ a: _ArrayLikeFloat_co,
191
+ full_matrices: bool = ...,
192
+ compute_uv: L[True] = ...,
193
+ hermitian: bool = ...,
194
+ ) -> SVDResult: ...
195
+ @overload
196
+ def svd(
197
+ a: _ArrayLikeComplex_co,
198
+ full_matrices: bool = ...,
199
+ compute_uv: L[True] = ...,
200
+ hermitian: bool = ...,
201
+ ) -> SVDResult: ...
202
+ @overload
203
+ def svd(
204
+ a: _ArrayLikeInt_co,
205
+ full_matrices: bool = ...,
206
+ compute_uv: L[False] = ...,
207
+ hermitian: bool = ...,
208
+ ) -> NDArray[float64]: ...
209
+ @overload
210
+ def svd(
211
+ a: _ArrayLikeComplex_co,
212
+ full_matrices: bool = ...,
213
+ compute_uv: L[False] = ...,
214
+ hermitian: bool = ...,
215
+ ) -> NDArray[floating[Any]]: ...
216
+
217
+ # TODO: Returns a scalar for 2D arrays and
218
+ # a `(x.ndim - 2)`` dimensionl array otherwise
219
+ def cond(x: _ArrayLikeComplex_co, p: None | float | L["fro", "nuc"] = ...) -> Any: ...
220
+
221
+ # TODO: Returns `int` for <2D arrays and `intp` otherwise
222
+ def matrix_rank(
223
+ A: _ArrayLikeComplex_co,
224
+ tol: None | _ArrayLikeFloat_co = ...,
225
+ hermitian: bool = ...,
226
+ ) -> Any: ...
227
+
228
+ @overload
229
+ def pinv(
230
+ a: _ArrayLikeInt_co,
231
+ rcond: _ArrayLikeFloat_co = ...,
232
+ hermitian: bool = ...,
233
+ ) -> NDArray[float64]: ...
234
+ @overload
235
+ def pinv(
236
+ a: _ArrayLikeFloat_co,
237
+ rcond: _ArrayLikeFloat_co = ...,
238
+ hermitian: bool = ...,
239
+ ) -> NDArray[floating[Any]]: ...
240
+ @overload
241
+ def pinv(
242
+ a: _ArrayLikeComplex_co,
243
+ rcond: _ArrayLikeFloat_co = ...,
244
+ hermitian: bool = ...,
245
+ ) -> NDArray[complexfloating[Any, Any]]: ...
246
+
247
+ # TODO: Returns a 2-tuple of scalars for 2D arrays and
248
+ # a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise
249
+ def slogdet(a: _ArrayLikeComplex_co) -> SlogdetResult: ...
250
+
251
+ # TODO: Returns a 2-tuple of scalars for 2D arrays and
252
+ # a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise
253
+ def det(a: _ArrayLikeComplex_co) -> Any: ...
254
+
255
+ @overload
256
+ def lstsq(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, rcond: None | float = ...) -> tuple[
257
+ NDArray[float64],
258
+ NDArray[float64],
259
+ int32,
260
+ NDArray[float64],
261
+ ]: ...
262
+ @overload
263
+ def lstsq(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, rcond: None | float = ...) -> tuple[
264
+ NDArray[floating[Any]],
265
+ NDArray[floating[Any]],
266
+ int32,
267
+ NDArray[floating[Any]],
268
+ ]: ...
269
+ @overload
270
+ def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: None | float = ...) -> tuple[
271
+ NDArray[complexfloating[Any, Any]],
272
+ NDArray[floating[Any]],
273
+ int32,
274
+ NDArray[floating[Any]],
275
+ ]: ...
276
+
277
+ @overload
278
+ def norm(
279
+ x: ArrayLike,
280
+ ord: None | float | L["fro", "nuc"] = ...,
281
+ axis: None = ...,
282
+ keepdims: bool = ...,
283
+ ) -> floating[Any]: ...
284
+ @overload
285
+ def norm(
286
+ x: ArrayLike,
287
+ ord: None | float | L["fro", "nuc"] = ...,
288
+ axis: SupportsInt | SupportsIndex | tuple[int, ...] = ...,
289
+ keepdims: bool = ...,
290
+ ) -> Any: ...
291
+
292
+ # TODO: Returns a scalar or array
293
+ def multi_dot(
294
+ arrays: Iterable[_ArrayLikeComplex_co | _ArrayLikeObject_co | _ArrayLikeTD64_co],
295
+ *,
296
+ out: None | NDArray[Any] = ...,
297
+ ) -> Any: ...
venv/lib/python3.10/site-packages/numpy/linalg/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc ADDED
Binary file (827 Bytes). View file
 
venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc ADDED
Binary file (65.5 kB). View file
 
venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc ADDED
Binary file (4.63 kB). View file
 
venv/lib/python3.10/site-packages/numpy/linalg/tests/test_deprecations.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test deprecation and future warnings.
2
+
3
+ """
4
+ import numpy as np
5
+ from numpy.testing import assert_warns
6
+
7
+
8
+ def test_qr_mode_full_future_warning():
9
+ """Check mode='full' FutureWarning.
10
+
11
+ In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were
12
+ deprecated. The release date will probably be sometime in the summer
13
+ of 2013.
14
+
15
+ """
16
+ a = np.eye(2)
17
+ assert_warns(DeprecationWarning, np.linalg.qr, a, mode='full')
18
+ assert_warns(DeprecationWarning, np.linalg.qr, a, mode='f')
19
+ assert_warns(DeprecationWarning, np.linalg.qr, a, mode='economic')
20
+ assert_warns(DeprecationWarning, np.linalg.qr, a, mode='e')
venv/lib/python3.10/site-packages/numpy/linalg/tests/test_linalg.py ADDED
@@ -0,0 +1,2198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test functions for linalg module
2
+
3
+ """
4
+ import os
5
+ import sys
6
+ import itertools
7
+ import traceback
8
+ import textwrap
9
+ import subprocess
10
+ import pytest
11
+
12
+ import numpy as np
13
+ from numpy import array, single, double, csingle, cdouble, dot, identity, matmul
14
+ from numpy.core import swapaxes
15
+ from numpy import multiply, atleast_2d, inf, asarray
16
+ from numpy import linalg
17
+ from numpy.linalg import matrix_power, norm, matrix_rank, multi_dot, LinAlgError
18
+ from numpy.linalg.linalg import _multi_dot_matrix_chain_order
19
+ from numpy.testing import (
20
+ assert_, assert_equal, assert_raises, assert_array_equal,
21
+ assert_almost_equal, assert_allclose, suppress_warnings,
22
+ assert_raises_regex, HAS_LAPACK64, IS_WASM
23
+ )
24
+ try:
25
+ import numpy.linalg.lapack_lite
26
+ except ImportError:
27
+ # May be broken when numpy was built without BLAS/LAPACK present
28
+ # If so, ensure we don't break the whole test suite - the `lapack_lite`
29
+ # submodule should be removed, it's only used in two tests in this file.
30
+ pass
31
+
32
+
33
+ def consistent_subclass(out, in_):
34
+ # For ndarray subclass input, our output should have the same subclass
35
+ # (non-ndarray input gets converted to ndarray).
36
+ return type(out) is (type(in_) if isinstance(in_, np.ndarray)
37
+ else np.ndarray)
38
+
39
+
40
+ old_assert_almost_equal = assert_almost_equal
41
+
42
+
43
+ def assert_almost_equal(a, b, single_decimal=6, double_decimal=12, **kw):
44
+ if asarray(a).dtype.type in (single, csingle):
45
+ decimal = single_decimal
46
+ else:
47
+ decimal = double_decimal
48
+ old_assert_almost_equal(a, b, decimal=decimal, **kw)
49
+
50
+
51
+ def get_real_dtype(dtype):
52
+ return {single: single, double: double,
53
+ csingle: single, cdouble: double}[dtype]
54
+
55
+
56
+ def get_complex_dtype(dtype):
57
+ return {single: csingle, double: cdouble,
58
+ csingle: csingle, cdouble: cdouble}[dtype]
59
+
60
+
61
+ def get_rtol(dtype):
62
+ # Choose a safe rtol
63
+ if dtype in (single, csingle):
64
+ return 1e-5
65
+ else:
66
+ return 1e-11
67
+
68
+
69
+ # used to categorize tests
70
+ all_tags = {
71
+ 'square', 'nonsquare', 'hermitian', # mutually exclusive
72
+ 'generalized', 'size-0', 'strided' # optional additions
73
+ }
74
+
75
+
76
+ class LinalgCase:
77
+ def __init__(self, name, a, b, tags=set()):
78
+ """
79
+ A bundle of arguments to be passed to a test case, with an identifying
80
+ name, the operands a and b, and a set of tags to filter the tests
81
+ """
82
+ assert_(isinstance(name, str))
83
+ self.name = name
84
+ self.a = a
85
+ self.b = b
86
+ self.tags = frozenset(tags) # prevent shared tags
87
+
88
+ def check(self, do):
89
+ """
90
+ Run the function `do` on this test case, expanding arguments
91
+ """
92
+ do(self.a, self.b, tags=self.tags)
93
+
94
+ def __repr__(self):
95
+ return f'<LinalgCase: {self.name}>'
96
+
97
+
98
+ def apply_tag(tag, cases):
99
+ """
100
+ Add the given tag (a string) to each of the cases (a list of LinalgCase
101
+ objects)
102
+ """
103
+ assert tag in all_tags, "Invalid tag"
104
+ for case in cases:
105
+ case.tags = case.tags | {tag}
106
+ return cases
107
+
108
+
109
+ #
110
+ # Base test cases
111
+ #
112
+
113
+ np.random.seed(1234)
114
+
115
+ CASES = []
116
+
117
+ # square test cases
118
+ CASES += apply_tag('square', [
119
+ LinalgCase("single",
120
+ array([[1., 2.], [3., 4.]], dtype=single),
121
+ array([2., 1.], dtype=single)),
122
+ LinalgCase("double",
123
+ array([[1., 2.], [3., 4.]], dtype=double),
124
+ array([2., 1.], dtype=double)),
125
+ LinalgCase("double_2",
126
+ array([[1., 2.], [3., 4.]], dtype=double),
127
+ array([[2., 1., 4.], [3., 4., 6.]], dtype=double)),
128
+ LinalgCase("csingle",
129
+ array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=csingle),
130
+ array([2. + 1j, 1. + 2j], dtype=csingle)),
131
+ LinalgCase("cdouble",
132
+ array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble),
133
+ array([2. + 1j, 1. + 2j], dtype=cdouble)),
134
+ LinalgCase("cdouble_2",
135
+ array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble),
136
+ array([[2. + 1j, 1. + 2j, 1 + 3j], [1 - 2j, 1 - 3j, 1 - 6j]], dtype=cdouble)),
137
+ LinalgCase("0x0",
138
+ np.empty((0, 0), dtype=double),
139
+ np.empty((0,), dtype=double),
140
+ tags={'size-0'}),
141
+ LinalgCase("8x8",
142
+ np.random.rand(8, 8),
143
+ np.random.rand(8)),
144
+ LinalgCase("1x1",
145
+ np.random.rand(1, 1),
146
+ np.random.rand(1)),
147
+ LinalgCase("nonarray",
148
+ [[1, 2], [3, 4]],
149
+ [2, 1]),
150
+ ])
151
+
152
+ # non-square test-cases
153
+ CASES += apply_tag('nonsquare', [
154
+ LinalgCase("single_nsq_1",
155
+ array([[1., 2., 3.], [3., 4., 6.]], dtype=single),
156
+ array([2., 1.], dtype=single)),
157
+ LinalgCase("single_nsq_2",
158
+ array([[1., 2.], [3., 4.], [5., 6.]], dtype=single),
159
+ array([2., 1., 3.], dtype=single)),
160
+ LinalgCase("double_nsq_1",
161
+ array([[1., 2., 3.], [3., 4., 6.]], dtype=double),
162
+ array([2., 1.], dtype=double)),
163
+ LinalgCase("double_nsq_2",
164
+ array([[1., 2.], [3., 4.], [5., 6.]], dtype=double),
165
+ array([2., 1., 3.], dtype=double)),
166
+ LinalgCase("csingle_nsq_1",
167
+ array(
168
+ [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=csingle),
169
+ array([2. + 1j, 1. + 2j], dtype=csingle)),
170
+ LinalgCase("csingle_nsq_2",
171
+ array(
172
+ [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=csingle),
173
+ array([2. + 1j, 1. + 2j, 3. - 3j], dtype=csingle)),
174
+ LinalgCase("cdouble_nsq_1",
175
+ array(
176
+ [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble),
177
+ array([2. + 1j, 1. + 2j], dtype=cdouble)),
178
+ LinalgCase("cdouble_nsq_2",
179
+ array(
180
+ [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble),
181
+ array([2. + 1j, 1. + 2j, 3. - 3j], dtype=cdouble)),
182
+ LinalgCase("cdouble_nsq_1_2",
183
+ array(
184
+ [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble),
185
+ array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)),
186
+ LinalgCase("cdouble_nsq_2_2",
187
+ array(
188
+ [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble),
189
+ array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)),
190
+ LinalgCase("8x11",
191
+ np.random.rand(8, 11),
192
+ np.random.rand(8)),
193
+ LinalgCase("1x5",
194
+ np.random.rand(1, 5),
195
+ np.random.rand(1)),
196
+ LinalgCase("5x1",
197
+ np.random.rand(5, 1),
198
+ np.random.rand(5)),
199
+ LinalgCase("0x4",
200
+ np.random.rand(0, 4),
201
+ np.random.rand(0),
202
+ tags={'size-0'}),
203
+ LinalgCase("4x0",
204
+ np.random.rand(4, 0),
205
+ np.random.rand(4),
206
+ tags={'size-0'}),
207
+ ])
208
+
209
+ # hermitian test-cases
210
+ CASES += apply_tag('hermitian', [
211
+ LinalgCase("hsingle",
212
+ array([[1., 2.], [2., 1.]], dtype=single),
213
+ None),
214
+ LinalgCase("hdouble",
215
+ array([[1., 2.], [2., 1.]], dtype=double),
216
+ None),
217
+ LinalgCase("hcsingle",
218
+ array([[1., 2 + 3j], [2 - 3j, 1]], dtype=csingle),
219
+ None),
220
+ LinalgCase("hcdouble",
221
+ array([[1., 2 + 3j], [2 - 3j, 1]], dtype=cdouble),
222
+ None),
223
+ LinalgCase("hempty",
224
+ np.empty((0, 0), dtype=double),
225
+ None,
226
+ tags={'size-0'}),
227
+ LinalgCase("hnonarray",
228
+ [[1, 2], [2, 1]],
229
+ None),
230
+ LinalgCase("matrix_b_only",
231
+ array([[1., 2.], [2., 1.]]),
232
+ None),
233
+ LinalgCase("hmatrix_1x1",
234
+ np.random.rand(1, 1),
235
+ None),
236
+ ])
237
+
238
+
239
+ #
240
+ # Gufunc test cases
241
+ #
242
+ def _make_generalized_cases():
243
+ new_cases = []
244
+
245
+ for case in CASES:
246
+ if not isinstance(case.a, np.ndarray):
247
+ continue
248
+
249
+ a = np.array([case.a, 2 * case.a, 3 * case.a])
250
+ if case.b is None:
251
+ b = None
252
+ else:
253
+ b = np.array([case.b, 7 * case.b, 6 * case.b])
254
+ new_case = LinalgCase(case.name + "_tile3", a, b,
255
+ tags=case.tags | {'generalized'})
256
+ new_cases.append(new_case)
257
+
258
+ a = np.array([case.a] * 2 * 3).reshape((3, 2) + case.a.shape)
259
+ if case.b is None:
260
+ b = None
261
+ else:
262
+ b = np.array([case.b] * 2 * 3).reshape((3, 2) + case.b.shape)
263
+ new_case = LinalgCase(case.name + "_tile213", a, b,
264
+ tags=case.tags | {'generalized'})
265
+ new_cases.append(new_case)
266
+
267
+ return new_cases
268
+
269
+
270
+ CASES += _make_generalized_cases()
271
+
272
+
273
+ #
274
+ # Generate stride combination variations of the above
275
+ #
276
+ def _stride_comb_iter(x):
277
+ """
278
+ Generate cartesian product of strides for all axes
279
+ """
280
+
281
+ if not isinstance(x, np.ndarray):
282
+ yield x, "nop"
283
+ return
284
+
285
+ stride_set = [(1,)] * x.ndim
286
+ stride_set[-1] = (1, 3, -4)
287
+ if x.ndim > 1:
288
+ stride_set[-2] = (1, 3, -4)
289
+ if x.ndim > 2:
290
+ stride_set[-3] = (1, -4)
291
+
292
+ for repeats in itertools.product(*tuple(stride_set)):
293
+ new_shape = [abs(a * b) for a, b in zip(x.shape, repeats)]
294
+ slices = tuple([slice(None, None, repeat) for repeat in repeats])
295
+
296
+ # new array with different strides, but same data
297
+ xi = np.empty(new_shape, dtype=x.dtype)
298
+ xi.view(np.uint32).fill(0xdeadbeef)
299
+ xi = xi[slices]
300
+ xi[...] = x
301
+ xi = xi.view(x.__class__)
302
+ assert_(np.all(xi == x))
303
+ yield xi, "stride_" + "_".join(["%+d" % j for j in repeats])
304
+
305
+ # generate also zero strides if possible
306
+ if x.ndim >= 1 and x.shape[-1] == 1:
307
+ s = list(x.strides)
308
+ s[-1] = 0
309
+ xi = np.lib.stride_tricks.as_strided(x, strides=s)
310
+ yield xi, "stride_xxx_0"
311
+ if x.ndim >= 2 and x.shape[-2] == 1:
312
+ s = list(x.strides)
313
+ s[-2] = 0
314
+ xi = np.lib.stride_tricks.as_strided(x, strides=s)
315
+ yield xi, "stride_xxx_0_x"
316
+ if x.ndim >= 2 and x.shape[:-2] == (1, 1):
317
+ s = list(x.strides)
318
+ s[-1] = 0
319
+ s[-2] = 0
320
+ xi = np.lib.stride_tricks.as_strided(x, strides=s)
321
+ yield xi, "stride_xxx_0_0"
322
+
323
+
324
+ def _make_strided_cases():
325
+ new_cases = []
326
+ for case in CASES:
327
+ for a, a_label in _stride_comb_iter(case.a):
328
+ for b, b_label in _stride_comb_iter(case.b):
329
+ new_case = LinalgCase(case.name + "_" + a_label + "_" + b_label, a, b,
330
+ tags=case.tags | {'strided'})
331
+ new_cases.append(new_case)
332
+ return new_cases
333
+
334
+
335
+ CASES += _make_strided_cases()
336
+
337
+
338
+ #
339
+ # Test different routines against the above cases
340
+ #
341
+ class LinalgTestCase:
342
+ TEST_CASES = CASES
343
+
344
+ def check_cases(self, require=set(), exclude=set()):
345
+ """
346
+ Run func on each of the cases with all of the tags in require, and none
347
+ of the tags in exclude
348
+ """
349
+ for case in self.TEST_CASES:
350
+ # filter by require and exclude
351
+ if case.tags & require != require:
352
+ continue
353
+ if case.tags & exclude:
354
+ continue
355
+
356
+ try:
357
+ case.check(self.do)
358
+ except Exception as e:
359
+ msg = f'In test case: {case!r}\n\n'
360
+ msg += traceback.format_exc()
361
+ raise AssertionError(msg) from e
362
+
363
+
364
+ class LinalgSquareTestCase(LinalgTestCase):
365
+
366
+ def test_sq_cases(self):
367
+ self.check_cases(require={'square'},
368
+ exclude={'generalized', 'size-0'})
369
+
370
+ def test_empty_sq_cases(self):
371
+ self.check_cases(require={'square', 'size-0'},
372
+ exclude={'generalized'})
373
+
374
+
375
+ class LinalgNonsquareTestCase(LinalgTestCase):
376
+
377
+ def test_nonsq_cases(self):
378
+ self.check_cases(require={'nonsquare'},
379
+ exclude={'generalized', 'size-0'})
380
+
381
+ def test_empty_nonsq_cases(self):
382
+ self.check_cases(require={'nonsquare', 'size-0'},
383
+ exclude={'generalized'})
384
+
385
+
386
+ class HermitianTestCase(LinalgTestCase):
387
+
388
+ def test_herm_cases(self):
389
+ self.check_cases(require={'hermitian'},
390
+ exclude={'generalized', 'size-0'})
391
+
392
+ def test_empty_herm_cases(self):
393
+ self.check_cases(require={'hermitian', 'size-0'},
394
+ exclude={'generalized'})
395
+
396
+
397
+ class LinalgGeneralizedSquareTestCase(LinalgTestCase):
398
+
399
+ @pytest.mark.slow
400
+ def test_generalized_sq_cases(self):
401
+ self.check_cases(require={'generalized', 'square'},
402
+ exclude={'size-0'})
403
+
404
+ @pytest.mark.slow
405
+ def test_generalized_empty_sq_cases(self):
406
+ self.check_cases(require={'generalized', 'square', 'size-0'})
407
+
408
+
409
+ class LinalgGeneralizedNonsquareTestCase(LinalgTestCase):
410
+
411
+ @pytest.mark.slow
412
+ def test_generalized_nonsq_cases(self):
413
+ self.check_cases(require={'generalized', 'nonsquare'},
414
+ exclude={'size-0'})
415
+
416
+ @pytest.mark.slow
417
+ def test_generalized_empty_nonsq_cases(self):
418
+ self.check_cases(require={'generalized', 'nonsquare', 'size-0'})
419
+
420
+
421
+ class HermitianGeneralizedTestCase(LinalgTestCase):
422
+
423
+ @pytest.mark.slow
424
+ def test_generalized_herm_cases(self):
425
+ self.check_cases(require={'generalized', 'hermitian'},
426
+ exclude={'size-0'})
427
+
428
+ @pytest.mark.slow
429
+ def test_generalized_empty_herm_cases(self):
430
+ self.check_cases(require={'generalized', 'hermitian', 'size-0'},
431
+ exclude={'none'})
432
+
433
+
434
+ def dot_generalized(a, b):
435
+ a = asarray(a)
436
+ if a.ndim >= 3:
437
+ if a.ndim == b.ndim:
438
+ # matrix x matrix
439
+ new_shape = a.shape[:-1] + b.shape[-1:]
440
+ elif a.ndim == b.ndim + 1:
441
+ # matrix x vector
442
+ new_shape = a.shape[:-1]
443
+ else:
444
+ raise ValueError("Not implemented...")
445
+ r = np.empty(new_shape, dtype=np.common_type(a, b))
446
+ for c in itertools.product(*map(range, a.shape[:-2])):
447
+ r[c] = dot(a[c], b[c])
448
+ return r
449
+ else:
450
+ return dot(a, b)
451
+
452
+
453
+ def identity_like_generalized(a):
454
+ a = asarray(a)
455
+ if a.ndim >= 3:
456
+ r = np.empty(a.shape, dtype=a.dtype)
457
+ r[...] = identity(a.shape[-2])
458
+ return r
459
+ else:
460
+ return identity(a.shape[0])
461
+
462
+
463
+ class SolveCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
464
+ # kept apart from TestSolve for use for testing with matrices.
465
+ def do(self, a, b, tags):
466
+ x = linalg.solve(a, b)
467
+ assert_almost_equal(b, dot_generalized(a, x))
468
+ assert_(consistent_subclass(x, b))
469
+
470
+
471
+ class TestSolve(SolveCases):
472
+ @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
473
+ def test_types(self, dtype):
474
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
475
+ assert_equal(linalg.solve(x, x).dtype, dtype)
476
+
477
+ def test_0_size(self):
478
+ class ArraySubclass(np.ndarray):
479
+ pass
480
+ # Test system of 0x0 matrices
481
+ a = np.arange(8).reshape(2, 2, 2)
482
+ b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass)
483
+
484
+ expected = linalg.solve(a, b)[:, 0:0, :]
485
+ result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, :])
486
+ assert_array_equal(result, expected)
487
+ assert_(isinstance(result, ArraySubclass))
488
+
489
+ # Test errors for non-square and only b's dimension being 0
490
+ assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b)
491
+ assert_raises(ValueError, linalg.solve, a, b[:, 0:0, :])
492
+
493
+ # Test broadcasting error
494
+ b = np.arange(6).reshape(1, 3, 2) # broadcasting error
495
+ assert_raises(ValueError, linalg.solve, a, b)
496
+ assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
497
+
498
+ # Test zero "single equations" with 0x0 matrices.
499
+ b = np.arange(2).reshape(1, 2).view(ArraySubclass)
500
+ expected = linalg.solve(a, b)[:, 0:0]
501
+ result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0])
502
+ assert_array_equal(result, expected)
503
+ assert_(isinstance(result, ArraySubclass))
504
+
505
+ b = np.arange(3).reshape(1, 3)
506
+ assert_raises(ValueError, linalg.solve, a, b)
507
+ assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
508
+ assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b)
509
+
510
+ def test_0_size_k(self):
511
+ # test zero multiple equation (K=0) case.
512
+ class ArraySubclass(np.ndarray):
513
+ pass
514
+ a = np.arange(4).reshape(1, 2, 2)
515
+ b = np.arange(6).reshape(3, 2, 1).view(ArraySubclass)
516
+
517
+ expected = linalg.solve(a, b)[:, :, 0:0]
518
+ result = linalg.solve(a, b[:, :, 0:0])
519
+ assert_array_equal(result, expected)
520
+ assert_(isinstance(result, ArraySubclass))
521
+
522
+ # test both zero.
523
+ expected = linalg.solve(a, b)[:, 0:0, 0:0]
524
+ result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, 0:0])
525
+ assert_array_equal(result, expected)
526
+ assert_(isinstance(result, ArraySubclass))
527
+
528
+
529
+ class InvCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
530
+
531
+ def do(self, a, b, tags):
532
+ a_inv = linalg.inv(a)
533
+ assert_almost_equal(dot_generalized(a, a_inv),
534
+ identity_like_generalized(a))
535
+ assert_(consistent_subclass(a_inv, a))
536
+
537
+
538
+ class TestInv(InvCases):
539
+ @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
540
+ def test_types(self, dtype):
541
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
542
+ assert_equal(linalg.inv(x).dtype, dtype)
543
+
544
+ def test_0_size(self):
545
+ # Check that all kinds of 0-sized arrays work
546
+ class ArraySubclass(np.ndarray):
547
+ pass
548
+ a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
549
+ res = linalg.inv(a)
550
+ assert_(res.dtype.type is np.float64)
551
+ assert_equal(a.shape, res.shape)
552
+ assert_(isinstance(res, ArraySubclass))
553
+
554
+ a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
555
+ res = linalg.inv(a)
556
+ assert_(res.dtype.type is np.complex64)
557
+ assert_equal(a.shape, res.shape)
558
+ assert_(isinstance(res, ArraySubclass))
559
+
560
+
561
+ class EigvalsCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
562
+
563
+ def do(self, a, b, tags):
564
+ ev = linalg.eigvals(a)
565
+ evalues, evectors = linalg.eig(a)
566
+ assert_almost_equal(ev, evalues)
567
+
568
+
569
+ class TestEigvals(EigvalsCases):
570
+ @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
571
+ def test_types(self, dtype):
572
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
573
+ assert_equal(linalg.eigvals(x).dtype, dtype)
574
+ x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
575
+ assert_equal(linalg.eigvals(x).dtype, get_complex_dtype(dtype))
576
+
577
+ def test_0_size(self):
578
+ # Check that all kinds of 0-sized arrays work
579
+ class ArraySubclass(np.ndarray):
580
+ pass
581
+ a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
582
+ res = linalg.eigvals(a)
583
+ assert_(res.dtype.type is np.float64)
584
+ assert_equal((0, 1), res.shape)
585
+ # This is just for documentation, it might make sense to change:
586
+ assert_(isinstance(res, np.ndarray))
587
+
588
+ a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
589
+ res = linalg.eigvals(a)
590
+ assert_(res.dtype.type is np.complex64)
591
+ assert_equal((0,), res.shape)
592
+ # This is just for documentation, it might make sense to change:
593
+ assert_(isinstance(res, np.ndarray))
594
+
595
+
596
+ class EigCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
597
+
598
+ def do(self, a, b, tags):
599
+ res = linalg.eig(a)
600
+ eigenvalues, eigenvectors = res.eigenvalues, res.eigenvectors
601
+ assert_allclose(dot_generalized(a, eigenvectors),
602
+ np.asarray(eigenvectors) * np.asarray(eigenvalues)[..., None, :],
603
+ rtol=get_rtol(eigenvalues.dtype))
604
+ assert_(consistent_subclass(eigenvectors, a))
605
+
606
+
607
+ class TestEig(EigCases):
608
+ @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
609
+ def test_types(self, dtype):
610
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
611
+ w, v = np.linalg.eig(x)
612
+ assert_equal(w.dtype, dtype)
613
+ assert_equal(v.dtype, dtype)
614
+
615
+ x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
616
+ w, v = np.linalg.eig(x)
617
+ assert_equal(w.dtype, get_complex_dtype(dtype))
618
+ assert_equal(v.dtype, get_complex_dtype(dtype))
619
+
620
+ def test_0_size(self):
621
+ # Check that all kinds of 0-sized arrays work
622
+ class ArraySubclass(np.ndarray):
623
+ pass
624
+ a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
625
+ res, res_v = linalg.eig(a)
626
+ assert_(res_v.dtype.type is np.float64)
627
+ assert_(res.dtype.type is np.float64)
628
+ assert_equal(a.shape, res_v.shape)
629
+ assert_equal((0, 1), res.shape)
630
+ # This is just for documentation, it might make sense to change:
631
+ assert_(isinstance(a, np.ndarray))
632
+
633
+ a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
634
+ res, res_v = linalg.eig(a)
635
+ assert_(res_v.dtype.type is np.complex64)
636
+ assert_(res.dtype.type is np.complex64)
637
+ assert_equal(a.shape, res_v.shape)
638
+ assert_equal((0,), res.shape)
639
+ # This is just for documentation, it might make sense to change:
640
+ assert_(isinstance(a, np.ndarray))
641
+
642
+
643
+ class SVDBaseTests:
644
+ hermitian = False
645
+
646
+ @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
647
+ def test_types(self, dtype):
648
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
649
+ res = linalg.svd(x)
650
+ U, S, Vh = res.U, res.S, res.Vh
651
+ assert_equal(U.dtype, dtype)
652
+ assert_equal(S.dtype, get_real_dtype(dtype))
653
+ assert_equal(Vh.dtype, dtype)
654
+ s = linalg.svd(x, compute_uv=False, hermitian=self.hermitian)
655
+ assert_equal(s.dtype, get_real_dtype(dtype))
656
+
657
+
658
+ class SVDCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
659
+
660
+ def do(self, a, b, tags):
661
+ u, s, vt = linalg.svd(a, False)
662
+ assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :],
663
+ np.asarray(vt)),
664
+ rtol=get_rtol(u.dtype))
665
+ assert_(consistent_subclass(u, a))
666
+ assert_(consistent_subclass(vt, a))
667
+
668
+
669
+ class TestSVD(SVDCases, SVDBaseTests):
670
+ def test_empty_identity(self):
671
+ """ Empty input should put an identity matrix in u or vh """
672
+ x = np.empty((4, 0))
673
+ u, s, vh = linalg.svd(x, compute_uv=True, hermitian=self.hermitian)
674
+ assert_equal(u.shape, (4, 4))
675
+ assert_equal(vh.shape, (0, 0))
676
+ assert_equal(u, np.eye(4))
677
+
678
+ x = np.empty((0, 4))
679
+ u, s, vh = linalg.svd(x, compute_uv=True, hermitian=self.hermitian)
680
+ assert_equal(u.shape, (0, 0))
681
+ assert_equal(vh.shape, (4, 4))
682
+ assert_equal(vh, np.eye(4))
683
+
684
+
685
+ class SVDHermitianCases(HermitianTestCase, HermitianGeneralizedTestCase):
686
+
687
+ def do(self, a, b, tags):
688
+ u, s, vt = linalg.svd(a, False, hermitian=True)
689
+ assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :],
690
+ np.asarray(vt)),
691
+ rtol=get_rtol(u.dtype))
692
+ def hermitian(mat):
693
+ axes = list(range(mat.ndim))
694
+ axes[-1], axes[-2] = axes[-2], axes[-1]
695
+ return np.conj(np.transpose(mat, axes=axes))
696
+
697
+ assert_almost_equal(np.matmul(u, hermitian(u)), np.broadcast_to(np.eye(u.shape[-1]), u.shape))
698
+ assert_almost_equal(np.matmul(vt, hermitian(vt)), np.broadcast_to(np.eye(vt.shape[-1]), vt.shape))
699
+ assert_equal(np.sort(s)[..., ::-1], s)
700
+ assert_(consistent_subclass(u, a))
701
+ assert_(consistent_subclass(vt, a))
702
+
703
+
704
+ class TestSVDHermitian(SVDHermitianCases, SVDBaseTests):
705
+ hermitian = True
706
+
707
+
708
+ class CondCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
709
+ # cond(x, p) for p in (None, 2, -2)
710
+
711
+ def do(self, a, b, tags):
712
+ c = asarray(a) # a might be a matrix
713
+ if 'size-0' in tags:
714
+ assert_raises(LinAlgError, linalg.cond, c)
715
+ return
716
+
717
+ # +-2 norms
718
+ s = linalg.svd(c, compute_uv=False)
719
+ assert_almost_equal(
720
+ linalg.cond(a), s[..., 0] / s[..., -1],
721
+ single_decimal=5, double_decimal=11)
722
+ assert_almost_equal(
723
+ linalg.cond(a, 2), s[..., 0] / s[..., -1],
724
+ single_decimal=5, double_decimal=11)
725
+ assert_almost_equal(
726
+ linalg.cond(a, -2), s[..., -1] / s[..., 0],
727
+ single_decimal=5, double_decimal=11)
728
+
729
+ # Other norms
730
+ cinv = np.linalg.inv(c)
731
+ assert_almost_equal(
732
+ linalg.cond(a, 1),
733
+ abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
734
+ single_decimal=5, double_decimal=11)
735
+ assert_almost_equal(
736
+ linalg.cond(a, -1),
737
+ abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
738
+ single_decimal=5, double_decimal=11)
739
+ assert_almost_equal(
740
+ linalg.cond(a, np.inf),
741
+ abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
742
+ single_decimal=5, double_decimal=11)
743
+ assert_almost_equal(
744
+ linalg.cond(a, -np.inf),
745
+ abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
746
+ single_decimal=5, double_decimal=11)
747
+ assert_almost_equal(
748
+ linalg.cond(a, 'fro'),
749
+ np.sqrt((abs(c)**2).sum(-1).sum(-1)
750
+ * (abs(cinv)**2).sum(-1).sum(-1)),
751
+ single_decimal=5, double_decimal=11)
752
+
753
+
754
+ class TestCond(CondCases):
755
+ def test_basic_nonsvd(self):
756
+ # Smoketest the non-svd norms
757
+ A = array([[1., 0, 1], [0, -2., 0], [0, 0, 3.]])
758
+ assert_almost_equal(linalg.cond(A, inf), 4)
759
+ assert_almost_equal(linalg.cond(A, -inf), 2/3)
760
+ assert_almost_equal(linalg.cond(A, 1), 4)
761
+ assert_almost_equal(linalg.cond(A, -1), 0.5)
762
+ assert_almost_equal(linalg.cond(A, 'fro'), np.sqrt(265 / 12))
763
+
764
+ def test_singular(self):
765
+ # Singular matrices have infinite condition number for
766
+ # positive norms, and negative norms shouldn't raise
767
+ # exceptions
768
+ As = [np.zeros((2, 2)), np.ones((2, 2))]
769
+ p_pos = [None, 1, 2, 'fro']
770
+ p_neg = [-1, -2]
771
+ for A, p in itertools.product(As, p_pos):
772
+ # Inversion may not hit exact infinity, so just check the
773
+ # number is large
774
+ assert_(linalg.cond(A, p) > 1e15)
775
+ for A, p in itertools.product(As, p_neg):
776
+ linalg.cond(A, p)
777
+
778
+ @pytest.mark.xfail(True, run=False,
779
+ reason="Platform/LAPACK-dependent failure, "
780
+ "see gh-18914")
781
+ def test_nan(self):
782
+ # nans should be passed through, not converted to infs
783
+ ps = [None, 1, -1, 2, -2, 'fro']
784
+ p_pos = [None, 1, 2, 'fro']
785
+
786
+ A = np.ones((2, 2))
787
+ A[0,1] = np.nan
788
+ for p in ps:
789
+ c = linalg.cond(A, p)
790
+ assert_(isinstance(c, np.float_))
791
+ assert_(np.isnan(c))
792
+
793
+ A = np.ones((3, 2, 2))
794
+ A[1,0,1] = np.nan
795
+ for p in ps:
796
+ c = linalg.cond(A, p)
797
+ assert_(np.isnan(c[1]))
798
+ if p in p_pos:
799
+ assert_(c[0] > 1e15)
800
+ assert_(c[2] > 1e15)
801
+ else:
802
+ assert_(not np.isnan(c[0]))
803
+ assert_(not np.isnan(c[2]))
804
+
805
+ def test_stacked_singular(self):
806
+ # Check behavior when only some of the stacked matrices are
807
+ # singular
808
+ np.random.seed(1234)
809
+ A = np.random.rand(2, 2, 2, 2)
810
+ A[0,0] = 0
811
+ A[1,1] = 0
812
+
813
+ for p in (None, 1, 2, 'fro', -1, -2):
814
+ c = linalg.cond(A, p)
815
+ assert_equal(c[0,0], np.inf)
816
+ assert_equal(c[1,1], np.inf)
817
+ assert_(np.isfinite(c[0,1]))
818
+ assert_(np.isfinite(c[1,0]))
819
+
820
+
821
+ class PinvCases(LinalgSquareTestCase,
822
+ LinalgNonsquareTestCase,
823
+ LinalgGeneralizedSquareTestCase,
824
+ LinalgGeneralizedNonsquareTestCase):
825
+
826
+ def do(self, a, b, tags):
827
+ a_ginv = linalg.pinv(a)
828
+ # `a @ a_ginv == I` does not hold if a is singular
829
+ dot = dot_generalized
830
+ assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
831
+ assert_(consistent_subclass(a_ginv, a))
832
+
833
+
834
+ class TestPinv(PinvCases):
835
+ pass
836
+
837
+
838
+ class PinvHermitianCases(HermitianTestCase, HermitianGeneralizedTestCase):
839
+
840
+ def do(self, a, b, tags):
841
+ a_ginv = linalg.pinv(a, hermitian=True)
842
+ # `a @ a_ginv == I` does not hold if a is singular
843
+ dot = dot_generalized
844
+ assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
845
+ assert_(consistent_subclass(a_ginv, a))
846
+
847
+
848
+ class TestPinvHermitian(PinvHermitianCases):
849
+ pass
850
+
851
+
852
+ class DetCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
853
+
854
+ def do(self, a, b, tags):
855
+ d = linalg.det(a)
856
+ res = linalg.slogdet(a)
857
+ s, ld = res.sign, res.logabsdet
858
+ if asarray(a).dtype.type in (single, double):
859
+ ad = asarray(a).astype(double)
860
+ else:
861
+ ad = asarray(a).astype(cdouble)
862
+ ev = linalg.eigvals(ad)
863
+ assert_almost_equal(d, multiply.reduce(ev, axis=-1))
864
+ assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))
865
+
866
+ s = np.atleast_1d(s)
867
+ ld = np.atleast_1d(ld)
868
+ m = (s != 0)
869
+ assert_almost_equal(np.abs(s[m]), 1)
870
+ assert_equal(ld[~m], -inf)
871
+
872
+
873
+ class TestDet(DetCases):
874
+ def test_zero(self):
875
+ assert_equal(linalg.det([[0.0]]), 0.0)
876
+ assert_equal(type(linalg.det([[0.0]])), double)
877
+ assert_equal(linalg.det([[0.0j]]), 0.0)
878
+ assert_equal(type(linalg.det([[0.0j]])), cdouble)
879
+
880
+ assert_equal(linalg.slogdet([[0.0]]), (0.0, -inf))
881
+ assert_equal(type(linalg.slogdet([[0.0]])[0]), double)
882
+ assert_equal(type(linalg.slogdet([[0.0]])[1]), double)
883
+ assert_equal(linalg.slogdet([[0.0j]]), (0.0j, -inf))
884
+ assert_equal(type(linalg.slogdet([[0.0j]])[0]), cdouble)
885
+ assert_equal(type(linalg.slogdet([[0.0j]])[1]), double)
886
+
887
+ @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
888
+ def test_types(self, dtype):
889
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
890
+ assert_equal(np.linalg.det(x).dtype, dtype)
891
+ ph, s = np.linalg.slogdet(x)
892
+ assert_equal(s.dtype, get_real_dtype(dtype))
893
+ assert_equal(ph.dtype, dtype)
894
+
895
+ def test_0_size(self):
896
+ a = np.zeros((0, 0), dtype=np.complex64)
897
+ res = linalg.det(a)
898
+ assert_equal(res, 1.)
899
+ assert_(res.dtype.type is np.complex64)
900
+ res = linalg.slogdet(a)
901
+ assert_equal(res, (1, 0))
902
+ assert_(res[0].dtype.type is np.complex64)
903
+ assert_(res[1].dtype.type is np.float32)
904
+
905
+ a = np.zeros((0, 0), dtype=np.float64)
906
+ res = linalg.det(a)
907
+ assert_equal(res, 1.)
908
+ assert_(res.dtype.type is np.float64)
909
+ res = linalg.slogdet(a)
910
+ assert_equal(res, (1, 0))
911
+ assert_(res[0].dtype.type is np.float64)
912
+ assert_(res[1].dtype.type is np.float64)
913
+
914
+
915
+ class LstsqCases(LinalgSquareTestCase, LinalgNonsquareTestCase):
916
+
917
+ def do(self, a, b, tags):
918
+ arr = np.asarray(a)
919
+ m, n = arr.shape
920
+ u, s, vt = linalg.svd(a, False)
921
+ x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
922
+ if m == 0:
923
+ assert_((x == 0).all())
924
+ if m <= n:
925
+ assert_almost_equal(b, dot(a, x))
926
+ assert_equal(rank, m)
927
+ else:
928
+ assert_equal(rank, n)
929
+ assert_almost_equal(sv, sv.__array_wrap__(s))
930
+ if rank == n and m > n:
931
+ expect_resids = (
932
+ np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
933
+ expect_resids = np.asarray(expect_resids)
934
+ if np.asarray(b).ndim == 1:
935
+ expect_resids.shape = (1,)
936
+ assert_equal(residuals.shape, expect_resids.shape)
937
+ else:
938
+ expect_resids = np.array([]).view(type(x))
939
+ assert_almost_equal(residuals, expect_resids)
940
+ assert_(np.issubdtype(residuals.dtype, np.floating))
941
+ assert_(consistent_subclass(x, b))
942
+ assert_(consistent_subclass(residuals, b))
943
+
944
+
945
+ class TestLstsq(LstsqCases):
946
+ def test_future_rcond(self):
947
+ a = np.array([[0., 1., 0., 1., 2., 0.],
948
+ [0., 2., 0., 0., 1., 0.],
949
+ [1., 0., 1., 0., 0., 4.],
950
+ [0., 0., 0., 2., 3., 0.]]).T
951
+
952
+ b = np.array([1, 0, 0, 0, 0, 0])
953
+ with suppress_warnings() as sup:
954
+ w = sup.record(FutureWarning, "`rcond` parameter will change")
955
+ x, residuals, rank, s = linalg.lstsq(a, b)
956
+ assert_(rank == 4)
957
+ x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
958
+ assert_(rank == 4)
959
+ x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
960
+ assert_(rank == 3)
961
+ # Warning should be raised exactly once (first command)
962
+ assert_(len(w) == 1)
963
+
964
+ @pytest.mark.parametrize(["m", "n", "n_rhs"], [
965
+ (4, 2, 2),
966
+ (0, 4, 1),
967
+ (0, 4, 2),
968
+ (4, 0, 1),
969
+ (4, 0, 2),
970
+ (4, 2, 0),
971
+ (0, 0, 0)
972
+ ])
973
+ def test_empty_a_b(self, m, n, n_rhs):
974
+ a = np.arange(m * n).reshape(m, n)
975
+ b = np.ones((m, n_rhs))
976
+ x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
977
+ if m == 0:
978
+ assert_((x == 0).all())
979
+ assert_equal(x.shape, (n, n_rhs))
980
+ assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
981
+ if m > n and n_rhs > 0:
982
+ # residuals are exactly the squared norms of b's columns
983
+ r = b - np.dot(a, x)
984
+ assert_almost_equal(residuals, (r * r).sum(axis=-2))
985
+ assert_equal(rank, min(m, n))
986
+ assert_equal(s.shape, (min(m, n),))
987
+
988
+ def test_incompatible_dims(self):
989
+ # use modified version of docstring example
990
+ x = np.array([0, 1, 2, 3])
991
+ y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
992
+ A = np.vstack([x, np.ones(len(x))]).T
993
+ with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
994
+ linalg.lstsq(A, y, rcond=None)
995
+
996
+
997
+ @pytest.mark.parametrize('dt', [np.dtype(c) for c in '?bBhHiIqQefdgFDGO'])
998
+ class TestMatrixPower:
999
+
1000
+ rshft_0 = np.eye(4)
1001
+ rshft_1 = rshft_0[[3, 0, 1, 2]]
1002
+ rshft_2 = rshft_0[[2, 3, 0, 1]]
1003
+ rshft_3 = rshft_0[[1, 2, 3, 0]]
1004
+ rshft_all = [rshft_0, rshft_1, rshft_2, rshft_3]
1005
+ noninv = array([[1, 0], [0, 0]])
1006
+ stacked = np.block([[[rshft_0]]]*2)
1007
+ #FIXME the 'e' dtype might work in future
1008
+ dtnoinv = [object, np.dtype('e'), np.dtype('g'), np.dtype('G')]
1009
+
1010
+ def test_large_power(self, dt):
1011
+ rshft = self.rshft_1.astype(dt)
1012
+ assert_equal(
1013
+ matrix_power(rshft, 2**100 + 2**10 + 2**5 + 0), self.rshft_0)
1014
+ assert_equal(
1015
+ matrix_power(rshft, 2**100 + 2**10 + 2**5 + 1), self.rshft_1)
1016
+ assert_equal(
1017
+ matrix_power(rshft, 2**100 + 2**10 + 2**5 + 2), self.rshft_2)
1018
+ assert_equal(
1019
+ matrix_power(rshft, 2**100 + 2**10 + 2**5 + 3), self.rshft_3)
1020
+
1021
+ def test_power_is_zero(self, dt):
1022
+ def tz(M):
1023
+ mz = matrix_power(M, 0)
1024
+ assert_equal(mz, identity_like_generalized(M))
1025
+ assert_equal(mz.dtype, M.dtype)
1026
+
1027
+ for mat in self.rshft_all:
1028
+ tz(mat.astype(dt))
1029
+ if dt != object:
1030
+ tz(self.stacked.astype(dt))
1031
+
1032
+ def test_power_is_one(self, dt):
1033
+ def tz(mat):
1034
+ mz = matrix_power(mat, 1)
1035
+ assert_equal(mz, mat)
1036
+ assert_equal(mz.dtype, mat.dtype)
1037
+
1038
+ for mat in self.rshft_all:
1039
+ tz(mat.astype(dt))
1040
+ if dt != object:
1041
+ tz(self.stacked.astype(dt))
1042
+
1043
+ def test_power_is_two(self, dt):
1044
+ def tz(mat):
1045
+ mz = matrix_power(mat, 2)
1046
+ mmul = matmul if mat.dtype != object else dot
1047
+ assert_equal(mz, mmul(mat, mat))
1048
+ assert_equal(mz.dtype, mat.dtype)
1049
+
1050
+ for mat in self.rshft_all:
1051
+ tz(mat.astype(dt))
1052
+ if dt != object:
1053
+ tz(self.stacked.astype(dt))
1054
+
1055
+ def test_power_is_minus_one(self, dt):
1056
+ def tz(mat):
1057
+ invmat = matrix_power(mat, -1)
1058
+ mmul = matmul if mat.dtype != object else dot
1059
+ assert_almost_equal(
1060
+ mmul(invmat, mat), identity_like_generalized(mat))
1061
+
1062
+ for mat in self.rshft_all:
1063
+ if dt not in self.dtnoinv:
1064
+ tz(mat.astype(dt))
1065
+
1066
+ def test_exceptions_bad_power(self, dt):
1067
+ mat = self.rshft_0.astype(dt)
1068
+ assert_raises(TypeError, matrix_power, mat, 1.5)
1069
+ assert_raises(TypeError, matrix_power, mat, [1])
1070
+
1071
+ def test_exceptions_non_square(self, dt):
1072
+ assert_raises(LinAlgError, matrix_power, np.array([1], dt), 1)
1073
+ assert_raises(LinAlgError, matrix_power, np.array([[1], [2]], dt), 1)
1074
+ assert_raises(LinAlgError, matrix_power, np.ones((4, 3, 2), dt), 1)
1075
+
1076
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1077
+ def test_exceptions_not_invertible(self, dt):
1078
+ if dt in self.dtnoinv:
1079
+ return
1080
+ mat = self.noninv.astype(dt)
1081
+ assert_raises(LinAlgError, matrix_power, mat, -1)
1082
+
1083
+
1084
+ class TestEigvalshCases(HermitianTestCase, HermitianGeneralizedTestCase):
1085
+
1086
+ def do(self, a, b, tags):
1087
+ # note that eigenvalue arrays returned by eig must be sorted since
1088
+ # their order isn't guaranteed.
1089
+ ev = linalg.eigvalsh(a, 'L')
1090
+ evalues, evectors = linalg.eig(a)
1091
+ evalues.sort(axis=-1)
1092
+ assert_allclose(ev, evalues, rtol=get_rtol(ev.dtype))
1093
+
1094
+ ev2 = linalg.eigvalsh(a, 'U')
1095
+ assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype))
1096
+
1097
+
1098
+ class TestEigvalsh:
1099
+ @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
1100
+ def test_types(self, dtype):
1101
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
1102
+ w = np.linalg.eigvalsh(x)
1103
+ assert_equal(w.dtype, get_real_dtype(dtype))
1104
+
1105
+ def test_invalid(self):
1106
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
1107
+ assert_raises(ValueError, np.linalg.eigvalsh, x, UPLO="lrong")
1108
+ assert_raises(ValueError, np.linalg.eigvalsh, x, "lower")
1109
+ assert_raises(ValueError, np.linalg.eigvalsh, x, "upper")
1110
+
1111
+ def test_UPLO(self):
1112
+ Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
1113
+ Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
1114
+ tgt = np.array([-1, 1], dtype=np.double)
1115
+ rtol = get_rtol(np.double)
1116
+
1117
+ # Check default is 'L'
1118
+ w = np.linalg.eigvalsh(Klo)
1119
+ assert_allclose(w, tgt, rtol=rtol)
1120
+ # Check 'L'
1121
+ w = np.linalg.eigvalsh(Klo, UPLO='L')
1122
+ assert_allclose(w, tgt, rtol=rtol)
1123
+ # Check 'l'
1124
+ w = np.linalg.eigvalsh(Klo, UPLO='l')
1125
+ assert_allclose(w, tgt, rtol=rtol)
1126
+ # Check 'U'
1127
+ w = np.linalg.eigvalsh(Kup, UPLO='U')
1128
+ assert_allclose(w, tgt, rtol=rtol)
1129
+ # Check 'u'
1130
+ w = np.linalg.eigvalsh(Kup, UPLO='u')
1131
+ assert_allclose(w, tgt, rtol=rtol)
1132
+
1133
+ def test_0_size(self):
1134
+ # Check that all kinds of 0-sized arrays work
1135
+ class ArraySubclass(np.ndarray):
1136
+ pass
1137
+ a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
1138
+ res = linalg.eigvalsh(a)
1139
+ assert_(res.dtype.type is np.float64)
1140
+ assert_equal((0, 1), res.shape)
1141
+ # This is just for documentation, it might make sense to change:
1142
+ assert_(isinstance(res, np.ndarray))
1143
+
1144
+ a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
1145
+ res = linalg.eigvalsh(a)
1146
+ assert_(res.dtype.type is np.float32)
1147
+ assert_equal((0,), res.shape)
1148
+ # This is just for documentation, it might make sense to change:
1149
+ assert_(isinstance(res, np.ndarray))
1150
+
1151
+
1152
+ class TestEighCases(HermitianTestCase, HermitianGeneralizedTestCase):
1153
+
1154
+ def do(self, a, b, tags):
1155
+ # note that eigenvalue arrays returned by eig must be sorted since
1156
+ # their order isn't guaranteed.
1157
+ res = linalg.eigh(a)
1158
+ ev, evc = res.eigenvalues, res.eigenvectors
1159
+ evalues, evectors = linalg.eig(a)
1160
+ evalues.sort(axis=-1)
1161
+ assert_almost_equal(ev, evalues)
1162
+
1163
+ assert_allclose(dot_generalized(a, evc),
1164
+ np.asarray(ev)[..., None, :] * np.asarray(evc),
1165
+ rtol=get_rtol(ev.dtype))
1166
+
1167
+ ev2, evc2 = linalg.eigh(a, 'U')
1168
+ assert_almost_equal(ev2, evalues)
1169
+
1170
+ assert_allclose(dot_generalized(a, evc2),
1171
+ np.asarray(ev2)[..., None, :] * np.asarray(evc2),
1172
+ rtol=get_rtol(ev.dtype), err_msg=repr(a))
1173
+
1174
+
1175
+ class TestEigh:
1176
+ @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
1177
+ def test_types(self, dtype):
1178
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
1179
+ w, v = np.linalg.eigh(x)
1180
+ assert_equal(w.dtype, get_real_dtype(dtype))
1181
+ assert_equal(v.dtype, dtype)
1182
+
1183
+ def test_invalid(self):
1184
+ x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
1185
+ assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
1186
+ assert_raises(ValueError, np.linalg.eigh, x, "lower")
1187
+ assert_raises(ValueError, np.linalg.eigh, x, "upper")
1188
+
1189
+ def test_UPLO(self):
1190
+ Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
1191
+ Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
1192
+ tgt = np.array([-1, 1], dtype=np.double)
1193
+ rtol = get_rtol(np.double)
1194
+
1195
+ # Check default is 'L'
1196
+ w, v = np.linalg.eigh(Klo)
1197
+ assert_allclose(w, tgt, rtol=rtol)
1198
+ # Check 'L'
1199
+ w, v = np.linalg.eigh(Klo, UPLO='L')
1200
+ assert_allclose(w, tgt, rtol=rtol)
1201
+ # Check 'l'
1202
+ w, v = np.linalg.eigh(Klo, UPLO='l')
1203
+ assert_allclose(w, tgt, rtol=rtol)
1204
+ # Check 'U'
1205
+ w, v = np.linalg.eigh(Kup, UPLO='U')
1206
+ assert_allclose(w, tgt, rtol=rtol)
1207
+ # Check 'u'
1208
+ w, v = np.linalg.eigh(Kup, UPLO='u')
1209
+ assert_allclose(w, tgt, rtol=rtol)
1210
+
1211
+ def test_0_size(self):
1212
+ # Check that all kinds of 0-sized arrays work
1213
+ class ArraySubclass(np.ndarray):
1214
+ pass
1215
+ a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
1216
+ res, res_v = linalg.eigh(a)
1217
+ assert_(res_v.dtype.type is np.float64)
1218
+ assert_(res.dtype.type is np.float64)
1219
+ assert_equal(a.shape, res_v.shape)
1220
+ assert_equal((0, 1), res.shape)
1221
+ # This is just for documentation, it might make sense to change:
1222
+ assert_(isinstance(a, np.ndarray))
1223
+
1224
+ a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
1225
+ res, res_v = linalg.eigh(a)
1226
+ assert_(res_v.dtype.type is np.complex64)
1227
+ assert_(res.dtype.type is np.float32)
1228
+ assert_equal(a.shape, res_v.shape)
1229
+ assert_equal((0,), res.shape)
1230
+ # This is just for documentation, it might make sense to change:
1231
+ assert_(isinstance(a, np.ndarray))
1232
+
1233
+
1234
+ class _TestNormBase:
1235
+ dt = None
1236
+ dec = None
1237
+
1238
+ @staticmethod
1239
+ def check_dtype(x, res):
1240
+ if issubclass(x.dtype.type, np.inexact):
1241
+ assert_equal(res.dtype, x.real.dtype)
1242
+ else:
1243
+ # For integer input, don't have to test float precision of output.
1244
+ assert_(issubclass(res.dtype.type, np.floating))
1245
+
1246
+
1247
+ class _TestNormGeneral(_TestNormBase):
1248
+
1249
+ def test_empty(self):
1250
+ assert_equal(norm([]), 0.0)
1251
+ assert_equal(norm(array([], dtype=self.dt)), 0.0)
1252
+ assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
1253
+
1254
+ def test_vector_return_type(self):
1255
+ a = np.array([1, 0, 1])
1256
+
1257
+ exact_types = np.typecodes['AllInteger']
1258
+ inexact_types = np.typecodes['AllFloat']
1259
+
1260
+ all_types = exact_types + inexact_types
1261
+
1262
+ for each_type in all_types:
1263
+ at = a.astype(each_type)
1264
+
1265
+ an = norm(at, -np.inf)
1266
+ self.check_dtype(at, an)
1267
+ assert_almost_equal(an, 0.0)
1268
+
1269
+ with suppress_warnings() as sup:
1270
+ sup.filter(RuntimeWarning, "divide by zero encountered")
1271
+ an = norm(at, -1)
1272
+ self.check_dtype(at, an)
1273
+ assert_almost_equal(an, 0.0)
1274
+
1275
+ an = norm(at, 0)
1276
+ self.check_dtype(at, an)
1277
+ assert_almost_equal(an, 2)
1278
+
1279
+ an = norm(at, 1)
1280
+ self.check_dtype(at, an)
1281
+ assert_almost_equal(an, 2.0)
1282
+
1283
+ an = norm(at, 2)
1284
+ self.check_dtype(at, an)
1285
+ assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/2.0))
1286
+
1287
+ an = norm(at, 4)
1288
+ self.check_dtype(at, an)
1289
+ assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/4.0))
1290
+
1291
+ an = norm(at, np.inf)
1292
+ self.check_dtype(at, an)
1293
+ assert_almost_equal(an, 1.0)
1294
+
1295
+ def test_vector(self):
1296
+ a = [1, 2, 3, 4]
1297
+ b = [-1, -2, -3, -4]
1298
+ c = [-1, 2, -3, 4]
1299
+
1300
+ def _test(v):
1301
+ np.testing.assert_almost_equal(norm(v), 30 ** 0.5,
1302
+ decimal=self.dec)
1303
+ np.testing.assert_almost_equal(norm(v, inf), 4.0,
1304
+ decimal=self.dec)
1305
+ np.testing.assert_almost_equal(norm(v, -inf), 1.0,
1306
+ decimal=self.dec)
1307
+ np.testing.assert_almost_equal(norm(v, 1), 10.0,
1308
+ decimal=self.dec)
1309
+ np.testing.assert_almost_equal(norm(v, -1), 12.0 / 25,
1310
+ decimal=self.dec)
1311
+ np.testing.assert_almost_equal(norm(v, 2), 30 ** 0.5,
1312
+ decimal=self.dec)
1313
+ np.testing.assert_almost_equal(norm(v, -2), ((205. / 144) ** -0.5),
1314
+ decimal=self.dec)
1315
+ np.testing.assert_almost_equal(norm(v, 0), 4,
1316
+ decimal=self.dec)
1317
+
1318
+ for v in (a, b, c,):
1319
+ _test(v)
1320
+
1321
+ for v in (array(a, dtype=self.dt), array(b, dtype=self.dt),
1322
+ array(c, dtype=self.dt)):
1323
+ _test(v)
1324
+
1325
+ def test_axis(self):
1326
+ # Vector norms.
1327
+ # Compare the use of `axis` with computing the norm of each row
1328
+ # or column separately.
1329
+ A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
1330
+ for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
1331
+ expected0 = [norm(A[:, k], ord=order) for k in range(A.shape[1])]
1332
+ assert_almost_equal(norm(A, ord=order, axis=0), expected0)
1333
+ expected1 = [norm(A[k, :], ord=order) for k in range(A.shape[0])]
1334
+ assert_almost_equal(norm(A, ord=order, axis=1), expected1)
1335
+
1336
+ # Matrix norms.
1337
+ B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
1338
+ nd = B.ndim
1339
+ for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro']:
1340
+ for axis in itertools.combinations(range(-nd, nd), 2):
1341
+ row_axis, col_axis = axis
1342
+ if row_axis < 0:
1343
+ row_axis += nd
1344
+ if col_axis < 0:
1345
+ col_axis += nd
1346
+ if row_axis == col_axis:
1347
+ assert_raises(ValueError, norm, B, ord=order, axis=axis)
1348
+ else:
1349
+ n = norm(B, ord=order, axis=axis)
1350
+
1351
+ # The logic using k_index only works for nd = 3.
1352
+ # This has to be changed if nd is increased.
1353
+ k_index = nd - (row_axis + col_axis)
1354
+ if row_axis < col_axis:
1355
+ expected = [norm(B[:].take(k, axis=k_index), ord=order)
1356
+ for k in range(B.shape[k_index])]
1357
+ else:
1358
+ expected = [norm(B[:].take(k, axis=k_index).T, ord=order)
1359
+ for k in range(B.shape[k_index])]
1360
+ assert_almost_equal(n, expected)
1361
+
1362
+ def test_keepdims(self):
1363
+ A = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
1364
+
1365
+ allclose_err = 'order {0}, axis = {1}'
1366
+ shape_err = 'Shape mismatch found {0}, expected {1}, order={2}, axis={3}'
1367
+
1368
+ # check the order=None, axis=None case
1369
+ expected = norm(A, ord=None, axis=None)
1370
+ found = norm(A, ord=None, axis=None, keepdims=True)
1371
+ assert_allclose(np.squeeze(found), expected,
1372
+ err_msg=allclose_err.format(None, None))
1373
+ expected_shape = (1, 1, 1)
1374
+ assert_(found.shape == expected_shape,
1375
+ shape_err.format(found.shape, expected_shape, None, None))
1376
+
1377
+ # Vector norms.
1378
+ for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
1379
+ for k in range(A.ndim):
1380
+ expected = norm(A, ord=order, axis=k)
1381
+ found = norm(A, ord=order, axis=k, keepdims=True)
1382
+ assert_allclose(np.squeeze(found), expected,
1383
+ err_msg=allclose_err.format(order, k))
1384
+ expected_shape = list(A.shape)
1385
+ expected_shape[k] = 1
1386
+ expected_shape = tuple(expected_shape)
1387
+ assert_(found.shape == expected_shape,
1388
+ shape_err.format(found.shape, expected_shape, order, k))
1389
+
1390
+ # Matrix norms.
1391
+ for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro', 'nuc']:
1392
+ for k in itertools.permutations(range(A.ndim), 2):
1393
+ expected = norm(A, ord=order, axis=k)
1394
+ found = norm(A, ord=order, axis=k, keepdims=True)
1395
+ assert_allclose(np.squeeze(found), expected,
1396
+ err_msg=allclose_err.format(order, k))
1397
+ expected_shape = list(A.shape)
1398
+ expected_shape[k[0]] = 1
1399
+ expected_shape[k[1]] = 1
1400
+ expected_shape = tuple(expected_shape)
1401
+ assert_(found.shape == expected_shape,
1402
+ shape_err.format(found.shape, expected_shape, order, k))
1403
+
1404
+
1405
+ class _TestNorm2D(_TestNormBase):
1406
+ # Define the part for 2d arrays separately, so we can subclass this
1407
+ # and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg.
1408
+ array = np.array
1409
+
1410
+ def test_matrix_empty(self):
1411
+ assert_equal(norm(self.array([[]], dtype=self.dt)), 0.0)
1412
+
1413
+ def test_matrix_return_type(self):
1414
+ a = self.array([[1, 0, 1], [0, 1, 1]])
1415
+
1416
+ exact_types = np.typecodes['AllInteger']
1417
+
1418
+ # float32, complex64, float64, complex128 types are the only types
1419
+ # allowed by `linalg`, which performs the matrix operations used
1420
+ # within `norm`.
1421
+ inexact_types = 'fdFD'
1422
+
1423
+ all_types = exact_types + inexact_types
1424
+
1425
+ for each_type in all_types:
1426
+ at = a.astype(each_type)
1427
+
1428
+ an = norm(at, -np.inf)
1429
+ self.check_dtype(at, an)
1430
+ assert_almost_equal(an, 2.0)
1431
+
1432
+ with suppress_warnings() as sup:
1433
+ sup.filter(RuntimeWarning, "divide by zero encountered")
1434
+ an = norm(at, -1)
1435
+ self.check_dtype(at, an)
1436
+ assert_almost_equal(an, 1.0)
1437
+
1438
+ an = norm(at, 1)
1439
+ self.check_dtype(at, an)
1440
+ assert_almost_equal(an, 2.0)
1441
+
1442
+ an = norm(at, 2)
1443
+ self.check_dtype(at, an)
1444
+ assert_almost_equal(an, 3.0**(1.0/2.0))
1445
+
1446
+ an = norm(at, -2)
1447
+ self.check_dtype(at, an)
1448
+ assert_almost_equal(an, 1.0)
1449
+
1450
+ an = norm(at, np.inf)
1451
+ self.check_dtype(at, an)
1452
+ assert_almost_equal(an, 2.0)
1453
+
1454
+ an = norm(at, 'fro')
1455
+ self.check_dtype(at, an)
1456
+ assert_almost_equal(an, 2.0)
1457
+
1458
+ an = norm(at, 'nuc')
1459
+ self.check_dtype(at, an)
1460
+ # Lower bar needed to support low precision floats.
1461
+ # They end up being off by 1 in the 7th place.
1462
+ np.testing.assert_almost_equal(an, 2.7320508075688772, decimal=6)
1463
+
1464
+ def test_matrix_2x2(self):
1465
+ A = self.array([[1, 3], [5, 7]], dtype=self.dt)
1466
+ assert_almost_equal(norm(A), 84 ** 0.5)
1467
+ assert_almost_equal(norm(A, 'fro'), 84 ** 0.5)
1468
+ assert_almost_equal(norm(A, 'nuc'), 10.0)
1469
+ assert_almost_equal(norm(A, inf), 12.0)
1470
+ assert_almost_equal(norm(A, -inf), 4.0)
1471
+ assert_almost_equal(norm(A, 1), 10.0)
1472
+ assert_almost_equal(norm(A, -1), 6.0)
1473
+ assert_almost_equal(norm(A, 2), 9.1231056256176615)
1474
+ assert_almost_equal(norm(A, -2), 0.87689437438234041)
1475
+
1476
+ assert_raises(ValueError, norm, A, 'nofro')
1477
+ assert_raises(ValueError, norm, A, -3)
1478
+ assert_raises(ValueError, norm, A, 0)
1479
+
1480
+ def test_matrix_3x3(self):
1481
+ # This test has been added because the 2x2 example
1482
+ # happened to have equal nuclear norm and induced 1-norm.
1483
+ # The 1/10 scaling factor accommodates the absolute tolerance
1484
+ # used in assert_almost_equal.
1485
+ A = (1 / 10) * \
1486
+ self.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt)
1487
+ assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5)
1488
+ assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5)
1489
+ assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836)
1490
+ assert_almost_equal(norm(A, inf), 1.1)
1491
+ assert_almost_equal(norm(A, -inf), 0.6)
1492
+ assert_almost_equal(norm(A, 1), 1.0)
1493
+ assert_almost_equal(norm(A, -1), 0.4)
1494
+ assert_almost_equal(norm(A, 2), 0.88722940323461277)
1495
+ assert_almost_equal(norm(A, -2), 0.19456584790481812)
1496
+
1497
+ def test_bad_args(self):
1498
+ # Check that bad arguments raise the appropriate exceptions.
1499
+
1500
+ A = self.array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
1501
+ B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
1502
+
1503
+ # Using `axis=<integer>` or passing in a 1-D array implies vector
1504
+ # norms are being computed, so also using `ord='fro'`
1505
+ # or `ord='nuc'` or any other string raises a ValueError.
1506
+ assert_raises(ValueError, norm, A, 'fro', 0)
1507
+ assert_raises(ValueError, norm, A, 'nuc', 0)
1508
+ assert_raises(ValueError, norm, [3, 4], 'fro', None)
1509
+ assert_raises(ValueError, norm, [3, 4], 'nuc', None)
1510
+ assert_raises(ValueError, norm, [3, 4], 'test', None)
1511
+
1512
+ # Similarly, norm should raise an exception when ord is any finite
1513
+ # number other than 1, 2, -1 or -2 when computing matrix norms.
1514
+ for order in [0, 3]:
1515
+ assert_raises(ValueError, norm, A, order, None)
1516
+ assert_raises(ValueError, norm, A, order, (0, 1))
1517
+ assert_raises(ValueError, norm, B, order, (1, 2))
1518
+
1519
+ # Invalid axis
1520
+ assert_raises(np.AxisError, norm, B, None, 3)
1521
+ assert_raises(np.AxisError, norm, B, None, (2, 3))
1522
+ assert_raises(ValueError, norm, B, None, (0, 1, 2))
1523
+
1524
+
1525
+ class _TestNorm(_TestNorm2D, _TestNormGeneral):
1526
+ pass
1527
+
1528
+
1529
+ class TestNorm_NonSystematic:
1530
+
1531
+ def test_longdouble_norm(self):
1532
+ # Non-regression test: p-norm of longdouble would previously raise
1533
+ # UnboundLocalError.
1534
+ x = np.arange(10, dtype=np.longdouble)
1535
+ old_assert_almost_equal(norm(x, ord=3), 12.65, decimal=2)
1536
+
1537
+ def test_intmin(self):
1538
+ # Non-regression test: p-norm of signed integer would previously do
1539
+ # float cast and abs in the wrong order.
1540
+ x = np.array([-2 ** 31], dtype=np.int32)
1541
+ old_assert_almost_equal(norm(x, ord=3), 2 ** 31, decimal=5)
1542
+
1543
+ def test_complex_high_ord(self):
1544
+ # gh-4156
1545
+ d = np.empty((2,), dtype=np.clongdouble)
1546
+ d[0] = 6 + 7j
1547
+ d[1] = -6 + 7j
1548
+ res = 11.615898132184
1549
+ old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=10)
1550
+ d = d.astype(np.complex128)
1551
+ old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=9)
1552
+ d = d.astype(np.complex64)
1553
+ old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5)
1554
+
1555
+
1556
+ # Separate definitions so we can use them for matrix tests.
1557
+ class _TestNormDoubleBase(_TestNormBase):
1558
+ dt = np.double
1559
+ dec = 12
1560
+
1561
+
1562
+ class _TestNormSingleBase(_TestNormBase):
1563
+ dt = np.float32
1564
+ dec = 6
1565
+
1566
+
1567
+ class _TestNormInt64Base(_TestNormBase):
1568
+ dt = np.int64
1569
+ dec = 12
1570
+
1571
+
1572
+ class TestNormDouble(_TestNorm, _TestNormDoubleBase):
1573
+ pass
1574
+
1575
+
1576
+ class TestNormSingle(_TestNorm, _TestNormSingleBase):
1577
+ pass
1578
+
1579
+
1580
+ class TestNormInt64(_TestNorm, _TestNormInt64Base):
1581
+ pass
1582
+
1583
+
1584
+ class TestMatrixRank:
1585
+
1586
+ def test_matrix_rank(self):
1587
+ # Full rank matrix
1588
+ assert_equal(4, matrix_rank(np.eye(4)))
1589
+ # rank deficient matrix
1590
+ I = np.eye(4)
1591
+ I[-1, -1] = 0.
1592
+ assert_equal(matrix_rank(I), 3)
1593
+ # All zeros - zero rank
1594
+ assert_equal(matrix_rank(np.zeros((4, 4))), 0)
1595
+ # 1 dimension - rank 1 unless all 0
1596
+ assert_equal(matrix_rank([1, 0, 0, 0]), 1)
1597
+ assert_equal(matrix_rank(np.zeros((4,))), 0)
1598
+ # accepts array-like
1599
+ assert_equal(matrix_rank([1]), 1)
1600
+ # greater than 2 dimensions treated as stacked matrices
1601
+ ms = np.array([I, np.eye(4), np.zeros((4,4))])
1602
+ assert_equal(matrix_rank(ms), np.array([3, 4, 0]))
1603
+ # works on scalar
1604
+ assert_equal(matrix_rank(1), 1)
1605
+
1606
+ def test_symmetric_rank(self):
1607
+ assert_equal(4, matrix_rank(np.eye(4), hermitian=True))
1608
+ assert_equal(1, matrix_rank(np.ones((4, 4)), hermitian=True))
1609
+ assert_equal(0, matrix_rank(np.zeros((4, 4)), hermitian=True))
1610
+ # rank deficient matrix
1611
+ I = np.eye(4)
1612
+ I[-1, -1] = 0.
1613
+ assert_equal(3, matrix_rank(I, hermitian=True))
1614
+ # manually supplied tolerance
1615
+ I[-1, -1] = 1e-8
1616
+ assert_equal(4, matrix_rank(I, hermitian=True, tol=0.99e-8))
1617
+ assert_equal(3, matrix_rank(I, hermitian=True, tol=1.01e-8))
1618
+
1619
+
1620
+ def test_reduced_rank():
1621
+ # Test matrices with reduced rank
1622
+ rng = np.random.RandomState(20120714)
1623
+ for i in range(100):
1624
+ # Make a rank deficient matrix
1625
+ X = rng.normal(size=(40, 10))
1626
+ X[:, 0] = X[:, 1] + X[:, 2]
1627
+ # Assert that matrix_rank detected deficiency
1628
+ assert_equal(matrix_rank(X), 9)
1629
+ X[:, 3] = X[:, 4] + X[:, 5]
1630
+ assert_equal(matrix_rank(X), 8)
1631
+
1632
+
1633
+ class TestQR:
1634
+ # Define the array class here, so run this on matrices elsewhere.
1635
+ array = np.array
1636
+
1637
+ def check_qr(self, a):
1638
+ # This test expects the argument `a` to be an ndarray or
1639
+ # a subclass of an ndarray of inexact type.
1640
+ a_type = type(a)
1641
+ a_dtype = a.dtype
1642
+ m, n = a.shape
1643
+ k = min(m, n)
1644
+
1645
+ # mode == 'complete'
1646
+ res = linalg.qr(a, mode='complete')
1647
+ Q, R = res.Q, res.R
1648
+ assert_(Q.dtype == a_dtype)
1649
+ assert_(R.dtype == a_dtype)
1650
+ assert_(isinstance(Q, a_type))
1651
+ assert_(isinstance(R, a_type))
1652
+ assert_(Q.shape == (m, m))
1653
+ assert_(R.shape == (m, n))
1654
+ assert_almost_equal(dot(Q, R), a)
1655
+ assert_almost_equal(dot(Q.T.conj(), Q), np.eye(m))
1656
+ assert_almost_equal(np.triu(R), R)
1657
+
1658
+ # mode == 'reduced'
1659
+ q1, r1 = linalg.qr(a, mode='reduced')
1660
+ assert_(q1.dtype == a_dtype)
1661
+ assert_(r1.dtype == a_dtype)
1662
+ assert_(isinstance(q1, a_type))
1663
+ assert_(isinstance(r1, a_type))
1664
+ assert_(q1.shape == (m, k))
1665
+ assert_(r1.shape == (k, n))
1666
+ assert_almost_equal(dot(q1, r1), a)
1667
+ assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k))
1668
+ assert_almost_equal(np.triu(r1), r1)
1669
+
1670
+ # mode == 'r'
1671
+ r2 = linalg.qr(a, mode='r')
1672
+ assert_(r2.dtype == a_dtype)
1673
+ assert_(isinstance(r2, a_type))
1674
+ assert_almost_equal(r2, r1)
1675
+
1676
+
1677
+ @pytest.mark.parametrize(["m", "n"], [
1678
+ (3, 0),
1679
+ (0, 3),
1680
+ (0, 0)
1681
+ ])
1682
+ def test_qr_empty(self, m, n):
1683
+ k = min(m, n)
1684
+ a = np.empty((m, n))
1685
+
1686
+ self.check_qr(a)
1687
+
1688
+ h, tau = np.linalg.qr(a, mode='raw')
1689
+ assert_equal(h.dtype, np.double)
1690
+ assert_equal(tau.dtype, np.double)
1691
+ assert_equal(h.shape, (n, m))
1692
+ assert_equal(tau.shape, (k,))
1693
+
1694
+ def test_mode_raw(self):
1695
+ # The factorization is not unique and varies between libraries,
1696
+ # so it is not possible to check against known values. Functional
1697
+ # testing is a possibility, but awaits the exposure of more
1698
+ # of the functions in lapack_lite. Consequently, this test is
1699
+ # very limited in scope. Note that the results are in FORTRAN
1700
+ # order, hence the h arrays are transposed.
1701
+ a = self.array([[1, 2], [3, 4], [5, 6]], dtype=np.double)
1702
+
1703
+ # Test double
1704
+ h, tau = linalg.qr(a, mode='raw')
1705
+ assert_(h.dtype == np.double)
1706
+ assert_(tau.dtype == np.double)
1707
+ assert_(h.shape == (2, 3))
1708
+ assert_(tau.shape == (2,))
1709
+
1710
+ h, tau = linalg.qr(a.T, mode='raw')
1711
+ assert_(h.dtype == np.double)
1712
+ assert_(tau.dtype == np.double)
1713
+ assert_(h.shape == (3, 2))
1714
+ assert_(tau.shape == (2,))
1715
+
1716
+ def test_mode_all_but_economic(self):
1717
+ a = self.array([[1, 2], [3, 4]])
1718
+ b = self.array([[1, 2], [3, 4], [5, 6]])
1719
+ for dt in "fd":
1720
+ m1 = a.astype(dt)
1721
+ m2 = b.astype(dt)
1722
+ self.check_qr(m1)
1723
+ self.check_qr(m2)
1724
+ self.check_qr(m2.T)
1725
+
1726
+ for dt in "fd":
1727
+ m1 = 1 + 1j * a.astype(dt)
1728
+ m2 = 1 + 1j * b.astype(dt)
1729
+ self.check_qr(m1)
1730
+ self.check_qr(m2)
1731
+ self.check_qr(m2.T)
1732
+
1733
+ def check_qr_stacked(self, a):
1734
+ # This test expects the argument `a` to be an ndarray or
1735
+ # a subclass of an ndarray of inexact type.
1736
+ a_type = type(a)
1737
+ a_dtype = a.dtype
1738
+ m, n = a.shape[-2:]
1739
+ k = min(m, n)
1740
+
1741
+ # mode == 'complete'
1742
+ q, r = linalg.qr(a, mode='complete')
1743
+ assert_(q.dtype == a_dtype)
1744
+ assert_(r.dtype == a_dtype)
1745
+ assert_(isinstance(q, a_type))
1746
+ assert_(isinstance(r, a_type))
1747
+ assert_(q.shape[-2:] == (m, m))
1748
+ assert_(r.shape[-2:] == (m, n))
1749
+ assert_almost_equal(matmul(q, r), a)
1750
+ I_mat = np.identity(q.shape[-1])
1751
+ stack_I_mat = np.broadcast_to(I_mat,
1752
+ q.shape[:-2] + (q.shape[-1],)*2)
1753
+ assert_almost_equal(matmul(swapaxes(q, -1, -2).conj(), q), stack_I_mat)
1754
+ assert_almost_equal(np.triu(r[..., :, :]), r)
1755
+
1756
+ # mode == 'reduced'
1757
+ q1, r1 = linalg.qr(a, mode='reduced')
1758
+ assert_(q1.dtype == a_dtype)
1759
+ assert_(r1.dtype == a_dtype)
1760
+ assert_(isinstance(q1, a_type))
1761
+ assert_(isinstance(r1, a_type))
1762
+ assert_(q1.shape[-2:] == (m, k))
1763
+ assert_(r1.shape[-2:] == (k, n))
1764
+ assert_almost_equal(matmul(q1, r1), a)
1765
+ I_mat = np.identity(q1.shape[-1])
1766
+ stack_I_mat = np.broadcast_to(I_mat,
1767
+ q1.shape[:-2] + (q1.shape[-1],)*2)
1768
+ assert_almost_equal(matmul(swapaxes(q1, -1, -2).conj(), q1),
1769
+ stack_I_mat)
1770
+ assert_almost_equal(np.triu(r1[..., :, :]), r1)
1771
+
1772
+ # mode == 'r'
1773
+ r2 = linalg.qr(a, mode='r')
1774
+ assert_(r2.dtype == a_dtype)
1775
+ assert_(isinstance(r2, a_type))
1776
+ assert_almost_equal(r2, r1)
1777
+
1778
+ @pytest.mark.parametrize("size", [
1779
+ (3, 4), (4, 3), (4, 4),
1780
+ (3, 0), (0, 3)])
1781
+ @pytest.mark.parametrize("outer_size", [
1782
+ (2, 2), (2,), (2, 3, 4)])
1783
+ @pytest.mark.parametrize("dt", [
1784
+ np.single, np.double,
1785
+ np.csingle, np.cdouble])
1786
+ def test_stacked_inputs(self, outer_size, size, dt):
1787
+
1788
+ A = np.random.normal(size=outer_size + size).astype(dt)
1789
+ B = np.random.normal(size=outer_size + size).astype(dt)
1790
+ self.check_qr_stacked(A)
1791
+ self.check_qr_stacked(A + 1.j*B)
1792
+
1793
+
1794
+ class TestCholesky:
1795
+ # TODO: are there no other tests for cholesky?
1796
+
1797
+ @pytest.mark.parametrize(
1798
+ 'shape', [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
1799
+ )
1800
+ @pytest.mark.parametrize(
1801
+ 'dtype', (np.float32, np.float64, np.complex64, np.complex128)
1802
+ )
1803
+ def test_basic_property(self, shape, dtype):
1804
+ # Check A = L L^H
1805
+ np.random.seed(1)
1806
+ a = np.random.randn(*shape)
1807
+ if np.issubdtype(dtype, np.complexfloating):
1808
+ a = a + 1j*np.random.randn(*shape)
1809
+
1810
+ t = list(range(len(shape)))
1811
+ t[-2:] = -1, -2
1812
+
1813
+ a = np.matmul(a.transpose(t).conj(), a)
1814
+ a = np.asarray(a, dtype=dtype)
1815
+
1816
+ c = np.linalg.cholesky(a)
1817
+
1818
+ b = np.matmul(c, c.transpose(t).conj())
1819
+ with np._no_nep50_warning():
1820
+ atol = 500 * a.shape[0] * np.finfo(dtype).eps
1821
+ assert_allclose(b, a, atol=atol, err_msg=f'{shape} {dtype}\n{a}\n{c}')
1822
+
1823
+ def test_0_size(self):
1824
+ class ArraySubclass(np.ndarray):
1825
+ pass
1826
+ a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
1827
+ res = linalg.cholesky(a)
1828
+ assert_equal(a.shape, res.shape)
1829
+ assert_(res.dtype.type is np.float64)
1830
+ # for documentation purpose:
1831
+ assert_(isinstance(res, np.ndarray))
1832
+
1833
+ a = np.zeros((1, 0, 0), dtype=np.complex64).view(ArraySubclass)
1834
+ res = linalg.cholesky(a)
1835
+ assert_equal(a.shape, res.shape)
1836
+ assert_(res.dtype.type is np.complex64)
1837
+ assert_(isinstance(res, np.ndarray))
1838
+
1839
+
1840
+ def test_byteorder_check():
1841
+ # Byte order check should pass for native order
1842
+ if sys.byteorder == 'little':
1843
+ native = '<'
1844
+ else:
1845
+ native = '>'
1846
+
1847
+ for dtt in (np.float32, np.float64):
1848
+ arr = np.eye(4, dtype=dtt)
1849
+ n_arr = arr.newbyteorder(native)
1850
+ sw_arr = arr.newbyteorder('S').byteswap()
1851
+ assert_equal(arr.dtype.byteorder, '=')
1852
+ for routine in (linalg.inv, linalg.det, linalg.pinv):
1853
+ # Normal call
1854
+ res = routine(arr)
1855
+ # Native but not '='
1856
+ assert_array_equal(res, routine(n_arr))
1857
+ # Swapped
1858
+ assert_array_equal(res, routine(sw_arr))
1859
+
1860
+
1861
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1862
+ def test_generalized_raise_multiloop():
1863
+ # It should raise an error even if the error doesn't occur in the
1864
+ # last iteration of the ufunc inner loop
1865
+
1866
+ invertible = np.array([[1, 2], [3, 4]])
1867
+ non_invertible = np.array([[1, 1], [1, 1]])
1868
+
1869
+ x = np.zeros([4, 4, 2, 2])[1::2]
1870
+ x[...] = invertible
1871
+ x[0, 0] = non_invertible
1872
+
1873
+ assert_raises(np.linalg.LinAlgError, np.linalg.inv, x)
1874
+
1875
+
1876
+ def test_xerbla_override():
1877
+ # Check that our xerbla has been successfully linked in. If it is not,
1878
+ # the default xerbla routine is called, which prints a message to stdout
1879
+ # and may, or may not, abort the process depending on the LAPACK package.
1880
+
1881
+ XERBLA_OK = 255
1882
+
1883
+ try:
1884
+ pid = os.fork()
1885
+ except (OSError, AttributeError):
1886
+ # fork failed, or not running on POSIX
1887
+ pytest.skip("Not POSIX or fork failed.")
1888
+
1889
+ if pid == 0:
1890
+ # child; close i/o file handles
1891
+ os.close(1)
1892
+ os.close(0)
1893
+ # Avoid producing core files.
1894
+ import resource
1895
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1896
+ # These calls may abort.
1897
+ try:
1898
+ np.linalg.lapack_lite.xerbla()
1899
+ except ValueError:
1900
+ pass
1901
+ except Exception:
1902
+ os._exit(os.EX_CONFIG)
1903
+
1904
+ try:
1905
+ a = np.array([[1.]])
1906
+ np.linalg.lapack_lite.dorgqr(
1907
+ 1, 1, 1, a,
1908
+ 0, # <- invalid value
1909
+ a, a, 0, 0)
1910
+ except ValueError as e:
1911
+ if "DORGQR parameter number 5" in str(e):
1912
+ # success, reuse error code to mark success as
1913
+ # FORTRAN STOP returns as success.
1914
+ os._exit(XERBLA_OK)
1915
+
1916
+ # Did not abort, but our xerbla was not linked in.
1917
+ os._exit(os.EX_CONFIG)
1918
+ else:
1919
+ # parent
1920
+ pid, status = os.wait()
1921
+ if os.WEXITSTATUS(status) != XERBLA_OK:
1922
+ pytest.skip('Numpy xerbla not linked in.')
1923
+
1924
+
1925
+ @pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
1926
+ @pytest.mark.slow
1927
+ def test_sdot_bug_8577():
1928
+ # Regression test that loading certain other libraries does not
1929
+ # result to wrong results in float32 linear algebra.
1930
+ #
1931
+ # There's a bug gh-8577 on OSX that can trigger this, and perhaps
1932
+ # there are also other situations in which it occurs.
1933
+ #
1934
+ # Do the check in a separate process.
1935
+
1936
+ bad_libs = ['PyQt5.QtWidgets', 'IPython']
1937
+
1938
+ template = textwrap.dedent("""
1939
+ import sys
1940
+ {before}
1941
+ try:
1942
+ import {bad_lib}
1943
+ except ImportError:
1944
+ sys.exit(0)
1945
+ {after}
1946
+ x = np.ones(2, dtype=np.float32)
1947
+ sys.exit(0 if np.allclose(x.dot(x), 2.0) else 1)
1948
+ """)
1949
+
1950
+ for bad_lib in bad_libs:
1951
+ code = template.format(before="import numpy as np", after="",
1952
+ bad_lib=bad_lib)
1953
+ subprocess.check_call([sys.executable, "-c", code])
1954
+
1955
+ # Swapped import order
1956
+ code = template.format(after="import numpy as np", before="",
1957
+ bad_lib=bad_lib)
1958
+ subprocess.check_call([sys.executable, "-c", code])
1959
+
1960
+
1961
+ class TestMultiDot:
1962
+
1963
+ def test_basic_function_with_three_arguments(self):
1964
+ # multi_dot with three arguments uses a fast hand coded algorithm to
1965
+ # determine the optimal order. Therefore test it separately.
1966
+ A = np.random.random((6, 2))
1967
+ B = np.random.random((2, 6))
1968
+ C = np.random.random((6, 2))
1969
+
1970
+ assert_almost_equal(multi_dot([A, B, C]), A.dot(B).dot(C))
1971
+ assert_almost_equal(multi_dot([A, B, C]), np.dot(A, np.dot(B, C)))
1972
+
1973
+ def test_basic_function_with_two_arguments(self):
1974
+ # separate code path with two arguments
1975
+ A = np.random.random((6, 2))
1976
+ B = np.random.random((2, 6))
1977
+
1978
+ assert_almost_equal(multi_dot([A, B]), A.dot(B))
1979
+ assert_almost_equal(multi_dot([A, B]), np.dot(A, B))
1980
+
1981
+ def test_basic_function_with_dynamic_programming_optimization(self):
1982
+ # multi_dot with four or more arguments uses the dynamic programming
1983
+ # optimization and therefore deserve a separate
1984
+ A = np.random.random((6, 2))
1985
+ B = np.random.random((2, 6))
1986
+ C = np.random.random((6, 2))
1987
+ D = np.random.random((2, 1))
1988
+ assert_almost_equal(multi_dot([A, B, C, D]), A.dot(B).dot(C).dot(D))
1989
+
1990
+ def test_vector_as_first_argument(self):
1991
+ # The first argument can be 1-D
1992
+ A1d = np.random.random(2) # 1-D
1993
+ B = np.random.random((2, 6))
1994
+ C = np.random.random((6, 2))
1995
+ D = np.random.random((2, 2))
1996
+
1997
+ # the result should be 1-D
1998
+ assert_equal(multi_dot([A1d, B, C, D]).shape, (2,))
1999
+
2000
+ def test_vector_as_last_argument(self):
2001
+ # The last argument can be 1-D
2002
+ A = np.random.random((6, 2))
2003
+ B = np.random.random((2, 6))
2004
+ C = np.random.random((6, 2))
2005
+ D1d = np.random.random(2) # 1-D
2006
+
2007
+ # the result should be 1-D
2008
+ assert_equal(multi_dot([A, B, C, D1d]).shape, (6,))
2009
+
2010
+ def test_vector_as_first_and_last_argument(self):
2011
+ # The first and last arguments can be 1-D
2012
+ A1d = np.random.random(2) # 1-D
2013
+ B = np.random.random((2, 6))
2014
+ C = np.random.random((6, 2))
2015
+ D1d = np.random.random(2) # 1-D
2016
+
2017
+ # the result should be a scalar
2018
+ assert_equal(multi_dot([A1d, B, C, D1d]).shape, ())
2019
+
2020
+ def test_three_arguments_and_out(self):
2021
+ # multi_dot with three arguments uses a fast hand coded algorithm to
2022
+ # determine the optimal order. Therefore test it separately.
2023
+ A = np.random.random((6, 2))
2024
+ B = np.random.random((2, 6))
2025
+ C = np.random.random((6, 2))
2026
+
2027
+ out = np.zeros((6, 2))
2028
+ ret = multi_dot([A, B, C], out=out)
2029
+ assert out is ret
2030
+ assert_almost_equal(out, A.dot(B).dot(C))
2031
+ assert_almost_equal(out, np.dot(A, np.dot(B, C)))
2032
+
2033
+ def test_two_arguments_and_out(self):
2034
+ # separate code path with two arguments
2035
+ A = np.random.random((6, 2))
2036
+ B = np.random.random((2, 6))
2037
+ out = np.zeros((6, 6))
2038
+ ret = multi_dot([A, B], out=out)
2039
+ assert out is ret
2040
+ assert_almost_equal(out, A.dot(B))
2041
+ assert_almost_equal(out, np.dot(A, B))
2042
+
2043
+ def test_dynamic_programming_optimization_and_out(self):
2044
+ # multi_dot with four or more arguments uses the dynamic programming
2045
+ # optimization and therefore deserve a separate test
2046
+ A = np.random.random((6, 2))
2047
+ B = np.random.random((2, 6))
2048
+ C = np.random.random((6, 2))
2049
+ D = np.random.random((2, 1))
2050
+ out = np.zeros((6, 1))
2051
+ ret = multi_dot([A, B, C, D], out=out)
2052
+ assert out is ret
2053
+ assert_almost_equal(out, A.dot(B).dot(C).dot(D))
2054
+
2055
+ def test_dynamic_programming_logic(self):
2056
+ # Test for the dynamic programming part
2057
+ # This test is directly taken from Cormen page 376.
2058
+ arrays = [np.random.random((30, 35)),
2059
+ np.random.random((35, 15)),
2060
+ np.random.random((15, 5)),
2061
+ np.random.random((5, 10)),
2062
+ np.random.random((10, 20)),
2063
+ np.random.random((20, 25))]
2064
+ m_expected = np.array([[0., 15750., 7875., 9375., 11875., 15125.],
2065
+ [0., 0., 2625., 4375., 7125., 10500.],
2066
+ [0., 0., 0., 750., 2500., 5375.],
2067
+ [0., 0., 0., 0., 1000., 3500.],
2068
+ [0., 0., 0., 0., 0., 5000.],
2069
+ [0., 0., 0., 0., 0., 0.]])
2070
+ s_expected = np.array([[0, 1, 1, 3, 3, 3],
2071
+ [0, 0, 2, 3, 3, 3],
2072
+ [0, 0, 0, 3, 3, 3],
2073
+ [0, 0, 0, 0, 4, 5],
2074
+ [0, 0, 0, 0, 0, 5],
2075
+ [0, 0, 0, 0, 0, 0]], dtype=int)
2076
+ s_expected -= 1 # Cormen uses 1-based index, python does not.
2077
+
2078
+ s, m = _multi_dot_matrix_chain_order(arrays, return_costs=True)
2079
+
2080
+ # Only the upper triangular part (without the diagonal) is interesting.
2081
+ assert_almost_equal(np.triu(s[:-1, 1:]),
2082
+ np.triu(s_expected[:-1, 1:]))
2083
+ assert_almost_equal(np.triu(m), np.triu(m_expected))
2084
+
2085
+ def test_too_few_input_arrays(self):
2086
+ assert_raises(ValueError, multi_dot, [])
2087
+ assert_raises(ValueError, multi_dot, [np.random.random((3, 3))])
2088
+
2089
+
2090
+ class TestTensorinv:
2091
+
2092
+ @pytest.mark.parametrize("arr, ind", [
2093
+ (np.ones((4, 6, 8, 2)), 2),
2094
+ (np.ones((3, 3, 2)), 1),
2095
+ ])
2096
+ def test_non_square_handling(self, arr, ind):
2097
+ with assert_raises(LinAlgError):
2098
+ linalg.tensorinv(arr, ind=ind)
2099
+
2100
+ @pytest.mark.parametrize("shape, ind", [
2101
+ # examples from docstring
2102
+ ((4, 6, 8, 3), 2),
2103
+ ((24, 8, 3), 1),
2104
+ ])
2105
+ def test_tensorinv_shape(self, shape, ind):
2106
+ a = np.eye(24)
2107
+ a.shape = shape
2108
+ ainv = linalg.tensorinv(a=a, ind=ind)
2109
+ expected = a.shape[ind:] + a.shape[:ind]
2110
+ actual = ainv.shape
2111
+ assert_equal(actual, expected)
2112
+
2113
+ @pytest.mark.parametrize("ind", [
2114
+ 0, -2,
2115
+ ])
2116
+ def test_tensorinv_ind_limit(self, ind):
2117
+ a = np.eye(24)
2118
+ a.shape = (4, 6, 8, 3)
2119
+ with assert_raises(ValueError):
2120
+ linalg.tensorinv(a=a, ind=ind)
2121
+
2122
+ def test_tensorinv_result(self):
2123
+ # mimic a docstring example
2124
+ a = np.eye(24)
2125
+ a.shape = (24, 8, 3)
2126
+ ainv = linalg.tensorinv(a, ind=1)
2127
+ b = np.ones(24)
2128
+ assert_allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
2129
+
2130
+
2131
+ class TestTensorsolve:
2132
+
2133
+ @pytest.mark.parametrize("a, axes", [
2134
+ (np.ones((4, 6, 8, 2)), None),
2135
+ (np.ones((3, 3, 2)), (0, 2)),
2136
+ ])
2137
+ def test_non_square_handling(self, a, axes):
2138
+ with assert_raises(LinAlgError):
2139
+ b = np.ones(a.shape[:2])
2140
+ linalg.tensorsolve(a, b, axes=axes)
2141
+
2142
+ @pytest.mark.parametrize("shape",
2143
+ [(2, 3, 6), (3, 4, 4, 3), (0, 3, 3, 0)],
2144
+ )
2145
+ def test_tensorsolve_result(self, shape):
2146
+ a = np.random.randn(*shape)
2147
+ b = np.ones(a.shape[:2])
2148
+ x = np.linalg.tensorsolve(a, b)
2149
+ assert_allclose(np.tensordot(a, x, axes=len(x.shape)), b)
2150
+
2151
+
2152
+ def test_unsupported_commontype():
2153
+ # linalg gracefully handles unsupported type
2154
+ arr = np.array([[1, -2], [2, 5]], dtype='float16')
2155
+ with assert_raises_regex(TypeError, "unsupported in linalg"):
2156
+ linalg.cholesky(arr)
2157
+
2158
+
2159
+ #@pytest.mark.slow
2160
+ #@pytest.mark.xfail(not HAS_LAPACK64, run=False,
2161
+ # reason="Numpy not compiled with 64-bit BLAS/LAPACK")
2162
+ #@requires_memory(free_bytes=16e9)
2163
+ @pytest.mark.skip(reason="Bad memory reports lead to OOM in ci testing")
2164
+ def test_blas64_dot():
2165
+ n = 2**32
2166
+ a = np.zeros([1, n], dtype=np.float32)
2167
+ b = np.ones([1, 1], dtype=np.float32)
2168
+ a[0,-1] = 1
2169
+ c = np.dot(b, a)
2170
+ assert_equal(c[0,-1], 1)
2171
+
2172
+
2173
+ @pytest.mark.xfail(not HAS_LAPACK64,
2174
+ reason="Numpy not compiled with 64-bit BLAS/LAPACK")
2175
+ def test_blas64_geqrf_lwork_smoketest():
2176
+ # Smoke test LAPACK geqrf lwork call with 64-bit integers
2177
+ dtype = np.float64
2178
+ lapack_routine = np.linalg.lapack_lite.dgeqrf
2179
+
2180
+ m = 2**32 + 1
2181
+ n = 2**32 + 1
2182
+ lda = m
2183
+
2184
+ # Dummy arrays, not referenced by the lapack routine, so don't
2185
+ # need to be of the right size
2186
+ a = np.zeros([1, 1], dtype=dtype)
2187
+ work = np.zeros([1], dtype=dtype)
2188
+ tau = np.zeros([1], dtype=dtype)
2189
+
2190
+ # Size query
2191
+ results = lapack_routine(m, n, a, lda, tau, work, -1, 0)
2192
+ assert_equal(results['info'], 0)
2193
+ assert_equal(results['m'], m)
2194
+ assert_equal(results['n'], m)
2195
+
2196
+ # Should result to an integer of a reasonable size
2197
+ lwork = int(work.item())
2198
+ assert_(2**32 < lwork < 2**42)
venv/lib/python3.10/site-packages/numpy/linalg/tests/test_regression.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test functions for linalg module
2
+ """
3
+ import warnings
4
+
5
+ import numpy as np
6
+ from numpy import linalg, arange, float64, array, dot, transpose
7
+ from numpy.testing import (
8
+ assert_, assert_raises, assert_equal, assert_array_equal,
9
+ assert_array_almost_equal, assert_array_less
10
+ )
11
+
12
+
13
+ class TestRegression:
14
+
15
+ def test_eig_build(self):
16
+ # Ticket #652
17
+ rva = array([1.03221168e+02 + 0.j,
18
+ -1.91843603e+01 + 0.j,
19
+ -6.04004526e-01 + 15.84422474j,
20
+ -6.04004526e-01 - 15.84422474j,
21
+ -1.13692929e+01 + 0.j,
22
+ -6.57612485e-01 + 10.41755503j,
23
+ -6.57612485e-01 - 10.41755503j,
24
+ 1.82126812e+01 + 0.j,
25
+ 1.06011014e+01 + 0.j,
26
+ 7.80732773e+00 + 0.j,
27
+ -7.65390898e-01 + 0.j,
28
+ 1.51971555e-15 + 0.j,
29
+ -1.51308713e-15 + 0.j])
30
+ a = arange(13 * 13, dtype=float64)
31
+ a.shape = (13, 13)
32
+ a = a % 17
33
+ va, ve = linalg.eig(a)
34
+ va.sort()
35
+ rva.sort()
36
+ assert_array_almost_equal(va, rva)
37
+
38
+ def test_eigh_build(self):
39
+ # Ticket 662.
40
+ rvals = [68.60568999, 89.57756725, 106.67185574]
41
+
42
+ cov = array([[77.70273908, 3.51489954, 15.64602427],
43
+ [3.51489954, 88.97013878, -1.07431931],
44
+ [15.64602427, -1.07431931, 98.18223512]])
45
+
46
+ vals, vecs = linalg.eigh(cov)
47
+ assert_array_almost_equal(vals, rvals)
48
+
49
+ def test_svd_build(self):
50
+ # Ticket 627.
51
+ a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]])
52
+ m, n = a.shape
53
+ u, s, vh = linalg.svd(a)
54
+
55
+ b = dot(transpose(u[:, n:]), a)
56
+
57
+ assert_array_almost_equal(b, np.zeros((2, 2)))
58
+
59
+ def test_norm_vector_badarg(self):
60
+ # Regression for #786: Frobenius norm for vectors raises
61
+ # ValueError.
62
+ assert_raises(ValueError, linalg.norm, array([1., 2., 3.]), 'fro')
63
+
64
+ def test_lapack_endian(self):
65
+ # For bug #1482
66
+ a = array([[5.7998084, -2.1825367],
67
+ [-2.1825367, 9.85910595]], dtype='>f8')
68
+ b = array(a, dtype='<f8')
69
+
70
+ ap = linalg.cholesky(a)
71
+ bp = linalg.cholesky(b)
72
+ assert_array_equal(ap, bp)
73
+
74
+ def test_large_svd_32bit(self):
75
+ # See gh-4442, 64bit would require very large/slow matrices.
76
+ x = np.eye(1000, 66)
77
+ np.linalg.svd(x)
78
+
79
+ def test_svd_no_uv(self):
80
+ # gh-4733
81
+ for shape in (3, 4), (4, 4), (4, 3):
82
+ for t in float, complex:
83
+ a = np.ones(shape, dtype=t)
84
+ w = linalg.svd(a, compute_uv=False)
85
+ c = np.count_nonzero(np.absolute(w) > 0.5)
86
+ assert_equal(c, 1)
87
+ assert_equal(np.linalg.matrix_rank(a), 1)
88
+ assert_array_less(1, np.linalg.norm(a, ord=2))
89
+
90
+ def test_norm_object_array(self):
91
+ # gh-7575
92
+ testvector = np.array([np.array([0, 1]), 0, 0], dtype=object)
93
+
94
+ norm = linalg.norm(testvector)
95
+ assert_array_equal(norm, [0, 1])
96
+ assert_(norm.dtype == np.dtype('float64'))
97
+
98
+ norm = linalg.norm(testvector, ord=1)
99
+ assert_array_equal(norm, [0, 1])
100
+ assert_(norm.dtype != np.dtype('float64'))
101
+
102
+ norm = linalg.norm(testvector, ord=2)
103
+ assert_array_equal(norm, [0, 1])
104
+ assert_(norm.dtype == np.dtype('float64'))
105
+
106
+ assert_raises(ValueError, linalg.norm, testvector, ord='fro')
107
+ assert_raises(ValueError, linalg.norm, testvector, ord='nuc')
108
+ assert_raises(ValueError, linalg.norm, testvector, ord=np.inf)
109
+ assert_raises(ValueError, linalg.norm, testvector, ord=-np.inf)
110
+ assert_raises(ValueError, linalg.norm, testvector, ord=0)
111
+ assert_raises(ValueError, linalg.norm, testvector, ord=-1)
112
+ assert_raises(ValueError, linalg.norm, testvector, ord=-2)
113
+
114
+ testmatrix = np.array([[np.array([0, 1]), 0, 0],
115
+ [0, 0, 0]], dtype=object)
116
+
117
+ norm = linalg.norm(testmatrix)
118
+ assert_array_equal(norm, [0, 1])
119
+ assert_(norm.dtype == np.dtype('float64'))
120
+
121
+ norm = linalg.norm(testmatrix, ord='fro')
122
+ assert_array_equal(norm, [0, 1])
123
+ assert_(norm.dtype == np.dtype('float64'))
124
+
125
+ assert_raises(TypeError, linalg.norm, testmatrix, ord='nuc')
126
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=np.inf)
127
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=-np.inf)
128
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=0)
129
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=1)
130
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=-1)
131
+ assert_raises(TypeError, linalg.norm, testmatrix, ord=2)
132
+ assert_raises(TypeError, linalg.norm, testmatrix, ord=-2)
133
+ assert_raises(ValueError, linalg.norm, testmatrix, ord=3)
134
+
135
+ def test_lstsq_complex_larger_rhs(self):
136
+ # gh-9891
137
+ size = 20
138
+ n_rhs = 70
139
+ G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
140
+ u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
141
+ b = G.dot(u)
142
+ # This should work without segmentation fault.
143
+ u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
144
+ # check results just in case
145
+ assert_array_almost_equal(u_lstsq, u)
venv/lib/python3.10/site-packages/numpy/ma/LICENSE ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ * Copyright (c) 2006, University of Georgia and Pierre G.F. Gerard-Marchant
2
+ * All rights reserved.
3
+ * Redistribution and use in source and binary forms, with or without
4
+ * modification, are permitted provided that the following conditions are met:
5
+ *
6
+ * * Redistributions of source code must retain the above copyright
7
+ * notice, this list of conditions and the following disclaimer.
8
+ * * Redistributions in binary form must reproduce the above copyright
9
+ * notice, this list of conditions and the following disclaimer in the
10
+ * documentation and/or other materials provided with the distribution.
11
+ * * Neither the name of the University of Georgia nor the
12
+ * names of its contributors may be used to endorse or promote products
13
+ * derived from this software without specific prior written permission.
14
+ *
15
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
16
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
19
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
venv/lib/python3.10/site-packages/numpy/ma/README.rst ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ==================================
2
+ A Guide to Masked Arrays in NumPy
3
+ ==================================
4
+
5
+ .. Contents::
6
+
7
+ See http://www.scipy.org/scipy/numpy/wiki/MaskedArray (dead link)
8
+ for updates of this document.
9
+
10
+
11
+ History
12
+ -------
13
+
14
+ As a regular user of MaskedArray, I (Pierre G.F. Gerard-Marchant) became
15
+ increasingly frustrated with the subclassing of masked arrays (even if
16
+ I can only blame my inexperience). I needed to develop a class of arrays
17
+ that could store some additional information along with numerical values,
18
+ while keeping the possibility for missing data (picture storing a series
19
+ of dates along with measurements, what would later become the `TimeSeries
20
+ Scikit <http://projects.scipy.org/scipy/scikits/wiki/TimeSeries>`__
21
+ (dead link).
22
+
23
+ I started to implement such a class, but then quickly realized that
24
+ any additional information disappeared when processing these subarrays
25
+ (for example, adding a constant value to a subarray would erase its
26
+ dates). I ended up writing the equivalent of *numpy.core.ma* for my
27
+ particular class, ufuncs included. Everything went fine until I needed to
28
+ subclass my new class, when more problems showed up: some attributes of
29
+ the new subclass were lost during processing. I identified the culprit as
30
+ MaskedArray, which returns masked ndarrays when I expected masked
31
+ arrays of my class. I was preparing myself to rewrite *numpy.core.ma*
32
+ when I forced myself to learn how to subclass ndarrays. As I became more
33
+ familiar with the *__new__* and *__array_finalize__* methods,
34
+ I started to wonder why masked arrays were objects, and not ndarrays,
35
+ and whether it wouldn't be more convenient for subclassing if they did
36
+ behave like regular ndarrays.
37
+
38
+ The new *maskedarray* is what I eventually come up with. The
39
+ main differences with the initial *numpy.core.ma* package are
40
+ that MaskedArray is now a subclass of *ndarray* and that the
41
+ *_data* section can now be any subclass of *ndarray*. Apart from a
42
+ couple of issues listed below, the behavior of the new MaskedArray
43
+ class reproduces the old one. Initially the *maskedarray*
44
+ implementation was marginally slower than *numpy.ma* in some areas,
45
+ but work is underway to speed it up; the expectation is that it can be
46
+ made substantially faster than the present *numpy.ma*.
47
+
48
+
49
+ Note that if the subclass has some special methods and
50
+ attributes, they are not propagated to the masked version:
51
+ this would require a modification of the *__getattribute__*
52
+ method (first trying *ndarray.__getattribute__*, then trying
53
+ *self._data.__getattribute__* if an exception is raised in the first
54
+ place), which really slows things down.
55
+
56
+ Main differences
57
+ ----------------
58
+
59
+ * The *_data* part of the masked array can be any subclass of ndarray (but not recarray, cf below).
60
+ * *fill_value* is now a property, not a function.
61
+ * in the majority of cases, the mask is forced to *nomask* when no value is actually masked. A notable exception is when a masked array (with no masked values) has just been unpickled.
62
+ * I got rid of the *share_mask* flag, I never understood its purpose.
63
+ * *put*, *putmask* and *take* now mimic the ndarray methods, to avoid unpleasant surprises. Moreover, *put* and *putmask* both update the mask when needed. * if *a* is a masked array, *bool(a)* raises a *ValueError*, as it does with ndarrays.
64
+ * in the same way, the comparison of two masked arrays is a masked array, not a boolean
65
+ * *filled(a)* returns an array of the same subclass as *a._data*, and no test is performed on whether it is contiguous or not.
66
+ * the mask is always printed, even if it's *nomask*, which makes things easy (for me at least) to remember that a masked array is used.
67
+ * *cumsum* works as if the *_data* array was filled with 0. The mask is preserved, but not updated.
68
+ * *cumprod* works as if the *_data* array was filled with 1. The mask is preserved, but not updated.
69
+
70
+ New features
71
+ ------------
72
+
73
+ This list is non-exhaustive...
74
+
75
+ * the *mr_* function mimics *r_* for masked arrays.
76
+ * the *anom* method returns the anomalies (deviations from the average)
77
+
78
+ Using the new package with numpy.core.ma
79
+ ----------------------------------------
80
+
81
+ I tried to make sure that the new package can understand old masked
82
+ arrays. Unfortunately, there's no upward compatibility.
83
+
84
+ For example:
85
+
86
+ >>> import numpy.core.ma as old_ma
87
+ >>> import maskedarray as new_ma
88
+ >>> x = old_ma.array([1,2,3,4,5], mask=[0,0,1,0,0])
89
+ >>> x
90
+ array(data =
91
+ [ 1 2 999999 4 5],
92
+ mask =
93
+ [False False True False False],
94
+ fill_value=999999)
95
+ >>> y = new_ma.array([1,2,3,4,5], mask=[0,0,1,0,0])
96
+ >>> y
97
+ array(data = [1 2 -- 4 5],
98
+ mask = [False False True False False],
99
+ fill_value=999999)
100
+ >>> x==y
101
+ array(data =
102
+ [True True True True True],
103
+ mask =
104
+ [False False True False False],
105
+ fill_value=?)
106
+ >>> old_ma.getmask(x) == new_ma.getmask(x)
107
+ array([True, True, True, True, True])
108
+ >>> old_ma.getmask(y) == new_ma.getmask(y)
109
+ array([True, True, False, True, True])
110
+ >>> old_ma.getmask(y)
111
+ False
112
+
113
+
114
+ Using maskedarray with matplotlib
115
+ ---------------------------------
116
+
117
+ Starting with matplotlib 0.91.2, the masked array importing will work with
118
+ the maskedarray branch) as well as with earlier versions.
119
+
120
+ By default matplotlib still uses numpy.ma, but there is an rcParams setting
121
+ that you can use to select maskedarray instead. In the matplotlibrc file
122
+ you will find::
123
+
124
+ #maskedarray : False # True to use external maskedarray module
125
+ # instead of numpy.ma; this is a temporary #
126
+ setting for testing maskedarray.
127
+
128
+
129
+ Uncomment and set to True to select maskedarray everywhere.
130
+ Alternatively, you can test a script with maskedarray by using a
131
+ command-line option, e.g.::
132
+
133
+ python simple_plot.py --maskedarray
134
+
135
+
136
+ Masked records
137
+ --------------
138
+
139
+ Like *numpy.core.ma*, the *ndarray*-based implementation
140
+ of MaskedArray is limited when working with records: you can
141
+ mask any record of the array, but not a field in a record. If you
142
+ need this feature, you may want to give the *mrecords* package
143
+ a try (available in the *maskedarray* directory in the scipy
144
+ sandbox). This module defines a new class, *MaskedRecord*. An
145
+ instance of this class accepts a *recarray* as data, and uses two
146
+ masks: the *fieldmask* has as many entries as records in the array,
147
+ each entry with the same fields as a record, but of boolean types:
148
+ they indicate whether the field is masked or not; a record entry
149
+ is flagged as masked in the *mask* array if all the fields are
150
+ masked. A few examples in the file should give you an idea of what
151
+ can be done. Note that *mrecords* is still experimental...
152
+
153
+ Optimizing maskedarray
154
+ ----------------------
155
+
156
+ Should masked arrays be filled before processing or not?
157
+ --------------------------------------------------------
158
+
159
+ In the current implementation, most operations on masked arrays involve
160
+ the following steps:
161
+
162
+ * the input arrays are filled
163
+ * the operation is performed on the filled arrays
164
+ * the mask is set for the results, from the combination of the input masks and the mask corresponding to the domain of the operation.
165
+
166
+ For example, consider the division of two masked arrays::
167
+
168
+ import numpy
169
+ import maskedarray as ma
170
+ x = ma.array([1,2,3,4],mask=[1,0,0,0], dtype=numpy.float_)
171
+ y = ma.array([-1,0,1,2], mask=[0,0,0,1], dtype=numpy.float_)
172
+
173
+ The division of x by y is then computed as::
174
+
175
+ d1 = x.filled(0) # d1 = array([0., 2., 3., 4.])
176
+ d2 = y.filled(1) # array([-1., 0., 1., 1.])
177
+ m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
178
+ array([True,False,False,True])
179
+ dm = ma.divide.domain(d1,d2) # array([False, True, False, False])
180
+ result = (d1/d2).view(MaskedArray) # masked_array([-0. inf, 3., 4.])
181
+ result._mask = logical_or(m, dm)
182
+
183
+ Note that a division by zero takes place. To avoid it, we can consider
184
+ to fill the input arrays, taking the domain mask into account, so that::
185
+
186
+ d1 = x._data.copy() # d1 = array([1., 2., 3., 4.])
187
+ d2 = y._data.copy() # array([-1., 0., 1., 2.])
188
+ dm = ma.divide.domain(d1,d2) # array([False, True, False, False])
189
+ numpy.putmask(d2, dm, 1) # d2 = array([-1., 1., 1., 2.])
190
+ m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
191
+ array([True,False,False,True])
192
+ result = (d1/d2).view(MaskedArray) # masked_array([-1. 0., 3., 2.])
193
+ result._mask = logical_or(m, dm)
194
+
195
+ Note that the *.copy()* is required to avoid updating the inputs with
196
+ *putmask*. The *.filled()* method also involves a *.copy()*.
197
+
198
+ A third possibility consists in avoid filling the arrays::
199
+
200
+ d1 = x._data # d1 = array([1., 2., 3., 4.])
201
+ d2 = y._data # array([-1., 0., 1., 2.])
202
+ dm = ma.divide.domain(d1,d2) # array([False, True, False, False])
203
+ m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
204
+ array([True,False,False,True])
205
+ result = (d1/d2).view(MaskedArray) # masked_array([-1. inf, 3., 2.])
206
+ result._mask = logical_or(m, dm)
207
+
208
+ Note that here again the division by zero takes place.
209
+
210
+ A quick benchmark gives the following results:
211
+
212
+ * *numpy.ma.divide* : 2.69 ms per loop
213
+ * classical division : 2.21 ms per loop
214
+ * division w/ prefilling : 2.34 ms per loop
215
+ * division w/o filling : 1.55 ms per loop
216
+
217
+ So, is it worth filling the arrays beforehand ? Yes, if we are interested
218
+ in avoiding floating-point exceptions that may fill the result with infs
219
+ and nans. No, if we are only interested into speed...
220
+
221
+
222
+ Thanks
223
+ ------
224
+
225
+ I'd like to thank Paul Dubois, Travis Oliphant and Sasha for the
226
+ original masked array package: without you, I would never have started
227
+ that (it might be argued that I shouldn't have anyway, but that's
228
+ another story...). I also wish to extend these thanks to Reggie Dugard
229
+ and Eric Firing for their suggestions and numerous improvements.
230
+
231
+
232
+ Revision notes
233
+ --------------
234
+
235
+ * 08/25/2007 : Creation of this page
236
+ * 01/23/2007 : The package has been moved to the SciPy sandbox, and is regularly updated: please check out your SVN version!
venv/lib/python3.10/site-packages/numpy/ma/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =============
3
+ Masked Arrays
4
+ =============
5
+
6
+ Arrays sometimes contain invalid or missing data. When doing operations
7
+ on such arrays, we wish to suppress invalid values, which is the purpose masked
8
+ arrays fulfill (an example of typical use is given below).
9
+
10
+ For example, examine the following array:
11
+
12
+ >>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan])
13
+
14
+ When we try to calculate the mean of the data, the result is undetermined:
15
+
16
+ >>> np.mean(x)
17
+ nan
18
+
19
+ The mean is calculated using roughly ``np.sum(x)/len(x)``, but since
20
+ any number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work. Enter
21
+ masked arrays:
22
+
23
+ >>> m = np.ma.masked_array(x, np.isnan(x))
24
+ >>> m
25
+ masked_array(data = [2.0 1.0 3.0 -- 5.0 2.0 3.0 --],
26
+ mask = [False False False True False False False True],
27
+ fill_value=1e+20)
28
+
29
+ Here, we construct a masked array that suppress all ``NaN`` values. We
30
+ may now proceed to calculate the mean of the other values:
31
+
32
+ >>> np.mean(m)
33
+ 2.6666666666666665
34
+
35
+ .. [1] Not-a-Number, a floating point value that is the result of an
36
+ invalid operation.
37
+
38
+ .. moduleauthor:: Pierre Gerard-Marchant
39
+ .. moduleauthor:: Jarrod Millman
40
+
41
+ """
42
+ from . import core
43
+ from .core import *
44
+
45
+ from . import extras
46
+ from .extras import *
47
+
48
+ __all__ = ['core', 'extras']
49
+ __all__ += core.__all__
50
+ __all__ += extras.__all__
51
+
52
+ from numpy._pytesttester import PytestTester
53
+ test = PytestTester(__name__)
54
+ del PytestTester
venv/lib/python3.10/site-packages/numpy/ma/__init__.pyi ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy._pytesttester import PytestTester
2
+
3
+ from numpy.ma import extras as extras
4
+
5
+ from numpy.ma.core import (
6
+ MAError as MAError,
7
+ MaskError as MaskError,
8
+ MaskType as MaskType,
9
+ MaskedArray as MaskedArray,
10
+ abs as abs,
11
+ absolute as absolute,
12
+ add as add,
13
+ all as all,
14
+ allclose as allclose,
15
+ allequal as allequal,
16
+ alltrue as alltrue,
17
+ amax as amax,
18
+ amin as amin,
19
+ angle as angle,
20
+ anom as anom,
21
+ anomalies as anomalies,
22
+ any as any,
23
+ append as append,
24
+ arange as arange,
25
+ arccos as arccos,
26
+ arccosh as arccosh,
27
+ arcsin as arcsin,
28
+ arcsinh as arcsinh,
29
+ arctan as arctan,
30
+ arctan2 as arctan2,
31
+ arctanh as arctanh,
32
+ argmax as argmax,
33
+ argmin as argmin,
34
+ argsort as argsort,
35
+ around as around,
36
+ array as array,
37
+ asanyarray as asanyarray,
38
+ asarray as asarray,
39
+ bitwise_and as bitwise_and,
40
+ bitwise_or as bitwise_or,
41
+ bitwise_xor as bitwise_xor,
42
+ bool_ as bool_,
43
+ ceil as ceil,
44
+ choose as choose,
45
+ clip as clip,
46
+ common_fill_value as common_fill_value,
47
+ compress as compress,
48
+ compressed as compressed,
49
+ concatenate as concatenate,
50
+ conjugate as conjugate,
51
+ convolve as convolve,
52
+ copy as copy,
53
+ correlate as correlate,
54
+ cos as cos,
55
+ cosh as cosh,
56
+ count as count,
57
+ cumprod as cumprod,
58
+ cumsum as cumsum,
59
+ default_fill_value as default_fill_value,
60
+ diag as diag,
61
+ diagonal as diagonal,
62
+ diff as diff,
63
+ divide as divide,
64
+ empty as empty,
65
+ empty_like as empty_like,
66
+ equal as equal,
67
+ exp as exp,
68
+ expand_dims as expand_dims,
69
+ fabs as fabs,
70
+ filled as filled,
71
+ fix_invalid as fix_invalid,
72
+ flatten_mask as flatten_mask,
73
+ flatten_structured_array as flatten_structured_array,
74
+ floor as floor,
75
+ floor_divide as floor_divide,
76
+ fmod as fmod,
77
+ frombuffer as frombuffer,
78
+ fromflex as fromflex,
79
+ fromfunction as fromfunction,
80
+ getdata as getdata,
81
+ getmask as getmask,
82
+ getmaskarray as getmaskarray,
83
+ greater as greater,
84
+ greater_equal as greater_equal,
85
+ harden_mask as harden_mask,
86
+ hypot as hypot,
87
+ identity as identity,
88
+ ids as ids,
89
+ indices as indices,
90
+ inner as inner,
91
+ innerproduct as innerproduct,
92
+ isMA as isMA,
93
+ isMaskedArray as isMaskedArray,
94
+ is_mask as is_mask,
95
+ is_masked as is_masked,
96
+ isarray as isarray,
97
+ left_shift as left_shift,
98
+ less as less,
99
+ less_equal as less_equal,
100
+ log as log,
101
+ log10 as log10,
102
+ log2 as log2,
103
+ logical_and as logical_and,
104
+ logical_not as logical_not,
105
+ logical_or as logical_or,
106
+ logical_xor as logical_xor,
107
+ make_mask as make_mask,
108
+ make_mask_descr as make_mask_descr,
109
+ make_mask_none as make_mask_none,
110
+ mask_or as mask_or,
111
+ masked as masked,
112
+ masked_array as masked_array,
113
+ masked_equal as masked_equal,
114
+ masked_greater as masked_greater,
115
+ masked_greater_equal as masked_greater_equal,
116
+ masked_inside as masked_inside,
117
+ masked_invalid as masked_invalid,
118
+ masked_less as masked_less,
119
+ masked_less_equal as masked_less_equal,
120
+ masked_not_equal as masked_not_equal,
121
+ masked_object as masked_object,
122
+ masked_outside as masked_outside,
123
+ masked_print_option as masked_print_option,
124
+ masked_singleton as masked_singleton,
125
+ masked_values as masked_values,
126
+ masked_where as masked_where,
127
+ max as max,
128
+ maximum as maximum,
129
+ maximum_fill_value as maximum_fill_value,
130
+ mean as mean,
131
+ min as min,
132
+ minimum as minimum,
133
+ minimum_fill_value as minimum_fill_value,
134
+ mod as mod,
135
+ multiply as multiply,
136
+ mvoid as mvoid,
137
+ ndim as ndim,
138
+ negative as negative,
139
+ nomask as nomask,
140
+ nonzero as nonzero,
141
+ not_equal as not_equal,
142
+ ones as ones,
143
+ outer as outer,
144
+ outerproduct as outerproduct,
145
+ power as power,
146
+ prod as prod,
147
+ product as product,
148
+ ptp as ptp,
149
+ put as put,
150
+ putmask as putmask,
151
+ ravel as ravel,
152
+ remainder as remainder,
153
+ repeat as repeat,
154
+ reshape as reshape,
155
+ resize as resize,
156
+ right_shift as right_shift,
157
+ round as round,
158
+ set_fill_value as set_fill_value,
159
+ shape as shape,
160
+ sin as sin,
161
+ sinh as sinh,
162
+ size as size,
163
+ soften_mask as soften_mask,
164
+ sometrue as sometrue,
165
+ sort as sort,
166
+ sqrt as sqrt,
167
+ squeeze as squeeze,
168
+ std as std,
169
+ subtract as subtract,
170
+ sum as sum,
171
+ swapaxes as swapaxes,
172
+ take as take,
173
+ tan as tan,
174
+ tanh as tanh,
175
+ trace as trace,
176
+ transpose as transpose,
177
+ true_divide as true_divide,
178
+ var as var,
179
+ where as where,
180
+ zeros as zeros,
181
+ )
182
+
183
+ from numpy.ma.extras import (
184
+ apply_along_axis as apply_along_axis,
185
+ apply_over_axes as apply_over_axes,
186
+ atleast_1d as atleast_1d,
187
+ atleast_2d as atleast_2d,
188
+ atleast_3d as atleast_3d,
189
+ average as average,
190
+ clump_masked as clump_masked,
191
+ clump_unmasked as clump_unmasked,
192
+ column_stack as column_stack,
193
+ compress_cols as compress_cols,
194
+ compress_nd as compress_nd,
195
+ compress_rowcols as compress_rowcols,
196
+ compress_rows as compress_rows,
197
+ count_masked as count_masked,
198
+ corrcoef as corrcoef,
199
+ cov as cov,
200
+ diagflat as diagflat,
201
+ dot as dot,
202
+ dstack as dstack,
203
+ ediff1d as ediff1d,
204
+ flatnotmasked_contiguous as flatnotmasked_contiguous,
205
+ flatnotmasked_edges as flatnotmasked_edges,
206
+ hsplit as hsplit,
207
+ hstack as hstack,
208
+ isin as isin,
209
+ in1d as in1d,
210
+ intersect1d as intersect1d,
211
+ mask_cols as mask_cols,
212
+ mask_rowcols as mask_rowcols,
213
+ mask_rows as mask_rows,
214
+ masked_all as masked_all,
215
+ masked_all_like as masked_all_like,
216
+ median as median,
217
+ mr_ as mr_,
218
+ ndenumerate as ndenumerate,
219
+ notmasked_contiguous as notmasked_contiguous,
220
+ notmasked_edges as notmasked_edges,
221
+ polyfit as polyfit,
222
+ row_stack as row_stack,
223
+ setdiff1d as setdiff1d,
224
+ setxor1d as setxor1d,
225
+ stack as stack,
226
+ unique as unique,
227
+ union1d as union1d,
228
+ vander as vander,
229
+ vstack as vstack,
230
+ )
231
+
232
+ __all__: list[str]
233
+ __path__: list[str]
234
+ test: PytestTester
venv/lib/python3.10/site-packages/numpy/ma/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.56 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc ADDED
Binary file (224 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/__pycache__/extras.cpython-310.pyc ADDED
Binary file (57.2 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/__pycache__/mrecords.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/__pycache__/setup.cpython-310.pyc ADDED
Binary file (625 Bytes). View file
 
venv/lib/python3.10/site-packages/numpy/ma/__pycache__/testutils.cpython-310.pyc ADDED
Binary file (7.8 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/__pycache__/timer_comparison.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/core.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/numpy/ma/core.pyi ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any, TypeVar
3
+ from numpy import ndarray, dtype, float64
4
+
5
+ from numpy import (
6
+ amax as amax,
7
+ amin as amin,
8
+ bool_ as bool_,
9
+ expand_dims as expand_dims,
10
+ clip as clip,
11
+ indices as indices,
12
+ ones_like as ones_like,
13
+ squeeze as squeeze,
14
+ zeros_like as zeros_like,
15
+ )
16
+
17
+ from numpy.lib.function_base import (
18
+ angle as angle,
19
+ )
20
+
21
+ # TODO: Set the `bound` to something more suitable once we
22
+ # have proper shape support
23
+ _ShapeType = TypeVar("_ShapeType", bound=Any)
24
+ _DType_co = TypeVar("_DType_co", bound=dtype[Any], covariant=True)
25
+
26
+ __all__: list[str]
27
+
28
+ MaskType = bool_
29
+ nomask: bool_
30
+
31
+ class MaskedArrayFutureWarning(FutureWarning): ...
32
+ class MAError(Exception): ...
33
+ class MaskError(MAError): ...
34
+
35
+ def default_fill_value(obj): ...
36
+ def minimum_fill_value(obj): ...
37
+ def maximum_fill_value(obj): ...
38
+ def set_fill_value(a, fill_value): ...
39
+ def common_fill_value(a, b): ...
40
+ def filled(a, fill_value=...): ...
41
+ def getdata(a, subok=...): ...
42
+ get_data = getdata
43
+
44
+ def fix_invalid(a, mask=..., copy=..., fill_value=...): ...
45
+
46
+ class _MaskedUFunc:
47
+ f: Any
48
+ __doc__: Any
49
+ __name__: Any
50
+ def __init__(self, ufunc): ...
51
+
52
+ class _MaskedUnaryOperation(_MaskedUFunc):
53
+ fill: Any
54
+ domain: Any
55
+ def __init__(self, mufunc, fill=..., domain=...): ...
56
+ def __call__(self, a, *args, **kwargs): ...
57
+
58
+ class _MaskedBinaryOperation(_MaskedUFunc):
59
+ fillx: Any
60
+ filly: Any
61
+ def __init__(self, mbfunc, fillx=..., filly=...): ...
62
+ def __call__(self, a, b, *args, **kwargs): ...
63
+ def reduce(self, target, axis=..., dtype=...): ...
64
+ def outer(self, a, b): ...
65
+ def accumulate(self, target, axis=...): ...
66
+
67
+ class _DomainedBinaryOperation(_MaskedUFunc):
68
+ domain: Any
69
+ fillx: Any
70
+ filly: Any
71
+ def __init__(self, dbfunc, domain, fillx=..., filly=...): ...
72
+ def __call__(self, a, b, *args, **kwargs): ...
73
+
74
+ exp: _MaskedUnaryOperation
75
+ conjugate: _MaskedUnaryOperation
76
+ sin: _MaskedUnaryOperation
77
+ cos: _MaskedUnaryOperation
78
+ arctan: _MaskedUnaryOperation
79
+ arcsinh: _MaskedUnaryOperation
80
+ sinh: _MaskedUnaryOperation
81
+ cosh: _MaskedUnaryOperation
82
+ tanh: _MaskedUnaryOperation
83
+ abs: _MaskedUnaryOperation
84
+ absolute: _MaskedUnaryOperation
85
+ fabs: _MaskedUnaryOperation
86
+ negative: _MaskedUnaryOperation
87
+ floor: _MaskedUnaryOperation
88
+ ceil: _MaskedUnaryOperation
89
+ around: _MaskedUnaryOperation
90
+ logical_not: _MaskedUnaryOperation
91
+ sqrt: _MaskedUnaryOperation
92
+ log: _MaskedUnaryOperation
93
+ log2: _MaskedUnaryOperation
94
+ log10: _MaskedUnaryOperation
95
+ tan: _MaskedUnaryOperation
96
+ arcsin: _MaskedUnaryOperation
97
+ arccos: _MaskedUnaryOperation
98
+ arccosh: _MaskedUnaryOperation
99
+ arctanh: _MaskedUnaryOperation
100
+
101
+ add: _MaskedBinaryOperation
102
+ subtract: _MaskedBinaryOperation
103
+ multiply: _MaskedBinaryOperation
104
+ arctan2: _MaskedBinaryOperation
105
+ equal: _MaskedBinaryOperation
106
+ not_equal: _MaskedBinaryOperation
107
+ less_equal: _MaskedBinaryOperation
108
+ greater_equal: _MaskedBinaryOperation
109
+ less: _MaskedBinaryOperation
110
+ greater: _MaskedBinaryOperation
111
+ logical_and: _MaskedBinaryOperation
112
+ alltrue: _MaskedBinaryOperation
113
+ logical_or: _MaskedBinaryOperation
114
+ sometrue: Callable[..., Any]
115
+ logical_xor: _MaskedBinaryOperation
116
+ bitwise_and: _MaskedBinaryOperation
117
+ bitwise_or: _MaskedBinaryOperation
118
+ bitwise_xor: _MaskedBinaryOperation
119
+ hypot: _MaskedBinaryOperation
120
+ divide: _MaskedBinaryOperation
121
+ true_divide: _MaskedBinaryOperation
122
+ floor_divide: _MaskedBinaryOperation
123
+ remainder: _MaskedBinaryOperation
124
+ fmod: _MaskedBinaryOperation
125
+ mod: _MaskedBinaryOperation
126
+
127
+ def make_mask_descr(ndtype): ...
128
+ def getmask(a): ...
129
+ get_mask = getmask
130
+
131
+ def getmaskarray(arr): ...
132
+ def is_mask(m): ...
133
+ def make_mask(m, copy=..., shrink=..., dtype=...): ...
134
+ def make_mask_none(newshape, dtype=...): ...
135
+ def mask_or(m1, m2, copy=..., shrink=...): ...
136
+ def flatten_mask(mask): ...
137
+ def masked_where(condition, a, copy=...): ...
138
+ def masked_greater(x, value, copy=...): ...
139
+ def masked_greater_equal(x, value, copy=...): ...
140
+ def masked_less(x, value, copy=...): ...
141
+ def masked_less_equal(x, value, copy=...): ...
142
+ def masked_not_equal(x, value, copy=...): ...
143
+ def masked_equal(x, value, copy=...): ...
144
+ def masked_inside(x, v1, v2, copy=...): ...
145
+ def masked_outside(x, v1, v2, copy=...): ...
146
+ def masked_object(x, value, copy=..., shrink=...): ...
147
+ def masked_values(x, value, rtol=..., atol=..., copy=..., shrink=...): ...
148
+ def masked_invalid(a, copy=...): ...
149
+
150
+ class _MaskedPrintOption:
151
+ def __init__(self, display): ...
152
+ def display(self): ...
153
+ def set_display(self, s): ...
154
+ def enabled(self): ...
155
+ def enable(self, shrink=...): ...
156
+
157
+ masked_print_option: _MaskedPrintOption
158
+
159
+ def flatten_structured_array(a): ...
160
+
161
+ class MaskedIterator:
162
+ ma: Any
163
+ dataiter: Any
164
+ maskiter: Any
165
+ def __init__(self, ma): ...
166
+ def __iter__(self): ...
167
+ def __getitem__(self, indx): ...
168
+ def __setitem__(self, index, value): ...
169
+ def __next__(self): ...
170
+
171
+ class MaskedArray(ndarray[_ShapeType, _DType_co]):
172
+ __array_priority__: Any
173
+ def __new__(cls, data=..., mask=..., dtype=..., copy=..., subok=..., ndmin=..., fill_value=..., keep_mask=..., hard_mask=..., shrink=..., order=...): ...
174
+ def __array_finalize__(self, obj): ...
175
+ def __array_wrap__(self, obj, context=...): ...
176
+ def view(self, dtype=..., type=..., fill_value=...): ...
177
+ def __getitem__(self, indx): ...
178
+ def __setitem__(self, indx, value): ...
179
+ @property
180
+ def dtype(self): ...
181
+ @dtype.setter
182
+ def dtype(self, dtype): ...
183
+ @property
184
+ def shape(self): ...
185
+ @shape.setter
186
+ def shape(self, shape): ...
187
+ def __setmask__(self, mask, copy=...): ...
188
+ @property
189
+ def mask(self): ...
190
+ @mask.setter
191
+ def mask(self, value): ...
192
+ @property
193
+ def recordmask(self): ...
194
+ @recordmask.setter
195
+ def recordmask(self, mask): ...
196
+ def harden_mask(self): ...
197
+ def soften_mask(self): ...
198
+ @property
199
+ def hardmask(self): ...
200
+ def unshare_mask(self): ...
201
+ @property
202
+ def sharedmask(self): ...
203
+ def shrink_mask(self): ...
204
+ @property
205
+ def baseclass(self): ...
206
+ data: Any
207
+ @property
208
+ def flat(self): ...
209
+ @flat.setter
210
+ def flat(self, value): ...
211
+ @property
212
+ def fill_value(self): ...
213
+ @fill_value.setter
214
+ def fill_value(self, value=...): ...
215
+ get_fill_value: Any
216
+ set_fill_value: Any
217
+ def filled(self, fill_value=...): ...
218
+ def compressed(self): ...
219
+ def compress(self, condition, axis=..., out=...): ...
220
+ def __eq__(self, other): ...
221
+ def __ne__(self, other): ...
222
+ def __ge__(self, other): ...
223
+ def __gt__(self, other): ...
224
+ def __le__(self, other): ...
225
+ def __lt__(self, other): ...
226
+ def __add__(self, other): ...
227
+ def __radd__(self, other): ...
228
+ def __sub__(self, other): ...
229
+ def __rsub__(self, other): ...
230
+ def __mul__(self, other): ...
231
+ def __rmul__(self, other): ...
232
+ def __div__(self, other): ...
233
+ def __truediv__(self, other): ...
234
+ def __rtruediv__(self, other): ...
235
+ def __floordiv__(self, other): ...
236
+ def __rfloordiv__(self, other): ...
237
+ def __pow__(self, other): ...
238
+ def __rpow__(self, other): ...
239
+ def __iadd__(self, other): ...
240
+ def __isub__(self, other): ...
241
+ def __imul__(self, other): ...
242
+ def __idiv__(self, other): ...
243
+ def __ifloordiv__(self, other): ...
244
+ def __itruediv__(self, other): ...
245
+ def __ipow__(self, other): ...
246
+ def __float__(self): ...
247
+ def __int__(self): ...
248
+ @property # type: ignore[misc]
249
+ def imag(self): ...
250
+ get_imag: Any
251
+ @property # type: ignore[misc]
252
+ def real(self): ...
253
+ get_real: Any
254
+ def count(self, axis=..., keepdims=...): ...
255
+ def ravel(self, order=...): ...
256
+ def reshape(self, *s, **kwargs): ...
257
+ def resize(self, newshape, refcheck=..., order=...): ...
258
+ def put(self, indices, values, mode=...): ...
259
+ def ids(self): ...
260
+ def iscontiguous(self): ...
261
+ def all(self, axis=..., out=..., keepdims=...): ...
262
+ def any(self, axis=..., out=..., keepdims=...): ...
263
+ def nonzero(self): ...
264
+ def trace(self, offset=..., axis1=..., axis2=..., dtype=..., out=...): ...
265
+ def dot(self, b, out=..., strict=...): ...
266
+ def sum(self, axis=..., dtype=..., out=..., keepdims=...): ...
267
+ def cumsum(self, axis=..., dtype=..., out=...): ...
268
+ def prod(self, axis=..., dtype=..., out=..., keepdims=...): ...
269
+ product: Any
270
+ def cumprod(self, axis=..., dtype=..., out=...): ...
271
+ def mean(self, axis=..., dtype=..., out=..., keepdims=...): ...
272
+ def anom(self, axis=..., dtype=...): ...
273
+ def var(self, axis=..., dtype=..., out=..., ddof=..., keepdims=...): ...
274
+ def std(self, axis=..., dtype=..., out=..., ddof=..., keepdims=...): ...
275
+ def round(self, decimals=..., out=...): ...
276
+ def argsort(self, axis=..., kind=..., order=..., endwith=..., fill_value=...): ...
277
+ def argmin(self, axis=..., fill_value=..., out=..., *, keepdims=...): ...
278
+ def argmax(self, axis=..., fill_value=..., out=..., *, keepdims=...): ...
279
+ def sort(self, axis=..., kind=..., order=..., endwith=..., fill_value=...): ...
280
+ def min(self, axis=..., out=..., fill_value=..., keepdims=...): ...
281
+ # NOTE: deprecated
282
+ # def tostring(self, fill_value=..., order=...): ...
283
+ def max(self, axis=..., out=..., fill_value=..., keepdims=...): ...
284
+ def ptp(self, axis=..., out=..., fill_value=..., keepdims=...): ...
285
+ def partition(self, *args, **kwargs): ...
286
+ def argpartition(self, *args, **kwargs): ...
287
+ def take(self, indices, axis=..., out=..., mode=...): ...
288
+ copy: Any
289
+ diagonal: Any
290
+ flatten: Any
291
+ repeat: Any
292
+ squeeze: Any
293
+ swapaxes: Any
294
+ T: Any
295
+ transpose: Any
296
+ def tolist(self, fill_value=...): ...
297
+ def tobytes(self, fill_value=..., order=...): ...
298
+ def tofile(self, fid, sep=..., format=...): ...
299
+ def toflex(self): ...
300
+ torecords: Any
301
+ def __reduce__(self): ...
302
+ def __deepcopy__(self, memo=...): ...
303
+
304
+ class mvoid(MaskedArray[_ShapeType, _DType_co]):
305
+ def __new__(
306
+ self,
307
+ data,
308
+ mask=...,
309
+ dtype=...,
310
+ fill_value=...,
311
+ hardmask=...,
312
+ copy=...,
313
+ subok=...,
314
+ ): ...
315
+ def __getitem__(self, indx): ...
316
+ def __setitem__(self, indx, value): ...
317
+ def __iter__(self): ...
318
+ def __len__(self): ...
319
+ def filled(self, fill_value=...): ...
320
+ def tolist(self): ...
321
+
322
+ def isMaskedArray(x): ...
323
+ isarray = isMaskedArray
324
+ isMA = isMaskedArray
325
+
326
+ # 0D float64 array
327
+ class MaskedConstant(MaskedArray[Any, dtype[float64]]):
328
+ def __new__(cls): ...
329
+ __class__: Any
330
+ def __array_finalize__(self, obj): ...
331
+ def __array_prepare__(self, obj, context=...): ...
332
+ def __array_wrap__(self, obj, context=...): ...
333
+ def __format__(self, format_spec): ...
334
+ def __reduce__(self): ...
335
+ def __iop__(self, other): ...
336
+ __iadd__: Any
337
+ __isub__: Any
338
+ __imul__: Any
339
+ __ifloordiv__: Any
340
+ __itruediv__: Any
341
+ __ipow__: Any
342
+ def copy(self, *args, **kwargs): ...
343
+ def __copy__(self): ...
344
+ def __deepcopy__(self, memo): ...
345
+ def __setattr__(self, attr, value): ...
346
+
347
+ masked: MaskedConstant
348
+ masked_singleton: MaskedConstant
349
+ masked_array = MaskedArray
350
+
351
+ def array(
352
+ data,
353
+ dtype=...,
354
+ copy=...,
355
+ order=...,
356
+ mask=...,
357
+ fill_value=...,
358
+ keep_mask=...,
359
+ hard_mask=...,
360
+ shrink=...,
361
+ subok=...,
362
+ ndmin=...,
363
+ ): ...
364
+ def is_masked(x): ...
365
+
366
+ class _extrema_operation(_MaskedUFunc):
367
+ compare: Any
368
+ fill_value_func: Any
369
+ def __init__(self, ufunc, compare, fill_value): ...
370
+ # NOTE: in practice `b` has a default value, but users should
371
+ # explicitly provide a value here as the default is deprecated
372
+ def __call__(self, a, b): ...
373
+ def reduce(self, target, axis=...): ...
374
+ def outer(self, a, b): ...
375
+
376
+ def min(obj, axis=..., out=..., fill_value=..., keepdims=...): ...
377
+ def max(obj, axis=..., out=..., fill_value=..., keepdims=...): ...
378
+ def ptp(obj, axis=..., out=..., fill_value=..., keepdims=...): ...
379
+
380
+ class _frommethod:
381
+ __name__: Any
382
+ __doc__: Any
383
+ reversed: Any
384
+ def __init__(self, methodname, reversed=...): ...
385
+ def getdoc(self): ...
386
+ def __call__(self, a, *args, **params): ...
387
+
388
+ all: _frommethod
389
+ anomalies: _frommethod
390
+ anom: _frommethod
391
+ any: _frommethod
392
+ compress: _frommethod
393
+ cumprod: _frommethod
394
+ cumsum: _frommethod
395
+ copy: _frommethod
396
+ diagonal: _frommethod
397
+ harden_mask: _frommethod
398
+ ids: _frommethod
399
+ mean: _frommethod
400
+ nonzero: _frommethod
401
+ prod: _frommethod
402
+ product: _frommethod
403
+ ravel: _frommethod
404
+ repeat: _frommethod
405
+ soften_mask: _frommethod
406
+ std: _frommethod
407
+ sum: _frommethod
408
+ swapaxes: _frommethod
409
+ trace: _frommethod
410
+ var: _frommethod
411
+ count: _frommethod
412
+ argmin: _frommethod
413
+ argmax: _frommethod
414
+
415
+ minimum: _extrema_operation
416
+ maximum: _extrema_operation
417
+
418
+ def take(a, indices, axis=..., out=..., mode=...): ...
419
+ def power(a, b, third=...): ...
420
+ def argsort(a, axis=..., kind=..., order=..., endwith=..., fill_value=...): ...
421
+ def sort(a, axis=..., kind=..., order=..., endwith=..., fill_value=...): ...
422
+ def compressed(x): ...
423
+ def concatenate(arrays, axis=...): ...
424
+ def diag(v, k=...): ...
425
+ def left_shift(a, n): ...
426
+ def right_shift(a, n): ...
427
+ def put(a, indices, values, mode=...): ...
428
+ def putmask(a, mask, values): ...
429
+ def transpose(a, axes=...): ...
430
+ def reshape(a, new_shape, order=...): ...
431
+ def resize(x, new_shape): ...
432
+ def ndim(obj): ...
433
+ def shape(obj): ...
434
+ def size(obj, axis=...): ...
435
+ def diff(a, /, n=..., axis=..., prepend=..., append=...): ...
436
+ def where(condition, x=..., y=...): ...
437
+ def choose(indices, choices, out=..., mode=...): ...
438
+ def round(a, decimals=..., out=...): ...
439
+
440
+ def inner(a, b): ...
441
+ innerproduct = inner
442
+
443
+ def outer(a, b): ...
444
+ outerproduct = outer
445
+
446
+ def correlate(a, v, mode=..., propagate_mask=...): ...
447
+ def convolve(a, v, mode=..., propagate_mask=...): ...
448
+ def allequal(a, b, fill_value=...): ...
449
+ def allclose(a, b, masked_equal=..., rtol=..., atol=...): ...
450
+ def asarray(a, dtype=..., order=...): ...
451
+ def asanyarray(a, dtype=...): ...
452
+ def fromflex(fxarray): ...
453
+
454
+ class _convert2ma:
455
+ __doc__: Any
456
+ def __init__(self, funcname, params=...): ...
457
+ def getdoc(self): ...
458
+ def __call__(self, *args, **params): ...
459
+
460
+ arange: _convert2ma
461
+ empty: _convert2ma
462
+ empty_like: _convert2ma
463
+ frombuffer: _convert2ma
464
+ fromfunction: _convert2ma
465
+ identity: _convert2ma
466
+ ones: _convert2ma
467
+ zeros: _convert2ma
468
+
469
+ def append(a, b, axis=...): ...
470
+ def dot(a, b, strict=..., out=...): ...
471
+ def mask_rowcols(a, axis=...): ...
venv/lib/python3.10/site-packages/numpy/ma/extras.pyi ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ from numpy.lib.index_tricks import AxisConcatenator
3
+
4
+ from numpy.ma.core import (
5
+ dot as dot,
6
+ mask_rowcols as mask_rowcols,
7
+ )
8
+
9
+ __all__: list[str]
10
+
11
+ def count_masked(arr, axis=...): ...
12
+ def masked_all(shape, dtype = ...): ...
13
+ def masked_all_like(arr): ...
14
+
15
+ class _fromnxfunction:
16
+ __name__: Any
17
+ __doc__: Any
18
+ def __init__(self, funcname): ...
19
+ def getdoc(self): ...
20
+ def __call__(self, *args, **params): ...
21
+
22
+ class _fromnxfunction_single(_fromnxfunction):
23
+ def __call__(self, x, *args, **params): ...
24
+
25
+ class _fromnxfunction_seq(_fromnxfunction):
26
+ def __call__(self, x, *args, **params): ...
27
+
28
+ class _fromnxfunction_allargs(_fromnxfunction):
29
+ def __call__(self, *args, **params): ...
30
+
31
+ atleast_1d: _fromnxfunction_allargs
32
+ atleast_2d: _fromnxfunction_allargs
33
+ atleast_3d: _fromnxfunction_allargs
34
+
35
+ vstack: _fromnxfunction_seq
36
+ row_stack: _fromnxfunction_seq
37
+ hstack: _fromnxfunction_seq
38
+ column_stack: _fromnxfunction_seq
39
+ dstack: _fromnxfunction_seq
40
+ stack: _fromnxfunction_seq
41
+
42
+ hsplit: _fromnxfunction_single
43
+ diagflat: _fromnxfunction_single
44
+
45
+ def apply_along_axis(func1d, axis, arr, *args, **kwargs): ...
46
+ def apply_over_axes(func, a, axes): ...
47
+ def average(a, axis=..., weights=..., returned=..., keepdims=...): ...
48
+ def median(a, axis=..., out=..., overwrite_input=..., keepdims=...): ...
49
+ def compress_nd(x, axis=...): ...
50
+ def compress_rowcols(x, axis=...): ...
51
+ def compress_rows(a): ...
52
+ def compress_cols(a): ...
53
+ def mask_rows(a, axis = ...): ...
54
+ def mask_cols(a, axis = ...): ...
55
+ def ediff1d(arr, to_end=..., to_begin=...): ...
56
+ def unique(ar1, return_index=..., return_inverse=...): ...
57
+ def intersect1d(ar1, ar2, assume_unique=...): ...
58
+ def setxor1d(ar1, ar2, assume_unique=...): ...
59
+ def in1d(ar1, ar2, assume_unique=..., invert=...): ...
60
+ def isin(element, test_elements, assume_unique=..., invert=...): ...
61
+ def union1d(ar1, ar2): ...
62
+ def setdiff1d(ar1, ar2, assume_unique=...): ...
63
+ def cov(x, y=..., rowvar=..., bias=..., allow_masked=..., ddof=...): ...
64
+ def corrcoef(x, y=..., rowvar=..., bias = ..., allow_masked=..., ddof = ...): ...
65
+
66
+ class MAxisConcatenator(AxisConcatenator):
67
+ concatenate: Any
68
+ @classmethod
69
+ def makemat(cls, arr): ...
70
+ def __getitem__(self, key): ...
71
+
72
+ class mr_class(MAxisConcatenator):
73
+ def __init__(self): ...
74
+
75
+ mr_: mr_class
76
+
77
+ def ndenumerate(a, compressed=...): ...
78
+ def flatnotmasked_edges(a): ...
79
+ def notmasked_edges(a, axis=...): ...
80
+ def flatnotmasked_contiguous(a): ...
81
+ def notmasked_contiguous(a, axis=...): ...
82
+ def clump_unmasked(a): ...
83
+ def clump_masked(a): ...
84
+ def vander(x, n=...): ...
85
+ def polyfit(x, y, deg, rcond=..., full=..., w=..., cov=...): ...
venv/lib/python3.10/site-packages/numpy/ma/mrecords.pyi ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, TypeVar
2
+
3
+ from numpy import dtype
4
+ from numpy.ma import MaskedArray
5
+
6
+ __all__: list[str]
7
+
8
+ # TODO: Set the `bound` to something more suitable once we
9
+ # have proper shape support
10
+ _ShapeType = TypeVar("_ShapeType", bound=Any)
11
+ _DType_co = TypeVar("_DType_co", bound=dtype[Any], covariant=True)
12
+
13
+ class MaskedRecords(MaskedArray[_ShapeType, _DType_co]):
14
+ def __new__(
15
+ cls,
16
+ shape,
17
+ dtype=...,
18
+ buf=...,
19
+ offset=...,
20
+ strides=...,
21
+ formats=...,
22
+ names=...,
23
+ titles=...,
24
+ byteorder=...,
25
+ aligned=...,
26
+ mask=...,
27
+ hard_mask=...,
28
+ fill_value=...,
29
+ keep_mask=...,
30
+ copy=...,
31
+ **options,
32
+ ): ...
33
+ _mask: Any
34
+ _fill_value: Any
35
+ @property
36
+ def _data(self): ...
37
+ @property
38
+ def _fieldmask(self): ...
39
+ def __array_finalize__(self, obj): ...
40
+ def __len__(self): ...
41
+ def __getattribute__(self, attr): ...
42
+ def __setattr__(self, attr, val): ...
43
+ def __getitem__(self, indx): ...
44
+ def __setitem__(self, indx, value): ...
45
+ def view(self, dtype=..., type=...): ...
46
+ def harden_mask(self): ...
47
+ def soften_mask(self): ...
48
+ def copy(self): ...
49
+ def tolist(self, fill_value=...): ...
50
+ def __reduce__(self): ...
51
+
52
+ mrecarray = MaskedRecords
53
+
54
+ def fromarrays(
55
+ arraylist,
56
+ dtype=...,
57
+ shape=...,
58
+ formats=...,
59
+ names=...,
60
+ titles=...,
61
+ aligned=...,
62
+ byteorder=...,
63
+ fill_value=...,
64
+ ): ...
65
+
66
+ def fromrecords(
67
+ reclist,
68
+ dtype=...,
69
+ shape=...,
70
+ formats=...,
71
+ names=...,
72
+ titles=...,
73
+ aligned=...,
74
+ byteorder=...,
75
+ fill_value=...,
76
+ mask=...,
77
+ ): ...
78
+
79
+ def fromtextfile(
80
+ fname,
81
+ delimiter=...,
82
+ commentchar=...,
83
+ missingchar=...,
84
+ varnames=...,
85
+ vartypes=...,
86
+ # NOTE: deprecated: NumPy 1.22.0, 2021-09-23
87
+ # delimitor=...,
88
+ ): ...
89
+
90
+ def addfield(mrecord, newfield, newfieldname=...): ...
venv/lib/python3.10/site-packages/numpy/ma/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (182 Bytes). View file
 
venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc ADDED
Binary file (169 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_deprecations.cpython-310.pyc ADDED
Binary file (2.96 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_extras.cpython-310.pyc ADDED
Binary file (56.8 kB). View file
 
venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_mrecords.cpython-310.pyc ADDED
Binary file (15.1 kB). View file