applied-ai-018 commited on
Commit
4a88805
·
verified ·
1 Parent(s): 37dcb99

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. env-llmeval/lib/python3.10/site-packages/numpy/_typing/__init__.py +221 -0
  2. env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/__init__.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/_add_docstring.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/_char_codes.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/_extended_precision.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/_nested_sequence.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/setup.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_add_docstring.py +152 -0
  9. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_array_like.py +167 -0
  10. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_callable.pyi +338 -0
  11. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_char_codes.py +111 -0
  12. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_dtype_like.py +246 -0
  13. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_extended_precision.py +27 -0
  14. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_nbit.py +16 -0
  15. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_nested_sequence.py +86 -0
  16. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_scalars.py +30 -0
  17. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_shape.py +7 -0
  18. env-llmeval/lib/python3.10/site-packages/numpy/_typing/_ufunc.pyi +445 -0
  19. env-llmeval/lib/python3.10/site-packages/numpy/_typing/setup.py +10 -0
  20. env-llmeval/lib/python3.10/site-packages/numpy/linalg/__init__.py +80 -0
  21. env-llmeval/lib/python3.10/site-packages/numpy/linalg/__init__.pyi +30 -0
  22. env-llmeval/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so +0 -0
  25. env-llmeval/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so +0 -0
  26. env-llmeval/lib/python3.10/site-packages/numpy/linalg/linalg.py +2836 -0
  27. env-llmeval/lib/python3.10/site-packages/numpy/linalg/linalg.pyi +297 -0
  28. env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__init__.py +0 -0
  29. env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/test_deprecations.py +20 -0
  34. env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/test_linalg.py +2198 -0
  35. env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/test_regression.py +145 -0
  36. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/__init__.py +185 -0
  37. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/_polybase.py +1206 -0
  38. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/_polybase.pyi +71 -0
  39. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/chebyshev.py +2082 -0
  40. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/chebyshev.pyi +51 -0
  41. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/hermite.py +1703 -0
  42. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/hermite.pyi +46 -0
  43. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/hermite_e.py +1695 -0
  44. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/laguerre.pyi +46 -0
  45. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/legendre.py +1664 -0
  46. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/polynomial.py +1542 -0
  47. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/polynomial.pyi +41 -0
  48. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/polyutils.pyi +11 -0
  49. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/setup.py +10 -0
  50. env-llmeval/lib/python3.10/site-packages/numpy/polynomial/tests/__init__.py +0 -0
env-llmeval/lib/python3.10/site-packages/numpy/_typing/__init__.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private counterpart of ``numpy.typing``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .. import ufunc
6
+ from .._utils import set_module
7
+ from typing import TYPE_CHECKING, final
8
+
9
+
10
+ @final # Disallow the creation of arbitrary `NBitBase` subclasses
11
+ @set_module("numpy.typing")
12
+ class NBitBase:
13
+ """
14
+ A type representing `numpy.number` precision during static type checking.
15
+
16
+ Used exclusively for the purpose static type checking, `NBitBase`
17
+ represents the base of a hierarchical set of subclasses.
18
+ Each subsequent subclass is herein used for representing a lower level
19
+ of precision, *e.g.* ``64Bit > 32Bit > 16Bit``.
20
+
21
+ .. versionadded:: 1.20
22
+
23
+ Examples
24
+ --------
25
+ Below is a typical usage example: `NBitBase` is herein used for annotating
26
+ a function that takes a float and integer of arbitrary precision
27
+ as arguments and returns a new float of whichever precision is largest
28
+ (*e.g.* ``np.float16 + np.int64 -> np.float64``).
29
+
30
+ .. code-block:: python
31
+
32
+ >>> from __future__ import annotations
33
+ >>> from typing import TypeVar, TYPE_CHECKING
34
+ >>> import numpy as np
35
+ >>> import numpy.typing as npt
36
+
37
+ >>> T1 = TypeVar("T1", bound=npt.NBitBase)
38
+ >>> T2 = TypeVar("T2", bound=npt.NBitBase)
39
+
40
+ >>> def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[T1 | T2]:
41
+ ... return a + b
42
+
43
+ >>> a = np.float16()
44
+ >>> b = np.int64()
45
+ >>> out = add(a, b)
46
+
47
+ >>> if TYPE_CHECKING:
48
+ ... reveal_locals()
49
+ ... # note: Revealed local types are:
50
+ ... # note: a: numpy.floating[numpy.typing._16Bit*]
51
+ ... # note: b: numpy.signedinteger[numpy.typing._64Bit*]
52
+ ... # note: out: numpy.floating[numpy.typing._64Bit*]
53
+
54
+ """
55
+
56
+ def __init_subclass__(cls) -> None:
57
+ allowed_names = {
58
+ "NBitBase", "_256Bit", "_128Bit", "_96Bit", "_80Bit",
59
+ "_64Bit", "_32Bit", "_16Bit", "_8Bit",
60
+ }
61
+ if cls.__name__ not in allowed_names:
62
+ raise TypeError('cannot inherit from final class "NBitBase"')
63
+ super().__init_subclass__()
64
+
65
+
66
+ # Silence errors about subclassing a `@final`-decorated class
67
+ class _256Bit(NBitBase): # type: ignore[misc]
68
+ pass
69
+
70
+ class _128Bit(_256Bit): # type: ignore[misc]
71
+ pass
72
+
73
+ class _96Bit(_128Bit): # type: ignore[misc]
74
+ pass
75
+
76
+ class _80Bit(_96Bit): # type: ignore[misc]
77
+ pass
78
+
79
+ class _64Bit(_80Bit): # type: ignore[misc]
80
+ pass
81
+
82
+ class _32Bit(_64Bit): # type: ignore[misc]
83
+ pass
84
+
85
+ class _16Bit(_32Bit): # type: ignore[misc]
86
+ pass
87
+
88
+ class _8Bit(_16Bit): # type: ignore[misc]
89
+ pass
90
+
91
+
92
+ from ._nested_sequence import (
93
+ _NestedSequence as _NestedSequence,
94
+ )
95
+ from ._nbit import (
96
+ _NBitByte as _NBitByte,
97
+ _NBitShort as _NBitShort,
98
+ _NBitIntC as _NBitIntC,
99
+ _NBitIntP as _NBitIntP,
100
+ _NBitInt as _NBitInt,
101
+ _NBitLongLong as _NBitLongLong,
102
+ _NBitHalf as _NBitHalf,
103
+ _NBitSingle as _NBitSingle,
104
+ _NBitDouble as _NBitDouble,
105
+ _NBitLongDouble as _NBitLongDouble,
106
+ )
107
+ from ._char_codes import (
108
+ _BoolCodes as _BoolCodes,
109
+ _UInt8Codes as _UInt8Codes,
110
+ _UInt16Codes as _UInt16Codes,
111
+ _UInt32Codes as _UInt32Codes,
112
+ _UInt64Codes as _UInt64Codes,
113
+ _Int8Codes as _Int8Codes,
114
+ _Int16Codes as _Int16Codes,
115
+ _Int32Codes as _Int32Codes,
116
+ _Int64Codes as _Int64Codes,
117
+ _Float16Codes as _Float16Codes,
118
+ _Float32Codes as _Float32Codes,
119
+ _Float64Codes as _Float64Codes,
120
+ _Complex64Codes as _Complex64Codes,
121
+ _Complex128Codes as _Complex128Codes,
122
+ _ByteCodes as _ByteCodes,
123
+ _ShortCodes as _ShortCodes,
124
+ _IntCCodes as _IntCCodes,
125
+ _IntPCodes as _IntPCodes,
126
+ _IntCodes as _IntCodes,
127
+ _LongLongCodes as _LongLongCodes,
128
+ _UByteCodes as _UByteCodes,
129
+ _UShortCodes as _UShortCodes,
130
+ _UIntCCodes as _UIntCCodes,
131
+ _UIntPCodes as _UIntPCodes,
132
+ _UIntCodes as _UIntCodes,
133
+ _ULongLongCodes as _ULongLongCodes,
134
+ _HalfCodes as _HalfCodes,
135
+ _SingleCodes as _SingleCodes,
136
+ _DoubleCodes as _DoubleCodes,
137
+ _LongDoubleCodes as _LongDoubleCodes,
138
+ _CSingleCodes as _CSingleCodes,
139
+ _CDoubleCodes as _CDoubleCodes,
140
+ _CLongDoubleCodes as _CLongDoubleCodes,
141
+ _DT64Codes as _DT64Codes,
142
+ _TD64Codes as _TD64Codes,
143
+ _StrCodes as _StrCodes,
144
+ _BytesCodes as _BytesCodes,
145
+ _VoidCodes as _VoidCodes,
146
+ _ObjectCodes as _ObjectCodes,
147
+ )
148
+ from ._scalars import (
149
+ _CharLike_co as _CharLike_co,
150
+ _BoolLike_co as _BoolLike_co,
151
+ _UIntLike_co as _UIntLike_co,
152
+ _IntLike_co as _IntLike_co,
153
+ _FloatLike_co as _FloatLike_co,
154
+ _ComplexLike_co as _ComplexLike_co,
155
+ _TD64Like_co as _TD64Like_co,
156
+ _NumberLike_co as _NumberLike_co,
157
+ _ScalarLike_co as _ScalarLike_co,
158
+ _VoidLike_co as _VoidLike_co,
159
+ )
160
+ from ._shape import (
161
+ _Shape as _Shape,
162
+ _ShapeLike as _ShapeLike,
163
+ )
164
+ from ._dtype_like import (
165
+ DTypeLike as DTypeLike,
166
+ _DTypeLike as _DTypeLike,
167
+ _SupportsDType as _SupportsDType,
168
+ _VoidDTypeLike as _VoidDTypeLike,
169
+ _DTypeLikeBool as _DTypeLikeBool,
170
+ _DTypeLikeUInt as _DTypeLikeUInt,
171
+ _DTypeLikeInt as _DTypeLikeInt,
172
+ _DTypeLikeFloat as _DTypeLikeFloat,
173
+ _DTypeLikeComplex as _DTypeLikeComplex,
174
+ _DTypeLikeTD64 as _DTypeLikeTD64,
175
+ _DTypeLikeDT64 as _DTypeLikeDT64,
176
+ _DTypeLikeObject as _DTypeLikeObject,
177
+ _DTypeLikeVoid as _DTypeLikeVoid,
178
+ _DTypeLikeStr as _DTypeLikeStr,
179
+ _DTypeLikeBytes as _DTypeLikeBytes,
180
+ _DTypeLikeComplex_co as _DTypeLikeComplex_co,
181
+ )
182
+ from ._array_like import (
183
+ NDArray as NDArray,
184
+ ArrayLike as ArrayLike,
185
+ _ArrayLike as _ArrayLike,
186
+ _FiniteNestedSequence as _FiniteNestedSequence,
187
+ _SupportsArray as _SupportsArray,
188
+ _SupportsArrayFunc as _SupportsArrayFunc,
189
+ _ArrayLikeInt as _ArrayLikeInt,
190
+ _ArrayLikeBool_co as _ArrayLikeBool_co,
191
+ _ArrayLikeUInt_co as _ArrayLikeUInt_co,
192
+ _ArrayLikeInt_co as _ArrayLikeInt_co,
193
+ _ArrayLikeFloat_co as _ArrayLikeFloat_co,
194
+ _ArrayLikeComplex_co as _ArrayLikeComplex_co,
195
+ _ArrayLikeNumber_co as _ArrayLikeNumber_co,
196
+ _ArrayLikeTD64_co as _ArrayLikeTD64_co,
197
+ _ArrayLikeDT64_co as _ArrayLikeDT64_co,
198
+ _ArrayLikeObject_co as _ArrayLikeObject_co,
199
+ _ArrayLikeVoid_co as _ArrayLikeVoid_co,
200
+ _ArrayLikeStr_co as _ArrayLikeStr_co,
201
+ _ArrayLikeBytes_co as _ArrayLikeBytes_co,
202
+ _ArrayLikeUnknown as _ArrayLikeUnknown,
203
+ _UnknownType as _UnknownType,
204
+ )
205
+
206
+ if TYPE_CHECKING:
207
+ from ._ufunc import (
208
+ _UFunc_Nin1_Nout1 as _UFunc_Nin1_Nout1,
209
+ _UFunc_Nin2_Nout1 as _UFunc_Nin2_Nout1,
210
+ _UFunc_Nin1_Nout2 as _UFunc_Nin1_Nout2,
211
+ _UFunc_Nin2_Nout2 as _UFunc_Nin2_Nout2,
212
+ _GUFunc_Nin2_Nout1 as _GUFunc_Nin2_Nout1,
213
+ )
214
+ else:
215
+ # Declare the (type-check-only) ufunc subclasses as ufunc aliases during
216
+ # runtime; this helps autocompletion tools such as Jedi (numpy/numpy#19834)
217
+ _UFunc_Nin1_Nout1 = ufunc
218
+ _UFunc_Nin2_Nout1 = ufunc
219
+ _UFunc_Nin1_Nout2 = ufunc
220
+ _UFunc_Nin2_Nout2 = ufunc
221
+ _GUFunc_Nin2_Nout1 = ufunc
env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (6.13 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/_add_docstring.cpython-310.pyc ADDED
Binary file (3.81 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/_char_codes.cpython-310.pyc ADDED
Binary file (5.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/_extended_precision.cpython-310.pyc ADDED
Binary file (870 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/_nested_sequence.cpython-310.pyc ADDED
Binary file (3.27 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/_typing/__pycache__/setup.cpython-310.pyc ADDED
Binary file (559 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_add_docstring.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module for creating docstrings for sphinx ``data`` domains."""
2
+
3
+ import re
4
+ import textwrap
5
+
6
+ from ._array_like import NDArray
7
+
8
+ _docstrings_list = []
9
+
10
+
11
+ def add_newdoc(name: str, value: str, doc: str) -> None:
12
+ """Append ``_docstrings_list`` with a docstring for `name`.
13
+
14
+ Parameters
15
+ ----------
16
+ name : str
17
+ The name of the object.
18
+ value : str
19
+ A string-representation of the object.
20
+ doc : str
21
+ The docstring of the object.
22
+
23
+ """
24
+ _docstrings_list.append((name, value, doc))
25
+
26
+
27
+ def _parse_docstrings() -> str:
28
+ """Convert all docstrings in ``_docstrings_list`` into a single
29
+ sphinx-legible text block.
30
+
31
+ """
32
+ type_list_ret = []
33
+ for name, value, doc in _docstrings_list:
34
+ s = textwrap.dedent(doc).replace("\n", "\n ")
35
+
36
+ # Replace sections by rubrics
37
+ lines = s.split("\n")
38
+ new_lines = []
39
+ indent = ""
40
+ for line in lines:
41
+ m = re.match(r'^(\s+)[-=]+\s*$', line)
42
+ if m and new_lines:
43
+ prev = textwrap.dedent(new_lines.pop())
44
+ if prev == "Examples":
45
+ indent = ""
46
+ new_lines.append(f'{m.group(1)}.. rubric:: {prev}')
47
+ else:
48
+ indent = 4 * " "
49
+ new_lines.append(f'{m.group(1)}.. admonition:: {prev}')
50
+ new_lines.append("")
51
+ else:
52
+ new_lines.append(f"{indent}{line}")
53
+
54
+ s = "\n".join(new_lines)
55
+ s_block = f""".. data:: {name}\n :value: {value}\n {s}"""
56
+ type_list_ret.append(s_block)
57
+ return "\n".join(type_list_ret)
58
+
59
+
60
+ add_newdoc('ArrayLike', 'typing.Union[...]',
61
+ """
62
+ A `~typing.Union` representing objects that can be coerced
63
+ into an `~numpy.ndarray`.
64
+
65
+ Among others this includes the likes of:
66
+
67
+ * Scalars.
68
+ * (Nested) sequences.
69
+ * Objects implementing the `~class.__array__` protocol.
70
+
71
+ .. versionadded:: 1.20
72
+
73
+ See Also
74
+ --------
75
+ :term:`array_like`:
76
+ Any scalar or sequence that can be interpreted as an ndarray.
77
+
78
+ Examples
79
+ --------
80
+ .. code-block:: python
81
+
82
+ >>> import numpy as np
83
+ >>> import numpy.typing as npt
84
+
85
+ >>> def as_array(a: npt.ArrayLike) -> np.ndarray:
86
+ ... return np.array(a)
87
+
88
+ """)
89
+
90
+ add_newdoc('DTypeLike', 'typing.Union[...]',
91
+ """
92
+ A `~typing.Union` representing objects that can be coerced
93
+ into a `~numpy.dtype`.
94
+
95
+ Among others this includes the likes of:
96
+
97
+ * :class:`type` objects.
98
+ * Character codes or the names of :class:`type` objects.
99
+ * Objects with the ``.dtype`` attribute.
100
+
101
+ .. versionadded:: 1.20
102
+
103
+ See Also
104
+ --------
105
+ :ref:`Specifying and constructing data types <arrays.dtypes.constructing>`
106
+ A comprehensive overview of all objects that can be coerced
107
+ into data types.
108
+
109
+ Examples
110
+ --------
111
+ .. code-block:: python
112
+
113
+ >>> import numpy as np
114
+ >>> import numpy.typing as npt
115
+
116
+ >>> def as_dtype(d: npt.DTypeLike) -> np.dtype:
117
+ ... return np.dtype(d)
118
+
119
+ """)
120
+
121
+ add_newdoc('NDArray', repr(NDArray),
122
+ """
123
+ A :term:`generic <generic type>` version of
124
+ `np.ndarray[Any, np.dtype[+ScalarType]] <numpy.ndarray>`.
125
+
126
+ Can be used during runtime for typing arrays with a given dtype
127
+ and unspecified shape.
128
+
129
+ .. versionadded:: 1.21
130
+
131
+ Examples
132
+ --------
133
+ .. code-block:: python
134
+
135
+ >>> import numpy as np
136
+ >>> import numpy.typing as npt
137
+
138
+ >>> print(npt.NDArray)
139
+ numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]
140
+
141
+ >>> print(npt.NDArray[np.float64])
142
+ numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
143
+
144
+ >>> NDArrayInt = npt.NDArray[np.int_]
145
+ >>> a: NDArrayInt = np.arange(10)
146
+
147
+ >>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
148
+ ... return np.array(a)
149
+
150
+ """)
151
+
152
+ _docstrings = _parse_docstrings()
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_array_like.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from collections.abc import Collection, Callable, Sequence
5
+ from typing import Any, Protocol, Union, TypeVar, runtime_checkable
6
+
7
+ from numpy import (
8
+ ndarray,
9
+ dtype,
10
+ generic,
11
+ bool_,
12
+ unsignedinteger,
13
+ integer,
14
+ floating,
15
+ complexfloating,
16
+ number,
17
+ timedelta64,
18
+ datetime64,
19
+ object_,
20
+ void,
21
+ str_,
22
+ bytes_,
23
+ )
24
+ from ._nested_sequence import _NestedSequence
25
+
26
+ _T = TypeVar("_T")
27
+ _ScalarType = TypeVar("_ScalarType", bound=generic)
28
+ _ScalarType_co = TypeVar("_ScalarType_co", bound=generic, covariant=True)
29
+ _DType = TypeVar("_DType", bound=dtype[Any])
30
+ _DType_co = TypeVar("_DType_co", covariant=True, bound=dtype[Any])
31
+
32
+ NDArray = ndarray[Any, dtype[_ScalarType_co]]
33
+
34
+ # The `_SupportsArray` protocol only cares about the default dtype
35
+ # (i.e. `dtype=None` or no `dtype` parameter at all) of the to-be returned
36
+ # array.
37
+ # Concrete implementations of the protocol are responsible for adding
38
+ # any and all remaining overloads
39
+ @runtime_checkable
40
+ class _SupportsArray(Protocol[_DType_co]):
41
+ def __array__(self) -> ndarray[Any, _DType_co]: ...
42
+
43
+
44
+ @runtime_checkable
45
+ class _SupportsArrayFunc(Protocol):
46
+ """A protocol class representing `~class.__array_function__`."""
47
+ def __array_function__(
48
+ self,
49
+ func: Callable[..., Any],
50
+ types: Collection[type[Any]],
51
+ args: tuple[Any, ...],
52
+ kwargs: dict[str, Any],
53
+ ) -> object: ...
54
+
55
+
56
+ # TODO: Wait until mypy supports recursive objects in combination with typevars
57
+ _FiniteNestedSequence = Union[
58
+ _T,
59
+ Sequence[_T],
60
+ Sequence[Sequence[_T]],
61
+ Sequence[Sequence[Sequence[_T]]],
62
+ Sequence[Sequence[Sequence[Sequence[_T]]]],
63
+ ]
64
+
65
+ # A subset of `npt.ArrayLike` that can be parametrized w.r.t. `np.generic`
66
+ _ArrayLike = Union[
67
+ _SupportsArray[dtype[_ScalarType]],
68
+ _NestedSequence[_SupportsArray[dtype[_ScalarType]]],
69
+ ]
70
+
71
+ # A union representing array-like objects; consists of two typevars:
72
+ # One representing types that can be parametrized w.r.t. `np.dtype`
73
+ # and another one for the rest
74
+ _DualArrayLike = Union[
75
+ _SupportsArray[_DType],
76
+ _NestedSequence[_SupportsArray[_DType]],
77
+ _T,
78
+ _NestedSequence[_T],
79
+ ]
80
+
81
+ if sys.version_info >= (3, 12):
82
+ from collections.abc import Buffer
83
+
84
+ ArrayLike = Buffer | _DualArrayLike[
85
+ dtype[Any],
86
+ Union[bool, int, float, complex, str, bytes],
87
+ ]
88
+ else:
89
+ ArrayLike = _DualArrayLike[
90
+ dtype[Any],
91
+ Union[bool, int, float, complex, str, bytes],
92
+ ]
93
+
94
+ # `ArrayLike<X>_co`: array-like objects that can be coerced into `X`
95
+ # given the casting rules `same_kind`
96
+ _ArrayLikeBool_co = _DualArrayLike[
97
+ dtype[bool_],
98
+ bool,
99
+ ]
100
+ _ArrayLikeUInt_co = _DualArrayLike[
101
+ dtype[Union[bool_, unsignedinteger[Any]]],
102
+ bool,
103
+ ]
104
+ _ArrayLikeInt_co = _DualArrayLike[
105
+ dtype[Union[bool_, integer[Any]]],
106
+ Union[bool, int],
107
+ ]
108
+ _ArrayLikeFloat_co = _DualArrayLike[
109
+ dtype[Union[bool_, integer[Any], floating[Any]]],
110
+ Union[bool, int, float],
111
+ ]
112
+ _ArrayLikeComplex_co = _DualArrayLike[
113
+ dtype[Union[
114
+ bool_,
115
+ integer[Any],
116
+ floating[Any],
117
+ complexfloating[Any, Any],
118
+ ]],
119
+ Union[bool, int, float, complex],
120
+ ]
121
+ _ArrayLikeNumber_co = _DualArrayLike[
122
+ dtype[Union[bool_, number[Any]]],
123
+ Union[bool, int, float, complex],
124
+ ]
125
+ _ArrayLikeTD64_co = _DualArrayLike[
126
+ dtype[Union[bool_, integer[Any], timedelta64]],
127
+ Union[bool, int],
128
+ ]
129
+ _ArrayLikeDT64_co = Union[
130
+ _SupportsArray[dtype[datetime64]],
131
+ _NestedSequence[_SupportsArray[dtype[datetime64]]],
132
+ ]
133
+ _ArrayLikeObject_co = Union[
134
+ _SupportsArray[dtype[object_]],
135
+ _NestedSequence[_SupportsArray[dtype[object_]]],
136
+ ]
137
+
138
+ _ArrayLikeVoid_co = Union[
139
+ _SupportsArray[dtype[void]],
140
+ _NestedSequence[_SupportsArray[dtype[void]]],
141
+ ]
142
+ _ArrayLikeStr_co = _DualArrayLike[
143
+ dtype[str_],
144
+ str,
145
+ ]
146
+ _ArrayLikeBytes_co = _DualArrayLike[
147
+ dtype[bytes_],
148
+ bytes,
149
+ ]
150
+
151
+ _ArrayLikeInt = _DualArrayLike[
152
+ dtype[integer[Any]],
153
+ int,
154
+ ]
155
+
156
+ # Extra ArrayLike type so that pyright can deal with NDArray[Any]
157
+ # Used as the first overload, should only match NDArray[Any],
158
+ # not any actual types.
159
+ # https://github.com/numpy/numpy/pull/22193
160
+ class _UnknownType:
161
+ ...
162
+
163
+
164
+ _ArrayLikeUnknown = _DualArrayLike[
165
+ dtype[_UnknownType],
166
+ _UnknownType,
167
+ ]
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_callable.pyi ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module with various ``typing.Protocol`` subclasses that implement
3
+ the ``__call__`` magic method.
4
+
5
+ See the `Mypy documentation`_ on protocols for more details.
6
+
7
+ .. _`Mypy documentation`: https://mypy.readthedocs.io/en/stable/protocols.html#callback-protocols
8
+
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import (
14
+ TypeVar,
15
+ overload,
16
+ Any,
17
+ NoReturn,
18
+ Protocol,
19
+ )
20
+
21
+ from numpy import (
22
+ ndarray,
23
+ dtype,
24
+ generic,
25
+ bool_,
26
+ timedelta64,
27
+ number,
28
+ integer,
29
+ unsignedinteger,
30
+ signedinteger,
31
+ int8,
32
+ int_,
33
+ floating,
34
+ float64,
35
+ complexfloating,
36
+ complex128,
37
+ )
38
+ from ._nbit import _NBitInt, _NBitDouble
39
+ from ._scalars import (
40
+ _BoolLike_co,
41
+ _IntLike_co,
42
+ _FloatLike_co,
43
+ _NumberLike_co,
44
+ )
45
+ from . import NBitBase
46
+ from ._array_like import NDArray
47
+ from ._nested_sequence import _NestedSequence
48
+
49
+ _T1 = TypeVar("_T1")
50
+ _T2 = TypeVar("_T2")
51
+ _T1_contra = TypeVar("_T1_contra", contravariant=True)
52
+ _T2_contra = TypeVar("_T2_contra", contravariant=True)
53
+ _2Tuple = tuple[_T1, _T1]
54
+
55
+ _NBit1 = TypeVar("_NBit1", bound=NBitBase)
56
+ _NBit2 = TypeVar("_NBit2", bound=NBitBase)
57
+
58
+ _IntType = TypeVar("_IntType", bound=integer)
59
+ _FloatType = TypeVar("_FloatType", bound=floating)
60
+ _NumberType = TypeVar("_NumberType", bound=number)
61
+ _NumberType_co = TypeVar("_NumberType_co", covariant=True, bound=number)
62
+ _GenericType_co = TypeVar("_GenericType_co", covariant=True, bound=generic)
63
+
64
+ class _BoolOp(Protocol[_GenericType_co]):
65
+ @overload
66
+ def __call__(self, other: _BoolLike_co, /) -> _GenericType_co: ...
67
+ @overload # platform dependent
68
+ def __call__(self, other: int, /) -> int_: ...
69
+ @overload
70
+ def __call__(self, other: float, /) -> float64: ...
71
+ @overload
72
+ def __call__(self, other: complex, /) -> complex128: ...
73
+ @overload
74
+ def __call__(self, other: _NumberType, /) -> _NumberType: ...
75
+
76
+ class _BoolBitOp(Protocol[_GenericType_co]):
77
+ @overload
78
+ def __call__(self, other: _BoolLike_co, /) -> _GenericType_co: ...
79
+ @overload # platform dependent
80
+ def __call__(self, other: int, /) -> int_: ...
81
+ @overload
82
+ def __call__(self, other: _IntType, /) -> _IntType: ...
83
+
84
+ class _BoolSub(Protocol):
85
+ # Note that `other: bool_` is absent here
86
+ @overload
87
+ def __call__(self, other: bool, /) -> NoReturn: ...
88
+ @overload # platform dependent
89
+ def __call__(self, other: int, /) -> int_: ...
90
+ @overload
91
+ def __call__(self, other: float, /) -> float64: ...
92
+ @overload
93
+ def __call__(self, other: complex, /) -> complex128: ...
94
+ @overload
95
+ def __call__(self, other: _NumberType, /) -> _NumberType: ...
96
+
97
+ class _BoolTrueDiv(Protocol):
98
+ @overload
99
+ def __call__(self, other: float | _IntLike_co, /) -> float64: ...
100
+ @overload
101
+ def __call__(self, other: complex, /) -> complex128: ...
102
+ @overload
103
+ def __call__(self, other: _NumberType, /) -> _NumberType: ...
104
+
105
+ class _BoolMod(Protocol):
106
+ @overload
107
+ def __call__(self, other: _BoolLike_co, /) -> int8: ...
108
+ @overload # platform dependent
109
+ def __call__(self, other: int, /) -> int_: ...
110
+ @overload
111
+ def __call__(self, other: float, /) -> float64: ...
112
+ @overload
113
+ def __call__(self, other: _IntType, /) -> _IntType: ...
114
+ @overload
115
+ def __call__(self, other: _FloatType, /) -> _FloatType: ...
116
+
117
+ class _BoolDivMod(Protocol):
118
+ @overload
119
+ def __call__(self, other: _BoolLike_co, /) -> _2Tuple[int8]: ...
120
+ @overload # platform dependent
121
+ def __call__(self, other: int, /) -> _2Tuple[int_]: ...
122
+ @overload
123
+ def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
124
+ @overload
125
+ def __call__(self, other: _IntType, /) -> _2Tuple[_IntType]: ...
126
+ @overload
127
+ def __call__(self, other: _FloatType, /) -> _2Tuple[_FloatType]: ...
128
+
129
+ class _TD64Div(Protocol[_NumberType_co]):
130
+ @overload
131
+ def __call__(self, other: timedelta64, /) -> _NumberType_co: ...
132
+ @overload
133
+ def __call__(self, other: _BoolLike_co, /) -> NoReturn: ...
134
+ @overload
135
+ def __call__(self, other: _FloatLike_co, /) -> timedelta64: ...
136
+
137
+ class _IntTrueDiv(Protocol[_NBit1]):
138
+ @overload
139
+ def __call__(self, other: bool, /) -> floating[_NBit1]: ...
140
+ @overload
141
+ def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
142
+ @overload
143
+ def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
144
+ @overload
145
+ def __call__(
146
+ self, other: complex, /,
147
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
148
+ @overload
149
+ def __call__(self, other: integer[_NBit2], /) -> floating[_NBit1 | _NBit2]: ...
150
+
151
+ class _UnsignedIntOp(Protocol[_NBit1]):
152
+ # NOTE: `uint64 + signedinteger -> float64`
153
+ @overload
154
+ def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
155
+ @overload
156
+ def __call__(
157
+ self, other: int | signedinteger[Any], /
158
+ ) -> Any: ...
159
+ @overload
160
+ def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
161
+ @overload
162
+ def __call__(
163
+ self, other: complex, /,
164
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
165
+ @overload
166
+ def __call__(
167
+ self, other: unsignedinteger[_NBit2], /
168
+ ) -> unsignedinteger[_NBit1 | _NBit2]: ...
169
+
170
+ class _UnsignedIntBitOp(Protocol[_NBit1]):
171
+ @overload
172
+ def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
173
+ @overload
174
+ def __call__(self, other: int, /) -> signedinteger[Any]: ...
175
+ @overload
176
+ def __call__(self, other: signedinteger[Any], /) -> signedinteger[Any]: ...
177
+ @overload
178
+ def __call__(
179
+ self, other: unsignedinteger[_NBit2], /
180
+ ) -> unsignedinteger[_NBit1 | _NBit2]: ...
181
+
182
+ class _UnsignedIntMod(Protocol[_NBit1]):
183
+ @overload
184
+ def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
185
+ @overload
186
+ def __call__(
187
+ self, other: int | signedinteger[Any], /
188
+ ) -> Any: ...
189
+ @overload
190
+ def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
191
+ @overload
192
+ def __call__(
193
+ self, other: unsignedinteger[_NBit2], /
194
+ ) -> unsignedinteger[_NBit1 | _NBit2]: ...
195
+
196
+ class _UnsignedIntDivMod(Protocol[_NBit1]):
197
+ @overload
198
+ def __call__(self, other: bool, /) -> _2Tuple[signedinteger[_NBit1]]: ...
199
+ @overload
200
+ def __call__(
201
+ self, other: int | signedinteger[Any], /
202
+ ) -> _2Tuple[Any]: ...
203
+ @overload
204
+ def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
205
+ @overload
206
+ def __call__(
207
+ self, other: unsignedinteger[_NBit2], /
208
+ ) -> _2Tuple[unsignedinteger[_NBit1 | _NBit2]]: ...
209
+
210
+ class _SignedIntOp(Protocol[_NBit1]):
211
+ @overload
212
+ def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
213
+ @overload
214
+ def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
215
+ @overload
216
+ def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
217
+ @overload
218
+ def __call__(
219
+ self, other: complex, /,
220
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
221
+ @overload
222
+ def __call__(
223
+ self, other: signedinteger[_NBit2], /,
224
+ ) -> signedinteger[_NBit1 | _NBit2]: ...
225
+
226
+ class _SignedIntBitOp(Protocol[_NBit1]):
227
+ @overload
228
+ def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
229
+ @overload
230
+ def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
231
+ @overload
232
+ def __call__(
233
+ self, other: signedinteger[_NBit2], /,
234
+ ) -> signedinteger[_NBit1 | _NBit2]: ...
235
+
236
+ class _SignedIntMod(Protocol[_NBit1]):
237
+ @overload
238
+ def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
239
+ @overload
240
+ def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
241
+ @overload
242
+ def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
243
+ @overload
244
+ def __call__(
245
+ self, other: signedinteger[_NBit2], /,
246
+ ) -> signedinteger[_NBit1 | _NBit2]: ...
247
+
248
+ class _SignedIntDivMod(Protocol[_NBit1]):
249
+ @overload
250
+ def __call__(self, other: bool, /) -> _2Tuple[signedinteger[_NBit1]]: ...
251
+ @overload
252
+ def __call__(self, other: int, /) -> _2Tuple[signedinteger[_NBit1 | _NBitInt]]: ...
253
+ @overload
254
+ def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
255
+ @overload
256
+ def __call__(
257
+ self, other: signedinteger[_NBit2], /,
258
+ ) -> _2Tuple[signedinteger[_NBit1 | _NBit2]]: ...
259
+
260
+ class _FloatOp(Protocol[_NBit1]):
261
+ @overload
262
+ def __call__(self, other: bool, /) -> floating[_NBit1]: ...
263
+ @overload
264
+ def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
265
+ @overload
266
+ def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
267
+ @overload
268
+ def __call__(
269
+ self, other: complex, /,
270
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
271
+ @overload
272
+ def __call__(
273
+ self, other: integer[_NBit2] | floating[_NBit2], /
274
+ ) -> floating[_NBit1 | _NBit2]: ...
275
+
276
+ class _FloatMod(Protocol[_NBit1]):
277
+ @overload
278
+ def __call__(self, other: bool, /) -> floating[_NBit1]: ...
279
+ @overload
280
+ def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
281
+ @overload
282
+ def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
283
+ @overload
284
+ def __call__(
285
+ self, other: integer[_NBit2] | floating[_NBit2], /
286
+ ) -> floating[_NBit1 | _NBit2]: ...
287
+
288
+ class _FloatDivMod(Protocol[_NBit1]):
289
+ @overload
290
+ def __call__(self, other: bool, /) -> _2Tuple[floating[_NBit1]]: ...
291
+ @overload
292
+ def __call__(self, other: int, /) -> _2Tuple[floating[_NBit1 | _NBitInt]]: ...
293
+ @overload
294
+ def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
295
+ @overload
296
+ def __call__(
297
+ self, other: integer[_NBit2] | floating[_NBit2], /
298
+ ) -> _2Tuple[floating[_NBit1 | _NBit2]]: ...
299
+
300
+ class _ComplexOp(Protocol[_NBit1]):
301
+ @overload
302
+ def __call__(self, other: bool, /) -> complexfloating[_NBit1, _NBit1]: ...
303
+ @overload
304
+ def __call__(self, other: int, /) -> complexfloating[_NBit1 | _NBitInt, _NBit1 | _NBitInt]: ...
305
+ @overload
306
+ def __call__(
307
+ self, other: complex, /,
308
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
309
+ @overload
310
+ def __call__(
311
+ self,
312
+ other: (
313
+ integer[_NBit2]
314
+ | floating[_NBit2]
315
+ | complexfloating[_NBit2, _NBit2]
316
+ ), /,
317
+ ) -> complexfloating[_NBit1 | _NBit2, _NBit1 | _NBit2]: ...
318
+
319
+ class _NumberOp(Protocol):
320
+ def __call__(self, other: _NumberLike_co, /) -> Any: ...
321
+
322
+ class _SupportsLT(Protocol):
323
+ def __lt__(self, other: Any, /) -> object: ...
324
+
325
+ class _SupportsGT(Protocol):
326
+ def __gt__(self, other: Any, /) -> object: ...
327
+
328
+ class _ComparisonOp(Protocol[_T1_contra, _T2_contra]):
329
+ @overload
330
+ def __call__(self, other: _T1_contra, /) -> bool_: ...
331
+ @overload
332
+ def __call__(self, other: _T2_contra, /) -> NDArray[bool_]: ...
333
+ @overload
334
+ def __call__(
335
+ self,
336
+ other: _SupportsLT | _SupportsGT | _NestedSequence[_SupportsLT | _SupportsGT],
337
+ /,
338
+ ) -> Any: ...
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_char_codes.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+
3
+ _BoolCodes = Literal["?", "=?", "<?", ">?", "bool", "bool_", "bool8"]
4
+
5
+ _UInt8Codes = Literal["uint8", "u1", "=u1", "<u1", ">u1"]
6
+ _UInt16Codes = Literal["uint16", "u2", "=u2", "<u2", ">u2"]
7
+ _UInt32Codes = Literal["uint32", "u4", "=u4", "<u4", ">u4"]
8
+ _UInt64Codes = Literal["uint64", "u8", "=u8", "<u8", ">u8"]
9
+
10
+ _Int8Codes = Literal["int8", "i1", "=i1", "<i1", ">i1"]
11
+ _Int16Codes = Literal["int16", "i2", "=i2", "<i2", ">i2"]
12
+ _Int32Codes = Literal["int32", "i4", "=i4", "<i4", ">i4"]
13
+ _Int64Codes = Literal["int64", "i8", "=i8", "<i8", ">i8"]
14
+
15
+ _Float16Codes = Literal["float16", "f2", "=f2", "<f2", ">f2"]
16
+ _Float32Codes = Literal["float32", "f4", "=f4", "<f4", ">f4"]
17
+ _Float64Codes = Literal["float64", "f8", "=f8", "<f8", ">f8"]
18
+
19
+ _Complex64Codes = Literal["complex64", "c8", "=c8", "<c8", ">c8"]
20
+ _Complex128Codes = Literal["complex128", "c16", "=c16", "<c16", ">c16"]
21
+
22
+ _ByteCodes = Literal["byte", "b", "=b", "<b", ">b"]
23
+ _ShortCodes = Literal["short", "h", "=h", "<h", ">h"]
24
+ _IntCCodes = Literal["intc", "i", "=i", "<i", ">i"]
25
+ _IntPCodes = Literal["intp", "int0", "p", "=p", "<p", ">p"]
26
+ _IntCodes = Literal["long", "int", "int_", "l", "=l", "<l", ">l"]
27
+ _LongLongCodes = Literal["longlong", "q", "=q", "<q", ">q"]
28
+
29
+ _UByteCodes = Literal["ubyte", "B", "=B", "<B", ">B"]
30
+ _UShortCodes = Literal["ushort", "H", "=H", "<H", ">H"]
31
+ _UIntCCodes = Literal["uintc", "I", "=I", "<I", ">I"]
32
+ _UIntPCodes = Literal["uintp", "uint0", "P", "=P", "<P", ">P"]
33
+ _UIntCodes = Literal["ulong", "uint", "L", "=L", "<L", ">L"]
34
+ _ULongLongCodes = Literal["ulonglong", "Q", "=Q", "<Q", ">Q"]
35
+
36
+ _HalfCodes = Literal["half", "e", "=e", "<e", ">e"]
37
+ _SingleCodes = Literal["single", "f", "=f", "<f", ">f"]
38
+ _DoubleCodes = Literal["double", "float", "float_", "d", "=d", "<d", ">d"]
39
+ _LongDoubleCodes = Literal["longdouble", "longfloat", "g", "=g", "<g", ">g"]
40
+
41
+ _CSingleCodes = Literal["csingle", "singlecomplex", "F", "=F", "<F", ">F"]
42
+ _CDoubleCodes = Literal["cdouble", "complex", "complex_", "cfloat", "D", "=D", "<D", ">D"]
43
+ _CLongDoubleCodes = Literal["clongdouble", "clongfloat", "longcomplex", "G", "=G", "<G", ">G"]
44
+
45
+ _StrCodes = Literal["str", "str_", "str0", "unicode", "unicode_", "U", "=U", "<U", ">U"]
46
+ _BytesCodes = Literal["bytes", "bytes_", "bytes0", "S", "=S", "<S", ">S"]
47
+ _VoidCodes = Literal["void", "void0", "V", "=V", "<V", ">V"]
48
+ _ObjectCodes = Literal["object", "object_", "O", "=O", "<O", ">O"]
49
+
50
+ _DT64Codes = Literal[
51
+ "datetime64", "=datetime64", "<datetime64", ">datetime64",
52
+ "datetime64[Y]", "=datetime64[Y]", "<datetime64[Y]", ">datetime64[Y]",
53
+ "datetime64[M]", "=datetime64[M]", "<datetime64[M]", ">datetime64[M]",
54
+ "datetime64[W]", "=datetime64[W]", "<datetime64[W]", ">datetime64[W]",
55
+ "datetime64[D]", "=datetime64[D]", "<datetime64[D]", ">datetime64[D]",
56
+ "datetime64[h]", "=datetime64[h]", "<datetime64[h]", ">datetime64[h]",
57
+ "datetime64[m]", "=datetime64[m]", "<datetime64[m]", ">datetime64[m]",
58
+ "datetime64[s]", "=datetime64[s]", "<datetime64[s]", ">datetime64[s]",
59
+ "datetime64[ms]", "=datetime64[ms]", "<datetime64[ms]", ">datetime64[ms]",
60
+ "datetime64[us]", "=datetime64[us]", "<datetime64[us]", ">datetime64[us]",
61
+ "datetime64[ns]", "=datetime64[ns]", "<datetime64[ns]", ">datetime64[ns]",
62
+ "datetime64[ps]", "=datetime64[ps]", "<datetime64[ps]", ">datetime64[ps]",
63
+ "datetime64[fs]", "=datetime64[fs]", "<datetime64[fs]", ">datetime64[fs]",
64
+ "datetime64[as]", "=datetime64[as]", "<datetime64[as]", ">datetime64[as]",
65
+ "M", "=M", "<M", ">M",
66
+ "M8", "=M8", "<M8", ">M8",
67
+ "M8[Y]", "=M8[Y]", "<M8[Y]", ">M8[Y]",
68
+ "M8[M]", "=M8[M]", "<M8[M]", ">M8[M]",
69
+ "M8[W]", "=M8[W]", "<M8[W]", ">M8[W]",
70
+ "M8[D]", "=M8[D]", "<M8[D]", ">M8[D]",
71
+ "M8[h]", "=M8[h]", "<M8[h]", ">M8[h]",
72
+ "M8[m]", "=M8[m]", "<M8[m]", ">M8[m]",
73
+ "M8[s]", "=M8[s]", "<M8[s]", ">M8[s]",
74
+ "M8[ms]", "=M8[ms]", "<M8[ms]", ">M8[ms]",
75
+ "M8[us]", "=M8[us]", "<M8[us]", ">M8[us]",
76
+ "M8[ns]", "=M8[ns]", "<M8[ns]", ">M8[ns]",
77
+ "M8[ps]", "=M8[ps]", "<M8[ps]", ">M8[ps]",
78
+ "M8[fs]", "=M8[fs]", "<M8[fs]", ">M8[fs]",
79
+ "M8[as]", "=M8[as]", "<M8[as]", ">M8[as]",
80
+ ]
81
+ _TD64Codes = Literal[
82
+ "timedelta64", "=timedelta64", "<timedelta64", ">timedelta64",
83
+ "timedelta64[Y]", "=timedelta64[Y]", "<timedelta64[Y]", ">timedelta64[Y]",
84
+ "timedelta64[M]", "=timedelta64[M]", "<timedelta64[M]", ">timedelta64[M]",
85
+ "timedelta64[W]", "=timedelta64[W]", "<timedelta64[W]", ">timedelta64[W]",
86
+ "timedelta64[D]", "=timedelta64[D]", "<timedelta64[D]", ">timedelta64[D]",
87
+ "timedelta64[h]", "=timedelta64[h]", "<timedelta64[h]", ">timedelta64[h]",
88
+ "timedelta64[m]", "=timedelta64[m]", "<timedelta64[m]", ">timedelta64[m]",
89
+ "timedelta64[s]", "=timedelta64[s]", "<timedelta64[s]", ">timedelta64[s]",
90
+ "timedelta64[ms]", "=timedelta64[ms]", "<timedelta64[ms]", ">timedelta64[ms]",
91
+ "timedelta64[us]", "=timedelta64[us]", "<timedelta64[us]", ">timedelta64[us]",
92
+ "timedelta64[ns]", "=timedelta64[ns]", "<timedelta64[ns]", ">timedelta64[ns]",
93
+ "timedelta64[ps]", "=timedelta64[ps]", "<timedelta64[ps]", ">timedelta64[ps]",
94
+ "timedelta64[fs]", "=timedelta64[fs]", "<timedelta64[fs]", ">timedelta64[fs]",
95
+ "timedelta64[as]", "=timedelta64[as]", "<timedelta64[as]", ">timedelta64[as]",
96
+ "m", "=m", "<m", ">m",
97
+ "m8", "=m8", "<m8", ">m8",
98
+ "m8[Y]", "=m8[Y]", "<m8[Y]", ">m8[Y]",
99
+ "m8[M]", "=m8[M]", "<m8[M]", ">m8[M]",
100
+ "m8[W]", "=m8[W]", "<m8[W]", ">m8[W]",
101
+ "m8[D]", "=m8[D]", "<m8[D]", ">m8[D]",
102
+ "m8[h]", "=m8[h]", "<m8[h]", ">m8[h]",
103
+ "m8[m]", "=m8[m]", "<m8[m]", ">m8[m]",
104
+ "m8[s]", "=m8[s]", "<m8[s]", ">m8[s]",
105
+ "m8[ms]", "=m8[ms]", "<m8[ms]", ">m8[ms]",
106
+ "m8[us]", "=m8[us]", "<m8[us]", ">m8[us]",
107
+ "m8[ns]", "=m8[ns]", "<m8[ns]", ">m8[ns]",
108
+ "m8[ps]", "=m8[ps]", "<m8[ps]", ">m8[ps]",
109
+ "m8[fs]", "=m8[fs]", "<m8[fs]", ">m8[fs]",
110
+ "m8[as]", "=m8[as]", "<m8[as]", ">m8[as]",
111
+ ]
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_dtype_like.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ from typing import (
3
+ Any,
4
+ Sequence,
5
+ Union,
6
+ TypeVar,
7
+ Protocol,
8
+ TypedDict,
9
+ runtime_checkable,
10
+ )
11
+
12
+ import numpy as np
13
+
14
+ from ._shape import _ShapeLike
15
+
16
+ from ._char_codes import (
17
+ _BoolCodes,
18
+ _UInt8Codes,
19
+ _UInt16Codes,
20
+ _UInt32Codes,
21
+ _UInt64Codes,
22
+ _Int8Codes,
23
+ _Int16Codes,
24
+ _Int32Codes,
25
+ _Int64Codes,
26
+ _Float16Codes,
27
+ _Float32Codes,
28
+ _Float64Codes,
29
+ _Complex64Codes,
30
+ _Complex128Codes,
31
+ _ByteCodes,
32
+ _ShortCodes,
33
+ _IntCCodes,
34
+ _IntPCodes,
35
+ _IntCodes,
36
+ _LongLongCodes,
37
+ _UByteCodes,
38
+ _UShortCodes,
39
+ _UIntCCodes,
40
+ _UIntPCodes,
41
+ _UIntCodes,
42
+ _ULongLongCodes,
43
+ _HalfCodes,
44
+ _SingleCodes,
45
+ _DoubleCodes,
46
+ _LongDoubleCodes,
47
+ _CSingleCodes,
48
+ _CDoubleCodes,
49
+ _CLongDoubleCodes,
50
+ _DT64Codes,
51
+ _TD64Codes,
52
+ _StrCodes,
53
+ _BytesCodes,
54
+ _VoidCodes,
55
+ _ObjectCodes,
56
+ )
57
+
58
+ _SCT = TypeVar("_SCT", bound=np.generic)
59
+ _DType_co = TypeVar("_DType_co", covariant=True, bound=np.dtype[Any])
60
+
61
+ _DTypeLikeNested = Any # TODO: wait for support for recursive types
62
+
63
+
64
+ # Mandatory keys
65
+ class _DTypeDictBase(TypedDict):
66
+ names: Sequence[str]
67
+ formats: Sequence[_DTypeLikeNested]
68
+
69
+
70
+ # Mandatory + optional keys
71
+ class _DTypeDict(_DTypeDictBase, total=False):
72
+ # Only `str` elements are usable as indexing aliases,
73
+ # but `titles` can in principle accept any object
74
+ offsets: Sequence[int]
75
+ titles: Sequence[Any]
76
+ itemsize: int
77
+ aligned: bool
78
+
79
+
80
+ # A protocol for anything with the dtype attribute
81
+ @runtime_checkable
82
+ class _SupportsDType(Protocol[_DType_co]):
83
+ @property
84
+ def dtype(self) -> _DType_co: ...
85
+
86
+
87
+ # A subset of `npt.DTypeLike` that can be parametrized w.r.t. `np.generic`
88
+ _DTypeLike = Union[
89
+ np.dtype[_SCT],
90
+ type[_SCT],
91
+ _SupportsDType[np.dtype[_SCT]],
92
+ ]
93
+
94
+
95
+ # Would create a dtype[np.void]
96
+ _VoidDTypeLike = Union[
97
+ # (flexible_dtype, itemsize)
98
+ tuple[_DTypeLikeNested, int],
99
+ # (fixed_dtype, shape)
100
+ tuple[_DTypeLikeNested, _ShapeLike],
101
+ # [(field_name, field_dtype, field_shape), ...]
102
+ #
103
+ # The type here is quite broad because NumPy accepts quite a wide
104
+ # range of inputs inside the list; see the tests for some
105
+ # examples.
106
+ list[Any],
107
+ # {'names': ..., 'formats': ..., 'offsets': ..., 'titles': ...,
108
+ # 'itemsize': ...}
109
+ _DTypeDict,
110
+ # (base_dtype, new_dtype)
111
+ tuple[_DTypeLikeNested, _DTypeLikeNested],
112
+ ]
113
+
114
+ # Anything that can be coerced into numpy.dtype.
115
+ # Reference: https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html
116
+ DTypeLike = Union[
117
+ np.dtype[Any],
118
+ # default data type (float64)
119
+ None,
120
+ # array-scalar types and generic types
121
+ type[Any], # NOTE: We're stuck with `type[Any]` due to object dtypes
122
+ # anything with a dtype attribute
123
+ _SupportsDType[np.dtype[Any]],
124
+ # character codes, type strings or comma-separated fields, e.g., 'float64'
125
+ str,
126
+ _VoidDTypeLike,
127
+ ]
128
+
129
+ # NOTE: while it is possible to provide the dtype as a dict of
130
+ # dtype-like objects (e.g. `{'field1': ..., 'field2': ..., ...}`),
131
+ # this syntax is officially discourged and
132
+ # therefore not included in the Union defining `DTypeLike`.
133
+ #
134
+ # See https://github.com/numpy/numpy/issues/16891 for more details.
135
+
136
+ # Aliases for commonly used dtype-like objects.
137
+ # Note that the precision of `np.number` subclasses is ignored herein.
138
+ _DTypeLikeBool = Union[
139
+ type[bool],
140
+ type[np.bool_],
141
+ np.dtype[np.bool_],
142
+ _SupportsDType[np.dtype[np.bool_]],
143
+ _BoolCodes,
144
+ ]
145
+ _DTypeLikeUInt = Union[
146
+ type[np.unsignedinteger],
147
+ np.dtype[np.unsignedinteger],
148
+ _SupportsDType[np.dtype[np.unsignedinteger]],
149
+ _UInt8Codes,
150
+ _UInt16Codes,
151
+ _UInt32Codes,
152
+ _UInt64Codes,
153
+ _UByteCodes,
154
+ _UShortCodes,
155
+ _UIntCCodes,
156
+ _UIntPCodes,
157
+ _UIntCodes,
158
+ _ULongLongCodes,
159
+ ]
160
+ _DTypeLikeInt = Union[
161
+ type[int],
162
+ type[np.signedinteger],
163
+ np.dtype[np.signedinteger],
164
+ _SupportsDType[np.dtype[np.signedinteger]],
165
+ _Int8Codes,
166
+ _Int16Codes,
167
+ _Int32Codes,
168
+ _Int64Codes,
169
+ _ByteCodes,
170
+ _ShortCodes,
171
+ _IntCCodes,
172
+ _IntPCodes,
173
+ _IntCodes,
174
+ _LongLongCodes,
175
+ ]
176
+ _DTypeLikeFloat = Union[
177
+ type[float],
178
+ type[np.floating],
179
+ np.dtype[np.floating],
180
+ _SupportsDType[np.dtype[np.floating]],
181
+ _Float16Codes,
182
+ _Float32Codes,
183
+ _Float64Codes,
184
+ _HalfCodes,
185
+ _SingleCodes,
186
+ _DoubleCodes,
187
+ _LongDoubleCodes,
188
+ ]
189
+ _DTypeLikeComplex = Union[
190
+ type[complex],
191
+ type[np.complexfloating],
192
+ np.dtype[np.complexfloating],
193
+ _SupportsDType[np.dtype[np.complexfloating]],
194
+ _Complex64Codes,
195
+ _Complex128Codes,
196
+ _CSingleCodes,
197
+ _CDoubleCodes,
198
+ _CLongDoubleCodes,
199
+ ]
200
+ _DTypeLikeDT64 = Union[
201
+ type[np.timedelta64],
202
+ np.dtype[np.timedelta64],
203
+ _SupportsDType[np.dtype[np.timedelta64]],
204
+ _TD64Codes,
205
+ ]
206
+ _DTypeLikeTD64 = Union[
207
+ type[np.datetime64],
208
+ np.dtype[np.datetime64],
209
+ _SupportsDType[np.dtype[np.datetime64]],
210
+ _DT64Codes,
211
+ ]
212
+ _DTypeLikeStr = Union[
213
+ type[str],
214
+ type[np.str_],
215
+ np.dtype[np.str_],
216
+ _SupportsDType[np.dtype[np.str_]],
217
+ _StrCodes,
218
+ ]
219
+ _DTypeLikeBytes = Union[
220
+ type[bytes],
221
+ type[np.bytes_],
222
+ np.dtype[np.bytes_],
223
+ _SupportsDType[np.dtype[np.bytes_]],
224
+ _BytesCodes,
225
+ ]
226
+ _DTypeLikeVoid = Union[
227
+ type[np.void],
228
+ np.dtype[np.void],
229
+ _SupportsDType[np.dtype[np.void]],
230
+ _VoidCodes,
231
+ _VoidDTypeLike,
232
+ ]
233
+ _DTypeLikeObject = Union[
234
+ type,
235
+ np.dtype[np.object_],
236
+ _SupportsDType[np.dtype[np.object_]],
237
+ _ObjectCodes,
238
+ ]
239
+
240
+ _DTypeLikeComplex_co = Union[
241
+ _DTypeLikeBool,
242
+ _DTypeLikeUInt,
243
+ _DTypeLikeInt,
244
+ _DTypeLikeFloat,
245
+ _DTypeLikeComplex,
246
+ ]
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_extended_precision.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module with platform-specific extended precision
2
+ `numpy.number` subclasses.
3
+
4
+ The subclasses are defined here (instead of ``__init__.pyi``) such
5
+ that they can be imported conditionally via the numpy's mypy plugin.
6
+ """
7
+
8
+ import numpy as np
9
+ from . import (
10
+ _80Bit,
11
+ _96Bit,
12
+ _128Bit,
13
+ _256Bit,
14
+ )
15
+
16
+ uint128 = np.unsignedinteger[_128Bit]
17
+ uint256 = np.unsignedinteger[_256Bit]
18
+ int128 = np.signedinteger[_128Bit]
19
+ int256 = np.signedinteger[_256Bit]
20
+ float80 = np.floating[_80Bit]
21
+ float96 = np.floating[_96Bit]
22
+ float128 = np.floating[_128Bit]
23
+ float256 = np.floating[_256Bit]
24
+ complex160 = np.complexfloating[_80Bit, _80Bit]
25
+ complex192 = np.complexfloating[_96Bit, _96Bit]
26
+ complex256 = np.complexfloating[_128Bit, _128Bit]
27
+ complex512 = np.complexfloating[_256Bit, _256Bit]
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_nbit.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module with the precisions of platform-specific `~numpy.number`s."""
2
+
3
+ from typing import Any
4
+
5
+ # To-be replaced with a `npt.NBitBase` subclass by numpy's mypy plugin
6
+ _NBitByte = Any
7
+ _NBitShort = Any
8
+ _NBitIntC = Any
9
+ _NBitIntP = Any
10
+ _NBitInt = Any
11
+ _NBitLongLong = Any
12
+
13
+ _NBitHalf = Any
14
+ _NBitSingle = Any
15
+ _NBitDouble = Any
16
+ _NBitLongDouble = Any
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_nested_sequence.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module containing the `_NestedSequence` protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from typing import (
7
+ Any,
8
+ TypeVar,
9
+ Protocol,
10
+ runtime_checkable,
11
+ )
12
+
13
+ __all__ = ["_NestedSequence"]
14
+
15
+ _T_co = TypeVar("_T_co", covariant=True)
16
+
17
+
18
+ @runtime_checkable
19
+ class _NestedSequence(Protocol[_T_co]):
20
+ """A protocol for representing nested sequences.
21
+
22
+ Warning
23
+ -------
24
+ `_NestedSequence` currently does not work in combination with typevars,
25
+ *e.g.* ``def func(a: _NestedSequnce[T]) -> T: ...``.
26
+
27
+ See Also
28
+ --------
29
+ collections.abc.Sequence
30
+ ABCs for read-only and mutable :term:`sequences`.
31
+
32
+ Examples
33
+ --------
34
+ .. code-block:: python
35
+
36
+ >>> from __future__ import annotations
37
+
38
+ >>> from typing import TYPE_CHECKING
39
+ >>> import numpy as np
40
+ >>> from numpy._typing import _NestedSequence
41
+
42
+ >>> def get_dtype(seq: _NestedSequence[float]) -> np.dtype[np.float64]:
43
+ ... return np.asarray(seq).dtype
44
+
45
+ >>> a = get_dtype([1.0])
46
+ >>> b = get_dtype([[1.0]])
47
+ >>> c = get_dtype([[[1.0]]])
48
+ >>> d = get_dtype([[[[1.0]]]])
49
+
50
+ >>> if TYPE_CHECKING:
51
+ ... reveal_locals()
52
+ ... # note: Revealed local types are:
53
+ ... # note: a: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
54
+ ... # note: b: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
55
+ ... # note: c: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
56
+ ... # note: d: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
57
+
58
+ """
59
+
60
+ def __len__(self, /) -> int:
61
+ """Implement ``len(self)``."""
62
+ raise NotImplementedError
63
+
64
+ def __getitem__(self, index: int, /) -> _T_co | _NestedSequence[_T_co]:
65
+ """Implement ``self[x]``."""
66
+ raise NotImplementedError
67
+
68
+ def __contains__(self, x: object, /) -> bool:
69
+ """Implement ``x in self``."""
70
+ raise NotImplementedError
71
+
72
+ def __iter__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]:
73
+ """Implement ``iter(self)``."""
74
+ raise NotImplementedError
75
+
76
+ def __reversed__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]:
77
+ """Implement ``reversed(self)``."""
78
+ raise NotImplementedError
79
+
80
+ def count(self, value: Any, /) -> int:
81
+ """Return the number of occurrences of `value`."""
82
+ raise NotImplementedError
83
+
84
+ def index(self, value: Any, /) -> int:
85
+ """Return the first index of `value`."""
86
+ raise NotImplementedError
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_scalars.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Any
2
+
3
+ import numpy as np
4
+
5
+ # NOTE: `_StrLike_co` and `_BytesLike_co` are pointless, as `np.str_` and
6
+ # `np.bytes_` are already subclasses of their builtin counterpart
7
+
8
+ _CharLike_co = Union[str, bytes]
9
+
10
+ # The 6 `<X>Like_co` type-aliases below represent all scalars that can be
11
+ # coerced into `<X>` (with the casting rule `same_kind`)
12
+ _BoolLike_co = Union[bool, np.bool_]
13
+ _UIntLike_co = Union[_BoolLike_co, np.unsignedinteger[Any]]
14
+ _IntLike_co = Union[_BoolLike_co, int, np.integer[Any]]
15
+ _FloatLike_co = Union[_IntLike_co, float, np.floating[Any]]
16
+ _ComplexLike_co = Union[_FloatLike_co, complex, np.complexfloating[Any, Any]]
17
+ _TD64Like_co = Union[_IntLike_co, np.timedelta64]
18
+
19
+ _NumberLike_co = Union[int, float, complex, np.number[Any], np.bool_]
20
+ _ScalarLike_co = Union[
21
+ int,
22
+ float,
23
+ complex,
24
+ str,
25
+ bytes,
26
+ np.generic,
27
+ ]
28
+
29
+ # `_VoidLike_co` is technically not a scalar, but it's close enough
30
+ _VoidLike_co = Union[tuple[Any, ...], np.void]
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_shape.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ from typing import Union, SupportsIndex
3
+
4
+ _Shape = tuple[int, ...]
5
+
6
+ # Anything that can be coerced to a shape tuple
7
+ _ShapeLike = Union[SupportsIndex, Sequence[SupportsIndex]]
env-llmeval/lib/python3.10/site-packages/numpy/_typing/_ufunc.pyi ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module with private type-check-only `numpy.ufunc` subclasses.
2
+
3
+ The signatures of the ufuncs are too varied to reasonably type
4
+ with a single class. So instead, `ufunc` has been expanded into
5
+ four private subclasses, one for each combination of
6
+ `~ufunc.nin` and `~ufunc.nout`.
7
+
8
+ """
9
+
10
+ from typing import (
11
+ Any,
12
+ Generic,
13
+ overload,
14
+ TypeVar,
15
+ Literal,
16
+ SupportsIndex,
17
+ Protocol,
18
+ )
19
+
20
+ from numpy import ufunc, _CastingKind, _OrderKACF
21
+ from numpy.typing import NDArray
22
+
23
+ from ._shape import _ShapeLike
24
+ from ._scalars import _ScalarLike_co
25
+ from ._array_like import ArrayLike, _ArrayLikeBool_co, _ArrayLikeInt_co
26
+ from ._dtype_like import DTypeLike
27
+
28
+ _T = TypeVar("_T")
29
+ _2Tuple = tuple[_T, _T]
30
+ _3Tuple = tuple[_T, _T, _T]
31
+ _4Tuple = tuple[_T, _T, _T, _T]
32
+
33
+ _NTypes = TypeVar("_NTypes", bound=int)
34
+ _IDType = TypeVar("_IDType", bound=Any)
35
+ _NameType = TypeVar("_NameType", bound=str)
36
+
37
+
38
+ class _SupportsArrayUFunc(Protocol):
39
+ def __array_ufunc__(
40
+ self,
41
+ ufunc: ufunc,
42
+ method: Literal["__call__", "reduce", "reduceat", "accumulate", "outer", "inner"],
43
+ *inputs: Any,
44
+ **kwargs: Any,
45
+ ) -> Any: ...
46
+
47
+
48
+ # NOTE: In reality `extobj` should be a length of list 3 containing an
49
+ # int, an int, and a callable, but there's no way to properly express
50
+ # non-homogenous lists.
51
+ # Use `Any` over `Union` to avoid issues related to lists invariance.
52
+
53
+ # NOTE: `reduce`, `accumulate`, `reduceat` and `outer` raise a ValueError for
54
+ # ufuncs that don't accept two input arguments and return one output argument.
55
+ # In such cases the respective methods are simply typed as `None`.
56
+
57
+ # NOTE: Similarly, `at` won't be defined for ufuncs that return
58
+ # multiple outputs; in such cases `at` is typed as `None`
59
+
60
+ # NOTE: If 2 output types are returned then `out` must be a
61
+ # 2-tuple of arrays. Otherwise `None` or a plain array are also acceptable
62
+
63
+ class _UFunc_Nin1_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
64
+ @property
65
+ def __name__(self) -> _NameType: ...
66
+ @property
67
+ def ntypes(self) -> _NTypes: ...
68
+ @property
69
+ def identity(self) -> _IDType: ...
70
+ @property
71
+ def nin(self) -> Literal[1]: ...
72
+ @property
73
+ def nout(self) -> Literal[1]: ...
74
+ @property
75
+ def nargs(self) -> Literal[2]: ...
76
+ @property
77
+ def signature(self) -> None: ...
78
+ @property
79
+ def reduce(self) -> None: ...
80
+ @property
81
+ def accumulate(self) -> None: ...
82
+ @property
83
+ def reduceat(self) -> None: ...
84
+ @property
85
+ def outer(self) -> None: ...
86
+
87
+ @overload
88
+ def __call__(
89
+ self,
90
+ __x1: _ScalarLike_co,
91
+ out: None = ...,
92
+ *,
93
+ where: None | _ArrayLikeBool_co = ...,
94
+ casting: _CastingKind = ...,
95
+ order: _OrderKACF = ...,
96
+ dtype: DTypeLike = ...,
97
+ subok: bool = ...,
98
+ signature: str | _2Tuple[None | str] = ...,
99
+ extobj: list[Any] = ...,
100
+ ) -> Any: ...
101
+ @overload
102
+ def __call__(
103
+ self,
104
+ __x1: ArrayLike,
105
+ out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
106
+ *,
107
+ where: None | _ArrayLikeBool_co = ...,
108
+ casting: _CastingKind = ...,
109
+ order: _OrderKACF = ...,
110
+ dtype: DTypeLike = ...,
111
+ subok: bool = ...,
112
+ signature: str | _2Tuple[None | str] = ...,
113
+ extobj: list[Any] = ...,
114
+ ) -> NDArray[Any]: ...
115
+ @overload
116
+ def __call__(
117
+ self,
118
+ __x1: _SupportsArrayUFunc,
119
+ out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
120
+ *,
121
+ where: None | _ArrayLikeBool_co = ...,
122
+ casting: _CastingKind = ...,
123
+ order: _OrderKACF = ...,
124
+ dtype: DTypeLike = ...,
125
+ subok: bool = ...,
126
+ signature: str | _2Tuple[None | str] = ...,
127
+ extobj: list[Any] = ...,
128
+ ) -> Any: ...
129
+
130
+ def at(
131
+ self,
132
+ a: _SupportsArrayUFunc,
133
+ indices: _ArrayLikeInt_co,
134
+ /,
135
+ ) -> None: ...
136
+
137
+ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
138
+ @property
139
+ def __name__(self) -> _NameType: ...
140
+ @property
141
+ def ntypes(self) -> _NTypes: ...
142
+ @property
143
+ def identity(self) -> _IDType: ...
144
+ @property
145
+ def nin(self) -> Literal[2]: ...
146
+ @property
147
+ def nout(self) -> Literal[1]: ...
148
+ @property
149
+ def nargs(self) -> Literal[3]: ...
150
+ @property
151
+ def signature(self) -> None: ...
152
+
153
+ @overload
154
+ def __call__(
155
+ self,
156
+ __x1: _ScalarLike_co,
157
+ __x2: _ScalarLike_co,
158
+ out: None = ...,
159
+ *,
160
+ where: None | _ArrayLikeBool_co = ...,
161
+ casting: _CastingKind = ...,
162
+ order: _OrderKACF = ...,
163
+ dtype: DTypeLike = ...,
164
+ subok: bool = ...,
165
+ signature: str | _3Tuple[None | str] = ...,
166
+ extobj: list[Any] = ...,
167
+ ) -> Any: ...
168
+ @overload
169
+ def __call__(
170
+ self,
171
+ __x1: ArrayLike,
172
+ __x2: ArrayLike,
173
+ out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
174
+ *,
175
+ where: None | _ArrayLikeBool_co = ...,
176
+ casting: _CastingKind = ...,
177
+ order: _OrderKACF = ...,
178
+ dtype: DTypeLike = ...,
179
+ subok: bool = ...,
180
+ signature: str | _3Tuple[None | str] = ...,
181
+ extobj: list[Any] = ...,
182
+ ) -> NDArray[Any]: ...
183
+
184
+ def at(
185
+ self,
186
+ a: NDArray[Any],
187
+ indices: _ArrayLikeInt_co,
188
+ b: ArrayLike,
189
+ /,
190
+ ) -> None: ...
191
+
192
+ def reduce(
193
+ self,
194
+ array: ArrayLike,
195
+ axis: None | _ShapeLike = ...,
196
+ dtype: DTypeLike = ...,
197
+ out: None | NDArray[Any] = ...,
198
+ keepdims: bool = ...,
199
+ initial: Any = ...,
200
+ where: _ArrayLikeBool_co = ...,
201
+ ) -> Any: ...
202
+
203
+ def accumulate(
204
+ self,
205
+ array: ArrayLike,
206
+ axis: SupportsIndex = ...,
207
+ dtype: DTypeLike = ...,
208
+ out: None | NDArray[Any] = ...,
209
+ ) -> NDArray[Any]: ...
210
+
211
+ def reduceat(
212
+ self,
213
+ array: ArrayLike,
214
+ indices: _ArrayLikeInt_co,
215
+ axis: SupportsIndex = ...,
216
+ dtype: DTypeLike = ...,
217
+ out: None | NDArray[Any] = ...,
218
+ ) -> NDArray[Any]: ...
219
+
220
+ # Expand `**kwargs` into explicit keyword-only arguments
221
+ @overload
222
+ def outer(
223
+ self,
224
+ A: _ScalarLike_co,
225
+ B: _ScalarLike_co,
226
+ /, *,
227
+ out: None = ...,
228
+ where: None | _ArrayLikeBool_co = ...,
229
+ casting: _CastingKind = ...,
230
+ order: _OrderKACF = ...,
231
+ dtype: DTypeLike = ...,
232
+ subok: bool = ...,
233
+ signature: str | _3Tuple[None | str] = ...,
234
+ extobj: list[Any] = ...,
235
+ ) -> Any: ...
236
+ @overload
237
+ def outer( # type: ignore[misc]
238
+ self,
239
+ A: ArrayLike,
240
+ B: ArrayLike,
241
+ /, *,
242
+ out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
243
+ where: None | _ArrayLikeBool_co = ...,
244
+ casting: _CastingKind = ...,
245
+ order: _OrderKACF = ...,
246
+ dtype: DTypeLike = ...,
247
+ subok: bool = ...,
248
+ signature: str | _3Tuple[None | str] = ...,
249
+ extobj: list[Any] = ...,
250
+ ) -> NDArray[Any]: ...
251
+
252
+ class _UFunc_Nin1_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
253
+ @property
254
+ def __name__(self) -> _NameType: ...
255
+ @property
256
+ def ntypes(self) -> _NTypes: ...
257
+ @property
258
+ def identity(self) -> _IDType: ...
259
+ @property
260
+ def nin(self) -> Literal[1]: ...
261
+ @property
262
+ def nout(self) -> Literal[2]: ...
263
+ @property
264
+ def nargs(self) -> Literal[3]: ...
265
+ @property
266
+ def signature(self) -> None: ...
267
+ @property
268
+ def at(self) -> None: ...
269
+ @property
270
+ def reduce(self) -> None: ...
271
+ @property
272
+ def accumulate(self) -> None: ...
273
+ @property
274
+ def reduceat(self) -> None: ...
275
+ @property
276
+ def outer(self) -> None: ...
277
+
278
+ @overload
279
+ def __call__(
280
+ self,
281
+ __x1: _ScalarLike_co,
282
+ __out1: None = ...,
283
+ __out2: None = ...,
284
+ *,
285
+ where: None | _ArrayLikeBool_co = ...,
286
+ casting: _CastingKind = ...,
287
+ order: _OrderKACF = ...,
288
+ dtype: DTypeLike = ...,
289
+ subok: bool = ...,
290
+ signature: str | _3Tuple[None | str] = ...,
291
+ extobj: list[Any] = ...,
292
+ ) -> _2Tuple[Any]: ...
293
+ @overload
294
+ def __call__(
295
+ self,
296
+ __x1: ArrayLike,
297
+ __out1: None | NDArray[Any] = ...,
298
+ __out2: None | NDArray[Any] = ...,
299
+ *,
300
+ out: _2Tuple[NDArray[Any]] = ...,
301
+ where: None | _ArrayLikeBool_co = ...,
302
+ casting: _CastingKind = ...,
303
+ order: _OrderKACF = ...,
304
+ dtype: DTypeLike = ...,
305
+ subok: bool = ...,
306
+ signature: str | _3Tuple[None | str] = ...,
307
+ extobj: list[Any] = ...,
308
+ ) -> _2Tuple[NDArray[Any]]: ...
309
+ @overload
310
+ def __call__(
311
+ self,
312
+ __x1: _SupportsArrayUFunc,
313
+ __out1: None | NDArray[Any] = ...,
314
+ __out2: None | NDArray[Any] = ...,
315
+ *,
316
+ out: _2Tuple[NDArray[Any]] = ...,
317
+ where: None | _ArrayLikeBool_co = ...,
318
+ casting: _CastingKind = ...,
319
+ order: _OrderKACF = ...,
320
+ dtype: DTypeLike = ...,
321
+ subok: bool = ...,
322
+ signature: str | _3Tuple[None | str] = ...,
323
+ extobj: list[Any] = ...,
324
+ ) -> _2Tuple[Any]: ...
325
+
326
+ class _UFunc_Nin2_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
327
+ @property
328
+ def __name__(self) -> _NameType: ...
329
+ @property
330
+ def ntypes(self) -> _NTypes: ...
331
+ @property
332
+ def identity(self) -> _IDType: ...
333
+ @property
334
+ def nin(self) -> Literal[2]: ...
335
+ @property
336
+ def nout(self) -> Literal[2]: ...
337
+ @property
338
+ def nargs(self) -> Literal[4]: ...
339
+ @property
340
+ def signature(self) -> None: ...
341
+ @property
342
+ def at(self) -> None: ...
343
+ @property
344
+ def reduce(self) -> None: ...
345
+ @property
346
+ def accumulate(self) -> None: ...
347
+ @property
348
+ def reduceat(self) -> None: ...
349
+ @property
350
+ def outer(self) -> None: ...
351
+
352
+ @overload
353
+ def __call__(
354
+ self,
355
+ __x1: _ScalarLike_co,
356
+ __x2: _ScalarLike_co,
357
+ __out1: None = ...,
358
+ __out2: None = ...,
359
+ *,
360
+ where: None | _ArrayLikeBool_co = ...,
361
+ casting: _CastingKind = ...,
362
+ order: _OrderKACF = ...,
363
+ dtype: DTypeLike = ...,
364
+ subok: bool = ...,
365
+ signature: str | _4Tuple[None | str] = ...,
366
+ extobj: list[Any] = ...,
367
+ ) -> _2Tuple[Any]: ...
368
+ @overload
369
+ def __call__(
370
+ self,
371
+ __x1: ArrayLike,
372
+ __x2: ArrayLike,
373
+ __out1: None | NDArray[Any] = ...,
374
+ __out2: None | NDArray[Any] = ...,
375
+ *,
376
+ out: _2Tuple[NDArray[Any]] = ...,
377
+ where: None | _ArrayLikeBool_co = ...,
378
+ casting: _CastingKind = ...,
379
+ order: _OrderKACF = ...,
380
+ dtype: DTypeLike = ...,
381
+ subok: bool = ...,
382
+ signature: str | _4Tuple[None | str] = ...,
383
+ extobj: list[Any] = ...,
384
+ ) -> _2Tuple[NDArray[Any]]: ...
385
+
386
+ class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
387
+ @property
388
+ def __name__(self) -> _NameType: ...
389
+ @property
390
+ def ntypes(self) -> _NTypes: ...
391
+ @property
392
+ def identity(self) -> _IDType: ...
393
+ @property
394
+ def nin(self) -> Literal[2]: ...
395
+ @property
396
+ def nout(self) -> Literal[1]: ...
397
+ @property
398
+ def nargs(self) -> Literal[3]: ...
399
+
400
+ # NOTE: In practice the only gufunc in the main namespace is `matmul`,
401
+ # so we can use its signature here
402
+ @property
403
+ def signature(self) -> Literal["(n?,k),(k,m?)->(n?,m?)"]: ...
404
+ @property
405
+ def reduce(self) -> None: ...
406
+ @property
407
+ def accumulate(self) -> None: ...
408
+ @property
409
+ def reduceat(self) -> None: ...
410
+ @property
411
+ def outer(self) -> None: ...
412
+ @property
413
+ def at(self) -> None: ...
414
+
415
+ # Scalar for 1D array-likes; ndarray otherwise
416
+ @overload
417
+ def __call__(
418
+ self,
419
+ __x1: ArrayLike,
420
+ __x2: ArrayLike,
421
+ out: None = ...,
422
+ *,
423
+ casting: _CastingKind = ...,
424
+ order: _OrderKACF = ...,
425
+ dtype: DTypeLike = ...,
426
+ subok: bool = ...,
427
+ signature: str | _3Tuple[None | str] = ...,
428
+ extobj: list[Any] = ...,
429
+ axes: list[_2Tuple[SupportsIndex]] = ...,
430
+ ) -> Any: ...
431
+ @overload
432
+ def __call__(
433
+ self,
434
+ __x1: ArrayLike,
435
+ __x2: ArrayLike,
436
+ out: NDArray[Any] | tuple[NDArray[Any]],
437
+ *,
438
+ casting: _CastingKind = ...,
439
+ order: _OrderKACF = ...,
440
+ dtype: DTypeLike = ...,
441
+ subok: bool = ...,
442
+ signature: str | _3Tuple[None | str] = ...,
443
+ extobj: list[Any] = ...,
444
+ axes: list[_2Tuple[SupportsIndex]] = ...,
445
+ ) -> NDArray[Any]: ...
env-llmeval/lib/python3.10/site-packages/numpy/_typing/setup.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ def configuration(parent_package='', top_path=None):
2
+ from numpy.distutils.misc_util import Configuration
3
+ config = Configuration('_typing', parent_package, top_path)
4
+ config.add_data_files('*.pyi')
5
+ return config
6
+
7
+
8
+ if __name__ == '__main__':
9
+ from numpy.distutils.core import setup
10
+ setup(configuration=configuration)
env-llmeval/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
env-llmeval/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): ...
env-llmeval/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc ADDED
Binary file (83.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (217 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (29.8 kB). View file
 
env-llmeval/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)
env-llmeval/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: ...
env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (183 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc ADDED
Binary file (824 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc ADDED
Binary file (65.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc ADDED
Binary file (4.63 kB). View file
 
env-llmeval/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')
env-llmeval/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)
env-llmeval/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)
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/__init__.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A sub-package for efficiently dealing with polynomials.
3
+
4
+ Within the documentation for this sub-package, a "finite power series,"
5
+ i.e., a polynomial (also referred to simply as a "series") is represented
6
+ by a 1-D numpy array of the polynomial's coefficients, ordered from lowest
7
+ order term to highest. For example, array([1,2,3]) represents
8
+ ``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial
9
+ applicable to the specific module in question, e.g., `polynomial` (which
10
+ "wraps" the "standard" basis) or `chebyshev`. For optimal performance,
11
+ all operations on polynomials, including evaluation at an argument, are
12
+ implemented as operations on the coefficients. Additional (module-specific)
13
+ information can be found in the docstring for the module of interest.
14
+
15
+ This package provides *convenience classes* for each of six different kinds
16
+ of polynomials:
17
+
18
+ ======================== ================
19
+ **Name** **Provides**
20
+ ======================== ================
21
+ `~polynomial.Polynomial` Power series
22
+ `~chebyshev.Chebyshev` Chebyshev series
23
+ `~legendre.Legendre` Legendre series
24
+ `~laguerre.Laguerre` Laguerre series
25
+ `~hermite.Hermite` Hermite series
26
+ `~hermite_e.HermiteE` HermiteE series
27
+ ======================== ================
28
+
29
+ These *convenience classes* provide a consistent interface for creating,
30
+ manipulating, and fitting data with polynomials of different bases.
31
+ The convenience classes are the preferred interface for the `~numpy.polynomial`
32
+ package, and are available from the ``numpy.polynomial`` namespace.
33
+ This eliminates the need to navigate to the corresponding submodules, e.g.
34
+ ``np.polynomial.Polynomial`` or ``np.polynomial.Chebyshev`` instead of
35
+ ``np.polynomial.polynomial.Polynomial`` or
36
+ ``np.polynomial.chebyshev.Chebyshev``, respectively.
37
+ The classes provide a more consistent and concise interface than the
38
+ type-specific functions defined in the submodules for each type of polynomial.
39
+ For example, to fit a Chebyshev polynomial with degree ``1`` to data given
40
+ by arrays ``xdata`` and ``ydata``, the
41
+ `~chebyshev.Chebyshev.fit` class method::
42
+
43
+ >>> from numpy.polynomial import Chebyshev
44
+ >>> c = Chebyshev.fit(xdata, ydata, deg=1)
45
+
46
+ is preferred over the `chebyshev.chebfit` function from the
47
+ ``np.polynomial.chebyshev`` module::
48
+
49
+ >>> from numpy.polynomial.chebyshev import chebfit
50
+ >>> c = chebfit(xdata, ydata, deg=1)
51
+
52
+ See :doc:`routines.polynomials.classes` for more details.
53
+
54
+ Convenience Classes
55
+ ===================
56
+
57
+ The following lists the various constants and methods common to all of
58
+ the classes representing the various kinds of polynomials. In the following,
59
+ the term ``Poly`` represents any one of the convenience classes (e.g.
60
+ `~polynomial.Polynomial`, `~chebyshev.Chebyshev`, `~hermite.Hermite`, etc.)
61
+ while the lowercase ``p`` represents an **instance** of a polynomial class.
62
+
63
+ Constants
64
+ ---------
65
+
66
+ - ``Poly.domain`` -- Default domain
67
+ - ``Poly.window`` -- Default window
68
+ - ``Poly.basis_name`` -- String used to represent the basis
69
+ - ``Poly.maxpower`` -- Maximum value ``n`` such that ``p**n`` is allowed
70
+ - ``Poly.nickname`` -- String used in printing
71
+
72
+ Creation
73
+ --------
74
+
75
+ Methods for creating polynomial instances.
76
+
77
+ - ``Poly.basis(degree)`` -- Basis polynomial of given degree
78
+ - ``Poly.identity()`` -- ``p`` where ``p(x) = x`` for all ``x``
79
+ - ``Poly.fit(x, y, deg)`` -- ``p`` of degree ``deg`` with coefficients
80
+ determined by the least-squares fit to the data ``x``, ``y``
81
+ - ``Poly.fromroots(roots)`` -- ``p`` with specified roots
82
+ - ``p.copy()`` -- Create a copy of ``p``
83
+
84
+ Conversion
85
+ ----------
86
+
87
+ Methods for converting a polynomial instance of one kind to another.
88
+
89
+ - ``p.cast(Poly)`` -- Convert ``p`` to instance of kind ``Poly``
90
+ - ``p.convert(Poly)`` -- Convert ``p`` to instance of kind ``Poly`` or map
91
+ between ``domain`` and ``window``
92
+
93
+ Calculus
94
+ --------
95
+ - ``p.deriv()`` -- Take the derivative of ``p``
96
+ - ``p.integ()`` -- Integrate ``p``
97
+
98
+ Validation
99
+ ----------
100
+ - ``Poly.has_samecoef(p1, p2)`` -- Check if coefficients match
101
+ - ``Poly.has_samedomain(p1, p2)`` -- Check if domains match
102
+ - ``Poly.has_sametype(p1, p2)`` -- Check if types match
103
+ - ``Poly.has_samewindow(p1, p2)`` -- Check if windows match
104
+
105
+ Misc
106
+ ----
107
+ - ``p.linspace()`` -- Return ``x, p(x)`` at equally-spaced points in ``domain``
108
+ - ``p.mapparms()`` -- Return the parameters for the linear mapping between
109
+ ``domain`` and ``window``.
110
+ - ``p.roots()`` -- Return the roots of `p`.
111
+ - ``p.trim()`` -- Remove trailing coefficients.
112
+ - ``p.cutdeg(degree)`` -- Truncate p to given degree
113
+ - ``p.truncate(size)`` -- Truncate p to given size
114
+
115
+ """
116
+ from .polynomial import Polynomial
117
+ from .chebyshev import Chebyshev
118
+ from .legendre import Legendre
119
+ from .hermite import Hermite
120
+ from .hermite_e import HermiteE
121
+ from .laguerre import Laguerre
122
+
123
+ __all__ = [
124
+ "set_default_printstyle",
125
+ "polynomial", "Polynomial",
126
+ "chebyshev", "Chebyshev",
127
+ "legendre", "Legendre",
128
+ "hermite", "Hermite",
129
+ "hermite_e", "HermiteE",
130
+ "laguerre", "Laguerre",
131
+ ]
132
+
133
+
134
+ def set_default_printstyle(style):
135
+ """
136
+ Set the default format for the string representation of polynomials.
137
+
138
+ Values for ``style`` must be valid inputs to ``__format__``, i.e. 'ascii'
139
+ or 'unicode'.
140
+
141
+ Parameters
142
+ ----------
143
+ style : str
144
+ Format string for default printing style. Must be either 'ascii' or
145
+ 'unicode'.
146
+
147
+ Notes
148
+ -----
149
+ The default format depends on the platform: 'unicode' is used on
150
+ Unix-based systems and 'ascii' on Windows. This determination is based on
151
+ default font support for the unicode superscript and subscript ranges.
152
+
153
+ Examples
154
+ --------
155
+ >>> p = np.polynomial.Polynomial([1, 2, 3])
156
+ >>> c = np.polynomial.Chebyshev([1, 2, 3])
157
+ >>> np.polynomial.set_default_printstyle('unicode')
158
+ >>> print(p)
159
+ 1.0 + 2.0·x + 3.0·x²
160
+ >>> print(c)
161
+ 1.0 + 2.0·T₁(x) + 3.0·T₂(x)
162
+ >>> np.polynomial.set_default_printstyle('ascii')
163
+ >>> print(p)
164
+ 1.0 + 2.0 x + 3.0 x**2
165
+ >>> print(c)
166
+ 1.0 + 2.0 T_1(x) + 3.0 T_2(x)
167
+ >>> # Formatting supersedes all class/package-level defaults
168
+ >>> print(f"{p:unicode}")
169
+ 1.0 + 2.0·x + 3.0·x²
170
+ """
171
+ if style not in ('unicode', 'ascii'):
172
+ raise ValueError(
173
+ f"Unsupported format string '{style}'. Valid options are 'ascii' "
174
+ f"and 'unicode'"
175
+ )
176
+ _use_unicode = True
177
+ if style == 'ascii':
178
+ _use_unicode = False
179
+ from ._polybase import ABCPolyBase
180
+ ABCPolyBase._use_unicode = _use_unicode
181
+
182
+
183
+ from numpy._pytesttester import PytestTester
184
+ test = PytestTester(__name__)
185
+ del PytestTester
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/_polybase.py ADDED
@@ -0,0 +1,1206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Abstract base class for the various polynomial Classes.
3
+
4
+ The ABCPolyBase class provides the methods needed to implement the common API
5
+ for the various polynomial classes. It operates as a mixin, but uses the
6
+ abc module from the stdlib, hence it is only available for Python >= 2.6.
7
+
8
+ """
9
+ import os
10
+ import abc
11
+ import numbers
12
+
13
+ import numpy as np
14
+ from . import polyutils as pu
15
+
16
+ __all__ = ['ABCPolyBase']
17
+
18
+ class ABCPolyBase(abc.ABC):
19
+ """An abstract base class for immutable series classes.
20
+
21
+ ABCPolyBase provides the standard Python numerical methods
22
+ '+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the
23
+ methods listed below.
24
+
25
+ .. versionadded:: 1.9.0
26
+
27
+ Parameters
28
+ ----------
29
+ coef : array_like
30
+ Series coefficients in order of increasing degree, i.e.,
31
+ ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where
32
+ ``P_i`` is the basis polynomials of degree ``i``.
33
+ domain : (2,) array_like, optional
34
+ Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
35
+ to the interval ``[window[0], window[1]]`` by shifting and scaling.
36
+ The default value is the derived class domain.
37
+ window : (2,) array_like, optional
38
+ Window, see domain for its use. The default value is the
39
+ derived class window.
40
+ symbol : str, optional
41
+ Symbol used to represent the independent variable in string
42
+ representations of the polynomial expression, e.g. for printing.
43
+ The symbol must be a valid Python identifier. Default value is 'x'.
44
+
45
+ .. versionadded:: 1.24
46
+
47
+ Attributes
48
+ ----------
49
+ coef : (N,) ndarray
50
+ Series coefficients in order of increasing degree.
51
+ domain : (2,) ndarray
52
+ Domain that is mapped to window.
53
+ window : (2,) ndarray
54
+ Window that domain is mapped to.
55
+ symbol : str
56
+ Symbol representing the independent variable.
57
+
58
+ Class Attributes
59
+ ----------------
60
+ maxpower : int
61
+ Maximum power allowed, i.e., the largest number ``n`` such that
62
+ ``p(x)**n`` is allowed. This is to limit runaway polynomial size.
63
+ domain : (2,) ndarray
64
+ Default domain of the class.
65
+ window : (2,) ndarray
66
+ Default window of the class.
67
+
68
+ """
69
+
70
+ # Not hashable
71
+ __hash__ = None
72
+
73
+ # Opt out of numpy ufuncs and Python ops with ndarray subclasses.
74
+ __array_ufunc__ = None
75
+
76
+ # Limit runaway size. T_n^m has degree n*m
77
+ maxpower = 100
78
+
79
+ # Unicode character mappings for improved __str__
80
+ _superscript_mapping = str.maketrans({
81
+ "0": "⁰",
82
+ "1": "¹",
83
+ "2": "²",
84
+ "3": "³",
85
+ "4": "⁴",
86
+ "5": "⁵",
87
+ "6": "⁶",
88
+ "7": "⁷",
89
+ "8": "⁸",
90
+ "9": "⁹"
91
+ })
92
+ _subscript_mapping = str.maketrans({
93
+ "0": "₀",
94
+ "1": "₁",
95
+ "2": "₂",
96
+ "3": "₃",
97
+ "4": "₄",
98
+ "5": "₅",
99
+ "6": "₆",
100
+ "7": "₇",
101
+ "8": "₈",
102
+ "9": "₉"
103
+ })
104
+ # Some fonts don't support full unicode character ranges necessary for
105
+ # the full set of superscripts and subscripts, including common/default
106
+ # fonts in Windows shells/terminals. Therefore, default to ascii-only
107
+ # printing on windows.
108
+ _use_unicode = not os.name == 'nt'
109
+
110
+ @property
111
+ def symbol(self):
112
+ return self._symbol
113
+
114
+ @property
115
+ @abc.abstractmethod
116
+ def domain(self):
117
+ pass
118
+
119
+ @property
120
+ @abc.abstractmethod
121
+ def window(self):
122
+ pass
123
+
124
+ @property
125
+ @abc.abstractmethod
126
+ def basis_name(self):
127
+ pass
128
+
129
+ @staticmethod
130
+ @abc.abstractmethod
131
+ def _add(c1, c2):
132
+ pass
133
+
134
+ @staticmethod
135
+ @abc.abstractmethod
136
+ def _sub(c1, c2):
137
+ pass
138
+
139
+ @staticmethod
140
+ @abc.abstractmethod
141
+ def _mul(c1, c2):
142
+ pass
143
+
144
+ @staticmethod
145
+ @abc.abstractmethod
146
+ def _div(c1, c2):
147
+ pass
148
+
149
+ @staticmethod
150
+ @abc.abstractmethod
151
+ def _pow(c, pow, maxpower=None):
152
+ pass
153
+
154
+ @staticmethod
155
+ @abc.abstractmethod
156
+ def _val(x, c):
157
+ pass
158
+
159
+ @staticmethod
160
+ @abc.abstractmethod
161
+ def _int(c, m, k, lbnd, scl):
162
+ pass
163
+
164
+ @staticmethod
165
+ @abc.abstractmethod
166
+ def _der(c, m, scl):
167
+ pass
168
+
169
+ @staticmethod
170
+ @abc.abstractmethod
171
+ def _fit(x, y, deg, rcond, full):
172
+ pass
173
+
174
+ @staticmethod
175
+ @abc.abstractmethod
176
+ def _line(off, scl):
177
+ pass
178
+
179
+ @staticmethod
180
+ @abc.abstractmethod
181
+ def _roots(c):
182
+ pass
183
+
184
+ @staticmethod
185
+ @abc.abstractmethod
186
+ def _fromroots(r):
187
+ pass
188
+
189
+ def has_samecoef(self, other):
190
+ """Check if coefficients match.
191
+
192
+ .. versionadded:: 1.6.0
193
+
194
+ Parameters
195
+ ----------
196
+ other : class instance
197
+ The other class must have the ``coef`` attribute.
198
+
199
+ Returns
200
+ -------
201
+ bool : boolean
202
+ True if the coefficients are the same, False otherwise.
203
+
204
+ """
205
+ if len(self.coef) != len(other.coef):
206
+ return False
207
+ elif not np.all(self.coef == other.coef):
208
+ return False
209
+ else:
210
+ return True
211
+
212
+ def has_samedomain(self, other):
213
+ """Check if domains match.
214
+
215
+ .. versionadded:: 1.6.0
216
+
217
+ Parameters
218
+ ----------
219
+ other : class instance
220
+ The other class must have the ``domain`` attribute.
221
+
222
+ Returns
223
+ -------
224
+ bool : boolean
225
+ True if the domains are the same, False otherwise.
226
+
227
+ """
228
+ return np.all(self.domain == other.domain)
229
+
230
+ def has_samewindow(self, other):
231
+ """Check if windows match.
232
+
233
+ .. versionadded:: 1.6.0
234
+
235
+ Parameters
236
+ ----------
237
+ other : class instance
238
+ The other class must have the ``window`` attribute.
239
+
240
+ Returns
241
+ -------
242
+ bool : boolean
243
+ True if the windows are the same, False otherwise.
244
+
245
+ """
246
+ return np.all(self.window == other.window)
247
+
248
+ def has_sametype(self, other):
249
+ """Check if types match.
250
+
251
+ .. versionadded:: 1.7.0
252
+
253
+ Parameters
254
+ ----------
255
+ other : object
256
+ Class instance.
257
+
258
+ Returns
259
+ -------
260
+ bool : boolean
261
+ True if other is same class as self
262
+
263
+ """
264
+ return isinstance(other, self.__class__)
265
+
266
+ def _get_coefficients(self, other):
267
+ """Interpret other as polynomial coefficients.
268
+
269
+ The `other` argument is checked to see if it is of the same
270
+ class as self with identical domain and window. If so,
271
+ return its coefficients, otherwise return `other`.
272
+
273
+ .. versionadded:: 1.9.0
274
+
275
+ Parameters
276
+ ----------
277
+ other : anything
278
+ Object to be checked.
279
+
280
+ Returns
281
+ -------
282
+ coef
283
+ The coefficients of`other` if it is a compatible instance,
284
+ of ABCPolyBase, otherwise `other`.
285
+
286
+ Raises
287
+ ------
288
+ TypeError
289
+ When `other` is an incompatible instance of ABCPolyBase.
290
+
291
+ """
292
+ if isinstance(other, ABCPolyBase):
293
+ if not isinstance(other, self.__class__):
294
+ raise TypeError("Polynomial types differ")
295
+ elif not np.all(self.domain == other.domain):
296
+ raise TypeError("Domains differ")
297
+ elif not np.all(self.window == other.window):
298
+ raise TypeError("Windows differ")
299
+ elif self.symbol != other.symbol:
300
+ raise ValueError("Polynomial symbols differ")
301
+ return other.coef
302
+ return other
303
+
304
+ def __init__(self, coef, domain=None, window=None, symbol='x'):
305
+ [coef] = pu.as_series([coef], trim=False)
306
+ self.coef = coef
307
+
308
+ if domain is not None:
309
+ [domain] = pu.as_series([domain], trim=False)
310
+ if len(domain) != 2:
311
+ raise ValueError("Domain has wrong number of elements.")
312
+ self.domain = domain
313
+
314
+ if window is not None:
315
+ [window] = pu.as_series([window], trim=False)
316
+ if len(window) != 2:
317
+ raise ValueError("Window has wrong number of elements.")
318
+ self.window = window
319
+
320
+ # Validation for symbol
321
+ try:
322
+ if not symbol.isidentifier():
323
+ raise ValueError(
324
+ "Symbol string must be a valid Python identifier"
325
+ )
326
+ # If a user passes in something other than a string, the above
327
+ # results in an AttributeError. Catch this and raise a more
328
+ # informative exception
329
+ except AttributeError:
330
+ raise TypeError("Symbol must be a non-empty string")
331
+
332
+ self._symbol = symbol
333
+
334
+ def __repr__(self):
335
+ coef = repr(self.coef)[6:-1]
336
+ domain = repr(self.domain)[6:-1]
337
+ window = repr(self.window)[6:-1]
338
+ name = self.__class__.__name__
339
+ return (f"{name}({coef}, domain={domain}, window={window}, "
340
+ f"symbol='{self.symbol}')")
341
+
342
+ def __format__(self, fmt_str):
343
+ if fmt_str == '':
344
+ return self.__str__()
345
+ if fmt_str not in ('ascii', 'unicode'):
346
+ raise ValueError(
347
+ f"Unsupported format string '{fmt_str}' passed to "
348
+ f"{self.__class__}.__format__. Valid options are "
349
+ f"'ascii' and 'unicode'"
350
+ )
351
+ if fmt_str == 'ascii':
352
+ return self._generate_string(self._str_term_ascii)
353
+ return self._generate_string(self._str_term_unicode)
354
+
355
+ def __str__(self):
356
+ if self._use_unicode:
357
+ return self._generate_string(self._str_term_unicode)
358
+ return self._generate_string(self._str_term_ascii)
359
+
360
+ def _generate_string(self, term_method):
361
+ """
362
+ Generate the full string representation of the polynomial, using
363
+ ``term_method`` to generate each polynomial term.
364
+ """
365
+ # Get configuration for line breaks
366
+ linewidth = np.get_printoptions().get('linewidth', 75)
367
+ if linewidth < 1:
368
+ linewidth = 1
369
+ out = pu.format_float(self.coef[0])
370
+ for i, coef in enumerate(self.coef[1:]):
371
+ out += " "
372
+ power = str(i + 1)
373
+ # Polynomial coefficient
374
+ # The coefficient array can be an object array with elements that
375
+ # will raise a TypeError with >= 0 (e.g. strings or Python
376
+ # complex). In this case, represent the coefficient as-is.
377
+ try:
378
+ if coef >= 0:
379
+ next_term = f"+ " + pu.format_float(coef, parens=True)
380
+ else:
381
+ next_term = f"- " + pu.format_float(-coef, parens=True)
382
+ except TypeError:
383
+ next_term = f"+ {coef}"
384
+ # Polynomial term
385
+ next_term += term_method(power, self.symbol)
386
+ # Length of the current line with next term added
387
+ line_len = len(out.split('\n')[-1]) + len(next_term)
388
+ # If not the last term in the polynomial, it will be two
389
+ # characters longer due to the +/- with the next term
390
+ if i < len(self.coef[1:]) - 1:
391
+ line_len += 2
392
+ # Handle linebreaking
393
+ if line_len >= linewidth:
394
+ next_term = next_term.replace(" ", "\n", 1)
395
+ out += next_term
396
+ return out
397
+
398
+ @classmethod
399
+ def _str_term_unicode(cls, i, arg_str):
400
+ """
401
+ String representation of single polynomial term using unicode
402
+ characters for superscripts and subscripts.
403
+ """
404
+ if cls.basis_name is None:
405
+ raise NotImplementedError(
406
+ "Subclasses must define either a basis_name, or override "
407
+ "_str_term_unicode(cls, i, arg_str)"
408
+ )
409
+ return (f"·{cls.basis_name}{i.translate(cls._subscript_mapping)}"
410
+ f"({arg_str})")
411
+
412
+ @classmethod
413
+ def _str_term_ascii(cls, i, arg_str):
414
+ """
415
+ String representation of a single polynomial term using ** and _ to
416
+ represent superscripts and subscripts, respectively.
417
+ """
418
+ if cls.basis_name is None:
419
+ raise NotImplementedError(
420
+ "Subclasses must define either a basis_name, or override "
421
+ "_str_term_ascii(cls, i, arg_str)"
422
+ )
423
+ return f" {cls.basis_name}_{i}({arg_str})"
424
+
425
+ @classmethod
426
+ def _repr_latex_term(cls, i, arg_str, needs_parens):
427
+ if cls.basis_name is None:
428
+ raise NotImplementedError(
429
+ "Subclasses must define either a basis name, or override "
430
+ "_repr_latex_term(i, arg_str, needs_parens)")
431
+ # since we always add parens, we don't care if the expression needs them
432
+ return f"{{{cls.basis_name}}}_{{{i}}}({arg_str})"
433
+
434
+ @staticmethod
435
+ def _repr_latex_scalar(x, parens=False):
436
+ # TODO: we're stuck with disabling math formatting until we handle
437
+ # exponents in this function
438
+ return r'\text{{{}}}'.format(pu.format_float(x, parens=parens))
439
+
440
+ def _repr_latex_(self):
441
+ # get the scaled argument string to the basis functions
442
+ off, scale = self.mapparms()
443
+ if off == 0 and scale == 1:
444
+ term = self.symbol
445
+ needs_parens = False
446
+ elif scale == 1:
447
+ term = f"{self._repr_latex_scalar(off)} + {self.symbol}"
448
+ needs_parens = True
449
+ elif off == 0:
450
+ term = f"{self._repr_latex_scalar(scale)}{self.symbol}"
451
+ needs_parens = True
452
+ else:
453
+ term = (
454
+ f"{self._repr_latex_scalar(off)} + "
455
+ f"{self._repr_latex_scalar(scale)}{self.symbol}"
456
+ )
457
+ needs_parens = True
458
+
459
+ mute = r"\color{{LightGray}}{{{}}}".format
460
+
461
+ parts = []
462
+ for i, c in enumerate(self.coef):
463
+ # prevent duplication of + and - signs
464
+ if i == 0:
465
+ coef_str = f"{self._repr_latex_scalar(c)}"
466
+ elif not isinstance(c, numbers.Real):
467
+ coef_str = f" + ({self._repr_latex_scalar(c)})"
468
+ elif not np.signbit(c):
469
+ coef_str = f" + {self._repr_latex_scalar(c, parens=True)}"
470
+ else:
471
+ coef_str = f" - {self._repr_latex_scalar(-c, parens=True)}"
472
+
473
+ # produce the string for the term
474
+ term_str = self._repr_latex_term(i, term, needs_parens)
475
+ if term_str == '1':
476
+ part = coef_str
477
+ else:
478
+ part = rf"{coef_str}\,{term_str}"
479
+
480
+ if c == 0:
481
+ part = mute(part)
482
+
483
+ parts.append(part)
484
+
485
+ if parts:
486
+ body = ''.join(parts)
487
+ else:
488
+ # in case somehow there are no coefficients at all
489
+ body = '0'
490
+
491
+ return rf"${self.symbol} \mapsto {body}$"
492
+
493
+
494
+
495
+ # Pickle and copy
496
+
497
+ def __getstate__(self):
498
+ ret = self.__dict__.copy()
499
+ ret['coef'] = self.coef.copy()
500
+ ret['domain'] = self.domain.copy()
501
+ ret['window'] = self.window.copy()
502
+ ret['symbol'] = self.symbol
503
+ return ret
504
+
505
+ def __setstate__(self, dict):
506
+ self.__dict__ = dict
507
+
508
+ # Call
509
+
510
+ def __call__(self, arg):
511
+ off, scl = pu.mapparms(self.domain, self.window)
512
+ arg = off + scl*arg
513
+ return self._val(arg, self.coef)
514
+
515
+ def __iter__(self):
516
+ return iter(self.coef)
517
+
518
+ def __len__(self):
519
+ return len(self.coef)
520
+
521
+ # Numeric properties.
522
+
523
+ def __neg__(self):
524
+ return self.__class__(
525
+ -self.coef, self.domain, self.window, self.symbol
526
+ )
527
+
528
+ def __pos__(self):
529
+ return self
530
+
531
+ def __add__(self, other):
532
+ othercoef = self._get_coefficients(other)
533
+ try:
534
+ coef = self._add(self.coef, othercoef)
535
+ except Exception:
536
+ return NotImplemented
537
+ return self.__class__(coef, self.domain, self.window, self.symbol)
538
+
539
+ def __sub__(self, other):
540
+ othercoef = self._get_coefficients(other)
541
+ try:
542
+ coef = self._sub(self.coef, othercoef)
543
+ except Exception:
544
+ return NotImplemented
545
+ return self.__class__(coef, self.domain, self.window, self.symbol)
546
+
547
+ def __mul__(self, other):
548
+ othercoef = self._get_coefficients(other)
549
+ try:
550
+ coef = self._mul(self.coef, othercoef)
551
+ except Exception:
552
+ return NotImplemented
553
+ return self.__class__(coef, self.domain, self.window, self.symbol)
554
+
555
+ def __truediv__(self, other):
556
+ # there is no true divide if the rhs is not a Number, although it
557
+ # could return the first n elements of an infinite series.
558
+ # It is hard to see where n would come from, though.
559
+ if not isinstance(other, numbers.Number) or isinstance(other, bool):
560
+ raise TypeError(
561
+ f"unsupported types for true division: "
562
+ f"'{type(self)}', '{type(other)}'"
563
+ )
564
+ return self.__floordiv__(other)
565
+
566
+ def __floordiv__(self, other):
567
+ res = self.__divmod__(other)
568
+ if res is NotImplemented:
569
+ return res
570
+ return res[0]
571
+
572
+ def __mod__(self, other):
573
+ res = self.__divmod__(other)
574
+ if res is NotImplemented:
575
+ return res
576
+ return res[1]
577
+
578
+ def __divmod__(self, other):
579
+ othercoef = self._get_coefficients(other)
580
+ try:
581
+ quo, rem = self._div(self.coef, othercoef)
582
+ except ZeroDivisionError:
583
+ raise
584
+ except Exception:
585
+ return NotImplemented
586
+ quo = self.__class__(quo, self.domain, self.window, self.symbol)
587
+ rem = self.__class__(rem, self.domain, self.window, self.symbol)
588
+ return quo, rem
589
+
590
+ def __pow__(self, other):
591
+ coef = self._pow(self.coef, other, maxpower=self.maxpower)
592
+ res = self.__class__(coef, self.domain, self.window, self.symbol)
593
+ return res
594
+
595
+ def __radd__(self, other):
596
+ try:
597
+ coef = self._add(other, self.coef)
598
+ except Exception:
599
+ return NotImplemented
600
+ return self.__class__(coef, self.domain, self.window, self.symbol)
601
+
602
+ def __rsub__(self, other):
603
+ try:
604
+ coef = self._sub(other, self.coef)
605
+ except Exception:
606
+ return NotImplemented
607
+ return self.__class__(coef, self.domain, self.window, self.symbol)
608
+
609
+ def __rmul__(self, other):
610
+ try:
611
+ coef = self._mul(other, self.coef)
612
+ except Exception:
613
+ return NotImplemented
614
+ return self.__class__(coef, self.domain, self.window, self.symbol)
615
+
616
+ def __rdiv__(self, other):
617
+ # set to __floordiv__ /.
618
+ return self.__rfloordiv__(other)
619
+
620
+ def __rtruediv__(self, other):
621
+ # An instance of ABCPolyBase is not considered a
622
+ # Number.
623
+ return NotImplemented
624
+
625
+ def __rfloordiv__(self, other):
626
+ res = self.__rdivmod__(other)
627
+ if res is NotImplemented:
628
+ return res
629
+ return res[0]
630
+
631
+ def __rmod__(self, other):
632
+ res = self.__rdivmod__(other)
633
+ if res is NotImplemented:
634
+ return res
635
+ return res[1]
636
+
637
+ def __rdivmod__(self, other):
638
+ try:
639
+ quo, rem = self._div(other, self.coef)
640
+ except ZeroDivisionError:
641
+ raise
642
+ except Exception:
643
+ return NotImplemented
644
+ quo = self.__class__(quo, self.domain, self.window, self.symbol)
645
+ rem = self.__class__(rem, self.domain, self.window, self.symbol)
646
+ return quo, rem
647
+
648
+ def __eq__(self, other):
649
+ res = (isinstance(other, self.__class__) and
650
+ np.all(self.domain == other.domain) and
651
+ np.all(self.window == other.window) and
652
+ (self.coef.shape == other.coef.shape) and
653
+ np.all(self.coef == other.coef) and
654
+ (self.symbol == other.symbol))
655
+ return res
656
+
657
+ def __ne__(self, other):
658
+ return not self.__eq__(other)
659
+
660
+ #
661
+ # Extra methods.
662
+ #
663
+
664
+ def copy(self):
665
+ """Return a copy.
666
+
667
+ Returns
668
+ -------
669
+ new_series : series
670
+ Copy of self.
671
+
672
+ """
673
+ return self.__class__(self.coef, self.domain, self.window, self.symbol)
674
+
675
+ def degree(self):
676
+ """The degree of the series.
677
+
678
+ .. versionadded:: 1.5.0
679
+
680
+ Returns
681
+ -------
682
+ degree : int
683
+ Degree of the series, one less than the number of coefficients.
684
+
685
+ Examples
686
+ --------
687
+
688
+ Create a polynomial object for ``1 + 7*x + 4*x**2``:
689
+
690
+ >>> poly = np.polynomial.Polynomial([1, 7, 4])
691
+ >>> print(poly)
692
+ 1.0 + 7.0·x + 4.0·x²
693
+ >>> poly.degree()
694
+ 2
695
+
696
+ Note that this method does not check for non-zero coefficients.
697
+ You must trim the polynomial to remove any trailing zeroes:
698
+
699
+ >>> poly = np.polynomial.Polynomial([1, 7, 0])
700
+ >>> print(poly)
701
+ 1.0 + 7.0·x + 0.0·x²
702
+ >>> poly.degree()
703
+ 2
704
+ >>> poly.trim().degree()
705
+ 1
706
+
707
+ """
708
+ return len(self) - 1
709
+
710
+ def cutdeg(self, deg):
711
+ """Truncate series to the given degree.
712
+
713
+ Reduce the degree of the series to `deg` by discarding the
714
+ high order terms. If `deg` is greater than the current degree a
715
+ copy of the current series is returned. This can be useful in least
716
+ squares where the coefficients of the high degree terms may be very
717
+ small.
718
+
719
+ .. versionadded:: 1.5.0
720
+
721
+ Parameters
722
+ ----------
723
+ deg : non-negative int
724
+ The series is reduced to degree `deg` by discarding the high
725
+ order terms. The value of `deg` must be a non-negative integer.
726
+
727
+ Returns
728
+ -------
729
+ new_series : series
730
+ New instance of series with reduced degree.
731
+
732
+ """
733
+ return self.truncate(deg + 1)
734
+
735
+ def trim(self, tol=0):
736
+ """Remove trailing coefficients
737
+
738
+ Remove trailing coefficients until a coefficient is reached whose
739
+ absolute value greater than `tol` or the beginning of the series is
740
+ reached. If all the coefficients would be removed the series is set
741
+ to ``[0]``. A new series instance is returned with the new
742
+ coefficients. The current instance remains unchanged.
743
+
744
+ Parameters
745
+ ----------
746
+ tol : non-negative number.
747
+ All trailing coefficients less than `tol` will be removed.
748
+
749
+ Returns
750
+ -------
751
+ new_series : series
752
+ New instance of series with trimmed coefficients.
753
+
754
+ """
755
+ coef = pu.trimcoef(self.coef, tol)
756
+ return self.__class__(coef, self.domain, self.window, self.symbol)
757
+
758
+ def truncate(self, size):
759
+ """Truncate series to length `size`.
760
+
761
+ Reduce the series to length `size` by discarding the high
762
+ degree terms. The value of `size` must be a positive integer. This
763
+ can be useful in least squares where the coefficients of the
764
+ high degree terms may be very small.
765
+
766
+ Parameters
767
+ ----------
768
+ size : positive int
769
+ The series is reduced to length `size` by discarding the high
770
+ degree terms. The value of `size` must be a positive integer.
771
+
772
+ Returns
773
+ -------
774
+ new_series : series
775
+ New instance of series with truncated coefficients.
776
+
777
+ """
778
+ isize = int(size)
779
+ if isize != size or isize < 1:
780
+ raise ValueError("size must be a positive integer")
781
+ if isize >= len(self.coef):
782
+ coef = self.coef
783
+ else:
784
+ coef = self.coef[:isize]
785
+ return self.__class__(coef, self.domain, self.window, self.symbol)
786
+
787
+ def convert(self, domain=None, kind=None, window=None):
788
+ """Convert series to a different kind and/or domain and/or window.
789
+
790
+ Parameters
791
+ ----------
792
+ domain : array_like, optional
793
+ The domain of the converted series. If the value is None,
794
+ the default domain of `kind` is used.
795
+ kind : class, optional
796
+ The polynomial series type class to which the current instance
797
+ should be converted. If kind is None, then the class of the
798
+ current instance is used.
799
+ window : array_like, optional
800
+ The window of the converted series. If the value is None,
801
+ the default window of `kind` is used.
802
+
803
+ Returns
804
+ -------
805
+ new_series : series
806
+ The returned class can be of different type than the current
807
+ instance and/or have a different domain and/or different
808
+ window.
809
+
810
+ Notes
811
+ -----
812
+ Conversion between domains and class types can result in
813
+ numerically ill defined series.
814
+
815
+ """
816
+ if kind is None:
817
+ kind = self.__class__
818
+ if domain is None:
819
+ domain = kind.domain
820
+ if window is None:
821
+ window = kind.window
822
+ return self(kind.identity(domain, window=window, symbol=self.symbol))
823
+
824
+ def mapparms(self):
825
+ """Return the mapping parameters.
826
+
827
+ The returned values define a linear map ``off + scl*x`` that is
828
+ applied to the input arguments before the series is evaluated. The
829
+ map depends on the ``domain`` and ``window``; if the current
830
+ ``domain`` is equal to the ``window`` the resulting map is the
831
+ identity. If the coefficients of the series instance are to be
832
+ used by themselves outside this class, then the linear function
833
+ must be substituted for the ``x`` in the standard representation of
834
+ the base polynomials.
835
+
836
+ Returns
837
+ -------
838
+ off, scl : float or complex
839
+ The mapping function is defined by ``off + scl*x``.
840
+
841
+ Notes
842
+ -----
843
+ If the current domain is the interval ``[l1, r1]`` and the window
844
+ is ``[l2, r2]``, then the linear mapping function ``L`` is
845
+ defined by the equations::
846
+
847
+ L(l1) = l2
848
+ L(r1) = r2
849
+
850
+ """
851
+ return pu.mapparms(self.domain, self.window)
852
+
853
+ def integ(self, m=1, k=[], lbnd=None):
854
+ """Integrate.
855
+
856
+ Return a series instance that is the definite integral of the
857
+ current series.
858
+
859
+ Parameters
860
+ ----------
861
+ m : non-negative int
862
+ The number of integrations to perform.
863
+ k : array_like
864
+ Integration constants. The first constant is applied to the
865
+ first integration, the second to the second, and so on. The
866
+ list of values must less than or equal to `m` in length and any
867
+ missing values are set to zero.
868
+ lbnd : Scalar
869
+ The lower bound of the definite integral.
870
+
871
+ Returns
872
+ -------
873
+ new_series : series
874
+ A new series representing the integral. The domain is the same
875
+ as the domain of the integrated series.
876
+
877
+ """
878
+ off, scl = self.mapparms()
879
+ if lbnd is None:
880
+ lbnd = 0
881
+ else:
882
+ lbnd = off + scl*lbnd
883
+ coef = self._int(self.coef, m, k, lbnd, 1./scl)
884
+ return self.__class__(coef, self.domain, self.window, self.symbol)
885
+
886
+ def deriv(self, m=1):
887
+ """Differentiate.
888
+
889
+ Return a series instance of that is the derivative of the current
890
+ series.
891
+
892
+ Parameters
893
+ ----------
894
+ m : non-negative int
895
+ Find the derivative of order `m`.
896
+
897
+ Returns
898
+ -------
899
+ new_series : series
900
+ A new series representing the derivative. The domain is the same
901
+ as the domain of the differentiated series.
902
+
903
+ """
904
+ off, scl = self.mapparms()
905
+ coef = self._der(self.coef, m, scl)
906
+ return self.__class__(coef, self.domain, self.window, self.symbol)
907
+
908
+ def roots(self):
909
+ """Return the roots of the series polynomial.
910
+
911
+ Compute the roots for the series. Note that the accuracy of the
912
+ roots decreases the further outside the `domain` they lie.
913
+
914
+ Returns
915
+ -------
916
+ roots : ndarray
917
+ Array containing the roots of the series.
918
+
919
+ """
920
+ roots = self._roots(self.coef)
921
+ return pu.mapdomain(roots, self.window, self.domain)
922
+
923
+ def linspace(self, n=100, domain=None):
924
+ """Return x, y values at equally spaced points in domain.
925
+
926
+ Returns the x, y values at `n` linearly spaced points across the
927
+ domain. Here y is the value of the polynomial at the points x. By
928
+ default the domain is the same as that of the series instance.
929
+ This method is intended mostly as a plotting aid.
930
+
931
+ .. versionadded:: 1.5.0
932
+
933
+ Parameters
934
+ ----------
935
+ n : int, optional
936
+ Number of point pairs to return. The default value is 100.
937
+ domain : {None, array_like}, optional
938
+ If not None, the specified domain is used instead of that of
939
+ the calling instance. It should be of the form ``[beg,end]``.
940
+ The default is None which case the class domain is used.
941
+
942
+ Returns
943
+ -------
944
+ x, y : ndarray
945
+ x is equal to linspace(self.domain[0], self.domain[1], n) and
946
+ y is the series evaluated at element of x.
947
+
948
+ """
949
+ if domain is None:
950
+ domain = self.domain
951
+ x = np.linspace(domain[0], domain[1], n)
952
+ y = self(x)
953
+ return x, y
954
+
955
+ @classmethod
956
+ def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None,
957
+ window=None, symbol='x'):
958
+ """Least squares fit to data.
959
+
960
+ Return a series instance that is the least squares fit to the data
961
+ `y` sampled at `x`. The domain of the returned instance can be
962
+ specified and this will often result in a superior fit with less
963
+ chance of ill conditioning.
964
+
965
+ Parameters
966
+ ----------
967
+ x : array_like, shape (M,)
968
+ x-coordinates of the M sample points ``(x[i], y[i])``.
969
+ y : array_like, shape (M,)
970
+ y-coordinates of the M sample points ``(x[i], y[i])``.
971
+ deg : int or 1-D array_like
972
+ Degree(s) of the fitting polynomials. If `deg` is a single integer
973
+ all terms up to and including the `deg`'th term are included in the
974
+ fit. For NumPy versions >= 1.11.0 a list of integers specifying the
975
+ degrees of the terms to include may be used instead.
976
+ domain : {None, [beg, end], []}, optional
977
+ Domain to use for the returned series. If ``None``,
978
+ then a minimal domain that covers the points `x` is chosen. If
979
+ ``[]`` the class domain is used. The default value was the
980
+ class domain in NumPy 1.4 and ``None`` in later versions.
981
+ The ``[]`` option was added in numpy 1.5.0.
982
+ rcond : float, optional
983
+ Relative condition number of the fit. Singular values smaller
984
+ than this relative to the largest singular value will be
985
+ ignored. The default value is len(x)*eps, where eps is the
986
+ relative precision of the float type, about 2e-16 in most
987
+ cases.
988
+ full : bool, optional
989
+ Switch determining nature of return value. When it is False
990
+ (the default) just the coefficients are returned, when True
991
+ diagnostic information from the singular value decomposition is
992
+ also returned.
993
+ w : array_like, shape (M,), optional
994
+ Weights. If not None, the weight ``w[i]`` applies to the unsquared
995
+ residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
996
+ chosen so that the errors of the products ``w[i]*y[i]`` all have
997
+ the same variance. When using inverse-variance weighting, use
998
+ ``w[i] = 1/sigma(y[i])``. The default value is None.
999
+
1000
+ .. versionadded:: 1.5.0
1001
+ window : {[beg, end]}, optional
1002
+ Window to use for the returned series. The default
1003
+ value is the default class domain
1004
+
1005
+ .. versionadded:: 1.6.0
1006
+ symbol : str, optional
1007
+ Symbol representing the independent variable. Default is 'x'.
1008
+
1009
+ Returns
1010
+ -------
1011
+ new_series : series
1012
+ A series that represents the least squares fit to the data and
1013
+ has the domain and window specified in the call. If the
1014
+ coefficients for the unscaled and unshifted basis polynomials are
1015
+ of interest, do ``new_series.convert().coef``.
1016
+
1017
+ [resid, rank, sv, rcond] : list
1018
+ These values are only returned if ``full == True``
1019
+
1020
+ - resid -- sum of squared residuals of the least squares fit
1021
+ - rank -- the numerical rank of the scaled Vandermonde matrix
1022
+ - sv -- singular values of the scaled Vandermonde matrix
1023
+ - rcond -- value of `rcond`.
1024
+
1025
+ For more details, see `linalg.lstsq`.
1026
+
1027
+ """
1028
+ if domain is None:
1029
+ domain = pu.getdomain(x)
1030
+ elif type(domain) is list and len(domain) == 0:
1031
+ domain = cls.domain
1032
+
1033
+ if window is None:
1034
+ window = cls.window
1035
+
1036
+ xnew = pu.mapdomain(x, domain, window)
1037
+ res = cls._fit(xnew, y, deg, w=w, rcond=rcond, full=full)
1038
+ if full:
1039
+ [coef, status] = res
1040
+ return (
1041
+ cls(coef, domain=domain, window=window, symbol=symbol), status
1042
+ )
1043
+ else:
1044
+ coef = res
1045
+ return cls(coef, domain=domain, window=window, symbol=symbol)
1046
+
1047
+ @classmethod
1048
+ def fromroots(cls, roots, domain=[], window=None, symbol='x'):
1049
+ """Return series instance that has the specified roots.
1050
+
1051
+ Returns a series representing the product
1052
+ ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
1053
+ list of roots.
1054
+
1055
+ Parameters
1056
+ ----------
1057
+ roots : array_like
1058
+ List of roots.
1059
+ domain : {[], None, array_like}, optional
1060
+ Domain for the resulting series. If None the domain is the
1061
+ interval from the smallest root to the largest. If [] the
1062
+ domain is the class domain. The default is [].
1063
+ window : {None, array_like}, optional
1064
+ Window for the returned series. If None the class window is
1065
+ used. The default is None.
1066
+ symbol : str, optional
1067
+ Symbol representing the independent variable. Default is 'x'.
1068
+
1069
+ Returns
1070
+ -------
1071
+ new_series : series
1072
+ Series with the specified roots.
1073
+
1074
+ """
1075
+ [roots] = pu.as_series([roots], trim=False)
1076
+ if domain is None:
1077
+ domain = pu.getdomain(roots)
1078
+ elif type(domain) is list and len(domain) == 0:
1079
+ domain = cls.domain
1080
+
1081
+ if window is None:
1082
+ window = cls.window
1083
+
1084
+ deg = len(roots)
1085
+ off, scl = pu.mapparms(domain, window)
1086
+ rnew = off + scl*roots
1087
+ coef = cls._fromroots(rnew) / scl**deg
1088
+ return cls(coef, domain=domain, window=window, symbol=symbol)
1089
+
1090
+ @classmethod
1091
+ def identity(cls, domain=None, window=None, symbol='x'):
1092
+ """Identity function.
1093
+
1094
+ If ``p`` is the returned series, then ``p(x) == x`` for all
1095
+ values of x.
1096
+
1097
+ Parameters
1098
+ ----------
1099
+ domain : {None, array_like}, optional
1100
+ If given, the array must be of the form ``[beg, end]``, where
1101
+ ``beg`` and ``end`` are the endpoints of the domain. If None is
1102
+ given then the class domain is used. The default is None.
1103
+ window : {None, array_like}, optional
1104
+ If given, the resulting array must be if the form
1105
+ ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
1106
+ the window. If None is given then the class window is used. The
1107
+ default is None.
1108
+ symbol : str, optional
1109
+ Symbol representing the independent variable. Default is 'x'.
1110
+
1111
+ Returns
1112
+ -------
1113
+ new_series : series
1114
+ Series of representing the identity.
1115
+
1116
+ """
1117
+ if domain is None:
1118
+ domain = cls.domain
1119
+ if window is None:
1120
+ window = cls.window
1121
+ off, scl = pu.mapparms(window, domain)
1122
+ coef = cls._line(off, scl)
1123
+ return cls(coef, domain, window, symbol)
1124
+
1125
+ @classmethod
1126
+ def basis(cls, deg, domain=None, window=None, symbol='x'):
1127
+ """Series basis polynomial of degree `deg`.
1128
+
1129
+ Returns the series representing the basis polynomial of degree `deg`.
1130
+
1131
+ .. versionadded:: 1.7.0
1132
+
1133
+ Parameters
1134
+ ----------
1135
+ deg : int
1136
+ Degree of the basis polynomial for the series. Must be >= 0.
1137
+ domain : {None, array_like}, optional
1138
+ If given, the array must be of the form ``[beg, end]``, where
1139
+ ``beg`` and ``end`` are the endpoints of the domain. If None is
1140
+ given then the class domain is used. The default is None.
1141
+ window : {None, array_like}, optional
1142
+ If given, the resulting array must be if the form
1143
+ ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
1144
+ the window. If None is given then the class window is used. The
1145
+ default is None.
1146
+ symbol : str, optional
1147
+ Symbol representing the independent variable. Default is 'x'.
1148
+
1149
+ Returns
1150
+ -------
1151
+ new_series : series
1152
+ A series with the coefficient of the `deg` term set to one and
1153
+ all others zero.
1154
+
1155
+ """
1156
+ if domain is None:
1157
+ domain = cls.domain
1158
+ if window is None:
1159
+ window = cls.window
1160
+ ideg = int(deg)
1161
+
1162
+ if ideg != deg or ideg < 0:
1163
+ raise ValueError("deg must be non-negative integer")
1164
+ return cls([0]*ideg + [1], domain, window, symbol)
1165
+
1166
+ @classmethod
1167
+ def cast(cls, series, domain=None, window=None):
1168
+ """Convert series to series of this class.
1169
+
1170
+ The `series` is expected to be an instance of some polynomial
1171
+ series of one of the types supported by by the numpy.polynomial
1172
+ module, but could be some other class that supports the convert
1173
+ method.
1174
+
1175
+ .. versionadded:: 1.7.0
1176
+
1177
+ Parameters
1178
+ ----------
1179
+ series : series
1180
+ The series instance to be converted.
1181
+ domain : {None, array_like}, optional
1182
+ If given, the array must be of the form ``[beg, end]``, where
1183
+ ``beg`` and ``end`` are the endpoints of the domain. If None is
1184
+ given then the class domain is used. The default is None.
1185
+ window : {None, array_like}, optional
1186
+ If given, the resulting array must be if the form
1187
+ ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
1188
+ the window. If None is given then the class window is used. The
1189
+ default is None.
1190
+
1191
+ Returns
1192
+ -------
1193
+ new_series : series
1194
+ A series of the same kind as the calling class and equal to
1195
+ `series` when evaluated.
1196
+
1197
+ See Also
1198
+ --------
1199
+ convert : similar instance method
1200
+
1201
+ """
1202
+ if domain is None:
1203
+ domain = cls.domain
1204
+ if window is None:
1205
+ window = cls.window
1206
+ return series.convert(domain, cls, window)
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/_polybase.pyi ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ from typing import Any, ClassVar
3
+
4
+ __all__: list[str]
5
+
6
+ class ABCPolyBase(abc.ABC):
7
+ __hash__: ClassVar[None] # type: ignore[assignment]
8
+ __array_ufunc__: ClassVar[None]
9
+ maxpower: ClassVar[int]
10
+ coef: Any
11
+ @property
12
+ def symbol(self) -> str: ...
13
+ @property
14
+ @abc.abstractmethod
15
+ def domain(self): ...
16
+ @property
17
+ @abc.abstractmethod
18
+ def window(self): ...
19
+ @property
20
+ @abc.abstractmethod
21
+ def basis_name(self): ...
22
+ def has_samecoef(self, other): ...
23
+ def has_samedomain(self, other): ...
24
+ def has_samewindow(self, other): ...
25
+ def has_sametype(self, other): ...
26
+ def __init__(self, coef, domain=..., window=..., symbol: str = ...) -> None: ...
27
+ def __format__(self, fmt_str): ...
28
+ def __call__(self, arg): ...
29
+ def __iter__(self): ...
30
+ def __len__(self): ...
31
+ def __neg__(self): ...
32
+ def __pos__(self): ...
33
+ def __add__(self, other): ...
34
+ def __sub__(self, other): ...
35
+ def __mul__(self, other): ...
36
+ def __truediv__(self, other): ...
37
+ def __floordiv__(self, other): ...
38
+ def __mod__(self, other): ...
39
+ def __divmod__(self, other): ...
40
+ def __pow__(self, other): ...
41
+ def __radd__(self, other): ...
42
+ def __rsub__(self, other): ...
43
+ def __rmul__(self, other): ...
44
+ def __rdiv__(self, other): ...
45
+ def __rtruediv__(self, other): ...
46
+ def __rfloordiv__(self, other): ...
47
+ def __rmod__(self, other): ...
48
+ def __rdivmod__(self, other): ...
49
+ def __eq__(self, other): ...
50
+ def __ne__(self, other): ...
51
+ def copy(self): ...
52
+ def degree(self): ...
53
+ def cutdeg(self, deg): ...
54
+ def trim(self, tol=...): ...
55
+ def truncate(self, size): ...
56
+ def convert(self, domain=..., kind=..., window=...): ...
57
+ def mapparms(self): ...
58
+ def integ(self, m=..., k = ..., lbnd=...): ...
59
+ def deriv(self, m=...): ...
60
+ def roots(self): ...
61
+ def linspace(self, n=..., domain=...): ...
62
+ @classmethod
63
+ def fit(cls, x, y, deg, domain=..., rcond=..., full=..., w=..., window=...): ...
64
+ @classmethod
65
+ def fromroots(cls, roots, domain = ..., window=...): ...
66
+ @classmethod
67
+ def identity(cls, domain=..., window=...): ...
68
+ @classmethod
69
+ def basis(cls, deg, domain=..., window=...): ...
70
+ @classmethod
71
+ def cast(cls, series, domain=..., window=...): ...
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/chebyshev.py ADDED
@@ -0,0 +1,2082 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ====================================================
3
+ Chebyshev Series (:mod:`numpy.polynomial.chebyshev`)
4
+ ====================================================
5
+
6
+ This module provides a number of objects (mostly functions) useful for
7
+ dealing with Chebyshev series, including a `Chebyshev` class that
8
+ encapsulates the usual arithmetic operations. (General information
9
+ on how this module represents and works with such polynomials is in the
10
+ docstring for its "parent" sub-package, `numpy.polynomial`).
11
+
12
+ Classes
13
+ -------
14
+
15
+ .. autosummary::
16
+ :toctree: generated/
17
+
18
+ Chebyshev
19
+
20
+
21
+ Constants
22
+ ---------
23
+
24
+ .. autosummary::
25
+ :toctree: generated/
26
+
27
+ chebdomain
28
+ chebzero
29
+ chebone
30
+ chebx
31
+
32
+ Arithmetic
33
+ ----------
34
+
35
+ .. autosummary::
36
+ :toctree: generated/
37
+
38
+ chebadd
39
+ chebsub
40
+ chebmulx
41
+ chebmul
42
+ chebdiv
43
+ chebpow
44
+ chebval
45
+ chebval2d
46
+ chebval3d
47
+ chebgrid2d
48
+ chebgrid3d
49
+
50
+ Calculus
51
+ --------
52
+
53
+ .. autosummary::
54
+ :toctree: generated/
55
+
56
+ chebder
57
+ chebint
58
+
59
+ Misc Functions
60
+ --------------
61
+
62
+ .. autosummary::
63
+ :toctree: generated/
64
+
65
+ chebfromroots
66
+ chebroots
67
+ chebvander
68
+ chebvander2d
69
+ chebvander3d
70
+ chebgauss
71
+ chebweight
72
+ chebcompanion
73
+ chebfit
74
+ chebpts1
75
+ chebpts2
76
+ chebtrim
77
+ chebline
78
+ cheb2poly
79
+ poly2cheb
80
+ chebinterpolate
81
+
82
+ See also
83
+ --------
84
+ `numpy.polynomial`
85
+
86
+ Notes
87
+ -----
88
+ The implementations of multiplication, division, integration, and
89
+ differentiation use the algebraic identities [1]_:
90
+
91
+ .. math::
92
+ T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\
93
+ z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}.
94
+
95
+ where
96
+
97
+ .. math:: x = \\frac{z + z^{-1}}{2}.
98
+
99
+ These identities allow a Chebyshev series to be expressed as a finite,
100
+ symmetric Laurent series. In this module, this sort of Laurent series
101
+ is referred to as a "z-series."
102
+
103
+ References
104
+ ----------
105
+ .. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev
106
+ Polynomials," *Journal of Statistical Planning and Inference 14*, 2008
107
+ (https://web.archive.org/web/20080221202153/https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4)
108
+
109
+ """
110
+ import numpy as np
111
+ import numpy.linalg as la
112
+ from numpy.core.multiarray import normalize_axis_index
113
+
114
+ from . import polyutils as pu
115
+ from ._polybase import ABCPolyBase
116
+
117
+ __all__ = [
118
+ 'chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd',
119
+ 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval',
120
+ 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots',
121
+ 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1',
122
+ 'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d',
123
+ 'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion',
124
+ 'chebgauss', 'chebweight', 'chebinterpolate']
125
+
126
+ chebtrim = pu.trimcoef
127
+
128
+ #
129
+ # A collection of functions for manipulating z-series. These are private
130
+ # functions and do minimal error checking.
131
+ #
132
+
133
+ def _cseries_to_zseries(c):
134
+ """Convert Chebyshev series to z-series.
135
+
136
+ Convert a Chebyshev series to the equivalent z-series. The result is
137
+ never an empty array. The dtype of the return is the same as that of
138
+ the input. No checks are run on the arguments as this routine is for
139
+ internal use.
140
+
141
+ Parameters
142
+ ----------
143
+ c : 1-D ndarray
144
+ Chebyshev coefficients, ordered from low to high
145
+
146
+ Returns
147
+ -------
148
+ zs : 1-D ndarray
149
+ Odd length symmetric z-series, ordered from low to high.
150
+
151
+ """
152
+ n = c.size
153
+ zs = np.zeros(2*n-1, dtype=c.dtype)
154
+ zs[n-1:] = c/2
155
+ return zs + zs[::-1]
156
+
157
+
158
+ def _zseries_to_cseries(zs):
159
+ """Convert z-series to a Chebyshev series.
160
+
161
+ Convert a z series to the equivalent Chebyshev series. The result is
162
+ never an empty array. The dtype of the return is the same as that of
163
+ the input. No checks are run on the arguments as this routine is for
164
+ internal use.
165
+
166
+ Parameters
167
+ ----------
168
+ zs : 1-D ndarray
169
+ Odd length symmetric z-series, ordered from low to high.
170
+
171
+ Returns
172
+ -------
173
+ c : 1-D ndarray
174
+ Chebyshev coefficients, ordered from low to high.
175
+
176
+ """
177
+ n = (zs.size + 1)//2
178
+ c = zs[n-1:].copy()
179
+ c[1:n] *= 2
180
+ return c
181
+
182
+
183
+ def _zseries_mul(z1, z2):
184
+ """Multiply two z-series.
185
+
186
+ Multiply two z-series to produce a z-series.
187
+
188
+ Parameters
189
+ ----------
190
+ z1, z2 : 1-D ndarray
191
+ The arrays must be 1-D but this is not checked.
192
+
193
+ Returns
194
+ -------
195
+ product : 1-D ndarray
196
+ The product z-series.
197
+
198
+ Notes
199
+ -----
200
+ This is simply convolution. If symmetric/anti-symmetric z-series are
201
+ denoted by S/A then the following rules apply:
202
+
203
+ S*S, A*A -> S
204
+ S*A, A*S -> A
205
+
206
+ """
207
+ return np.convolve(z1, z2)
208
+
209
+
210
+ def _zseries_div(z1, z2):
211
+ """Divide the first z-series by the second.
212
+
213
+ Divide `z1` by `z2` and return the quotient and remainder as z-series.
214
+ Warning: this implementation only applies when both z1 and z2 have the
215
+ same symmetry, which is sufficient for present purposes.
216
+
217
+ Parameters
218
+ ----------
219
+ z1, z2 : 1-D ndarray
220
+ The arrays must be 1-D and have the same symmetry, but this is not
221
+ checked.
222
+
223
+ Returns
224
+ -------
225
+
226
+ (quotient, remainder) : 1-D ndarrays
227
+ Quotient and remainder as z-series.
228
+
229
+ Notes
230
+ -----
231
+ This is not the same as polynomial division on account of the desired form
232
+ of the remainder. If symmetric/anti-symmetric z-series are denoted by S/A
233
+ then the following rules apply:
234
+
235
+ S/S -> S,S
236
+ A/A -> S,A
237
+
238
+ The restriction to types of the same symmetry could be fixed but seems like
239
+ unneeded generality. There is no natural form for the remainder in the case
240
+ where there is no symmetry.
241
+
242
+ """
243
+ z1 = z1.copy()
244
+ z2 = z2.copy()
245
+ lc1 = len(z1)
246
+ lc2 = len(z2)
247
+ if lc2 == 1:
248
+ z1 /= z2
249
+ return z1, z1[:1]*0
250
+ elif lc1 < lc2:
251
+ return z1[:1]*0, z1
252
+ else:
253
+ dlen = lc1 - lc2
254
+ scl = z2[0]
255
+ z2 /= scl
256
+ quo = np.empty(dlen + 1, dtype=z1.dtype)
257
+ i = 0
258
+ j = dlen
259
+ while i < j:
260
+ r = z1[i]
261
+ quo[i] = z1[i]
262
+ quo[dlen - i] = r
263
+ tmp = r*z2
264
+ z1[i:i+lc2] -= tmp
265
+ z1[j:j+lc2] -= tmp
266
+ i += 1
267
+ j -= 1
268
+ r = z1[i]
269
+ quo[i] = r
270
+ tmp = r*z2
271
+ z1[i:i+lc2] -= tmp
272
+ quo /= scl
273
+ rem = z1[i+1:i-1+lc2].copy()
274
+ return quo, rem
275
+
276
+
277
+ def _zseries_der(zs):
278
+ """Differentiate a z-series.
279
+
280
+ The derivative is with respect to x, not z. This is achieved using the
281
+ chain rule and the value of dx/dz given in the module notes.
282
+
283
+ Parameters
284
+ ----------
285
+ zs : z-series
286
+ The z-series to differentiate.
287
+
288
+ Returns
289
+ -------
290
+ derivative : z-series
291
+ The derivative
292
+
293
+ Notes
294
+ -----
295
+ The zseries for x (ns) has been multiplied by two in order to avoid
296
+ using floats that are incompatible with Decimal and likely other
297
+ specialized scalar types. This scaling has been compensated by
298
+ multiplying the value of zs by two also so that the two cancels in the
299
+ division.
300
+
301
+ """
302
+ n = len(zs)//2
303
+ ns = np.array([-1, 0, 1], dtype=zs.dtype)
304
+ zs *= np.arange(-n, n+1)*2
305
+ d, r = _zseries_div(zs, ns)
306
+ return d
307
+
308
+
309
+ def _zseries_int(zs):
310
+ """Integrate a z-series.
311
+
312
+ The integral is with respect to x, not z. This is achieved by a change
313
+ of variable using dx/dz given in the module notes.
314
+
315
+ Parameters
316
+ ----------
317
+ zs : z-series
318
+ The z-series to integrate
319
+
320
+ Returns
321
+ -------
322
+ integral : z-series
323
+ The indefinite integral
324
+
325
+ Notes
326
+ -----
327
+ The zseries for x (ns) has been multiplied by two in order to avoid
328
+ using floats that are incompatible with Decimal and likely other
329
+ specialized scalar types. This scaling has been compensated by
330
+ dividing the resulting zs by two.
331
+
332
+ """
333
+ n = 1 + len(zs)//2
334
+ ns = np.array([-1, 0, 1], dtype=zs.dtype)
335
+ zs = _zseries_mul(zs, ns)
336
+ div = np.arange(-n, n+1)*2
337
+ zs[:n] /= div[:n]
338
+ zs[n+1:] /= div[n+1:]
339
+ zs[n] = 0
340
+ return zs
341
+
342
+ #
343
+ # Chebyshev series functions
344
+ #
345
+
346
+
347
+ def poly2cheb(pol):
348
+ """
349
+ Convert a polynomial to a Chebyshev series.
350
+
351
+ Convert an array representing the coefficients of a polynomial (relative
352
+ to the "standard" basis) ordered from lowest degree to highest, to an
353
+ array of the coefficients of the equivalent Chebyshev series, ordered
354
+ from lowest to highest degree.
355
+
356
+ Parameters
357
+ ----------
358
+ pol : array_like
359
+ 1-D array containing the polynomial coefficients
360
+
361
+ Returns
362
+ -------
363
+ c : ndarray
364
+ 1-D array containing the coefficients of the equivalent Chebyshev
365
+ series.
366
+
367
+ See Also
368
+ --------
369
+ cheb2poly
370
+
371
+ Notes
372
+ -----
373
+ The easy way to do conversions between polynomial basis sets
374
+ is to use the convert method of a class instance.
375
+
376
+ Examples
377
+ --------
378
+ >>> from numpy import polynomial as P
379
+ >>> p = P.Polynomial(range(4))
380
+ >>> p
381
+ Polynomial([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
382
+ >>> c = p.convert(kind=P.Chebyshev)
383
+ >>> c
384
+ Chebyshev([1. , 3.25, 1. , 0.75], domain=[-1., 1.], window=[-1., 1.])
385
+ >>> P.chebyshev.poly2cheb(range(4))
386
+ array([1. , 3.25, 1. , 0.75])
387
+
388
+ """
389
+ [pol] = pu.as_series([pol])
390
+ deg = len(pol) - 1
391
+ res = 0
392
+ for i in range(deg, -1, -1):
393
+ res = chebadd(chebmulx(res), pol[i])
394
+ return res
395
+
396
+
397
+ def cheb2poly(c):
398
+ """
399
+ Convert a Chebyshev series to a polynomial.
400
+
401
+ Convert an array representing the coefficients of a Chebyshev series,
402
+ ordered from lowest degree to highest, to an array of the coefficients
403
+ of the equivalent polynomial (relative to the "standard" basis) ordered
404
+ from lowest to highest degree.
405
+
406
+ Parameters
407
+ ----------
408
+ c : array_like
409
+ 1-D array containing the Chebyshev series coefficients, ordered
410
+ from lowest order term to highest.
411
+
412
+ Returns
413
+ -------
414
+ pol : ndarray
415
+ 1-D array containing the coefficients of the equivalent polynomial
416
+ (relative to the "standard" basis) ordered from lowest order term
417
+ to highest.
418
+
419
+ See Also
420
+ --------
421
+ poly2cheb
422
+
423
+ Notes
424
+ -----
425
+ The easy way to do conversions between polynomial basis sets
426
+ is to use the convert method of a class instance.
427
+
428
+ Examples
429
+ --------
430
+ >>> from numpy import polynomial as P
431
+ >>> c = P.Chebyshev(range(4))
432
+ >>> c
433
+ Chebyshev([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
434
+ >>> p = c.convert(kind=P.Polynomial)
435
+ >>> p
436
+ Polynomial([-2., -8., 4., 12.], domain=[-1., 1.], window=[-1., 1.])
437
+ >>> P.chebyshev.cheb2poly(range(4))
438
+ array([-2., -8., 4., 12.])
439
+
440
+ """
441
+ from .polynomial import polyadd, polysub, polymulx
442
+
443
+ [c] = pu.as_series([c])
444
+ n = len(c)
445
+ if n < 3:
446
+ return c
447
+ else:
448
+ c0 = c[-2]
449
+ c1 = c[-1]
450
+ # i is the current degree of c1
451
+ for i in range(n - 1, 1, -1):
452
+ tmp = c0
453
+ c0 = polysub(c[i - 2], c1)
454
+ c1 = polyadd(tmp, polymulx(c1)*2)
455
+ return polyadd(c0, polymulx(c1))
456
+
457
+
458
+ #
459
+ # These are constant arrays are of integer type so as to be compatible
460
+ # with the widest range of other types, such as Decimal.
461
+ #
462
+
463
+ # Chebyshev default domain.
464
+ chebdomain = np.array([-1, 1])
465
+
466
+ # Chebyshev coefficients representing zero.
467
+ chebzero = np.array([0])
468
+
469
+ # Chebyshev coefficients representing one.
470
+ chebone = np.array([1])
471
+
472
+ # Chebyshev coefficients representing the identity x.
473
+ chebx = np.array([0, 1])
474
+
475
+
476
+ def chebline(off, scl):
477
+ """
478
+ Chebyshev series whose graph is a straight line.
479
+
480
+ Parameters
481
+ ----------
482
+ off, scl : scalars
483
+ The specified line is given by ``off + scl*x``.
484
+
485
+ Returns
486
+ -------
487
+ y : ndarray
488
+ This module's representation of the Chebyshev series for
489
+ ``off + scl*x``.
490
+
491
+ See Also
492
+ --------
493
+ numpy.polynomial.polynomial.polyline
494
+ numpy.polynomial.legendre.legline
495
+ numpy.polynomial.laguerre.lagline
496
+ numpy.polynomial.hermite.hermline
497
+ numpy.polynomial.hermite_e.hermeline
498
+
499
+ Examples
500
+ --------
501
+ >>> import numpy.polynomial.chebyshev as C
502
+ >>> C.chebline(3,2)
503
+ array([3, 2])
504
+ >>> C.chebval(-3, C.chebline(3,2)) # should be -3
505
+ -3.0
506
+
507
+ """
508
+ if scl != 0:
509
+ return np.array([off, scl])
510
+ else:
511
+ return np.array([off])
512
+
513
+
514
+ def chebfromroots(roots):
515
+ """
516
+ Generate a Chebyshev series with given roots.
517
+
518
+ The function returns the coefficients of the polynomial
519
+
520
+ .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
521
+
522
+ in Chebyshev form, where the `r_n` are the roots specified in `roots`.
523
+ If a zero has multiplicity n, then it must appear in `roots` n times.
524
+ For instance, if 2 is a root of multiplicity three and 3 is a root of
525
+ multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
526
+ roots can appear in any order.
527
+
528
+ If the returned coefficients are `c`, then
529
+
530
+ .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x)
531
+
532
+ The coefficient of the last term is not generally 1 for monic
533
+ polynomials in Chebyshev form.
534
+
535
+ Parameters
536
+ ----------
537
+ roots : array_like
538
+ Sequence containing the roots.
539
+
540
+ Returns
541
+ -------
542
+ out : ndarray
543
+ 1-D array of coefficients. If all roots are real then `out` is a
544
+ real array, if some of the roots are complex, then `out` is complex
545
+ even if all the coefficients in the result are real (see Examples
546
+ below).
547
+
548
+ See Also
549
+ --------
550
+ numpy.polynomial.polynomial.polyfromroots
551
+ numpy.polynomial.legendre.legfromroots
552
+ numpy.polynomial.laguerre.lagfromroots
553
+ numpy.polynomial.hermite.hermfromroots
554
+ numpy.polynomial.hermite_e.hermefromroots
555
+
556
+ Examples
557
+ --------
558
+ >>> import numpy.polynomial.chebyshev as C
559
+ >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis
560
+ array([ 0. , -0.25, 0. , 0.25])
561
+ >>> j = complex(0,1)
562
+ >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis
563
+ array([1.5+0.j, 0. +0.j, 0.5+0.j])
564
+
565
+ """
566
+ return pu._fromroots(chebline, chebmul, roots)
567
+
568
+
569
+ def chebadd(c1, c2):
570
+ """
571
+ Add one Chebyshev series to another.
572
+
573
+ Returns the sum of two Chebyshev series `c1` + `c2`. The arguments
574
+ are sequences of coefficients ordered from lowest order term to
575
+ highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
576
+
577
+ Parameters
578
+ ----------
579
+ c1, c2 : array_like
580
+ 1-D arrays of Chebyshev series coefficients ordered from low to
581
+ high.
582
+
583
+ Returns
584
+ -------
585
+ out : ndarray
586
+ Array representing the Chebyshev series of their sum.
587
+
588
+ See Also
589
+ --------
590
+ chebsub, chebmulx, chebmul, chebdiv, chebpow
591
+
592
+ Notes
593
+ -----
594
+ Unlike multiplication, division, etc., the sum of two Chebyshev series
595
+ is a Chebyshev series (without having to "reproject" the result onto
596
+ the basis set) so addition, just like that of "standard" polynomials,
597
+ is simply "component-wise."
598
+
599
+ Examples
600
+ --------
601
+ >>> from numpy.polynomial import chebyshev as C
602
+ >>> c1 = (1,2,3)
603
+ >>> c2 = (3,2,1)
604
+ >>> C.chebadd(c1,c2)
605
+ array([4., 4., 4.])
606
+
607
+ """
608
+ return pu._add(c1, c2)
609
+
610
+
611
+ def chebsub(c1, c2):
612
+ """
613
+ Subtract one Chebyshev series from another.
614
+
615
+ Returns the difference of two Chebyshev series `c1` - `c2`. The
616
+ sequences of coefficients are from lowest order term to highest, i.e.,
617
+ [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
618
+
619
+ Parameters
620
+ ----------
621
+ c1, c2 : array_like
622
+ 1-D arrays of Chebyshev series coefficients ordered from low to
623
+ high.
624
+
625
+ Returns
626
+ -------
627
+ out : ndarray
628
+ Of Chebyshev series coefficients representing their difference.
629
+
630
+ See Also
631
+ --------
632
+ chebadd, chebmulx, chebmul, chebdiv, chebpow
633
+
634
+ Notes
635
+ -----
636
+ Unlike multiplication, division, etc., the difference of two Chebyshev
637
+ series is a Chebyshev series (without having to "reproject" the result
638
+ onto the basis set) so subtraction, just like that of "standard"
639
+ polynomials, is simply "component-wise."
640
+
641
+ Examples
642
+ --------
643
+ >>> from numpy.polynomial import chebyshev as C
644
+ >>> c1 = (1,2,3)
645
+ >>> c2 = (3,2,1)
646
+ >>> C.chebsub(c1,c2)
647
+ array([-2., 0., 2.])
648
+ >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2)
649
+ array([ 2., 0., -2.])
650
+
651
+ """
652
+ return pu._sub(c1, c2)
653
+
654
+
655
+ def chebmulx(c):
656
+ """Multiply a Chebyshev series by x.
657
+
658
+ Multiply the polynomial `c` by x, where x is the independent
659
+ variable.
660
+
661
+
662
+ Parameters
663
+ ----------
664
+ c : array_like
665
+ 1-D array of Chebyshev series coefficients ordered from low to
666
+ high.
667
+
668
+ Returns
669
+ -------
670
+ out : ndarray
671
+ Array representing the result of the multiplication.
672
+
673
+ Notes
674
+ -----
675
+
676
+ .. versionadded:: 1.5.0
677
+
678
+ Examples
679
+ --------
680
+ >>> from numpy.polynomial import chebyshev as C
681
+ >>> C.chebmulx([1,2,3])
682
+ array([1. , 2.5, 1. , 1.5])
683
+
684
+ """
685
+ # c is a trimmed copy
686
+ [c] = pu.as_series([c])
687
+ # The zero series needs special treatment
688
+ if len(c) == 1 and c[0] == 0:
689
+ return c
690
+
691
+ prd = np.empty(len(c) + 1, dtype=c.dtype)
692
+ prd[0] = c[0]*0
693
+ prd[1] = c[0]
694
+ if len(c) > 1:
695
+ tmp = c[1:]/2
696
+ prd[2:] = tmp
697
+ prd[0:-2] += tmp
698
+ return prd
699
+
700
+
701
+ def chebmul(c1, c2):
702
+ """
703
+ Multiply one Chebyshev series by another.
704
+
705
+ Returns the product of two Chebyshev series `c1` * `c2`. The arguments
706
+ are sequences of coefficients, from lowest order "term" to highest,
707
+ e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
708
+
709
+ Parameters
710
+ ----------
711
+ c1, c2 : array_like
712
+ 1-D arrays of Chebyshev series coefficients ordered from low to
713
+ high.
714
+
715
+ Returns
716
+ -------
717
+ out : ndarray
718
+ Of Chebyshev series coefficients representing their product.
719
+
720
+ See Also
721
+ --------
722
+ chebadd, chebsub, chebmulx, chebdiv, chebpow
723
+
724
+ Notes
725
+ -----
726
+ In general, the (polynomial) product of two C-series results in terms
727
+ that are not in the Chebyshev polynomial basis set. Thus, to express
728
+ the product as a C-series, it is typically necessary to "reproject"
729
+ the product onto said basis set, which typically produces
730
+ "unintuitive live" (but correct) results; see Examples section below.
731
+
732
+ Examples
733
+ --------
734
+ >>> from numpy.polynomial import chebyshev as C
735
+ >>> c1 = (1,2,3)
736
+ >>> c2 = (3,2,1)
737
+ >>> C.chebmul(c1,c2) # multiplication requires "reprojection"
738
+ array([ 6.5, 12. , 12. , 4. , 1.5])
739
+
740
+ """
741
+ # c1, c2 are trimmed copies
742
+ [c1, c2] = pu.as_series([c1, c2])
743
+ z1 = _cseries_to_zseries(c1)
744
+ z2 = _cseries_to_zseries(c2)
745
+ prd = _zseries_mul(z1, z2)
746
+ ret = _zseries_to_cseries(prd)
747
+ return pu.trimseq(ret)
748
+
749
+
750
+ def chebdiv(c1, c2):
751
+ """
752
+ Divide one Chebyshev series by another.
753
+
754
+ Returns the quotient-with-remainder of two Chebyshev series
755
+ `c1` / `c2`. The arguments are sequences of coefficients from lowest
756
+ order "term" to highest, e.g., [1,2,3] represents the series
757
+ ``T_0 + 2*T_1 + 3*T_2``.
758
+
759
+ Parameters
760
+ ----------
761
+ c1, c2 : array_like
762
+ 1-D arrays of Chebyshev series coefficients ordered from low to
763
+ high.
764
+
765
+ Returns
766
+ -------
767
+ [quo, rem] : ndarrays
768
+ Of Chebyshev series coefficients representing the quotient and
769
+ remainder.
770
+
771
+ See Also
772
+ --------
773
+ chebadd, chebsub, chebmulx, chebmul, chebpow
774
+
775
+ Notes
776
+ -----
777
+ In general, the (polynomial) division of one C-series by another
778
+ results in quotient and remainder terms that are not in the Chebyshev
779
+ polynomial basis set. Thus, to express these results as C-series, it
780
+ is typically necessary to "reproject" the results onto said basis
781
+ set, which typically produces "unintuitive" (but correct) results;
782
+ see Examples section below.
783
+
784
+ Examples
785
+ --------
786
+ >>> from numpy.polynomial import chebyshev as C
787
+ >>> c1 = (1,2,3)
788
+ >>> c2 = (3,2,1)
789
+ >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not
790
+ (array([3.]), array([-8., -4.]))
791
+ >>> c2 = (0,1,2,3)
792
+ >>> C.chebdiv(c2,c1) # neither "intuitive"
793
+ (array([0., 2.]), array([-2., -4.]))
794
+
795
+ """
796
+ # c1, c2 are trimmed copies
797
+ [c1, c2] = pu.as_series([c1, c2])
798
+ if c2[-1] == 0:
799
+ raise ZeroDivisionError()
800
+
801
+ # note: this is more efficient than `pu._div(chebmul, c1, c2)`
802
+ lc1 = len(c1)
803
+ lc2 = len(c2)
804
+ if lc1 < lc2:
805
+ return c1[:1]*0, c1
806
+ elif lc2 == 1:
807
+ return c1/c2[-1], c1[:1]*0
808
+ else:
809
+ z1 = _cseries_to_zseries(c1)
810
+ z2 = _cseries_to_zseries(c2)
811
+ quo, rem = _zseries_div(z1, z2)
812
+ quo = pu.trimseq(_zseries_to_cseries(quo))
813
+ rem = pu.trimseq(_zseries_to_cseries(rem))
814
+ return quo, rem
815
+
816
+
817
+ def chebpow(c, pow, maxpower=16):
818
+ """Raise a Chebyshev series to a power.
819
+
820
+ Returns the Chebyshev series `c` raised to the power `pow`. The
821
+ argument `c` is a sequence of coefficients ordered from low to high.
822
+ i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.``
823
+
824
+ Parameters
825
+ ----------
826
+ c : array_like
827
+ 1-D array of Chebyshev series coefficients ordered from low to
828
+ high.
829
+ pow : integer
830
+ Power to which the series will be raised
831
+ maxpower : integer, optional
832
+ Maximum power allowed. This is mainly to limit growth of the series
833
+ to unmanageable size. Default is 16
834
+
835
+ Returns
836
+ -------
837
+ coef : ndarray
838
+ Chebyshev series of power.
839
+
840
+ See Also
841
+ --------
842
+ chebadd, chebsub, chebmulx, chebmul, chebdiv
843
+
844
+ Examples
845
+ --------
846
+ >>> from numpy.polynomial import chebyshev as C
847
+ >>> C.chebpow([1, 2, 3, 4], 2)
848
+ array([15.5, 22. , 16. , ..., 12.5, 12. , 8. ])
849
+
850
+ """
851
+ # note: this is more efficient than `pu._pow(chebmul, c1, c2)`, as it
852
+ # avoids converting between z and c series repeatedly
853
+
854
+ # c is a trimmed copy
855
+ [c] = pu.as_series([c])
856
+ power = int(pow)
857
+ if power != pow or power < 0:
858
+ raise ValueError("Power must be a non-negative integer.")
859
+ elif maxpower is not None and power > maxpower:
860
+ raise ValueError("Power is too large")
861
+ elif power == 0:
862
+ return np.array([1], dtype=c.dtype)
863
+ elif power == 1:
864
+ return c
865
+ else:
866
+ # This can be made more efficient by using powers of two
867
+ # in the usual way.
868
+ zs = _cseries_to_zseries(c)
869
+ prd = zs
870
+ for i in range(2, power + 1):
871
+ prd = np.convolve(prd, zs)
872
+ return _zseries_to_cseries(prd)
873
+
874
+
875
+ def chebder(c, m=1, scl=1, axis=0):
876
+ """
877
+ Differentiate a Chebyshev series.
878
+
879
+ Returns the Chebyshev series coefficients `c` differentiated `m` times
880
+ along `axis`. At each iteration the result is multiplied by `scl` (the
881
+ scaling factor is for use in a linear change of variable). The argument
882
+ `c` is an array of coefficients from low to high degree along each
883
+ axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2``
884
+ while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) +
885
+ 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is
886
+ ``y``.
887
+
888
+ Parameters
889
+ ----------
890
+ c : array_like
891
+ Array of Chebyshev series coefficients. If c is multidimensional
892
+ the different axis correspond to different variables with the
893
+ degree in each axis given by the corresponding index.
894
+ m : int, optional
895
+ Number of derivatives taken, must be non-negative. (Default: 1)
896
+ scl : scalar, optional
897
+ Each differentiation is multiplied by `scl`. The end result is
898
+ multiplication by ``scl**m``. This is for use in a linear change of
899
+ variable. (Default: 1)
900
+ axis : int, optional
901
+ Axis over which the derivative is taken. (Default: 0).
902
+
903
+ .. versionadded:: 1.7.0
904
+
905
+ Returns
906
+ -------
907
+ der : ndarray
908
+ Chebyshev series of the derivative.
909
+
910
+ See Also
911
+ --------
912
+ chebint
913
+
914
+ Notes
915
+ -----
916
+ In general, the result of differentiating a C-series needs to be
917
+ "reprojected" onto the C-series basis set. Thus, typically, the
918
+ result of this function is "unintuitive," albeit correct; see Examples
919
+ section below.
920
+
921
+ Examples
922
+ --------
923
+ >>> from numpy.polynomial import chebyshev as C
924
+ >>> c = (1,2,3,4)
925
+ >>> C.chebder(c)
926
+ array([14., 12., 24.])
927
+ >>> C.chebder(c,3)
928
+ array([96.])
929
+ >>> C.chebder(c,scl=-1)
930
+ array([-14., -12., -24.])
931
+ >>> C.chebder(c,2,-1)
932
+ array([12., 96.])
933
+
934
+ """
935
+ c = np.array(c, ndmin=1, copy=True)
936
+ if c.dtype.char in '?bBhHiIlLqQpP':
937
+ c = c.astype(np.double)
938
+ cnt = pu._deprecate_as_int(m, "the order of derivation")
939
+ iaxis = pu._deprecate_as_int(axis, "the axis")
940
+ if cnt < 0:
941
+ raise ValueError("The order of derivation must be non-negative")
942
+ iaxis = normalize_axis_index(iaxis, c.ndim)
943
+
944
+ if cnt == 0:
945
+ return c
946
+
947
+ c = np.moveaxis(c, iaxis, 0)
948
+ n = len(c)
949
+ if cnt >= n:
950
+ c = c[:1]*0
951
+ else:
952
+ for i in range(cnt):
953
+ n = n - 1
954
+ c *= scl
955
+ der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
956
+ for j in range(n, 2, -1):
957
+ der[j - 1] = (2*j)*c[j]
958
+ c[j - 2] += (j*c[j])/(j - 2)
959
+ if n > 1:
960
+ der[1] = 4*c[2]
961
+ der[0] = c[1]
962
+ c = der
963
+ c = np.moveaxis(c, 0, iaxis)
964
+ return c
965
+
966
+
967
+ def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
968
+ """
969
+ Integrate a Chebyshev series.
970
+
971
+ Returns the Chebyshev series coefficients `c` integrated `m` times from
972
+ `lbnd` along `axis`. At each iteration the resulting series is
973
+ **multiplied** by `scl` and an integration constant, `k`, is added.
974
+ The scaling factor is for use in a linear change of variable. ("Buyer
975
+ beware": note that, depending on what one is doing, one may want `scl`
976
+ to be the reciprocal of what one might expect; for more information,
977
+ see the Notes section below.) The argument `c` is an array of
978
+ coefficients from low to high degree along each axis, e.g., [1,2,3]
979
+ represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]]
980
+ represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) +
981
+ 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
982
+
983
+ Parameters
984
+ ----------
985
+ c : array_like
986
+ Array of Chebyshev series coefficients. If c is multidimensional
987
+ the different axis correspond to different variables with the
988
+ degree in each axis given by the corresponding index.
989
+ m : int, optional
990
+ Order of integration, must be positive. (Default: 1)
991
+ k : {[], list, scalar}, optional
992
+ Integration constant(s). The value of the first integral at zero
993
+ is the first value in the list, the value of the second integral
994
+ at zero is the second value, etc. If ``k == []`` (the default),
995
+ all constants are set to zero. If ``m == 1``, a single scalar can
996
+ be given instead of a list.
997
+ lbnd : scalar, optional
998
+ The lower bound of the integral. (Default: 0)
999
+ scl : scalar, optional
1000
+ Following each integration the result is *multiplied* by `scl`
1001
+ before the integration constant is added. (Default: 1)
1002
+ axis : int, optional
1003
+ Axis over which the integral is taken. (Default: 0).
1004
+
1005
+ .. versionadded:: 1.7.0
1006
+
1007
+ Returns
1008
+ -------
1009
+ S : ndarray
1010
+ C-series coefficients of the integral.
1011
+
1012
+ Raises
1013
+ ------
1014
+ ValueError
1015
+ If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
1016
+ ``np.ndim(scl) != 0``.
1017
+
1018
+ See Also
1019
+ --------
1020
+ chebder
1021
+
1022
+ Notes
1023
+ -----
1024
+ Note that the result of each integration is *multiplied* by `scl`.
1025
+ Why is this important to note? Say one is making a linear change of
1026
+ variable :math:`u = ax + b` in an integral relative to `x`. Then
1027
+ :math:`dx = du/a`, so one will need to set `scl` equal to
1028
+ :math:`1/a`- perhaps not what one would have first thought.
1029
+
1030
+ Also note that, in general, the result of integrating a C-series needs
1031
+ to be "reprojected" onto the C-series basis set. Thus, typically,
1032
+ the result of this function is "unintuitive," albeit correct; see
1033
+ Examples section below.
1034
+
1035
+ Examples
1036
+ --------
1037
+ >>> from numpy.polynomial import chebyshev as C
1038
+ >>> c = (1,2,3)
1039
+ >>> C.chebint(c)
1040
+ array([ 0.5, -0.5, 0.5, 0.5])
1041
+ >>> C.chebint(c,3)
1042
+ array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, # may vary
1043
+ 0.00625 ])
1044
+ >>> C.chebint(c, k=3)
1045
+ array([ 3.5, -0.5, 0.5, 0.5])
1046
+ >>> C.chebint(c,lbnd=-2)
1047
+ array([ 8.5, -0.5, 0.5, 0.5])
1048
+ >>> C.chebint(c,scl=-2)
1049
+ array([-1., 1., -1., -1.])
1050
+
1051
+ """
1052
+ c = np.array(c, ndmin=1, copy=True)
1053
+ if c.dtype.char in '?bBhHiIlLqQpP':
1054
+ c = c.astype(np.double)
1055
+ if not np.iterable(k):
1056
+ k = [k]
1057
+ cnt = pu._deprecate_as_int(m, "the order of integration")
1058
+ iaxis = pu._deprecate_as_int(axis, "the axis")
1059
+ if cnt < 0:
1060
+ raise ValueError("The order of integration must be non-negative")
1061
+ if len(k) > cnt:
1062
+ raise ValueError("Too many integration constants")
1063
+ if np.ndim(lbnd) != 0:
1064
+ raise ValueError("lbnd must be a scalar.")
1065
+ if np.ndim(scl) != 0:
1066
+ raise ValueError("scl must be a scalar.")
1067
+ iaxis = normalize_axis_index(iaxis, c.ndim)
1068
+
1069
+ if cnt == 0:
1070
+ return c
1071
+
1072
+ c = np.moveaxis(c, iaxis, 0)
1073
+ k = list(k) + [0]*(cnt - len(k))
1074
+ for i in range(cnt):
1075
+ n = len(c)
1076
+ c *= scl
1077
+ if n == 1 and np.all(c[0] == 0):
1078
+ c[0] += k[i]
1079
+ else:
1080
+ tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
1081
+ tmp[0] = c[0]*0
1082
+ tmp[1] = c[0]
1083
+ if n > 1:
1084
+ tmp[2] = c[1]/4
1085
+ for j in range(2, n):
1086
+ tmp[j + 1] = c[j]/(2*(j + 1))
1087
+ tmp[j - 1] -= c[j]/(2*(j - 1))
1088
+ tmp[0] += k[i] - chebval(lbnd, tmp)
1089
+ c = tmp
1090
+ c = np.moveaxis(c, 0, iaxis)
1091
+ return c
1092
+
1093
+
1094
+ def chebval(x, c, tensor=True):
1095
+ """
1096
+ Evaluate a Chebyshev series at points x.
1097
+
1098
+ If `c` is of length `n + 1`, this function returns the value:
1099
+
1100
+ .. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)
1101
+
1102
+ The parameter `x` is converted to an array only if it is a tuple or a
1103
+ list, otherwise it is treated as a scalar. In either case, either `x`
1104
+ or its elements must support multiplication and addition both with
1105
+ themselves and with the elements of `c`.
1106
+
1107
+ If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
1108
+ `c` is multidimensional, then the shape of the result depends on the
1109
+ value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
1110
+ x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
1111
+ scalars have shape (,).
1112
+
1113
+ Trailing zeros in the coefficients will be used in the evaluation, so
1114
+ they should be avoided if efficiency is a concern.
1115
+
1116
+ Parameters
1117
+ ----------
1118
+ x : array_like, compatible object
1119
+ If `x` is a list or tuple, it is converted to an ndarray, otherwise
1120
+ it is left unchanged and treated as a scalar. In either case, `x`
1121
+ or its elements must support addition and multiplication with
1122
+ themselves and with the elements of `c`.
1123
+ c : array_like
1124
+ Array of coefficients ordered so that the coefficients for terms of
1125
+ degree n are contained in c[n]. If `c` is multidimensional the
1126
+ remaining indices enumerate multiple polynomials. In the two
1127
+ dimensional case the coefficients may be thought of as stored in
1128
+ the columns of `c`.
1129
+ tensor : boolean, optional
1130
+ If True, the shape of the coefficient array is extended with ones
1131
+ on the right, one for each dimension of `x`. Scalars have dimension 0
1132
+ for this action. The result is that every column of coefficients in
1133
+ `c` is evaluated for every element of `x`. If False, `x` is broadcast
1134
+ over the columns of `c` for the evaluation. This keyword is useful
1135
+ when `c` is multidimensional. The default value is True.
1136
+
1137
+ .. versionadded:: 1.7.0
1138
+
1139
+ Returns
1140
+ -------
1141
+ values : ndarray, algebra_like
1142
+ The shape of the return value is described above.
1143
+
1144
+ See Also
1145
+ --------
1146
+ chebval2d, chebgrid2d, chebval3d, chebgrid3d
1147
+
1148
+ Notes
1149
+ -----
1150
+ The evaluation uses Clenshaw recursion, aka synthetic division.
1151
+
1152
+ """
1153
+ c = np.array(c, ndmin=1, copy=True)
1154
+ if c.dtype.char in '?bBhHiIlLqQpP':
1155
+ c = c.astype(np.double)
1156
+ if isinstance(x, (tuple, list)):
1157
+ x = np.asarray(x)
1158
+ if isinstance(x, np.ndarray) and tensor:
1159
+ c = c.reshape(c.shape + (1,)*x.ndim)
1160
+
1161
+ if len(c) == 1:
1162
+ c0 = c[0]
1163
+ c1 = 0
1164
+ elif len(c) == 2:
1165
+ c0 = c[0]
1166
+ c1 = c[1]
1167
+ else:
1168
+ x2 = 2*x
1169
+ c0 = c[-2]
1170
+ c1 = c[-1]
1171
+ for i in range(3, len(c) + 1):
1172
+ tmp = c0
1173
+ c0 = c[-i] - c1
1174
+ c1 = tmp + c1*x2
1175
+ return c0 + c1*x
1176
+
1177
+
1178
+ def chebval2d(x, y, c):
1179
+ """
1180
+ Evaluate a 2-D Chebyshev series at points (x, y).
1181
+
1182
+ This function returns the values:
1183
+
1184
+ .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y)
1185
+
1186
+ The parameters `x` and `y` are converted to arrays only if they are
1187
+ tuples or a lists, otherwise they are treated as a scalars and they
1188
+ must have the same shape after conversion. In either case, either `x`
1189
+ and `y` or their elements must support multiplication and addition both
1190
+ with themselves and with the elements of `c`.
1191
+
1192
+ If `c` is a 1-D array a one is implicitly appended to its shape to make
1193
+ it 2-D. The shape of the result will be c.shape[2:] + x.shape.
1194
+
1195
+ Parameters
1196
+ ----------
1197
+ x, y : array_like, compatible objects
1198
+ The two dimensional series is evaluated at the points `(x, y)`,
1199
+ where `x` and `y` must have the same shape. If `x` or `y` is a list
1200
+ or tuple, it is first converted to an ndarray, otherwise it is left
1201
+ unchanged and if it isn't an ndarray it is treated as a scalar.
1202
+ c : array_like
1203
+ Array of coefficients ordered so that the coefficient of the term
1204
+ of multi-degree i,j is contained in ``c[i,j]``. If `c` has
1205
+ dimension greater than 2 the remaining indices enumerate multiple
1206
+ sets of coefficients.
1207
+
1208
+ Returns
1209
+ -------
1210
+ values : ndarray, compatible object
1211
+ The values of the two dimensional Chebyshev series at points formed
1212
+ from pairs of corresponding values from `x` and `y`.
1213
+
1214
+ See Also
1215
+ --------
1216
+ chebval, chebgrid2d, chebval3d, chebgrid3d
1217
+
1218
+ Notes
1219
+ -----
1220
+
1221
+ .. versionadded:: 1.7.0
1222
+
1223
+ """
1224
+ return pu._valnd(chebval, c, x, y)
1225
+
1226
+
1227
+ def chebgrid2d(x, y, c):
1228
+ """
1229
+ Evaluate a 2-D Chebyshev series on the Cartesian product of x and y.
1230
+
1231
+ This function returns the values:
1232
+
1233
+ .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * T_i(a) * T_j(b),
1234
+
1235
+ where the points `(a, b)` consist of all pairs formed by taking
1236
+ `a` from `x` and `b` from `y`. The resulting points form a grid with
1237
+ `x` in the first dimension and `y` in the second.
1238
+
1239
+ The parameters `x` and `y` are converted to arrays only if they are
1240
+ tuples or a lists, otherwise they are treated as a scalars. In either
1241
+ case, either `x` and `y` or their elements must support multiplication
1242
+ and addition both with themselves and with the elements of `c`.
1243
+
1244
+ If `c` has fewer than two dimensions, ones are implicitly appended to
1245
+ its shape to make it 2-D. The shape of the result will be c.shape[2:] +
1246
+ x.shape + y.shape.
1247
+
1248
+ Parameters
1249
+ ----------
1250
+ x, y : array_like, compatible objects
1251
+ The two dimensional series is evaluated at the points in the
1252
+ Cartesian product of `x` and `y`. If `x` or `y` is a list or
1253
+ tuple, it is first converted to an ndarray, otherwise it is left
1254
+ unchanged and, if it isn't an ndarray, it is treated as a scalar.
1255
+ c : array_like
1256
+ Array of coefficients ordered so that the coefficient of the term of
1257
+ multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
1258
+ greater than two the remaining indices enumerate multiple sets of
1259
+ coefficients.
1260
+
1261
+ Returns
1262
+ -------
1263
+ values : ndarray, compatible object
1264
+ The values of the two dimensional Chebyshev series at points in the
1265
+ Cartesian product of `x` and `y`.
1266
+
1267
+ See Also
1268
+ --------
1269
+ chebval, chebval2d, chebval3d, chebgrid3d
1270
+
1271
+ Notes
1272
+ -----
1273
+
1274
+ .. versionadded:: 1.7.0
1275
+
1276
+ """
1277
+ return pu._gridnd(chebval, c, x, y)
1278
+
1279
+
1280
+ def chebval3d(x, y, z, c):
1281
+ """
1282
+ Evaluate a 3-D Chebyshev series at points (x, y, z).
1283
+
1284
+ This function returns the values:
1285
+
1286
+ .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z)
1287
+
1288
+ The parameters `x`, `y`, and `z` are converted to arrays only if
1289
+ they are tuples or a lists, otherwise they are treated as a scalars and
1290
+ they must have the same shape after conversion. In either case, either
1291
+ `x`, `y`, and `z` or their elements must support multiplication and
1292
+ addition both with themselves and with the elements of `c`.
1293
+
1294
+ If `c` has fewer than 3 dimensions, ones are implicitly appended to its
1295
+ shape to make it 3-D. The shape of the result will be c.shape[3:] +
1296
+ x.shape.
1297
+
1298
+ Parameters
1299
+ ----------
1300
+ x, y, z : array_like, compatible object
1301
+ The three dimensional series is evaluated at the points
1302
+ `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
1303
+ any of `x`, `y`, or `z` is a list or tuple, it is first converted
1304
+ to an ndarray, otherwise it is left unchanged and if it isn't an
1305
+ ndarray it is treated as a scalar.
1306
+ c : array_like
1307
+ Array of coefficients ordered so that the coefficient of the term of
1308
+ multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
1309
+ greater than 3 the remaining indices enumerate multiple sets of
1310
+ coefficients.
1311
+
1312
+ Returns
1313
+ -------
1314
+ values : ndarray, compatible object
1315
+ The values of the multidimensional polynomial on points formed with
1316
+ triples of corresponding values from `x`, `y`, and `z`.
1317
+
1318
+ See Also
1319
+ --------
1320
+ chebval, chebval2d, chebgrid2d, chebgrid3d
1321
+
1322
+ Notes
1323
+ -----
1324
+
1325
+ .. versionadded:: 1.7.0
1326
+
1327
+ """
1328
+ return pu._valnd(chebval, c, x, y, z)
1329
+
1330
+
1331
+ def chebgrid3d(x, y, z, c):
1332
+ """
1333
+ Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.
1334
+
1335
+ This function returns the values:
1336
+
1337
+ .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)
1338
+
1339
+ where the points `(a, b, c)` consist of all triples formed by taking
1340
+ `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
1341
+ a grid with `x` in the first dimension, `y` in the second, and `z` in
1342
+ the third.
1343
+
1344
+ The parameters `x`, `y`, and `z` are converted to arrays only if they
1345
+ are tuples or a lists, otherwise they are treated as a scalars. In
1346
+ either case, either `x`, `y`, and `z` or their elements must support
1347
+ multiplication and addition both with themselves and with the elements
1348
+ of `c`.
1349
+
1350
+ If `c` has fewer than three dimensions, ones are implicitly appended to
1351
+ its shape to make it 3-D. The shape of the result will be c.shape[3:] +
1352
+ x.shape + y.shape + z.shape.
1353
+
1354
+ Parameters
1355
+ ----------
1356
+ x, y, z : array_like, compatible objects
1357
+ The three dimensional series is evaluated at the points in the
1358
+ Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
1359
+ list or tuple, it is first converted to an ndarray, otherwise it is
1360
+ left unchanged and, if it isn't an ndarray, it is treated as a
1361
+ scalar.
1362
+ c : array_like
1363
+ Array of coefficients ordered so that the coefficients for terms of
1364
+ degree i,j are contained in ``c[i,j]``. If `c` has dimension
1365
+ greater than two the remaining indices enumerate multiple sets of
1366
+ coefficients.
1367
+
1368
+ Returns
1369
+ -------
1370
+ values : ndarray, compatible object
1371
+ The values of the two dimensional polynomial at points in the Cartesian
1372
+ product of `x` and `y`.
1373
+
1374
+ See Also
1375
+ --------
1376
+ chebval, chebval2d, chebgrid2d, chebval3d
1377
+
1378
+ Notes
1379
+ -----
1380
+
1381
+ .. versionadded:: 1.7.0
1382
+
1383
+ """
1384
+ return pu._gridnd(chebval, c, x, y, z)
1385
+
1386
+
1387
+ def chebvander(x, deg):
1388
+ """Pseudo-Vandermonde matrix of given degree.
1389
+
1390
+ Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
1391
+ `x`. The pseudo-Vandermonde matrix is defined by
1392
+
1393
+ .. math:: V[..., i] = T_i(x),
1394
+
1395
+ where `0 <= i <= deg`. The leading indices of `V` index the elements of
1396
+ `x` and the last index is the degree of the Chebyshev polynomial.
1397
+
1398
+ If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
1399
+ matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and
1400
+ ``chebval(x, c)`` are the same up to roundoff. This equivalence is
1401
+ useful both for least squares fitting and for the evaluation of a large
1402
+ number of Chebyshev series of the same degree and sample points.
1403
+
1404
+ Parameters
1405
+ ----------
1406
+ x : array_like
1407
+ Array of points. The dtype is converted to float64 or complex128
1408
+ depending on whether any of the elements are complex. If `x` is
1409
+ scalar it is converted to a 1-D array.
1410
+ deg : int
1411
+ Degree of the resulting matrix.
1412
+
1413
+ Returns
1414
+ -------
1415
+ vander : ndarray
1416
+ The pseudo Vandermonde matrix. The shape of the returned matrix is
1417
+ ``x.shape + (deg + 1,)``, where The last index is the degree of the
1418
+ corresponding Chebyshev polynomial. The dtype will be the same as
1419
+ the converted `x`.
1420
+
1421
+ """
1422
+ ideg = pu._deprecate_as_int(deg, "deg")
1423
+ if ideg < 0:
1424
+ raise ValueError("deg must be non-negative")
1425
+
1426
+ x = np.array(x, copy=False, ndmin=1) + 0.0
1427
+ dims = (ideg + 1,) + x.shape
1428
+ dtyp = x.dtype
1429
+ v = np.empty(dims, dtype=dtyp)
1430
+ # Use forward recursion to generate the entries.
1431
+ v[0] = x*0 + 1
1432
+ if ideg > 0:
1433
+ x2 = 2*x
1434
+ v[1] = x
1435
+ for i in range(2, ideg + 1):
1436
+ v[i] = v[i-1]*x2 - v[i-2]
1437
+ return np.moveaxis(v, 0, -1)
1438
+
1439
+
1440
+ def chebvander2d(x, y, deg):
1441
+ """Pseudo-Vandermonde matrix of given degrees.
1442
+
1443
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1444
+ points `(x, y)`. The pseudo-Vandermonde matrix is defined by
1445
+
1446
+ .. math:: V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y),
1447
+
1448
+ where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
1449
+ `V` index the points `(x, y)` and the last index encodes the degrees of
1450
+ the Chebyshev polynomials.
1451
+
1452
+ If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
1453
+ correspond to the elements of a 2-D coefficient array `c` of shape
1454
+ (xdeg + 1, ydeg + 1) in the order
1455
+
1456
+ .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
1457
+
1458
+ and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same
1459
+ up to roundoff. This equivalence is useful both for least squares
1460
+ fitting and for the evaluation of a large number of 2-D Chebyshev
1461
+ series of the same degrees and sample points.
1462
+
1463
+ Parameters
1464
+ ----------
1465
+ x, y : array_like
1466
+ Arrays of point coordinates, all of the same shape. The dtypes
1467
+ will be converted to either float64 or complex128 depending on
1468
+ whether any of the elements are complex. Scalars are converted to
1469
+ 1-D arrays.
1470
+ deg : list of ints
1471
+ List of maximum degrees of the form [x_deg, y_deg].
1472
+
1473
+ Returns
1474
+ -------
1475
+ vander2d : ndarray
1476
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1477
+ :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same
1478
+ as the converted `x` and `y`.
1479
+
1480
+ See Also
1481
+ --------
1482
+ chebvander, chebvander3d, chebval2d, chebval3d
1483
+
1484
+ Notes
1485
+ -----
1486
+
1487
+ .. versionadded:: 1.7.0
1488
+
1489
+ """
1490
+ return pu._vander_nd_flat((chebvander, chebvander), (x, y), deg)
1491
+
1492
+
1493
+ def chebvander3d(x, y, z, deg):
1494
+ """Pseudo-Vandermonde matrix of given degrees.
1495
+
1496
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1497
+ points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
1498
+ then The pseudo-Vandermonde matrix is defined by
1499
+
1500
+ .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z),
1501
+
1502
+ where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
1503
+ indices of `V` index the points `(x, y, z)` and the last index encodes
1504
+ the degrees of the Chebyshev polynomials.
1505
+
1506
+ If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
1507
+ of `V` correspond to the elements of a 3-D coefficient array `c` of
1508
+ shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
1509
+
1510
+ .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
1511
+
1512
+ and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the
1513
+ same up to roundoff. This equivalence is useful both for least squares
1514
+ fitting and for the evaluation of a large number of 3-D Chebyshev
1515
+ series of the same degrees and sample points.
1516
+
1517
+ Parameters
1518
+ ----------
1519
+ x, y, z : array_like
1520
+ Arrays of point coordinates, all of the same shape. The dtypes will
1521
+ be converted to either float64 or complex128 depending on whether
1522
+ any of the elements are complex. Scalars are converted to 1-D
1523
+ arrays.
1524
+ deg : list of ints
1525
+ List of maximum degrees of the form [x_deg, y_deg, z_deg].
1526
+
1527
+ Returns
1528
+ -------
1529
+ vander3d : ndarray
1530
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1531
+ :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will
1532
+ be the same as the converted `x`, `y`, and `z`.
1533
+
1534
+ See Also
1535
+ --------
1536
+ chebvander, chebvander3d, chebval2d, chebval3d
1537
+
1538
+ Notes
1539
+ -----
1540
+
1541
+ .. versionadded:: 1.7.0
1542
+
1543
+ """
1544
+ return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg)
1545
+
1546
+
1547
+ def chebfit(x, y, deg, rcond=None, full=False, w=None):
1548
+ """
1549
+ Least squares fit of Chebyshev series to data.
1550
+
1551
+ Return the coefficients of a Chebyshev series of degree `deg` that is the
1552
+ least squares fit to the data values `y` given at points `x`. If `y` is
1553
+ 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
1554
+ fits are done, one for each column of `y`, and the resulting
1555
+ coefficients are stored in the corresponding columns of a 2-D return.
1556
+ The fitted polynomial(s) are in the form
1557
+
1558
+ .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x),
1559
+
1560
+ where `n` is `deg`.
1561
+
1562
+ Parameters
1563
+ ----------
1564
+ x : array_like, shape (M,)
1565
+ x-coordinates of the M sample points ``(x[i], y[i])``.
1566
+ y : array_like, shape (M,) or (M, K)
1567
+ y-coordinates of the sample points. Several data sets of sample
1568
+ points sharing the same x-coordinates can be fitted at once by
1569
+ passing in a 2D-array that contains one dataset per column.
1570
+ deg : int or 1-D array_like
1571
+ Degree(s) of the fitting polynomials. If `deg` is a single integer,
1572
+ all terms up to and including the `deg`'th term are included in the
1573
+ fit. For NumPy versions >= 1.11.0 a list of integers specifying the
1574
+ degrees of the terms to include may be used instead.
1575
+ rcond : float, optional
1576
+ Relative condition number of the fit. Singular values smaller than
1577
+ this relative to the largest singular value will be ignored. The
1578
+ default value is len(x)*eps, where eps is the relative precision of
1579
+ the float type, about 2e-16 in most cases.
1580
+ full : bool, optional
1581
+ Switch determining nature of return value. When it is False (the
1582
+ default) just the coefficients are returned, when True diagnostic
1583
+ information from the singular value decomposition is also returned.
1584
+ w : array_like, shape (`M`,), optional
1585
+ Weights. If not None, the weight ``w[i]`` applies to the unsquared
1586
+ residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
1587
+ chosen so that the errors of the products ``w[i]*y[i]`` all have the
1588
+ same variance. When using inverse-variance weighting, use
1589
+ ``w[i] = 1/sigma(y[i])``. The default value is None.
1590
+
1591
+ .. versionadded:: 1.5.0
1592
+
1593
+ Returns
1594
+ -------
1595
+ coef : ndarray, shape (M,) or (M, K)
1596
+ Chebyshev coefficients ordered from low to high. If `y` was 2-D,
1597
+ the coefficients for the data in column k of `y` are in column
1598
+ `k`.
1599
+
1600
+ [residuals, rank, singular_values, rcond] : list
1601
+ These values are only returned if ``full == True``
1602
+
1603
+ - residuals -- sum of squared residuals of the least squares fit
1604
+ - rank -- the numerical rank of the scaled Vandermonde matrix
1605
+ - singular_values -- singular values of the scaled Vandermonde matrix
1606
+ - rcond -- value of `rcond`.
1607
+
1608
+ For more details, see `numpy.linalg.lstsq`.
1609
+
1610
+ Warns
1611
+ -----
1612
+ RankWarning
1613
+ The rank of the coefficient matrix in the least-squares fit is
1614
+ deficient. The warning is only raised if ``full == False``. The
1615
+ warnings can be turned off by
1616
+
1617
+ >>> import warnings
1618
+ >>> warnings.simplefilter('ignore', np.RankWarning)
1619
+
1620
+ See Also
1621
+ --------
1622
+ numpy.polynomial.polynomial.polyfit
1623
+ numpy.polynomial.legendre.legfit
1624
+ numpy.polynomial.laguerre.lagfit
1625
+ numpy.polynomial.hermite.hermfit
1626
+ numpy.polynomial.hermite_e.hermefit
1627
+ chebval : Evaluates a Chebyshev series.
1628
+ chebvander : Vandermonde matrix of Chebyshev series.
1629
+ chebweight : Chebyshev weight function.
1630
+ numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
1631
+ scipy.interpolate.UnivariateSpline : Computes spline fits.
1632
+
1633
+ Notes
1634
+ -----
1635
+ The solution is the coefficients of the Chebyshev series `p` that
1636
+ minimizes the sum of the weighted squared errors
1637
+
1638
+ .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
1639
+
1640
+ where :math:`w_j` are the weights. This problem is solved by setting up
1641
+ as the (typically) overdetermined matrix equation
1642
+
1643
+ .. math:: V(x) * c = w * y,
1644
+
1645
+ where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
1646
+ coefficients to be solved for, `w` are the weights, and `y` are the
1647
+ observed values. This equation is then solved using the singular value
1648
+ decomposition of `V`.
1649
+
1650
+ If some of the singular values of `V` are so small that they are
1651
+ neglected, then a `RankWarning` will be issued. This means that the
1652
+ coefficient values may be poorly determined. Using a lower order fit
1653
+ will usually get rid of the warning. The `rcond` parameter can also be
1654
+ set to a value smaller than its default, but the resulting fit may be
1655
+ spurious and have large contributions from roundoff error.
1656
+
1657
+ Fits using Chebyshev series are usually better conditioned than fits
1658
+ using power series, but much can depend on the distribution of the
1659
+ sample points and the smoothness of the data. If the quality of the fit
1660
+ is inadequate splines may be a good alternative.
1661
+
1662
+ References
1663
+ ----------
1664
+ .. [1] Wikipedia, "Curve fitting",
1665
+ https://en.wikipedia.org/wiki/Curve_fitting
1666
+
1667
+ Examples
1668
+ --------
1669
+
1670
+ """
1671
+ return pu._fit(chebvander, x, y, deg, rcond, full, w)
1672
+
1673
+
1674
+ def chebcompanion(c):
1675
+ """Return the scaled companion matrix of c.
1676
+
1677
+ The basis polynomials are scaled so that the companion matrix is
1678
+ symmetric when `c` is a Chebyshev basis polynomial. This provides
1679
+ better eigenvalue estimates than the unscaled case and for basis
1680
+ polynomials the eigenvalues are guaranteed to be real if
1681
+ `numpy.linalg.eigvalsh` is used to obtain them.
1682
+
1683
+ Parameters
1684
+ ----------
1685
+ c : array_like
1686
+ 1-D array of Chebyshev series coefficients ordered from low to high
1687
+ degree.
1688
+
1689
+ Returns
1690
+ -------
1691
+ mat : ndarray
1692
+ Scaled companion matrix of dimensions (deg, deg).
1693
+
1694
+ Notes
1695
+ -----
1696
+
1697
+ .. versionadded:: 1.7.0
1698
+
1699
+ """
1700
+ # c is a trimmed copy
1701
+ [c] = pu.as_series([c])
1702
+ if len(c) < 2:
1703
+ raise ValueError('Series must have maximum degree of at least 1.')
1704
+ if len(c) == 2:
1705
+ return np.array([[-c[0]/c[1]]])
1706
+
1707
+ n = len(c) - 1
1708
+ mat = np.zeros((n, n), dtype=c.dtype)
1709
+ scl = np.array([1.] + [np.sqrt(.5)]*(n-1))
1710
+ top = mat.reshape(-1)[1::n+1]
1711
+ bot = mat.reshape(-1)[n::n+1]
1712
+ top[0] = np.sqrt(.5)
1713
+ top[1:] = 1/2
1714
+ bot[...] = top
1715
+ mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5
1716
+ return mat
1717
+
1718
+
1719
+ def chebroots(c):
1720
+ """
1721
+ Compute the roots of a Chebyshev series.
1722
+
1723
+ Return the roots (a.k.a. "zeros") of the polynomial
1724
+
1725
+ .. math:: p(x) = \\sum_i c[i] * T_i(x).
1726
+
1727
+ Parameters
1728
+ ----------
1729
+ c : 1-D array_like
1730
+ 1-D array of coefficients.
1731
+
1732
+ Returns
1733
+ -------
1734
+ out : ndarray
1735
+ Array of the roots of the series. If all the roots are real,
1736
+ then `out` is also real, otherwise it is complex.
1737
+
1738
+ See Also
1739
+ --------
1740
+ numpy.polynomial.polynomial.polyroots
1741
+ numpy.polynomial.legendre.legroots
1742
+ numpy.polynomial.laguerre.lagroots
1743
+ numpy.polynomial.hermite.hermroots
1744
+ numpy.polynomial.hermite_e.hermeroots
1745
+
1746
+ Notes
1747
+ -----
1748
+ The root estimates are obtained as the eigenvalues of the companion
1749
+ matrix, Roots far from the origin of the complex plane may have large
1750
+ errors due to the numerical instability of the series for such
1751
+ values. Roots with multiplicity greater than 1 will also show larger
1752
+ errors as the value of the series near such points is relatively
1753
+ insensitive to errors in the roots. Isolated roots near the origin can
1754
+ be improved by a few iterations of Newton's method.
1755
+
1756
+ The Chebyshev series basis polynomials aren't powers of `x` so the
1757
+ results of this function may seem unintuitive.
1758
+
1759
+ Examples
1760
+ --------
1761
+ >>> import numpy.polynomial.chebyshev as cheb
1762
+ >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots
1763
+ array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) # may vary
1764
+
1765
+ """
1766
+ # c is a trimmed copy
1767
+ [c] = pu.as_series([c])
1768
+ if len(c) < 2:
1769
+ return np.array([], dtype=c.dtype)
1770
+ if len(c) == 2:
1771
+ return np.array([-c[0]/c[1]])
1772
+
1773
+ # rotated companion matrix reduces error
1774
+ m = chebcompanion(c)[::-1,::-1]
1775
+ r = la.eigvals(m)
1776
+ r.sort()
1777
+ return r
1778
+
1779
+
1780
+ def chebinterpolate(func, deg, args=()):
1781
+ """Interpolate a function at the Chebyshev points of the first kind.
1782
+
1783
+ Returns the Chebyshev series that interpolates `func` at the Chebyshev
1784
+ points of the first kind in the interval [-1, 1]. The interpolating
1785
+ series tends to a minmax approximation to `func` with increasing `deg`
1786
+ if the function is continuous in the interval.
1787
+
1788
+ .. versionadded:: 1.14.0
1789
+
1790
+ Parameters
1791
+ ----------
1792
+ func : function
1793
+ The function to be approximated. It must be a function of a single
1794
+ variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
1795
+ extra arguments passed in the `args` parameter.
1796
+ deg : int
1797
+ Degree of the interpolating polynomial
1798
+ args : tuple, optional
1799
+ Extra arguments to be used in the function call. Default is no extra
1800
+ arguments.
1801
+
1802
+ Returns
1803
+ -------
1804
+ coef : ndarray, shape (deg + 1,)
1805
+ Chebyshev coefficients of the interpolating series ordered from low to
1806
+ high.
1807
+
1808
+ Examples
1809
+ --------
1810
+ >>> import numpy.polynomial.chebyshev as C
1811
+ >>> C.chebfromfunction(lambda x: np.tanh(x) + 0.5, 8)
1812
+ array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17,
1813
+ -5.42457905e-02, -2.71387850e-16, 4.51658839e-03,
1814
+ 2.46716228e-17, -3.79694221e-04, -3.26899002e-16])
1815
+
1816
+ Notes
1817
+ -----
1818
+
1819
+ The Chebyshev polynomials used in the interpolation are orthogonal when
1820
+ sampled at the Chebyshev points of the first kind. If it is desired to
1821
+ constrain some of the coefficients they can simply be set to the desired
1822
+ value after the interpolation, no new interpolation or fit is needed. This
1823
+ is especially useful if it is known apriori that some of coefficients are
1824
+ zero. For instance, if the function is even then the coefficients of the
1825
+ terms of odd degree in the result can be set to zero.
1826
+
1827
+ """
1828
+ deg = np.asarray(deg)
1829
+
1830
+ # check arguments.
1831
+ if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0:
1832
+ raise TypeError("deg must be an int")
1833
+ if deg < 0:
1834
+ raise ValueError("expected deg >= 0")
1835
+
1836
+ order = deg + 1
1837
+ xcheb = chebpts1(order)
1838
+ yfunc = func(xcheb, *args)
1839
+ m = chebvander(xcheb, deg)
1840
+ c = np.dot(m.T, yfunc)
1841
+ c[0] /= order
1842
+ c[1:] /= 0.5*order
1843
+
1844
+ return c
1845
+
1846
+
1847
+ def chebgauss(deg):
1848
+ """
1849
+ Gauss-Chebyshev quadrature.
1850
+
1851
+ Computes the sample points and weights for Gauss-Chebyshev quadrature.
1852
+ These sample points and weights will correctly integrate polynomials of
1853
+ degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
1854
+ the weight function :math:`f(x) = 1/\\sqrt{1 - x^2}`.
1855
+
1856
+ Parameters
1857
+ ----------
1858
+ deg : int
1859
+ Number of sample points and weights. It must be >= 1.
1860
+
1861
+ Returns
1862
+ -------
1863
+ x : ndarray
1864
+ 1-D ndarray containing the sample points.
1865
+ y : ndarray
1866
+ 1-D ndarray containing the weights.
1867
+
1868
+ Notes
1869
+ -----
1870
+
1871
+ .. versionadded:: 1.7.0
1872
+
1873
+ The results have only been tested up to degree 100, higher degrees may
1874
+ be problematic. For Gauss-Chebyshev there are closed form solutions for
1875
+ the sample points and weights. If n = `deg`, then
1876
+
1877
+ .. math:: x_i = \\cos(\\pi (2 i - 1) / (2 n))
1878
+
1879
+ .. math:: w_i = \\pi / n
1880
+
1881
+ """
1882
+ ideg = pu._deprecate_as_int(deg, "deg")
1883
+ if ideg <= 0:
1884
+ raise ValueError("deg must be a positive integer")
1885
+
1886
+ x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg))
1887
+ w = np.ones(ideg)*(np.pi/ideg)
1888
+
1889
+ return x, w
1890
+
1891
+
1892
+ def chebweight(x):
1893
+ """
1894
+ The weight function of the Chebyshev polynomials.
1895
+
1896
+ The weight function is :math:`1/\\sqrt{1 - x^2}` and the interval of
1897
+ integration is :math:`[-1, 1]`. The Chebyshev polynomials are
1898
+ orthogonal, but not normalized, with respect to this weight function.
1899
+
1900
+ Parameters
1901
+ ----------
1902
+ x : array_like
1903
+ Values at which the weight function will be computed.
1904
+
1905
+ Returns
1906
+ -------
1907
+ w : ndarray
1908
+ The weight function at `x`.
1909
+
1910
+ Notes
1911
+ -----
1912
+
1913
+ .. versionadded:: 1.7.0
1914
+
1915
+ """
1916
+ w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x))
1917
+ return w
1918
+
1919
+
1920
+ def chebpts1(npts):
1921
+ """
1922
+ Chebyshev points of the first kind.
1923
+
1924
+ The Chebyshev points of the first kind are the points ``cos(x)``,
1925
+ where ``x = [pi*(k + .5)/npts for k in range(npts)]``.
1926
+
1927
+ Parameters
1928
+ ----------
1929
+ npts : int
1930
+ Number of sample points desired.
1931
+
1932
+ Returns
1933
+ -------
1934
+ pts : ndarray
1935
+ The Chebyshev points of the first kind.
1936
+
1937
+ See Also
1938
+ --------
1939
+ chebpts2
1940
+
1941
+ Notes
1942
+ -----
1943
+
1944
+ .. versionadded:: 1.5.0
1945
+
1946
+ """
1947
+ _npts = int(npts)
1948
+ if _npts != npts:
1949
+ raise ValueError("npts must be integer")
1950
+ if _npts < 1:
1951
+ raise ValueError("npts must be >= 1")
1952
+
1953
+ x = 0.5 * np.pi / _npts * np.arange(-_npts+1, _npts+1, 2)
1954
+ return np.sin(x)
1955
+
1956
+
1957
+ def chebpts2(npts):
1958
+ """
1959
+ Chebyshev points of the second kind.
1960
+
1961
+ The Chebyshev points of the second kind are the points ``cos(x)``,
1962
+ where ``x = [pi*k/(npts - 1) for k in range(npts)]`` sorted in ascending
1963
+ order.
1964
+
1965
+ Parameters
1966
+ ----------
1967
+ npts : int
1968
+ Number of sample points desired.
1969
+
1970
+ Returns
1971
+ -------
1972
+ pts : ndarray
1973
+ The Chebyshev points of the second kind.
1974
+
1975
+ Notes
1976
+ -----
1977
+
1978
+ .. versionadded:: 1.5.0
1979
+
1980
+ """
1981
+ _npts = int(npts)
1982
+ if _npts != npts:
1983
+ raise ValueError("npts must be integer")
1984
+ if _npts < 2:
1985
+ raise ValueError("npts must be >= 2")
1986
+
1987
+ x = np.linspace(-np.pi, 0, _npts)
1988
+ return np.cos(x)
1989
+
1990
+
1991
+ #
1992
+ # Chebyshev series class
1993
+ #
1994
+
1995
+ class Chebyshev(ABCPolyBase):
1996
+ """A Chebyshev series class.
1997
+
1998
+ The Chebyshev class provides the standard Python numerical methods
1999
+ '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
2000
+ methods listed below.
2001
+
2002
+ Parameters
2003
+ ----------
2004
+ coef : array_like
2005
+ Chebyshev coefficients in order of increasing degree, i.e.,
2006
+ ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``.
2007
+ domain : (2,) array_like, optional
2008
+ Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
2009
+ to the interval ``[window[0], window[1]]`` by shifting and scaling.
2010
+ The default value is [-1, 1].
2011
+ window : (2,) array_like, optional
2012
+ Window, see `domain` for its use. The default value is [-1, 1].
2013
+
2014
+ .. versionadded:: 1.6.0
2015
+ symbol : str, optional
2016
+ Symbol used to represent the independent variable in string
2017
+ representations of the polynomial expression, e.g. for printing.
2018
+ The symbol must be a valid Python identifier. Default value is 'x'.
2019
+
2020
+ .. versionadded:: 1.24
2021
+
2022
+ """
2023
+ # Virtual Functions
2024
+ _add = staticmethod(chebadd)
2025
+ _sub = staticmethod(chebsub)
2026
+ _mul = staticmethod(chebmul)
2027
+ _div = staticmethod(chebdiv)
2028
+ _pow = staticmethod(chebpow)
2029
+ _val = staticmethod(chebval)
2030
+ _int = staticmethod(chebint)
2031
+ _der = staticmethod(chebder)
2032
+ _fit = staticmethod(chebfit)
2033
+ _line = staticmethod(chebline)
2034
+ _roots = staticmethod(chebroots)
2035
+ _fromroots = staticmethod(chebfromroots)
2036
+
2037
+ @classmethod
2038
+ def interpolate(cls, func, deg, domain=None, args=()):
2039
+ """Interpolate a function at the Chebyshev points of the first kind.
2040
+
2041
+ Returns the series that interpolates `func` at the Chebyshev points of
2042
+ the first kind scaled and shifted to the `domain`. The resulting series
2043
+ tends to a minmax approximation of `func` when the function is
2044
+ continuous in the domain.
2045
+
2046
+ .. versionadded:: 1.14.0
2047
+
2048
+ Parameters
2049
+ ----------
2050
+ func : function
2051
+ The function to be interpolated. It must be a function of a single
2052
+ variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
2053
+ extra arguments passed in the `args` parameter.
2054
+ deg : int
2055
+ Degree of the interpolating polynomial.
2056
+ domain : {None, [beg, end]}, optional
2057
+ Domain over which `func` is interpolated. The default is None, in
2058
+ which case the domain is [-1, 1].
2059
+ args : tuple, optional
2060
+ Extra arguments to be used in the function call. Default is no
2061
+ extra arguments.
2062
+
2063
+ Returns
2064
+ -------
2065
+ polynomial : Chebyshev instance
2066
+ Interpolating Chebyshev instance.
2067
+
2068
+ Notes
2069
+ -----
2070
+ See `numpy.polynomial.chebfromfunction` for more details.
2071
+
2072
+ """
2073
+ if domain is None:
2074
+ domain = cls.domain
2075
+ xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args)
2076
+ coef = chebinterpolate(xfunc, deg)
2077
+ return cls(coef, domain=domain)
2078
+
2079
+ # Virtual properties
2080
+ domain = np.array(chebdomain)
2081
+ window = np.array(chebdomain)
2082
+ basis_name = 'T'
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/chebyshev.pyi ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from numpy import ndarray, dtype, int_
4
+ from numpy.polynomial._polybase import ABCPolyBase
5
+ from numpy.polynomial.polyutils import trimcoef
6
+
7
+ __all__: list[str]
8
+
9
+ chebtrim = trimcoef
10
+
11
+ def poly2cheb(pol): ...
12
+ def cheb2poly(c): ...
13
+
14
+ chebdomain: ndarray[Any, dtype[int_]]
15
+ chebzero: ndarray[Any, dtype[int_]]
16
+ chebone: ndarray[Any, dtype[int_]]
17
+ chebx: ndarray[Any, dtype[int_]]
18
+
19
+ def chebline(off, scl): ...
20
+ def chebfromroots(roots): ...
21
+ def chebadd(c1, c2): ...
22
+ def chebsub(c1, c2): ...
23
+ def chebmulx(c): ...
24
+ def chebmul(c1, c2): ...
25
+ def chebdiv(c1, c2): ...
26
+ def chebpow(c, pow, maxpower=...): ...
27
+ def chebder(c, m=..., scl=..., axis=...): ...
28
+ def chebint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...
29
+ def chebval(x, c, tensor=...): ...
30
+ def chebval2d(x, y, c): ...
31
+ def chebgrid2d(x, y, c): ...
32
+ def chebval3d(x, y, z, c): ...
33
+ def chebgrid3d(x, y, z, c): ...
34
+ def chebvander(x, deg): ...
35
+ def chebvander2d(x, y, deg): ...
36
+ def chebvander3d(x, y, z, deg): ...
37
+ def chebfit(x, y, deg, rcond=..., full=..., w=...): ...
38
+ def chebcompanion(c): ...
39
+ def chebroots(c): ...
40
+ def chebinterpolate(func, deg, args = ...): ...
41
+ def chebgauss(deg): ...
42
+ def chebweight(x): ...
43
+ def chebpts1(npts): ...
44
+ def chebpts2(npts): ...
45
+
46
+ class Chebyshev(ABCPolyBase):
47
+ @classmethod
48
+ def interpolate(cls, func, deg, domain=..., args = ...): ...
49
+ domain: Any
50
+ window: Any
51
+ basis_name: Any
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/hermite.py ADDED
@@ -0,0 +1,1703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ==============================================================
3
+ Hermite Series, "Physicists" (:mod:`numpy.polynomial.hermite`)
4
+ ==============================================================
5
+
6
+ This module provides a number of objects (mostly functions) useful for
7
+ dealing with Hermite series, including a `Hermite` class that
8
+ encapsulates the usual arithmetic operations. (General information
9
+ on how this module represents and works with such polynomials is in the
10
+ docstring for its "parent" sub-package, `numpy.polynomial`).
11
+
12
+ Classes
13
+ -------
14
+ .. autosummary::
15
+ :toctree: generated/
16
+
17
+ Hermite
18
+
19
+ Constants
20
+ ---------
21
+ .. autosummary::
22
+ :toctree: generated/
23
+
24
+ hermdomain
25
+ hermzero
26
+ hermone
27
+ hermx
28
+
29
+ Arithmetic
30
+ ----------
31
+ .. autosummary::
32
+ :toctree: generated/
33
+
34
+ hermadd
35
+ hermsub
36
+ hermmulx
37
+ hermmul
38
+ hermdiv
39
+ hermpow
40
+ hermval
41
+ hermval2d
42
+ hermval3d
43
+ hermgrid2d
44
+ hermgrid3d
45
+
46
+ Calculus
47
+ --------
48
+ .. autosummary::
49
+ :toctree: generated/
50
+
51
+ hermder
52
+ hermint
53
+
54
+ Misc Functions
55
+ --------------
56
+ .. autosummary::
57
+ :toctree: generated/
58
+
59
+ hermfromroots
60
+ hermroots
61
+ hermvander
62
+ hermvander2d
63
+ hermvander3d
64
+ hermgauss
65
+ hermweight
66
+ hermcompanion
67
+ hermfit
68
+ hermtrim
69
+ hermline
70
+ herm2poly
71
+ poly2herm
72
+
73
+ See also
74
+ --------
75
+ `numpy.polynomial`
76
+
77
+ """
78
+ import numpy as np
79
+ import numpy.linalg as la
80
+ from numpy.core.multiarray import normalize_axis_index
81
+
82
+ from . import polyutils as pu
83
+ from ._polybase import ABCPolyBase
84
+
85
+ __all__ = [
86
+ 'hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline', 'hermadd',
87
+ 'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow', 'hermval',
88
+ 'hermder', 'hermint', 'herm2poly', 'poly2herm', 'hermfromroots',
89
+ 'hermvander', 'hermfit', 'hermtrim', 'hermroots', 'Hermite',
90
+ 'hermval2d', 'hermval3d', 'hermgrid2d', 'hermgrid3d', 'hermvander2d',
91
+ 'hermvander3d', 'hermcompanion', 'hermgauss', 'hermweight']
92
+
93
+ hermtrim = pu.trimcoef
94
+
95
+
96
+ def poly2herm(pol):
97
+ """
98
+ poly2herm(pol)
99
+
100
+ Convert a polynomial to a Hermite series.
101
+
102
+ Convert an array representing the coefficients of a polynomial (relative
103
+ to the "standard" basis) ordered from lowest degree to highest, to an
104
+ array of the coefficients of the equivalent Hermite series, ordered
105
+ from lowest to highest degree.
106
+
107
+ Parameters
108
+ ----------
109
+ pol : array_like
110
+ 1-D array containing the polynomial coefficients
111
+
112
+ Returns
113
+ -------
114
+ c : ndarray
115
+ 1-D array containing the coefficients of the equivalent Hermite
116
+ series.
117
+
118
+ See Also
119
+ --------
120
+ herm2poly
121
+
122
+ Notes
123
+ -----
124
+ The easy way to do conversions between polynomial basis sets
125
+ is to use the convert method of a class instance.
126
+
127
+ Examples
128
+ --------
129
+ >>> from numpy.polynomial.hermite import poly2herm
130
+ >>> poly2herm(np.arange(4))
131
+ array([1. , 2.75 , 0.5 , 0.375])
132
+
133
+ """
134
+ [pol] = pu.as_series([pol])
135
+ deg = len(pol) - 1
136
+ res = 0
137
+ for i in range(deg, -1, -1):
138
+ res = hermadd(hermmulx(res), pol[i])
139
+ return res
140
+
141
+
142
+ def herm2poly(c):
143
+ """
144
+ Convert a Hermite series to a polynomial.
145
+
146
+ Convert an array representing the coefficients of a Hermite series,
147
+ ordered from lowest degree to highest, to an array of the coefficients
148
+ of the equivalent polynomial (relative to the "standard" basis) ordered
149
+ from lowest to highest degree.
150
+
151
+ Parameters
152
+ ----------
153
+ c : array_like
154
+ 1-D array containing the Hermite series coefficients, ordered
155
+ from lowest order term to highest.
156
+
157
+ Returns
158
+ -------
159
+ pol : ndarray
160
+ 1-D array containing the coefficients of the equivalent polynomial
161
+ (relative to the "standard" basis) ordered from lowest order term
162
+ to highest.
163
+
164
+ See Also
165
+ --------
166
+ poly2herm
167
+
168
+ Notes
169
+ -----
170
+ The easy way to do conversions between polynomial basis sets
171
+ is to use the convert method of a class instance.
172
+
173
+ Examples
174
+ --------
175
+ >>> from numpy.polynomial.hermite import herm2poly
176
+ >>> herm2poly([ 1. , 2.75 , 0.5 , 0.375])
177
+ array([0., 1., 2., 3.])
178
+
179
+ """
180
+ from .polynomial import polyadd, polysub, polymulx
181
+
182
+ [c] = pu.as_series([c])
183
+ n = len(c)
184
+ if n == 1:
185
+ return c
186
+ if n == 2:
187
+ c[1] *= 2
188
+ return c
189
+ else:
190
+ c0 = c[-2]
191
+ c1 = c[-1]
192
+ # i is the current degree of c1
193
+ for i in range(n - 1, 1, -1):
194
+ tmp = c0
195
+ c0 = polysub(c[i - 2], c1*(2*(i - 1)))
196
+ c1 = polyadd(tmp, polymulx(c1)*2)
197
+ return polyadd(c0, polymulx(c1)*2)
198
+
199
+ #
200
+ # These are constant arrays are of integer type so as to be compatible
201
+ # with the widest range of other types, such as Decimal.
202
+ #
203
+
204
+ # Hermite
205
+ hermdomain = np.array([-1, 1])
206
+
207
+ # Hermite coefficients representing zero.
208
+ hermzero = np.array([0])
209
+
210
+ # Hermite coefficients representing one.
211
+ hermone = np.array([1])
212
+
213
+ # Hermite coefficients representing the identity x.
214
+ hermx = np.array([0, 1/2])
215
+
216
+
217
+ def hermline(off, scl):
218
+ """
219
+ Hermite series whose graph is a straight line.
220
+
221
+
222
+
223
+ Parameters
224
+ ----------
225
+ off, scl : scalars
226
+ The specified line is given by ``off + scl*x``.
227
+
228
+ Returns
229
+ -------
230
+ y : ndarray
231
+ This module's representation of the Hermite series for
232
+ ``off + scl*x``.
233
+
234
+ See Also
235
+ --------
236
+ numpy.polynomial.polynomial.polyline
237
+ numpy.polynomial.chebyshev.chebline
238
+ numpy.polynomial.legendre.legline
239
+ numpy.polynomial.laguerre.lagline
240
+ numpy.polynomial.hermite_e.hermeline
241
+
242
+ Examples
243
+ --------
244
+ >>> from numpy.polynomial.hermite import hermline, hermval
245
+ >>> hermval(0,hermline(3, 2))
246
+ 3.0
247
+ >>> hermval(1,hermline(3, 2))
248
+ 5.0
249
+
250
+ """
251
+ if scl != 0:
252
+ return np.array([off, scl/2])
253
+ else:
254
+ return np.array([off])
255
+
256
+
257
+ def hermfromroots(roots):
258
+ """
259
+ Generate a Hermite series with given roots.
260
+
261
+ The function returns the coefficients of the polynomial
262
+
263
+ .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
264
+
265
+ in Hermite form, where the `r_n` are the roots specified in `roots`.
266
+ If a zero has multiplicity n, then it must appear in `roots` n times.
267
+ For instance, if 2 is a root of multiplicity three and 3 is a root of
268
+ multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
269
+ roots can appear in any order.
270
+
271
+ If the returned coefficients are `c`, then
272
+
273
+ .. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x)
274
+
275
+ The coefficient of the last term is not generally 1 for monic
276
+ polynomials in Hermite form.
277
+
278
+ Parameters
279
+ ----------
280
+ roots : array_like
281
+ Sequence containing the roots.
282
+
283
+ Returns
284
+ -------
285
+ out : ndarray
286
+ 1-D array of coefficients. If all roots are real then `out` is a
287
+ real array, if some of the roots are complex, then `out` is complex
288
+ even if all the coefficients in the result are real (see Examples
289
+ below).
290
+
291
+ See Also
292
+ --------
293
+ numpy.polynomial.polynomial.polyfromroots
294
+ numpy.polynomial.legendre.legfromroots
295
+ numpy.polynomial.laguerre.lagfromroots
296
+ numpy.polynomial.chebyshev.chebfromroots
297
+ numpy.polynomial.hermite_e.hermefromroots
298
+
299
+ Examples
300
+ --------
301
+ >>> from numpy.polynomial.hermite import hermfromroots, hermval
302
+ >>> coef = hermfromroots((-1, 0, 1))
303
+ >>> hermval((-1, 0, 1), coef)
304
+ array([0., 0., 0.])
305
+ >>> coef = hermfromroots((-1j, 1j))
306
+ >>> hermval((-1j, 1j), coef)
307
+ array([0.+0.j, 0.+0.j])
308
+
309
+ """
310
+ return pu._fromroots(hermline, hermmul, roots)
311
+
312
+
313
+ def hermadd(c1, c2):
314
+ """
315
+ Add one Hermite series to another.
316
+
317
+ Returns the sum of two Hermite series `c1` + `c2`. The arguments
318
+ are sequences of coefficients ordered from lowest order term to
319
+ highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
320
+
321
+ Parameters
322
+ ----------
323
+ c1, c2 : array_like
324
+ 1-D arrays of Hermite series coefficients ordered from low to
325
+ high.
326
+
327
+ Returns
328
+ -------
329
+ out : ndarray
330
+ Array representing the Hermite series of their sum.
331
+
332
+ See Also
333
+ --------
334
+ hermsub, hermmulx, hermmul, hermdiv, hermpow
335
+
336
+ Notes
337
+ -----
338
+ Unlike multiplication, division, etc., the sum of two Hermite series
339
+ is a Hermite series (without having to "reproject" the result onto
340
+ the basis set) so addition, just like that of "standard" polynomials,
341
+ is simply "component-wise."
342
+
343
+ Examples
344
+ --------
345
+ >>> from numpy.polynomial.hermite import hermadd
346
+ >>> hermadd([1, 2, 3], [1, 2, 3, 4])
347
+ array([2., 4., 6., 4.])
348
+
349
+ """
350
+ return pu._add(c1, c2)
351
+
352
+
353
+ def hermsub(c1, c2):
354
+ """
355
+ Subtract one Hermite series from another.
356
+
357
+ Returns the difference of two Hermite series `c1` - `c2`. The
358
+ sequences of coefficients are from lowest order term to highest, i.e.,
359
+ [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
360
+
361
+ Parameters
362
+ ----------
363
+ c1, c2 : array_like
364
+ 1-D arrays of Hermite series coefficients ordered from low to
365
+ high.
366
+
367
+ Returns
368
+ -------
369
+ out : ndarray
370
+ Of Hermite series coefficients representing their difference.
371
+
372
+ See Also
373
+ --------
374
+ hermadd, hermmulx, hermmul, hermdiv, hermpow
375
+
376
+ Notes
377
+ -----
378
+ Unlike multiplication, division, etc., the difference of two Hermite
379
+ series is a Hermite series (without having to "reproject" the result
380
+ onto the basis set) so subtraction, just like that of "standard"
381
+ polynomials, is simply "component-wise."
382
+
383
+ Examples
384
+ --------
385
+ >>> from numpy.polynomial.hermite import hermsub
386
+ >>> hermsub([1, 2, 3, 4], [1, 2, 3])
387
+ array([0., 0., 0., 4.])
388
+
389
+ """
390
+ return pu._sub(c1, c2)
391
+
392
+
393
+ def hermmulx(c):
394
+ """Multiply a Hermite series by x.
395
+
396
+ Multiply the Hermite series `c` by x, where x is the independent
397
+ variable.
398
+
399
+
400
+ Parameters
401
+ ----------
402
+ c : array_like
403
+ 1-D array of Hermite series coefficients ordered from low to
404
+ high.
405
+
406
+ Returns
407
+ -------
408
+ out : ndarray
409
+ Array representing the result of the multiplication.
410
+
411
+ See Also
412
+ --------
413
+ hermadd, hermsub, hermmul, hermdiv, hermpow
414
+
415
+ Notes
416
+ -----
417
+ The multiplication uses the recursion relationship for Hermite
418
+ polynomials in the form
419
+
420
+ .. math::
421
+
422
+ xP_i(x) = (P_{i + 1}(x)/2 + i*P_{i - 1}(x))
423
+
424
+ Examples
425
+ --------
426
+ >>> from numpy.polynomial.hermite import hermmulx
427
+ >>> hermmulx([1, 2, 3])
428
+ array([2. , 6.5, 1. , 1.5])
429
+
430
+ """
431
+ # c is a trimmed copy
432
+ [c] = pu.as_series([c])
433
+ # The zero series needs special treatment
434
+ if len(c) == 1 and c[0] == 0:
435
+ return c
436
+
437
+ prd = np.empty(len(c) + 1, dtype=c.dtype)
438
+ prd[0] = c[0]*0
439
+ prd[1] = c[0]/2
440
+ for i in range(1, len(c)):
441
+ prd[i + 1] = c[i]/2
442
+ prd[i - 1] += c[i]*i
443
+ return prd
444
+
445
+
446
+ def hermmul(c1, c2):
447
+ """
448
+ Multiply one Hermite series by another.
449
+
450
+ Returns the product of two Hermite series `c1` * `c2`. The arguments
451
+ are sequences of coefficients, from lowest order "term" to highest,
452
+ e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
453
+
454
+ Parameters
455
+ ----------
456
+ c1, c2 : array_like
457
+ 1-D arrays of Hermite series coefficients ordered from low to
458
+ high.
459
+
460
+ Returns
461
+ -------
462
+ out : ndarray
463
+ Of Hermite series coefficients representing their product.
464
+
465
+ See Also
466
+ --------
467
+ hermadd, hermsub, hermmulx, hermdiv, hermpow
468
+
469
+ Notes
470
+ -----
471
+ In general, the (polynomial) product of two C-series results in terms
472
+ that are not in the Hermite polynomial basis set. Thus, to express
473
+ the product as a Hermite series, it is necessary to "reproject" the
474
+ product onto said basis set, which may produce "unintuitive" (but
475
+ correct) results; see Examples section below.
476
+
477
+ Examples
478
+ --------
479
+ >>> from numpy.polynomial.hermite import hermmul
480
+ >>> hermmul([1, 2, 3], [0, 1, 2])
481
+ array([52., 29., 52., 7., 6.])
482
+
483
+ """
484
+ # s1, s2 are trimmed copies
485
+ [c1, c2] = pu.as_series([c1, c2])
486
+
487
+ if len(c1) > len(c2):
488
+ c = c2
489
+ xs = c1
490
+ else:
491
+ c = c1
492
+ xs = c2
493
+
494
+ if len(c) == 1:
495
+ c0 = c[0]*xs
496
+ c1 = 0
497
+ elif len(c) == 2:
498
+ c0 = c[0]*xs
499
+ c1 = c[1]*xs
500
+ else:
501
+ nd = len(c)
502
+ c0 = c[-2]*xs
503
+ c1 = c[-1]*xs
504
+ for i in range(3, len(c) + 1):
505
+ tmp = c0
506
+ nd = nd - 1
507
+ c0 = hermsub(c[-i]*xs, c1*(2*(nd - 1)))
508
+ c1 = hermadd(tmp, hermmulx(c1)*2)
509
+ return hermadd(c0, hermmulx(c1)*2)
510
+
511
+
512
+ def hermdiv(c1, c2):
513
+ """
514
+ Divide one Hermite series by another.
515
+
516
+ Returns the quotient-with-remainder of two Hermite series
517
+ `c1` / `c2`. The arguments are sequences of coefficients from lowest
518
+ order "term" to highest, e.g., [1,2,3] represents the series
519
+ ``P_0 + 2*P_1 + 3*P_2``.
520
+
521
+ Parameters
522
+ ----------
523
+ c1, c2 : array_like
524
+ 1-D arrays of Hermite series coefficients ordered from low to
525
+ high.
526
+
527
+ Returns
528
+ -------
529
+ [quo, rem] : ndarrays
530
+ Of Hermite series coefficients representing the quotient and
531
+ remainder.
532
+
533
+ See Also
534
+ --------
535
+ hermadd, hermsub, hermmulx, hermmul, hermpow
536
+
537
+ Notes
538
+ -----
539
+ In general, the (polynomial) division of one Hermite series by another
540
+ results in quotient and remainder terms that are not in the Hermite
541
+ polynomial basis set. Thus, to express these results as a Hermite
542
+ series, it is necessary to "reproject" the results onto the Hermite
543
+ basis set, which may produce "unintuitive" (but correct) results; see
544
+ Examples section below.
545
+
546
+ Examples
547
+ --------
548
+ >>> from numpy.polynomial.hermite import hermdiv
549
+ >>> hermdiv([ 52., 29., 52., 7., 6.], [0, 1, 2])
550
+ (array([1., 2., 3.]), array([0.]))
551
+ >>> hermdiv([ 54., 31., 52., 7., 6.], [0, 1, 2])
552
+ (array([1., 2., 3.]), array([2., 2.]))
553
+ >>> hermdiv([ 53., 30., 52., 7., 6.], [0, 1, 2])
554
+ (array([1., 2., 3.]), array([1., 1.]))
555
+
556
+ """
557
+ return pu._div(hermmul, c1, c2)
558
+
559
+
560
+ def hermpow(c, pow, maxpower=16):
561
+ """Raise a Hermite series to a power.
562
+
563
+ Returns the Hermite series `c` raised to the power `pow`. The
564
+ argument `c` is a sequence of coefficients ordered from low to high.
565
+ i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``
566
+
567
+ Parameters
568
+ ----------
569
+ c : array_like
570
+ 1-D array of Hermite series coefficients ordered from low to
571
+ high.
572
+ pow : integer
573
+ Power to which the series will be raised
574
+ maxpower : integer, optional
575
+ Maximum power allowed. This is mainly to limit growth of the series
576
+ to unmanageable size. Default is 16
577
+
578
+ Returns
579
+ -------
580
+ coef : ndarray
581
+ Hermite series of power.
582
+
583
+ See Also
584
+ --------
585
+ hermadd, hermsub, hermmulx, hermmul, hermdiv
586
+
587
+ Examples
588
+ --------
589
+ >>> from numpy.polynomial.hermite import hermpow
590
+ >>> hermpow([1, 2, 3], 2)
591
+ array([81., 52., 82., 12., 9.])
592
+
593
+ """
594
+ return pu._pow(hermmul, c, pow, maxpower)
595
+
596
+
597
+ def hermder(c, m=1, scl=1, axis=0):
598
+ """
599
+ Differentiate a Hermite series.
600
+
601
+ Returns the Hermite series coefficients `c` differentiated `m` times
602
+ along `axis`. At each iteration the result is multiplied by `scl` (the
603
+ scaling factor is for use in a linear change of variable). The argument
604
+ `c` is an array of coefficients from low to high degree along each
605
+ axis, e.g., [1,2,3] represents the series ``1*H_0 + 2*H_1 + 3*H_2``
606
+ while [[1,2],[1,2]] represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) +
607
+ 2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is
608
+ ``y``.
609
+
610
+ Parameters
611
+ ----------
612
+ c : array_like
613
+ Array of Hermite series coefficients. If `c` is multidimensional the
614
+ different axis correspond to different variables with the degree in
615
+ each axis given by the corresponding index.
616
+ m : int, optional
617
+ Number of derivatives taken, must be non-negative. (Default: 1)
618
+ scl : scalar, optional
619
+ Each differentiation is multiplied by `scl`. The end result is
620
+ multiplication by ``scl**m``. This is for use in a linear change of
621
+ variable. (Default: 1)
622
+ axis : int, optional
623
+ Axis over which the derivative is taken. (Default: 0).
624
+
625
+ .. versionadded:: 1.7.0
626
+
627
+ Returns
628
+ -------
629
+ der : ndarray
630
+ Hermite series of the derivative.
631
+
632
+ See Also
633
+ --------
634
+ hermint
635
+
636
+ Notes
637
+ -----
638
+ In general, the result of differentiating a Hermite series does not
639
+ resemble the same operation on a power series. Thus the result of this
640
+ function may be "unintuitive," albeit correct; see Examples section
641
+ below.
642
+
643
+ Examples
644
+ --------
645
+ >>> from numpy.polynomial.hermite import hermder
646
+ >>> hermder([ 1. , 0.5, 0.5, 0.5])
647
+ array([1., 2., 3.])
648
+ >>> hermder([-0.5, 1./2., 1./8., 1./12., 1./16.], m=2)
649
+ array([1., 2., 3.])
650
+
651
+ """
652
+ c = np.array(c, ndmin=1, copy=True)
653
+ if c.dtype.char in '?bBhHiIlLqQpP':
654
+ c = c.astype(np.double)
655
+ cnt = pu._deprecate_as_int(m, "the order of derivation")
656
+ iaxis = pu._deprecate_as_int(axis, "the axis")
657
+ if cnt < 0:
658
+ raise ValueError("The order of derivation must be non-negative")
659
+ iaxis = normalize_axis_index(iaxis, c.ndim)
660
+
661
+ if cnt == 0:
662
+ return c
663
+
664
+ c = np.moveaxis(c, iaxis, 0)
665
+ n = len(c)
666
+ if cnt >= n:
667
+ c = c[:1]*0
668
+ else:
669
+ for i in range(cnt):
670
+ n = n - 1
671
+ c *= scl
672
+ der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
673
+ for j in range(n, 0, -1):
674
+ der[j - 1] = (2*j)*c[j]
675
+ c = der
676
+ c = np.moveaxis(c, 0, iaxis)
677
+ return c
678
+
679
+
680
+ def hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
681
+ """
682
+ Integrate a Hermite series.
683
+
684
+ Returns the Hermite series coefficients `c` integrated `m` times from
685
+ `lbnd` along `axis`. At each iteration the resulting series is
686
+ **multiplied** by `scl` and an integration constant, `k`, is added.
687
+ The scaling factor is for use in a linear change of variable. ("Buyer
688
+ beware": note that, depending on what one is doing, one may want `scl`
689
+ to be the reciprocal of what one might expect; for more information,
690
+ see the Notes section below.) The argument `c` is an array of
691
+ coefficients from low to high degree along each axis, e.g., [1,2,3]
692
+ represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]
693
+ represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +
694
+ 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
695
+
696
+ Parameters
697
+ ----------
698
+ c : array_like
699
+ Array of Hermite series coefficients. If c is multidimensional the
700
+ different axis correspond to different variables with the degree in
701
+ each axis given by the corresponding index.
702
+ m : int, optional
703
+ Order of integration, must be positive. (Default: 1)
704
+ k : {[], list, scalar}, optional
705
+ Integration constant(s). The value of the first integral at
706
+ ``lbnd`` is the first value in the list, the value of the second
707
+ integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
708
+ default), all constants are set to zero. If ``m == 1``, a single
709
+ scalar can be given instead of a list.
710
+ lbnd : scalar, optional
711
+ The lower bound of the integral. (Default: 0)
712
+ scl : scalar, optional
713
+ Following each integration the result is *multiplied* by `scl`
714
+ before the integration constant is added. (Default: 1)
715
+ axis : int, optional
716
+ Axis over which the integral is taken. (Default: 0).
717
+
718
+ .. versionadded:: 1.7.0
719
+
720
+ Returns
721
+ -------
722
+ S : ndarray
723
+ Hermite series coefficients of the integral.
724
+
725
+ Raises
726
+ ------
727
+ ValueError
728
+ If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
729
+ ``np.ndim(scl) != 0``.
730
+
731
+ See Also
732
+ --------
733
+ hermder
734
+
735
+ Notes
736
+ -----
737
+ Note that the result of each integration is *multiplied* by `scl`.
738
+ Why is this important to note? Say one is making a linear change of
739
+ variable :math:`u = ax + b` in an integral relative to `x`. Then
740
+ :math:`dx = du/a`, so one will need to set `scl` equal to
741
+ :math:`1/a` - perhaps not what one would have first thought.
742
+
743
+ Also note that, in general, the result of integrating a C-series needs
744
+ to be "reprojected" onto the C-series basis set. Thus, typically,
745
+ the result of this function is "unintuitive," albeit correct; see
746
+ Examples section below.
747
+
748
+ Examples
749
+ --------
750
+ >>> from numpy.polynomial.hermite import hermint
751
+ >>> hermint([1,2,3]) # integrate once, value 0 at 0.
752
+ array([1. , 0.5, 0.5, 0.5])
753
+ >>> hermint([1,2,3], m=2) # integrate twice, value & deriv 0 at 0
754
+ array([-0.5 , 0.5 , 0.125 , 0.08333333, 0.0625 ]) # may vary
755
+ >>> hermint([1,2,3], k=1) # integrate once, value 1 at 0.
756
+ array([2. , 0.5, 0.5, 0.5])
757
+ >>> hermint([1,2,3], lbnd=-1) # integrate once, value 0 at -1
758
+ array([-2. , 0.5, 0.5, 0.5])
759
+ >>> hermint([1,2,3], m=2, k=[1,2], lbnd=-1)
760
+ array([ 1.66666667, -0.5 , 0.125 , 0.08333333, 0.0625 ]) # may vary
761
+
762
+ """
763
+ c = np.array(c, ndmin=1, copy=True)
764
+ if c.dtype.char in '?bBhHiIlLqQpP':
765
+ c = c.astype(np.double)
766
+ if not np.iterable(k):
767
+ k = [k]
768
+ cnt = pu._deprecate_as_int(m, "the order of integration")
769
+ iaxis = pu._deprecate_as_int(axis, "the axis")
770
+ if cnt < 0:
771
+ raise ValueError("The order of integration must be non-negative")
772
+ if len(k) > cnt:
773
+ raise ValueError("Too many integration constants")
774
+ if np.ndim(lbnd) != 0:
775
+ raise ValueError("lbnd must be a scalar.")
776
+ if np.ndim(scl) != 0:
777
+ raise ValueError("scl must be a scalar.")
778
+ iaxis = normalize_axis_index(iaxis, c.ndim)
779
+
780
+ if cnt == 0:
781
+ return c
782
+
783
+ c = np.moveaxis(c, iaxis, 0)
784
+ k = list(k) + [0]*(cnt - len(k))
785
+ for i in range(cnt):
786
+ n = len(c)
787
+ c *= scl
788
+ if n == 1 and np.all(c[0] == 0):
789
+ c[0] += k[i]
790
+ else:
791
+ tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
792
+ tmp[0] = c[0]*0
793
+ tmp[1] = c[0]/2
794
+ for j in range(1, n):
795
+ tmp[j + 1] = c[j]/(2*(j + 1))
796
+ tmp[0] += k[i] - hermval(lbnd, tmp)
797
+ c = tmp
798
+ c = np.moveaxis(c, 0, iaxis)
799
+ return c
800
+
801
+
802
+ def hermval(x, c, tensor=True):
803
+ """
804
+ Evaluate an Hermite series at points x.
805
+
806
+ If `c` is of length `n + 1`, this function returns the value:
807
+
808
+ .. math:: p(x) = c_0 * H_0(x) + c_1 * H_1(x) + ... + c_n * H_n(x)
809
+
810
+ The parameter `x` is converted to an array only if it is a tuple or a
811
+ list, otherwise it is treated as a scalar. In either case, either `x`
812
+ or its elements must support multiplication and addition both with
813
+ themselves and with the elements of `c`.
814
+
815
+ If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
816
+ `c` is multidimensional, then the shape of the result depends on the
817
+ value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
818
+ x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
819
+ scalars have shape (,).
820
+
821
+ Trailing zeros in the coefficients will be used in the evaluation, so
822
+ they should be avoided if efficiency is a concern.
823
+
824
+ Parameters
825
+ ----------
826
+ x : array_like, compatible object
827
+ If `x` is a list or tuple, it is converted to an ndarray, otherwise
828
+ it is left unchanged and treated as a scalar. In either case, `x`
829
+ or its elements must support addition and multiplication with
830
+ themselves and with the elements of `c`.
831
+ c : array_like
832
+ Array of coefficients ordered so that the coefficients for terms of
833
+ degree n are contained in c[n]. If `c` is multidimensional the
834
+ remaining indices enumerate multiple polynomials. In the two
835
+ dimensional case the coefficients may be thought of as stored in
836
+ the columns of `c`.
837
+ tensor : boolean, optional
838
+ If True, the shape of the coefficient array is extended with ones
839
+ on the right, one for each dimension of `x`. Scalars have dimension 0
840
+ for this action. The result is that every column of coefficients in
841
+ `c` is evaluated for every element of `x`. If False, `x` is broadcast
842
+ over the columns of `c` for the evaluation. This keyword is useful
843
+ when `c` is multidimensional. The default value is True.
844
+
845
+ .. versionadded:: 1.7.0
846
+
847
+ Returns
848
+ -------
849
+ values : ndarray, algebra_like
850
+ The shape of the return value is described above.
851
+
852
+ See Also
853
+ --------
854
+ hermval2d, hermgrid2d, hermval3d, hermgrid3d
855
+
856
+ Notes
857
+ -----
858
+ The evaluation uses Clenshaw recursion, aka synthetic division.
859
+
860
+ Examples
861
+ --------
862
+ >>> from numpy.polynomial.hermite import hermval
863
+ >>> coef = [1,2,3]
864
+ >>> hermval(1, coef)
865
+ 11.0
866
+ >>> hermval([[1,2],[3,4]], coef)
867
+ array([[ 11., 51.],
868
+ [115., 203.]])
869
+
870
+ """
871
+ c = np.array(c, ndmin=1, copy=False)
872
+ if c.dtype.char in '?bBhHiIlLqQpP':
873
+ c = c.astype(np.double)
874
+ if isinstance(x, (tuple, list)):
875
+ x = np.asarray(x)
876
+ if isinstance(x, np.ndarray) and tensor:
877
+ c = c.reshape(c.shape + (1,)*x.ndim)
878
+
879
+ x2 = x*2
880
+ if len(c) == 1:
881
+ c0 = c[0]
882
+ c1 = 0
883
+ elif len(c) == 2:
884
+ c0 = c[0]
885
+ c1 = c[1]
886
+ else:
887
+ nd = len(c)
888
+ c0 = c[-2]
889
+ c1 = c[-1]
890
+ for i in range(3, len(c) + 1):
891
+ tmp = c0
892
+ nd = nd - 1
893
+ c0 = c[-i] - c1*(2*(nd - 1))
894
+ c1 = tmp + c1*x2
895
+ return c0 + c1*x2
896
+
897
+
898
+ def hermval2d(x, y, c):
899
+ """
900
+ Evaluate a 2-D Hermite series at points (x, y).
901
+
902
+ This function returns the values:
903
+
904
+ .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * H_i(x) * H_j(y)
905
+
906
+ The parameters `x` and `y` are converted to arrays only if they are
907
+ tuples or a lists, otherwise they are treated as a scalars and they
908
+ must have the same shape after conversion. In either case, either `x`
909
+ and `y` or their elements must support multiplication and addition both
910
+ with themselves and with the elements of `c`.
911
+
912
+ If `c` is a 1-D array a one is implicitly appended to its shape to make
913
+ it 2-D. The shape of the result will be c.shape[2:] + x.shape.
914
+
915
+ Parameters
916
+ ----------
917
+ x, y : array_like, compatible objects
918
+ The two dimensional series is evaluated at the points `(x, y)`,
919
+ where `x` and `y` must have the same shape. If `x` or `y` is a list
920
+ or tuple, it is first converted to an ndarray, otherwise it is left
921
+ unchanged and if it isn't an ndarray it is treated as a scalar.
922
+ c : array_like
923
+ Array of coefficients ordered so that the coefficient of the term
924
+ of multi-degree i,j is contained in ``c[i,j]``. If `c` has
925
+ dimension greater than two the remaining indices enumerate multiple
926
+ sets of coefficients.
927
+
928
+ Returns
929
+ -------
930
+ values : ndarray, compatible object
931
+ The values of the two dimensional polynomial at points formed with
932
+ pairs of corresponding values from `x` and `y`.
933
+
934
+ See Also
935
+ --------
936
+ hermval, hermgrid2d, hermval3d, hermgrid3d
937
+
938
+ Notes
939
+ -----
940
+
941
+ .. versionadded:: 1.7.0
942
+
943
+ """
944
+ return pu._valnd(hermval, c, x, y)
945
+
946
+
947
+ def hermgrid2d(x, y, c):
948
+ """
949
+ Evaluate a 2-D Hermite series on the Cartesian product of x and y.
950
+
951
+ This function returns the values:
952
+
953
+ .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * H_i(a) * H_j(b)
954
+
955
+ where the points `(a, b)` consist of all pairs formed by taking
956
+ `a` from `x` and `b` from `y`. The resulting points form a grid with
957
+ `x` in the first dimension and `y` in the second.
958
+
959
+ The parameters `x` and `y` are converted to arrays only if they are
960
+ tuples or a lists, otherwise they are treated as a scalars. In either
961
+ case, either `x` and `y` or their elements must support multiplication
962
+ and addition both with themselves and with the elements of `c`.
963
+
964
+ If `c` has fewer than two dimensions, ones are implicitly appended to
965
+ its shape to make it 2-D. The shape of the result will be c.shape[2:] +
966
+ x.shape.
967
+
968
+ Parameters
969
+ ----------
970
+ x, y : array_like, compatible objects
971
+ The two dimensional series is evaluated at the points in the
972
+ Cartesian product of `x` and `y`. If `x` or `y` is a list or
973
+ tuple, it is first converted to an ndarray, otherwise it is left
974
+ unchanged and, if it isn't an ndarray, it is treated as a scalar.
975
+ c : array_like
976
+ Array of coefficients ordered so that the coefficients for terms of
977
+ degree i,j are contained in ``c[i,j]``. If `c` has dimension
978
+ greater than two the remaining indices enumerate multiple sets of
979
+ coefficients.
980
+
981
+ Returns
982
+ -------
983
+ values : ndarray, compatible object
984
+ The values of the two dimensional polynomial at points in the Cartesian
985
+ product of `x` and `y`.
986
+
987
+ See Also
988
+ --------
989
+ hermval, hermval2d, hermval3d, hermgrid3d
990
+
991
+ Notes
992
+ -----
993
+
994
+ .. versionadded:: 1.7.0
995
+
996
+ """
997
+ return pu._gridnd(hermval, c, x, y)
998
+
999
+
1000
+ def hermval3d(x, y, z, c):
1001
+ """
1002
+ Evaluate a 3-D Hermite series at points (x, y, z).
1003
+
1004
+ This function returns the values:
1005
+
1006
+ .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * H_i(x) * H_j(y) * H_k(z)
1007
+
1008
+ The parameters `x`, `y`, and `z` are converted to arrays only if
1009
+ they are tuples or a lists, otherwise they are treated as a scalars and
1010
+ they must have the same shape after conversion. In either case, either
1011
+ `x`, `y`, and `z` or their elements must support multiplication and
1012
+ addition both with themselves and with the elements of `c`.
1013
+
1014
+ If `c` has fewer than 3 dimensions, ones are implicitly appended to its
1015
+ shape to make it 3-D. The shape of the result will be c.shape[3:] +
1016
+ x.shape.
1017
+
1018
+ Parameters
1019
+ ----------
1020
+ x, y, z : array_like, compatible object
1021
+ The three dimensional series is evaluated at the points
1022
+ `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
1023
+ any of `x`, `y`, or `z` is a list or tuple, it is first converted
1024
+ to an ndarray, otherwise it is left unchanged and if it isn't an
1025
+ ndarray it is treated as a scalar.
1026
+ c : array_like
1027
+ Array of coefficients ordered so that the coefficient of the term of
1028
+ multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
1029
+ greater than 3 the remaining indices enumerate multiple sets of
1030
+ coefficients.
1031
+
1032
+ Returns
1033
+ -------
1034
+ values : ndarray, compatible object
1035
+ The values of the multidimensional polynomial on points formed with
1036
+ triples of corresponding values from `x`, `y`, and `z`.
1037
+
1038
+ See Also
1039
+ --------
1040
+ hermval, hermval2d, hermgrid2d, hermgrid3d
1041
+
1042
+ Notes
1043
+ -----
1044
+
1045
+ .. versionadded:: 1.7.0
1046
+
1047
+ """
1048
+ return pu._valnd(hermval, c, x, y, z)
1049
+
1050
+
1051
+ def hermgrid3d(x, y, z, c):
1052
+ """
1053
+ Evaluate a 3-D Hermite series on the Cartesian product of x, y, and z.
1054
+
1055
+ This function returns the values:
1056
+
1057
+ .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * H_i(a) * H_j(b) * H_k(c)
1058
+
1059
+ where the points `(a, b, c)` consist of all triples formed by taking
1060
+ `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
1061
+ a grid with `x` in the first dimension, `y` in the second, and `z` in
1062
+ the third.
1063
+
1064
+ The parameters `x`, `y`, and `z` are converted to arrays only if they
1065
+ are tuples or a lists, otherwise they are treated as a scalars. In
1066
+ either case, either `x`, `y`, and `z` or their elements must support
1067
+ multiplication and addition both with themselves and with the elements
1068
+ of `c`.
1069
+
1070
+ If `c` has fewer than three dimensions, ones are implicitly appended to
1071
+ its shape to make it 3-D. The shape of the result will be c.shape[3:] +
1072
+ x.shape + y.shape + z.shape.
1073
+
1074
+ Parameters
1075
+ ----------
1076
+ x, y, z : array_like, compatible objects
1077
+ The three dimensional series is evaluated at the points in the
1078
+ Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
1079
+ list or tuple, it is first converted to an ndarray, otherwise it is
1080
+ left unchanged and, if it isn't an ndarray, it is treated as a
1081
+ scalar.
1082
+ c : array_like
1083
+ Array of coefficients ordered so that the coefficients for terms of
1084
+ degree i,j are contained in ``c[i,j]``. If `c` has dimension
1085
+ greater than two the remaining indices enumerate multiple sets of
1086
+ coefficients.
1087
+
1088
+ Returns
1089
+ -------
1090
+ values : ndarray, compatible object
1091
+ The values of the two dimensional polynomial at points in the Cartesian
1092
+ product of `x` and `y`.
1093
+
1094
+ See Also
1095
+ --------
1096
+ hermval, hermval2d, hermgrid2d, hermval3d
1097
+
1098
+ Notes
1099
+ -----
1100
+
1101
+ .. versionadded:: 1.7.0
1102
+
1103
+ """
1104
+ return pu._gridnd(hermval, c, x, y, z)
1105
+
1106
+
1107
+ def hermvander(x, deg):
1108
+ """Pseudo-Vandermonde matrix of given degree.
1109
+
1110
+ Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
1111
+ `x`. The pseudo-Vandermonde matrix is defined by
1112
+
1113
+ .. math:: V[..., i] = H_i(x),
1114
+
1115
+ where `0 <= i <= deg`. The leading indices of `V` index the elements of
1116
+ `x` and the last index is the degree of the Hermite polynomial.
1117
+
1118
+ If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
1119
+ array ``V = hermvander(x, n)``, then ``np.dot(V, c)`` and
1120
+ ``hermval(x, c)`` are the same up to roundoff. This equivalence is
1121
+ useful both for least squares fitting and for the evaluation of a large
1122
+ number of Hermite series of the same degree and sample points.
1123
+
1124
+ Parameters
1125
+ ----------
1126
+ x : array_like
1127
+ Array of points. The dtype is converted to float64 or complex128
1128
+ depending on whether any of the elements are complex. If `x` is
1129
+ scalar it is converted to a 1-D array.
1130
+ deg : int
1131
+ Degree of the resulting matrix.
1132
+
1133
+ Returns
1134
+ -------
1135
+ vander : ndarray
1136
+ The pseudo-Vandermonde matrix. The shape of the returned matrix is
1137
+ ``x.shape + (deg + 1,)``, where The last index is the degree of the
1138
+ corresponding Hermite polynomial. The dtype will be the same as
1139
+ the converted `x`.
1140
+
1141
+ Examples
1142
+ --------
1143
+ >>> from numpy.polynomial.hermite import hermvander
1144
+ >>> x = np.array([-1, 0, 1])
1145
+ >>> hermvander(x, 3)
1146
+ array([[ 1., -2., 2., 4.],
1147
+ [ 1., 0., -2., -0.],
1148
+ [ 1., 2., 2., -4.]])
1149
+
1150
+ """
1151
+ ideg = pu._deprecate_as_int(deg, "deg")
1152
+ if ideg < 0:
1153
+ raise ValueError("deg must be non-negative")
1154
+
1155
+ x = np.array(x, copy=False, ndmin=1) + 0.0
1156
+ dims = (ideg + 1,) + x.shape
1157
+ dtyp = x.dtype
1158
+ v = np.empty(dims, dtype=dtyp)
1159
+ v[0] = x*0 + 1
1160
+ if ideg > 0:
1161
+ x2 = x*2
1162
+ v[1] = x2
1163
+ for i in range(2, ideg + 1):
1164
+ v[i] = (v[i-1]*x2 - v[i-2]*(2*(i - 1)))
1165
+ return np.moveaxis(v, 0, -1)
1166
+
1167
+
1168
+ def hermvander2d(x, y, deg):
1169
+ """Pseudo-Vandermonde matrix of given degrees.
1170
+
1171
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1172
+ points `(x, y)`. The pseudo-Vandermonde matrix is defined by
1173
+
1174
+ .. math:: V[..., (deg[1] + 1)*i + j] = H_i(x) * H_j(y),
1175
+
1176
+ where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
1177
+ `V` index the points `(x, y)` and the last index encodes the degrees of
1178
+ the Hermite polynomials.
1179
+
1180
+ If ``V = hermvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
1181
+ correspond to the elements of a 2-D coefficient array `c` of shape
1182
+ (xdeg + 1, ydeg + 1) in the order
1183
+
1184
+ .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
1185
+
1186
+ and ``np.dot(V, c.flat)`` and ``hermval2d(x, y, c)`` will be the same
1187
+ up to roundoff. This equivalence is useful both for least squares
1188
+ fitting and for the evaluation of a large number of 2-D Hermite
1189
+ series of the same degrees and sample points.
1190
+
1191
+ Parameters
1192
+ ----------
1193
+ x, y : array_like
1194
+ Arrays of point coordinates, all of the same shape. The dtypes
1195
+ will be converted to either float64 or complex128 depending on
1196
+ whether any of the elements are complex. Scalars are converted to 1-D
1197
+ arrays.
1198
+ deg : list of ints
1199
+ List of maximum degrees of the form [x_deg, y_deg].
1200
+
1201
+ Returns
1202
+ -------
1203
+ vander2d : ndarray
1204
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1205
+ :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same
1206
+ as the converted `x` and `y`.
1207
+
1208
+ See Also
1209
+ --------
1210
+ hermvander, hermvander3d, hermval2d, hermval3d
1211
+
1212
+ Notes
1213
+ -----
1214
+
1215
+ .. versionadded:: 1.7.0
1216
+
1217
+ """
1218
+ return pu._vander_nd_flat((hermvander, hermvander), (x, y), deg)
1219
+
1220
+
1221
+ def hermvander3d(x, y, z, deg):
1222
+ """Pseudo-Vandermonde matrix of given degrees.
1223
+
1224
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1225
+ points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
1226
+ then The pseudo-Vandermonde matrix is defined by
1227
+
1228
+ .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = H_i(x)*H_j(y)*H_k(z),
1229
+
1230
+ where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
1231
+ indices of `V` index the points `(x, y, z)` and the last index encodes
1232
+ the degrees of the Hermite polynomials.
1233
+
1234
+ If ``V = hermvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
1235
+ of `V` correspond to the elements of a 3-D coefficient array `c` of
1236
+ shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
1237
+
1238
+ .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
1239
+
1240
+ and ``np.dot(V, c.flat)`` and ``hermval3d(x, y, z, c)`` will be the
1241
+ same up to roundoff. This equivalence is useful both for least squares
1242
+ fitting and for the evaluation of a large number of 3-D Hermite
1243
+ series of the same degrees and sample points.
1244
+
1245
+ Parameters
1246
+ ----------
1247
+ x, y, z : array_like
1248
+ Arrays of point coordinates, all of the same shape. The dtypes will
1249
+ be converted to either float64 or complex128 depending on whether
1250
+ any of the elements are complex. Scalars are converted to 1-D
1251
+ arrays.
1252
+ deg : list of ints
1253
+ List of maximum degrees of the form [x_deg, y_deg, z_deg].
1254
+
1255
+ Returns
1256
+ -------
1257
+ vander3d : ndarray
1258
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1259
+ :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will
1260
+ be the same as the converted `x`, `y`, and `z`.
1261
+
1262
+ See Also
1263
+ --------
1264
+ hermvander, hermvander3d, hermval2d, hermval3d
1265
+
1266
+ Notes
1267
+ -----
1268
+
1269
+ .. versionadded:: 1.7.0
1270
+
1271
+ """
1272
+ return pu._vander_nd_flat((hermvander, hermvander, hermvander), (x, y, z), deg)
1273
+
1274
+
1275
+ def hermfit(x, y, deg, rcond=None, full=False, w=None):
1276
+ """
1277
+ Least squares fit of Hermite series to data.
1278
+
1279
+ Return the coefficients of a Hermite series of degree `deg` that is the
1280
+ least squares fit to the data values `y` given at points `x`. If `y` is
1281
+ 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
1282
+ fits are done, one for each column of `y`, and the resulting
1283
+ coefficients are stored in the corresponding columns of a 2-D return.
1284
+ The fitted polynomial(s) are in the form
1285
+
1286
+ .. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x),
1287
+
1288
+ where `n` is `deg`.
1289
+
1290
+ Parameters
1291
+ ----------
1292
+ x : array_like, shape (M,)
1293
+ x-coordinates of the M sample points ``(x[i], y[i])``.
1294
+ y : array_like, shape (M,) or (M, K)
1295
+ y-coordinates of the sample points. Several data sets of sample
1296
+ points sharing the same x-coordinates can be fitted at once by
1297
+ passing in a 2D-array that contains one dataset per column.
1298
+ deg : int or 1-D array_like
1299
+ Degree(s) of the fitting polynomials. If `deg` is a single integer
1300
+ all terms up to and including the `deg`'th term are included in the
1301
+ fit. For NumPy versions >= 1.11.0 a list of integers specifying the
1302
+ degrees of the terms to include may be used instead.
1303
+ rcond : float, optional
1304
+ Relative condition number of the fit. Singular values smaller than
1305
+ this relative to the largest singular value will be ignored. The
1306
+ default value is len(x)*eps, where eps is the relative precision of
1307
+ the float type, about 2e-16 in most cases.
1308
+ full : bool, optional
1309
+ Switch determining nature of return value. When it is False (the
1310
+ default) just the coefficients are returned, when True diagnostic
1311
+ information from the singular value decomposition is also returned.
1312
+ w : array_like, shape (`M`,), optional
1313
+ Weights. If not None, the weight ``w[i]`` applies to the unsquared
1314
+ residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
1315
+ chosen so that the errors of the products ``w[i]*y[i]`` all have the
1316
+ same variance. When using inverse-variance weighting, use
1317
+ ``w[i] = 1/sigma(y[i])``. The default value is None.
1318
+
1319
+ Returns
1320
+ -------
1321
+ coef : ndarray, shape (M,) or (M, K)
1322
+ Hermite coefficients ordered from low to high. If `y` was 2-D,
1323
+ the coefficients for the data in column k of `y` are in column
1324
+ `k`.
1325
+
1326
+ [residuals, rank, singular_values, rcond] : list
1327
+ These values are only returned if ``full == True``
1328
+
1329
+ - residuals -- sum of squared residuals of the least squares fit
1330
+ - rank -- the numerical rank of the scaled Vandermonde matrix
1331
+ - singular_values -- singular values of the scaled Vandermonde matrix
1332
+ - rcond -- value of `rcond`.
1333
+
1334
+ For more details, see `numpy.linalg.lstsq`.
1335
+
1336
+ Warns
1337
+ -----
1338
+ RankWarning
1339
+ The rank of the coefficient matrix in the least-squares fit is
1340
+ deficient. The warning is only raised if ``full == False``. The
1341
+ warnings can be turned off by
1342
+
1343
+ >>> import warnings
1344
+ >>> warnings.simplefilter('ignore', np.RankWarning)
1345
+
1346
+ See Also
1347
+ --------
1348
+ numpy.polynomial.chebyshev.chebfit
1349
+ numpy.polynomial.legendre.legfit
1350
+ numpy.polynomial.laguerre.lagfit
1351
+ numpy.polynomial.polynomial.polyfit
1352
+ numpy.polynomial.hermite_e.hermefit
1353
+ hermval : Evaluates a Hermite series.
1354
+ hermvander : Vandermonde matrix of Hermite series.
1355
+ hermweight : Hermite weight function
1356
+ numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
1357
+ scipy.interpolate.UnivariateSpline : Computes spline fits.
1358
+
1359
+ Notes
1360
+ -----
1361
+ The solution is the coefficients of the Hermite series `p` that
1362
+ minimizes the sum of the weighted squared errors
1363
+
1364
+ .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
1365
+
1366
+ where the :math:`w_j` are the weights. This problem is solved by
1367
+ setting up the (typically) overdetermined matrix equation
1368
+
1369
+ .. math:: V(x) * c = w * y,
1370
+
1371
+ where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
1372
+ coefficients to be solved for, `w` are the weights, `y` are the
1373
+ observed values. This equation is then solved using the singular value
1374
+ decomposition of `V`.
1375
+
1376
+ If some of the singular values of `V` are so small that they are
1377
+ neglected, then a `RankWarning` will be issued. This means that the
1378
+ coefficient values may be poorly determined. Using a lower order fit
1379
+ will usually get rid of the warning. The `rcond` parameter can also be
1380
+ set to a value smaller than its default, but the resulting fit may be
1381
+ spurious and have large contributions from roundoff error.
1382
+
1383
+ Fits using Hermite series are probably most useful when the data can be
1384
+ approximated by ``sqrt(w(x)) * p(x)``, where `w(x)` is the Hermite
1385
+ weight. In that case the weight ``sqrt(w(x[i]))`` should be used
1386
+ together with data values ``y[i]/sqrt(w(x[i]))``. The weight function is
1387
+ available as `hermweight`.
1388
+
1389
+ References
1390
+ ----------
1391
+ .. [1] Wikipedia, "Curve fitting",
1392
+ https://en.wikipedia.org/wiki/Curve_fitting
1393
+
1394
+ Examples
1395
+ --------
1396
+ >>> from numpy.polynomial.hermite import hermfit, hermval
1397
+ >>> x = np.linspace(-10, 10)
1398
+ >>> err = np.random.randn(len(x))/10
1399
+ >>> y = hermval(x, [1, 2, 3]) + err
1400
+ >>> hermfit(x, y, 2)
1401
+ array([1.0218, 1.9986, 2.9999]) # may vary
1402
+
1403
+ """
1404
+ return pu._fit(hermvander, x, y, deg, rcond, full, w)
1405
+
1406
+
1407
+ def hermcompanion(c):
1408
+ """Return the scaled companion matrix of c.
1409
+
1410
+ The basis polynomials are scaled so that the companion matrix is
1411
+ symmetric when `c` is an Hermite basis polynomial. This provides
1412
+ better eigenvalue estimates than the unscaled case and for basis
1413
+ polynomials the eigenvalues are guaranteed to be real if
1414
+ `numpy.linalg.eigvalsh` is used to obtain them.
1415
+
1416
+ Parameters
1417
+ ----------
1418
+ c : array_like
1419
+ 1-D array of Hermite series coefficients ordered from low to high
1420
+ degree.
1421
+
1422
+ Returns
1423
+ -------
1424
+ mat : ndarray
1425
+ Scaled companion matrix of dimensions (deg, deg).
1426
+
1427
+ Notes
1428
+ -----
1429
+
1430
+ .. versionadded:: 1.7.0
1431
+
1432
+ """
1433
+ # c is a trimmed copy
1434
+ [c] = pu.as_series([c])
1435
+ if len(c) < 2:
1436
+ raise ValueError('Series must have maximum degree of at least 1.')
1437
+ if len(c) == 2:
1438
+ return np.array([[-.5*c[0]/c[1]]])
1439
+
1440
+ n = len(c) - 1
1441
+ mat = np.zeros((n, n), dtype=c.dtype)
1442
+ scl = np.hstack((1., 1./np.sqrt(2.*np.arange(n - 1, 0, -1))))
1443
+ scl = np.multiply.accumulate(scl)[::-1]
1444
+ top = mat.reshape(-1)[1::n+1]
1445
+ bot = mat.reshape(-1)[n::n+1]
1446
+ top[...] = np.sqrt(.5*np.arange(1, n))
1447
+ bot[...] = top
1448
+ mat[:, -1] -= scl*c[:-1]/(2.0*c[-1])
1449
+ return mat
1450
+
1451
+
1452
+ def hermroots(c):
1453
+ """
1454
+ Compute the roots of a Hermite series.
1455
+
1456
+ Return the roots (a.k.a. "zeros") of the polynomial
1457
+
1458
+ .. math:: p(x) = \\sum_i c[i] * H_i(x).
1459
+
1460
+ Parameters
1461
+ ----------
1462
+ c : 1-D array_like
1463
+ 1-D array of coefficients.
1464
+
1465
+ Returns
1466
+ -------
1467
+ out : ndarray
1468
+ Array of the roots of the series. If all the roots are real,
1469
+ then `out` is also real, otherwise it is complex.
1470
+
1471
+ See Also
1472
+ --------
1473
+ numpy.polynomial.polynomial.polyroots
1474
+ numpy.polynomial.legendre.legroots
1475
+ numpy.polynomial.laguerre.lagroots
1476
+ numpy.polynomial.chebyshev.chebroots
1477
+ numpy.polynomial.hermite_e.hermeroots
1478
+
1479
+ Notes
1480
+ -----
1481
+ The root estimates are obtained as the eigenvalues of the companion
1482
+ matrix, Roots far from the origin of the complex plane may have large
1483
+ errors due to the numerical instability of the series for such
1484
+ values. Roots with multiplicity greater than 1 will also show larger
1485
+ errors as the value of the series near such points is relatively
1486
+ insensitive to errors in the roots. Isolated roots near the origin can
1487
+ be improved by a few iterations of Newton's method.
1488
+
1489
+ The Hermite series basis polynomials aren't powers of `x` so the
1490
+ results of this function may seem unintuitive.
1491
+
1492
+ Examples
1493
+ --------
1494
+ >>> from numpy.polynomial.hermite import hermroots, hermfromroots
1495
+ >>> coef = hermfromroots([-1, 0, 1])
1496
+ >>> coef
1497
+ array([0. , 0.25 , 0. , 0.125])
1498
+ >>> hermroots(coef)
1499
+ array([-1.00000000e+00, -1.38777878e-17, 1.00000000e+00])
1500
+
1501
+ """
1502
+ # c is a trimmed copy
1503
+ [c] = pu.as_series([c])
1504
+ if len(c) <= 1:
1505
+ return np.array([], dtype=c.dtype)
1506
+ if len(c) == 2:
1507
+ return np.array([-.5*c[0]/c[1]])
1508
+
1509
+ # rotated companion matrix reduces error
1510
+ m = hermcompanion(c)[::-1,::-1]
1511
+ r = la.eigvals(m)
1512
+ r.sort()
1513
+ return r
1514
+
1515
+
1516
+ def _normed_hermite_n(x, n):
1517
+ """
1518
+ Evaluate a normalized Hermite polynomial.
1519
+
1520
+ Compute the value of the normalized Hermite polynomial of degree ``n``
1521
+ at the points ``x``.
1522
+
1523
+
1524
+ Parameters
1525
+ ----------
1526
+ x : ndarray of double.
1527
+ Points at which to evaluate the function
1528
+ n : int
1529
+ Degree of the normalized Hermite function to be evaluated.
1530
+
1531
+ Returns
1532
+ -------
1533
+ values : ndarray
1534
+ The shape of the return value is described above.
1535
+
1536
+ Notes
1537
+ -----
1538
+ .. versionadded:: 1.10.0
1539
+
1540
+ This function is needed for finding the Gauss points and integration
1541
+ weights for high degrees. The values of the standard Hermite functions
1542
+ overflow when n >= 207.
1543
+
1544
+ """
1545
+ if n == 0:
1546
+ return np.full(x.shape, 1/np.sqrt(np.sqrt(np.pi)))
1547
+
1548
+ c0 = 0.
1549
+ c1 = 1./np.sqrt(np.sqrt(np.pi))
1550
+ nd = float(n)
1551
+ for i in range(n - 1):
1552
+ tmp = c0
1553
+ c0 = -c1*np.sqrt((nd - 1.)/nd)
1554
+ c1 = tmp + c1*x*np.sqrt(2./nd)
1555
+ nd = nd - 1.0
1556
+ return c0 + c1*x*np.sqrt(2)
1557
+
1558
+
1559
+ def hermgauss(deg):
1560
+ """
1561
+ Gauss-Hermite quadrature.
1562
+
1563
+ Computes the sample points and weights for Gauss-Hermite quadrature.
1564
+ These sample points and weights will correctly integrate polynomials of
1565
+ degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`
1566
+ with the weight function :math:`f(x) = \\exp(-x^2)`.
1567
+
1568
+ Parameters
1569
+ ----------
1570
+ deg : int
1571
+ Number of sample points and weights. It must be >= 1.
1572
+
1573
+ Returns
1574
+ -------
1575
+ x : ndarray
1576
+ 1-D ndarray containing the sample points.
1577
+ y : ndarray
1578
+ 1-D ndarray containing the weights.
1579
+
1580
+ Notes
1581
+ -----
1582
+
1583
+ .. versionadded:: 1.7.0
1584
+
1585
+ The results have only been tested up to degree 100, higher degrees may
1586
+ be problematic. The weights are determined by using the fact that
1587
+
1588
+ .. math:: w_k = c / (H'_n(x_k) * H_{n-1}(x_k))
1589
+
1590
+ where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
1591
+ is the k'th root of :math:`H_n`, and then scaling the results to get
1592
+ the right value when integrating 1.
1593
+
1594
+ """
1595
+ ideg = pu._deprecate_as_int(deg, "deg")
1596
+ if ideg <= 0:
1597
+ raise ValueError("deg must be a positive integer")
1598
+
1599
+ # first approximation of roots. We use the fact that the companion
1600
+ # matrix is symmetric in this case in order to obtain better zeros.
1601
+ c = np.array([0]*deg + [1], dtype=np.float64)
1602
+ m = hermcompanion(c)
1603
+ x = la.eigvalsh(m)
1604
+
1605
+ # improve roots by one application of Newton
1606
+ dy = _normed_hermite_n(x, ideg)
1607
+ df = _normed_hermite_n(x, ideg - 1) * np.sqrt(2*ideg)
1608
+ x -= dy/df
1609
+
1610
+ # compute the weights. We scale the factor to avoid possible numerical
1611
+ # overflow.
1612
+ fm = _normed_hermite_n(x, ideg - 1)
1613
+ fm /= np.abs(fm).max()
1614
+ w = 1/(fm * fm)
1615
+
1616
+ # for Hermite we can also symmetrize
1617
+ w = (w + w[::-1])/2
1618
+ x = (x - x[::-1])/2
1619
+
1620
+ # scale w to get the right value
1621
+ w *= np.sqrt(np.pi) / w.sum()
1622
+
1623
+ return x, w
1624
+
1625
+
1626
+ def hermweight(x):
1627
+ """
1628
+ Weight function of the Hermite polynomials.
1629
+
1630
+ The weight function is :math:`\\exp(-x^2)` and the interval of
1631
+ integration is :math:`[-\\inf, \\inf]`. the Hermite polynomials are
1632
+ orthogonal, but not normalized, with respect to this weight function.
1633
+
1634
+ Parameters
1635
+ ----------
1636
+ x : array_like
1637
+ Values at which the weight function will be computed.
1638
+
1639
+ Returns
1640
+ -------
1641
+ w : ndarray
1642
+ The weight function at `x`.
1643
+
1644
+ Notes
1645
+ -----
1646
+
1647
+ .. versionadded:: 1.7.0
1648
+
1649
+ """
1650
+ w = np.exp(-x**2)
1651
+ return w
1652
+
1653
+
1654
+ #
1655
+ # Hermite series class
1656
+ #
1657
+
1658
+ class Hermite(ABCPolyBase):
1659
+ """An Hermite series class.
1660
+
1661
+ The Hermite class provides the standard Python numerical methods
1662
+ '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
1663
+ attributes and methods listed in the `ABCPolyBase` documentation.
1664
+
1665
+ Parameters
1666
+ ----------
1667
+ coef : array_like
1668
+ Hermite coefficients in order of increasing degree, i.e,
1669
+ ``(1, 2, 3)`` gives ``1*H_0(x) + 2*H_1(X) + 3*H_2(x)``.
1670
+ domain : (2,) array_like, optional
1671
+ Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
1672
+ to the interval ``[window[0], window[1]]`` by shifting and scaling.
1673
+ The default value is [-1, 1].
1674
+ window : (2,) array_like, optional
1675
+ Window, see `domain` for its use. The default value is [-1, 1].
1676
+
1677
+ .. versionadded:: 1.6.0
1678
+ symbol : str, optional
1679
+ Symbol used to represent the independent variable in string
1680
+ representations of the polynomial expression, e.g. for printing.
1681
+ The symbol must be a valid Python identifier. Default value is 'x'.
1682
+
1683
+ .. versionadded:: 1.24
1684
+
1685
+ """
1686
+ # Virtual Functions
1687
+ _add = staticmethod(hermadd)
1688
+ _sub = staticmethod(hermsub)
1689
+ _mul = staticmethod(hermmul)
1690
+ _div = staticmethod(hermdiv)
1691
+ _pow = staticmethod(hermpow)
1692
+ _val = staticmethod(hermval)
1693
+ _int = staticmethod(hermint)
1694
+ _der = staticmethod(hermder)
1695
+ _fit = staticmethod(hermfit)
1696
+ _line = staticmethod(hermline)
1697
+ _roots = staticmethod(hermroots)
1698
+ _fromroots = staticmethod(hermfromroots)
1699
+
1700
+ # Virtual properties
1701
+ domain = np.array(hermdomain)
1702
+ window = np.array(hermdomain)
1703
+ basis_name = 'H'
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/hermite.pyi ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from numpy import ndarray, dtype, int_, float_
4
+ from numpy.polynomial._polybase import ABCPolyBase
5
+ from numpy.polynomial.polyutils import trimcoef
6
+
7
+ __all__: list[str]
8
+
9
+ hermtrim = trimcoef
10
+
11
+ def poly2herm(pol): ...
12
+ def herm2poly(c): ...
13
+
14
+ hermdomain: ndarray[Any, dtype[int_]]
15
+ hermzero: ndarray[Any, dtype[int_]]
16
+ hermone: ndarray[Any, dtype[int_]]
17
+ hermx: ndarray[Any, dtype[float_]]
18
+
19
+ def hermline(off, scl): ...
20
+ def hermfromroots(roots): ...
21
+ def hermadd(c1, c2): ...
22
+ def hermsub(c1, c2): ...
23
+ def hermmulx(c): ...
24
+ def hermmul(c1, c2): ...
25
+ def hermdiv(c1, c2): ...
26
+ def hermpow(c, pow, maxpower=...): ...
27
+ def hermder(c, m=..., scl=..., axis=...): ...
28
+ def hermint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...
29
+ def hermval(x, c, tensor=...): ...
30
+ def hermval2d(x, y, c): ...
31
+ def hermgrid2d(x, y, c): ...
32
+ def hermval3d(x, y, z, c): ...
33
+ def hermgrid3d(x, y, z, c): ...
34
+ def hermvander(x, deg): ...
35
+ def hermvander2d(x, y, deg): ...
36
+ def hermvander3d(x, y, z, deg): ...
37
+ def hermfit(x, y, deg, rcond=..., full=..., w=...): ...
38
+ def hermcompanion(c): ...
39
+ def hermroots(c): ...
40
+ def hermgauss(deg): ...
41
+ def hermweight(x): ...
42
+
43
+ class Hermite(ABCPolyBase):
44
+ domain: Any
45
+ window: Any
46
+ basis_name: Any
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/hermite_e.py ADDED
@@ -0,0 +1,1695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ===================================================================
3
+ HermiteE Series, "Probabilists" (:mod:`numpy.polynomial.hermite_e`)
4
+ ===================================================================
5
+
6
+ This module provides a number of objects (mostly functions) useful for
7
+ dealing with Hermite_e series, including a `HermiteE` class that
8
+ encapsulates the usual arithmetic operations. (General information
9
+ on how this module represents and works with such polynomials is in the
10
+ docstring for its "parent" sub-package, `numpy.polynomial`).
11
+
12
+ Classes
13
+ -------
14
+ .. autosummary::
15
+ :toctree: generated/
16
+
17
+ HermiteE
18
+
19
+ Constants
20
+ ---------
21
+ .. autosummary::
22
+ :toctree: generated/
23
+
24
+ hermedomain
25
+ hermezero
26
+ hermeone
27
+ hermex
28
+
29
+ Arithmetic
30
+ ----------
31
+ .. autosummary::
32
+ :toctree: generated/
33
+
34
+ hermeadd
35
+ hermesub
36
+ hermemulx
37
+ hermemul
38
+ hermediv
39
+ hermepow
40
+ hermeval
41
+ hermeval2d
42
+ hermeval3d
43
+ hermegrid2d
44
+ hermegrid3d
45
+
46
+ Calculus
47
+ --------
48
+ .. autosummary::
49
+ :toctree: generated/
50
+
51
+ hermeder
52
+ hermeint
53
+
54
+ Misc Functions
55
+ --------------
56
+ .. autosummary::
57
+ :toctree: generated/
58
+
59
+ hermefromroots
60
+ hermeroots
61
+ hermevander
62
+ hermevander2d
63
+ hermevander3d
64
+ hermegauss
65
+ hermeweight
66
+ hermecompanion
67
+ hermefit
68
+ hermetrim
69
+ hermeline
70
+ herme2poly
71
+ poly2herme
72
+
73
+ See also
74
+ --------
75
+ `numpy.polynomial`
76
+
77
+ """
78
+ import numpy as np
79
+ import numpy.linalg as la
80
+ from numpy.core.multiarray import normalize_axis_index
81
+
82
+ from . import polyutils as pu
83
+ from ._polybase import ABCPolyBase
84
+
85
+ __all__ = [
86
+ 'hermezero', 'hermeone', 'hermex', 'hermedomain', 'hermeline',
87
+ 'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv',
88
+ 'hermepow', 'hermeval', 'hermeder', 'hermeint', 'herme2poly',
89
+ 'poly2herme', 'hermefromroots', 'hermevander', 'hermefit', 'hermetrim',
90
+ 'hermeroots', 'HermiteE', 'hermeval2d', 'hermeval3d', 'hermegrid2d',
91
+ 'hermegrid3d', 'hermevander2d', 'hermevander3d', 'hermecompanion',
92
+ 'hermegauss', 'hermeweight']
93
+
94
+ hermetrim = pu.trimcoef
95
+
96
+
97
+ def poly2herme(pol):
98
+ """
99
+ poly2herme(pol)
100
+
101
+ Convert a polynomial to a Hermite series.
102
+
103
+ Convert an array representing the coefficients of a polynomial (relative
104
+ to the "standard" basis) ordered from lowest degree to highest, to an
105
+ array of the coefficients of the equivalent Hermite series, ordered
106
+ from lowest to highest degree.
107
+
108
+ Parameters
109
+ ----------
110
+ pol : array_like
111
+ 1-D array containing the polynomial coefficients
112
+
113
+ Returns
114
+ -------
115
+ c : ndarray
116
+ 1-D array containing the coefficients of the equivalent Hermite
117
+ series.
118
+
119
+ See Also
120
+ --------
121
+ herme2poly
122
+
123
+ Notes
124
+ -----
125
+ The easy way to do conversions between polynomial basis sets
126
+ is to use the convert method of a class instance.
127
+
128
+ Examples
129
+ --------
130
+ >>> from numpy.polynomial.hermite_e import poly2herme
131
+ >>> poly2herme(np.arange(4))
132
+ array([ 2., 10., 2., 3.])
133
+
134
+ """
135
+ [pol] = pu.as_series([pol])
136
+ deg = len(pol) - 1
137
+ res = 0
138
+ for i in range(deg, -1, -1):
139
+ res = hermeadd(hermemulx(res), pol[i])
140
+ return res
141
+
142
+
143
+ def herme2poly(c):
144
+ """
145
+ Convert a Hermite series to a polynomial.
146
+
147
+ Convert an array representing the coefficients of a Hermite series,
148
+ ordered from lowest degree to highest, to an array of the coefficients
149
+ of the equivalent polynomial (relative to the "standard" basis) ordered
150
+ from lowest to highest degree.
151
+
152
+ Parameters
153
+ ----------
154
+ c : array_like
155
+ 1-D array containing the Hermite series coefficients, ordered
156
+ from lowest order term to highest.
157
+
158
+ Returns
159
+ -------
160
+ pol : ndarray
161
+ 1-D array containing the coefficients of the equivalent polynomial
162
+ (relative to the "standard" basis) ordered from lowest order term
163
+ to highest.
164
+
165
+ See Also
166
+ --------
167
+ poly2herme
168
+
169
+ Notes
170
+ -----
171
+ The easy way to do conversions between polynomial basis sets
172
+ is to use the convert method of a class instance.
173
+
174
+ Examples
175
+ --------
176
+ >>> from numpy.polynomial.hermite_e import herme2poly
177
+ >>> herme2poly([ 2., 10., 2., 3.])
178
+ array([0., 1., 2., 3.])
179
+
180
+ """
181
+ from .polynomial import polyadd, polysub, polymulx
182
+
183
+ [c] = pu.as_series([c])
184
+ n = len(c)
185
+ if n == 1:
186
+ return c
187
+ if n == 2:
188
+ return c
189
+ else:
190
+ c0 = c[-2]
191
+ c1 = c[-1]
192
+ # i is the current degree of c1
193
+ for i in range(n - 1, 1, -1):
194
+ tmp = c0
195
+ c0 = polysub(c[i - 2], c1*(i - 1))
196
+ c1 = polyadd(tmp, polymulx(c1))
197
+ return polyadd(c0, polymulx(c1))
198
+
199
+ #
200
+ # These are constant arrays are of integer type so as to be compatible
201
+ # with the widest range of other types, such as Decimal.
202
+ #
203
+
204
+ # Hermite
205
+ hermedomain = np.array([-1, 1])
206
+
207
+ # Hermite coefficients representing zero.
208
+ hermezero = np.array([0])
209
+
210
+ # Hermite coefficients representing one.
211
+ hermeone = np.array([1])
212
+
213
+ # Hermite coefficients representing the identity x.
214
+ hermex = np.array([0, 1])
215
+
216
+
217
+ def hermeline(off, scl):
218
+ """
219
+ Hermite series whose graph is a straight line.
220
+
221
+ Parameters
222
+ ----------
223
+ off, scl : scalars
224
+ The specified line is given by ``off + scl*x``.
225
+
226
+ Returns
227
+ -------
228
+ y : ndarray
229
+ This module's representation of the Hermite series for
230
+ ``off + scl*x``.
231
+
232
+ See Also
233
+ --------
234
+ numpy.polynomial.polynomial.polyline
235
+ numpy.polynomial.chebyshev.chebline
236
+ numpy.polynomial.legendre.legline
237
+ numpy.polynomial.laguerre.lagline
238
+ numpy.polynomial.hermite.hermline
239
+
240
+ Examples
241
+ --------
242
+ >>> from numpy.polynomial.hermite_e import hermeline
243
+ >>> from numpy.polynomial.hermite_e import hermeline, hermeval
244
+ >>> hermeval(0,hermeline(3, 2))
245
+ 3.0
246
+ >>> hermeval(1,hermeline(3, 2))
247
+ 5.0
248
+
249
+ """
250
+ if scl != 0:
251
+ return np.array([off, scl])
252
+ else:
253
+ return np.array([off])
254
+
255
+
256
+ def hermefromroots(roots):
257
+ """
258
+ Generate a HermiteE series with given roots.
259
+
260
+ The function returns the coefficients of the polynomial
261
+
262
+ .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
263
+
264
+ in HermiteE form, where the `r_n` are the roots specified in `roots`.
265
+ If a zero has multiplicity n, then it must appear in `roots` n times.
266
+ For instance, if 2 is a root of multiplicity three and 3 is a root of
267
+ multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
268
+ roots can appear in any order.
269
+
270
+ If the returned coefficients are `c`, then
271
+
272
+ .. math:: p(x) = c_0 + c_1 * He_1(x) + ... + c_n * He_n(x)
273
+
274
+ The coefficient of the last term is not generally 1 for monic
275
+ polynomials in HermiteE form.
276
+
277
+ Parameters
278
+ ----------
279
+ roots : array_like
280
+ Sequence containing the roots.
281
+
282
+ Returns
283
+ -------
284
+ out : ndarray
285
+ 1-D array of coefficients. If all roots are real then `out` is a
286
+ real array, if some of the roots are complex, then `out` is complex
287
+ even if all the coefficients in the result are real (see Examples
288
+ below).
289
+
290
+ See Also
291
+ --------
292
+ numpy.polynomial.polynomial.polyfromroots
293
+ numpy.polynomial.legendre.legfromroots
294
+ numpy.polynomial.laguerre.lagfromroots
295
+ numpy.polynomial.hermite.hermfromroots
296
+ numpy.polynomial.chebyshev.chebfromroots
297
+
298
+ Examples
299
+ --------
300
+ >>> from numpy.polynomial.hermite_e import hermefromroots, hermeval
301
+ >>> coef = hermefromroots((-1, 0, 1))
302
+ >>> hermeval((-1, 0, 1), coef)
303
+ array([0., 0., 0.])
304
+ >>> coef = hermefromroots((-1j, 1j))
305
+ >>> hermeval((-1j, 1j), coef)
306
+ array([0.+0.j, 0.+0.j])
307
+
308
+ """
309
+ return pu._fromroots(hermeline, hermemul, roots)
310
+
311
+
312
+ def hermeadd(c1, c2):
313
+ """
314
+ Add one Hermite series to another.
315
+
316
+ Returns the sum of two Hermite series `c1` + `c2`. The arguments
317
+ are sequences of coefficients ordered from lowest order term to
318
+ highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
319
+
320
+ Parameters
321
+ ----------
322
+ c1, c2 : array_like
323
+ 1-D arrays of Hermite series coefficients ordered from low to
324
+ high.
325
+
326
+ Returns
327
+ -------
328
+ out : ndarray
329
+ Array representing the Hermite series of their sum.
330
+
331
+ See Also
332
+ --------
333
+ hermesub, hermemulx, hermemul, hermediv, hermepow
334
+
335
+ Notes
336
+ -----
337
+ Unlike multiplication, division, etc., the sum of two Hermite series
338
+ is a Hermite series (without having to "reproject" the result onto
339
+ the basis set) so addition, just like that of "standard" polynomials,
340
+ is simply "component-wise."
341
+
342
+ Examples
343
+ --------
344
+ >>> from numpy.polynomial.hermite_e import hermeadd
345
+ >>> hermeadd([1, 2, 3], [1, 2, 3, 4])
346
+ array([2., 4., 6., 4.])
347
+
348
+ """
349
+ return pu._add(c1, c2)
350
+
351
+
352
+ def hermesub(c1, c2):
353
+ """
354
+ Subtract one Hermite series from another.
355
+
356
+ Returns the difference of two Hermite series `c1` - `c2`. The
357
+ sequences of coefficients are from lowest order term to highest, i.e.,
358
+ [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
359
+
360
+ Parameters
361
+ ----------
362
+ c1, c2 : array_like
363
+ 1-D arrays of Hermite series coefficients ordered from low to
364
+ high.
365
+
366
+ Returns
367
+ -------
368
+ out : ndarray
369
+ Of Hermite series coefficients representing their difference.
370
+
371
+ See Also
372
+ --------
373
+ hermeadd, hermemulx, hermemul, hermediv, hermepow
374
+
375
+ Notes
376
+ -----
377
+ Unlike multiplication, division, etc., the difference of two Hermite
378
+ series is a Hermite series (without having to "reproject" the result
379
+ onto the basis set) so subtraction, just like that of "standard"
380
+ polynomials, is simply "component-wise."
381
+
382
+ Examples
383
+ --------
384
+ >>> from numpy.polynomial.hermite_e import hermesub
385
+ >>> hermesub([1, 2, 3, 4], [1, 2, 3])
386
+ array([0., 0., 0., 4.])
387
+
388
+ """
389
+ return pu._sub(c1, c2)
390
+
391
+
392
+ def hermemulx(c):
393
+ """Multiply a Hermite series by x.
394
+
395
+ Multiply the Hermite series `c` by x, where x is the independent
396
+ variable.
397
+
398
+
399
+ Parameters
400
+ ----------
401
+ c : array_like
402
+ 1-D array of Hermite series coefficients ordered from low to
403
+ high.
404
+
405
+ Returns
406
+ -------
407
+ out : ndarray
408
+ Array representing the result of the multiplication.
409
+
410
+ Notes
411
+ -----
412
+ The multiplication uses the recursion relationship for Hermite
413
+ polynomials in the form
414
+
415
+ .. math::
416
+
417
+ xP_i(x) = (P_{i + 1}(x) + iP_{i - 1}(x)))
418
+
419
+ Examples
420
+ --------
421
+ >>> from numpy.polynomial.hermite_e import hermemulx
422
+ >>> hermemulx([1, 2, 3])
423
+ array([2., 7., 2., 3.])
424
+
425
+ """
426
+ # c is a trimmed copy
427
+ [c] = pu.as_series([c])
428
+ # The zero series needs special treatment
429
+ if len(c) == 1 and c[0] == 0:
430
+ return c
431
+
432
+ prd = np.empty(len(c) + 1, dtype=c.dtype)
433
+ prd[0] = c[0]*0
434
+ prd[1] = c[0]
435
+ for i in range(1, len(c)):
436
+ prd[i + 1] = c[i]
437
+ prd[i - 1] += c[i]*i
438
+ return prd
439
+
440
+
441
+ def hermemul(c1, c2):
442
+ """
443
+ Multiply one Hermite series by another.
444
+
445
+ Returns the product of two Hermite series `c1` * `c2`. The arguments
446
+ are sequences of coefficients, from lowest order "term" to highest,
447
+ e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
448
+
449
+ Parameters
450
+ ----------
451
+ c1, c2 : array_like
452
+ 1-D arrays of Hermite series coefficients ordered from low to
453
+ high.
454
+
455
+ Returns
456
+ -------
457
+ out : ndarray
458
+ Of Hermite series coefficients representing their product.
459
+
460
+ See Also
461
+ --------
462
+ hermeadd, hermesub, hermemulx, hermediv, hermepow
463
+
464
+ Notes
465
+ -----
466
+ In general, the (polynomial) product of two C-series results in terms
467
+ that are not in the Hermite polynomial basis set. Thus, to express
468
+ the product as a Hermite series, it is necessary to "reproject" the
469
+ product onto said basis set, which may produce "unintuitive" (but
470
+ correct) results; see Examples section below.
471
+
472
+ Examples
473
+ --------
474
+ >>> from numpy.polynomial.hermite_e import hermemul
475
+ >>> hermemul([1, 2, 3], [0, 1, 2])
476
+ array([14., 15., 28., 7., 6.])
477
+
478
+ """
479
+ # s1, s2 are trimmed copies
480
+ [c1, c2] = pu.as_series([c1, c2])
481
+
482
+ if len(c1) > len(c2):
483
+ c = c2
484
+ xs = c1
485
+ else:
486
+ c = c1
487
+ xs = c2
488
+
489
+ if len(c) == 1:
490
+ c0 = c[0]*xs
491
+ c1 = 0
492
+ elif len(c) == 2:
493
+ c0 = c[0]*xs
494
+ c1 = c[1]*xs
495
+ else:
496
+ nd = len(c)
497
+ c0 = c[-2]*xs
498
+ c1 = c[-1]*xs
499
+ for i in range(3, len(c) + 1):
500
+ tmp = c0
501
+ nd = nd - 1
502
+ c0 = hermesub(c[-i]*xs, c1*(nd - 1))
503
+ c1 = hermeadd(tmp, hermemulx(c1))
504
+ return hermeadd(c0, hermemulx(c1))
505
+
506
+
507
+ def hermediv(c1, c2):
508
+ """
509
+ Divide one Hermite series by another.
510
+
511
+ Returns the quotient-with-remainder of two Hermite series
512
+ `c1` / `c2`. The arguments are sequences of coefficients from lowest
513
+ order "term" to highest, e.g., [1,2,3] represents the series
514
+ ``P_0 + 2*P_1 + 3*P_2``.
515
+
516
+ Parameters
517
+ ----------
518
+ c1, c2 : array_like
519
+ 1-D arrays of Hermite series coefficients ordered from low to
520
+ high.
521
+
522
+ Returns
523
+ -------
524
+ [quo, rem] : ndarrays
525
+ Of Hermite series coefficients representing the quotient and
526
+ remainder.
527
+
528
+ See Also
529
+ --------
530
+ hermeadd, hermesub, hermemulx, hermemul, hermepow
531
+
532
+ Notes
533
+ -----
534
+ In general, the (polynomial) division of one Hermite series by another
535
+ results in quotient and remainder terms that are not in the Hermite
536
+ polynomial basis set. Thus, to express these results as a Hermite
537
+ series, it is necessary to "reproject" the results onto the Hermite
538
+ basis set, which may produce "unintuitive" (but correct) results; see
539
+ Examples section below.
540
+
541
+ Examples
542
+ --------
543
+ >>> from numpy.polynomial.hermite_e import hermediv
544
+ >>> hermediv([ 14., 15., 28., 7., 6.], [0, 1, 2])
545
+ (array([1., 2., 3.]), array([0.]))
546
+ >>> hermediv([ 15., 17., 28., 7., 6.], [0, 1, 2])
547
+ (array([1., 2., 3.]), array([1., 2.]))
548
+
549
+ """
550
+ return pu._div(hermemul, c1, c2)
551
+
552
+
553
+ def hermepow(c, pow, maxpower=16):
554
+ """Raise a Hermite series to a power.
555
+
556
+ Returns the Hermite series `c` raised to the power `pow`. The
557
+ argument `c` is a sequence of coefficients ordered from low to high.
558
+ i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``
559
+
560
+ Parameters
561
+ ----------
562
+ c : array_like
563
+ 1-D array of Hermite series coefficients ordered from low to
564
+ high.
565
+ pow : integer
566
+ Power to which the series will be raised
567
+ maxpower : integer, optional
568
+ Maximum power allowed. This is mainly to limit growth of the series
569
+ to unmanageable size. Default is 16
570
+
571
+ Returns
572
+ -------
573
+ coef : ndarray
574
+ Hermite series of power.
575
+
576
+ See Also
577
+ --------
578
+ hermeadd, hermesub, hermemulx, hermemul, hermediv
579
+
580
+ Examples
581
+ --------
582
+ >>> from numpy.polynomial.hermite_e import hermepow
583
+ >>> hermepow([1, 2, 3], 2)
584
+ array([23., 28., 46., 12., 9.])
585
+
586
+ """
587
+ return pu._pow(hermemul, c, pow, maxpower)
588
+
589
+
590
+ def hermeder(c, m=1, scl=1, axis=0):
591
+ """
592
+ Differentiate a Hermite_e series.
593
+
594
+ Returns the series coefficients `c` differentiated `m` times along
595
+ `axis`. At each iteration the result is multiplied by `scl` (the
596
+ scaling factor is for use in a linear change of variable). The argument
597
+ `c` is an array of coefficients from low to high degree along each
598
+ axis, e.g., [1,2,3] represents the series ``1*He_0 + 2*He_1 + 3*He_2``
599
+ while [[1,2],[1,2]] represents ``1*He_0(x)*He_0(y) + 1*He_1(x)*He_0(y)
600
+ + 2*He_0(x)*He_1(y) + 2*He_1(x)*He_1(y)`` if axis=0 is ``x`` and axis=1
601
+ is ``y``.
602
+
603
+ Parameters
604
+ ----------
605
+ c : array_like
606
+ Array of Hermite_e series coefficients. If `c` is multidimensional
607
+ the different axis correspond to different variables with the
608
+ degree in each axis given by the corresponding index.
609
+ m : int, optional
610
+ Number of derivatives taken, must be non-negative. (Default: 1)
611
+ scl : scalar, optional
612
+ Each differentiation is multiplied by `scl`. The end result is
613
+ multiplication by ``scl**m``. This is for use in a linear change of
614
+ variable. (Default: 1)
615
+ axis : int, optional
616
+ Axis over which the derivative is taken. (Default: 0).
617
+
618
+ .. versionadded:: 1.7.0
619
+
620
+ Returns
621
+ -------
622
+ der : ndarray
623
+ Hermite series of the derivative.
624
+
625
+ See Also
626
+ --------
627
+ hermeint
628
+
629
+ Notes
630
+ -----
631
+ In general, the result of differentiating a Hermite series does not
632
+ resemble the same operation on a power series. Thus the result of this
633
+ function may be "unintuitive," albeit correct; see Examples section
634
+ below.
635
+
636
+ Examples
637
+ --------
638
+ >>> from numpy.polynomial.hermite_e import hermeder
639
+ >>> hermeder([ 1., 1., 1., 1.])
640
+ array([1., 2., 3.])
641
+ >>> hermeder([-0.25, 1., 1./2., 1./3., 1./4 ], m=2)
642
+ array([1., 2., 3.])
643
+
644
+ """
645
+ c = np.array(c, ndmin=1, copy=True)
646
+ if c.dtype.char in '?bBhHiIlLqQpP':
647
+ c = c.astype(np.double)
648
+ cnt = pu._deprecate_as_int(m, "the order of derivation")
649
+ iaxis = pu._deprecate_as_int(axis, "the axis")
650
+ if cnt < 0:
651
+ raise ValueError("The order of derivation must be non-negative")
652
+ iaxis = normalize_axis_index(iaxis, c.ndim)
653
+
654
+ if cnt == 0:
655
+ return c
656
+
657
+ c = np.moveaxis(c, iaxis, 0)
658
+ n = len(c)
659
+ if cnt >= n:
660
+ return c[:1]*0
661
+ else:
662
+ for i in range(cnt):
663
+ n = n - 1
664
+ c *= scl
665
+ der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
666
+ for j in range(n, 0, -1):
667
+ der[j - 1] = j*c[j]
668
+ c = der
669
+ c = np.moveaxis(c, 0, iaxis)
670
+ return c
671
+
672
+
673
+ def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
674
+ """
675
+ Integrate a Hermite_e series.
676
+
677
+ Returns the Hermite_e series coefficients `c` integrated `m` times from
678
+ `lbnd` along `axis`. At each iteration the resulting series is
679
+ **multiplied** by `scl` and an integration constant, `k`, is added.
680
+ The scaling factor is for use in a linear change of variable. ("Buyer
681
+ beware": note that, depending on what one is doing, one may want `scl`
682
+ to be the reciprocal of what one might expect; for more information,
683
+ see the Notes section below.) The argument `c` is an array of
684
+ coefficients from low to high degree along each axis, e.g., [1,2,3]
685
+ represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]
686
+ represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +
687
+ 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
688
+
689
+ Parameters
690
+ ----------
691
+ c : array_like
692
+ Array of Hermite_e series coefficients. If c is multidimensional
693
+ the different axis correspond to different variables with the
694
+ degree in each axis given by the corresponding index.
695
+ m : int, optional
696
+ Order of integration, must be positive. (Default: 1)
697
+ k : {[], list, scalar}, optional
698
+ Integration constant(s). The value of the first integral at
699
+ ``lbnd`` is the first value in the list, the value of the second
700
+ integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
701
+ default), all constants are set to zero. If ``m == 1``, a single
702
+ scalar can be given instead of a list.
703
+ lbnd : scalar, optional
704
+ The lower bound of the integral. (Default: 0)
705
+ scl : scalar, optional
706
+ Following each integration the result is *multiplied* by `scl`
707
+ before the integration constant is added. (Default: 1)
708
+ axis : int, optional
709
+ Axis over which the integral is taken. (Default: 0).
710
+
711
+ .. versionadded:: 1.7.0
712
+
713
+ Returns
714
+ -------
715
+ S : ndarray
716
+ Hermite_e series coefficients of the integral.
717
+
718
+ Raises
719
+ ------
720
+ ValueError
721
+ If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
722
+ ``np.ndim(scl) != 0``.
723
+
724
+ See Also
725
+ --------
726
+ hermeder
727
+
728
+ Notes
729
+ -----
730
+ Note that the result of each integration is *multiplied* by `scl`.
731
+ Why is this important to note? Say one is making a linear change of
732
+ variable :math:`u = ax + b` in an integral relative to `x`. Then
733
+ :math:`dx = du/a`, so one will need to set `scl` equal to
734
+ :math:`1/a` - perhaps not what one would have first thought.
735
+
736
+ Also note that, in general, the result of integrating a C-series needs
737
+ to be "reprojected" onto the C-series basis set. Thus, typically,
738
+ the result of this function is "unintuitive," albeit correct; see
739
+ Examples section below.
740
+
741
+ Examples
742
+ --------
743
+ >>> from numpy.polynomial.hermite_e import hermeint
744
+ >>> hermeint([1, 2, 3]) # integrate once, value 0 at 0.
745
+ array([1., 1., 1., 1.])
746
+ >>> hermeint([1, 2, 3], m=2) # integrate twice, value & deriv 0 at 0
747
+ array([-0.25 , 1. , 0.5 , 0.33333333, 0.25 ]) # may vary
748
+ >>> hermeint([1, 2, 3], k=1) # integrate once, value 1 at 0.
749
+ array([2., 1., 1., 1.])
750
+ >>> hermeint([1, 2, 3], lbnd=-1) # integrate once, value 0 at -1
751
+ array([-1., 1., 1., 1.])
752
+ >>> hermeint([1, 2, 3], m=2, k=[1, 2], lbnd=-1)
753
+ array([ 1.83333333, 0. , 0.5 , 0.33333333, 0.25 ]) # may vary
754
+
755
+ """
756
+ c = np.array(c, ndmin=1, copy=True)
757
+ if c.dtype.char in '?bBhHiIlLqQpP':
758
+ c = c.astype(np.double)
759
+ if not np.iterable(k):
760
+ k = [k]
761
+ cnt = pu._deprecate_as_int(m, "the order of integration")
762
+ iaxis = pu._deprecate_as_int(axis, "the axis")
763
+ if cnt < 0:
764
+ raise ValueError("The order of integration must be non-negative")
765
+ if len(k) > cnt:
766
+ raise ValueError("Too many integration constants")
767
+ if np.ndim(lbnd) != 0:
768
+ raise ValueError("lbnd must be a scalar.")
769
+ if np.ndim(scl) != 0:
770
+ raise ValueError("scl must be a scalar.")
771
+ iaxis = normalize_axis_index(iaxis, c.ndim)
772
+
773
+ if cnt == 0:
774
+ return c
775
+
776
+ c = np.moveaxis(c, iaxis, 0)
777
+ k = list(k) + [0]*(cnt - len(k))
778
+ for i in range(cnt):
779
+ n = len(c)
780
+ c *= scl
781
+ if n == 1 and np.all(c[0] == 0):
782
+ c[0] += k[i]
783
+ else:
784
+ tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
785
+ tmp[0] = c[0]*0
786
+ tmp[1] = c[0]
787
+ for j in range(1, n):
788
+ tmp[j + 1] = c[j]/(j + 1)
789
+ tmp[0] += k[i] - hermeval(lbnd, tmp)
790
+ c = tmp
791
+ c = np.moveaxis(c, 0, iaxis)
792
+ return c
793
+
794
+
795
+ def hermeval(x, c, tensor=True):
796
+ """
797
+ Evaluate an HermiteE series at points x.
798
+
799
+ If `c` is of length `n + 1`, this function returns the value:
800
+
801
+ .. math:: p(x) = c_0 * He_0(x) + c_1 * He_1(x) + ... + c_n * He_n(x)
802
+
803
+ The parameter `x` is converted to an array only if it is a tuple or a
804
+ list, otherwise it is treated as a scalar. In either case, either `x`
805
+ or its elements must support multiplication and addition both with
806
+ themselves and with the elements of `c`.
807
+
808
+ If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
809
+ `c` is multidimensional, then the shape of the result depends on the
810
+ value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
811
+ x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
812
+ scalars have shape (,).
813
+
814
+ Trailing zeros in the coefficients will be used in the evaluation, so
815
+ they should be avoided if efficiency is a concern.
816
+
817
+ Parameters
818
+ ----------
819
+ x : array_like, compatible object
820
+ If `x` is a list or tuple, it is converted to an ndarray, otherwise
821
+ it is left unchanged and treated as a scalar. In either case, `x`
822
+ or its elements must support addition and multiplication with
823
+ with themselves and with the elements of `c`.
824
+ c : array_like
825
+ Array of coefficients ordered so that the coefficients for terms of
826
+ degree n are contained in c[n]. If `c` is multidimensional the
827
+ remaining indices enumerate multiple polynomials. In the two
828
+ dimensional case the coefficients may be thought of as stored in
829
+ the columns of `c`.
830
+ tensor : boolean, optional
831
+ If True, the shape of the coefficient array is extended with ones
832
+ on the right, one for each dimension of `x`. Scalars have dimension 0
833
+ for this action. The result is that every column of coefficients in
834
+ `c` is evaluated for every element of `x`. If False, `x` is broadcast
835
+ over the columns of `c` for the evaluation. This keyword is useful
836
+ when `c` is multidimensional. The default value is True.
837
+
838
+ .. versionadded:: 1.7.0
839
+
840
+ Returns
841
+ -------
842
+ values : ndarray, algebra_like
843
+ The shape of the return value is described above.
844
+
845
+ See Also
846
+ --------
847
+ hermeval2d, hermegrid2d, hermeval3d, hermegrid3d
848
+
849
+ Notes
850
+ -----
851
+ The evaluation uses Clenshaw recursion, aka synthetic division.
852
+
853
+ Examples
854
+ --------
855
+ >>> from numpy.polynomial.hermite_e import hermeval
856
+ >>> coef = [1,2,3]
857
+ >>> hermeval(1, coef)
858
+ 3.0
859
+ >>> hermeval([[1,2],[3,4]], coef)
860
+ array([[ 3., 14.],
861
+ [31., 54.]])
862
+
863
+ """
864
+ c = np.array(c, ndmin=1, copy=False)
865
+ if c.dtype.char in '?bBhHiIlLqQpP':
866
+ c = c.astype(np.double)
867
+ if isinstance(x, (tuple, list)):
868
+ x = np.asarray(x)
869
+ if isinstance(x, np.ndarray) and tensor:
870
+ c = c.reshape(c.shape + (1,)*x.ndim)
871
+
872
+ if len(c) == 1:
873
+ c0 = c[0]
874
+ c1 = 0
875
+ elif len(c) == 2:
876
+ c0 = c[0]
877
+ c1 = c[1]
878
+ else:
879
+ nd = len(c)
880
+ c0 = c[-2]
881
+ c1 = c[-1]
882
+ for i in range(3, len(c) + 1):
883
+ tmp = c0
884
+ nd = nd - 1
885
+ c0 = c[-i] - c1*(nd - 1)
886
+ c1 = tmp + c1*x
887
+ return c0 + c1*x
888
+
889
+
890
+ def hermeval2d(x, y, c):
891
+ """
892
+ Evaluate a 2-D HermiteE series at points (x, y).
893
+
894
+ This function returns the values:
895
+
896
+ .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y)
897
+
898
+ The parameters `x` and `y` are converted to arrays only if they are
899
+ tuples or a lists, otherwise they are treated as a scalars and they
900
+ must have the same shape after conversion. In either case, either `x`
901
+ and `y` or their elements must support multiplication and addition both
902
+ with themselves and with the elements of `c`.
903
+
904
+ If `c` is a 1-D array a one is implicitly appended to its shape to make
905
+ it 2-D. The shape of the result will be c.shape[2:] + x.shape.
906
+
907
+ Parameters
908
+ ----------
909
+ x, y : array_like, compatible objects
910
+ The two dimensional series is evaluated at the points `(x, y)`,
911
+ where `x` and `y` must have the same shape. If `x` or `y` is a list
912
+ or tuple, it is first converted to an ndarray, otherwise it is left
913
+ unchanged and if it isn't an ndarray it is treated as a scalar.
914
+ c : array_like
915
+ Array of coefficients ordered so that the coefficient of the term
916
+ of multi-degree i,j is contained in ``c[i,j]``. If `c` has
917
+ dimension greater than two the remaining indices enumerate multiple
918
+ sets of coefficients.
919
+
920
+ Returns
921
+ -------
922
+ values : ndarray, compatible object
923
+ The values of the two dimensional polynomial at points formed with
924
+ pairs of corresponding values from `x` and `y`.
925
+
926
+ See Also
927
+ --------
928
+ hermeval, hermegrid2d, hermeval3d, hermegrid3d
929
+
930
+ Notes
931
+ -----
932
+
933
+ .. versionadded:: 1.7.0
934
+
935
+ """
936
+ return pu._valnd(hermeval, c, x, y)
937
+
938
+
939
+ def hermegrid2d(x, y, c):
940
+ """
941
+ Evaluate a 2-D HermiteE series on the Cartesian product of x and y.
942
+
943
+ This function returns the values:
944
+
945
+ .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * H_i(a) * H_j(b)
946
+
947
+ where the points `(a, b)` consist of all pairs formed by taking
948
+ `a` from `x` and `b` from `y`. The resulting points form a grid with
949
+ `x` in the first dimension and `y` in the second.
950
+
951
+ The parameters `x` and `y` are converted to arrays only if they are
952
+ tuples or a lists, otherwise they are treated as a scalars. In either
953
+ case, either `x` and `y` or their elements must support multiplication
954
+ and addition both with themselves and with the elements of `c`.
955
+
956
+ If `c` has fewer than two dimensions, ones are implicitly appended to
957
+ its shape to make it 2-D. The shape of the result will be c.shape[2:] +
958
+ x.shape.
959
+
960
+ Parameters
961
+ ----------
962
+ x, y : array_like, compatible objects
963
+ The two dimensional series is evaluated at the points in the
964
+ Cartesian product of `x` and `y`. If `x` or `y` is a list or
965
+ tuple, it is first converted to an ndarray, otherwise it is left
966
+ unchanged and, if it isn't an ndarray, it is treated as a scalar.
967
+ c : array_like
968
+ Array of coefficients ordered so that the coefficients for terms of
969
+ degree i,j are contained in ``c[i,j]``. If `c` has dimension
970
+ greater than two the remaining indices enumerate multiple sets of
971
+ coefficients.
972
+
973
+ Returns
974
+ -------
975
+ values : ndarray, compatible object
976
+ The values of the two dimensional polynomial at points in the Cartesian
977
+ product of `x` and `y`.
978
+
979
+ See Also
980
+ --------
981
+ hermeval, hermeval2d, hermeval3d, hermegrid3d
982
+
983
+ Notes
984
+ -----
985
+
986
+ .. versionadded:: 1.7.0
987
+
988
+ """
989
+ return pu._gridnd(hermeval, c, x, y)
990
+
991
+
992
+ def hermeval3d(x, y, z, c):
993
+ """
994
+ Evaluate a 3-D Hermite_e series at points (x, y, z).
995
+
996
+ This function returns the values:
997
+
998
+ .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * He_i(x) * He_j(y) * He_k(z)
999
+
1000
+ The parameters `x`, `y`, and `z` are converted to arrays only if
1001
+ they are tuples or a lists, otherwise they are treated as a scalars and
1002
+ they must have the same shape after conversion. In either case, either
1003
+ `x`, `y`, and `z` or their elements must support multiplication and
1004
+ addition both with themselves and with the elements of `c`.
1005
+
1006
+ If `c` has fewer than 3 dimensions, ones are implicitly appended to its
1007
+ shape to make it 3-D. The shape of the result will be c.shape[3:] +
1008
+ x.shape.
1009
+
1010
+ Parameters
1011
+ ----------
1012
+ x, y, z : array_like, compatible object
1013
+ The three dimensional series is evaluated at the points
1014
+ `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
1015
+ any of `x`, `y`, or `z` is a list or tuple, it is first converted
1016
+ to an ndarray, otherwise it is left unchanged and if it isn't an
1017
+ ndarray it is treated as a scalar.
1018
+ c : array_like
1019
+ Array of coefficients ordered so that the coefficient of the term of
1020
+ multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
1021
+ greater than 3 the remaining indices enumerate multiple sets of
1022
+ coefficients.
1023
+
1024
+ Returns
1025
+ -------
1026
+ values : ndarray, compatible object
1027
+ The values of the multidimensional polynomial on points formed with
1028
+ triples of corresponding values from `x`, `y`, and `z`.
1029
+
1030
+ See Also
1031
+ --------
1032
+ hermeval, hermeval2d, hermegrid2d, hermegrid3d
1033
+
1034
+ Notes
1035
+ -----
1036
+
1037
+ .. versionadded:: 1.7.0
1038
+
1039
+ """
1040
+ return pu._valnd(hermeval, c, x, y, z)
1041
+
1042
+
1043
+ def hermegrid3d(x, y, z, c):
1044
+ """
1045
+ Evaluate a 3-D HermiteE series on the Cartesian product of x, y, and z.
1046
+
1047
+ This function returns the values:
1048
+
1049
+ .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * He_i(a) * He_j(b) * He_k(c)
1050
+
1051
+ where the points `(a, b, c)` consist of all triples formed by taking
1052
+ `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
1053
+ a grid with `x` in the first dimension, `y` in the second, and `z` in
1054
+ the third.
1055
+
1056
+ The parameters `x`, `y`, and `z` are converted to arrays only if they
1057
+ are tuples or a lists, otherwise they are treated as a scalars. In
1058
+ either case, either `x`, `y`, and `z` or their elements must support
1059
+ multiplication and addition both with themselves and with the elements
1060
+ of `c`.
1061
+
1062
+ If `c` has fewer than three dimensions, ones are implicitly appended to
1063
+ its shape to make it 3-D. The shape of the result will be c.shape[3:] +
1064
+ x.shape + y.shape + z.shape.
1065
+
1066
+ Parameters
1067
+ ----------
1068
+ x, y, z : array_like, compatible objects
1069
+ The three dimensional series is evaluated at the points in the
1070
+ Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
1071
+ list or tuple, it is first converted to an ndarray, otherwise it is
1072
+ left unchanged and, if it isn't an ndarray, it is treated as a
1073
+ scalar.
1074
+ c : array_like
1075
+ Array of coefficients ordered so that the coefficients for terms of
1076
+ degree i,j are contained in ``c[i,j]``. If `c` has dimension
1077
+ greater than two the remaining indices enumerate multiple sets of
1078
+ coefficients.
1079
+
1080
+ Returns
1081
+ -------
1082
+ values : ndarray, compatible object
1083
+ The values of the two dimensional polynomial at points in the Cartesian
1084
+ product of `x` and `y`.
1085
+
1086
+ See Also
1087
+ --------
1088
+ hermeval, hermeval2d, hermegrid2d, hermeval3d
1089
+
1090
+ Notes
1091
+ -----
1092
+
1093
+ .. versionadded:: 1.7.0
1094
+
1095
+ """
1096
+ return pu._gridnd(hermeval, c, x, y, z)
1097
+
1098
+
1099
+ def hermevander(x, deg):
1100
+ """Pseudo-Vandermonde matrix of given degree.
1101
+
1102
+ Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
1103
+ `x`. The pseudo-Vandermonde matrix is defined by
1104
+
1105
+ .. math:: V[..., i] = He_i(x),
1106
+
1107
+ where `0 <= i <= deg`. The leading indices of `V` index the elements of
1108
+ `x` and the last index is the degree of the HermiteE polynomial.
1109
+
1110
+ If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
1111
+ array ``V = hermevander(x, n)``, then ``np.dot(V, c)`` and
1112
+ ``hermeval(x, c)`` are the same up to roundoff. This equivalence is
1113
+ useful both for least squares fitting and for the evaluation of a large
1114
+ number of HermiteE series of the same degree and sample points.
1115
+
1116
+ Parameters
1117
+ ----------
1118
+ x : array_like
1119
+ Array of points. The dtype is converted to float64 or complex128
1120
+ depending on whether any of the elements are complex. If `x` is
1121
+ scalar it is converted to a 1-D array.
1122
+ deg : int
1123
+ Degree of the resulting matrix.
1124
+
1125
+ Returns
1126
+ -------
1127
+ vander : ndarray
1128
+ The pseudo-Vandermonde matrix. The shape of the returned matrix is
1129
+ ``x.shape + (deg + 1,)``, where The last index is the degree of the
1130
+ corresponding HermiteE polynomial. The dtype will be the same as
1131
+ the converted `x`.
1132
+
1133
+ Examples
1134
+ --------
1135
+ >>> from numpy.polynomial.hermite_e import hermevander
1136
+ >>> x = np.array([-1, 0, 1])
1137
+ >>> hermevander(x, 3)
1138
+ array([[ 1., -1., 0., 2.],
1139
+ [ 1., 0., -1., -0.],
1140
+ [ 1., 1., 0., -2.]])
1141
+
1142
+ """
1143
+ ideg = pu._deprecate_as_int(deg, "deg")
1144
+ if ideg < 0:
1145
+ raise ValueError("deg must be non-negative")
1146
+
1147
+ x = np.array(x, copy=False, ndmin=1) + 0.0
1148
+ dims = (ideg + 1,) + x.shape
1149
+ dtyp = x.dtype
1150
+ v = np.empty(dims, dtype=dtyp)
1151
+ v[0] = x*0 + 1
1152
+ if ideg > 0:
1153
+ v[1] = x
1154
+ for i in range(2, ideg + 1):
1155
+ v[i] = (v[i-1]*x - v[i-2]*(i - 1))
1156
+ return np.moveaxis(v, 0, -1)
1157
+
1158
+
1159
+ def hermevander2d(x, y, deg):
1160
+ """Pseudo-Vandermonde matrix of given degrees.
1161
+
1162
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1163
+ points `(x, y)`. The pseudo-Vandermonde matrix is defined by
1164
+
1165
+ .. math:: V[..., (deg[1] + 1)*i + j] = He_i(x) * He_j(y),
1166
+
1167
+ where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
1168
+ `V` index the points `(x, y)` and the last index encodes the degrees of
1169
+ the HermiteE polynomials.
1170
+
1171
+ If ``V = hermevander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
1172
+ correspond to the elements of a 2-D coefficient array `c` of shape
1173
+ (xdeg + 1, ydeg + 1) in the order
1174
+
1175
+ .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
1176
+
1177
+ and ``np.dot(V, c.flat)`` and ``hermeval2d(x, y, c)`` will be the same
1178
+ up to roundoff. This equivalence is useful both for least squares
1179
+ fitting and for the evaluation of a large number of 2-D HermiteE
1180
+ series of the same degrees and sample points.
1181
+
1182
+ Parameters
1183
+ ----------
1184
+ x, y : array_like
1185
+ Arrays of point coordinates, all of the same shape. The dtypes
1186
+ will be converted to either float64 or complex128 depending on
1187
+ whether any of the elements are complex. Scalars are converted to
1188
+ 1-D arrays.
1189
+ deg : list of ints
1190
+ List of maximum degrees of the form [x_deg, y_deg].
1191
+
1192
+ Returns
1193
+ -------
1194
+ vander2d : ndarray
1195
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1196
+ :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same
1197
+ as the converted `x` and `y`.
1198
+
1199
+ See Also
1200
+ --------
1201
+ hermevander, hermevander3d, hermeval2d, hermeval3d
1202
+
1203
+ Notes
1204
+ -----
1205
+
1206
+ .. versionadded:: 1.7.0
1207
+
1208
+ """
1209
+ return pu._vander_nd_flat((hermevander, hermevander), (x, y), deg)
1210
+
1211
+
1212
+ def hermevander3d(x, y, z, deg):
1213
+ """Pseudo-Vandermonde matrix of given degrees.
1214
+
1215
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1216
+ points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
1217
+ then Hehe pseudo-Vandermonde matrix is defined by
1218
+
1219
+ .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = He_i(x)*He_j(y)*He_k(z),
1220
+
1221
+ where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
1222
+ indices of `V` index the points `(x, y, z)` and the last index encodes
1223
+ the degrees of the HermiteE polynomials.
1224
+
1225
+ If ``V = hermevander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
1226
+ of `V` correspond to the elements of a 3-D coefficient array `c` of
1227
+ shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
1228
+
1229
+ .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
1230
+
1231
+ and ``np.dot(V, c.flat)`` and ``hermeval3d(x, y, z, c)`` will be the
1232
+ same up to roundoff. This equivalence is useful both for least squares
1233
+ fitting and for the evaluation of a large number of 3-D HermiteE
1234
+ series of the same degrees and sample points.
1235
+
1236
+ Parameters
1237
+ ----------
1238
+ x, y, z : array_like
1239
+ Arrays of point coordinates, all of the same shape. The dtypes will
1240
+ be converted to either float64 or complex128 depending on whether
1241
+ any of the elements are complex. Scalars are converted to 1-D
1242
+ arrays.
1243
+ deg : list of ints
1244
+ List of maximum degrees of the form [x_deg, y_deg, z_deg].
1245
+
1246
+ Returns
1247
+ -------
1248
+ vander3d : ndarray
1249
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1250
+ :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will
1251
+ be the same as the converted `x`, `y`, and `z`.
1252
+
1253
+ See Also
1254
+ --------
1255
+ hermevander, hermevander3d, hermeval2d, hermeval3d
1256
+
1257
+ Notes
1258
+ -----
1259
+
1260
+ .. versionadded:: 1.7.0
1261
+
1262
+ """
1263
+ return pu._vander_nd_flat((hermevander, hermevander, hermevander), (x, y, z), deg)
1264
+
1265
+
1266
+ def hermefit(x, y, deg, rcond=None, full=False, w=None):
1267
+ """
1268
+ Least squares fit of Hermite series to data.
1269
+
1270
+ Return the coefficients of a HermiteE series of degree `deg` that is
1271
+ the least squares fit to the data values `y` given at points `x`. If
1272
+ `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D
1273
+ multiple fits are done, one for each column of `y`, and the resulting
1274
+ coefficients are stored in the corresponding columns of a 2-D return.
1275
+ The fitted polynomial(s) are in the form
1276
+
1277
+ .. math:: p(x) = c_0 + c_1 * He_1(x) + ... + c_n * He_n(x),
1278
+
1279
+ where `n` is `deg`.
1280
+
1281
+ Parameters
1282
+ ----------
1283
+ x : array_like, shape (M,)
1284
+ x-coordinates of the M sample points ``(x[i], y[i])``.
1285
+ y : array_like, shape (M,) or (M, K)
1286
+ y-coordinates of the sample points. Several data sets of sample
1287
+ points sharing the same x-coordinates can be fitted at once by
1288
+ passing in a 2D-array that contains one dataset per column.
1289
+ deg : int or 1-D array_like
1290
+ Degree(s) of the fitting polynomials. If `deg` is a single integer
1291
+ all terms up to and including the `deg`'th term are included in the
1292
+ fit. For NumPy versions >= 1.11.0 a list of integers specifying the
1293
+ degrees of the terms to include may be used instead.
1294
+ rcond : float, optional
1295
+ Relative condition number of the fit. Singular values smaller than
1296
+ this relative to the largest singular value will be ignored. The
1297
+ default value is len(x)*eps, where eps is the relative precision of
1298
+ the float type, about 2e-16 in most cases.
1299
+ full : bool, optional
1300
+ Switch determining nature of return value. When it is False (the
1301
+ default) just the coefficients are returned, when True diagnostic
1302
+ information from the singular value decomposition is also returned.
1303
+ w : array_like, shape (`M`,), optional
1304
+ Weights. If not None, the weight ``w[i]`` applies to the unsquared
1305
+ residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
1306
+ chosen so that the errors of the products ``w[i]*y[i]`` all have the
1307
+ same variance. When using inverse-variance weighting, use
1308
+ ``w[i] = 1/sigma(y[i])``. The default value is None.
1309
+
1310
+ Returns
1311
+ -------
1312
+ coef : ndarray, shape (M,) or (M, K)
1313
+ Hermite coefficients ordered from low to high. If `y` was 2-D,
1314
+ the coefficients for the data in column k of `y` are in column
1315
+ `k`.
1316
+
1317
+ [residuals, rank, singular_values, rcond] : list
1318
+ These values are only returned if ``full == True``
1319
+
1320
+ - residuals -- sum of squared residuals of the least squares fit
1321
+ - rank -- the numerical rank of the scaled Vandermonde matrix
1322
+ - singular_values -- singular values of the scaled Vandermonde matrix
1323
+ - rcond -- value of `rcond`.
1324
+
1325
+ For more details, see `numpy.linalg.lstsq`.
1326
+
1327
+ Warns
1328
+ -----
1329
+ RankWarning
1330
+ The rank of the coefficient matrix in the least-squares fit is
1331
+ deficient. The warning is only raised if ``full = False``. The
1332
+ warnings can be turned off by
1333
+
1334
+ >>> import warnings
1335
+ >>> warnings.simplefilter('ignore', np.RankWarning)
1336
+
1337
+ See Also
1338
+ --------
1339
+ numpy.polynomial.chebyshev.chebfit
1340
+ numpy.polynomial.legendre.legfit
1341
+ numpy.polynomial.polynomial.polyfit
1342
+ numpy.polynomial.hermite.hermfit
1343
+ numpy.polynomial.laguerre.lagfit
1344
+ hermeval : Evaluates a Hermite series.
1345
+ hermevander : pseudo Vandermonde matrix of Hermite series.
1346
+ hermeweight : HermiteE weight function.
1347
+ numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
1348
+ scipy.interpolate.UnivariateSpline : Computes spline fits.
1349
+
1350
+ Notes
1351
+ -----
1352
+ The solution is the coefficients of the HermiteE series `p` that
1353
+ minimizes the sum of the weighted squared errors
1354
+
1355
+ .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
1356
+
1357
+ where the :math:`w_j` are the weights. This problem is solved by
1358
+ setting up the (typically) overdetermined matrix equation
1359
+
1360
+ .. math:: V(x) * c = w * y,
1361
+
1362
+ where `V` is the pseudo Vandermonde matrix of `x`, the elements of `c`
1363
+ are the coefficients to be solved for, and the elements of `y` are the
1364
+ observed values. This equation is then solved using the singular value
1365
+ decomposition of `V`.
1366
+
1367
+ If some of the singular values of `V` are so small that they are
1368
+ neglected, then a `RankWarning` will be issued. This means that the
1369
+ coefficient values may be poorly determined. Using a lower order fit
1370
+ will usually get rid of the warning. The `rcond` parameter can also be
1371
+ set to a value smaller than its default, but the resulting fit may be
1372
+ spurious and have large contributions from roundoff error.
1373
+
1374
+ Fits using HermiteE series are probably most useful when the data can
1375
+ be approximated by ``sqrt(w(x)) * p(x)``, where `w(x)` is the HermiteE
1376
+ weight. In that case the weight ``sqrt(w(x[i]))`` should be used
1377
+ together with data values ``y[i]/sqrt(w(x[i]))``. The weight function is
1378
+ available as `hermeweight`.
1379
+
1380
+ References
1381
+ ----------
1382
+ .. [1] Wikipedia, "Curve fitting",
1383
+ https://en.wikipedia.org/wiki/Curve_fitting
1384
+
1385
+ Examples
1386
+ --------
1387
+ >>> from numpy.polynomial.hermite_e import hermefit, hermeval
1388
+ >>> x = np.linspace(-10, 10)
1389
+ >>> np.random.seed(123)
1390
+ >>> err = np.random.randn(len(x))/10
1391
+ >>> y = hermeval(x, [1, 2, 3]) + err
1392
+ >>> hermefit(x, y, 2)
1393
+ array([ 1.01690445, 1.99951418, 2.99948696]) # may vary
1394
+
1395
+ """
1396
+ return pu._fit(hermevander, x, y, deg, rcond, full, w)
1397
+
1398
+
1399
+ def hermecompanion(c):
1400
+ """
1401
+ Return the scaled companion matrix of c.
1402
+
1403
+ The basis polynomials are scaled so that the companion matrix is
1404
+ symmetric when `c` is an HermiteE basis polynomial. This provides
1405
+ better eigenvalue estimates than the unscaled case and for basis
1406
+ polynomials the eigenvalues are guaranteed to be real if
1407
+ `numpy.linalg.eigvalsh` is used to obtain them.
1408
+
1409
+ Parameters
1410
+ ----------
1411
+ c : array_like
1412
+ 1-D array of HermiteE series coefficients ordered from low to high
1413
+ degree.
1414
+
1415
+ Returns
1416
+ -------
1417
+ mat : ndarray
1418
+ Scaled companion matrix of dimensions (deg, deg).
1419
+
1420
+ Notes
1421
+ -----
1422
+
1423
+ .. versionadded:: 1.7.0
1424
+
1425
+ """
1426
+ # c is a trimmed copy
1427
+ [c] = pu.as_series([c])
1428
+ if len(c) < 2:
1429
+ raise ValueError('Series must have maximum degree of at least 1.')
1430
+ if len(c) == 2:
1431
+ return np.array([[-c[0]/c[1]]])
1432
+
1433
+ n = len(c) - 1
1434
+ mat = np.zeros((n, n), dtype=c.dtype)
1435
+ scl = np.hstack((1., 1./np.sqrt(np.arange(n - 1, 0, -1))))
1436
+ scl = np.multiply.accumulate(scl)[::-1]
1437
+ top = mat.reshape(-1)[1::n+1]
1438
+ bot = mat.reshape(-1)[n::n+1]
1439
+ top[...] = np.sqrt(np.arange(1, n))
1440
+ bot[...] = top
1441
+ mat[:, -1] -= scl*c[:-1]/c[-1]
1442
+ return mat
1443
+
1444
+
1445
+ def hermeroots(c):
1446
+ """
1447
+ Compute the roots of a HermiteE series.
1448
+
1449
+ Return the roots (a.k.a. "zeros") of the polynomial
1450
+
1451
+ .. math:: p(x) = \\sum_i c[i] * He_i(x).
1452
+
1453
+ Parameters
1454
+ ----------
1455
+ c : 1-D array_like
1456
+ 1-D array of coefficients.
1457
+
1458
+ Returns
1459
+ -------
1460
+ out : ndarray
1461
+ Array of the roots of the series. If all the roots are real,
1462
+ then `out` is also real, otherwise it is complex.
1463
+
1464
+ See Also
1465
+ --------
1466
+ numpy.polynomial.polynomial.polyroots
1467
+ numpy.polynomial.legendre.legroots
1468
+ numpy.polynomial.laguerre.lagroots
1469
+ numpy.polynomial.hermite.hermroots
1470
+ numpy.polynomial.chebyshev.chebroots
1471
+
1472
+ Notes
1473
+ -----
1474
+ The root estimates are obtained as the eigenvalues of the companion
1475
+ matrix, Roots far from the origin of the complex plane may have large
1476
+ errors due to the numerical instability of the series for such
1477
+ values. Roots with multiplicity greater than 1 will also show larger
1478
+ errors as the value of the series near such points is relatively
1479
+ insensitive to errors in the roots. Isolated roots near the origin can
1480
+ be improved by a few iterations of Newton's method.
1481
+
1482
+ The HermiteE series basis polynomials aren't powers of `x` so the
1483
+ results of this function may seem unintuitive.
1484
+
1485
+ Examples
1486
+ --------
1487
+ >>> from numpy.polynomial.hermite_e import hermeroots, hermefromroots
1488
+ >>> coef = hermefromroots([-1, 0, 1])
1489
+ >>> coef
1490
+ array([0., 2., 0., 1.])
1491
+ >>> hermeroots(coef)
1492
+ array([-1., 0., 1.]) # may vary
1493
+
1494
+ """
1495
+ # c is a trimmed copy
1496
+ [c] = pu.as_series([c])
1497
+ if len(c) <= 1:
1498
+ return np.array([], dtype=c.dtype)
1499
+ if len(c) == 2:
1500
+ return np.array([-c[0]/c[1]])
1501
+
1502
+ # rotated companion matrix reduces error
1503
+ m = hermecompanion(c)[::-1,::-1]
1504
+ r = la.eigvals(m)
1505
+ r.sort()
1506
+ return r
1507
+
1508
+
1509
+ def _normed_hermite_e_n(x, n):
1510
+ """
1511
+ Evaluate a normalized HermiteE polynomial.
1512
+
1513
+ Compute the value of the normalized HermiteE polynomial of degree ``n``
1514
+ at the points ``x``.
1515
+
1516
+
1517
+ Parameters
1518
+ ----------
1519
+ x : ndarray of double.
1520
+ Points at which to evaluate the function
1521
+ n : int
1522
+ Degree of the normalized HermiteE function to be evaluated.
1523
+
1524
+ Returns
1525
+ -------
1526
+ values : ndarray
1527
+ The shape of the return value is described above.
1528
+
1529
+ Notes
1530
+ -----
1531
+ .. versionadded:: 1.10.0
1532
+
1533
+ This function is needed for finding the Gauss points and integration
1534
+ weights for high degrees. The values of the standard HermiteE functions
1535
+ overflow when n >= 207.
1536
+
1537
+ """
1538
+ if n == 0:
1539
+ return np.full(x.shape, 1/np.sqrt(np.sqrt(2*np.pi)))
1540
+
1541
+ c0 = 0.
1542
+ c1 = 1./np.sqrt(np.sqrt(2*np.pi))
1543
+ nd = float(n)
1544
+ for i in range(n - 1):
1545
+ tmp = c0
1546
+ c0 = -c1*np.sqrt((nd - 1.)/nd)
1547
+ c1 = tmp + c1*x*np.sqrt(1./nd)
1548
+ nd = nd - 1.0
1549
+ return c0 + c1*x
1550
+
1551
+
1552
+ def hermegauss(deg):
1553
+ """
1554
+ Gauss-HermiteE quadrature.
1555
+
1556
+ Computes the sample points and weights for Gauss-HermiteE quadrature.
1557
+ These sample points and weights will correctly integrate polynomials of
1558
+ degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`
1559
+ with the weight function :math:`f(x) = \\exp(-x^2/2)`.
1560
+
1561
+ Parameters
1562
+ ----------
1563
+ deg : int
1564
+ Number of sample points and weights. It must be >= 1.
1565
+
1566
+ Returns
1567
+ -------
1568
+ x : ndarray
1569
+ 1-D ndarray containing the sample points.
1570
+ y : ndarray
1571
+ 1-D ndarray containing the weights.
1572
+
1573
+ Notes
1574
+ -----
1575
+
1576
+ .. versionadded:: 1.7.0
1577
+
1578
+ The results have only been tested up to degree 100, higher degrees may
1579
+ be problematic. The weights are determined by using the fact that
1580
+
1581
+ .. math:: w_k = c / (He'_n(x_k) * He_{n-1}(x_k))
1582
+
1583
+ where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
1584
+ is the k'th root of :math:`He_n`, and then scaling the results to get
1585
+ the right value when integrating 1.
1586
+
1587
+ """
1588
+ ideg = pu._deprecate_as_int(deg, "deg")
1589
+ if ideg <= 0:
1590
+ raise ValueError("deg must be a positive integer")
1591
+
1592
+ # first approximation of roots. We use the fact that the companion
1593
+ # matrix is symmetric in this case in order to obtain better zeros.
1594
+ c = np.array([0]*deg + [1])
1595
+ m = hermecompanion(c)
1596
+ x = la.eigvalsh(m)
1597
+
1598
+ # improve roots by one application of Newton
1599
+ dy = _normed_hermite_e_n(x, ideg)
1600
+ df = _normed_hermite_e_n(x, ideg - 1) * np.sqrt(ideg)
1601
+ x -= dy/df
1602
+
1603
+ # compute the weights. We scale the factor to avoid possible numerical
1604
+ # overflow.
1605
+ fm = _normed_hermite_e_n(x, ideg - 1)
1606
+ fm /= np.abs(fm).max()
1607
+ w = 1/(fm * fm)
1608
+
1609
+ # for Hermite_e we can also symmetrize
1610
+ w = (w + w[::-1])/2
1611
+ x = (x - x[::-1])/2
1612
+
1613
+ # scale w to get the right value
1614
+ w *= np.sqrt(2*np.pi) / w.sum()
1615
+
1616
+ return x, w
1617
+
1618
+
1619
+ def hermeweight(x):
1620
+ """Weight function of the Hermite_e polynomials.
1621
+
1622
+ The weight function is :math:`\\exp(-x^2/2)` and the interval of
1623
+ integration is :math:`[-\\inf, \\inf]`. the HermiteE polynomials are
1624
+ orthogonal, but not normalized, with respect to this weight function.
1625
+
1626
+ Parameters
1627
+ ----------
1628
+ x : array_like
1629
+ Values at which the weight function will be computed.
1630
+
1631
+ Returns
1632
+ -------
1633
+ w : ndarray
1634
+ The weight function at `x`.
1635
+
1636
+ Notes
1637
+ -----
1638
+
1639
+ .. versionadded:: 1.7.0
1640
+
1641
+ """
1642
+ w = np.exp(-.5*x**2)
1643
+ return w
1644
+
1645
+
1646
+ #
1647
+ # HermiteE series class
1648
+ #
1649
+
1650
+ class HermiteE(ABCPolyBase):
1651
+ """An HermiteE series class.
1652
+
1653
+ The HermiteE class provides the standard Python numerical methods
1654
+ '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
1655
+ attributes and methods listed in the `ABCPolyBase` documentation.
1656
+
1657
+ Parameters
1658
+ ----------
1659
+ coef : array_like
1660
+ HermiteE coefficients in order of increasing degree, i.e,
1661
+ ``(1, 2, 3)`` gives ``1*He_0(x) + 2*He_1(X) + 3*He_2(x)``.
1662
+ domain : (2,) array_like, optional
1663
+ Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
1664
+ to the interval ``[window[0], window[1]]`` by shifting and scaling.
1665
+ The default value is [-1, 1].
1666
+ window : (2,) array_like, optional
1667
+ Window, see `domain` for its use. The default value is [-1, 1].
1668
+
1669
+ .. versionadded:: 1.6.0
1670
+ symbol : str, optional
1671
+ Symbol used to represent the independent variable in string
1672
+ representations of the polynomial expression, e.g. for printing.
1673
+ The symbol must be a valid Python identifier. Default value is 'x'.
1674
+
1675
+ .. versionadded:: 1.24
1676
+
1677
+ """
1678
+ # Virtual Functions
1679
+ _add = staticmethod(hermeadd)
1680
+ _sub = staticmethod(hermesub)
1681
+ _mul = staticmethod(hermemul)
1682
+ _div = staticmethod(hermediv)
1683
+ _pow = staticmethod(hermepow)
1684
+ _val = staticmethod(hermeval)
1685
+ _int = staticmethod(hermeint)
1686
+ _der = staticmethod(hermeder)
1687
+ _fit = staticmethod(hermefit)
1688
+ _line = staticmethod(hermeline)
1689
+ _roots = staticmethod(hermeroots)
1690
+ _fromroots = staticmethod(hermefromroots)
1691
+
1692
+ # Virtual properties
1693
+ domain = np.array(hermedomain)
1694
+ window = np.array(hermedomain)
1695
+ basis_name = 'He'
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/laguerre.pyi ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from numpy import ndarray, dtype, int_
4
+ from numpy.polynomial._polybase import ABCPolyBase
5
+ from numpy.polynomial.polyutils import trimcoef
6
+
7
+ __all__: list[str]
8
+
9
+ lagtrim = trimcoef
10
+
11
+ def poly2lag(pol): ...
12
+ def lag2poly(c): ...
13
+
14
+ lagdomain: ndarray[Any, dtype[int_]]
15
+ lagzero: ndarray[Any, dtype[int_]]
16
+ lagone: ndarray[Any, dtype[int_]]
17
+ lagx: ndarray[Any, dtype[int_]]
18
+
19
+ def lagline(off, scl): ...
20
+ def lagfromroots(roots): ...
21
+ def lagadd(c1, c2): ...
22
+ def lagsub(c1, c2): ...
23
+ def lagmulx(c): ...
24
+ def lagmul(c1, c2): ...
25
+ def lagdiv(c1, c2): ...
26
+ def lagpow(c, pow, maxpower=...): ...
27
+ def lagder(c, m=..., scl=..., axis=...): ...
28
+ def lagint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...
29
+ def lagval(x, c, tensor=...): ...
30
+ def lagval2d(x, y, c): ...
31
+ def laggrid2d(x, y, c): ...
32
+ def lagval3d(x, y, z, c): ...
33
+ def laggrid3d(x, y, z, c): ...
34
+ def lagvander(x, deg): ...
35
+ def lagvander2d(x, y, deg): ...
36
+ def lagvander3d(x, y, z, deg): ...
37
+ def lagfit(x, y, deg, rcond=..., full=..., w=...): ...
38
+ def lagcompanion(c): ...
39
+ def lagroots(c): ...
40
+ def laggauss(deg): ...
41
+ def lagweight(x): ...
42
+
43
+ class Laguerre(ABCPolyBase):
44
+ domain: Any
45
+ window: Any
46
+ basis_name: Any
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/legendre.py ADDED
@@ -0,0 +1,1664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ==================================================
3
+ Legendre Series (:mod:`numpy.polynomial.legendre`)
4
+ ==================================================
5
+
6
+ This module provides a number of objects (mostly functions) useful for
7
+ dealing with Legendre series, including a `Legendre` class that
8
+ encapsulates the usual arithmetic operations. (General information
9
+ on how this module represents and works with such polynomials is in the
10
+ docstring for its "parent" sub-package, `numpy.polynomial`).
11
+
12
+ Classes
13
+ -------
14
+ .. autosummary::
15
+ :toctree: generated/
16
+
17
+ Legendre
18
+
19
+ Constants
20
+ ---------
21
+
22
+ .. autosummary::
23
+ :toctree: generated/
24
+
25
+ legdomain
26
+ legzero
27
+ legone
28
+ legx
29
+
30
+ Arithmetic
31
+ ----------
32
+
33
+ .. autosummary::
34
+ :toctree: generated/
35
+
36
+ legadd
37
+ legsub
38
+ legmulx
39
+ legmul
40
+ legdiv
41
+ legpow
42
+ legval
43
+ legval2d
44
+ legval3d
45
+ leggrid2d
46
+ leggrid3d
47
+
48
+ Calculus
49
+ --------
50
+
51
+ .. autosummary::
52
+ :toctree: generated/
53
+
54
+ legder
55
+ legint
56
+
57
+ Misc Functions
58
+ --------------
59
+
60
+ .. autosummary::
61
+ :toctree: generated/
62
+
63
+ legfromroots
64
+ legroots
65
+ legvander
66
+ legvander2d
67
+ legvander3d
68
+ leggauss
69
+ legweight
70
+ legcompanion
71
+ legfit
72
+ legtrim
73
+ legline
74
+ leg2poly
75
+ poly2leg
76
+
77
+ See also
78
+ --------
79
+ numpy.polynomial
80
+
81
+ """
82
+ import numpy as np
83
+ import numpy.linalg as la
84
+ from numpy.core.multiarray import normalize_axis_index
85
+
86
+ from . import polyutils as pu
87
+ from ._polybase import ABCPolyBase
88
+
89
+ __all__ = [
90
+ 'legzero', 'legone', 'legx', 'legdomain', 'legline', 'legadd',
91
+ 'legsub', 'legmulx', 'legmul', 'legdiv', 'legpow', 'legval', 'legder',
92
+ 'legint', 'leg2poly', 'poly2leg', 'legfromroots', 'legvander',
93
+ 'legfit', 'legtrim', 'legroots', 'Legendre', 'legval2d', 'legval3d',
94
+ 'leggrid2d', 'leggrid3d', 'legvander2d', 'legvander3d', 'legcompanion',
95
+ 'leggauss', 'legweight']
96
+
97
+ legtrim = pu.trimcoef
98
+
99
+
100
+ def poly2leg(pol):
101
+ """
102
+ Convert a polynomial to a Legendre series.
103
+
104
+ Convert an array representing the coefficients of a polynomial (relative
105
+ to the "standard" basis) ordered from lowest degree to highest, to an
106
+ array of the coefficients of the equivalent Legendre series, ordered
107
+ from lowest to highest degree.
108
+
109
+ Parameters
110
+ ----------
111
+ pol : array_like
112
+ 1-D array containing the polynomial coefficients
113
+
114
+ Returns
115
+ -------
116
+ c : ndarray
117
+ 1-D array containing the coefficients of the equivalent Legendre
118
+ series.
119
+
120
+ See Also
121
+ --------
122
+ leg2poly
123
+
124
+ Notes
125
+ -----
126
+ The easy way to do conversions between polynomial basis sets
127
+ is to use the convert method of a class instance.
128
+
129
+ Examples
130
+ --------
131
+ >>> from numpy import polynomial as P
132
+ >>> p = P.Polynomial(np.arange(4))
133
+ >>> p
134
+ Polynomial([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
135
+ >>> c = P.Legendre(P.legendre.poly2leg(p.coef))
136
+ >>> c
137
+ Legendre([ 1. , 3.25, 1. , 0.75], domain=[-1, 1], window=[-1, 1]) # may vary
138
+
139
+ """
140
+ [pol] = pu.as_series([pol])
141
+ deg = len(pol) - 1
142
+ res = 0
143
+ for i in range(deg, -1, -1):
144
+ res = legadd(legmulx(res), pol[i])
145
+ return res
146
+
147
+
148
+ def leg2poly(c):
149
+ """
150
+ Convert a Legendre series to a polynomial.
151
+
152
+ Convert an array representing the coefficients of a Legendre series,
153
+ ordered from lowest degree to highest, to an array of the coefficients
154
+ of the equivalent polynomial (relative to the "standard" basis) ordered
155
+ from lowest to highest degree.
156
+
157
+ Parameters
158
+ ----------
159
+ c : array_like
160
+ 1-D array containing the Legendre series coefficients, ordered
161
+ from lowest order term to highest.
162
+
163
+ Returns
164
+ -------
165
+ pol : ndarray
166
+ 1-D array containing the coefficients of the equivalent polynomial
167
+ (relative to the "standard" basis) ordered from lowest order term
168
+ to highest.
169
+
170
+ See Also
171
+ --------
172
+ poly2leg
173
+
174
+ Notes
175
+ -----
176
+ The easy way to do conversions between polynomial basis sets
177
+ is to use the convert method of a class instance.
178
+
179
+ Examples
180
+ --------
181
+ >>> from numpy import polynomial as P
182
+ >>> c = P.Legendre(range(4))
183
+ >>> c
184
+ Legendre([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
185
+ >>> p = c.convert(kind=P.Polynomial)
186
+ >>> p
187
+ Polynomial([-1. , -3.5, 3. , 7.5], domain=[-1., 1.], window=[-1., 1.])
188
+ >>> P.legendre.leg2poly(range(4))
189
+ array([-1. , -3.5, 3. , 7.5])
190
+
191
+
192
+ """
193
+ from .polynomial import polyadd, polysub, polymulx
194
+
195
+ [c] = pu.as_series([c])
196
+ n = len(c)
197
+ if n < 3:
198
+ return c
199
+ else:
200
+ c0 = c[-2]
201
+ c1 = c[-1]
202
+ # i is the current degree of c1
203
+ for i in range(n - 1, 1, -1):
204
+ tmp = c0
205
+ c0 = polysub(c[i - 2], (c1*(i - 1))/i)
206
+ c1 = polyadd(tmp, (polymulx(c1)*(2*i - 1))/i)
207
+ return polyadd(c0, polymulx(c1))
208
+
209
+ #
210
+ # These are constant arrays are of integer type so as to be compatible
211
+ # with the widest range of other types, such as Decimal.
212
+ #
213
+
214
+ # Legendre
215
+ legdomain = np.array([-1, 1])
216
+
217
+ # Legendre coefficients representing zero.
218
+ legzero = np.array([0])
219
+
220
+ # Legendre coefficients representing one.
221
+ legone = np.array([1])
222
+
223
+ # Legendre coefficients representing the identity x.
224
+ legx = np.array([0, 1])
225
+
226
+
227
+ def legline(off, scl):
228
+ """
229
+ Legendre series whose graph is a straight line.
230
+
231
+
232
+
233
+ Parameters
234
+ ----------
235
+ off, scl : scalars
236
+ The specified line is given by ``off + scl*x``.
237
+
238
+ Returns
239
+ -------
240
+ y : ndarray
241
+ This module's representation of the Legendre series for
242
+ ``off + scl*x``.
243
+
244
+ See Also
245
+ --------
246
+ numpy.polynomial.polynomial.polyline
247
+ numpy.polynomial.chebyshev.chebline
248
+ numpy.polynomial.laguerre.lagline
249
+ numpy.polynomial.hermite.hermline
250
+ numpy.polynomial.hermite_e.hermeline
251
+
252
+ Examples
253
+ --------
254
+ >>> import numpy.polynomial.legendre as L
255
+ >>> L.legline(3,2)
256
+ array([3, 2])
257
+ >>> L.legval(-3, L.legline(3,2)) # should be -3
258
+ -3.0
259
+
260
+ """
261
+ if scl != 0:
262
+ return np.array([off, scl])
263
+ else:
264
+ return np.array([off])
265
+
266
+
267
+ def legfromroots(roots):
268
+ """
269
+ Generate a Legendre series with given roots.
270
+
271
+ The function returns the coefficients of the polynomial
272
+
273
+ .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
274
+
275
+ in Legendre form, where the `r_n` are the roots specified in `roots`.
276
+ If a zero has multiplicity n, then it must appear in `roots` n times.
277
+ For instance, if 2 is a root of multiplicity three and 3 is a root of
278
+ multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
279
+ roots can appear in any order.
280
+
281
+ If the returned coefficients are `c`, then
282
+
283
+ .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x)
284
+
285
+ The coefficient of the last term is not generally 1 for monic
286
+ polynomials in Legendre form.
287
+
288
+ Parameters
289
+ ----------
290
+ roots : array_like
291
+ Sequence containing the roots.
292
+
293
+ Returns
294
+ -------
295
+ out : ndarray
296
+ 1-D array of coefficients. If all roots are real then `out` is a
297
+ real array, if some of the roots are complex, then `out` is complex
298
+ even if all the coefficients in the result are real (see Examples
299
+ below).
300
+
301
+ See Also
302
+ --------
303
+ numpy.polynomial.polynomial.polyfromroots
304
+ numpy.polynomial.chebyshev.chebfromroots
305
+ numpy.polynomial.laguerre.lagfromroots
306
+ numpy.polynomial.hermite.hermfromroots
307
+ numpy.polynomial.hermite_e.hermefromroots
308
+
309
+ Examples
310
+ --------
311
+ >>> import numpy.polynomial.legendre as L
312
+ >>> L.legfromroots((-1,0,1)) # x^3 - x relative to the standard basis
313
+ array([ 0. , -0.4, 0. , 0.4])
314
+ >>> j = complex(0,1)
315
+ >>> L.legfromroots((-j,j)) # x^2 + 1 relative to the standard basis
316
+ array([ 1.33333333+0.j, 0.00000000+0.j, 0.66666667+0.j]) # may vary
317
+
318
+ """
319
+ return pu._fromroots(legline, legmul, roots)
320
+
321
+
322
+ def legadd(c1, c2):
323
+ """
324
+ Add one Legendre series to another.
325
+
326
+ Returns the sum of two Legendre series `c1` + `c2`. The arguments
327
+ are sequences of coefficients ordered from lowest order term to
328
+ highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
329
+
330
+ Parameters
331
+ ----------
332
+ c1, c2 : array_like
333
+ 1-D arrays of Legendre series coefficients ordered from low to
334
+ high.
335
+
336
+ Returns
337
+ -------
338
+ out : ndarray
339
+ Array representing the Legendre series of their sum.
340
+
341
+ See Also
342
+ --------
343
+ legsub, legmulx, legmul, legdiv, legpow
344
+
345
+ Notes
346
+ -----
347
+ Unlike multiplication, division, etc., the sum of two Legendre series
348
+ is a Legendre series (without having to "reproject" the result onto
349
+ the basis set) so addition, just like that of "standard" polynomials,
350
+ is simply "component-wise."
351
+
352
+ Examples
353
+ --------
354
+ >>> from numpy.polynomial import legendre as L
355
+ >>> c1 = (1,2,3)
356
+ >>> c2 = (3,2,1)
357
+ >>> L.legadd(c1,c2)
358
+ array([4., 4., 4.])
359
+
360
+ """
361
+ return pu._add(c1, c2)
362
+
363
+
364
+ def legsub(c1, c2):
365
+ """
366
+ Subtract one Legendre series from another.
367
+
368
+ Returns the difference of two Legendre series `c1` - `c2`. The
369
+ sequences of coefficients are from lowest order term to highest, i.e.,
370
+ [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
371
+
372
+ Parameters
373
+ ----------
374
+ c1, c2 : array_like
375
+ 1-D arrays of Legendre series coefficients ordered from low to
376
+ high.
377
+
378
+ Returns
379
+ -------
380
+ out : ndarray
381
+ Of Legendre series coefficients representing their difference.
382
+
383
+ See Also
384
+ --------
385
+ legadd, legmulx, legmul, legdiv, legpow
386
+
387
+ Notes
388
+ -----
389
+ Unlike multiplication, division, etc., the difference of two Legendre
390
+ series is a Legendre series (without having to "reproject" the result
391
+ onto the basis set) so subtraction, just like that of "standard"
392
+ polynomials, is simply "component-wise."
393
+
394
+ Examples
395
+ --------
396
+ >>> from numpy.polynomial import legendre as L
397
+ >>> c1 = (1,2,3)
398
+ >>> c2 = (3,2,1)
399
+ >>> L.legsub(c1,c2)
400
+ array([-2., 0., 2.])
401
+ >>> L.legsub(c2,c1) # -C.legsub(c1,c2)
402
+ array([ 2., 0., -2.])
403
+
404
+ """
405
+ return pu._sub(c1, c2)
406
+
407
+
408
+ def legmulx(c):
409
+ """Multiply a Legendre series by x.
410
+
411
+ Multiply the Legendre series `c` by x, where x is the independent
412
+ variable.
413
+
414
+
415
+ Parameters
416
+ ----------
417
+ c : array_like
418
+ 1-D array of Legendre series coefficients ordered from low to
419
+ high.
420
+
421
+ Returns
422
+ -------
423
+ out : ndarray
424
+ Array representing the result of the multiplication.
425
+
426
+ See Also
427
+ --------
428
+ legadd, legmul, legdiv, legpow
429
+
430
+ Notes
431
+ -----
432
+ The multiplication uses the recursion relationship for Legendre
433
+ polynomials in the form
434
+
435
+ .. math::
436
+
437
+ xP_i(x) = ((i + 1)*P_{i + 1}(x) + i*P_{i - 1}(x))/(2i + 1)
438
+
439
+ Examples
440
+ --------
441
+ >>> from numpy.polynomial import legendre as L
442
+ >>> L.legmulx([1,2,3])
443
+ array([ 0.66666667, 2.2, 1.33333333, 1.8]) # may vary
444
+
445
+ """
446
+ # c is a trimmed copy
447
+ [c] = pu.as_series([c])
448
+ # The zero series needs special treatment
449
+ if len(c) == 1 and c[0] == 0:
450
+ return c
451
+
452
+ prd = np.empty(len(c) + 1, dtype=c.dtype)
453
+ prd[0] = c[0]*0
454
+ prd[1] = c[0]
455
+ for i in range(1, len(c)):
456
+ j = i + 1
457
+ k = i - 1
458
+ s = i + j
459
+ prd[j] = (c[i]*j)/s
460
+ prd[k] += (c[i]*i)/s
461
+ return prd
462
+
463
+
464
+ def legmul(c1, c2):
465
+ """
466
+ Multiply one Legendre series by another.
467
+
468
+ Returns the product of two Legendre series `c1` * `c2`. The arguments
469
+ are sequences of coefficients, from lowest order "term" to highest,
470
+ e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
471
+
472
+ Parameters
473
+ ----------
474
+ c1, c2 : array_like
475
+ 1-D arrays of Legendre series coefficients ordered from low to
476
+ high.
477
+
478
+ Returns
479
+ -------
480
+ out : ndarray
481
+ Of Legendre series coefficients representing their product.
482
+
483
+ See Also
484
+ --------
485
+ legadd, legsub, legmulx, legdiv, legpow
486
+
487
+ Notes
488
+ -----
489
+ In general, the (polynomial) product of two C-series results in terms
490
+ that are not in the Legendre polynomial basis set. Thus, to express
491
+ the product as a Legendre series, it is necessary to "reproject" the
492
+ product onto said basis set, which may produce "unintuitive" (but
493
+ correct) results; see Examples section below.
494
+
495
+ Examples
496
+ --------
497
+ >>> from numpy.polynomial import legendre as L
498
+ >>> c1 = (1,2,3)
499
+ >>> c2 = (3,2)
500
+ >>> L.legmul(c1,c2) # multiplication requires "reprojection"
501
+ array([ 4.33333333, 10.4 , 11.66666667, 3.6 ]) # may vary
502
+
503
+ """
504
+ # s1, s2 are trimmed copies
505
+ [c1, c2] = pu.as_series([c1, c2])
506
+
507
+ if len(c1) > len(c2):
508
+ c = c2
509
+ xs = c1
510
+ else:
511
+ c = c1
512
+ xs = c2
513
+
514
+ if len(c) == 1:
515
+ c0 = c[0]*xs
516
+ c1 = 0
517
+ elif len(c) == 2:
518
+ c0 = c[0]*xs
519
+ c1 = c[1]*xs
520
+ else:
521
+ nd = len(c)
522
+ c0 = c[-2]*xs
523
+ c1 = c[-1]*xs
524
+ for i in range(3, len(c) + 1):
525
+ tmp = c0
526
+ nd = nd - 1
527
+ c0 = legsub(c[-i]*xs, (c1*(nd - 1))/nd)
528
+ c1 = legadd(tmp, (legmulx(c1)*(2*nd - 1))/nd)
529
+ return legadd(c0, legmulx(c1))
530
+
531
+
532
+ def legdiv(c1, c2):
533
+ """
534
+ Divide one Legendre series by another.
535
+
536
+ Returns the quotient-with-remainder of two Legendre series
537
+ `c1` / `c2`. The arguments are sequences of coefficients from lowest
538
+ order "term" to highest, e.g., [1,2,3] represents the series
539
+ ``P_0 + 2*P_1 + 3*P_2``.
540
+
541
+ Parameters
542
+ ----------
543
+ c1, c2 : array_like
544
+ 1-D arrays of Legendre series coefficients ordered from low to
545
+ high.
546
+
547
+ Returns
548
+ -------
549
+ quo, rem : ndarrays
550
+ Of Legendre series coefficients representing the quotient and
551
+ remainder.
552
+
553
+ See Also
554
+ --------
555
+ legadd, legsub, legmulx, legmul, legpow
556
+
557
+ Notes
558
+ -----
559
+ In general, the (polynomial) division of one Legendre series by another
560
+ results in quotient and remainder terms that are not in the Legendre
561
+ polynomial basis set. Thus, to express these results as a Legendre
562
+ series, it is necessary to "reproject" the results onto the Legendre
563
+ basis set, which may produce "unintuitive" (but correct) results; see
564
+ Examples section below.
565
+
566
+ Examples
567
+ --------
568
+ >>> from numpy.polynomial import legendre as L
569
+ >>> c1 = (1,2,3)
570
+ >>> c2 = (3,2,1)
571
+ >>> L.legdiv(c1,c2) # quotient "intuitive," remainder not
572
+ (array([3.]), array([-8., -4.]))
573
+ >>> c2 = (0,1,2,3)
574
+ >>> L.legdiv(c2,c1) # neither "intuitive"
575
+ (array([-0.07407407, 1.66666667]), array([-1.03703704, -2.51851852])) # may vary
576
+
577
+ """
578
+ return pu._div(legmul, c1, c2)
579
+
580
+
581
+ def legpow(c, pow, maxpower=16):
582
+ """Raise a Legendre series to a power.
583
+
584
+ Returns the Legendre series `c` raised to the power `pow`. The
585
+ argument `c` is a sequence of coefficients ordered from low to high.
586
+ i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``
587
+
588
+ Parameters
589
+ ----------
590
+ c : array_like
591
+ 1-D array of Legendre series coefficients ordered from low to
592
+ high.
593
+ pow : integer
594
+ Power to which the series will be raised
595
+ maxpower : integer, optional
596
+ Maximum power allowed. This is mainly to limit growth of the series
597
+ to unmanageable size. Default is 16
598
+
599
+ Returns
600
+ -------
601
+ coef : ndarray
602
+ Legendre series of power.
603
+
604
+ See Also
605
+ --------
606
+ legadd, legsub, legmulx, legmul, legdiv
607
+
608
+ """
609
+ return pu._pow(legmul, c, pow, maxpower)
610
+
611
+
612
+ def legder(c, m=1, scl=1, axis=0):
613
+ """
614
+ Differentiate a Legendre series.
615
+
616
+ Returns the Legendre series coefficients `c` differentiated `m` times
617
+ along `axis`. At each iteration the result is multiplied by `scl` (the
618
+ scaling factor is for use in a linear change of variable). The argument
619
+ `c` is an array of coefficients from low to high degree along each
620
+ axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``
621
+ while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +
622
+ 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is
623
+ ``y``.
624
+
625
+ Parameters
626
+ ----------
627
+ c : array_like
628
+ Array of Legendre series coefficients. If c is multidimensional the
629
+ different axis correspond to different variables with the degree in
630
+ each axis given by the corresponding index.
631
+ m : int, optional
632
+ Number of derivatives taken, must be non-negative. (Default: 1)
633
+ scl : scalar, optional
634
+ Each differentiation is multiplied by `scl`. The end result is
635
+ multiplication by ``scl**m``. This is for use in a linear change of
636
+ variable. (Default: 1)
637
+ axis : int, optional
638
+ Axis over which the derivative is taken. (Default: 0).
639
+
640
+ .. versionadded:: 1.7.0
641
+
642
+ Returns
643
+ -------
644
+ der : ndarray
645
+ Legendre series of the derivative.
646
+
647
+ See Also
648
+ --------
649
+ legint
650
+
651
+ Notes
652
+ -----
653
+ In general, the result of differentiating a Legendre series does not
654
+ resemble the same operation on a power series. Thus the result of this
655
+ function may be "unintuitive," albeit correct; see Examples section
656
+ below.
657
+
658
+ Examples
659
+ --------
660
+ >>> from numpy.polynomial import legendre as L
661
+ >>> c = (1,2,3,4)
662
+ >>> L.legder(c)
663
+ array([ 6., 9., 20.])
664
+ >>> L.legder(c, 3)
665
+ array([60.])
666
+ >>> L.legder(c, scl=-1)
667
+ array([ -6., -9., -20.])
668
+ >>> L.legder(c, 2,-1)
669
+ array([ 9., 60.])
670
+
671
+ """
672
+ c = np.array(c, ndmin=1, copy=True)
673
+ if c.dtype.char in '?bBhHiIlLqQpP':
674
+ c = c.astype(np.double)
675
+ cnt = pu._deprecate_as_int(m, "the order of derivation")
676
+ iaxis = pu._deprecate_as_int(axis, "the axis")
677
+ if cnt < 0:
678
+ raise ValueError("The order of derivation must be non-negative")
679
+ iaxis = normalize_axis_index(iaxis, c.ndim)
680
+
681
+ if cnt == 0:
682
+ return c
683
+
684
+ c = np.moveaxis(c, iaxis, 0)
685
+ n = len(c)
686
+ if cnt >= n:
687
+ c = c[:1]*0
688
+ else:
689
+ for i in range(cnt):
690
+ n = n - 1
691
+ c *= scl
692
+ der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
693
+ for j in range(n, 2, -1):
694
+ der[j - 1] = (2*j - 1)*c[j]
695
+ c[j - 2] += c[j]
696
+ if n > 1:
697
+ der[1] = 3*c[2]
698
+ der[0] = c[1]
699
+ c = der
700
+ c = np.moveaxis(c, 0, iaxis)
701
+ return c
702
+
703
+
704
+ def legint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
705
+ """
706
+ Integrate a Legendre series.
707
+
708
+ Returns the Legendre series coefficients `c` integrated `m` times from
709
+ `lbnd` along `axis`. At each iteration the resulting series is
710
+ **multiplied** by `scl` and an integration constant, `k`, is added.
711
+ The scaling factor is for use in a linear change of variable. ("Buyer
712
+ beware": note that, depending on what one is doing, one may want `scl`
713
+ to be the reciprocal of what one might expect; for more information,
714
+ see the Notes section below.) The argument `c` is an array of
715
+ coefficients from low to high degree along each axis, e.g., [1,2,3]
716
+ represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]]
717
+ represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) +
718
+ 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
719
+
720
+ Parameters
721
+ ----------
722
+ c : array_like
723
+ Array of Legendre series coefficients. If c is multidimensional the
724
+ different axis correspond to different variables with the degree in
725
+ each axis given by the corresponding index.
726
+ m : int, optional
727
+ Order of integration, must be positive. (Default: 1)
728
+ k : {[], list, scalar}, optional
729
+ Integration constant(s). The value of the first integral at
730
+ ``lbnd`` is the first value in the list, the value of the second
731
+ integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
732
+ default), all constants are set to zero. If ``m == 1``, a single
733
+ scalar can be given instead of a list.
734
+ lbnd : scalar, optional
735
+ The lower bound of the integral. (Default: 0)
736
+ scl : scalar, optional
737
+ Following each integration the result is *multiplied* by `scl`
738
+ before the integration constant is added. (Default: 1)
739
+ axis : int, optional
740
+ Axis over which the integral is taken. (Default: 0).
741
+
742
+ .. versionadded:: 1.7.0
743
+
744
+ Returns
745
+ -------
746
+ S : ndarray
747
+ Legendre series coefficient array of the integral.
748
+
749
+ Raises
750
+ ------
751
+ ValueError
752
+ If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
753
+ ``np.ndim(scl) != 0``.
754
+
755
+ See Also
756
+ --------
757
+ legder
758
+
759
+ Notes
760
+ -----
761
+ Note that the result of each integration is *multiplied* by `scl`.
762
+ Why is this important to note? Say one is making a linear change of
763
+ variable :math:`u = ax + b` in an integral relative to `x`. Then
764
+ :math:`dx = du/a`, so one will need to set `scl` equal to
765
+ :math:`1/a` - perhaps not what one would have first thought.
766
+
767
+ Also note that, in general, the result of integrating a C-series needs
768
+ to be "reprojected" onto the C-series basis set. Thus, typically,
769
+ the result of this function is "unintuitive," albeit correct; see
770
+ Examples section below.
771
+
772
+ Examples
773
+ --------
774
+ >>> from numpy.polynomial import legendre as L
775
+ >>> c = (1,2,3)
776
+ >>> L.legint(c)
777
+ array([ 0.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
778
+ >>> L.legint(c, 3)
779
+ array([ 1.66666667e-02, -1.78571429e-02, 4.76190476e-02, # may vary
780
+ -1.73472348e-18, 1.90476190e-02, 9.52380952e-03])
781
+ >>> L.legint(c, k=3)
782
+ array([ 3.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
783
+ >>> L.legint(c, lbnd=-2)
784
+ array([ 7.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
785
+ >>> L.legint(c, scl=2)
786
+ array([ 0.66666667, 0.8 , 1.33333333, 1.2 ]) # may vary
787
+
788
+ """
789
+ c = np.array(c, ndmin=1, copy=True)
790
+ if c.dtype.char in '?bBhHiIlLqQpP':
791
+ c = c.astype(np.double)
792
+ if not np.iterable(k):
793
+ k = [k]
794
+ cnt = pu._deprecate_as_int(m, "the order of integration")
795
+ iaxis = pu._deprecate_as_int(axis, "the axis")
796
+ if cnt < 0:
797
+ raise ValueError("The order of integration must be non-negative")
798
+ if len(k) > cnt:
799
+ raise ValueError("Too many integration constants")
800
+ if np.ndim(lbnd) != 0:
801
+ raise ValueError("lbnd must be a scalar.")
802
+ if np.ndim(scl) != 0:
803
+ raise ValueError("scl must be a scalar.")
804
+ iaxis = normalize_axis_index(iaxis, c.ndim)
805
+
806
+ if cnt == 0:
807
+ return c
808
+
809
+ c = np.moveaxis(c, iaxis, 0)
810
+ k = list(k) + [0]*(cnt - len(k))
811
+ for i in range(cnt):
812
+ n = len(c)
813
+ c *= scl
814
+ if n == 1 and np.all(c[0] == 0):
815
+ c[0] += k[i]
816
+ else:
817
+ tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
818
+ tmp[0] = c[0]*0
819
+ tmp[1] = c[0]
820
+ if n > 1:
821
+ tmp[2] = c[1]/3
822
+ for j in range(2, n):
823
+ t = c[j]/(2*j + 1)
824
+ tmp[j + 1] = t
825
+ tmp[j - 1] -= t
826
+ tmp[0] += k[i] - legval(lbnd, tmp)
827
+ c = tmp
828
+ c = np.moveaxis(c, 0, iaxis)
829
+ return c
830
+
831
+
832
+ def legval(x, c, tensor=True):
833
+ """
834
+ Evaluate a Legendre series at points x.
835
+
836
+ If `c` is of length `n + 1`, this function returns the value:
837
+
838
+ .. math:: p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x)
839
+
840
+ The parameter `x` is converted to an array only if it is a tuple or a
841
+ list, otherwise it is treated as a scalar. In either case, either `x`
842
+ or its elements must support multiplication and addition both with
843
+ themselves and with the elements of `c`.
844
+
845
+ If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
846
+ `c` is multidimensional, then the shape of the result depends on the
847
+ value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
848
+ x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
849
+ scalars have shape (,).
850
+
851
+ Trailing zeros in the coefficients will be used in the evaluation, so
852
+ they should be avoided if efficiency is a concern.
853
+
854
+ Parameters
855
+ ----------
856
+ x : array_like, compatible object
857
+ If `x` is a list or tuple, it is converted to an ndarray, otherwise
858
+ it is left unchanged and treated as a scalar. In either case, `x`
859
+ or its elements must support addition and multiplication with
860
+ themselves and with the elements of `c`.
861
+ c : array_like
862
+ Array of coefficients ordered so that the coefficients for terms of
863
+ degree n are contained in c[n]. If `c` is multidimensional the
864
+ remaining indices enumerate multiple polynomials. In the two
865
+ dimensional case the coefficients may be thought of as stored in
866
+ the columns of `c`.
867
+ tensor : boolean, optional
868
+ If True, the shape of the coefficient array is extended with ones
869
+ on the right, one for each dimension of `x`. Scalars have dimension 0
870
+ for this action. The result is that every column of coefficients in
871
+ `c` is evaluated for every element of `x`. If False, `x` is broadcast
872
+ over the columns of `c` for the evaluation. This keyword is useful
873
+ when `c` is multidimensional. The default value is True.
874
+
875
+ .. versionadded:: 1.7.0
876
+
877
+ Returns
878
+ -------
879
+ values : ndarray, algebra_like
880
+ The shape of the return value is described above.
881
+
882
+ See Also
883
+ --------
884
+ legval2d, leggrid2d, legval3d, leggrid3d
885
+
886
+ Notes
887
+ -----
888
+ The evaluation uses Clenshaw recursion, aka synthetic division.
889
+
890
+ """
891
+ c = np.array(c, ndmin=1, copy=False)
892
+ if c.dtype.char in '?bBhHiIlLqQpP':
893
+ c = c.astype(np.double)
894
+ if isinstance(x, (tuple, list)):
895
+ x = np.asarray(x)
896
+ if isinstance(x, np.ndarray) and tensor:
897
+ c = c.reshape(c.shape + (1,)*x.ndim)
898
+
899
+ if len(c) == 1:
900
+ c0 = c[0]
901
+ c1 = 0
902
+ elif len(c) == 2:
903
+ c0 = c[0]
904
+ c1 = c[1]
905
+ else:
906
+ nd = len(c)
907
+ c0 = c[-2]
908
+ c1 = c[-1]
909
+ for i in range(3, len(c) + 1):
910
+ tmp = c0
911
+ nd = nd - 1
912
+ c0 = c[-i] - (c1*(nd - 1))/nd
913
+ c1 = tmp + (c1*x*(2*nd - 1))/nd
914
+ return c0 + c1*x
915
+
916
+
917
+ def legval2d(x, y, c):
918
+ """
919
+ Evaluate a 2-D Legendre series at points (x, y).
920
+
921
+ This function returns the values:
922
+
923
+ .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * L_i(x) * L_j(y)
924
+
925
+ The parameters `x` and `y` are converted to arrays only if they are
926
+ tuples or a lists, otherwise they are treated as a scalars and they
927
+ must have the same shape after conversion. In either case, either `x`
928
+ and `y` or their elements must support multiplication and addition both
929
+ with themselves and with the elements of `c`.
930
+
931
+ If `c` is a 1-D array a one is implicitly appended to its shape to make
932
+ it 2-D. The shape of the result will be c.shape[2:] + x.shape.
933
+
934
+ Parameters
935
+ ----------
936
+ x, y : array_like, compatible objects
937
+ The two dimensional series is evaluated at the points `(x, y)`,
938
+ where `x` and `y` must have the same shape. If `x` or `y` is a list
939
+ or tuple, it is first converted to an ndarray, otherwise it is left
940
+ unchanged and if it isn't an ndarray it is treated as a scalar.
941
+ c : array_like
942
+ Array of coefficients ordered so that the coefficient of the term
943
+ of multi-degree i,j is contained in ``c[i,j]``. If `c` has
944
+ dimension greater than two the remaining indices enumerate multiple
945
+ sets of coefficients.
946
+
947
+ Returns
948
+ -------
949
+ values : ndarray, compatible object
950
+ The values of the two dimensional Legendre series at points formed
951
+ from pairs of corresponding values from `x` and `y`.
952
+
953
+ See Also
954
+ --------
955
+ legval, leggrid2d, legval3d, leggrid3d
956
+
957
+ Notes
958
+ -----
959
+
960
+ .. versionadded:: 1.7.0
961
+
962
+ """
963
+ return pu._valnd(legval, c, x, y)
964
+
965
+
966
+ def leggrid2d(x, y, c):
967
+ """
968
+ Evaluate a 2-D Legendre series on the Cartesian product of x and y.
969
+
970
+ This function returns the values:
971
+
972
+ .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * L_i(a) * L_j(b)
973
+
974
+ where the points `(a, b)` consist of all pairs formed by taking
975
+ `a` from `x` and `b` from `y`. The resulting points form a grid with
976
+ `x` in the first dimension and `y` in the second.
977
+
978
+ The parameters `x` and `y` are converted to arrays only if they are
979
+ tuples or a lists, otherwise they are treated as a scalars. In either
980
+ case, either `x` and `y` or their elements must support multiplication
981
+ and addition both with themselves and with the elements of `c`.
982
+
983
+ If `c` has fewer than two dimensions, ones are implicitly appended to
984
+ its shape to make it 2-D. The shape of the result will be c.shape[2:] +
985
+ x.shape + y.shape.
986
+
987
+ Parameters
988
+ ----------
989
+ x, y : array_like, compatible objects
990
+ The two dimensional series is evaluated at the points in the
991
+ Cartesian product of `x` and `y`. If `x` or `y` is a list or
992
+ tuple, it is first converted to an ndarray, otherwise it is left
993
+ unchanged and, if it isn't an ndarray, it is treated as a scalar.
994
+ c : array_like
995
+ Array of coefficients ordered so that the coefficient of the term of
996
+ multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
997
+ greater than two the remaining indices enumerate multiple sets of
998
+ coefficients.
999
+
1000
+ Returns
1001
+ -------
1002
+ values : ndarray, compatible object
1003
+ The values of the two dimensional Chebyshev series at points in the
1004
+ Cartesian product of `x` and `y`.
1005
+
1006
+ See Also
1007
+ --------
1008
+ legval, legval2d, legval3d, leggrid3d
1009
+
1010
+ Notes
1011
+ -----
1012
+
1013
+ .. versionadded:: 1.7.0
1014
+
1015
+ """
1016
+ return pu._gridnd(legval, c, x, y)
1017
+
1018
+
1019
+ def legval3d(x, y, z, c):
1020
+ """
1021
+ Evaluate a 3-D Legendre series at points (x, y, z).
1022
+
1023
+ This function returns the values:
1024
+
1025
+ .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z)
1026
+
1027
+ The parameters `x`, `y`, and `z` are converted to arrays only if
1028
+ they are tuples or a lists, otherwise they are treated as a scalars and
1029
+ they must have the same shape after conversion. In either case, either
1030
+ `x`, `y`, and `z` or their elements must support multiplication and
1031
+ addition both with themselves and with the elements of `c`.
1032
+
1033
+ If `c` has fewer than 3 dimensions, ones are implicitly appended to its
1034
+ shape to make it 3-D. The shape of the result will be c.shape[3:] +
1035
+ x.shape.
1036
+
1037
+ Parameters
1038
+ ----------
1039
+ x, y, z : array_like, compatible object
1040
+ The three dimensional series is evaluated at the points
1041
+ `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
1042
+ any of `x`, `y`, or `z` is a list or tuple, it is first converted
1043
+ to an ndarray, otherwise it is left unchanged and if it isn't an
1044
+ ndarray it is treated as a scalar.
1045
+ c : array_like
1046
+ Array of coefficients ordered so that the coefficient of the term of
1047
+ multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
1048
+ greater than 3 the remaining indices enumerate multiple sets of
1049
+ coefficients.
1050
+
1051
+ Returns
1052
+ -------
1053
+ values : ndarray, compatible object
1054
+ The values of the multidimensional polynomial on points formed with
1055
+ triples of corresponding values from `x`, `y`, and `z`.
1056
+
1057
+ See Also
1058
+ --------
1059
+ legval, legval2d, leggrid2d, leggrid3d
1060
+
1061
+ Notes
1062
+ -----
1063
+
1064
+ .. versionadded:: 1.7.0
1065
+
1066
+ """
1067
+ return pu._valnd(legval, c, x, y, z)
1068
+
1069
+
1070
+ def leggrid3d(x, y, z, c):
1071
+ """
1072
+ Evaluate a 3-D Legendre series on the Cartesian product of x, y, and z.
1073
+
1074
+ This function returns the values:
1075
+
1076
+ .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c)
1077
+
1078
+ where the points `(a, b, c)` consist of all triples formed by taking
1079
+ `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
1080
+ a grid with `x` in the first dimension, `y` in the second, and `z` in
1081
+ the third.
1082
+
1083
+ The parameters `x`, `y`, and `z` are converted to arrays only if they
1084
+ are tuples or a lists, otherwise they are treated as a scalars. In
1085
+ either case, either `x`, `y`, and `z` or their elements must support
1086
+ multiplication and addition both with themselves and with the elements
1087
+ of `c`.
1088
+
1089
+ If `c` has fewer than three dimensions, ones are implicitly appended to
1090
+ its shape to make it 3-D. The shape of the result will be c.shape[3:] +
1091
+ x.shape + y.shape + z.shape.
1092
+
1093
+ Parameters
1094
+ ----------
1095
+ x, y, z : array_like, compatible objects
1096
+ The three dimensional series is evaluated at the points in the
1097
+ Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
1098
+ list or tuple, it is first converted to an ndarray, otherwise it is
1099
+ left unchanged and, if it isn't an ndarray, it is treated as a
1100
+ scalar.
1101
+ c : array_like
1102
+ Array of coefficients ordered so that the coefficients for terms of
1103
+ degree i,j are contained in ``c[i,j]``. If `c` has dimension
1104
+ greater than two the remaining indices enumerate multiple sets of
1105
+ coefficients.
1106
+
1107
+ Returns
1108
+ -------
1109
+ values : ndarray, compatible object
1110
+ The values of the two dimensional polynomial at points in the Cartesian
1111
+ product of `x` and `y`.
1112
+
1113
+ See Also
1114
+ --------
1115
+ legval, legval2d, leggrid2d, legval3d
1116
+
1117
+ Notes
1118
+ -----
1119
+
1120
+ .. versionadded:: 1.7.0
1121
+
1122
+ """
1123
+ return pu._gridnd(legval, c, x, y, z)
1124
+
1125
+
1126
+ def legvander(x, deg):
1127
+ """Pseudo-Vandermonde matrix of given degree.
1128
+
1129
+ Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
1130
+ `x`. The pseudo-Vandermonde matrix is defined by
1131
+
1132
+ .. math:: V[..., i] = L_i(x)
1133
+
1134
+ where `0 <= i <= deg`. The leading indices of `V` index the elements of
1135
+ `x` and the last index is the degree of the Legendre polynomial.
1136
+
1137
+ If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
1138
+ array ``V = legvander(x, n)``, then ``np.dot(V, c)`` and
1139
+ ``legval(x, c)`` are the same up to roundoff. This equivalence is
1140
+ useful both for least squares fitting and for the evaluation of a large
1141
+ number of Legendre series of the same degree and sample points.
1142
+
1143
+ Parameters
1144
+ ----------
1145
+ x : array_like
1146
+ Array of points. The dtype is converted to float64 or complex128
1147
+ depending on whether any of the elements are complex. If `x` is
1148
+ scalar it is converted to a 1-D array.
1149
+ deg : int
1150
+ Degree of the resulting matrix.
1151
+
1152
+ Returns
1153
+ -------
1154
+ vander : ndarray
1155
+ The pseudo-Vandermonde matrix. The shape of the returned matrix is
1156
+ ``x.shape + (deg + 1,)``, where The last index is the degree of the
1157
+ corresponding Legendre polynomial. The dtype will be the same as
1158
+ the converted `x`.
1159
+
1160
+ """
1161
+ ideg = pu._deprecate_as_int(deg, "deg")
1162
+ if ideg < 0:
1163
+ raise ValueError("deg must be non-negative")
1164
+
1165
+ x = np.array(x, copy=False, ndmin=1) + 0.0
1166
+ dims = (ideg + 1,) + x.shape
1167
+ dtyp = x.dtype
1168
+ v = np.empty(dims, dtype=dtyp)
1169
+ # Use forward recursion to generate the entries. This is not as accurate
1170
+ # as reverse recursion in this application but it is more efficient.
1171
+ v[0] = x*0 + 1
1172
+ if ideg > 0:
1173
+ v[1] = x
1174
+ for i in range(2, ideg + 1):
1175
+ v[i] = (v[i-1]*x*(2*i - 1) - v[i-2]*(i - 1))/i
1176
+ return np.moveaxis(v, 0, -1)
1177
+
1178
+
1179
+ def legvander2d(x, y, deg):
1180
+ """Pseudo-Vandermonde matrix of given degrees.
1181
+
1182
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1183
+ points `(x, y)`. The pseudo-Vandermonde matrix is defined by
1184
+
1185
+ .. math:: V[..., (deg[1] + 1)*i + j] = L_i(x) * L_j(y),
1186
+
1187
+ where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
1188
+ `V` index the points `(x, y)` and the last index encodes the degrees of
1189
+ the Legendre polynomials.
1190
+
1191
+ If ``V = legvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
1192
+ correspond to the elements of a 2-D coefficient array `c` of shape
1193
+ (xdeg + 1, ydeg + 1) in the order
1194
+
1195
+ .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
1196
+
1197
+ and ``np.dot(V, c.flat)`` and ``legval2d(x, y, c)`` will be the same
1198
+ up to roundoff. This equivalence is useful both for least squares
1199
+ fitting and for the evaluation of a large number of 2-D Legendre
1200
+ series of the same degrees and sample points.
1201
+
1202
+ Parameters
1203
+ ----------
1204
+ x, y : array_like
1205
+ Arrays of point coordinates, all of the same shape. The dtypes
1206
+ will be converted to either float64 or complex128 depending on
1207
+ whether any of the elements are complex. Scalars are converted to
1208
+ 1-D arrays.
1209
+ deg : list of ints
1210
+ List of maximum degrees of the form [x_deg, y_deg].
1211
+
1212
+ Returns
1213
+ -------
1214
+ vander2d : ndarray
1215
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1216
+ :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same
1217
+ as the converted `x` and `y`.
1218
+
1219
+ See Also
1220
+ --------
1221
+ legvander, legvander3d, legval2d, legval3d
1222
+
1223
+ Notes
1224
+ -----
1225
+
1226
+ .. versionadded:: 1.7.0
1227
+
1228
+ """
1229
+ return pu._vander_nd_flat((legvander, legvander), (x, y), deg)
1230
+
1231
+
1232
+ def legvander3d(x, y, z, deg):
1233
+ """Pseudo-Vandermonde matrix of given degrees.
1234
+
1235
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1236
+ points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
1237
+ then The pseudo-Vandermonde matrix is defined by
1238
+
1239
+ .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = L_i(x)*L_j(y)*L_k(z),
1240
+
1241
+ where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
1242
+ indices of `V` index the points `(x, y, z)` and the last index encodes
1243
+ the degrees of the Legendre polynomials.
1244
+
1245
+ If ``V = legvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
1246
+ of `V` correspond to the elements of a 3-D coefficient array `c` of
1247
+ shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
1248
+
1249
+ .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
1250
+
1251
+ and ``np.dot(V, c.flat)`` and ``legval3d(x, y, z, c)`` will be the
1252
+ same up to roundoff. This equivalence is useful both for least squares
1253
+ fitting and for the evaluation of a large number of 3-D Legendre
1254
+ series of the same degrees and sample points.
1255
+
1256
+ Parameters
1257
+ ----------
1258
+ x, y, z : array_like
1259
+ Arrays of point coordinates, all of the same shape. The dtypes will
1260
+ be converted to either float64 or complex128 depending on whether
1261
+ any of the elements are complex. Scalars are converted to 1-D
1262
+ arrays.
1263
+ deg : list of ints
1264
+ List of maximum degrees of the form [x_deg, y_deg, z_deg].
1265
+
1266
+ Returns
1267
+ -------
1268
+ vander3d : ndarray
1269
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1270
+ :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will
1271
+ be the same as the converted `x`, `y`, and `z`.
1272
+
1273
+ See Also
1274
+ --------
1275
+ legvander, legvander3d, legval2d, legval3d
1276
+
1277
+ Notes
1278
+ -----
1279
+
1280
+ .. versionadded:: 1.7.0
1281
+
1282
+ """
1283
+ return pu._vander_nd_flat((legvander, legvander, legvander), (x, y, z), deg)
1284
+
1285
+
1286
+ def legfit(x, y, deg, rcond=None, full=False, w=None):
1287
+ """
1288
+ Least squares fit of Legendre series to data.
1289
+
1290
+ Return the coefficients of a Legendre series of degree `deg` that is the
1291
+ least squares fit to the data values `y` given at points `x`. If `y` is
1292
+ 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
1293
+ fits are done, one for each column of `y`, and the resulting
1294
+ coefficients are stored in the corresponding columns of a 2-D return.
1295
+ The fitted polynomial(s) are in the form
1296
+
1297
+ .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x),
1298
+
1299
+ where `n` is `deg`.
1300
+
1301
+ Parameters
1302
+ ----------
1303
+ x : array_like, shape (M,)
1304
+ x-coordinates of the M sample points ``(x[i], y[i])``.
1305
+ y : array_like, shape (M,) or (M, K)
1306
+ y-coordinates of the sample points. Several data sets of sample
1307
+ points sharing the same x-coordinates can be fitted at once by
1308
+ passing in a 2D-array that contains one dataset per column.
1309
+ deg : int or 1-D array_like
1310
+ Degree(s) of the fitting polynomials. If `deg` is a single integer
1311
+ all terms up to and including the `deg`'th term are included in the
1312
+ fit. For NumPy versions >= 1.11.0 a list of integers specifying the
1313
+ degrees of the terms to include may be used instead.
1314
+ rcond : float, optional
1315
+ Relative condition number of the fit. Singular values smaller than
1316
+ this relative to the largest singular value will be ignored. The
1317
+ default value is len(x)*eps, where eps is the relative precision of
1318
+ the float type, about 2e-16 in most cases.
1319
+ full : bool, optional
1320
+ Switch determining nature of return value. When it is False (the
1321
+ default) just the coefficients are returned, when True diagnostic
1322
+ information from the singular value decomposition is also returned.
1323
+ w : array_like, shape (`M`,), optional
1324
+ Weights. If not None, the weight ``w[i]`` applies to the unsquared
1325
+ residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
1326
+ chosen so that the errors of the products ``w[i]*y[i]`` all have the
1327
+ same variance. When using inverse-variance weighting, use
1328
+ ``w[i] = 1/sigma(y[i])``. The default value is None.
1329
+
1330
+ .. versionadded:: 1.5.0
1331
+
1332
+ Returns
1333
+ -------
1334
+ coef : ndarray, shape (M,) or (M, K)
1335
+ Legendre coefficients ordered from low to high. If `y` was
1336
+ 2-D, the coefficients for the data in column k of `y` are in
1337
+ column `k`. If `deg` is specified as a list, coefficients for
1338
+ terms not included in the fit are set equal to zero in the
1339
+ returned `coef`.
1340
+
1341
+ [residuals, rank, singular_values, rcond] : list
1342
+ These values are only returned if ``full == True``
1343
+
1344
+ - residuals -- sum of squared residuals of the least squares fit
1345
+ - rank -- the numerical rank of the scaled Vandermonde matrix
1346
+ - singular_values -- singular values of the scaled Vandermonde matrix
1347
+ - rcond -- value of `rcond`.
1348
+
1349
+ For more details, see `numpy.linalg.lstsq`.
1350
+
1351
+ Warns
1352
+ -----
1353
+ RankWarning
1354
+ The rank of the coefficient matrix in the least-squares fit is
1355
+ deficient. The warning is only raised if ``full == False``. The
1356
+ warnings can be turned off by
1357
+
1358
+ >>> import warnings
1359
+ >>> warnings.simplefilter('ignore', np.RankWarning)
1360
+
1361
+ See Also
1362
+ --------
1363
+ numpy.polynomial.polynomial.polyfit
1364
+ numpy.polynomial.chebyshev.chebfit
1365
+ numpy.polynomial.laguerre.lagfit
1366
+ numpy.polynomial.hermite.hermfit
1367
+ numpy.polynomial.hermite_e.hermefit
1368
+ legval : Evaluates a Legendre series.
1369
+ legvander : Vandermonde matrix of Legendre series.
1370
+ legweight : Legendre weight function (= 1).
1371
+ numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
1372
+ scipy.interpolate.UnivariateSpline : Computes spline fits.
1373
+
1374
+ Notes
1375
+ -----
1376
+ The solution is the coefficients of the Legendre series `p` that
1377
+ minimizes the sum of the weighted squared errors
1378
+
1379
+ .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
1380
+
1381
+ where :math:`w_j` are the weights. This problem is solved by setting up
1382
+ as the (typically) overdetermined matrix equation
1383
+
1384
+ .. math:: V(x) * c = w * y,
1385
+
1386
+ where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
1387
+ coefficients to be solved for, `w` are the weights, and `y` are the
1388
+ observed values. This equation is then solved using the singular value
1389
+ decomposition of `V`.
1390
+
1391
+ If some of the singular values of `V` are so small that they are
1392
+ neglected, then a `RankWarning` will be issued. This means that the
1393
+ coefficient values may be poorly determined. Using a lower order fit
1394
+ will usually get rid of the warning. The `rcond` parameter can also be
1395
+ set to a value smaller than its default, but the resulting fit may be
1396
+ spurious and have large contributions from roundoff error.
1397
+
1398
+ Fits using Legendre series are usually better conditioned than fits
1399
+ using power series, but much can depend on the distribution of the
1400
+ sample points and the smoothness of the data. If the quality of the fit
1401
+ is inadequate splines may be a good alternative.
1402
+
1403
+ References
1404
+ ----------
1405
+ .. [1] Wikipedia, "Curve fitting",
1406
+ https://en.wikipedia.org/wiki/Curve_fitting
1407
+
1408
+ Examples
1409
+ --------
1410
+
1411
+ """
1412
+ return pu._fit(legvander, x, y, deg, rcond, full, w)
1413
+
1414
+
1415
+ def legcompanion(c):
1416
+ """Return the scaled companion matrix of c.
1417
+
1418
+ The basis polynomials are scaled so that the companion matrix is
1419
+ symmetric when `c` is an Legendre basis polynomial. This provides
1420
+ better eigenvalue estimates than the unscaled case and for basis
1421
+ polynomials the eigenvalues are guaranteed to be real if
1422
+ `numpy.linalg.eigvalsh` is used to obtain them.
1423
+
1424
+ Parameters
1425
+ ----------
1426
+ c : array_like
1427
+ 1-D array of Legendre series coefficients ordered from low to high
1428
+ degree.
1429
+
1430
+ Returns
1431
+ -------
1432
+ mat : ndarray
1433
+ Scaled companion matrix of dimensions (deg, deg).
1434
+
1435
+ Notes
1436
+ -----
1437
+
1438
+ .. versionadded:: 1.7.0
1439
+
1440
+ """
1441
+ # c is a trimmed copy
1442
+ [c] = pu.as_series([c])
1443
+ if len(c) < 2:
1444
+ raise ValueError('Series must have maximum degree of at least 1.')
1445
+ if len(c) == 2:
1446
+ return np.array([[-c[0]/c[1]]])
1447
+
1448
+ n = len(c) - 1
1449
+ mat = np.zeros((n, n), dtype=c.dtype)
1450
+ scl = 1./np.sqrt(2*np.arange(n) + 1)
1451
+ top = mat.reshape(-1)[1::n+1]
1452
+ bot = mat.reshape(-1)[n::n+1]
1453
+ top[...] = np.arange(1, n)*scl[:n-1]*scl[1:n]
1454
+ bot[...] = top
1455
+ mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*(n/(2*n - 1))
1456
+ return mat
1457
+
1458
+
1459
+ def legroots(c):
1460
+ """
1461
+ Compute the roots of a Legendre series.
1462
+
1463
+ Return the roots (a.k.a. "zeros") of the polynomial
1464
+
1465
+ .. math:: p(x) = \\sum_i c[i] * L_i(x).
1466
+
1467
+ Parameters
1468
+ ----------
1469
+ c : 1-D array_like
1470
+ 1-D array of coefficients.
1471
+
1472
+ Returns
1473
+ -------
1474
+ out : ndarray
1475
+ Array of the roots of the series. If all the roots are real,
1476
+ then `out` is also real, otherwise it is complex.
1477
+
1478
+ See Also
1479
+ --------
1480
+ numpy.polynomial.polynomial.polyroots
1481
+ numpy.polynomial.chebyshev.chebroots
1482
+ numpy.polynomial.laguerre.lagroots
1483
+ numpy.polynomial.hermite.hermroots
1484
+ numpy.polynomial.hermite_e.hermeroots
1485
+
1486
+ Notes
1487
+ -----
1488
+ The root estimates are obtained as the eigenvalues of the companion
1489
+ matrix, Roots far from the origin of the complex plane may have large
1490
+ errors due to the numerical instability of the series for such values.
1491
+ Roots with multiplicity greater than 1 will also show larger errors as
1492
+ the value of the series near such points is relatively insensitive to
1493
+ errors in the roots. Isolated roots near the origin can be improved by
1494
+ a few iterations of Newton's method.
1495
+
1496
+ The Legendre series basis polynomials aren't powers of ``x`` so the
1497
+ results of this function may seem unintuitive.
1498
+
1499
+ Examples
1500
+ --------
1501
+ >>> import numpy.polynomial.legendre as leg
1502
+ >>> leg.legroots((1, 2, 3, 4)) # 4L_3 + 3L_2 + 2L_1 + 1L_0, all real roots
1503
+ array([-0.85099543, -0.11407192, 0.51506735]) # may vary
1504
+
1505
+ """
1506
+ # c is a trimmed copy
1507
+ [c] = pu.as_series([c])
1508
+ if len(c) < 2:
1509
+ return np.array([], dtype=c.dtype)
1510
+ if len(c) == 2:
1511
+ return np.array([-c[0]/c[1]])
1512
+
1513
+ # rotated companion matrix reduces error
1514
+ m = legcompanion(c)[::-1,::-1]
1515
+ r = la.eigvals(m)
1516
+ r.sort()
1517
+ return r
1518
+
1519
+
1520
+ def leggauss(deg):
1521
+ """
1522
+ Gauss-Legendre quadrature.
1523
+
1524
+ Computes the sample points and weights for Gauss-Legendre quadrature.
1525
+ These sample points and weights will correctly integrate polynomials of
1526
+ degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
1527
+ the weight function :math:`f(x) = 1`.
1528
+
1529
+ Parameters
1530
+ ----------
1531
+ deg : int
1532
+ Number of sample points and weights. It must be >= 1.
1533
+
1534
+ Returns
1535
+ -------
1536
+ x : ndarray
1537
+ 1-D ndarray containing the sample points.
1538
+ y : ndarray
1539
+ 1-D ndarray containing the weights.
1540
+
1541
+ Notes
1542
+ -----
1543
+
1544
+ .. versionadded:: 1.7.0
1545
+
1546
+ The results have only been tested up to degree 100, higher degrees may
1547
+ be problematic. The weights are determined by using the fact that
1548
+
1549
+ .. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k))
1550
+
1551
+ where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
1552
+ is the k'th root of :math:`L_n`, and then scaling the results to get
1553
+ the right value when integrating 1.
1554
+
1555
+ """
1556
+ ideg = pu._deprecate_as_int(deg, "deg")
1557
+ if ideg <= 0:
1558
+ raise ValueError("deg must be a positive integer")
1559
+
1560
+ # first approximation of roots. We use the fact that the companion
1561
+ # matrix is symmetric in this case in order to obtain better zeros.
1562
+ c = np.array([0]*deg + [1])
1563
+ m = legcompanion(c)
1564
+ x = la.eigvalsh(m)
1565
+
1566
+ # improve roots by one application of Newton
1567
+ dy = legval(x, c)
1568
+ df = legval(x, legder(c))
1569
+ x -= dy/df
1570
+
1571
+ # compute the weights. We scale the factor to avoid possible numerical
1572
+ # overflow.
1573
+ fm = legval(x, c[1:])
1574
+ fm /= np.abs(fm).max()
1575
+ df /= np.abs(df).max()
1576
+ w = 1/(fm * df)
1577
+
1578
+ # for Legendre we can also symmetrize
1579
+ w = (w + w[::-1])/2
1580
+ x = (x - x[::-1])/2
1581
+
1582
+ # scale w to get the right value
1583
+ w *= 2. / w.sum()
1584
+
1585
+ return x, w
1586
+
1587
+
1588
+ def legweight(x):
1589
+ """
1590
+ Weight function of the Legendre polynomials.
1591
+
1592
+ The weight function is :math:`1` and the interval of integration is
1593
+ :math:`[-1, 1]`. The Legendre polynomials are orthogonal, but not
1594
+ normalized, with respect to this weight function.
1595
+
1596
+ Parameters
1597
+ ----------
1598
+ x : array_like
1599
+ Values at which the weight function will be computed.
1600
+
1601
+ Returns
1602
+ -------
1603
+ w : ndarray
1604
+ The weight function at `x`.
1605
+
1606
+ Notes
1607
+ -----
1608
+
1609
+ .. versionadded:: 1.7.0
1610
+
1611
+ """
1612
+ w = x*0.0 + 1.0
1613
+ return w
1614
+
1615
+ #
1616
+ # Legendre series class
1617
+ #
1618
+
1619
+ class Legendre(ABCPolyBase):
1620
+ """A Legendre series class.
1621
+
1622
+ The Legendre class provides the standard Python numerical methods
1623
+ '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
1624
+ attributes and methods listed in the `ABCPolyBase` documentation.
1625
+
1626
+ Parameters
1627
+ ----------
1628
+ coef : array_like
1629
+ Legendre coefficients in order of increasing degree, i.e.,
1630
+ ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``.
1631
+ domain : (2,) array_like, optional
1632
+ Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
1633
+ to the interval ``[window[0], window[1]]`` by shifting and scaling.
1634
+ The default value is [-1, 1].
1635
+ window : (2,) array_like, optional
1636
+ Window, see `domain` for its use. The default value is [-1, 1].
1637
+
1638
+ .. versionadded:: 1.6.0
1639
+ symbol : str, optional
1640
+ Symbol used to represent the independent variable in string
1641
+ representations of the polynomial expression, e.g. for printing.
1642
+ The symbol must be a valid Python identifier. Default value is 'x'.
1643
+
1644
+ .. versionadded:: 1.24
1645
+
1646
+ """
1647
+ # Virtual Functions
1648
+ _add = staticmethod(legadd)
1649
+ _sub = staticmethod(legsub)
1650
+ _mul = staticmethod(legmul)
1651
+ _div = staticmethod(legdiv)
1652
+ _pow = staticmethod(legpow)
1653
+ _val = staticmethod(legval)
1654
+ _int = staticmethod(legint)
1655
+ _der = staticmethod(legder)
1656
+ _fit = staticmethod(legfit)
1657
+ _line = staticmethod(legline)
1658
+ _roots = staticmethod(legroots)
1659
+ _fromroots = staticmethod(legfromroots)
1660
+
1661
+ # Virtual properties
1662
+ domain = np.array(legdomain)
1663
+ window = np.array(legdomain)
1664
+ basis_name = 'P'
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/polynomial.py ADDED
@@ -0,0 +1,1542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =================================================
3
+ Power Series (:mod:`numpy.polynomial.polynomial`)
4
+ =================================================
5
+
6
+ This module provides a number of objects (mostly functions) useful for
7
+ dealing with polynomials, including a `Polynomial` class that
8
+ encapsulates the usual arithmetic operations. (General information
9
+ on how this module represents and works with polynomial objects is in
10
+ the docstring for its "parent" sub-package, `numpy.polynomial`).
11
+
12
+ Classes
13
+ -------
14
+ .. autosummary::
15
+ :toctree: generated/
16
+
17
+ Polynomial
18
+
19
+ Constants
20
+ ---------
21
+ .. autosummary::
22
+ :toctree: generated/
23
+
24
+ polydomain
25
+ polyzero
26
+ polyone
27
+ polyx
28
+
29
+ Arithmetic
30
+ ----------
31
+ .. autosummary::
32
+ :toctree: generated/
33
+
34
+ polyadd
35
+ polysub
36
+ polymulx
37
+ polymul
38
+ polydiv
39
+ polypow
40
+ polyval
41
+ polyval2d
42
+ polyval3d
43
+ polygrid2d
44
+ polygrid3d
45
+
46
+ Calculus
47
+ --------
48
+ .. autosummary::
49
+ :toctree: generated/
50
+
51
+ polyder
52
+ polyint
53
+
54
+ Misc Functions
55
+ --------------
56
+ .. autosummary::
57
+ :toctree: generated/
58
+
59
+ polyfromroots
60
+ polyroots
61
+ polyvalfromroots
62
+ polyvander
63
+ polyvander2d
64
+ polyvander3d
65
+ polycompanion
66
+ polyfit
67
+ polytrim
68
+ polyline
69
+
70
+ See Also
71
+ --------
72
+ `numpy.polynomial`
73
+
74
+ """
75
+ __all__ = [
76
+ 'polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyadd',
77
+ 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow', 'polyval',
78
+ 'polyvalfromroots', 'polyder', 'polyint', 'polyfromroots', 'polyvander',
79
+ 'polyfit', 'polytrim', 'polyroots', 'Polynomial', 'polyval2d', 'polyval3d',
80
+ 'polygrid2d', 'polygrid3d', 'polyvander2d', 'polyvander3d']
81
+
82
+ import numpy as np
83
+ import numpy.linalg as la
84
+ from numpy.core.multiarray import normalize_axis_index
85
+
86
+ from . import polyutils as pu
87
+ from ._polybase import ABCPolyBase
88
+
89
+ polytrim = pu.trimcoef
90
+
91
+ #
92
+ # These are constant arrays are of integer type so as to be compatible
93
+ # with the widest range of other types, such as Decimal.
94
+ #
95
+
96
+ # Polynomial default domain.
97
+ polydomain = np.array([-1, 1])
98
+
99
+ # Polynomial coefficients representing zero.
100
+ polyzero = np.array([0])
101
+
102
+ # Polynomial coefficients representing one.
103
+ polyone = np.array([1])
104
+
105
+ # Polynomial coefficients representing the identity x.
106
+ polyx = np.array([0, 1])
107
+
108
+ #
109
+ # Polynomial series functions
110
+ #
111
+
112
+
113
+ def polyline(off, scl):
114
+ """
115
+ Returns an array representing a linear polynomial.
116
+
117
+ Parameters
118
+ ----------
119
+ off, scl : scalars
120
+ The "y-intercept" and "slope" of the line, respectively.
121
+
122
+ Returns
123
+ -------
124
+ y : ndarray
125
+ This module's representation of the linear polynomial ``off +
126
+ scl*x``.
127
+
128
+ See Also
129
+ --------
130
+ numpy.polynomial.chebyshev.chebline
131
+ numpy.polynomial.legendre.legline
132
+ numpy.polynomial.laguerre.lagline
133
+ numpy.polynomial.hermite.hermline
134
+ numpy.polynomial.hermite_e.hermeline
135
+
136
+ Examples
137
+ --------
138
+ >>> from numpy.polynomial import polynomial as P
139
+ >>> P.polyline(1,-1)
140
+ array([ 1, -1])
141
+ >>> P.polyval(1, P.polyline(1,-1)) # should be 0
142
+ 0.0
143
+
144
+ """
145
+ if scl != 0:
146
+ return np.array([off, scl])
147
+ else:
148
+ return np.array([off])
149
+
150
+
151
+ def polyfromroots(roots):
152
+ """
153
+ Generate a monic polynomial with given roots.
154
+
155
+ Return the coefficients of the polynomial
156
+
157
+ .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
158
+
159
+ where the ``r_n`` are the roots specified in `roots`. If a zero has
160
+ multiplicity n, then it must appear in `roots` n times. For instance,
161
+ if 2 is a root of multiplicity three and 3 is a root of multiplicity 2,
162
+ then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear
163
+ in any order.
164
+
165
+ If the returned coefficients are `c`, then
166
+
167
+ .. math:: p(x) = c_0 + c_1 * x + ... + x^n
168
+
169
+ The coefficient of the last term is 1 for monic polynomials in this
170
+ form.
171
+
172
+ Parameters
173
+ ----------
174
+ roots : array_like
175
+ Sequence containing the roots.
176
+
177
+ Returns
178
+ -------
179
+ out : ndarray
180
+ 1-D array of the polynomial's coefficients If all the roots are
181
+ real, then `out` is also real, otherwise it is complex. (see
182
+ Examples below).
183
+
184
+ See Also
185
+ --------
186
+ numpy.polynomial.chebyshev.chebfromroots
187
+ numpy.polynomial.legendre.legfromroots
188
+ numpy.polynomial.laguerre.lagfromroots
189
+ numpy.polynomial.hermite.hermfromroots
190
+ numpy.polynomial.hermite_e.hermefromroots
191
+
192
+ Notes
193
+ -----
194
+ The coefficients are determined by multiplying together linear factors
195
+ of the form ``(x - r_i)``, i.e.
196
+
197
+ .. math:: p(x) = (x - r_0) (x - r_1) ... (x - r_n)
198
+
199
+ where ``n == len(roots) - 1``; note that this implies that ``1`` is always
200
+ returned for :math:`a_n`.
201
+
202
+ Examples
203
+ --------
204
+ >>> from numpy.polynomial import polynomial as P
205
+ >>> P.polyfromroots((-1,0,1)) # x(x - 1)(x + 1) = x^3 - x
206
+ array([ 0., -1., 0., 1.])
207
+ >>> j = complex(0,1)
208
+ >>> P.polyfromroots((-j,j)) # complex returned, though values are real
209
+ array([1.+0.j, 0.+0.j, 1.+0.j])
210
+
211
+ """
212
+ return pu._fromroots(polyline, polymul, roots)
213
+
214
+
215
+ def polyadd(c1, c2):
216
+ """
217
+ Add one polynomial to another.
218
+
219
+ Returns the sum of two polynomials `c1` + `c2`. The arguments are
220
+ sequences of coefficients from lowest order term to highest, i.e.,
221
+ [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.
222
+
223
+ Parameters
224
+ ----------
225
+ c1, c2 : array_like
226
+ 1-D arrays of polynomial coefficients ordered from low to high.
227
+
228
+ Returns
229
+ -------
230
+ out : ndarray
231
+ The coefficient array representing their sum.
232
+
233
+ See Also
234
+ --------
235
+ polysub, polymulx, polymul, polydiv, polypow
236
+
237
+ Examples
238
+ --------
239
+ >>> from numpy.polynomial import polynomial as P
240
+ >>> c1 = (1,2,3)
241
+ >>> c2 = (3,2,1)
242
+ >>> sum = P.polyadd(c1,c2); sum
243
+ array([4., 4., 4.])
244
+ >>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2)
245
+ 28.0
246
+
247
+ """
248
+ return pu._add(c1, c2)
249
+
250
+
251
+ def polysub(c1, c2):
252
+ """
253
+ Subtract one polynomial from another.
254
+
255
+ Returns the difference of two polynomials `c1` - `c2`. The arguments
256
+ are sequences of coefficients from lowest order term to highest, i.e.,
257
+ [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.
258
+
259
+ Parameters
260
+ ----------
261
+ c1, c2 : array_like
262
+ 1-D arrays of polynomial coefficients ordered from low to
263
+ high.
264
+
265
+ Returns
266
+ -------
267
+ out : ndarray
268
+ Of coefficients representing their difference.
269
+
270
+ See Also
271
+ --------
272
+ polyadd, polymulx, polymul, polydiv, polypow
273
+
274
+ Examples
275
+ --------
276
+ >>> from numpy.polynomial import polynomial as P
277
+ >>> c1 = (1,2,3)
278
+ >>> c2 = (3,2,1)
279
+ >>> P.polysub(c1,c2)
280
+ array([-2., 0., 2.])
281
+ >>> P.polysub(c2,c1) # -P.polysub(c1,c2)
282
+ array([ 2., 0., -2.])
283
+
284
+ """
285
+ return pu._sub(c1, c2)
286
+
287
+
288
+ def polymulx(c):
289
+ """Multiply a polynomial by x.
290
+
291
+ Multiply the polynomial `c` by x, where x is the independent
292
+ variable.
293
+
294
+
295
+ Parameters
296
+ ----------
297
+ c : array_like
298
+ 1-D array of polynomial coefficients ordered from low to
299
+ high.
300
+
301
+ Returns
302
+ -------
303
+ out : ndarray
304
+ Array representing the result of the multiplication.
305
+
306
+ See Also
307
+ --------
308
+ polyadd, polysub, polymul, polydiv, polypow
309
+
310
+ Notes
311
+ -----
312
+
313
+ .. versionadded:: 1.5.0
314
+
315
+ """
316
+ # c is a trimmed copy
317
+ [c] = pu.as_series([c])
318
+ # The zero series needs special treatment
319
+ if len(c) == 1 and c[0] == 0:
320
+ return c
321
+
322
+ prd = np.empty(len(c) + 1, dtype=c.dtype)
323
+ prd[0] = c[0]*0
324
+ prd[1:] = c
325
+ return prd
326
+
327
+
328
+ def polymul(c1, c2):
329
+ """
330
+ Multiply one polynomial by another.
331
+
332
+ Returns the product of two polynomials `c1` * `c2`. The arguments are
333
+ sequences of coefficients, from lowest order term to highest, e.g.,
334
+ [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2.``
335
+
336
+ Parameters
337
+ ----------
338
+ c1, c2 : array_like
339
+ 1-D arrays of coefficients representing a polynomial, relative to the
340
+ "standard" basis, and ordered from lowest order term to highest.
341
+
342
+ Returns
343
+ -------
344
+ out : ndarray
345
+ Of the coefficients of their product.
346
+
347
+ See Also
348
+ --------
349
+ polyadd, polysub, polymulx, polydiv, polypow
350
+
351
+ Examples
352
+ --------
353
+ >>> from numpy.polynomial import polynomial as P
354
+ >>> c1 = (1,2,3)
355
+ >>> c2 = (3,2,1)
356
+ >>> P.polymul(c1,c2)
357
+ array([ 3., 8., 14., 8., 3.])
358
+
359
+ """
360
+ # c1, c2 are trimmed copies
361
+ [c1, c2] = pu.as_series([c1, c2])
362
+ ret = np.convolve(c1, c2)
363
+ return pu.trimseq(ret)
364
+
365
+
366
+ def polydiv(c1, c2):
367
+ """
368
+ Divide one polynomial by another.
369
+
370
+ Returns the quotient-with-remainder of two polynomials `c1` / `c2`.
371
+ The arguments are sequences of coefficients, from lowest order term
372
+ to highest, e.g., [1,2,3] represents ``1 + 2*x + 3*x**2``.
373
+
374
+ Parameters
375
+ ----------
376
+ c1, c2 : array_like
377
+ 1-D arrays of polynomial coefficients ordered from low to high.
378
+
379
+ Returns
380
+ -------
381
+ [quo, rem] : ndarrays
382
+ Of coefficient series representing the quotient and remainder.
383
+
384
+ See Also
385
+ --------
386
+ polyadd, polysub, polymulx, polymul, polypow
387
+
388
+ Examples
389
+ --------
390
+ >>> from numpy.polynomial import polynomial as P
391
+ >>> c1 = (1,2,3)
392
+ >>> c2 = (3,2,1)
393
+ >>> P.polydiv(c1,c2)
394
+ (array([3.]), array([-8., -4.]))
395
+ >>> P.polydiv(c2,c1)
396
+ (array([ 0.33333333]), array([ 2.66666667, 1.33333333])) # may vary
397
+
398
+ """
399
+ # c1, c2 are trimmed copies
400
+ [c1, c2] = pu.as_series([c1, c2])
401
+ if c2[-1] == 0:
402
+ raise ZeroDivisionError()
403
+
404
+ # note: this is more efficient than `pu._div(polymul, c1, c2)`
405
+ lc1 = len(c1)
406
+ lc2 = len(c2)
407
+ if lc1 < lc2:
408
+ return c1[:1]*0, c1
409
+ elif lc2 == 1:
410
+ return c1/c2[-1], c1[:1]*0
411
+ else:
412
+ dlen = lc1 - lc2
413
+ scl = c2[-1]
414
+ c2 = c2[:-1]/scl
415
+ i = dlen
416
+ j = lc1 - 1
417
+ while i >= 0:
418
+ c1[i:j] -= c2*c1[j]
419
+ i -= 1
420
+ j -= 1
421
+ return c1[j+1:]/scl, pu.trimseq(c1[:j+1])
422
+
423
+
424
+ def polypow(c, pow, maxpower=None):
425
+ """Raise a polynomial to a power.
426
+
427
+ Returns the polynomial `c` raised to the power `pow`. The argument
428
+ `c` is a sequence of coefficients ordered from low to high. i.e.,
429
+ [1,2,3] is the series ``1 + 2*x + 3*x**2.``
430
+
431
+ Parameters
432
+ ----------
433
+ c : array_like
434
+ 1-D array of array of series coefficients ordered from low to
435
+ high degree.
436
+ pow : integer
437
+ Power to which the series will be raised
438
+ maxpower : integer, optional
439
+ Maximum power allowed. This is mainly to limit growth of the series
440
+ to unmanageable size. Default is 16
441
+
442
+ Returns
443
+ -------
444
+ coef : ndarray
445
+ Power series of power.
446
+
447
+ See Also
448
+ --------
449
+ polyadd, polysub, polymulx, polymul, polydiv
450
+
451
+ Examples
452
+ --------
453
+ >>> from numpy.polynomial import polynomial as P
454
+ >>> P.polypow([1,2,3], 2)
455
+ array([ 1., 4., 10., 12., 9.])
456
+
457
+ """
458
+ # note: this is more efficient than `pu._pow(polymul, c1, c2)`, as it
459
+ # avoids calling `as_series` repeatedly
460
+ return pu._pow(np.convolve, c, pow, maxpower)
461
+
462
+
463
+ def polyder(c, m=1, scl=1, axis=0):
464
+ """
465
+ Differentiate a polynomial.
466
+
467
+ Returns the polynomial coefficients `c` differentiated `m` times along
468
+ `axis`. At each iteration the result is multiplied by `scl` (the
469
+ scaling factor is for use in a linear change of variable). The
470
+ argument `c` is an array of coefficients from low to high degree along
471
+ each axis, e.g., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``
472
+ while [[1,2],[1,2]] represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is
473
+ ``x`` and axis=1 is ``y``.
474
+
475
+ Parameters
476
+ ----------
477
+ c : array_like
478
+ Array of polynomial coefficients. If c is multidimensional the
479
+ different axis correspond to different variables with the degree
480
+ in each axis given by the corresponding index.
481
+ m : int, optional
482
+ Number of derivatives taken, must be non-negative. (Default: 1)
483
+ scl : scalar, optional
484
+ Each differentiation is multiplied by `scl`. The end result is
485
+ multiplication by ``scl**m``. This is for use in a linear change
486
+ of variable. (Default: 1)
487
+ axis : int, optional
488
+ Axis over which the derivative is taken. (Default: 0).
489
+
490
+ .. versionadded:: 1.7.0
491
+
492
+ Returns
493
+ -------
494
+ der : ndarray
495
+ Polynomial coefficients of the derivative.
496
+
497
+ See Also
498
+ --------
499
+ polyint
500
+
501
+ Examples
502
+ --------
503
+ >>> from numpy.polynomial import polynomial as P
504
+ >>> c = (1,2,3,4) # 1 + 2x + 3x**2 + 4x**3
505
+ >>> P.polyder(c) # (d/dx)(c) = 2 + 6x + 12x**2
506
+ array([ 2., 6., 12.])
507
+ >>> P.polyder(c,3) # (d**3/dx**3)(c) = 24
508
+ array([24.])
509
+ >>> P.polyder(c,scl=-1) # (d/d(-x))(c) = -2 - 6x - 12x**2
510
+ array([ -2., -6., -12.])
511
+ >>> P.polyder(c,2,-1) # (d**2/d(-x)**2)(c) = 6 + 24x
512
+ array([ 6., 24.])
513
+
514
+ """
515
+ c = np.array(c, ndmin=1, copy=True)
516
+ if c.dtype.char in '?bBhHiIlLqQpP':
517
+ # astype fails with NA
518
+ c = c + 0.0
519
+ cdt = c.dtype
520
+ cnt = pu._deprecate_as_int(m, "the order of derivation")
521
+ iaxis = pu._deprecate_as_int(axis, "the axis")
522
+ if cnt < 0:
523
+ raise ValueError("The order of derivation must be non-negative")
524
+ iaxis = normalize_axis_index(iaxis, c.ndim)
525
+
526
+ if cnt == 0:
527
+ return c
528
+
529
+ c = np.moveaxis(c, iaxis, 0)
530
+ n = len(c)
531
+ if cnt >= n:
532
+ c = c[:1]*0
533
+ else:
534
+ for i in range(cnt):
535
+ n = n - 1
536
+ c *= scl
537
+ der = np.empty((n,) + c.shape[1:], dtype=cdt)
538
+ for j in range(n, 0, -1):
539
+ der[j - 1] = j*c[j]
540
+ c = der
541
+ c = np.moveaxis(c, 0, iaxis)
542
+ return c
543
+
544
+
545
+ def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
546
+ """
547
+ Integrate a polynomial.
548
+
549
+ Returns the polynomial coefficients `c` integrated `m` times from
550
+ `lbnd` along `axis`. At each iteration the resulting series is
551
+ **multiplied** by `scl` and an integration constant, `k`, is added.
552
+ The scaling factor is for use in a linear change of variable. ("Buyer
553
+ beware": note that, depending on what one is doing, one may want `scl`
554
+ to be the reciprocal of what one might expect; for more information,
555
+ see the Notes section below.) The argument `c` is an array of
556
+ coefficients, from low to high degree along each axis, e.g., [1,2,3]
557
+ represents the polynomial ``1 + 2*x + 3*x**2`` while [[1,2],[1,2]]
558
+ represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is ``x`` and axis=1 is
559
+ ``y``.
560
+
561
+ Parameters
562
+ ----------
563
+ c : array_like
564
+ 1-D array of polynomial coefficients, ordered from low to high.
565
+ m : int, optional
566
+ Order of integration, must be positive. (Default: 1)
567
+ k : {[], list, scalar}, optional
568
+ Integration constant(s). The value of the first integral at zero
569
+ is the first value in the list, the value of the second integral
570
+ at zero is the second value, etc. If ``k == []`` (the default),
571
+ all constants are set to zero. If ``m == 1``, a single scalar can
572
+ be given instead of a list.
573
+ lbnd : scalar, optional
574
+ The lower bound of the integral. (Default: 0)
575
+ scl : scalar, optional
576
+ Following each integration the result is *multiplied* by `scl`
577
+ before the integration constant is added. (Default: 1)
578
+ axis : int, optional
579
+ Axis over which the integral is taken. (Default: 0).
580
+
581
+ .. versionadded:: 1.7.0
582
+
583
+ Returns
584
+ -------
585
+ S : ndarray
586
+ Coefficient array of the integral.
587
+
588
+ Raises
589
+ ------
590
+ ValueError
591
+ If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
592
+ ``np.ndim(scl) != 0``.
593
+
594
+ See Also
595
+ --------
596
+ polyder
597
+
598
+ Notes
599
+ -----
600
+ Note that the result of each integration is *multiplied* by `scl`. Why
601
+ is this important to note? Say one is making a linear change of
602
+ variable :math:`u = ax + b` in an integral relative to `x`. Then
603
+ :math:`dx = du/a`, so one will need to set `scl` equal to
604
+ :math:`1/a` - perhaps not what one would have first thought.
605
+
606
+ Examples
607
+ --------
608
+ >>> from numpy.polynomial import polynomial as P
609
+ >>> c = (1,2,3)
610
+ >>> P.polyint(c) # should return array([0, 1, 1, 1])
611
+ array([0., 1., 1., 1.])
612
+ >>> P.polyint(c,3) # should return array([0, 0, 0, 1/6, 1/12, 1/20])
613
+ array([ 0. , 0. , 0. , 0.16666667, 0.08333333, # may vary
614
+ 0.05 ])
615
+ >>> P.polyint(c,k=3) # should return array([3, 1, 1, 1])
616
+ array([3., 1., 1., 1.])
617
+ >>> P.polyint(c,lbnd=-2) # should return array([6, 1, 1, 1])
618
+ array([6., 1., 1., 1.])
619
+ >>> P.polyint(c,scl=-2) # should return array([0, -2, -2, -2])
620
+ array([ 0., -2., -2., -2.])
621
+
622
+ """
623
+ c = np.array(c, ndmin=1, copy=True)
624
+ if c.dtype.char in '?bBhHiIlLqQpP':
625
+ # astype doesn't preserve mask attribute.
626
+ c = c + 0.0
627
+ cdt = c.dtype
628
+ if not np.iterable(k):
629
+ k = [k]
630
+ cnt = pu._deprecate_as_int(m, "the order of integration")
631
+ iaxis = pu._deprecate_as_int(axis, "the axis")
632
+ if cnt < 0:
633
+ raise ValueError("The order of integration must be non-negative")
634
+ if len(k) > cnt:
635
+ raise ValueError("Too many integration constants")
636
+ if np.ndim(lbnd) != 0:
637
+ raise ValueError("lbnd must be a scalar.")
638
+ if np.ndim(scl) != 0:
639
+ raise ValueError("scl must be a scalar.")
640
+ iaxis = normalize_axis_index(iaxis, c.ndim)
641
+
642
+ if cnt == 0:
643
+ return c
644
+
645
+ k = list(k) + [0]*(cnt - len(k))
646
+ c = np.moveaxis(c, iaxis, 0)
647
+ for i in range(cnt):
648
+ n = len(c)
649
+ c *= scl
650
+ if n == 1 and np.all(c[0] == 0):
651
+ c[0] += k[i]
652
+ else:
653
+ tmp = np.empty((n + 1,) + c.shape[1:], dtype=cdt)
654
+ tmp[0] = c[0]*0
655
+ tmp[1] = c[0]
656
+ for j in range(1, n):
657
+ tmp[j + 1] = c[j]/(j + 1)
658
+ tmp[0] += k[i] - polyval(lbnd, tmp)
659
+ c = tmp
660
+ c = np.moveaxis(c, 0, iaxis)
661
+ return c
662
+
663
+
664
+ def polyval(x, c, tensor=True):
665
+ """
666
+ Evaluate a polynomial at points x.
667
+
668
+ If `c` is of length `n + 1`, this function returns the value
669
+
670
+ .. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n
671
+
672
+ The parameter `x` is converted to an array only if it is a tuple or a
673
+ list, otherwise it is treated as a scalar. In either case, either `x`
674
+ or its elements must support multiplication and addition both with
675
+ themselves and with the elements of `c`.
676
+
677
+ If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
678
+ `c` is multidimensional, then the shape of the result depends on the
679
+ value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
680
+ x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
681
+ scalars have shape (,).
682
+
683
+ Trailing zeros in the coefficients will be used in the evaluation, so
684
+ they should be avoided if efficiency is a concern.
685
+
686
+ Parameters
687
+ ----------
688
+ x : array_like, compatible object
689
+ If `x` is a list or tuple, it is converted to an ndarray, otherwise
690
+ it is left unchanged and treated as a scalar. In either case, `x`
691
+ or its elements must support addition and multiplication with
692
+ with themselves and with the elements of `c`.
693
+ c : array_like
694
+ Array of coefficients ordered so that the coefficients for terms of
695
+ degree n are contained in c[n]. If `c` is multidimensional the
696
+ remaining indices enumerate multiple polynomials. In the two
697
+ dimensional case the coefficients may be thought of as stored in
698
+ the columns of `c`.
699
+ tensor : boolean, optional
700
+ If True, the shape of the coefficient array is extended with ones
701
+ on the right, one for each dimension of `x`. Scalars have dimension 0
702
+ for this action. The result is that every column of coefficients in
703
+ `c` is evaluated for every element of `x`. If False, `x` is broadcast
704
+ over the columns of `c` for the evaluation. This keyword is useful
705
+ when `c` is multidimensional. The default value is True.
706
+
707
+ .. versionadded:: 1.7.0
708
+
709
+ Returns
710
+ -------
711
+ values : ndarray, compatible object
712
+ The shape of the returned array is described above.
713
+
714
+ See Also
715
+ --------
716
+ polyval2d, polygrid2d, polyval3d, polygrid3d
717
+
718
+ Notes
719
+ -----
720
+ The evaluation uses Horner's method.
721
+
722
+ Examples
723
+ --------
724
+ >>> from numpy.polynomial.polynomial import polyval
725
+ >>> polyval(1, [1,2,3])
726
+ 6.0
727
+ >>> a = np.arange(4).reshape(2,2)
728
+ >>> a
729
+ array([[0, 1],
730
+ [2, 3]])
731
+ >>> polyval(a, [1,2,3])
732
+ array([[ 1., 6.],
733
+ [17., 34.]])
734
+ >>> coef = np.arange(4).reshape(2,2) # multidimensional coefficients
735
+ >>> coef
736
+ array([[0, 1],
737
+ [2, 3]])
738
+ >>> polyval([1,2], coef, tensor=True)
739
+ array([[2., 4.],
740
+ [4., 7.]])
741
+ >>> polyval([1,2], coef, tensor=False)
742
+ array([2., 7.])
743
+
744
+ """
745
+ c = np.array(c, ndmin=1, copy=False)
746
+ if c.dtype.char in '?bBhHiIlLqQpP':
747
+ # astype fails with NA
748
+ c = c + 0.0
749
+ if isinstance(x, (tuple, list)):
750
+ x = np.asarray(x)
751
+ if isinstance(x, np.ndarray) and tensor:
752
+ c = c.reshape(c.shape + (1,)*x.ndim)
753
+
754
+ c0 = c[-1] + x*0
755
+ for i in range(2, len(c) + 1):
756
+ c0 = c[-i] + c0*x
757
+ return c0
758
+
759
+
760
+ def polyvalfromroots(x, r, tensor=True):
761
+ """
762
+ Evaluate a polynomial specified by its roots at points x.
763
+
764
+ If `r` is of length `N`, this function returns the value
765
+
766
+ .. math:: p(x) = \\prod_{n=1}^{N} (x - r_n)
767
+
768
+ The parameter `x` is converted to an array only if it is a tuple or a
769
+ list, otherwise it is treated as a scalar. In either case, either `x`
770
+ or its elements must support multiplication and addition both with
771
+ themselves and with the elements of `r`.
772
+
773
+ If `r` is a 1-D array, then `p(x)` will have the same shape as `x`. If `r`
774
+ is multidimensional, then the shape of the result depends on the value of
775
+ `tensor`. If `tensor` is ``True`` the shape will be r.shape[1:] + x.shape;
776
+ that is, each polynomial is evaluated at every value of `x`. If `tensor` is
777
+ ``False``, the shape will be r.shape[1:]; that is, each polynomial is
778
+ evaluated only for the corresponding broadcast value of `x`. Note that
779
+ scalars have shape (,).
780
+
781
+ .. versionadded:: 1.12
782
+
783
+ Parameters
784
+ ----------
785
+ x : array_like, compatible object
786
+ If `x` is a list or tuple, it is converted to an ndarray, otherwise
787
+ it is left unchanged and treated as a scalar. In either case, `x`
788
+ or its elements must support addition and multiplication with
789
+ with themselves and with the elements of `r`.
790
+ r : array_like
791
+ Array of roots. If `r` is multidimensional the first index is the
792
+ root index, while the remaining indices enumerate multiple
793
+ polynomials. For instance, in the two dimensional case the roots
794
+ of each polynomial may be thought of as stored in the columns of `r`.
795
+ tensor : boolean, optional
796
+ If True, the shape of the roots array is extended with ones on the
797
+ right, one for each dimension of `x`. Scalars have dimension 0 for this
798
+ action. The result is that every column of coefficients in `r` is
799
+ evaluated for every element of `x`. If False, `x` is broadcast over the
800
+ columns of `r` for the evaluation. This keyword is useful when `r` is
801
+ multidimensional. The default value is True.
802
+
803
+ Returns
804
+ -------
805
+ values : ndarray, compatible object
806
+ The shape of the returned array is described above.
807
+
808
+ See Also
809
+ --------
810
+ polyroots, polyfromroots, polyval
811
+
812
+ Examples
813
+ --------
814
+ >>> from numpy.polynomial.polynomial import polyvalfromroots
815
+ >>> polyvalfromroots(1, [1,2,3])
816
+ 0.0
817
+ >>> a = np.arange(4).reshape(2,2)
818
+ >>> a
819
+ array([[0, 1],
820
+ [2, 3]])
821
+ >>> polyvalfromroots(a, [-1, 0, 1])
822
+ array([[-0., 0.],
823
+ [ 6., 24.]])
824
+ >>> r = np.arange(-2, 2).reshape(2,2) # multidimensional coefficients
825
+ >>> r # each column of r defines one polynomial
826
+ array([[-2, -1],
827
+ [ 0, 1]])
828
+ >>> b = [-2, 1]
829
+ >>> polyvalfromroots(b, r, tensor=True)
830
+ array([[-0., 3.],
831
+ [ 3., 0.]])
832
+ >>> polyvalfromroots(b, r, tensor=False)
833
+ array([-0., 0.])
834
+ """
835
+ r = np.array(r, ndmin=1, copy=False)
836
+ if r.dtype.char in '?bBhHiIlLqQpP':
837
+ r = r.astype(np.double)
838
+ if isinstance(x, (tuple, list)):
839
+ x = np.asarray(x)
840
+ if isinstance(x, np.ndarray):
841
+ if tensor:
842
+ r = r.reshape(r.shape + (1,)*x.ndim)
843
+ elif x.ndim >= r.ndim:
844
+ raise ValueError("x.ndim must be < r.ndim when tensor == False")
845
+ return np.prod(x - r, axis=0)
846
+
847
+
848
+ def polyval2d(x, y, c):
849
+ """
850
+ Evaluate a 2-D polynomial at points (x, y).
851
+
852
+ This function returns the value
853
+
854
+ .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j
855
+
856
+ The parameters `x` and `y` are converted to arrays only if they are
857
+ tuples or a lists, otherwise they are treated as a scalars and they
858
+ must have the same shape after conversion. In either case, either `x`
859
+ and `y` or their elements must support multiplication and addition both
860
+ with themselves and with the elements of `c`.
861
+
862
+ If `c` has fewer than two dimensions, ones are implicitly appended to
863
+ its shape to make it 2-D. The shape of the result will be c.shape[2:] +
864
+ x.shape.
865
+
866
+ Parameters
867
+ ----------
868
+ x, y : array_like, compatible objects
869
+ The two dimensional series is evaluated at the points `(x, y)`,
870
+ where `x` and `y` must have the same shape. If `x` or `y` is a list
871
+ or tuple, it is first converted to an ndarray, otherwise it is left
872
+ unchanged and, if it isn't an ndarray, it is treated as a scalar.
873
+ c : array_like
874
+ Array of coefficients ordered so that the coefficient of the term
875
+ of multi-degree i,j is contained in `c[i,j]`. If `c` has
876
+ dimension greater than two the remaining indices enumerate multiple
877
+ sets of coefficients.
878
+
879
+ Returns
880
+ -------
881
+ values : ndarray, compatible object
882
+ The values of the two dimensional polynomial at points formed with
883
+ pairs of corresponding values from `x` and `y`.
884
+
885
+ See Also
886
+ --------
887
+ polyval, polygrid2d, polyval3d, polygrid3d
888
+
889
+ Notes
890
+ -----
891
+
892
+ .. versionadded:: 1.7.0
893
+
894
+ """
895
+ return pu._valnd(polyval, c, x, y)
896
+
897
+
898
+ def polygrid2d(x, y, c):
899
+ """
900
+ Evaluate a 2-D polynomial on the Cartesian product of x and y.
901
+
902
+ This function returns the values:
903
+
904
+ .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * a^i * b^j
905
+
906
+ where the points `(a, b)` consist of all pairs formed by taking
907
+ `a` from `x` and `b` from `y`. The resulting points form a grid with
908
+ `x` in the first dimension and `y` in the second.
909
+
910
+ The parameters `x` and `y` are converted to arrays only if they are
911
+ tuples or a lists, otherwise they are treated as a scalars. In either
912
+ case, either `x` and `y` or their elements must support multiplication
913
+ and addition both with themselves and with the elements of `c`.
914
+
915
+ If `c` has fewer than two dimensions, ones are implicitly appended to
916
+ its shape to make it 2-D. The shape of the result will be c.shape[2:] +
917
+ x.shape + y.shape.
918
+
919
+ Parameters
920
+ ----------
921
+ x, y : array_like, compatible objects
922
+ The two dimensional series is evaluated at the points in the
923
+ Cartesian product of `x` and `y`. If `x` or `y` is a list or
924
+ tuple, it is first converted to an ndarray, otherwise it is left
925
+ unchanged and, if it isn't an ndarray, it is treated as a scalar.
926
+ c : array_like
927
+ Array of coefficients ordered so that the coefficients for terms of
928
+ degree i,j are contained in ``c[i,j]``. If `c` has dimension
929
+ greater than two the remaining indices enumerate multiple sets of
930
+ coefficients.
931
+
932
+ Returns
933
+ -------
934
+ values : ndarray, compatible object
935
+ The values of the two dimensional polynomial at points in the Cartesian
936
+ product of `x` and `y`.
937
+
938
+ See Also
939
+ --------
940
+ polyval, polyval2d, polyval3d, polygrid3d
941
+
942
+ Notes
943
+ -----
944
+
945
+ .. versionadded:: 1.7.0
946
+
947
+ """
948
+ return pu._gridnd(polyval, c, x, y)
949
+
950
+
951
+ def polyval3d(x, y, z, c):
952
+ """
953
+ Evaluate a 3-D polynomial at points (x, y, z).
954
+
955
+ This function returns the values:
956
+
957
+ .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * x^i * y^j * z^k
958
+
959
+ The parameters `x`, `y`, and `z` are converted to arrays only if
960
+ they are tuples or a lists, otherwise they are treated as a scalars and
961
+ they must have the same shape after conversion. In either case, either
962
+ `x`, `y`, and `z` or their elements must support multiplication and
963
+ addition both with themselves and with the elements of `c`.
964
+
965
+ If `c` has fewer than 3 dimensions, ones are implicitly appended to its
966
+ shape to make it 3-D. The shape of the result will be c.shape[3:] +
967
+ x.shape.
968
+
969
+ Parameters
970
+ ----------
971
+ x, y, z : array_like, compatible object
972
+ The three dimensional series is evaluated at the points
973
+ `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
974
+ any of `x`, `y`, or `z` is a list or tuple, it is first converted
975
+ to an ndarray, otherwise it is left unchanged and if it isn't an
976
+ ndarray it is treated as a scalar.
977
+ c : array_like
978
+ Array of coefficients ordered so that the coefficient of the term of
979
+ multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
980
+ greater than 3 the remaining indices enumerate multiple sets of
981
+ coefficients.
982
+
983
+ Returns
984
+ -------
985
+ values : ndarray, compatible object
986
+ The values of the multidimensional polynomial on points formed with
987
+ triples of corresponding values from `x`, `y`, and `z`.
988
+
989
+ See Also
990
+ --------
991
+ polyval, polyval2d, polygrid2d, polygrid3d
992
+
993
+ Notes
994
+ -----
995
+
996
+ .. versionadded:: 1.7.0
997
+
998
+ """
999
+ return pu._valnd(polyval, c, x, y, z)
1000
+
1001
+
1002
+ def polygrid3d(x, y, z, c):
1003
+ """
1004
+ Evaluate a 3-D polynomial on the Cartesian product of x, y and z.
1005
+
1006
+ This function returns the values:
1007
+
1008
+ .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * a^i * b^j * c^k
1009
+
1010
+ where the points `(a, b, c)` consist of all triples formed by taking
1011
+ `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
1012
+ a grid with `x` in the first dimension, `y` in the second, and `z` in
1013
+ the third.
1014
+
1015
+ The parameters `x`, `y`, and `z` are converted to arrays only if they
1016
+ are tuples or a lists, otherwise they are treated as a scalars. In
1017
+ either case, either `x`, `y`, and `z` or their elements must support
1018
+ multiplication and addition both with themselves and with the elements
1019
+ of `c`.
1020
+
1021
+ If `c` has fewer than three dimensions, ones are implicitly appended to
1022
+ its shape to make it 3-D. The shape of the result will be c.shape[3:] +
1023
+ x.shape + y.shape + z.shape.
1024
+
1025
+ Parameters
1026
+ ----------
1027
+ x, y, z : array_like, compatible objects
1028
+ The three dimensional series is evaluated at the points in the
1029
+ Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
1030
+ list or tuple, it is first converted to an ndarray, otherwise it is
1031
+ left unchanged and, if it isn't an ndarray, it is treated as a
1032
+ scalar.
1033
+ c : array_like
1034
+ Array of coefficients ordered so that the coefficients for terms of
1035
+ degree i,j are contained in ``c[i,j]``. If `c` has dimension
1036
+ greater than two the remaining indices enumerate multiple sets of
1037
+ coefficients.
1038
+
1039
+ Returns
1040
+ -------
1041
+ values : ndarray, compatible object
1042
+ The values of the two dimensional polynomial at points in the Cartesian
1043
+ product of `x` and `y`.
1044
+
1045
+ See Also
1046
+ --------
1047
+ polyval, polyval2d, polygrid2d, polyval3d
1048
+
1049
+ Notes
1050
+ -----
1051
+
1052
+ .. versionadded:: 1.7.0
1053
+
1054
+ """
1055
+ return pu._gridnd(polyval, c, x, y, z)
1056
+
1057
+
1058
+ def polyvander(x, deg):
1059
+ """Vandermonde matrix of given degree.
1060
+
1061
+ Returns the Vandermonde matrix of degree `deg` and sample points
1062
+ `x`. The Vandermonde matrix is defined by
1063
+
1064
+ .. math:: V[..., i] = x^i,
1065
+
1066
+ where `0 <= i <= deg`. The leading indices of `V` index the elements of
1067
+ `x` and the last index is the power of `x`.
1068
+
1069
+ If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
1070
+ matrix ``V = polyvander(x, n)``, then ``np.dot(V, c)`` and
1071
+ ``polyval(x, c)`` are the same up to roundoff. This equivalence is
1072
+ useful both for least squares fitting and for the evaluation of a large
1073
+ number of polynomials of the same degree and sample points.
1074
+
1075
+ Parameters
1076
+ ----------
1077
+ x : array_like
1078
+ Array of points. The dtype is converted to float64 or complex128
1079
+ depending on whether any of the elements are complex. If `x` is
1080
+ scalar it is converted to a 1-D array.
1081
+ deg : int
1082
+ Degree of the resulting matrix.
1083
+
1084
+ Returns
1085
+ -------
1086
+ vander : ndarray.
1087
+ The Vandermonde matrix. The shape of the returned matrix is
1088
+ ``x.shape + (deg + 1,)``, where the last index is the power of `x`.
1089
+ The dtype will be the same as the converted `x`.
1090
+
1091
+ See Also
1092
+ --------
1093
+ polyvander2d, polyvander3d
1094
+
1095
+ """
1096
+ ideg = pu._deprecate_as_int(deg, "deg")
1097
+ if ideg < 0:
1098
+ raise ValueError("deg must be non-negative")
1099
+
1100
+ x = np.array(x, copy=False, ndmin=1) + 0.0
1101
+ dims = (ideg + 1,) + x.shape
1102
+ dtyp = x.dtype
1103
+ v = np.empty(dims, dtype=dtyp)
1104
+ v[0] = x*0 + 1
1105
+ if ideg > 0:
1106
+ v[1] = x
1107
+ for i in range(2, ideg + 1):
1108
+ v[i] = v[i-1]*x
1109
+ return np.moveaxis(v, 0, -1)
1110
+
1111
+
1112
+ def polyvander2d(x, y, deg):
1113
+ """Pseudo-Vandermonde matrix of given degrees.
1114
+
1115
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1116
+ points `(x, y)`. The pseudo-Vandermonde matrix is defined by
1117
+
1118
+ .. math:: V[..., (deg[1] + 1)*i + j] = x^i * y^j,
1119
+
1120
+ where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
1121
+ `V` index the points `(x, y)` and the last index encodes the powers of
1122
+ `x` and `y`.
1123
+
1124
+ If ``V = polyvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
1125
+ correspond to the elements of a 2-D coefficient array `c` of shape
1126
+ (xdeg + 1, ydeg + 1) in the order
1127
+
1128
+ .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
1129
+
1130
+ and ``np.dot(V, c.flat)`` and ``polyval2d(x, y, c)`` will be the same
1131
+ up to roundoff. This equivalence is useful both for least squares
1132
+ fitting and for the evaluation of a large number of 2-D polynomials
1133
+ of the same degrees and sample points.
1134
+
1135
+ Parameters
1136
+ ----------
1137
+ x, y : array_like
1138
+ Arrays of point coordinates, all of the same shape. The dtypes
1139
+ will be converted to either float64 or complex128 depending on
1140
+ whether any of the elements are complex. Scalars are converted to
1141
+ 1-D arrays.
1142
+ deg : list of ints
1143
+ List of maximum degrees of the form [x_deg, y_deg].
1144
+
1145
+ Returns
1146
+ -------
1147
+ vander2d : ndarray
1148
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1149
+ :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
1150
+ as the converted `x` and `y`.
1151
+
1152
+ See Also
1153
+ --------
1154
+ polyvander, polyvander3d, polyval2d, polyval3d
1155
+
1156
+ """
1157
+ return pu._vander_nd_flat((polyvander, polyvander), (x, y), deg)
1158
+
1159
+
1160
+ def polyvander3d(x, y, z, deg):
1161
+ """Pseudo-Vandermonde matrix of given degrees.
1162
+
1163
+ Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
1164
+ points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
1165
+ then The pseudo-Vandermonde matrix is defined by
1166
+
1167
+ .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = x^i * y^j * z^k,
1168
+
1169
+ where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
1170
+ indices of `V` index the points `(x, y, z)` and the last index encodes
1171
+ the powers of `x`, `y`, and `z`.
1172
+
1173
+ If ``V = polyvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
1174
+ of `V` correspond to the elements of a 3-D coefficient array `c` of
1175
+ shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
1176
+
1177
+ .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
1178
+
1179
+ and ``np.dot(V, c.flat)`` and ``polyval3d(x, y, z, c)`` will be the
1180
+ same up to roundoff. This equivalence is useful both for least squares
1181
+ fitting and for the evaluation of a large number of 3-D polynomials
1182
+ of the same degrees and sample points.
1183
+
1184
+ Parameters
1185
+ ----------
1186
+ x, y, z : array_like
1187
+ Arrays of point coordinates, all of the same shape. The dtypes will
1188
+ be converted to either float64 or complex128 depending on whether
1189
+ any of the elements are complex. Scalars are converted to 1-D
1190
+ arrays.
1191
+ deg : list of ints
1192
+ List of maximum degrees of the form [x_deg, y_deg, z_deg].
1193
+
1194
+ Returns
1195
+ -------
1196
+ vander3d : ndarray
1197
+ The shape of the returned matrix is ``x.shape + (order,)``, where
1198
+ :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will
1199
+ be the same as the converted `x`, `y`, and `z`.
1200
+
1201
+ See Also
1202
+ --------
1203
+ polyvander, polyvander3d, polyval2d, polyval3d
1204
+
1205
+ Notes
1206
+ -----
1207
+
1208
+ .. versionadded:: 1.7.0
1209
+
1210
+ """
1211
+ return pu._vander_nd_flat((polyvander, polyvander, polyvander), (x, y, z), deg)
1212
+
1213
+
1214
+ def polyfit(x, y, deg, rcond=None, full=False, w=None):
1215
+ """
1216
+ Least-squares fit of a polynomial to data.
1217
+
1218
+ Return the coefficients of a polynomial of degree `deg` that is the
1219
+ least squares fit to the data values `y` given at points `x`. If `y` is
1220
+ 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
1221
+ fits are done, one for each column of `y`, and the resulting
1222
+ coefficients are stored in the corresponding columns of a 2-D return.
1223
+ The fitted polynomial(s) are in the form
1224
+
1225
+ .. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n,
1226
+
1227
+ where `n` is `deg`.
1228
+
1229
+ Parameters
1230
+ ----------
1231
+ x : array_like, shape (`M`,)
1232
+ x-coordinates of the `M` sample (data) points ``(x[i], y[i])``.
1233
+ y : array_like, shape (`M`,) or (`M`, `K`)
1234
+ y-coordinates of the sample points. Several sets of sample points
1235
+ sharing the same x-coordinates can be (independently) fit with one
1236
+ call to `polyfit` by passing in for `y` a 2-D array that contains
1237
+ one data set per column.
1238
+ deg : int or 1-D array_like
1239
+ Degree(s) of the fitting polynomials. If `deg` is a single integer
1240
+ all terms up to and including the `deg`'th term are included in the
1241
+ fit. For NumPy versions >= 1.11.0 a list of integers specifying the
1242
+ degrees of the terms to include may be used instead.
1243
+ rcond : float, optional
1244
+ Relative condition number of the fit. Singular values smaller
1245
+ than `rcond`, relative to the largest singular value, will be
1246
+ ignored. The default value is ``len(x)*eps``, where `eps` is the
1247
+ relative precision of the platform's float type, about 2e-16 in
1248
+ most cases.
1249
+ full : bool, optional
1250
+ Switch determining the nature of the return value. When ``False``
1251
+ (the default) just the coefficients are returned; when ``True``,
1252
+ diagnostic information from the singular value decomposition (used
1253
+ to solve the fit's matrix equation) is also returned.
1254
+ w : array_like, shape (`M`,), optional
1255
+ Weights. If not None, the weight ``w[i]`` applies to the unsquared
1256
+ residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
1257
+ chosen so that the errors of the products ``w[i]*y[i]`` all have the
1258
+ same variance. When using inverse-variance weighting, use
1259
+ ``w[i] = 1/sigma(y[i])``. The default value is None.
1260
+
1261
+ .. versionadded:: 1.5.0
1262
+
1263
+ Returns
1264
+ -------
1265
+ coef : ndarray, shape (`deg` + 1,) or (`deg` + 1, `K`)
1266
+ Polynomial coefficients ordered from low to high. If `y` was 2-D,
1267
+ the coefficients in column `k` of `coef` represent the polynomial
1268
+ fit to the data in `y`'s `k`-th column.
1269
+
1270
+ [residuals, rank, singular_values, rcond] : list
1271
+ These values are only returned if ``full == True``
1272
+
1273
+ - residuals -- sum of squared residuals of the least squares fit
1274
+ - rank -- the numerical rank of the scaled Vandermonde matrix
1275
+ - singular_values -- singular values of the scaled Vandermonde matrix
1276
+ - rcond -- value of `rcond`.
1277
+
1278
+ For more details, see `numpy.linalg.lstsq`.
1279
+
1280
+ Raises
1281
+ ------
1282
+ RankWarning
1283
+ Raised if the matrix in the least-squares fit is rank deficient.
1284
+ The warning is only raised if ``full == False``. The warnings can
1285
+ be turned off by:
1286
+
1287
+ >>> import warnings
1288
+ >>> warnings.simplefilter('ignore', np.RankWarning)
1289
+
1290
+ See Also
1291
+ --------
1292
+ numpy.polynomial.chebyshev.chebfit
1293
+ numpy.polynomial.legendre.legfit
1294
+ numpy.polynomial.laguerre.lagfit
1295
+ numpy.polynomial.hermite.hermfit
1296
+ numpy.polynomial.hermite_e.hermefit
1297
+ polyval : Evaluates a polynomial.
1298
+ polyvander : Vandermonde matrix for powers.
1299
+ numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
1300
+ scipy.interpolate.UnivariateSpline : Computes spline fits.
1301
+
1302
+ Notes
1303
+ -----
1304
+ The solution is the coefficients of the polynomial `p` that minimizes
1305
+ the sum of the weighted squared errors
1306
+
1307
+ .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
1308
+
1309
+ where the :math:`w_j` are the weights. This problem is solved by
1310
+ setting up the (typically) over-determined matrix equation:
1311
+
1312
+ .. math:: V(x) * c = w * y,
1313
+
1314
+ where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
1315
+ coefficients to be solved for, `w` are the weights, and `y` are the
1316
+ observed values. This equation is then solved using the singular value
1317
+ decomposition of `V`.
1318
+
1319
+ If some of the singular values of `V` are so small that they are
1320
+ neglected (and `full` == ``False``), a `RankWarning` will be raised.
1321
+ This means that the coefficient values may be poorly determined.
1322
+ Fitting to a lower order polynomial will usually get rid of the warning
1323
+ (but may not be what you want, of course; if you have independent
1324
+ reason(s) for choosing the degree which isn't working, you may have to:
1325
+ a) reconsider those reasons, and/or b) reconsider the quality of your
1326
+ data). The `rcond` parameter can also be set to a value smaller than
1327
+ its default, but the resulting fit may be spurious and have large
1328
+ contributions from roundoff error.
1329
+
1330
+ Polynomial fits using double precision tend to "fail" at about
1331
+ (polynomial) degree 20. Fits using Chebyshev or Legendre series are
1332
+ generally better conditioned, but much can still depend on the
1333
+ distribution of the sample points and the smoothness of the data. If
1334
+ the quality of the fit is inadequate, splines may be a good
1335
+ alternative.
1336
+
1337
+ Examples
1338
+ --------
1339
+ >>> np.random.seed(123)
1340
+ >>> from numpy.polynomial import polynomial as P
1341
+ >>> x = np.linspace(-1,1,51) # x "data": [-1, -0.96, ..., 0.96, 1]
1342
+ >>> y = x**3 - x + np.random.randn(len(x)) # x^3 - x + Gaussian noise
1343
+ >>> c, stats = P.polyfit(x,y,3,full=True)
1344
+ >>> np.random.seed(123)
1345
+ >>> c # c[0], c[2] should be approx. 0, c[1] approx. -1, c[3] approx. 1
1346
+ array([ 0.01909725, -1.30598256, -0.00577963, 1.02644286]) # may vary
1347
+ >>> stats # note the large SSR, explaining the rather poor results
1348
+ [array([ 38.06116253]), 4, array([ 1.38446749, 1.32119158, 0.50443316, # may vary
1349
+ 0.28853036]), 1.1324274851176597e-014]
1350
+
1351
+ Same thing without the added noise
1352
+
1353
+ >>> y = x**3 - x
1354
+ >>> c, stats = P.polyfit(x,y,3,full=True)
1355
+ >>> c # c[0], c[2] should be "very close to 0", c[1] ~= -1, c[3] ~= 1
1356
+ array([-6.36925336e-18, -1.00000000e+00, -4.08053781e-16, 1.00000000e+00])
1357
+ >>> stats # note the minuscule SSR
1358
+ [array([ 7.46346754e-31]), 4, array([ 1.38446749, 1.32119158, # may vary
1359
+ 0.50443316, 0.28853036]), 1.1324274851176597e-014]
1360
+
1361
+ """
1362
+ return pu._fit(polyvander, x, y, deg, rcond, full, w)
1363
+
1364
+
1365
+ def polycompanion(c):
1366
+ """
1367
+ Return the companion matrix of c.
1368
+
1369
+ The companion matrix for power series cannot be made symmetric by
1370
+ scaling the basis, so this function differs from those for the
1371
+ orthogonal polynomials.
1372
+
1373
+ Parameters
1374
+ ----------
1375
+ c : array_like
1376
+ 1-D array of polynomial coefficients ordered from low to high
1377
+ degree.
1378
+
1379
+ Returns
1380
+ -------
1381
+ mat : ndarray
1382
+ Companion matrix of dimensions (deg, deg).
1383
+
1384
+ Notes
1385
+ -----
1386
+
1387
+ .. versionadded:: 1.7.0
1388
+
1389
+ """
1390
+ # c is a trimmed copy
1391
+ [c] = pu.as_series([c])
1392
+ if len(c) < 2:
1393
+ raise ValueError('Series must have maximum degree of at least 1.')
1394
+ if len(c) == 2:
1395
+ return np.array([[-c[0]/c[1]]])
1396
+
1397
+ n = len(c) - 1
1398
+ mat = np.zeros((n, n), dtype=c.dtype)
1399
+ bot = mat.reshape(-1)[n::n+1]
1400
+ bot[...] = 1
1401
+ mat[:, -1] -= c[:-1]/c[-1]
1402
+ return mat
1403
+
1404
+
1405
+ def polyroots(c):
1406
+ """
1407
+ Compute the roots of a polynomial.
1408
+
1409
+ Return the roots (a.k.a. "zeros") of the polynomial
1410
+
1411
+ .. math:: p(x) = \\sum_i c[i] * x^i.
1412
+
1413
+ Parameters
1414
+ ----------
1415
+ c : 1-D array_like
1416
+ 1-D array of polynomial coefficients.
1417
+
1418
+ Returns
1419
+ -------
1420
+ out : ndarray
1421
+ Array of the roots of the polynomial. If all the roots are real,
1422
+ then `out` is also real, otherwise it is complex.
1423
+
1424
+ See Also
1425
+ --------
1426
+ numpy.polynomial.chebyshev.chebroots
1427
+ numpy.polynomial.legendre.legroots
1428
+ numpy.polynomial.laguerre.lagroots
1429
+ numpy.polynomial.hermite.hermroots
1430
+ numpy.polynomial.hermite_e.hermeroots
1431
+
1432
+ Notes
1433
+ -----
1434
+ The root estimates are obtained as the eigenvalues of the companion
1435
+ matrix, Roots far from the origin of the complex plane may have large
1436
+ errors due to the numerical instability of the power series for such
1437
+ values. Roots with multiplicity greater than 1 will also show larger
1438
+ errors as the value of the series near such points is relatively
1439
+ insensitive to errors in the roots. Isolated roots near the origin can
1440
+ be improved by a few iterations of Newton's method.
1441
+
1442
+ Examples
1443
+ --------
1444
+ >>> import numpy.polynomial.polynomial as poly
1445
+ >>> poly.polyroots(poly.polyfromroots((-1,0,1)))
1446
+ array([-1., 0., 1.])
1447
+ >>> poly.polyroots(poly.polyfromroots((-1,0,1))).dtype
1448
+ dtype('float64')
1449
+ >>> j = complex(0,1)
1450
+ >>> poly.polyroots(poly.polyfromroots((-j,0,j)))
1451
+ array([ 0.00000000e+00+0.j, 0.00000000e+00+1.j, 2.77555756e-17-1.j]) # may vary
1452
+
1453
+ """
1454
+ # c is a trimmed copy
1455
+ [c] = pu.as_series([c])
1456
+ if len(c) < 2:
1457
+ return np.array([], dtype=c.dtype)
1458
+ if len(c) == 2:
1459
+ return np.array([-c[0]/c[1]])
1460
+
1461
+ # rotated companion matrix reduces error
1462
+ m = polycompanion(c)[::-1,::-1]
1463
+ r = la.eigvals(m)
1464
+ r.sort()
1465
+ return r
1466
+
1467
+
1468
+ #
1469
+ # polynomial class
1470
+ #
1471
+
1472
+ class Polynomial(ABCPolyBase):
1473
+ """A power series class.
1474
+
1475
+ The Polynomial class provides the standard Python numerical methods
1476
+ '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
1477
+ attributes and methods listed in the `ABCPolyBase` documentation.
1478
+
1479
+ Parameters
1480
+ ----------
1481
+ coef : array_like
1482
+ Polynomial coefficients in order of increasing degree, i.e.,
1483
+ ``(1, 2, 3)`` give ``1 + 2*x + 3*x**2``.
1484
+ domain : (2,) array_like, optional
1485
+ Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
1486
+ to the interval ``[window[0], window[1]]`` by shifting and scaling.
1487
+ The default value is [-1, 1].
1488
+ window : (2,) array_like, optional
1489
+ Window, see `domain` for its use. The default value is [-1, 1].
1490
+
1491
+ .. versionadded:: 1.6.0
1492
+ symbol : str, optional
1493
+ Symbol used to represent the independent variable in string
1494
+ representations of the polynomial expression, e.g. for printing.
1495
+ The symbol must be a valid Python identifier. Default value is 'x'.
1496
+
1497
+ .. versionadded:: 1.24
1498
+
1499
+ """
1500
+ # Virtual Functions
1501
+ _add = staticmethod(polyadd)
1502
+ _sub = staticmethod(polysub)
1503
+ _mul = staticmethod(polymul)
1504
+ _div = staticmethod(polydiv)
1505
+ _pow = staticmethod(polypow)
1506
+ _val = staticmethod(polyval)
1507
+ _int = staticmethod(polyint)
1508
+ _der = staticmethod(polyder)
1509
+ _fit = staticmethod(polyfit)
1510
+ _line = staticmethod(polyline)
1511
+ _roots = staticmethod(polyroots)
1512
+ _fromroots = staticmethod(polyfromroots)
1513
+
1514
+ # Virtual properties
1515
+ domain = np.array(polydomain)
1516
+ window = np.array(polydomain)
1517
+ basis_name = None
1518
+
1519
+ @classmethod
1520
+ def _str_term_unicode(cls, i, arg_str):
1521
+ if i == '1':
1522
+ return f"·{arg_str}"
1523
+ else:
1524
+ return f"·{arg_str}{i.translate(cls._superscript_mapping)}"
1525
+
1526
+ @staticmethod
1527
+ def _str_term_ascii(i, arg_str):
1528
+ if i == '1':
1529
+ return f" {arg_str}"
1530
+ else:
1531
+ return f" {arg_str}**{i}"
1532
+
1533
+ @staticmethod
1534
+ def _repr_latex_term(i, arg_str, needs_parens):
1535
+ if needs_parens:
1536
+ arg_str = rf"\left({arg_str}\right)"
1537
+ if i == 0:
1538
+ return '1'
1539
+ elif i == 1:
1540
+ return arg_str
1541
+ else:
1542
+ return f"{arg_str}^{{{i}}}"
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/polynomial.pyi ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from numpy import ndarray, dtype, int_
4
+ from numpy.polynomial._polybase import ABCPolyBase
5
+ from numpy.polynomial.polyutils import trimcoef
6
+
7
+ __all__: list[str]
8
+
9
+ polytrim = trimcoef
10
+
11
+ polydomain: ndarray[Any, dtype[int_]]
12
+ polyzero: ndarray[Any, dtype[int_]]
13
+ polyone: ndarray[Any, dtype[int_]]
14
+ polyx: ndarray[Any, dtype[int_]]
15
+
16
+ def polyline(off, scl): ...
17
+ def polyfromroots(roots): ...
18
+ def polyadd(c1, c2): ...
19
+ def polysub(c1, c2): ...
20
+ def polymulx(c): ...
21
+ def polymul(c1, c2): ...
22
+ def polydiv(c1, c2): ...
23
+ def polypow(c, pow, maxpower=...): ...
24
+ def polyder(c, m=..., scl=..., axis=...): ...
25
+ def polyint(c, m=..., k=..., lbnd=..., scl=..., axis=...): ...
26
+ def polyval(x, c, tensor=...): ...
27
+ def polyvalfromroots(x, r, tensor=...): ...
28
+ def polyval2d(x, y, c): ...
29
+ def polygrid2d(x, y, c): ...
30
+ def polyval3d(x, y, z, c): ...
31
+ def polygrid3d(x, y, z, c): ...
32
+ def polyvander(x, deg): ...
33
+ def polyvander2d(x, y, deg): ...
34
+ def polyvander3d(x, y, z, deg): ...
35
+ def polyfit(x, y, deg, rcond=..., full=..., w=...): ...
36
+ def polyroots(c): ...
37
+
38
+ class Polynomial(ABCPolyBase):
39
+ domain: Any
40
+ window: Any
41
+ basis_name: Any
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/polyutils.pyi ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__: list[str]
2
+
3
+ class RankWarning(UserWarning): ...
4
+
5
+ def trimseq(seq): ...
6
+ def as_series(alist, trim=...): ...
7
+ def trimcoef(c, tol=...): ...
8
+ def getdomain(x): ...
9
+ def mapparms(old, new): ...
10
+ def mapdomain(x, old, new): ...
11
+ def format_float(x, parens=...): ...
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/setup.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ def configuration(parent_package='',top_path=None):
2
+ from numpy.distutils.misc_util import Configuration
3
+ config = Configuration('polynomial', parent_package, top_path)
4
+ config.add_subpackage('tests')
5
+ config.add_data_files('*.pyi')
6
+ return config
7
+
8
+ if __name__ == '__main__':
9
+ from numpy.distutils.core import setup
10
+ setup(configuration=configuration)
env-llmeval/lib/python3.10/site-packages/numpy/polynomial/tests/__init__.py ADDED
File without changes