ZTWHHH commited on
Commit
cc5309b
·
verified ·
1 Parent(s): 5712a30

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. .gitattributes +2 -0
  2. deepseekvl2/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc +3 -0
  3. deepseekvl2/lib/python3.10/site-packages/numpy/lib/tests/data/python3.npy +3 -0
  4. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__init__.pyi +22 -0
  5. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/_polybase.cpython-310.pyc +0 -0
  6. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/hermite.cpython-310.pyc +0 -0
  7. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/laguerre.cpython-310.pyc +0 -0
  8. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/polynomial.cpython-310.pyc +0 -0
  9. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/polyutils.cpython-310.pyc +0 -0
  10. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/_polybase.py +1206 -0
  11. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/chebyshev.py +2082 -0
  12. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/chebyshev.pyi +51 -0
  13. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/hermite.py +1703 -0
  14. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/hermite_e.py +1695 -0
  15. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/hermite_e.pyi +46 -0
  16. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/legendre.py +1664 -0
  17. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/legendre.pyi +46 -0
  18. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/polynomial.py +1542 -0
  19. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/polyutils.pyi +11 -0
  20. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/setup.py +10 -0
  21. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__init__.py +0 -0
  22. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  23. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_chebyshev.cpython-310.pyc +0 -0
  24. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_classes.cpython-310.pyc +0 -0
  25. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_hermite.cpython-310.pyc +0 -0
  26. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_hermite_e.cpython-310.pyc +0 -0
  27. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_laguerre.cpython-310.pyc +0 -0
  28. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_legendre.cpython-310.pyc +0 -0
  29. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_polynomial.cpython-310.pyc +0 -0
  30. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_polyutils.cpython-310.pyc +0 -0
  31. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_printing.cpython-310.pyc +0 -0
  32. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_symbol.cpython-310.pyc +0 -0
  33. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_chebyshev.py +619 -0
  34. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_classes.py +600 -0
  35. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_hermite.py +555 -0
  36. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_hermite_e.py +556 -0
  37. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_laguerre.py +537 -0
  38. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_legendre.py +568 -0
  39. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_polynomial.py +611 -0
  40. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_polyutils.py +121 -0
  41. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_printing.py +530 -0
  42. deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_symbol.py +216 -0
  43. falcon/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolver.so.11 +3 -0
  44. infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__init__.py +38 -0
  45. infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/async_.cpython-310.pyc +0 -0
  46. infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/compat.py +32 -0
  47. infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__pycache__/gevent.cpython-310.pyc +0 -0
  48. infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__pycache__/immediate.cpython-310.pyc +0 -0
  49. infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/gevent.py +21 -0
  50. infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/immediate.py +27 -0
.gitattributes CHANGED
@@ -704,3 +704,5 @@ deepseek/lib/python3.10/site-packages/numpy/core/__pycache__/_add_newdocs.cpytho
704
  deepseekvl2/lib/python3.10/site-packages/torch/_inductor/__pycache__/ir.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
705
  infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
706
  deepseekvl2/lib/python3.10/site-packages/regex/__pycache__/test_regex.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
704
  deepseekvl2/lib/python3.10/site-packages/torch/_inductor/__pycache__/ir.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
705
  infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
706
  deepseekvl2/lib/python3.10/site-packages/regex/__pycache__/test_regex.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
707
+ falcon/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolver.so.11 filter=lfs diff=lfs merge=lfs -text
708
+ deepseekvl2/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
deepseekvl2/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aceb3f531fe0d2d5845bffb8cd81a939a3b88f59b7a5ef8d08622a4e5e2181d3
3
+ size 143252
deepseekvl2/lib/python3.10/site-packages/numpy/lib/tests/data/python3.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f469dde101a2c65e283d2ed487028f8180ebcb9457cf60c9d9b952314668fed
3
+ size 96
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__init__.pyi ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy._pytesttester import PytestTester
2
+
3
+ from numpy.polynomial import (
4
+ chebyshev as chebyshev,
5
+ hermite as hermite,
6
+ hermite_e as hermite_e,
7
+ laguerre as laguerre,
8
+ legendre as legendre,
9
+ polynomial as polynomial,
10
+ )
11
+ from numpy.polynomial.chebyshev import Chebyshev as Chebyshev
12
+ from numpy.polynomial.hermite import Hermite as Hermite
13
+ from numpy.polynomial.hermite_e import HermiteE as HermiteE
14
+ from numpy.polynomial.laguerre import Laguerre as Laguerre
15
+ from numpy.polynomial.legendre import Legendre as Legendre
16
+ from numpy.polynomial.polynomial import Polynomial as Polynomial
17
+
18
+ __all__: list[str]
19
+ __path__: list[str]
20
+ test: PytestTester
21
+
22
+ def set_default_printstyle(style): ...
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/_polybase.cpython-310.pyc ADDED
Binary file (36.4 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/hermite.cpython-310.pyc ADDED
Binary file (52.1 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/laguerre.cpython-310.pyc ADDED
Binary file (50.4 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/polynomial.cpython-310.pyc ADDED
Binary file (48.7 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/__pycache__/polyutils.cpython-310.pyc ADDED
Binary file (22.7 kB). View file
 
deepseekvl2/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)
deepseekvl2/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'
deepseekvl2/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
deepseekvl2/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'
deepseekvl2/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'
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/hermite_e.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
+ hermetrim = trimcoef
10
+
11
+ def poly2herme(pol): ...
12
+ def herme2poly(c): ...
13
+
14
+ hermedomain: ndarray[Any, dtype[int_]]
15
+ hermezero: ndarray[Any, dtype[int_]]
16
+ hermeone: ndarray[Any, dtype[int_]]
17
+ hermex: ndarray[Any, dtype[int_]]
18
+
19
+ def hermeline(off, scl): ...
20
+ def hermefromroots(roots): ...
21
+ def hermeadd(c1, c2): ...
22
+ def hermesub(c1, c2): ...
23
+ def hermemulx(c): ...
24
+ def hermemul(c1, c2): ...
25
+ def hermediv(c1, c2): ...
26
+ def hermepow(c, pow, maxpower=...): ...
27
+ def hermeder(c, m=..., scl=..., axis=...): ...
28
+ def hermeint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...
29
+ def hermeval(x, c, tensor=...): ...
30
+ def hermeval2d(x, y, c): ...
31
+ def hermegrid2d(x, y, c): ...
32
+ def hermeval3d(x, y, z, c): ...
33
+ def hermegrid3d(x, y, z, c): ...
34
+ def hermevander(x, deg): ...
35
+ def hermevander2d(x, y, deg): ...
36
+ def hermevander3d(x, y, z, deg): ...
37
+ def hermefit(x, y, deg, rcond=..., full=..., w=...): ...
38
+ def hermecompanion(c): ...
39
+ def hermeroots(c): ...
40
+ def hermegauss(deg): ...
41
+ def hermeweight(x): ...
42
+
43
+ class HermiteE(ABCPolyBase):
44
+ domain: Any
45
+ window: Any
46
+ basis_name: Any
deepseekvl2/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'
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/legendre.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
+ legtrim = trimcoef
10
+
11
+ def poly2leg(pol): ...
12
+ def leg2poly(c): ...
13
+
14
+ legdomain: ndarray[Any, dtype[int_]]
15
+ legzero: ndarray[Any, dtype[int_]]
16
+ legone: ndarray[Any, dtype[int_]]
17
+ legx: ndarray[Any, dtype[int_]]
18
+
19
+ def legline(off, scl): ...
20
+ def legfromroots(roots): ...
21
+ def legadd(c1, c2): ...
22
+ def legsub(c1, c2): ...
23
+ def legmulx(c): ...
24
+ def legmul(c1, c2): ...
25
+ def legdiv(c1, c2): ...
26
+ def legpow(c, pow, maxpower=...): ...
27
+ def legder(c, m=..., scl=..., axis=...): ...
28
+ def legint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...
29
+ def legval(x, c, tensor=...): ...
30
+ def legval2d(x, y, c): ...
31
+ def leggrid2d(x, y, c): ...
32
+ def legval3d(x, y, z, c): ...
33
+ def leggrid3d(x, y, z, c): ...
34
+ def legvander(x, deg): ...
35
+ def legvander2d(x, y, deg): ...
36
+ def legvander3d(x, y, z, deg): ...
37
+ def legfit(x, y, deg, rcond=..., full=..., w=...): ...
38
+ def legcompanion(c): ...
39
+ def legroots(c): ...
40
+ def leggauss(deg): ...
41
+ def legweight(x): ...
42
+
43
+ class Legendre(ABCPolyBase):
44
+ domain: Any
45
+ window: Any
46
+ basis_name: Any
deepseekvl2/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}}}"
deepseekvl2/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=...): ...
deepseekvl2/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)
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__init__.py ADDED
File without changes
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (179 Bytes). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_chebyshev.cpython-310.pyc ADDED
Binary file (20.1 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_classes.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_hermite.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_hermite_e.cpython-310.pyc ADDED
Binary file (17.6 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_laguerre.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_legendre.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_polynomial.cpython-310.pyc ADDED
Binary file (18.6 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_polyutils.cpython-310.pyc ADDED
Binary file (3.87 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_printing.cpython-310.pyc ADDED
Binary file (19.8 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/__pycache__/test_symbol.cpython-310.pyc ADDED
Binary file (8.4 kB). View file
 
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_chebyshev.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for chebyshev module.
2
+
3
+ """
4
+ from functools import reduce
5
+
6
+ import numpy as np
7
+ import numpy.polynomial.chebyshev as cheb
8
+ from numpy.polynomial.polynomial import polyval
9
+ from numpy.testing import (
10
+ assert_almost_equal, assert_raises, assert_equal, assert_,
11
+ )
12
+
13
+
14
+ def trim(x):
15
+ return cheb.chebtrim(x, tol=1e-6)
16
+
17
+ T0 = [1]
18
+ T1 = [0, 1]
19
+ T2 = [-1, 0, 2]
20
+ T3 = [0, -3, 0, 4]
21
+ T4 = [1, 0, -8, 0, 8]
22
+ T5 = [0, 5, 0, -20, 0, 16]
23
+ T6 = [-1, 0, 18, 0, -48, 0, 32]
24
+ T7 = [0, -7, 0, 56, 0, -112, 0, 64]
25
+ T8 = [1, 0, -32, 0, 160, 0, -256, 0, 128]
26
+ T9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256]
27
+
28
+ Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]
29
+
30
+
31
+ class TestPrivate:
32
+
33
+ def test__cseries_to_zseries(self):
34
+ for i in range(5):
35
+ inp = np.array([2] + [1]*i, np.double)
36
+ tgt = np.array([.5]*i + [2] + [.5]*i, np.double)
37
+ res = cheb._cseries_to_zseries(inp)
38
+ assert_equal(res, tgt)
39
+
40
+ def test__zseries_to_cseries(self):
41
+ for i in range(5):
42
+ inp = np.array([.5]*i + [2] + [.5]*i, np.double)
43
+ tgt = np.array([2] + [1]*i, np.double)
44
+ res = cheb._zseries_to_cseries(inp)
45
+ assert_equal(res, tgt)
46
+
47
+
48
+ class TestConstants:
49
+
50
+ def test_chebdomain(self):
51
+ assert_equal(cheb.chebdomain, [-1, 1])
52
+
53
+ def test_chebzero(self):
54
+ assert_equal(cheb.chebzero, [0])
55
+
56
+ def test_chebone(self):
57
+ assert_equal(cheb.chebone, [1])
58
+
59
+ def test_chebx(self):
60
+ assert_equal(cheb.chebx, [0, 1])
61
+
62
+
63
+ class TestArithmetic:
64
+
65
+ def test_chebadd(self):
66
+ for i in range(5):
67
+ for j in range(5):
68
+ msg = f"At i={i}, j={j}"
69
+ tgt = np.zeros(max(i, j) + 1)
70
+ tgt[i] += 1
71
+ tgt[j] += 1
72
+ res = cheb.chebadd([0]*i + [1], [0]*j + [1])
73
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
74
+
75
+ def test_chebsub(self):
76
+ for i in range(5):
77
+ for j in range(5):
78
+ msg = f"At i={i}, j={j}"
79
+ tgt = np.zeros(max(i, j) + 1)
80
+ tgt[i] += 1
81
+ tgt[j] -= 1
82
+ res = cheb.chebsub([0]*i + [1], [0]*j + [1])
83
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
84
+
85
+ def test_chebmulx(self):
86
+ assert_equal(cheb.chebmulx([0]), [0])
87
+ assert_equal(cheb.chebmulx([1]), [0, 1])
88
+ for i in range(1, 5):
89
+ ser = [0]*i + [1]
90
+ tgt = [0]*(i - 1) + [.5, 0, .5]
91
+ assert_equal(cheb.chebmulx(ser), tgt)
92
+
93
+ def test_chebmul(self):
94
+ for i in range(5):
95
+ for j in range(5):
96
+ msg = f"At i={i}, j={j}"
97
+ tgt = np.zeros(i + j + 1)
98
+ tgt[i + j] += .5
99
+ tgt[abs(i - j)] += .5
100
+ res = cheb.chebmul([0]*i + [1], [0]*j + [1])
101
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
102
+
103
+ def test_chebdiv(self):
104
+ for i in range(5):
105
+ for j in range(5):
106
+ msg = f"At i={i}, j={j}"
107
+ ci = [0]*i + [1]
108
+ cj = [0]*j + [1]
109
+ tgt = cheb.chebadd(ci, cj)
110
+ quo, rem = cheb.chebdiv(tgt, ci)
111
+ res = cheb.chebadd(cheb.chebmul(quo, ci), rem)
112
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
113
+
114
+ def test_chebpow(self):
115
+ for i in range(5):
116
+ for j in range(5):
117
+ msg = f"At i={i}, j={j}"
118
+ c = np.arange(i + 1)
119
+ tgt = reduce(cheb.chebmul, [c]*j, np.array([1]))
120
+ res = cheb.chebpow(c, j)
121
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
122
+
123
+
124
+ class TestEvaluation:
125
+ # coefficients of 1 + 2*x + 3*x**2
126
+ c1d = np.array([2.5, 2., 1.5])
127
+ c2d = np.einsum('i,j->ij', c1d, c1d)
128
+ c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
129
+
130
+ # some random values in [-1, 1)
131
+ x = np.random.random((3, 5))*2 - 1
132
+ y = polyval(x, [1., 2., 3.])
133
+
134
+ def test_chebval(self):
135
+ #check empty input
136
+ assert_equal(cheb.chebval([], [1]).size, 0)
137
+
138
+ #check normal input)
139
+ x = np.linspace(-1, 1)
140
+ y = [polyval(x, c) for c in Tlist]
141
+ for i in range(10):
142
+ msg = f"At i={i}"
143
+ tgt = y[i]
144
+ res = cheb.chebval(x, [0]*i + [1])
145
+ assert_almost_equal(res, tgt, err_msg=msg)
146
+
147
+ #check that shape is preserved
148
+ for i in range(3):
149
+ dims = [2]*i
150
+ x = np.zeros(dims)
151
+ assert_equal(cheb.chebval(x, [1]).shape, dims)
152
+ assert_equal(cheb.chebval(x, [1, 0]).shape, dims)
153
+ assert_equal(cheb.chebval(x, [1, 0, 0]).shape, dims)
154
+
155
+ def test_chebval2d(self):
156
+ x1, x2, x3 = self.x
157
+ y1, y2, y3 = self.y
158
+
159
+ #test exceptions
160
+ assert_raises(ValueError, cheb.chebval2d, x1, x2[:2], self.c2d)
161
+
162
+ #test values
163
+ tgt = y1*y2
164
+ res = cheb.chebval2d(x1, x2, self.c2d)
165
+ assert_almost_equal(res, tgt)
166
+
167
+ #test shape
168
+ z = np.ones((2, 3))
169
+ res = cheb.chebval2d(z, z, self.c2d)
170
+ assert_(res.shape == (2, 3))
171
+
172
+ def test_chebval3d(self):
173
+ x1, x2, x3 = self.x
174
+ y1, y2, y3 = self.y
175
+
176
+ #test exceptions
177
+ assert_raises(ValueError, cheb.chebval3d, x1, x2, x3[:2], self.c3d)
178
+
179
+ #test values
180
+ tgt = y1*y2*y3
181
+ res = cheb.chebval3d(x1, x2, x3, self.c3d)
182
+ assert_almost_equal(res, tgt)
183
+
184
+ #test shape
185
+ z = np.ones((2, 3))
186
+ res = cheb.chebval3d(z, z, z, self.c3d)
187
+ assert_(res.shape == (2, 3))
188
+
189
+ def test_chebgrid2d(self):
190
+ x1, x2, x3 = self.x
191
+ y1, y2, y3 = self.y
192
+
193
+ #test values
194
+ tgt = np.einsum('i,j->ij', y1, y2)
195
+ res = cheb.chebgrid2d(x1, x2, self.c2d)
196
+ assert_almost_equal(res, tgt)
197
+
198
+ #test shape
199
+ z = np.ones((2, 3))
200
+ res = cheb.chebgrid2d(z, z, self.c2d)
201
+ assert_(res.shape == (2, 3)*2)
202
+
203
+ def test_chebgrid3d(self):
204
+ x1, x2, x3 = self.x
205
+ y1, y2, y3 = self.y
206
+
207
+ #test values
208
+ tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
209
+ res = cheb.chebgrid3d(x1, x2, x3, self.c3d)
210
+ assert_almost_equal(res, tgt)
211
+
212
+ #test shape
213
+ z = np.ones((2, 3))
214
+ res = cheb.chebgrid3d(z, z, z, self.c3d)
215
+ assert_(res.shape == (2, 3)*3)
216
+
217
+
218
+ class TestIntegral:
219
+
220
+ def test_chebint(self):
221
+ # check exceptions
222
+ assert_raises(TypeError, cheb.chebint, [0], .5)
223
+ assert_raises(ValueError, cheb.chebint, [0], -1)
224
+ assert_raises(ValueError, cheb.chebint, [0], 1, [0, 0])
225
+ assert_raises(ValueError, cheb.chebint, [0], lbnd=[0])
226
+ assert_raises(ValueError, cheb.chebint, [0], scl=[0])
227
+ assert_raises(TypeError, cheb.chebint, [0], axis=.5)
228
+
229
+ # test integration of zero polynomial
230
+ for i in range(2, 5):
231
+ k = [0]*(i - 2) + [1]
232
+ res = cheb.chebint([0], m=i, k=k)
233
+ assert_almost_equal(res, [0, 1])
234
+
235
+ # check single integration with integration constant
236
+ for i in range(5):
237
+ scl = i + 1
238
+ pol = [0]*i + [1]
239
+ tgt = [i] + [0]*i + [1/scl]
240
+ chebpol = cheb.poly2cheb(pol)
241
+ chebint = cheb.chebint(chebpol, m=1, k=[i])
242
+ res = cheb.cheb2poly(chebint)
243
+ assert_almost_equal(trim(res), trim(tgt))
244
+
245
+ # check single integration with integration constant and lbnd
246
+ for i in range(5):
247
+ scl = i + 1
248
+ pol = [0]*i + [1]
249
+ chebpol = cheb.poly2cheb(pol)
250
+ chebint = cheb.chebint(chebpol, m=1, k=[i], lbnd=-1)
251
+ assert_almost_equal(cheb.chebval(-1, chebint), i)
252
+
253
+ # check single integration with integration constant and scaling
254
+ for i in range(5):
255
+ scl = i + 1
256
+ pol = [0]*i + [1]
257
+ tgt = [i] + [0]*i + [2/scl]
258
+ chebpol = cheb.poly2cheb(pol)
259
+ chebint = cheb.chebint(chebpol, m=1, k=[i], scl=2)
260
+ res = cheb.cheb2poly(chebint)
261
+ assert_almost_equal(trim(res), trim(tgt))
262
+
263
+ # check multiple integrations with default k
264
+ for i in range(5):
265
+ for j in range(2, 5):
266
+ pol = [0]*i + [1]
267
+ tgt = pol[:]
268
+ for k in range(j):
269
+ tgt = cheb.chebint(tgt, m=1)
270
+ res = cheb.chebint(pol, m=j)
271
+ assert_almost_equal(trim(res), trim(tgt))
272
+
273
+ # check multiple integrations with defined k
274
+ for i in range(5):
275
+ for j in range(2, 5):
276
+ pol = [0]*i + [1]
277
+ tgt = pol[:]
278
+ for k in range(j):
279
+ tgt = cheb.chebint(tgt, m=1, k=[k])
280
+ res = cheb.chebint(pol, m=j, k=list(range(j)))
281
+ assert_almost_equal(trim(res), trim(tgt))
282
+
283
+ # check multiple integrations with lbnd
284
+ for i in range(5):
285
+ for j in range(2, 5):
286
+ pol = [0]*i + [1]
287
+ tgt = pol[:]
288
+ for k in range(j):
289
+ tgt = cheb.chebint(tgt, m=1, k=[k], lbnd=-1)
290
+ res = cheb.chebint(pol, m=j, k=list(range(j)), lbnd=-1)
291
+ assert_almost_equal(trim(res), trim(tgt))
292
+
293
+ # check multiple integrations with scaling
294
+ for i in range(5):
295
+ for j in range(2, 5):
296
+ pol = [0]*i + [1]
297
+ tgt = pol[:]
298
+ for k in range(j):
299
+ tgt = cheb.chebint(tgt, m=1, k=[k], scl=2)
300
+ res = cheb.chebint(pol, m=j, k=list(range(j)), scl=2)
301
+ assert_almost_equal(trim(res), trim(tgt))
302
+
303
+ def test_chebint_axis(self):
304
+ # check that axis keyword works
305
+ c2d = np.random.random((3, 4))
306
+
307
+ tgt = np.vstack([cheb.chebint(c) for c in c2d.T]).T
308
+ res = cheb.chebint(c2d, axis=0)
309
+ assert_almost_equal(res, tgt)
310
+
311
+ tgt = np.vstack([cheb.chebint(c) for c in c2d])
312
+ res = cheb.chebint(c2d, axis=1)
313
+ assert_almost_equal(res, tgt)
314
+
315
+ tgt = np.vstack([cheb.chebint(c, k=3) for c in c2d])
316
+ res = cheb.chebint(c2d, k=3, axis=1)
317
+ assert_almost_equal(res, tgt)
318
+
319
+
320
+ class TestDerivative:
321
+
322
+ def test_chebder(self):
323
+ # check exceptions
324
+ assert_raises(TypeError, cheb.chebder, [0], .5)
325
+ assert_raises(ValueError, cheb.chebder, [0], -1)
326
+
327
+ # check that zeroth derivative does nothing
328
+ for i in range(5):
329
+ tgt = [0]*i + [1]
330
+ res = cheb.chebder(tgt, m=0)
331
+ assert_equal(trim(res), trim(tgt))
332
+
333
+ # check that derivation is the inverse of integration
334
+ for i in range(5):
335
+ for j in range(2, 5):
336
+ tgt = [0]*i + [1]
337
+ res = cheb.chebder(cheb.chebint(tgt, m=j), m=j)
338
+ assert_almost_equal(trim(res), trim(tgt))
339
+
340
+ # check derivation with scaling
341
+ for i in range(5):
342
+ for j in range(2, 5):
343
+ tgt = [0]*i + [1]
344
+ res = cheb.chebder(cheb.chebint(tgt, m=j, scl=2), m=j, scl=.5)
345
+ assert_almost_equal(trim(res), trim(tgt))
346
+
347
+ def test_chebder_axis(self):
348
+ # check that axis keyword works
349
+ c2d = np.random.random((3, 4))
350
+
351
+ tgt = np.vstack([cheb.chebder(c) for c in c2d.T]).T
352
+ res = cheb.chebder(c2d, axis=0)
353
+ assert_almost_equal(res, tgt)
354
+
355
+ tgt = np.vstack([cheb.chebder(c) for c in c2d])
356
+ res = cheb.chebder(c2d, axis=1)
357
+ assert_almost_equal(res, tgt)
358
+
359
+
360
+ class TestVander:
361
+ # some random values in [-1, 1)
362
+ x = np.random.random((3, 5))*2 - 1
363
+
364
+ def test_chebvander(self):
365
+ # check for 1d x
366
+ x = np.arange(3)
367
+ v = cheb.chebvander(x, 3)
368
+ assert_(v.shape == (3, 4))
369
+ for i in range(4):
370
+ coef = [0]*i + [1]
371
+ assert_almost_equal(v[..., i], cheb.chebval(x, coef))
372
+
373
+ # check for 2d x
374
+ x = np.array([[1, 2], [3, 4], [5, 6]])
375
+ v = cheb.chebvander(x, 3)
376
+ assert_(v.shape == (3, 2, 4))
377
+ for i in range(4):
378
+ coef = [0]*i + [1]
379
+ assert_almost_equal(v[..., i], cheb.chebval(x, coef))
380
+
381
+ def test_chebvander2d(self):
382
+ # also tests chebval2d for non-square coefficient array
383
+ x1, x2, x3 = self.x
384
+ c = np.random.random((2, 3))
385
+ van = cheb.chebvander2d(x1, x2, [1, 2])
386
+ tgt = cheb.chebval2d(x1, x2, c)
387
+ res = np.dot(van, c.flat)
388
+ assert_almost_equal(res, tgt)
389
+
390
+ # check shape
391
+ van = cheb.chebvander2d([x1], [x2], [1, 2])
392
+ assert_(van.shape == (1, 5, 6))
393
+
394
+ def test_chebvander3d(self):
395
+ # also tests chebval3d for non-square coefficient array
396
+ x1, x2, x3 = self.x
397
+ c = np.random.random((2, 3, 4))
398
+ van = cheb.chebvander3d(x1, x2, x3, [1, 2, 3])
399
+ tgt = cheb.chebval3d(x1, x2, x3, c)
400
+ res = np.dot(van, c.flat)
401
+ assert_almost_equal(res, tgt)
402
+
403
+ # check shape
404
+ van = cheb.chebvander3d([x1], [x2], [x3], [1, 2, 3])
405
+ assert_(van.shape == (1, 5, 24))
406
+
407
+
408
+ class TestFitting:
409
+
410
+ def test_chebfit(self):
411
+ def f(x):
412
+ return x*(x - 1)*(x - 2)
413
+
414
+ def f2(x):
415
+ return x**4 + x**2 + 1
416
+
417
+ # Test exceptions
418
+ assert_raises(ValueError, cheb.chebfit, [1], [1], -1)
419
+ assert_raises(TypeError, cheb.chebfit, [[1]], [1], 0)
420
+ assert_raises(TypeError, cheb.chebfit, [], [1], 0)
421
+ assert_raises(TypeError, cheb.chebfit, [1], [[[1]]], 0)
422
+ assert_raises(TypeError, cheb.chebfit, [1, 2], [1], 0)
423
+ assert_raises(TypeError, cheb.chebfit, [1], [1, 2], 0)
424
+ assert_raises(TypeError, cheb.chebfit, [1], [1], 0, w=[[1]])
425
+ assert_raises(TypeError, cheb.chebfit, [1], [1], 0, w=[1, 1])
426
+ assert_raises(ValueError, cheb.chebfit, [1], [1], [-1,])
427
+ assert_raises(ValueError, cheb.chebfit, [1], [1], [2, -1, 6])
428
+ assert_raises(TypeError, cheb.chebfit, [1], [1], [])
429
+
430
+ # Test fit
431
+ x = np.linspace(0, 2)
432
+ y = f(x)
433
+ #
434
+ coef3 = cheb.chebfit(x, y, 3)
435
+ assert_equal(len(coef3), 4)
436
+ assert_almost_equal(cheb.chebval(x, coef3), y)
437
+ coef3 = cheb.chebfit(x, y, [0, 1, 2, 3])
438
+ assert_equal(len(coef3), 4)
439
+ assert_almost_equal(cheb.chebval(x, coef3), y)
440
+ #
441
+ coef4 = cheb.chebfit(x, y, 4)
442
+ assert_equal(len(coef4), 5)
443
+ assert_almost_equal(cheb.chebval(x, coef4), y)
444
+ coef4 = cheb.chebfit(x, y, [0, 1, 2, 3, 4])
445
+ assert_equal(len(coef4), 5)
446
+ assert_almost_equal(cheb.chebval(x, coef4), y)
447
+ # check things still work if deg is not in strict increasing
448
+ coef4 = cheb.chebfit(x, y, [2, 3, 4, 1, 0])
449
+ assert_equal(len(coef4), 5)
450
+ assert_almost_equal(cheb.chebval(x, coef4), y)
451
+ #
452
+ coef2d = cheb.chebfit(x, np.array([y, y]).T, 3)
453
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
454
+ coef2d = cheb.chebfit(x, np.array([y, y]).T, [0, 1, 2, 3])
455
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
456
+ # test weighting
457
+ w = np.zeros_like(x)
458
+ yw = y.copy()
459
+ w[1::2] = 1
460
+ y[0::2] = 0
461
+ wcoef3 = cheb.chebfit(x, yw, 3, w=w)
462
+ assert_almost_equal(wcoef3, coef3)
463
+ wcoef3 = cheb.chebfit(x, yw, [0, 1, 2, 3], w=w)
464
+ assert_almost_equal(wcoef3, coef3)
465
+ #
466
+ wcoef2d = cheb.chebfit(x, np.array([yw, yw]).T, 3, w=w)
467
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
468
+ wcoef2d = cheb.chebfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
469
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
470
+ # test scaling with complex values x points whose square
471
+ # is zero when summed.
472
+ x = [1, 1j, -1, -1j]
473
+ assert_almost_equal(cheb.chebfit(x, x, 1), [0, 1])
474
+ assert_almost_equal(cheb.chebfit(x, x, [0, 1]), [0, 1])
475
+ # test fitting only even polynomials
476
+ x = np.linspace(-1, 1)
477
+ y = f2(x)
478
+ coef1 = cheb.chebfit(x, y, 4)
479
+ assert_almost_equal(cheb.chebval(x, coef1), y)
480
+ coef2 = cheb.chebfit(x, y, [0, 2, 4])
481
+ assert_almost_equal(cheb.chebval(x, coef2), y)
482
+ assert_almost_equal(coef1, coef2)
483
+
484
+
485
+ class TestInterpolate:
486
+
487
+ def f(self, x):
488
+ return x * (x - 1) * (x - 2)
489
+
490
+ def test_raises(self):
491
+ assert_raises(ValueError, cheb.chebinterpolate, self.f, -1)
492
+ assert_raises(TypeError, cheb.chebinterpolate, self.f, 10.)
493
+
494
+ def test_dimensions(self):
495
+ for deg in range(1, 5):
496
+ assert_(cheb.chebinterpolate(self.f, deg).shape == (deg + 1,))
497
+
498
+ def test_approximation(self):
499
+
500
+ def powx(x, p):
501
+ return x**p
502
+
503
+ x = np.linspace(-1, 1, 10)
504
+ for deg in range(0, 10):
505
+ for p in range(0, deg + 1):
506
+ c = cheb.chebinterpolate(powx, deg, (p,))
507
+ assert_almost_equal(cheb.chebval(x, c), powx(x, p), decimal=12)
508
+
509
+
510
+ class TestCompanion:
511
+
512
+ def test_raises(self):
513
+ assert_raises(ValueError, cheb.chebcompanion, [])
514
+ assert_raises(ValueError, cheb.chebcompanion, [1])
515
+
516
+ def test_dimensions(self):
517
+ for i in range(1, 5):
518
+ coef = [0]*i + [1]
519
+ assert_(cheb.chebcompanion(coef).shape == (i, i))
520
+
521
+ def test_linear_root(self):
522
+ assert_(cheb.chebcompanion([1, 2])[0, 0] == -.5)
523
+
524
+
525
+ class TestGauss:
526
+
527
+ def test_100(self):
528
+ x, w = cheb.chebgauss(100)
529
+
530
+ # test orthogonality. Note that the results need to be normalized,
531
+ # otherwise the huge values that can arise from fast growing
532
+ # functions like Laguerre can be very confusing.
533
+ v = cheb.chebvander(x, 99)
534
+ vv = np.dot(v.T * w, v)
535
+ vd = 1/np.sqrt(vv.diagonal())
536
+ vv = vd[:, None] * vv * vd
537
+ assert_almost_equal(vv, np.eye(100))
538
+
539
+ # check that the integral of 1 is correct
540
+ tgt = np.pi
541
+ assert_almost_equal(w.sum(), tgt)
542
+
543
+
544
+ class TestMisc:
545
+
546
+ def test_chebfromroots(self):
547
+ res = cheb.chebfromroots([])
548
+ assert_almost_equal(trim(res), [1])
549
+ for i in range(1, 5):
550
+ roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
551
+ tgt = [0]*i + [1]
552
+ res = cheb.chebfromroots(roots)*2**(i-1)
553
+ assert_almost_equal(trim(res), trim(tgt))
554
+
555
+ def test_chebroots(self):
556
+ assert_almost_equal(cheb.chebroots([1]), [])
557
+ assert_almost_equal(cheb.chebroots([1, 2]), [-.5])
558
+ for i in range(2, 5):
559
+ tgt = np.linspace(-1, 1, i)
560
+ res = cheb.chebroots(cheb.chebfromroots(tgt))
561
+ assert_almost_equal(trim(res), trim(tgt))
562
+
563
+ def test_chebtrim(self):
564
+ coef = [2, -1, 1, 0]
565
+
566
+ # Test exceptions
567
+ assert_raises(ValueError, cheb.chebtrim, coef, -1)
568
+
569
+ # Test results
570
+ assert_equal(cheb.chebtrim(coef), coef[:-1])
571
+ assert_equal(cheb.chebtrim(coef, 1), coef[:-3])
572
+ assert_equal(cheb.chebtrim(coef, 2), [0])
573
+
574
+ def test_chebline(self):
575
+ assert_equal(cheb.chebline(3, 4), [3, 4])
576
+
577
+ def test_cheb2poly(self):
578
+ for i in range(10):
579
+ assert_almost_equal(cheb.cheb2poly([0]*i + [1]), Tlist[i])
580
+
581
+ def test_poly2cheb(self):
582
+ for i in range(10):
583
+ assert_almost_equal(cheb.poly2cheb(Tlist[i]), [0]*i + [1])
584
+
585
+ def test_weight(self):
586
+ x = np.linspace(-1, 1, 11)[1:-1]
587
+ tgt = 1./(np.sqrt(1 + x) * np.sqrt(1 - x))
588
+ res = cheb.chebweight(x)
589
+ assert_almost_equal(res, tgt)
590
+
591
+ def test_chebpts1(self):
592
+ #test exceptions
593
+ assert_raises(ValueError, cheb.chebpts1, 1.5)
594
+ assert_raises(ValueError, cheb.chebpts1, 0)
595
+
596
+ #test points
597
+ tgt = [0]
598
+ assert_almost_equal(cheb.chebpts1(1), tgt)
599
+ tgt = [-0.70710678118654746, 0.70710678118654746]
600
+ assert_almost_equal(cheb.chebpts1(2), tgt)
601
+ tgt = [-0.86602540378443871, 0, 0.86602540378443871]
602
+ assert_almost_equal(cheb.chebpts1(3), tgt)
603
+ tgt = [-0.9238795325, -0.3826834323, 0.3826834323, 0.9238795325]
604
+ assert_almost_equal(cheb.chebpts1(4), tgt)
605
+
606
+ def test_chebpts2(self):
607
+ #test exceptions
608
+ assert_raises(ValueError, cheb.chebpts2, 1.5)
609
+ assert_raises(ValueError, cheb.chebpts2, 1)
610
+
611
+ #test points
612
+ tgt = [-1, 1]
613
+ assert_almost_equal(cheb.chebpts2(2), tgt)
614
+ tgt = [-1, 0, 1]
615
+ assert_almost_equal(cheb.chebpts2(3), tgt)
616
+ tgt = [-1, -0.5, .5, 1]
617
+ assert_almost_equal(cheb.chebpts2(4), tgt)
618
+ tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0]
619
+ assert_almost_equal(cheb.chebpts2(5), tgt)
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_classes.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test inter-conversion of different polynomial classes.
2
+
3
+ This tests the convert and cast methods of all the polynomial classes.
4
+
5
+ """
6
+ import operator as op
7
+ from numbers import Number
8
+
9
+ import pytest
10
+ import numpy as np
11
+ from numpy.polynomial import (
12
+ Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE)
13
+ from numpy.testing import (
14
+ assert_almost_equal, assert_raises, assert_equal, assert_,
15
+ )
16
+ from numpy.polynomial.polyutils import RankWarning
17
+
18
+ #
19
+ # fixtures
20
+ #
21
+
22
+ classes = (
23
+ Polynomial, Legendre, Chebyshev, Laguerre,
24
+ Hermite, HermiteE
25
+ )
26
+ classids = tuple(cls.__name__ for cls in classes)
27
+
28
+ @pytest.fixture(params=classes, ids=classids)
29
+ def Poly(request):
30
+ return request.param
31
+
32
+ #
33
+ # helper functions
34
+ #
35
+ random = np.random.random
36
+
37
+
38
+ def assert_poly_almost_equal(p1, p2, msg=""):
39
+ try:
40
+ assert_(np.all(p1.domain == p2.domain))
41
+ assert_(np.all(p1.window == p2.window))
42
+ assert_almost_equal(p1.coef, p2.coef)
43
+ except AssertionError:
44
+ msg = f"Result: {p1}\nTarget: {p2}"
45
+ raise AssertionError(msg)
46
+
47
+
48
+ #
49
+ # Test conversion methods that depend on combinations of two classes.
50
+ #
51
+
52
+ Poly1 = Poly
53
+ Poly2 = Poly
54
+
55
+
56
+ def test_conversion(Poly1, Poly2):
57
+ x = np.linspace(0, 1, 10)
58
+ coef = random((3,))
59
+
60
+ d1 = Poly1.domain + random((2,))*.25
61
+ w1 = Poly1.window + random((2,))*.25
62
+ p1 = Poly1(coef, domain=d1, window=w1)
63
+
64
+ d2 = Poly2.domain + random((2,))*.25
65
+ w2 = Poly2.window + random((2,))*.25
66
+ p2 = p1.convert(kind=Poly2, domain=d2, window=w2)
67
+
68
+ assert_almost_equal(p2.domain, d2)
69
+ assert_almost_equal(p2.window, w2)
70
+ assert_almost_equal(p2(x), p1(x))
71
+
72
+
73
+ def test_cast(Poly1, Poly2):
74
+ x = np.linspace(0, 1, 10)
75
+ coef = random((3,))
76
+
77
+ d1 = Poly1.domain + random((2,))*.25
78
+ w1 = Poly1.window + random((2,))*.25
79
+ p1 = Poly1(coef, domain=d1, window=w1)
80
+
81
+ d2 = Poly2.domain + random((2,))*.25
82
+ w2 = Poly2.window + random((2,))*.25
83
+ p2 = Poly2.cast(p1, domain=d2, window=w2)
84
+
85
+ assert_almost_equal(p2.domain, d2)
86
+ assert_almost_equal(p2.window, w2)
87
+ assert_almost_equal(p2(x), p1(x))
88
+
89
+
90
+ #
91
+ # test methods that depend on one class
92
+ #
93
+
94
+
95
+ def test_identity(Poly):
96
+ d = Poly.domain + random((2,))*.25
97
+ w = Poly.window + random((2,))*.25
98
+ x = np.linspace(d[0], d[1], 11)
99
+ p = Poly.identity(domain=d, window=w)
100
+ assert_equal(p.domain, d)
101
+ assert_equal(p.window, w)
102
+ assert_almost_equal(p(x), x)
103
+
104
+
105
+ def test_basis(Poly):
106
+ d = Poly.domain + random((2,))*.25
107
+ w = Poly.window + random((2,))*.25
108
+ p = Poly.basis(5, domain=d, window=w)
109
+ assert_equal(p.domain, d)
110
+ assert_equal(p.window, w)
111
+ assert_equal(p.coef, [0]*5 + [1])
112
+
113
+
114
+ def test_fromroots(Poly):
115
+ # check that requested roots are zeros of a polynomial
116
+ # of correct degree, domain, and window.
117
+ d = Poly.domain + random((2,))*.25
118
+ w = Poly.window + random((2,))*.25
119
+ r = random((5,))
120
+ p1 = Poly.fromroots(r, domain=d, window=w)
121
+ assert_equal(p1.degree(), len(r))
122
+ assert_equal(p1.domain, d)
123
+ assert_equal(p1.window, w)
124
+ assert_almost_equal(p1(r), 0)
125
+
126
+ # check that polynomial is monic
127
+ pdom = Polynomial.domain
128
+ pwin = Polynomial.window
129
+ p2 = Polynomial.cast(p1, domain=pdom, window=pwin)
130
+ assert_almost_equal(p2.coef[-1], 1)
131
+
132
+
133
+ def test_bad_conditioned_fit(Poly):
134
+
135
+ x = [0., 0., 1.]
136
+ y = [1., 2., 3.]
137
+
138
+ # check RankWarning is raised
139
+ with pytest.warns(RankWarning) as record:
140
+ Poly.fit(x, y, 2)
141
+ assert record[0].message.args[0] == "The fit may be poorly conditioned"
142
+
143
+
144
+ def test_fit(Poly):
145
+
146
+ def f(x):
147
+ return x*(x - 1)*(x - 2)
148
+ x = np.linspace(0, 3)
149
+ y = f(x)
150
+
151
+ # check default value of domain and window
152
+ p = Poly.fit(x, y, 3)
153
+ assert_almost_equal(p.domain, [0, 3])
154
+ assert_almost_equal(p(x), y)
155
+ assert_equal(p.degree(), 3)
156
+
157
+ # check with given domains and window
158
+ d = Poly.domain + random((2,))*.25
159
+ w = Poly.window + random((2,))*.25
160
+ p = Poly.fit(x, y, 3, domain=d, window=w)
161
+ assert_almost_equal(p(x), y)
162
+ assert_almost_equal(p.domain, d)
163
+ assert_almost_equal(p.window, w)
164
+ p = Poly.fit(x, y, [0, 1, 2, 3], domain=d, window=w)
165
+ assert_almost_equal(p(x), y)
166
+ assert_almost_equal(p.domain, d)
167
+ assert_almost_equal(p.window, w)
168
+
169
+ # check with class domain default
170
+ p = Poly.fit(x, y, 3, [])
171
+ assert_equal(p.domain, Poly.domain)
172
+ assert_equal(p.window, Poly.window)
173
+ p = Poly.fit(x, y, [0, 1, 2, 3], [])
174
+ assert_equal(p.domain, Poly.domain)
175
+ assert_equal(p.window, Poly.window)
176
+
177
+ # check that fit accepts weights.
178
+ w = np.zeros_like(x)
179
+ z = y + random(y.shape)*.25
180
+ w[::2] = 1
181
+ p1 = Poly.fit(x[::2], z[::2], 3)
182
+ p2 = Poly.fit(x, z, 3, w=w)
183
+ p3 = Poly.fit(x, z, [0, 1, 2, 3], w=w)
184
+ assert_almost_equal(p1(x), p2(x))
185
+ assert_almost_equal(p2(x), p3(x))
186
+
187
+
188
+ def test_equal(Poly):
189
+ p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3])
190
+ p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3])
191
+ p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3])
192
+ p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2])
193
+ assert_(p1 == p1)
194
+ assert_(not p1 == p2)
195
+ assert_(not p1 == p3)
196
+ assert_(not p1 == p4)
197
+
198
+
199
+ def test_not_equal(Poly):
200
+ p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3])
201
+ p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3])
202
+ p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3])
203
+ p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2])
204
+ assert_(not p1 != p1)
205
+ assert_(p1 != p2)
206
+ assert_(p1 != p3)
207
+ assert_(p1 != p4)
208
+
209
+
210
+ def test_add(Poly):
211
+ # This checks commutation, not numerical correctness
212
+ c1 = list(random((4,)) + .5)
213
+ c2 = list(random((3,)) + .5)
214
+ p1 = Poly(c1)
215
+ p2 = Poly(c2)
216
+ p3 = p1 + p2
217
+ assert_poly_almost_equal(p2 + p1, p3)
218
+ assert_poly_almost_equal(p1 + c2, p3)
219
+ assert_poly_almost_equal(c2 + p1, p3)
220
+ assert_poly_almost_equal(p1 + tuple(c2), p3)
221
+ assert_poly_almost_equal(tuple(c2) + p1, p3)
222
+ assert_poly_almost_equal(p1 + np.array(c2), p3)
223
+ assert_poly_almost_equal(np.array(c2) + p1, p3)
224
+ assert_raises(TypeError, op.add, p1, Poly([0], domain=Poly.domain + 1))
225
+ assert_raises(TypeError, op.add, p1, Poly([0], window=Poly.window + 1))
226
+ if Poly is Polynomial:
227
+ assert_raises(TypeError, op.add, p1, Chebyshev([0]))
228
+ else:
229
+ assert_raises(TypeError, op.add, p1, Polynomial([0]))
230
+
231
+
232
+ def test_sub(Poly):
233
+ # This checks commutation, not numerical correctness
234
+ c1 = list(random((4,)) + .5)
235
+ c2 = list(random((3,)) + .5)
236
+ p1 = Poly(c1)
237
+ p2 = Poly(c2)
238
+ p3 = p1 - p2
239
+ assert_poly_almost_equal(p2 - p1, -p3)
240
+ assert_poly_almost_equal(p1 - c2, p3)
241
+ assert_poly_almost_equal(c2 - p1, -p3)
242
+ assert_poly_almost_equal(p1 - tuple(c2), p3)
243
+ assert_poly_almost_equal(tuple(c2) - p1, -p3)
244
+ assert_poly_almost_equal(p1 - np.array(c2), p3)
245
+ assert_poly_almost_equal(np.array(c2) - p1, -p3)
246
+ assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1))
247
+ assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1))
248
+ if Poly is Polynomial:
249
+ assert_raises(TypeError, op.sub, p1, Chebyshev([0]))
250
+ else:
251
+ assert_raises(TypeError, op.sub, p1, Polynomial([0]))
252
+
253
+
254
+ def test_mul(Poly):
255
+ c1 = list(random((4,)) + .5)
256
+ c2 = list(random((3,)) + .5)
257
+ p1 = Poly(c1)
258
+ p2 = Poly(c2)
259
+ p3 = p1 * p2
260
+ assert_poly_almost_equal(p2 * p1, p3)
261
+ assert_poly_almost_equal(p1 * c2, p3)
262
+ assert_poly_almost_equal(c2 * p1, p3)
263
+ assert_poly_almost_equal(p1 * tuple(c2), p3)
264
+ assert_poly_almost_equal(tuple(c2) * p1, p3)
265
+ assert_poly_almost_equal(p1 * np.array(c2), p3)
266
+ assert_poly_almost_equal(np.array(c2) * p1, p3)
267
+ assert_poly_almost_equal(p1 * 2, p1 * Poly([2]))
268
+ assert_poly_almost_equal(2 * p1, p1 * Poly([2]))
269
+ assert_raises(TypeError, op.mul, p1, Poly([0], domain=Poly.domain + 1))
270
+ assert_raises(TypeError, op.mul, p1, Poly([0], window=Poly.window + 1))
271
+ if Poly is Polynomial:
272
+ assert_raises(TypeError, op.mul, p1, Chebyshev([0]))
273
+ else:
274
+ assert_raises(TypeError, op.mul, p1, Polynomial([0]))
275
+
276
+
277
+ def test_floordiv(Poly):
278
+ c1 = list(random((4,)) + .5)
279
+ c2 = list(random((3,)) + .5)
280
+ c3 = list(random((2,)) + .5)
281
+ p1 = Poly(c1)
282
+ p2 = Poly(c2)
283
+ p3 = Poly(c3)
284
+ p4 = p1 * p2 + p3
285
+ c4 = list(p4.coef)
286
+ assert_poly_almost_equal(p4 // p2, p1)
287
+ assert_poly_almost_equal(p4 // c2, p1)
288
+ assert_poly_almost_equal(c4 // p2, p1)
289
+ assert_poly_almost_equal(p4 // tuple(c2), p1)
290
+ assert_poly_almost_equal(tuple(c4) // p2, p1)
291
+ assert_poly_almost_equal(p4 // np.array(c2), p1)
292
+ assert_poly_almost_equal(np.array(c4) // p2, p1)
293
+ assert_poly_almost_equal(2 // p2, Poly([0]))
294
+ assert_poly_almost_equal(p2 // 2, 0.5*p2)
295
+ assert_raises(
296
+ TypeError, op.floordiv, p1, Poly([0], domain=Poly.domain + 1))
297
+ assert_raises(
298
+ TypeError, op.floordiv, p1, Poly([0], window=Poly.window + 1))
299
+ if Poly is Polynomial:
300
+ assert_raises(TypeError, op.floordiv, p1, Chebyshev([0]))
301
+ else:
302
+ assert_raises(TypeError, op.floordiv, p1, Polynomial([0]))
303
+
304
+
305
+ def test_truediv(Poly):
306
+ # true division is valid only if the denominator is a Number and
307
+ # not a python bool.
308
+ p1 = Poly([1,2,3])
309
+ p2 = p1 * 5
310
+
311
+ for stype in np.ScalarType:
312
+ if not issubclass(stype, Number) or issubclass(stype, bool):
313
+ continue
314
+ s = stype(5)
315
+ assert_poly_almost_equal(op.truediv(p2, s), p1)
316
+ assert_raises(TypeError, op.truediv, s, p2)
317
+ for stype in (int, float):
318
+ s = stype(5)
319
+ assert_poly_almost_equal(op.truediv(p2, s), p1)
320
+ assert_raises(TypeError, op.truediv, s, p2)
321
+ for stype in [complex]:
322
+ s = stype(5, 0)
323
+ assert_poly_almost_equal(op.truediv(p2, s), p1)
324
+ assert_raises(TypeError, op.truediv, s, p2)
325
+ for s in [tuple(), list(), dict(), bool(), np.array([1])]:
326
+ assert_raises(TypeError, op.truediv, p2, s)
327
+ assert_raises(TypeError, op.truediv, s, p2)
328
+ for ptype in classes:
329
+ assert_raises(TypeError, op.truediv, p2, ptype(1))
330
+
331
+
332
+ def test_mod(Poly):
333
+ # This checks commutation, not numerical correctness
334
+ c1 = list(random((4,)) + .5)
335
+ c2 = list(random((3,)) + .5)
336
+ c3 = list(random((2,)) + .5)
337
+ p1 = Poly(c1)
338
+ p2 = Poly(c2)
339
+ p3 = Poly(c3)
340
+ p4 = p1 * p2 + p3
341
+ c4 = list(p4.coef)
342
+ assert_poly_almost_equal(p4 % p2, p3)
343
+ assert_poly_almost_equal(p4 % c2, p3)
344
+ assert_poly_almost_equal(c4 % p2, p3)
345
+ assert_poly_almost_equal(p4 % tuple(c2), p3)
346
+ assert_poly_almost_equal(tuple(c4) % p2, p3)
347
+ assert_poly_almost_equal(p4 % np.array(c2), p3)
348
+ assert_poly_almost_equal(np.array(c4) % p2, p3)
349
+ assert_poly_almost_equal(2 % p2, Poly([2]))
350
+ assert_poly_almost_equal(p2 % 2, Poly([0]))
351
+ assert_raises(TypeError, op.mod, p1, Poly([0], domain=Poly.domain + 1))
352
+ assert_raises(TypeError, op.mod, p1, Poly([0], window=Poly.window + 1))
353
+ if Poly is Polynomial:
354
+ assert_raises(TypeError, op.mod, p1, Chebyshev([0]))
355
+ else:
356
+ assert_raises(TypeError, op.mod, p1, Polynomial([0]))
357
+
358
+
359
+ def test_divmod(Poly):
360
+ # This checks commutation, not numerical correctness
361
+ c1 = list(random((4,)) + .5)
362
+ c2 = list(random((3,)) + .5)
363
+ c3 = list(random((2,)) + .5)
364
+ p1 = Poly(c1)
365
+ p2 = Poly(c2)
366
+ p3 = Poly(c3)
367
+ p4 = p1 * p2 + p3
368
+ c4 = list(p4.coef)
369
+ quo, rem = divmod(p4, p2)
370
+ assert_poly_almost_equal(quo, p1)
371
+ assert_poly_almost_equal(rem, p3)
372
+ quo, rem = divmod(p4, c2)
373
+ assert_poly_almost_equal(quo, p1)
374
+ assert_poly_almost_equal(rem, p3)
375
+ quo, rem = divmod(c4, p2)
376
+ assert_poly_almost_equal(quo, p1)
377
+ assert_poly_almost_equal(rem, p3)
378
+ quo, rem = divmod(p4, tuple(c2))
379
+ assert_poly_almost_equal(quo, p1)
380
+ assert_poly_almost_equal(rem, p3)
381
+ quo, rem = divmod(tuple(c4), p2)
382
+ assert_poly_almost_equal(quo, p1)
383
+ assert_poly_almost_equal(rem, p3)
384
+ quo, rem = divmod(p4, np.array(c2))
385
+ assert_poly_almost_equal(quo, p1)
386
+ assert_poly_almost_equal(rem, p3)
387
+ quo, rem = divmod(np.array(c4), p2)
388
+ assert_poly_almost_equal(quo, p1)
389
+ assert_poly_almost_equal(rem, p3)
390
+ quo, rem = divmod(p2, 2)
391
+ assert_poly_almost_equal(quo, 0.5*p2)
392
+ assert_poly_almost_equal(rem, Poly([0]))
393
+ quo, rem = divmod(2, p2)
394
+ assert_poly_almost_equal(quo, Poly([0]))
395
+ assert_poly_almost_equal(rem, Poly([2]))
396
+ assert_raises(TypeError, divmod, p1, Poly([0], domain=Poly.domain + 1))
397
+ assert_raises(TypeError, divmod, p1, Poly([0], window=Poly.window + 1))
398
+ if Poly is Polynomial:
399
+ assert_raises(TypeError, divmod, p1, Chebyshev([0]))
400
+ else:
401
+ assert_raises(TypeError, divmod, p1, Polynomial([0]))
402
+
403
+
404
+ def test_roots(Poly):
405
+ d = Poly.domain * 1.25 + .25
406
+ w = Poly.window
407
+ tgt = np.linspace(d[0], d[1], 5)
408
+ res = np.sort(Poly.fromroots(tgt, domain=d, window=w).roots())
409
+ assert_almost_equal(res, tgt)
410
+ # default domain and window
411
+ res = np.sort(Poly.fromroots(tgt).roots())
412
+ assert_almost_equal(res, tgt)
413
+
414
+
415
+ def test_degree(Poly):
416
+ p = Poly.basis(5)
417
+ assert_equal(p.degree(), 5)
418
+
419
+
420
+ def test_copy(Poly):
421
+ p1 = Poly.basis(5)
422
+ p2 = p1.copy()
423
+ assert_(p1 == p2)
424
+ assert_(p1 is not p2)
425
+ assert_(p1.coef is not p2.coef)
426
+ assert_(p1.domain is not p2.domain)
427
+ assert_(p1.window is not p2.window)
428
+
429
+
430
+ def test_integ(Poly):
431
+ P = Polynomial
432
+ # Check defaults
433
+ p0 = Poly.cast(P([1*2, 2*3, 3*4]))
434
+ p1 = P.cast(p0.integ())
435
+ p2 = P.cast(p0.integ(2))
436
+ assert_poly_almost_equal(p1, P([0, 2, 3, 4]))
437
+ assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1]))
438
+ # Check with k
439
+ p0 = Poly.cast(P([1*2, 2*3, 3*4]))
440
+ p1 = P.cast(p0.integ(k=1))
441
+ p2 = P.cast(p0.integ(2, k=[1, 1]))
442
+ assert_poly_almost_equal(p1, P([1, 2, 3, 4]))
443
+ assert_poly_almost_equal(p2, P([1, 1, 1, 1, 1]))
444
+ # Check with lbnd
445
+ p0 = Poly.cast(P([1*2, 2*3, 3*4]))
446
+ p1 = P.cast(p0.integ(lbnd=1))
447
+ p2 = P.cast(p0.integ(2, lbnd=1))
448
+ assert_poly_almost_equal(p1, P([-9, 2, 3, 4]))
449
+ assert_poly_almost_equal(p2, P([6, -9, 1, 1, 1]))
450
+ # Check scaling
451
+ d = 2*Poly.domain
452
+ p0 = Poly.cast(P([1*2, 2*3, 3*4]), domain=d)
453
+ p1 = P.cast(p0.integ())
454
+ p2 = P.cast(p0.integ(2))
455
+ assert_poly_almost_equal(p1, P([0, 2, 3, 4]))
456
+ assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1]))
457
+
458
+
459
+ def test_deriv(Poly):
460
+ # Check that the derivative is the inverse of integration. It is
461
+ # assumes that the integration has been checked elsewhere.
462
+ d = Poly.domain + random((2,))*.25
463
+ w = Poly.window + random((2,))*.25
464
+ p1 = Poly([1, 2, 3], domain=d, window=w)
465
+ p2 = p1.integ(2, k=[1, 2])
466
+ p3 = p1.integ(1, k=[1])
467
+ assert_almost_equal(p2.deriv(1).coef, p3.coef)
468
+ assert_almost_equal(p2.deriv(2).coef, p1.coef)
469
+ # default domain and window
470
+ p1 = Poly([1, 2, 3])
471
+ p2 = p1.integ(2, k=[1, 2])
472
+ p3 = p1.integ(1, k=[1])
473
+ assert_almost_equal(p2.deriv(1).coef, p3.coef)
474
+ assert_almost_equal(p2.deriv(2).coef, p1.coef)
475
+
476
+
477
+ def test_linspace(Poly):
478
+ d = Poly.domain + random((2,))*.25
479
+ w = Poly.window + random((2,))*.25
480
+ p = Poly([1, 2, 3], domain=d, window=w)
481
+ # check default domain
482
+ xtgt = np.linspace(d[0], d[1], 20)
483
+ ytgt = p(xtgt)
484
+ xres, yres = p.linspace(20)
485
+ assert_almost_equal(xres, xtgt)
486
+ assert_almost_equal(yres, ytgt)
487
+ # check specified domain
488
+ xtgt = np.linspace(0, 2, 20)
489
+ ytgt = p(xtgt)
490
+ xres, yres = p.linspace(20, domain=[0, 2])
491
+ assert_almost_equal(xres, xtgt)
492
+ assert_almost_equal(yres, ytgt)
493
+
494
+
495
+ def test_pow(Poly):
496
+ d = Poly.domain + random((2,))*.25
497
+ w = Poly.window + random((2,))*.25
498
+ tgt = Poly([1], domain=d, window=w)
499
+ tst = Poly([1, 2, 3], domain=d, window=w)
500
+ for i in range(5):
501
+ assert_poly_almost_equal(tst**i, tgt)
502
+ tgt = tgt * tst
503
+ # default domain and window
504
+ tgt = Poly([1])
505
+ tst = Poly([1, 2, 3])
506
+ for i in range(5):
507
+ assert_poly_almost_equal(tst**i, tgt)
508
+ tgt = tgt * tst
509
+ # check error for invalid powers
510
+ assert_raises(ValueError, op.pow, tgt, 1.5)
511
+ assert_raises(ValueError, op.pow, tgt, -1)
512
+
513
+
514
+ def test_call(Poly):
515
+ P = Polynomial
516
+ d = Poly.domain
517
+ x = np.linspace(d[0], d[1], 11)
518
+
519
+ # Check defaults
520
+ p = Poly.cast(P([1, 2, 3]))
521
+ tgt = 1 + x*(2 + 3*x)
522
+ res = p(x)
523
+ assert_almost_equal(res, tgt)
524
+
525
+
526
+ def test_cutdeg(Poly):
527
+ p = Poly([1, 2, 3])
528
+ assert_raises(ValueError, p.cutdeg, .5)
529
+ assert_raises(ValueError, p.cutdeg, -1)
530
+ assert_equal(len(p.cutdeg(3)), 3)
531
+ assert_equal(len(p.cutdeg(2)), 3)
532
+ assert_equal(len(p.cutdeg(1)), 2)
533
+ assert_equal(len(p.cutdeg(0)), 1)
534
+
535
+
536
+ def test_truncate(Poly):
537
+ p = Poly([1, 2, 3])
538
+ assert_raises(ValueError, p.truncate, .5)
539
+ assert_raises(ValueError, p.truncate, 0)
540
+ assert_equal(len(p.truncate(4)), 3)
541
+ assert_equal(len(p.truncate(3)), 3)
542
+ assert_equal(len(p.truncate(2)), 2)
543
+ assert_equal(len(p.truncate(1)), 1)
544
+
545
+
546
+ def test_trim(Poly):
547
+ c = [1, 1e-6, 1e-12, 0]
548
+ p = Poly(c)
549
+ assert_equal(p.trim().coef, c[:3])
550
+ assert_equal(p.trim(1e-10).coef, c[:2])
551
+ assert_equal(p.trim(1e-5).coef, c[:1])
552
+
553
+
554
+ def test_mapparms(Poly):
555
+ # check with defaults. Should be identity.
556
+ d = Poly.domain
557
+ w = Poly.window
558
+ p = Poly([1], domain=d, window=w)
559
+ assert_almost_equal([0, 1], p.mapparms())
560
+ #
561
+ w = 2*d + 1
562
+ p = Poly([1], domain=d, window=w)
563
+ assert_almost_equal([1, 2], p.mapparms())
564
+
565
+
566
+ def test_ufunc_override(Poly):
567
+ p = Poly([1, 2, 3])
568
+ x = np.ones(3)
569
+ assert_raises(TypeError, np.add, p, x)
570
+ assert_raises(TypeError, np.add, x, p)
571
+
572
+
573
+ #
574
+ # Test class method that only exists for some classes
575
+ #
576
+
577
+
578
+ class TestInterpolate:
579
+
580
+ def f(self, x):
581
+ return x * (x - 1) * (x - 2)
582
+
583
+ def test_raises(self):
584
+ assert_raises(ValueError, Chebyshev.interpolate, self.f, -1)
585
+ assert_raises(TypeError, Chebyshev.interpolate, self.f, 10.)
586
+
587
+ def test_dimensions(self):
588
+ for deg in range(1, 5):
589
+ assert_(Chebyshev.interpolate(self.f, deg).degree() == deg)
590
+
591
+ def test_approximation(self):
592
+
593
+ def powx(x, p):
594
+ return x**p
595
+
596
+ x = np.linspace(0, 2, 10)
597
+ for deg in range(0, 10):
598
+ for t in range(0, deg + 1):
599
+ p = Chebyshev.interpolate(powx, deg, domain=[0, 2], args=(t,))
600
+ assert_almost_equal(p(x), powx(x, t), decimal=11)
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_hermite.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for hermite module.
2
+
3
+ """
4
+ from functools import reduce
5
+
6
+ import numpy as np
7
+ import numpy.polynomial.hermite as herm
8
+ from numpy.polynomial.polynomial import polyval
9
+ from numpy.testing import (
10
+ assert_almost_equal, assert_raises, assert_equal, assert_,
11
+ )
12
+
13
+ H0 = np.array([1])
14
+ H1 = np.array([0, 2])
15
+ H2 = np.array([-2, 0, 4])
16
+ H3 = np.array([0, -12, 0, 8])
17
+ H4 = np.array([12, 0, -48, 0, 16])
18
+ H5 = np.array([0, 120, 0, -160, 0, 32])
19
+ H6 = np.array([-120, 0, 720, 0, -480, 0, 64])
20
+ H7 = np.array([0, -1680, 0, 3360, 0, -1344, 0, 128])
21
+ H8 = np.array([1680, 0, -13440, 0, 13440, 0, -3584, 0, 256])
22
+ H9 = np.array([0, 30240, 0, -80640, 0, 48384, 0, -9216, 0, 512])
23
+
24
+ Hlist = [H0, H1, H2, H3, H4, H5, H6, H7, H8, H9]
25
+
26
+
27
+ def trim(x):
28
+ return herm.hermtrim(x, tol=1e-6)
29
+
30
+
31
+ class TestConstants:
32
+
33
+ def test_hermdomain(self):
34
+ assert_equal(herm.hermdomain, [-1, 1])
35
+
36
+ def test_hermzero(self):
37
+ assert_equal(herm.hermzero, [0])
38
+
39
+ def test_hermone(self):
40
+ assert_equal(herm.hermone, [1])
41
+
42
+ def test_hermx(self):
43
+ assert_equal(herm.hermx, [0, .5])
44
+
45
+
46
+ class TestArithmetic:
47
+ x = np.linspace(-3, 3, 100)
48
+
49
+ def test_hermadd(self):
50
+ for i in range(5):
51
+ for j in range(5):
52
+ msg = f"At i={i}, j={j}"
53
+ tgt = np.zeros(max(i, j) + 1)
54
+ tgt[i] += 1
55
+ tgt[j] += 1
56
+ res = herm.hermadd([0]*i + [1], [0]*j + [1])
57
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
58
+
59
+ def test_hermsub(self):
60
+ for i in range(5):
61
+ for j in range(5):
62
+ msg = f"At i={i}, j={j}"
63
+ tgt = np.zeros(max(i, j) + 1)
64
+ tgt[i] += 1
65
+ tgt[j] -= 1
66
+ res = herm.hermsub([0]*i + [1], [0]*j + [1])
67
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
68
+
69
+ def test_hermmulx(self):
70
+ assert_equal(herm.hermmulx([0]), [0])
71
+ assert_equal(herm.hermmulx([1]), [0, .5])
72
+ for i in range(1, 5):
73
+ ser = [0]*i + [1]
74
+ tgt = [0]*(i - 1) + [i, 0, .5]
75
+ assert_equal(herm.hermmulx(ser), tgt)
76
+
77
+ def test_hermmul(self):
78
+ # check values of result
79
+ for i in range(5):
80
+ pol1 = [0]*i + [1]
81
+ val1 = herm.hermval(self.x, pol1)
82
+ for j in range(5):
83
+ msg = f"At i={i}, j={j}"
84
+ pol2 = [0]*j + [1]
85
+ val2 = herm.hermval(self.x, pol2)
86
+ pol3 = herm.hermmul(pol1, pol2)
87
+ val3 = herm.hermval(self.x, pol3)
88
+ assert_(len(pol3) == i + j + 1, msg)
89
+ assert_almost_equal(val3, val1*val2, err_msg=msg)
90
+
91
+ def test_hermdiv(self):
92
+ for i in range(5):
93
+ for j in range(5):
94
+ msg = f"At i={i}, j={j}"
95
+ ci = [0]*i + [1]
96
+ cj = [0]*j + [1]
97
+ tgt = herm.hermadd(ci, cj)
98
+ quo, rem = herm.hermdiv(tgt, ci)
99
+ res = herm.hermadd(herm.hermmul(quo, ci), rem)
100
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
101
+
102
+ def test_hermpow(self):
103
+ for i in range(5):
104
+ for j in range(5):
105
+ msg = f"At i={i}, j={j}"
106
+ c = np.arange(i + 1)
107
+ tgt = reduce(herm.hermmul, [c]*j, np.array([1]))
108
+ res = herm.hermpow(c, j)
109
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
110
+
111
+
112
+ class TestEvaluation:
113
+ # coefficients of 1 + 2*x + 3*x**2
114
+ c1d = np.array([2.5, 1., .75])
115
+ c2d = np.einsum('i,j->ij', c1d, c1d)
116
+ c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
117
+
118
+ # some random values in [-1, 1)
119
+ x = np.random.random((3, 5))*2 - 1
120
+ y = polyval(x, [1., 2., 3.])
121
+
122
+ def test_hermval(self):
123
+ #check empty input
124
+ assert_equal(herm.hermval([], [1]).size, 0)
125
+
126
+ #check normal input)
127
+ x = np.linspace(-1, 1)
128
+ y = [polyval(x, c) for c in Hlist]
129
+ for i in range(10):
130
+ msg = f"At i={i}"
131
+ tgt = y[i]
132
+ res = herm.hermval(x, [0]*i + [1])
133
+ assert_almost_equal(res, tgt, err_msg=msg)
134
+
135
+ #check that shape is preserved
136
+ for i in range(3):
137
+ dims = [2]*i
138
+ x = np.zeros(dims)
139
+ assert_equal(herm.hermval(x, [1]).shape, dims)
140
+ assert_equal(herm.hermval(x, [1, 0]).shape, dims)
141
+ assert_equal(herm.hermval(x, [1, 0, 0]).shape, dims)
142
+
143
+ def test_hermval2d(self):
144
+ x1, x2, x3 = self.x
145
+ y1, y2, y3 = self.y
146
+
147
+ #test exceptions
148
+ assert_raises(ValueError, herm.hermval2d, x1, x2[:2], self.c2d)
149
+
150
+ #test values
151
+ tgt = y1*y2
152
+ res = herm.hermval2d(x1, x2, self.c2d)
153
+ assert_almost_equal(res, tgt)
154
+
155
+ #test shape
156
+ z = np.ones((2, 3))
157
+ res = herm.hermval2d(z, z, self.c2d)
158
+ assert_(res.shape == (2, 3))
159
+
160
+ def test_hermval3d(self):
161
+ x1, x2, x3 = self.x
162
+ y1, y2, y3 = self.y
163
+
164
+ #test exceptions
165
+ assert_raises(ValueError, herm.hermval3d, x1, x2, x3[:2], self.c3d)
166
+
167
+ #test values
168
+ tgt = y1*y2*y3
169
+ res = herm.hermval3d(x1, x2, x3, self.c3d)
170
+ assert_almost_equal(res, tgt)
171
+
172
+ #test shape
173
+ z = np.ones((2, 3))
174
+ res = herm.hermval3d(z, z, z, self.c3d)
175
+ assert_(res.shape == (2, 3))
176
+
177
+ def test_hermgrid2d(self):
178
+ x1, x2, x3 = self.x
179
+ y1, y2, y3 = self.y
180
+
181
+ #test values
182
+ tgt = np.einsum('i,j->ij', y1, y2)
183
+ res = herm.hermgrid2d(x1, x2, self.c2d)
184
+ assert_almost_equal(res, tgt)
185
+
186
+ #test shape
187
+ z = np.ones((2, 3))
188
+ res = herm.hermgrid2d(z, z, self.c2d)
189
+ assert_(res.shape == (2, 3)*2)
190
+
191
+ def test_hermgrid3d(self):
192
+ x1, x2, x3 = self.x
193
+ y1, y2, y3 = self.y
194
+
195
+ #test values
196
+ tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
197
+ res = herm.hermgrid3d(x1, x2, x3, self.c3d)
198
+ assert_almost_equal(res, tgt)
199
+
200
+ #test shape
201
+ z = np.ones((2, 3))
202
+ res = herm.hermgrid3d(z, z, z, self.c3d)
203
+ assert_(res.shape == (2, 3)*3)
204
+
205
+
206
+ class TestIntegral:
207
+
208
+ def test_hermint(self):
209
+ # check exceptions
210
+ assert_raises(TypeError, herm.hermint, [0], .5)
211
+ assert_raises(ValueError, herm.hermint, [0], -1)
212
+ assert_raises(ValueError, herm.hermint, [0], 1, [0, 0])
213
+ assert_raises(ValueError, herm.hermint, [0], lbnd=[0])
214
+ assert_raises(ValueError, herm.hermint, [0], scl=[0])
215
+ assert_raises(TypeError, herm.hermint, [0], axis=.5)
216
+
217
+ # test integration of zero polynomial
218
+ for i in range(2, 5):
219
+ k = [0]*(i - 2) + [1]
220
+ res = herm.hermint([0], m=i, k=k)
221
+ assert_almost_equal(res, [0, .5])
222
+
223
+ # check single integration with integration constant
224
+ for i in range(5):
225
+ scl = i + 1
226
+ pol = [0]*i + [1]
227
+ tgt = [i] + [0]*i + [1/scl]
228
+ hermpol = herm.poly2herm(pol)
229
+ hermint = herm.hermint(hermpol, m=1, k=[i])
230
+ res = herm.herm2poly(hermint)
231
+ assert_almost_equal(trim(res), trim(tgt))
232
+
233
+ # check single integration with integration constant and lbnd
234
+ for i in range(5):
235
+ scl = i + 1
236
+ pol = [0]*i + [1]
237
+ hermpol = herm.poly2herm(pol)
238
+ hermint = herm.hermint(hermpol, m=1, k=[i], lbnd=-1)
239
+ assert_almost_equal(herm.hermval(-1, hermint), i)
240
+
241
+ # check single integration with integration constant and scaling
242
+ for i in range(5):
243
+ scl = i + 1
244
+ pol = [0]*i + [1]
245
+ tgt = [i] + [0]*i + [2/scl]
246
+ hermpol = herm.poly2herm(pol)
247
+ hermint = herm.hermint(hermpol, m=1, k=[i], scl=2)
248
+ res = herm.herm2poly(hermint)
249
+ assert_almost_equal(trim(res), trim(tgt))
250
+
251
+ # check multiple integrations with default k
252
+ for i in range(5):
253
+ for j in range(2, 5):
254
+ pol = [0]*i + [1]
255
+ tgt = pol[:]
256
+ for k in range(j):
257
+ tgt = herm.hermint(tgt, m=1)
258
+ res = herm.hermint(pol, m=j)
259
+ assert_almost_equal(trim(res), trim(tgt))
260
+
261
+ # check multiple integrations with defined k
262
+ for i in range(5):
263
+ for j in range(2, 5):
264
+ pol = [0]*i + [1]
265
+ tgt = pol[:]
266
+ for k in range(j):
267
+ tgt = herm.hermint(tgt, m=1, k=[k])
268
+ res = herm.hermint(pol, m=j, k=list(range(j)))
269
+ assert_almost_equal(trim(res), trim(tgt))
270
+
271
+ # check multiple integrations with lbnd
272
+ for i in range(5):
273
+ for j in range(2, 5):
274
+ pol = [0]*i + [1]
275
+ tgt = pol[:]
276
+ for k in range(j):
277
+ tgt = herm.hermint(tgt, m=1, k=[k], lbnd=-1)
278
+ res = herm.hermint(pol, m=j, k=list(range(j)), lbnd=-1)
279
+ assert_almost_equal(trim(res), trim(tgt))
280
+
281
+ # check multiple integrations with scaling
282
+ for i in range(5):
283
+ for j in range(2, 5):
284
+ pol = [0]*i + [1]
285
+ tgt = pol[:]
286
+ for k in range(j):
287
+ tgt = herm.hermint(tgt, m=1, k=[k], scl=2)
288
+ res = herm.hermint(pol, m=j, k=list(range(j)), scl=2)
289
+ assert_almost_equal(trim(res), trim(tgt))
290
+
291
+ def test_hermint_axis(self):
292
+ # check that axis keyword works
293
+ c2d = np.random.random((3, 4))
294
+
295
+ tgt = np.vstack([herm.hermint(c) for c in c2d.T]).T
296
+ res = herm.hermint(c2d, axis=0)
297
+ assert_almost_equal(res, tgt)
298
+
299
+ tgt = np.vstack([herm.hermint(c) for c in c2d])
300
+ res = herm.hermint(c2d, axis=1)
301
+ assert_almost_equal(res, tgt)
302
+
303
+ tgt = np.vstack([herm.hermint(c, k=3) for c in c2d])
304
+ res = herm.hermint(c2d, k=3, axis=1)
305
+ assert_almost_equal(res, tgt)
306
+
307
+
308
+ class TestDerivative:
309
+
310
+ def test_hermder(self):
311
+ # check exceptions
312
+ assert_raises(TypeError, herm.hermder, [0], .5)
313
+ assert_raises(ValueError, herm.hermder, [0], -1)
314
+
315
+ # check that zeroth derivative does nothing
316
+ for i in range(5):
317
+ tgt = [0]*i + [1]
318
+ res = herm.hermder(tgt, m=0)
319
+ assert_equal(trim(res), trim(tgt))
320
+
321
+ # check that derivation is the inverse of integration
322
+ for i in range(5):
323
+ for j in range(2, 5):
324
+ tgt = [0]*i + [1]
325
+ res = herm.hermder(herm.hermint(tgt, m=j), m=j)
326
+ assert_almost_equal(trim(res), trim(tgt))
327
+
328
+ # check derivation with scaling
329
+ for i in range(5):
330
+ for j in range(2, 5):
331
+ tgt = [0]*i + [1]
332
+ res = herm.hermder(herm.hermint(tgt, m=j, scl=2), m=j, scl=.5)
333
+ assert_almost_equal(trim(res), trim(tgt))
334
+
335
+ def test_hermder_axis(self):
336
+ # check that axis keyword works
337
+ c2d = np.random.random((3, 4))
338
+
339
+ tgt = np.vstack([herm.hermder(c) for c in c2d.T]).T
340
+ res = herm.hermder(c2d, axis=0)
341
+ assert_almost_equal(res, tgt)
342
+
343
+ tgt = np.vstack([herm.hermder(c) for c in c2d])
344
+ res = herm.hermder(c2d, axis=1)
345
+ assert_almost_equal(res, tgt)
346
+
347
+
348
+ class TestVander:
349
+ # some random values in [-1, 1)
350
+ x = np.random.random((3, 5))*2 - 1
351
+
352
+ def test_hermvander(self):
353
+ # check for 1d x
354
+ x = np.arange(3)
355
+ v = herm.hermvander(x, 3)
356
+ assert_(v.shape == (3, 4))
357
+ for i in range(4):
358
+ coef = [0]*i + [1]
359
+ assert_almost_equal(v[..., i], herm.hermval(x, coef))
360
+
361
+ # check for 2d x
362
+ x = np.array([[1, 2], [3, 4], [5, 6]])
363
+ v = herm.hermvander(x, 3)
364
+ assert_(v.shape == (3, 2, 4))
365
+ for i in range(4):
366
+ coef = [0]*i + [1]
367
+ assert_almost_equal(v[..., i], herm.hermval(x, coef))
368
+
369
+ def test_hermvander2d(self):
370
+ # also tests hermval2d for non-square coefficient array
371
+ x1, x2, x3 = self.x
372
+ c = np.random.random((2, 3))
373
+ van = herm.hermvander2d(x1, x2, [1, 2])
374
+ tgt = herm.hermval2d(x1, x2, c)
375
+ res = np.dot(van, c.flat)
376
+ assert_almost_equal(res, tgt)
377
+
378
+ # check shape
379
+ van = herm.hermvander2d([x1], [x2], [1, 2])
380
+ assert_(van.shape == (1, 5, 6))
381
+
382
+ def test_hermvander3d(self):
383
+ # also tests hermval3d for non-square coefficient array
384
+ x1, x2, x3 = self.x
385
+ c = np.random.random((2, 3, 4))
386
+ van = herm.hermvander3d(x1, x2, x3, [1, 2, 3])
387
+ tgt = herm.hermval3d(x1, x2, x3, c)
388
+ res = np.dot(van, c.flat)
389
+ assert_almost_equal(res, tgt)
390
+
391
+ # check shape
392
+ van = herm.hermvander3d([x1], [x2], [x3], [1, 2, 3])
393
+ assert_(van.shape == (1, 5, 24))
394
+
395
+
396
+ class TestFitting:
397
+
398
+ def test_hermfit(self):
399
+ def f(x):
400
+ return x*(x - 1)*(x - 2)
401
+
402
+ def f2(x):
403
+ return x**4 + x**2 + 1
404
+
405
+ # Test exceptions
406
+ assert_raises(ValueError, herm.hermfit, [1], [1], -1)
407
+ assert_raises(TypeError, herm.hermfit, [[1]], [1], 0)
408
+ assert_raises(TypeError, herm.hermfit, [], [1], 0)
409
+ assert_raises(TypeError, herm.hermfit, [1], [[[1]]], 0)
410
+ assert_raises(TypeError, herm.hermfit, [1, 2], [1], 0)
411
+ assert_raises(TypeError, herm.hermfit, [1], [1, 2], 0)
412
+ assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[[1]])
413
+ assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[1, 1])
414
+ assert_raises(ValueError, herm.hermfit, [1], [1], [-1,])
415
+ assert_raises(ValueError, herm.hermfit, [1], [1], [2, -1, 6])
416
+ assert_raises(TypeError, herm.hermfit, [1], [1], [])
417
+
418
+ # Test fit
419
+ x = np.linspace(0, 2)
420
+ y = f(x)
421
+ #
422
+ coef3 = herm.hermfit(x, y, 3)
423
+ assert_equal(len(coef3), 4)
424
+ assert_almost_equal(herm.hermval(x, coef3), y)
425
+ coef3 = herm.hermfit(x, y, [0, 1, 2, 3])
426
+ assert_equal(len(coef3), 4)
427
+ assert_almost_equal(herm.hermval(x, coef3), y)
428
+ #
429
+ coef4 = herm.hermfit(x, y, 4)
430
+ assert_equal(len(coef4), 5)
431
+ assert_almost_equal(herm.hermval(x, coef4), y)
432
+ coef4 = herm.hermfit(x, y, [0, 1, 2, 3, 4])
433
+ assert_equal(len(coef4), 5)
434
+ assert_almost_equal(herm.hermval(x, coef4), y)
435
+ # check things still work if deg is not in strict increasing
436
+ coef4 = herm.hermfit(x, y, [2, 3, 4, 1, 0])
437
+ assert_equal(len(coef4), 5)
438
+ assert_almost_equal(herm.hermval(x, coef4), y)
439
+ #
440
+ coef2d = herm.hermfit(x, np.array([y, y]).T, 3)
441
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
442
+ coef2d = herm.hermfit(x, np.array([y, y]).T, [0, 1, 2, 3])
443
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
444
+ # test weighting
445
+ w = np.zeros_like(x)
446
+ yw = y.copy()
447
+ w[1::2] = 1
448
+ y[0::2] = 0
449
+ wcoef3 = herm.hermfit(x, yw, 3, w=w)
450
+ assert_almost_equal(wcoef3, coef3)
451
+ wcoef3 = herm.hermfit(x, yw, [0, 1, 2, 3], w=w)
452
+ assert_almost_equal(wcoef3, coef3)
453
+ #
454
+ wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, 3, w=w)
455
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
456
+ wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
457
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
458
+ # test scaling with complex values x points whose square
459
+ # is zero when summed.
460
+ x = [1, 1j, -1, -1j]
461
+ assert_almost_equal(herm.hermfit(x, x, 1), [0, .5])
462
+ assert_almost_equal(herm.hermfit(x, x, [0, 1]), [0, .5])
463
+ # test fitting only even Legendre polynomials
464
+ x = np.linspace(-1, 1)
465
+ y = f2(x)
466
+ coef1 = herm.hermfit(x, y, 4)
467
+ assert_almost_equal(herm.hermval(x, coef1), y)
468
+ coef2 = herm.hermfit(x, y, [0, 2, 4])
469
+ assert_almost_equal(herm.hermval(x, coef2), y)
470
+ assert_almost_equal(coef1, coef2)
471
+
472
+
473
+ class TestCompanion:
474
+
475
+ def test_raises(self):
476
+ assert_raises(ValueError, herm.hermcompanion, [])
477
+ assert_raises(ValueError, herm.hermcompanion, [1])
478
+
479
+ def test_dimensions(self):
480
+ for i in range(1, 5):
481
+ coef = [0]*i + [1]
482
+ assert_(herm.hermcompanion(coef).shape == (i, i))
483
+
484
+ def test_linear_root(self):
485
+ assert_(herm.hermcompanion([1, 2])[0, 0] == -.25)
486
+
487
+
488
+ class TestGauss:
489
+
490
+ def test_100(self):
491
+ x, w = herm.hermgauss(100)
492
+
493
+ # test orthogonality. Note that the results need to be normalized,
494
+ # otherwise the huge values that can arise from fast growing
495
+ # functions like Laguerre can be very confusing.
496
+ v = herm.hermvander(x, 99)
497
+ vv = np.dot(v.T * w, v)
498
+ vd = 1/np.sqrt(vv.diagonal())
499
+ vv = vd[:, None] * vv * vd
500
+ assert_almost_equal(vv, np.eye(100))
501
+
502
+ # check that the integral of 1 is correct
503
+ tgt = np.sqrt(np.pi)
504
+ assert_almost_equal(w.sum(), tgt)
505
+
506
+
507
+ class TestMisc:
508
+
509
+ def test_hermfromroots(self):
510
+ res = herm.hermfromroots([])
511
+ assert_almost_equal(trim(res), [1])
512
+ for i in range(1, 5):
513
+ roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
514
+ pol = herm.hermfromroots(roots)
515
+ res = herm.hermval(roots, pol)
516
+ tgt = 0
517
+ assert_(len(pol) == i + 1)
518
+ assert_almost_equal(herm.herm2poly(pol)[-1], 1)
519
+ assert_almost_equal(res, tgt)
520
+
521
+ def test_hermroots(self):
522
+ assert_almost_equal(herm.hermroots([1]), [])
523
+ assert_almost_equal(herm.hermroots([1, 1]), [-.5])
524
+ for i in range(2, 5):
525
+ tgt = np.linspace(-1, 1, i)
526
+ res = herm.hermroots(herm.hermfromroots(tgt))
527
+ assert_almost_equal(trim(res), trim(tgt))
528
+
529
+ def test_hermtrim(self):
530
+ coef = [2, -1, 1, 0]
531
+
532
+ # Test exceptions
533
+ assert_raises(ValueError, herm.hermtrim, coef, -1)
534
+
535
+ # Test results
536
+ assert_equal(herm.hermtrim(coef), coef[:-1])
537
+ assert_equal(herm.hermtrim(coef, 1), coef[:-3])
538
+ assert_equal(herm.hermtrim(coef, 2), [0])
539
+
540
+ def test_hermline(self):
541
+ assert_equal(herm.hermline(3, 4), [3, 2])
542
+
543
+ def test_herm2poly(self):
544
+ for i in range(10):
545
+ assert_almost_equal(herm.herm2poly([0]*i + [1]), Hlist[i])
546
+
547
+ def test_poly2herm(self):
548
+ for i in range(10):
549
+ assert_almost_equal(herm.poly2herm(Hlist[i]), [0]*i + [1])
550
+
551
+ def test_weight(self):
552
+ x = np.linspace(-5, 5, 11)
553
+ tgt = np.exp(-x**2)
554
+ res = herm.hermweight(x)
555
+ assert_almost_equal(res, tgt)
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_hermite_e.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for hermite_e module.
2
+
3
+ """
4
+ from functools import reduce
5
+
6
+ import numpy as np
7
+ import numpy.polynomial.hermite_e as herme
8
+ from numpy.polynomial.polynomial import polyval
9
+ from numpy.testing import (
10
+ assert_almost_equal, assert_raises, assert_equal, assert_,
11
+ )
12
+
13
+ He0 = np.array([1])
14
+ He1 = np.array([0, 1])
15
+ He2 = np.array([-1, 0, 1])
16
+ He3 = np.array([0, -3, 0, 1])
17
+ He4 = np.array([3, 0, -6, 0, 1])
18
+ He5 = np.array([0, 15, 0, -10, 0, 1])
19
+ He6 = np.array([-15, 0, 45, 0, -15, 0, 1])
20
+ He7 = np.array([0, -105, 0, 105, 0, -21, 0, 1])
21
+ He8 = np.array([105, 0, -420, 0, 210, 0, -28, 0, 1])
22
+ He9 = np.array([0, 945, 0, -1260, 0, 378, 0, -36, 0, 1])
23
+
24
+ Helist = [He0, He1, He2, He3, He4, He5, He6, He7, He8, He9]
25
+
26
+
27
+ def trim(x):
28
+ return herme.hermetrim(x, tol=1e-6)
29
+
30
+
31
+ class TestConstants:
32
+
33
+ def test_hermedomain(self):
34
+ assert_equal(herme.hermedomain, [-1, 1])
35
+
36
+ def test_hermezero(self):
37
+ assert_equal(herme.hermezero, [0])
38
+
39
+ def test_hermeone(self):
40
+ assert_equal(herme.hermeone, [1])
41
+
42
+ def test_hermex(self):
43
+ assert_equal(herme.hermex, [0, 1])
44
+
45
+
46
+ class TestArithmetic:
47
+ x = np.linspace(-3, 3, 100)
48
+
49
+ def test_hermeadd(self):
50
+ for i in range(5):
51
+ for j in range(5):
52
+ msg = f"At i={i}, j={j}"
53
+ tgt = np.zeros(max(i, j) + 1)
54
+ tgt[i] += 1
55
+ tgt[j] += 1
56
+ res = herme.hermeadd([0]*i + [1], [0]*j + [1])
57
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
58
+
59
+ def test_hermesub(self):
60
+ for i in range(5):
61
+ for j in range(5):
62
+ msg = f"At i={i}, j={j}"
63
+ tgt = np.zeros(max(i, j) + 1)
64
+ tgt[i] += 1
65
+ tgt[j] -= 1
66
+ res = herme.hermesub([0]*i + [1], [0]*j + [1])
67
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
68
+
69
+ def test_hermemulx(self):
70
+ assert_equal(herme.hermemulx([0]), [0])
71
+ assert_equal(herme.hermemulx([1]), [0, 1])
72
+ for i in range(1, 5):
73
+ ser = [0]*i + [1]
74
+ tgt = [0]*(i - 1) + [i, 0, 1]
75
+ assert_equal(herme.hermemulx(ser), tgt)
76
+
77
+ def test_hermemul(self):
78
+ # check values of result
79
+ for i in range(5):
80
+ pol1 = [0]*i + [1]
81
+ val1 = herme.hermeval(self.x, pol1)
82
+ for j in range(5):
83
+ msg = f"At i={i}, j={j}"
84
+ pol2 = [0]*j + [1]
85
+ val2 = herme.hermeval(self.x, pol2)
86
+ pol3 = herme.hermemul(pol1, pol2)
87
+ val3 = herme.hermeval(self.x, pol3)
88
+ assert_(len(pol3) == i + j + 1, msg)
89
+ assert_almost_equal(val3, val1*val2, err_msg=msg)
90
+
91
+ def test_hermediv(self):
92
+ for i in range(5):
93
+ for j in range(5):
94
+ msg = f"At i={i}, j={j}"
95
+ ci = [0]*i + [1]
96
+ cj = [0]*j + [1]
97
+ tgt = herme.hermeadd(ci, cj)
98
+ quo, rem = herme.hermediv(tgt, ci)
99
+ res = herme.hermeadd(herme.hermemul(quo, ci), rem)
100
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
101
+
102
+ def test_hermepow(self):
103
+ for i in range(5):
104
+ for j in range(5):
105
+ msg = f"At i={i}, j={j}"
106
+ c = np.arange(i + 1)
107
+ tgt = reduce(herme.hermemul, [c]*j, np.array([1]))
108
+ res = herme.hermepow(c, j)
109
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
110
+
111
+
112
+ class TestEvaluation:
113
+ # coefficients of 1 + 2*x + 3*x**2
114
+ c1d = np.array([4., 2., 3.])
115
+ c2d = np.einsum('i,j->ij', c1d, c1d)
116
+ c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
117
+
118
+ # some random values in [-1, 1)
119
+ x = np.random.random((3, 5))*2 - 1
120
+ y = polyval(x, [1., 2., 3.])
121
+
122
+ def test_hermeval(self):
123
+ #check empty input
124
+ assert_equal(herme.hermeval([], [1]).size, 0)
125
+
126
+ #check normal input)
127
+ x = np.linspace(-1, 1)
128
+ y = [polyval(x, c) for c in Helist]
129
+ for i in range(10):
130
+ msg = f"At i={i}"
131
+ tgt = y[i]
132
+ res = herme.hermeval(x, [0]*i + [1])
133
+ assert_almost_equal(res, tgt, err_msg=msg)
134
+
135
+ #check that shape is preserved
136
+ for i in range(3):
137
+ dims = [2]*i
138
+ x = np.zeros(dims)
139
+ assert_equal(herme.hermeval(x, [1]).shape, dims)
140
+ assert_equal(herme.hermeval(x, [1, 0]).shape, dims)
141
+ assert_equal(herme.hermeval(x, [1, 0, 0]).shape, dims)
142
+
143
+ def test_hermeval2d(self):
144
+ x1, x2, x3 = self.x
145
+ y1, y2, y3 = self.y
146
+
147
+ #test exceptions
148
+ assert_raises(ValueError, herme.hermeval2d, x1, x2[:2], self.c2d)
149
+
150
+ #test values
151
+ tgt = y1*y2
152
+ res = herme.hermeval2d(x1, x2, self.c2d)
153
+ assert_almost_equal(res, tgt)
154
+
155
+ #test shape
156
+ z = np.ones((2, 3))
157
+ res = herme.hermeval2d(z, z, self.c2d)
158
+ assert_(res.shape == (2, 3))
159
+
160
+ def test_hermeval3d(self):
161
+ x1, x2, x3 = self.x
162
+ y1, y2, y3 = self.y
163
+
164
+ #test exceptions
165
+ assert_raises(ValueError, herme.hermeval3d, x1, x2, x3[:2], self.c3d)
166
+
167
+ #test values
168
+ tgt = y1*y2*y3
169
+ res = herme.hermeval3d(x1, x2, x3, self.c3d)
170
+ assert_almost_equal(res, tgt)
171
+
172
+ #test shape
173
+ z = np.ones((2, 3))
174
+ res = herme.hermeval3d(z, z, z, self.c3d)
175
+ assert_(res.shape == (2, 3))
176
+
177
+ def test_hermegrid2d(self):
178
+ x1, x2, x3 = self.x
179
+ y1, y2, y3 = self.y
180
+
181
+ #test values
182
+ tgt = np.einsum('i,j->ij', y1, y2)
183
+ res = herme.hermegrid2d(x1, x2, self.c2d)
184
+ assert_almost_equal(res, tgt)
185
+
186
+ #test shape
187
+ z = np.ones((2, 3))
188
+ res = herme.hermegrid2d(z, z, self.c2d)
189
+ assert_(res.shape == (2, 3)*2)
190
+
191
+ def test_hermegrid3d(self):
192
+ x1, x2, x3 = self.x
193
+ y1, y2, y3 = self.y
194
+
195
+ #test values
196
+ tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
197
+ res = herme.hermegrid3d(x1, x2, x3, self.c3d)
198
+ assert_almost_equal(res, tgt)
199
+
200
+ #test shape
201
+ z = np.ones((2, 3))
202
+ res = herme.hermegrid3d(z, z, z, self.c3d)
203
+ assert_(res.shape == (2, 3)*3)
204
+
205
+
206
+ class TestIntegral:
207
+
208
+ def test_hermeint(self):
209
+ # check exceptions
210
+ assert_raises(TypeError, herme.hermeint, [0], .5)
211
+ assert_raises(ValueError, herme.hermeint, [0], -1)
212
+ assert_raises(ValueError, herme.hermeint, [0], 1, [0, 0])
213
+ assert_raises(ValueError, herme.hermeint, [0], lbnd=[0])
214
+ assert_raises(ValueError, herme.hermeint, [0], scl=[0])
215
+ assert_raises(TypeError, herme.hermeint, [0], axis=.5)
216
+
217
+ # test integration of zero polynomial
218
+ for i in range(2, 5):
219
+ k = [0]*(i - 2) + [1]
220
+ res = herme.hermeint([0], m=i, k=k)
221
+ assert_almost_equal(res, [0, 1])
222
+
223
+ # check single integration with integration constant
224
+ for i in range(5):
225
+ scl = i + 1
226
+ pol = [0]*i + [1]
227
+ tgt = [i] + [0]*i + [1/scl]
228
+ hermepol = herme.poly2herme(pol)
229
+ hermeint = herme.hermeint(hermepol, m=1, k=[i])
230
+ res = herme.herme2poly(hermeint)
231
+ assert_almost_equal(trim(res), trim(tgt))
232
+
233
+ # check single integration with integration constant and lbnd
234
+ for i in range(5):
235
+ scl = i + 1
236
+ pol = [0]*i + [1]
237
+ hermepol = herme.poly2herme(pol)
238
+ hermeint = herme.hermeint(hermepol, m=1, k=[i], lbnd=-1)
239
+ assert_almost_equal(herme.hermeval(-1, hermeint), i)
240
+
241
+ # check single integration with integration constant and scaling
242
+ for i in range(5):
243
+ scl = i + 1
244
+ pol = [0]*i + [1]
245
+ tgt = [i] + [0]*i + [2/scl]
246
+ hermepol = herme.poly2herme(pol)
247
+ hermeint = herme.hermeint(hermepol, m=1, k=[i], scl=2)
248
+ res = herme.herme2poly(hermeint)
249
+ assert_almost_equal(trim(res), trim(tgt))
250
+
251
+ # check multiple integrations with default k
252
+ for i in range(5):
253
+ for j in range(2, 5):
254
+ pol = [0]*i + [1]
255
+ tgt = pol[:]
256
+ for k in range(j):
257
+ tgt = herme.hermeint(tgt, m=1)
258
+ res = herme.hermeint(pol, m=j)
259
+ assert_almost_equal(trim(res), trim(tgt))
260
+
261
+ # check multiple integrations with defined k
262
+ for i in range(5):
263
+ for j in range(2, 5):
264
+ pol = [0]*i + [1]
265
+ tgt = pol[:]
266
+ for k in range(j):
267
+ tgt = herme.hermeint(tgt, m=1, k=[k])
268
+ res = herme.hermeint(pol, m=j, k=list(range(j)))
269
+ assert_almost_equal(trim(res), trim(tgt))
270
+
271
+ # check multiple integrations with lbnd
272
+ for i in range(5):
273
+ for j in range(2, 5):
274
+ pol = [0]*i + [1]
275
+ tgt = pol[:]
276
+ for k in range(j):
277
+ tgt = herme.hermeint(tgt, m=1, k=[k], lbnd=-1)
278
+ res = herme.hermeint(pol, m=j, k=list(range(j)), lbnd=-1)
279
+ assert_almost_equal(trim(res), trim(tgt))
280
+
281
+ # check multiple integrations with scaling
282
+ for i in range(5):
283
+ for j in range(2, 5):
284
+ pol = [0]*i + [1]
285
+ tgt = pol[:]
286
+ for k in range(j):
287
+ tgt = herme.hermeint(tgt, m=1, k=[k], scl=2)
288
+ res = herme.hermeint(pol, m=j, k=list(range(j)), scl=2)
289
+ assert_almost_equal(trim(res), trim(tgt))
290
+
291
+ def test_hermeint_axis(self):
292
+ # check that axis keyword works
293
+ c2d = np.random.random((3, 4))
294
+
295
+ tgt = np.vstack([herme.hermeint(c) for c in c2d.T]).T
296
+ res = herme.hermeint(c2d, axis=0)
297
+ assert_almost_equal(res, tgt)
298
+
299
+ tgt = np.vstack([herme.hermeint(c) for c in c2d])
300
+ res = herme.hermeint(c2d, axis=1)
301
+ assert_almost_equal(res, tgt)
302
+
303
+ tgt = np.vstack([herme.hermeint(c, k=3) for c in c2d])
304
+ res = herme.hermeint(c2d, k=3, axis=1)
305
+ assert_almost_equal(res, tgt)
306
+
307
+
308
+ class TestDerivative:
309
+
310
+ def test_hermeder(self):
311
+ # check exceptions
312
+ assert_raises(TypeError, herme.hermeder, [0], .5)
313
+ assert_raises(ValueError, herme.hermeder, [0], -1)
314
+
315
+ # check that zeroth derivative does nothing
316
+ for i in range(5):
317
+ tgt = [0]*i + [1]
318
+ res = herme.hermeder(tgt, m=0)
319
+ assert_equal(trim(res), trim(tgt))
320
+
321
+ # check that derivation is the inverse of integration
322
+ for i in range(5):
323
+ for j in range(2, 5):
324
+ tgt = [0]*i + [1]
325
+ res = herme.hermeder(herme.hermeint(tgt, m=j), m=j)
326
+ assert_almost_equal(trim(res), trim(tgt))
327
+
328
+ # check derivation with scaling
329
+ for i in range(5):
330
+ for j in range(2, 5):
331
+ tgt = [0]*i + [1]
332
+ res = herme.hermeder(
333
+ herme.hermeint(tgt, m=j, scl=2), m=j, scl=.5)
334
+ assert_almost_equal(trim(res), trim(tgt))
335
+
336
+ def test_hermeder_axis(self):
337
+ # check that axis keyword works
338
+ c2d = np.random.random((3, 4))
339
+
340
+ tgt = np.vstack([herme.hermeder(c) for c in c2d.T]).T
341
+ res = herme.hermeder(c2d, axis=0)
342
+ assert_almost_equal(res, tgt)
343
+
344
+ tgt = np.vstack([herme.hermeder(c) for c in c2d])
345
+ res = herme.hermeder(c2d, axis=1)
346
+ assert_almost_equal(res, tgt)
347
+
348
+
349
+ class TestVander:
350
+ # some random values in [-1, 1)
351
+ x = np.random.random((3, 5))*2 - 1
352
+
353
+ def test_hermevander(self):
354
+ # check for 1d x
355
+ x = np.arange(3)
356
+ v = herme.hermevander(x, 3)
357
+ assert_(v.shape == (3, 4))
358
+ for i in range(4):
359
+ coef = [0]*i + [1]
360
+ assert_almost_equal(v[..., i], herme.hermeval(x, coef))
361
+
362
+ # check for 2d x
363
+ x = np.array([[1, 2], [3, 4], [5, 6]])
364
+ v = herme.hermevander(x, 3)
365
+ assert_(v.shape == (3, 2, 4))
366
+ for i in range(4):
367
+ coef = [0]*i + [1]
368
+ assert_almost_equal(v[..., i], herme.hermeval(x, coef))
369
+
370
+ def test_hermevander2d(self):
371
+ # also tests hermeval2d for non-square coefficient array
372
+ x1, x2, x3 = self.x
373
+ c = np.random.random((2, 3))
374
+ van = herme.hermevander2d(x1, x2, [1, 2])
375
+ tgt = herme.hermeval2d(x1, x2, c)
376
+ res = np.dot(van, c.flat)
377
+ assert_almost_equal(res, tgt)
378
+
379
+ # check shape
380
+ van = herme.hermevander2d([x1], [x2], [1, 2])
381
+ assert_(van.shape == (1, 5, 6))
382
+
383
+ def test_hermevander3d(self):
384
+ # also tests hermeval3d for non-square coefficient array
385
+ x1, x2, x3 = self.x
386
+ c = np.random.random((2, 3, 4))
387
+ van = herme.hermevander3d(x1, x2, x3, [1, 2, 3])
388
+ tgt = herme.hermeval3d(x1, x2, x3, c)
389
+ res = np.dot(van, c.flat)
390
+ assert_almost_equal(res, tgt)
391
+
392
+ # check shape
393
+ van = herme.hermevander3d([x1], [x2], [x3], [1, 2, 3])
394
+ assert_(van.shape == (1, 5, 24))
395
+
396
+
397
+ class TestFitting:
398
+
399
+ def test_hermefit(self):
400
+ def f(x):
401
+ return x*(x - 1)*(x - 2)
402
+
403
+ def f2(x):
404
+ return x**4 + x**2 + 1
405
+
406
+ # Test exceptions
407
+ assert_raises(ValueError, herme.hermefit, [1], [1], -1)
408
+ assert_raises(TypeError, herme.hermefit, [[1]], [1], 0)
409
+ assert_raises(TypeError, herme.hermefit, [], [1], 0)
410
+ assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0)
411
+ assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0)
412
+ assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0)
413
+ assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]])
414
+ assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1, 1])
415
+ assert_raises(ValueError, herme.hermefit, [1], [1], [-1,])
416
+ assert_raises(ValueError, herme.hermefit, [1], [1], [2, -1, 6])
417
+ assert_raises(TypeError, herme.hermefit, [1], [1], [])
418
+
419
+ # Test fit
420
+ x = np.linspace(0, 2)
421
+ y = f(x)
422
+ #
423
+ coef3 = herme.hermefit(x, y, 3)
424
+ assert_equal(len(coef3), 4)
425
+ assert_almost_equal(herme.hermeval(x, coef3), y)
426
+ coef3 = herme.hermefit(x, y, [0, 1, 2, 3])
427
+ assert_equal(len(coef3), 4)
428
+ assert_almost_equal(herme.hermeval(x, coef3), y)
429
+ #
430
+ coef4 = herme.hermefit(x, y, 4)
431
+ assert_equal(len(coef4), 5)
432
+ assert_almost_equal(herme.hermeval(x, coef4), y)
433
+ coef4 = herme.hermefit(x, y, [0, 1, 2, 3, 4])
434
+ assert_equal(len(coef4), 5)
435
+ assert_almost_equal(herme.hermeval(x, coef4), y)
436
+ # check things still work if deg is not in strict increasing
437
+ coef4 = herme.hermefit(x, y, [2, 3, 4, 1, 0])
438
+ assert_equal(len(coef4), 5)
439
+ assert_almost_equal(herme.hermeval(x, coef4), y)
440
+ #
441
+ coef2d = herme.hermefit(x, np.array([y, y]).T, 3)
442
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
443
+ coef2d = herme.hermefit(x, np.array([y, y]).T, [0, 1, 2, 3])
444
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
445
+ # test weighting
446
+ w = np.zeros_like(x)
447
+ yw = y.copy()
448
+ w[1::2] = 1
449
+ y[0::2] = 0
450
+ wcoef3 = herme.hermefit(x, yw, 3, w=w)
451
+ assert_almost_equal(wcoef3, coef3)
452
+ wcoef3 = herme.hermefit(x, yw, [0, 1, 2, 3], w=w)
453
+ assert_almost_equal(wcoef3, coef3)
454
+ #
455
+ wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, 3, w=w)
456
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
457
+ wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
458
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
459
+ # test scaling with complex values x points whose square
460
+ # is zero when summed.
461
+ x = [1, 1j, -1, -1j]
462
+ assert_almost_equal(herme.hermefit(x, x, 1), [0, 1])
463
+ assert_almost_equal(herme.hermefit(x, x, [0, 1]), [0, 1])
464
+ # test fitting only even Legendre polynomials
465
+ x = np.linspace(-1, 1)
466
+ y = f2(x)
467
+ coef1 = herme.hermefit(x, y, 4)
468
+ assert_almost_equal(herme.hermeval(x, coef1), y)
469
+ coef2 = herme.hermefit(x, y, [0, 2, 4])
470
+ assert_almost_equal(herme.hermeval(x, coef2), y)
471
+ assert_almost_equal(coef1, coef2)
472
+
473
+
474
+ class TestCompanion:
475
+
476
+ def test_raises(self):
477
+ assert_raises(ValueError, herme.hermecompanion, [])
478
+ assert_raises(ValueError, herme.hermecompanion, [1])
479
+
480
+ def test_dimensions(self):
481
+ for i in range(1, 5):
482
+ coef = [0]*i + [1]
483
+ assert_(herme.hermecompanion(coef).shape == (i, i))
484
+
485
+ def test_linear_root(self):
486
+ assert_(herme.hermecompanion([1, 2])[0, 0] == -.5)
487
+
488
+
489
+ class TestGauss:
490
+
491
+ def test_100(self):
492
+ x, w = herme.hermegauss(100)
493
+
494
+ # test orthogonality. Note that the results need to be normalized,
495
+ # otherwise the huge values that can arise from fast growing
496
+ # functions like Laguerre can be very confusing.
497
+ v = herme.hermevander(x, 99)
498
+ vv = np.dot(v.T * w, v)
499
+ vd = 1/np.sqrt(vv.diagonal())
500
+ vv = vd[:, None] * vv * vd
501
+ assert_almost_equal(vv, np.eye(100))
502
+
503
+ # check that the integral of 1 is correct
504
+ tgt = np.sqrt(2*np.pi)
505
+ assert_almost_equal(w.sum(), tgt)
506
+
507
+
508
+ class TestMisc:
509
+
510
+ def test_hermefromroots(self):
511
+ res = herme.hermefromroots([])
512
+ assert_almost_equal(trim(res), [1])
513
+ for i in range(1, 5):
514
+ roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
515
+ pol = herme.hermefromroots(roots)
516
+ res = herme.hermeval(roots, pol)
517
+ tgt = 0
518
+ assert_(len(pol) == i + 1)
519
+ assert_almost_equal(herme.herme2poly(pol)[-1], 1)
520
+ assert_almost_equal(res, tgt)
521
+
522
+ def test_hermeroots(self):
523
+ assert_almost_equal(herme.hermeroots([1]), [])
524
+ assert_almost_equal(herme.hermeroots([1, 1]), [-1])
525
+ for i in range(2, 5):
526
+ tgt = np.linspace(-1, 1, i)
527
+ res = herme.hermeroots(herme.hermefromroots(tgt))
528
+ assert_almost_equal(trim(res), trim(tgt))
529
+
530
+ def test_hermetrim(self):
531
+ coef = [2, -1, 1, 0]
532
+
533
+ # Test exceptions
534
+ assert_raises(ValueError, herme.hermetrim, coef, -1)
535
+
536
+ # Test results
537
+ assert_equal(herme.hermetrim(coef), coef[:-1])
538
+ assert_equal(herme.hermetrim(coef, 1), coef[:-3])
539
+ assert_equal(herme.hermetrim(coef, 2), [0])
540
+
541
+ def test_hermeline(self):
542
+ assert_equal(herme.hermeline(3, 4), [3, 4])
543
+
544
+ def test_herme2poly(self):
545
+ for i in range(10):
546
+ assert_almost_equal(herme.herme2poly([0]*i + [1]), Helist[i])
547
+
548
+ def test_poly2herme(self):
549
+ for i in range(10):
550
+ assert_almost_equal(herme.poly2herme(Helist[i]), [0]*i + [1])
551
+
552
+ def test_weight(self):
553
+ x = np.linspace(-5, 5, 11)
554
+ tgt = np.exp(-.5*x**2)
555
+ res = herme.hermeweight(x)
556
+ assert_almost_equal(res, tgt)
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_laguerre.py ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for laguerre module.
2
+
3
+ """
4
+ from functools import reduce
5
+
6
+ import numpy as np
7
+ import numpy.polynomial.laguerre as lag
8
+ from numpy.polynomial.polynomial import polyval
9
+ from numpy.testing import (
10
+ assert_almost_equal, assert_raises, assert_equal, assert_,
11
+ )
12
+
13
+ L0 = np.array([1])/1
14
+ L1 = np.array([1, -1])/1
15
+ L2 = np.array([2, -4, 1])/2
16
+ L3 = np.array([6, -18, 9, -1])/6
17
+ L4 = np.array([24, -96, 72, -16, 1])/24
18
+ L5 = np.array([120, -600, 600, -200, 25, -1])/120
19
+ L6 = np.array([720, -4320, 5400, -2400, 450, -36, 1])/720
20
+
21
+ Llist = [L0, L1, L2, L3, L4, L5, L6]
22
+
23
+
24
+ def trim(x):
25
+ return lag.lagtrim(x, tol=1e-6)
26
+
27
+
28
+ class TestConstants:
29
+
30
+ def test_lagdomain(self):
31
+ assert_equal(lag.lagdomain, [0, 1])
32
+
33
+ def test_lagzero(self):
34
+ assert_equal(lag.lagzero, [0])
35
+
36
+ def test_lagone(self):
37
+ assert_equal(lag.lagone, [1])
38
+
39
+ def test_lagx(self):
40
+ assert_equal(lag.lagx, [1, -1])
41
+
42
+
43
+ class TestArithmetic:
44
+ x = np.linspace(-3, 3, 100)
45
+
46
+ def test_lagadd(self):
47
+ for i in range(5):
48
+ for j in range(5):
49
+ msg = f"At i={i}, j={j}"
50
+ tgt = np.zeros(max(i, j) + 1)
51
+ tgt[i] += 1
52
+ tgt[j] += 1
53
+ res = lag.lagadd([0]*i + [1], [0]*j + [1])
54
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
55
+
56
+ def test_lagsub(self):
57
+ for i in range(5):
58
+ for j in range(5):
59
+ msg = f"At i={i}, j={j}"
60
+ tgt = np.zeros(max(i, j) + 1)
61
+ tgt[i] += 1
62
+ tgt[j] -= 1
63
+ res = lag.lagsub([0]*i + [1], [0]*j + [1])
64
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
65
+
66
+ def test_lagmulx(self):
67
+ assert_equal(lag.lagmulx([0]), [0])
68
+ assert_equal(lag.lagmulx([1]), [1, -1])
69
+ for i in range(1, 5):
70
+ ser = [0]*i + [1]
71
+ tgt = [0]*(i - 1) + [-i, 2*i + 1, -(i + 1)]
72
+ assert_almost_equal(lag.lagmulx(ser), tgt)
73
+
74
+ def test_lagmul(self):
75
+ # check values of result
76
+ for i in range(5):
77
+ pol1 = [0]*i + [1]
78
+ val1 = lag.lagval(self.x, pol1)
79
+ for j in range(5):
80
+ msg = f"At i={i}, j={j}"
81
+ pol2 = [0]*j + [1]
82
+ val2 = lag.lagval(self.x, pol2)
83
+ pol3 = lag.lagmul(pol1, pol2)
84
+ val3 = lag.lagval(self.x, pol3)
85
+ assert_(len(pol3) == i + j + 1, msg)
86
+ assert_almost_equal(val3, val1*val2, err_msg=msg)
87
+
88
+ def test_lagdiv(self):
89
+ for i in range(5):
90
+ for j in range(5):
91
+ msg = f"At i={i}, j={j}"
92
+ ci = [0]*i + [1]
93
+ cj = [0]*j + [1]
94
+ tgt = lag.lagadd(ci, cj)
95
+ quo, rem = lag.lagdiv(tgt, ci)
96
+ res = lag.lagadd(lag.lagmul(quo, ci), rem)
97
+ assert_almost_equal(trim(res), trim(tgt), err_msg=msg)
98
+
99
+ def test_lagpow(self):
100
+ for i in range(5):
101
+ for j in range(5):
102
+ msg = f"At i={i}, j={j}"
103
+ c = np.arange(i + 1)
104
+ tgt = reduce(lag.lagmul, [c]*j, np.array([1]))
105
+ res = lag.lagpow(c, j)
106
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
107
+
108
+
109
+ class TestEvaluation:
110
+ # coefficients of 1 + 2*x + 3*x**2
111
+ c1d = np.array([9., -14., 6.])
112
+ c2d = np.einsum('i,j->ij', c1d, c1d)
113
+ c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
114
+
115
+ # some random values in [-1, 1)
116
+ x = np.random.random((3, 5))*2 - 1
117
+ y = polyval(x, [1., 2., 3.])
118
+
119
+ def test_lagval(self):
120
+ #check empty input
121
+ assert_equal(lag.lagval([], [1]).size, 0)
122
+
123
+ #check normal input)
124
+ x = np.linspace(-1, 1)
125
+ y = [polyval(x, c) for c in Llist]
126
+ for i in range(7):
127
+ msg = f"At i={i}"
128
+ tgt = y[i]
129
+ res = lag.lagval(x, [0]*i + [1])
130
+ assert_almost_equal(res, tgt, err_msg=msg)
131
+
132
+ #check that shape is preserved
133
+ for i in range(3):
134
+ dims = [2]*i
135
+ x = np.zeros(dims)
136
+ assert_equal(lag.lagval(x, [1]).shape, dims)
137
+ assert_equal(lag.lagval(x, [1, 0]).shape, dims)
138
+ assert_equal(lag.lagval(x, [1, 0, 0]).shape, dims)
139
+
140
+ def test_lagval2d(self):
141
+ x1, x2, x3 = self.x
142
+ y1, y2, y3 = self.y
143
+
144
+ #test exceptions
145
+ assert_raises(ValueError, lag.lagval2d, x1, x2[:2], self.c2d)
146
+
147
+ #test values
148
+ tgt = y1*y2
149
+ res = lag.lagval2d(x1, x2, self.c2d)
150
+ assert_almost_equal(res, tgt)
151
+
152
+ #test shape
153
+ z = np.ones((2, 3))
154
+ res = lag.lagval2d(z, z, self.c2d)
155
+ assert_(res.shape == (2, 3))
156
+
157
+ def test_lagval3d(self):
158
+ x1, x2, x3 = self.x
159
+ y1, y2, y3 = self.y
160
+
161
+ #test exceptions
162
+ assert_raises(ValueError, lag.lagval3d, x1, x2, x3[:2], self.c3d)
163
+
164
+ #test values
165
+ tgt = y1*y2*y3
166
+ res = lag.lagval3d(x1, x2, x3, self.c3d)
167
+ assert_almost_equal(res, tgt)
168
+
169
+ #test shape
170
+ z = np.ones((2, 3))
171
+ res = lag.lagval3d(z, z, z, self.c3d)
172
+ assert_(res.shape == (2, 3))
173
+
174
+ def test_laggrid2d(self):
175
+ x1, x2, x3 = self.x
176
+ y1, y2, y3 = self.y
177
+
178
+ #test values
179
+ tgt = np.einsum('i,j->ij', y1, y2)
180
+ res = lag.laggrid2d(x1, x2, self.c2d)
181
+ assert_almost_equal(res, tgt)
182
+
183
+ #test shape
184
+ z = np.ones((2, 3))
185
+ res = lag.laggrid2d(z, z, self.c2d)
186
+ assert_(res.shape == (2, 3)*2)
187
+
188
+ def test_laggrid3d(self):
189
+ x1, x2, x3 = self.x
190
+ y1, y2, y3 = self.y
191
+
192
+ #test values
193
+ tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
194
+ res = lag.laggrid3d(x1, x2, x3, self.c3d)
195
+ assert_almost_equal(res, tgt)
196
+
197
+ #test shape
198
+ z = np.ones((2, 3))
199
+ res = lag.laggrid3d(z, z, z, self.c3d)
200
+ assert_(res.shape == (2, 3)*3)
201
+
202
+
203
+ class TestIntegral:
204
+
205
+ def test_lagint(self):
206
+ # check exceptions
207
+ assert_raises(TypeError, lag.lagint, [0], .5)
208
+ assert_raises(ValueError, lag.lagint, [0], -1)
209
+ assert_raises(ValueError, lag.lagint, [0], 1, [0, 0])
210
+ assert_raises(ValueError, lag.lagint, [0], lbnd=[0])
211
+ assert_raises(ValueError, lag.lagint, [0], scl=[0])
212
+ assert_raises(TypeError, lag.lagint, [0], axis=.5)
213
+
214
+ # test integration of zero polynomial
215
+ for i in range(2, 5):
216
+ k = [0]*(i - 2) + [1]
217
+ res = lag.lagint([0], m=i, k=k)
218
+ assert_almost_equal(res, [1, -1])
219
+
220
+ # check single integration with integration constant
221
+ for i in range(5):
222
+ scl = i + 1
223
+ pol = [0]*i + [1]
224
+ tgt = [i] + [0]*i + [1/scl]
225
+ lagpol = lag.poly2lag(pol)
226
+ lagint = lag.lagint(lagpol, m=1, k=[i])
227
+ res = lag.lag2poly(lagint)
228
+ assert_almost_equal(trim(res), trim(tgt))
229
+
230
+ # check single integration with integration constant and lbnd
231
+ for i in range(5):
232
+ scl = i + 1
233
+ pol = [0]*i + [1]
234
+ lagpol = lag.poly2lag(pol)
235
+ lagint = lag.lagint(lagpol, m=1, k=[i], lbnd=-1)
236
+ assert_almost_equal(lag.lagval(-1, lagint), i)
237
+
238
+ # check single integration with integration constant and scaling
239
+ for i in range(5):
240
+ scl = i + 1
241
+ pol = [0]*i + [1]
242
+ tgt = [i] + [0]*i + [2/scl]
243
+ lagpol = lag.poly2lag(pol)
244
+ lagint = lag.lagint(lagpol, m=1, k=[i], scl=2)
245
+ res = lag.lag2poly(lagint)
246
+ assert_almost_equal(trim(res), trim(tgt))
247
+
248
+ # check multiple integrations with default k
249
+ for i in range(5):
250
+ for j in range(2, 5):
251
+ pol = [0]*i + [1]
252
+ tgt = pol[:]
253
+ for k in range(j):
254
+ tgt = lag.lagint(tgt, m=1)
255
+ res = lag.lagint(pol, m=j)
256
+ assert_almost_equal(trim(res), trim(tgt))
257
+
258
+ # check multiple integrations with defined k
259
+ for i in range(5):
260
+ for j in range(2, 5):
261
+ pol = [0]*i + [1]
262
+ tgt = pol[:]
263
+ for k in range(j):
264
+ tgt = lag.lagint(tgt, m=1, k=[k])
265
+ res = lag.lagint(pol, m=j, k=list(range(j)))
266
+ assert_almost_equal(trim(res), trim(tgt))
267
+
268
+ # check multiple integrations with lbnd
269
+ for i in range(5):
270
+ for j in range(2, 5):
271
+ pol = [0]*i + [1]
272
+ tgt = pol[:]
273
+ for k in range(j):
274
+ tgt = lag.lagint(tgt, m=1, k=[k], lbnd=-1)
275
+ res = lag.lagint(pol, m=j, k=list(range(j)), lbnd=-1)
276
+ assert_almost_equal(trim(res), trim(tgt))
277
+
278
+ # check multiple integrations with scaling
279
+ for i in range(5):
280
+ for j in range(2, 5):
281
+ pol = [0]*i + [1]
282
+ tgt = pol[:]
283
+ for k in range(j):
284
+ tgt = lag.lagint(tgt, m=1, k=[k], scl=2)
285
+ res = lag.lagint(pol, m=j, k=list(range(j)), scl=2)
286
+ assert_almost_equal(trim(res), trim(tgt))
287
+
288
+ def test_lagint_axis(self):
289
+ # check that axis keyword works
290
+ c2d = np.random.random((3, 4))
291
+
292
+ tgt = np.vstack([lag.lagint(c) for c in c2d.T]).T
293
+ res = lag.lagint(c2d, axis=0)
294
+ assert_almost_equal(res, tgt)
295
+
296
+ tgt = np.vstack([lag.lagint(c) for c in c2d])
297
+ res = lag.lagint(c2d, axis=1)
298
+ assert_almost_equal(res, tgt)
299
+
300
+ tgt = np.vstack([lag.lagint(c, k=3) for c in c2d])
301
+ res = lag.lagint(c2d, k=3, axis=1)
302
+ assert_almost_equal(res, tgt)
303
+
304
+
305
+ class TestDerivative:
306
+
307
+ def test_lagder(self):
308
+ # check exceptions
309
+ assert_raises(TypeError, lag.lagder, [0], .5)
310
+ assert_raises(ValueError, lag.lagder, [0], -1)
311
+
312
+ # check that zeroth derivative does nothing
313
+ for i in range(5):
314
+ tgt = [0]*i + [1]
315
+ res = lag.lagder(tgt, m=0)
316
+ assert_equal(trim(res), trim(tgt))
317
+
318
+ # check that derivation is the inverse of integration
319
+ for i in range(5):
320
+ for j in range(2, 5):
321
+ tgt = [0]*i + [1]
322
+ res = lag.lagder(lag.lagint(tgt, m=j), m=j)
323
+ assert_almost_equal(trim(res), trim(tgt))
324
+
325
+ # check derivation with scaling
326
+ for i in range(5):
327
+ for j in range(2, 5):
328
+ tgt = [0]*i + [1]
329
+ res = lag.lagder(lag.lagint(tgt, m=j, scl=2), m=j, scl=.5)
330
+ assert_almost_equal(trim(res), trim(tgt))
331
+
332
+ def test_lagder_axis(self):
333
+ # check that axis keyword works
334
+ c2d = np.random.random((3, 4))
335
+
336
+ tgt = np.vstack([lag.lagder(c) for c in c2d.T]).T
337
+ res = lag.lagder(c2d, axis=0)
338
+ assert_almost_equal(res, tgt)
339
+
340
+ tgt = np.vstack([lag.lagder(c) for c in c2d])
341
+ res = lag.lagder(c2d, axis=1)
342
+ assert_almost_equal(res, tgt)
343
+
344
+
345
+ class TestVander:
346
+ # some random values in [-1, 1)
347
+ x = np.random.random((3, 5))*2 - 1
348
+
349
+ def test_lagvander(self):
350
+ # check for 1d x
351
+ x = np.arange(3)
352
+ v = lag.lagvander(x, 3)
353
+ assert_(v.shape == (3, 4))
354
+ for i in range(4):
355
+ coef = [0]*i + [1]
356
+ assert_almost_equal(v[..., i], lag.lagval(x, coef))
357
+
358
+ # check for 2d x
359
+ x = np.array([[1, 2], [3, 4], [5, 6]])
360
+ v = lag.lagvander(x, 3)
361
+ assert_(v.shape == (3, 2, 4))
362
+ for i in range(4):
363
+ coef = [0]*i + [1]
364
+ assert_almost_equal(v[..., i], lag.lagval(x, coef))
365
+
366
+ def test_lagvander2d(self):
367
+ # also tests lagval2d for non-square coefficient array
368
+ x1, x2, x3 = self.x
369
+ c = np.random.random((2, 3))
370
+ van = lag.lagvander2d(x1, x2, [1, 2])
371
+ tgt = lag.lagval2d(x1, x2, c)
372
+ res = np.dot(van, c.flat)
373
+ assert_almost_equal(res, tgt)
374
+
375
+ # check shape
376
+ van = lag.lagvander2d([x1], [x2], [1, 2])
377
+ assert_(van.shape == (1, 5, 6))
378
+
379
+ def test_lagvander3d(self):
380
+ # also tests lagval3d for non-square coefficient array
381
+ x1, x2, x3 = self.x
382
+ c = np.random.random((2, 3, 4))
383
+ van = lag.lagvander3d(x1, x2, x3, [1, 2, 3])
384
+ tgt = lag.lagval3d(x1, x2, x3, c)
385
+ res = np.dot(van, c.flat)
386
+ assert_almost_equal(res, tgt)
387
+
388
+ # check shape
389
+ van = lag.lagvander3d([x1], [x2], [x3], [1, 2, 3])
390
+ assert_(van.shape == (1, 5, 24))
391
+
392
+
393
+ class TestFitting:
394
+
395
+ def test_lagfit(self):
396
+ def f(x):
397
+ return x*(x - 1)*(x - 2)
398
+
399
+ # Test exceptions
400
+ assert_raises(ValueError, lag.lagfit, [1], [1], -1)
401
+ assert_raises(TypeError, lag.lagfit, [[1]], [1], 0)
402
+ assert_raises(TypeError, lag.lagfit, [], [1], 0)
403
+ assert_raises(TypeError, lag.lagfit, [1], [[[1]]], 0)
404
+ assert_raises(TypeError, lag.lagfit, [1, 2], [1], 0)
405
+ assert_raises(TypeError, lag.lagfit, [1], [1, 2], 0)
406
+ assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[[1]])
407
+ assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[1, 1])
408
+ assert_raises(ValueError, lag.lagfit, [1], [1], [-1,])
409
+ assert_raises(ValueError, lag.lagfit, [1], [1], [2, -1, 6])
410
+ assert_raises(TypeError, lag.lagfit, [1], [1], [])
411
+
412
+ # Test fit
413
+ x = np.linspace(0, 2)
414
+ y = f(x)
415
+ #
416
+ coef3 = lag.lagfit(x, y, 3)
417
+ assert_equal(len(coef3), 4)
418
+ assert_almost_equal(lag.lagval(x, coef3), y)
419
+ coef3 = lag.lagfit(x, y, [0, 1, 2, 3])
420
+ assert_equal(len(coef3), 4)
421
+ assert_almost_equal(lag.lagval(x, coef3), y)
422
+ #
423
+ coef4 = lag.lagfit(x, y, 4)
424
+ assert_equal(len(coef4), 5)
425
+ assert_almost_equal(lag.lagval(x, coef4), y)
426
+ coef4 = lag.lagfit(x, y, [0, 1, 2, 3, 4])
427
+ assert_equal(len(coef4), 5)
428
+ assert_almost_equal(lag.lagval(x, coef4), y)
429
+ #
430
+ coef2d = lag.lagfit(x, np.array([y, y]).T, 3)
431
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
432
+ coef2d = lag.lagfit(x, np.array([y, y]).T, [0, 1, 2, 3])
433
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
434
+ # test weighting
435
+ w = np.zeros_like(x)
436
+ yw = y.copy()
437
+ w[1::2] = 1
438
+ y[0::2] = 0
439
+ wcoef3 = lag.lagfit(x, yw, 3, w=w)
440
+ assert_almost_equal(wcoef3, coef3)
441
+ wcoef3 = lag.lagfit(x, yw, [0, 1, 2, 3], w=w)
442
+ assert_almost_equal(wcoef3, coef3)
443
+ #
444
+ wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, 3, w=w)
445
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
446
+ wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
447
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
448
+ # test scaling with complex values x points whose square
449
+ # is zero when summed.
450
+ x = [1, 1j, -1, -1j]
451
+ assert_almost_equal(lag.lagfit(x, x, 1), [1, -1])
452
+ assert_almost_equal(lag.lagfit(x, x, [0, 1]), [1, -1])
453
+
454
+
455
+ class TestCompanion:
456
+
457
+ def test_raises(self):
458
+ assert_raises(ValueError, lag.lagcompanion, [])
459
+ assert_raises(ValueError, lag.lagcompanion, [1])
460
+
461
+ def test_dimensions(self):
462
+ for i in range(1, 5):
463
+ coef = [0]*i + [1]
464
+ assert_(lag.lagcompanion(coef).shape == (i, i))
465
+
466
+ def test_linear_root(self):
467
+ assert_(lag.lagcompanion([1, 2])[0, 0] == 1.5)
468
+
469
+
470
+ class TestGauss:
471
+
472
+ def test_100(self):
473
+ x, w = lag.laggauss(100)
474
+
475
+ # test orthogonality. Note that the results need to be normalized,
476
+ # otherwise the huge values that can arise from fast growing
477
+ # functions like Laguerre can be very confusing.
478
+ v = lag.lagvander(x, 99)
479
+ vv = np.dot(v.T * w, v)
480
+ vd = 1/np.sqrt(vv.diagonal())
481
+ vv = vd[:, None] * vv * vd
482
+ assert_almost_equal(vv, np.eye(100))
483
+
484
+ # check that the integral of 1 is correct
485
+ tgt = 1.0
486
+ assert_almost_equal(w.sum(), tgt)
487
+
488
+
489
+ class TestMisc:
490
+
491
+ def test_lagfromroots(self):
492
+ res = lag.lagfromroots([])
493
+ assert_almost_equal(trim(res), [1])
494
+ for i in range(1, 5):
495
+ roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
496
+ pol = lag.lagfromroots(roots)
497
+ res = lag.lagval(roots, pol)
498
+ tgt = 0
499
+ assert_(len(pol) == i + 1)
500
+ assert_almost_equal(lag.lag2poly(pol)[-1], 1)
501
+ assert_almost_equal(res, tgt)
502
+
503
+ def test_lagroots(self):
504
+ assert_almost_equal(lag.lagroots([1]), [])
505
+ assert_almost_equal(lag.lagroots([0, 1]), [1])
506
+ for i in range(2, 5):
507
+ tgt = np.linspace(0, 3, i)
508
+ res = lag.lagroots(lag.lagfromroots(tgt))
509
+ assert_almost_equal(trim(res), trim(tgt))
510
+
511
+ def test_lagtrim(self):
512
+ coef = [2, -1, 1, 0]
513
+
514
+ # Test exceptions
515
+ assert_raises(ValueError, lag.lagtrim, coef, -1)
516
+
517
+ # Test results
518
+ assert_equal(lag.lagtrim(coef), coef[:-1])
519
+ assert_equal(lag.lagtrim(coef, 1), coef[:-3])
520
+ assert_equal(lag.lagtrim(coef, 2), [0])
521
+
522
+ def test_lagline(self):
523
+ assert_equal(lag.lagline(3, 4), [7, -4])
524
+
525
+ def test_lag2poly(self):
526
+ for i in range(7):
527
+ assert_almost_equal(lag.lag2poly([0]*i + [1]), Llist[i])
528
+
529
+ def test_poly2lag(self):
530
+ for i in range(7):
531
+ assert_almost_equal(lag.poly2lag(Llist[i]), [0]*i + [1])
532
+
533
+ def test_weight(self):
534
+ x = np.linspace(0, 10, 11)
535
+ tgt = np.exp(-x)
536
+ res = lag.lagweight(x)
537
+ assert_almost_equal(res, tgt)
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_legendre.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for legendre module.
2
+
3
+ """
4
+ from functools import reduce
5
+
6
+ import numpy as np
7
+ import numpy.polynomial.legendre as leg
8
+ from numpy.polynomial.polynomial import polyval
9
+ from numpy.testing import (
10
+ assert_almost_equal, assert_raises, assert_equal, assert_,
11
+ )
12
+
13
+ L0 = np.array([1])
14
+ L1 = np.array([0, 1])
15
+ L2 = np.array([-1, 0, 3])/2
16
+ L3 = np.array([0, -3, 0, 5])/2
17
+ L4 = np.array([3, 0, -30, 0, 35])/8
18
+ L5 = np.array([0, 15, 0, -70, 0, 63])/8
19
+ L6 = np.array([-5, 0, 105, 0, -315, 0, 231])/16
20
+ L7 = np.array([0, -35, 0, 315, 0, -693, 0, 429])/16
21
+ L8 = np.array([35, 0, -1260, 0, 6930, 0, -12012, 0, 6435])/128
22
+ L9 = np.array([0, 315, 0, -4620, 0, 18018, 0, -25740, 0, 12155])/128
23
+
24
+ Llist = [L0, L1, L2, L3, L4, L5, L6, L7, L8, L9]
25
+
26
+
27
+ def trim(x):
28
+ return leg.legtrim(x, tol=1e-6)
29
+
30
+
31
+ class TestConstants:
32
+
33
+ def test_legdomain(self):
34
+ assert_equal(leg.legdomain, [-1, 1])
35
+
36
+ def test_legzero(self):
37
+ assert_equal(leg.legzero, [0])
38
+
39
+ def test_legone(self):
40
+ assert_equal(leg.legone, [1])
41
+
42
+ def test_legx(self):
43
+ assert_equal(leg.legx, [0, 1])
44
+
45
+
46
+ class TestArithmetic:
47
+ x = np.linspace(-1, 1, 100)
48
+
49
+ def test_legadd(self):
50
+ for i in range(5):
51
+ for j in range(5):
52
+ msg = f"At i={i}, j={j}"
53
+ tgt = np.zeros(max(i, j) + 1)
54
+ tgt[i] += 1
55
+ tgt[j] += 1
56
+ res = leg.legadd([0]*i + [1], [0]*j + [1])
57
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
58
+
59
+ def test_legsub(self):
60
+ for i in range(5):
61
+ for j in range(5):
62
+ msg = f"At i={i}, j={j}"
63
+ tgt = np.zeros(max(i, j) + 1)
64
+ tgt[i] += 1
65
+ tgt[j] -= 1
66
+ res = leg.legsub([0]*i + [1], [0]*j + [1])
67
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
68
+
69
+ def test_legmulx(self):
70
+ assert_equal(leg.legmulx([0]), [0])
71
+ assert_equal(leg.legmulx([1]), [0, 1])
72
+ for i in range(1, 5):
73
+ tmp = 2*i + 1
74
+ ser = [0]*i + [1]
75
+ tgt = [0]*(i - 1) + [i/tmp, 0, (i + 1)/tmp]
76
+ assert_equal(leg.legmulx(ser), tgt)
77
+
78
+ def test_legmul(self):
79
+ # check values of result
80
+ for i in range(5):
81
+ pol1 = [0]*i + [1]
82
+ val1 = leg.legval(self.x, pol1)
83
+ for j in range(5):
84
+ msg = f"At i={i}, j={j}"
85
+ pol2 = [0]*j + [1]
86
+ val2 = leg.legval(self.x, pol2)
87
+ pol3 = leg.legmul(pol1, pol2)
88
+ val3 = leg.legval(self.x, pol3)
89
+ assert_(len(pol3) == i + j + 1, msg)
90
+ assert_almost_equal(val3, val1*val2, err_msg=msg)
91
+
92
+ def test_legdiv(self):
93
+ for i in range(5):
94
+ for j in range(5):
95
+ msg = f"At i={i}, j={j}"
96
+ ci = [0]*i + [1]
97
+ cj = [0]*j + [1]
98
+ tgt = leg.legadd(ci, cj)
99
+ quo, rem = leg.legdiv(tgt, ci)
100
+ res = leg.legadd(leg.legmul(quo, ci), rem)
101
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
102
+
103
+ def test_legpow(self):
104
+ for i in range(5):
105
+ for j in range(5):
106
+ msg = f"At i={i}, j={j}"
107
+ c = np.arange(i + 1)
108
+ tgt = reduce(leg.legmul, [c]*j, np.array([1]))
109
+ res = leg.legpow(c, j)
110
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
111
+
112
+
113
+ class TestEvaluation:
114
+ # coefficients of 1 + 2*x + 3*x**2
115
+ c1d = np.array([2., 2., 2.])
116
+ c2d = np.einsum('i,j->ij', c1d, c1d)
117
+ c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
118
+
119
+ # some random values in [-1, 1)
120
+ x = np.random.random((3, 5))*2 - 1
121
+ y = polyval(x, [1., 2., 3.])
122
+
123
+ def test_legval(self):
124
+ #check empty input
125
+ assert_equal(leg.legval([], [1]).size, 0)
126
+
127
+ #check normal input)
128
+ x = np.linspace(-1, 1)
129
+ y = [polyval(x, c) for c in Llist]
130
+ for i in range(10):
131
+ msg = f"At i={i}"
132
+ tgt = y[i]
133
+ res = leg.legval(x, [0]*i + [1])
134
+ assert_almost_equal(res, tgt, err_msg=msg)
135
+
136
+ #check that shape is preserved
137
+ for i in range(3):
138
+ dims = [2]*i
139
+ x = np.zeros(dims)
140
+ assert_equal(leg.legval(x, [1]).shape, dims)
141
+ assert_equal(leg.legval(x, [1, 0]).shape, dims)
142
+ assert_equal(leg.legval(x, [1, 0, 0]).shape, dims)
143
+
144
+ def test_legval2d(self):
145
+ x1, x2, x3 = self.x
146
+ y1, y2, y3 = self.y
147
+
148
+ #test exceptions
149
+ assert_raises(ValueError, leg.legval2d, x1, x2[:2], self.c2d)
150
+
151
+ #test values
152
+ tgt = y1*y2
153
+ res = leg.legval2d(x1, x2, self.c2d)
154
+ assert_almost_equal(res, tgt)
155
+
156
+ #test shape
157
+ z = np.ones((2, 3))
158
+ res = leg.legval2d(z, z, self.c2d)
159
+ assert_(res.shape == (2, 3))
160
+
161
+ def test_legval3d(self):
162
+ x1, x2, x3 = self.x
163
+ y1, y2, y3 = self.y
164
+
165
+ #test exceptions
166
+ assert_raises(ValueError, leg.legval3d, x1, x2, x3[:2], self.c3d)
167
+
168
+ #test values
169
+ tgt = y1*y2*y3
170
+ res = leg.legval3d(x1, x2, x3, self.c3d)
171
+ assert_almost_equal(res, tgt)
172
+
173
+ #test shape
174
+ z = np.ones((2, 3))
175
+ res = leg.legval3d(z, z, z, self.c3d)
176
+ assert_(res.shape == (2, 3))
177
+
178
+ def test_leggrid2d(self):
179
+ x1, x2, x3 = self.x
180
+ y1, y2, y3 = self.y
181
+
182
+ #test values
183
+ tgt = np.einsum('i,j->ij', y1, y2)
184
+ res = leg.leggrid2d(x1, x2, self.c2d)
185
+ assert_almost_equal(res, tgt)
186
+
187
+ #test shape
188
+ z = np.ones((2, 3))
189
+ res = leg.leggrid2d(z, z, self.c2d)
190
+ assert_(res.shape == (2, 3)*2)
191
+
192
+ def test_leggrid3d(self):
193
+ x1, x2, x3 = self.x
194
+ y1, y2, y3 = self.y
195
+
196
+ #test values
197
+ tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
198
+ res = leg.leggrid3d(x1, x2, x3, self.c3d)
199
+ assert_almost_equal(res, tgt)
200
+
201
+ #test shape
202
+ z = np.ones((2, 3))
203
+ res = leg.leggrid3d(z, z, z, self.c3d)
204
+ assert_(res.shape == (2, 3)*3)
205
+
206
+
207
+ class TestIntegral:
208
+
209
+ def test_legint(self):
210
+ # check exceptions
211
+ assert_raises(TypeError, leg.legint, [0], .5)
212
+ assert_raises(ValueError, leg.legint, [0], -1)
213
+ assert_raises(ValueError, leg.legint, [0], 1, [0, 0])
214
+ assert_raises(ValueError, leg.legint, [0], lbnd=[0])
215
+ assert_raises(ValueError, leg.legint, [0], scl=[0])
216
+ assert_raises(TypeError, leg.legint, [0], axis=.5)
217
+
218
+ # test integration of zero polynomial
219
+ for i in range(2, 5):
220
+ k = [0]*(i - 2) + [1]
221
+ res = leg.legint([0], m=i, k=k)
222
+ assert_almost_equal(res, [0, 1])
223
+
224
+ # check single integration with integration constant
225
+ for i in range(5):
226
+ scl = i + 1
227
+ pol = [0]*i + [1]
228
+ tgt = [i] + [0]*i + [1/scl]
229
+ legpol = leg.poly2leg(pol)
230
+ legint = leg.legint(legpol, m=1, k=[i])
231
+ res = leg.leg2poly(legint)
232
+ assert_almost_equal(trim(res), trim(tgt))
233
+
234
+ # check single integration with integration constant and lbnd
235
+ for i in range(5):
236
+ scl = i + 1
237
+ pol = [0]*i + [1]
238
+ legpol = leg.poly2leg(pol)
239
+ legint = leg.legint(legpol, m=1, k=[i], lbnd=-1)
240
+ assert_almost_equal(leg.legval(-1, legint), i)
241
+
242
+ # check single integration with integration constant and scaling
243
+ for i in range(5):
244
+ scl = i + 1
245
+ pol = [0]*i + [1]
246
+ tgt = [i] + [0]*i + [2/scl]
247
+ legpol = leg.poly2leg(pol)
248
+ legint = leg.legint(legpol, m=1, k=[i], scl=2)
249
+ res = leg.leg2poly(legint)
250
+ assert_almost_equal(trim(res), trim(tgt))
251
+
252
+ # check multiple integrations with default k
253
+ for i in range(5):
254
+ for j in range(2, 5):
255
+ pol = [0]*i + [1]
256
+ tgt = pol[:]
257
+ for k in range(j):
258
+ tgt = leg.legint(tgt, m=1)
259
+ res = leg.legint(pol, m=j)
260
+ assert_almost_equal(trim(res), trim(tgt))
261
+
262
+ # check multiple integrations with defined k
263
+ for i in range(5):
264
+ for j in range(2, 5):
265
+ pol = [0]*i + [1]
266
+ tgt = pol[:]
267
+ for k in range(j):
268
+ tgt = leg.legint(tgt, m=1, k=[k])
269
+ res = leg.legint(pol, m=j, k=list(range(j)))
270
+ assert_almost_equal(trim(res), trim(tgt))
271
+
272
+ # check multiple integrations with lbnd
273
+ for i in range(5):
274
+ for j in range(2, 5):
275
+ pol = [0]*i + [1]
276
+ tgt = pol[:]
277
+ for k in range(j):
278
+ tgt = leg.legint(tgt, m=1, k=[k], lbnd=-1)
279
+ res = leg.legint(pol, m=j, k=list(range(j)), lbnd=-1)
280
+ assert_almost_equal(trim(res), trim(tgt))
281
+
282
+ # check multiple integrations with scaling
283
+ for i in range(5):
284
+ for j in range(2, 5):
285
+ pol = [0]*i + [1]
286
+ tgt = pol[:]
287
+ for k in range(j):
288
+ tgt = leg.legint(tgt, m=1, k=[k], scl=2)
289
+ res = leg.legint(pol, m=j, k=list(range(j)), scl=2)
290
+ assert_almost_equal(trim(res), trim(tgt))
291
+
292
+ def test_legint_axis(self):
293
+ # check that axis keyword works
294
+ c2d = np.random.random((3, 4))
295
+
296
+ tgt = np.vstack([leg.legint(c) for c in c2d.T]).T
297
+ res = leg.legint(c2d, axis=0)
298
+ assert_almost_equal(res, tgt)
299
+
300
+ tgt = np.vstack([leg.legint(c) for c in c2d])
301
+ res = leg.legint(c2d, axis=1)
302
+ assert_almost_equal(res, tgt)
303
+
304
+ tgt = np.vstack([leg.legint(c, k=3) for c in c2d])
305
+ res = leg.legint(c2d, k=3, axis=1)
306
+ assert_almost_equal(res, tgt)
307
+
308
+ def test_legint_zerointord(self):
309
+ assert_equal(leg.legint((1, 2, 3), 0), (1, 2, 3))
310
+
311
+
312
+ class TestDerivative:
313
+
314
+ def test_legder(self):
315
+ # check exceptions
316
+ assert_raises(TypeError, leg.legder, [0], .5)
317
+ assert_raises(ValueError, leg.legder, [0], -1)
318
+
319
+ # check that zeroth derivative does nothing
320
+ for i in range(5):
321
+ tgt = [0]*i + [1]
322
+ res = leg.legder(tgt, m=0)
323
+ assert_equal(trim(res), trim(tgt))
324
+
325
+ # check that derivation is the inverse of integration
326
+ for i in range(5):
327
+ for j in range(2, 5):
328
+ tgt = [0]*i + [1]
329
+ res = leg.legder(leg.legint(tgt, m=j), m=j)
330
+ assert_almost_equal(trim(res), trim(tgt))
331
+
332
+ # check derivation with scaling
333
+ for i in range(5):
334
+ for j in range(2, 5):
335
+ tgt = [0]*i + [1]
336
+ res = leg.legder(leg.legint(tgt, m=j, scl=2), m=j, scl=.5)
337
+ assert_almost_equal(trim(res), trim(tgt))
338
+
339
+ def test_legder_axis(self):
340
+ # check that axis keyword works
341
+ c2d = np.random.random((3, 4))
342
+
343
+ tgt = np.vstack([leg.legder(c) for c in c2d.T]).T
344
+ res = leg.legder(c2d, axis=0)
345
+ assert_almost_equal(res, tgt)
346
+
347
+ tgt = np.vstack([leg.legder(c) for c in c2d])
348
+ res = leg.legder(c2d, axis=1)
349
+ assert_almost_equal(res, tgt)
350
+
351
+ def test_legder_orderhigherthancoeff(self):
352
+ c = (1, 2, 3, 4)
353
+ assert_equal(leg.legder(c, 4), [0])
354
+
355
+ class TestVander:
356
+ # some random values in [-1, 1)
357
+ x = np.random.random((3, 5))*2 - 1
358
+
359
+ def test_legvander(self):
360
+ # check for 1d x
361
+ x = np.arange(3)
362
+ v = leg.legvander(x, 3)
363
+ assert_(v.shape == (3, 4))
364
+ for i in range(4):
365
+ coef = [0]*i + [1]
366
+ assert_almost_equal(v[..., i], leg.legval(x, coef))
367
+
368
+ # check for 2d x
369
+ x = np.array([[1, 2], [3, 4], [5, 6]])
370
+ v = leg.legvander(x, 3)
371
+ assert_(v.shape == (3, 2, 4))
372
+ for i in range(4):
373
+ coef = [0]*i + [1]
374
+ assert_almost_equal(v[..., i], leg.legval(x, coef))
375
+
376
+ def test_legvander2d(self):
377
+ # also tests polyval2d for non-square coefficient array
378
+ x1, x2, x3 = self.x
379
+ c = np.random.random((2, 3))
380
+ van = leg.legvander2d(x1, x2, [1, 2])
381
+ tgt = leg.legval2d(x1, x2, c)
382
+ res = np.dot(van, c.flat)
383
+ assert_almost_equal(res, tgt)
384
+
385
+ # check shape
386
+ van = leg.legvander2d([x1], [x2], [1, 2])
387
+ assert_(van.shape == (1, 5, 6))
388
+
389
+ def test_legvander3d(self):
390
+ # also tests polyval3d for non-square coefficient array
391
+ x1, x2, x3 = self.x
392
+ c = np.random.random((2, 3, 4))
393
+ van = leg.legvander3d(x1, x2, x3, [1, 2, 3])
394
+ tgt = leg.legval3d(x1, x2, x3, c)
395
+ res = np.dot(van, c.flat)
396
+ assert_almost_equal(res, tgt)
397
+
398
+ # check shape
399
+ van = leg.legvander3d([x1], [x2], [x3], [1, 2, 3])
400
+ assert_(van.shape == (1, 5, 24))
401
+
402
+ def test_legvander_negdeg(self):
403
+ assert_raises(ValueError, leg.legvander, (1, 2, 3), -1)
404
+
405
+
406
+ class TestFitting:
407
+
408
+ def test_legfit(self):
409
+ def f(x):
410
+ return x*(x - 1)*(x - 2)
411
+
412
+ def f2(x):
413
+ return x**4 + x**2 + 1
414
+
415
+ # Test exceptions
416
+ assert_raises(ValueError, leg.legfit, [1], [1], -1)
417
+ assert_raises(TypeError, leg.legfit, [[1]], [1], 0)
418
+ assert_raises(TypeError, leg.legfit, [], [1], 0)
419
+ assert_raises(TypeError, leg.legfit, [1], [[[1]]], 0)
420
+ assert_raises(TypeError, leg.legfit, [1, 2], [1], 0)
421
+ assert_raises(TypeError, leg.legfit, [1], [1, 2], 0)
422
+ assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[[1]])
423
+ assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[1, 1])
424
+ assert_raises(ValueError, leg.legfit, [1], [1], [-1,])
425
+ assert_raises(ValueError, leg.legfit, [1], [1], [2, -1, 6])
426
+ assert_raises(TypeError, leg.legfit, [1], [1], [])
427
+
428
+ # Test fit
429
+ x = np.linspace(0, 2)
430
+ y = f(x)
431
+ #
432
+ coef3 = leg.legfit(x, y, 3)
433
+ assert_equal(len(coef3), 4)
434
+ assert_almost_equal(leg.legval(x, coef3), y)
435
+ coef3 = leg.legfit(x, y, [0, 1, 2, 3])
436
+ assert_equal(len(coef3), 4)
437
+ assert_almost_equal(leg.legval(x, coef3), y)
438
+ #
439
+ coef4 = leg.legfit(x, y, 4)
440
+ assert_equal(len(coef4), 5)
441
+ assert_almost_equal(leg.legval(x, coef4), y)
442
+ coef4 = leg.legfit(x, y, [0, 1, 2, 3, 4])
443
+ assert_equal(len(coef4), 5)
444
+ assert_almost_equal(leg.legval(x, coef4), y)
445
+ # check things still work if deg is not in strict increasing
446
+ coef4 = leg.legfit(x, y, [2, 3, 4, 1, 0])
447
+ assert_equal(len(coef4), 5)
448
+ assert_almost_equal(leg.legval(x, coef4), y)
449
+ #
450
+ coef2d = leg.legfit(x, np.array([y, y]).T, 3)
451
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
452
+ coef2d = leg.legfit(x, np.array([y, y]).T, [0, 1, 2, 3])
453
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
454
+ # test weighting
455
+ w = np.zeros_like(x)
456
+ yw = y.copy()
457
+ w[1::2] = 1
458
+ y[0::2] = 0
459
+ wcoef3 = leg.legfit(x, yw, 3, w=w)
460
+ assert_almost_equal(wcoef3, coef3)
461
+ wcoef3 = leg.legfit(x, yw, [0, 1, 2, 3], w=w)
462
+ assert_almost_equal(wcoef3, coef3)
463
+ #
464
+ wcoef2d = leg.legfit(x, np.array([yw, yw]).T, 3, w=w)
465
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
466
+ wcoef2d = leg.legfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
467
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
468
+ # test scaling with complex values x points whose square
469
+ # is zero when summed.
470
+ x = [1, 1j, -1, -1j]
471
+ assert_almost_equal(leg.legfit(x, x, 1), [0, 1])
472
+ assert_almost_equal(leg.legfit(x, x, [0, 1]), [0, 1])
473
+ # test fitting only even Legendre polynomials
474
+ x = np.linspace(-1, 1)
475
+ y = f2(x)
476
+ coef1 = leg.legfit(x, y, 4)
477
+ assert_almost_equal(leg.legval(x, coef1), y)
478
+ coef2 = leg.legfit(x, y, [0, 2, 4])
479
+ assert_almost_equal(leg.legval(x, coef2), y)
480
+ assert_almost_equal(coef1, coef2)
481
+
482
+
483
+ class TestCompanion:
484
+
485
+ def test_raises(self):
486
+ assert_raises(ValueError, leg.legcompanion, [])
487
+ assert_raises(ValueError, leg.legcompanion, [1])
488
+
489
+ def test_dimensions(self):
490
+ for i in range(1, 5):
491
+ coef = [0]*i + [1]
492
+ assert_(leg.legcompanion(coef).shape == (i, i))
493
+
494
+ def test_linear_root(self):
495
+ assert_(leg.legcompanion([1, 2])[0, 0] == -.5)
496
+
497
+
498
+ class TestGauss:
499
+
500
+ def test_100(self):
501
+ x, w = leg.leggauss(100)
502
+
503
+ # test orthogonality. Note that the results need to be normalized,
504
+ # otherwise the huge values that can arise from fast growing
505
+ # functions like Laguerre can be very confusing.
506
+ v = leg.legvander(x, 99)
507
+ vv = np.dot(v.T * w, v)
508
+ vd = 1/np.sqrt(vv.diagonal())
509
+ vv = vd[:, None] * vv * vd
510
+ assert_almost_equal(vv, np.eye(100))
511
+
512
+ # check that the integral of 1 is correct
513
+ tgt = 2.0
514
+ assert_almost_equal(w.sum(), tgt)
515
+
516
+
517
+ class TestMisc:
518
+
519
+ def test_legfromroots(self):
520
+ res = leg.legfromroots([])
521
+ assert_almost_equal(trim(res), [1])
522
+ for i in range(1, 5):
523
+ roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
524
+ pol = leg.legfromroots(roots)
525
+ res = leg.legval(roots, pol)
526
+ tgt = 0
527
+ assert_(len(pol) == i + 1)
528
+ assert_almost_equal(leg.leg2poly(pol)[-1], 1)
529
+ assert_almost_equal(res, tgt)
530
+
531
+ def test_legroots(self):
532
+ assert_almost_equal(leg.legroots([1]), [])
533
+ assert_almost_equal(leg.legroots([1, 2]), [-.5])
534
+ for i in range(2, 5):
535
+ tgt = np.linspace(-1, 1, i)
536
+ res = leg.legroots(leg.legfromroots(tgt))
537
+ assert_almost_equal(trim(res), trim(tgt))
538
+
539
+ def test_legtrim(self):
540
+ coef = [2, -1, 1, 0]
541
+
542
+ # Test exceptions
543
+ assert_raises(ValueError, leg.legtrim, coef, -1)
544
+
545
+ # Test results
546
+ assert_equal(leg.legtrim(coef), coef[:-1])
547
+ assert_equal(leg.legtrim(coef, 1), coef[:-3])
548
+ assert_equal(leg.legtrim(coef, 2), [0])
549
+
550
+ def test_legline(self):
551
+ assert_equal(leg.legline(3, 4), [3, 4])
552
+
553
+ def test_legline_zeroscl(self):
554
+ assert_equal(leg.legline(3, 0), [3])
555
+
556
+ def test_leg2poly(self):
557
+ for i in range(10):
558
+ assert_almost_equal(leg.leg2poly([0]*i + [1]), Llist[i])
559
+
560
+ def test_poly2leg(self):
561
+ for i in range(10):
562
+ assert_almost_equal(leg.poly2leg(Llist[i]), [0]*i + [1])
563
+
564
+ def test_weight(self):
565
+ x = np.linspace(-1, 1, 11)
566
+ tgt = 1.
567
+ res = leg.legweight(x)
568
+ assert_almost_equal(res, tgt)
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_polynomial.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for polynomial module.
2
+
3
+ """
4
+ from functools import reduce
5
+
6
+ import numpy as np
7
+ import numpy.polynomial.polynomial as poly
8
+ import pickle
9
+ from copy import deepcopy
10
+ from numpy.testing import (
11
+ assert_almost_equal, assert_raises, assert_equal, assert_,
12
+ assert_warns, assert_array_equal, assert_raises_regex)
13
+
14
+
15
+ def trim(x):
16
+ return poly.polytrim(x, tol=1e-6)
17
+
18
+ T0 = [1]
19
+ T1 = [0, 1]
20
+ T2 = [-1, 0, 2]
21
+ T3 = [0, -3, 0, 4]
22
+ T4 = [1, 0, -8, 0, 8]
23
+ T5 = [0, 5, 0, -20, 0, 16]
24
+ T6 = [-1, 0, 18, 0, -48, 0, 32]
25
+ T7 = [0, -7, 0, 56, 0, -112, 0, 64]
26
+ T8 = [1, 0, -32, 0, 160, 0, -256, 0, 128]
27
+ T9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256]
28
+
29
+ Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]
30
+
31
+
32
+ class TestConstants:
33
+
34
+ def test_polydomain(self):
35
+ assert_equal(poly.polydomain, [-1, 1])
36
+
37
+ def test_polyzero(self):
38
+ assert_equal(poly.polyzero, [0])
39
+
40
+ def test_polyone(self):
41
+ assert_equal(poly.polyone, [1])
42
+
43
+ def test_polyx(self):
44
+ assert_equal(poly.polyx, [0, 1])
45
+
46
+ def test_copy(self):
47
+ x = poly.Polynomial([1, 2, 3])
48
+ y = deepcopy(x)
49
+ assert_equal(x, y)
50
+
51
+ def test_pickle(self):
52
+ x = poly.Polynomial([1, 2, 3])
53
+ y = pickle.loads(pickle.dumps(x))
54
+ assert_equal(x, y)
55
+
56
+ class TestArithmetic:
57
+
58
+ def test_polyadd(self):
59
+ for i in range(5):
60
+ for j in range(5):
61
+ msg = f"At i={i}, j={j}"
62
+ tgt = np.zeros(max(i, j) + 1)
63
+ tgt[i] += 1
64
+ tgt[j] += 1
65
+ res = poly.polyadd([0]*i + [1], [0]*j + [1])
66
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
67
+
68
+ def test_polysub(self):
69
+ for i in range(5):
70
+ for j in range(5):
71
+ msg = f"At i={i}, j={j}"
72
+ tgt = np.zeros(max(i, j) + 1)
73
+ tgt[i] += 1
74
+ tgt[j] -= 1
75
+ res = poly.polysub([0]*i + [1], [0]*j + [1])
76
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
77
+
78
+ def test_polymulx(self):
79
+ assert_equal(poly.polymulx([0]), [0])
80
+ assert_equal(poly.polymulx([1]), [0, 1])
81
+ for i in range(1, 5):
82
+ ser = [0]*i + [1]
83
+ tgt = [0]*(i + 1) + [1]
84
+ assert_equal(poly.polymulx(ser), tgt)
85
+
86
+ def test_polymul(self):
87
+ for i in range(5):
88
+ for j in range(5):
89
+ msg = f"At i={i}, j={j}"
90
+ tgt = np.zeros(i + j + 1)
91
+ tgt[i + j] += 1
92
+ res = poly.polymul([0]*i + [1], [0]*j + [1])
93
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
94
+
95
+ def test_polydiv(self):
96
+ # check zero division
97
+ assert_raises(ZeroDivisionError, poly.polydiv, [1], [0])
98
+
99
+ # check scalar division
100
+ quo, rem = poly.polydiv([2], [2])
101
+ assert_equal((quo, rem), (1, 0))
102
+ quo, rem = poly.polydiv([2, 2], [2])
103
+ assert_equal((quo, rem), ((1, 1), 0))
104
+
105
+ # check rest.
106
+ for i in range(5):
107
+ for j in range(5):
108
+ msg = f"At i={i}, j={j}"
109
+ ci = [0]*i + [1, 2]
110
+ cj = [0]*j + [1, 2]
111
+ tgt = poly.polyadd(ci, cj)
112
+ quo, rem = poly.polydiv(tgt, ci)
113
+ res = poly.polyadd(poly.polymul(quo, ci), rem)
114
+ assert_equal(res, tgt, err_msg=msg)
115
+
116
+ def test_polypow(self):
117
+ for i in range(5):
118
+ for j in range(5):
119
+ msg = f"At i={i}, j={j}"
120
+ c = np.arange(i + 1)
121
+ tgt = reduce(poly.polymul, [c]*j, np.array([1]))
122
+ res = poly.polypow(c, j)
123
+ assert_equal(trim(res), trim(tgt), err_msg=msg)
124
+
125
+
126
+ class TestEvaluation:
127
+ # coefficients of 1 + 2*x + 3*x**2
128
+ c1d = np.array([1., 2., 3.])
129
+ c2d = np.einsum('i,j->ij', c1d, c1d)
130
+ c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
131
+
132
+ # some random values in [-1, 1)
133
+ x = np.random.random((3, 5))*2 - 1
134
+ y = poly.polyval(x, [1., 2., 3.])
135
+
136
+ def test_polyval(self):
137
+ #check empty input
138
+ assert_equal(poly.polyval([], [1]).size, 0)
139
+
140
+ #check normal input)
141
+ x = np.linspace(-1, 1)
142
+ y = [x**i for i in range(5)]
143
+ for i in range(5):
144
+ tgt = y[i]
145
+ res = poly.polyval(x, [0]*i + [1])
146
+ assert_almost_equal(res, tgt)
147
+ tgt = x*(x**2 - 1)
148
+ res = poly.polyval(x, [0, -1, 0, 1])
149
+ assert_almost_equal(res, tgt)
150
+
151
+ #check that shape is preserved
152
+ for i in range(3):
153
+ dims = [2]*i
154
+ x = np.zeros(dims)
155
+ assert_equal(poly.polyval(x, [1]).shape, dims)
156
+ assert_equal(poly.polyval(x, [1, 0]).shape, dims)
157
+ assert_equal(poly.polyval(x, [1, 0, 0]).shape, dims)
158
+
159
+ #check masked arrays are processed correctly
160
+ mask = [False, True, False]
161
+ mx = np.ma.array([1, 2, 3], mask=mask)
162
+ res = np.polyval([7, 5, 3], mx)
163
+ assert_array_equal(res.mask, mask)
164
+
165
+ #check subtypes of ndarray are preserved
166
+ class C(np.ndarray):
167
+ pass
168
+
169
+ cx = np.array([1, 2, 3]).view(C)
170
+ assert_equal(type(np.polyval([2, 3, 4], cx)), C)
171
+
172
+ def test_polyvalfromroots(self):
173
+ # check exception for broadcasting x values over root array with
174
+ # too few dimensions
175
+ assert_raises(ValueError, poly.polyvalfromroots,
176
+ [1], [1], tensor=False)
177
+
178
+ # check empty input
179
+ assert_equal(poly.polyvalfromroots([], [1]).size, 0)
180
+ assert_(poly.polyvalfromroots([], [1]).shape == (0,))
181
+
182
+ # check empty input + multidimensional roots
183
+ assert_equal(poly.polyvalfromroots([], [[1] * 5]).size, 0)
184
+ assert_(poly.polyvalfromroots([], [[1] * 5]).shape == (5, 0))
185
+
186
+ # check scalar input
187
+ assert_equal(poly.polyvalfromroots(1, 1), 0)
188
+ assert_(poly.polyvalfromroots(1, np.ones((3, 3))).shape == (3,))
189
+
190
+ # check normal input)
191
+ x = np.linspace(-1, 1)
192
+ y = [x**i for i in range(5)]
193
+ for i in range(1, 5):
194
+ tgt = y[i]
195
+ res = poly.polyvalfromroots(x, [0]*i)
196
+ assert_almost_equal(res, tgt)
197
+ tgt = x*(x - 1)*(x + 1)
198
+ res = poly.polyvalfromroots(x, [-1, 0, 1])
199
+ assert_almost_equal(res, tgt)
200
+
201
+ # check that shape is preserved
202
+ for i in range(3):
203
+ dims = [2]*i
204
+ x = np.zeros(dims)
205
+ assert_equal(poly.polyvalfromroots(x, [1]).shape, dims)
206
+ assert_equal(poly.polyvalfromroots(x, [1, 0]).shape, dims)
207
+ assert_equal(poly.polyvalfromroots(x, [1, 0, 0]).shape, dims)
208
+
209
+ # check compatibility with factorization
210
+ ptest = [15, 2, -16, -2, 1]
211
+ r = poly.polyroots(ptest)
212
+ x = np.linspace(-1, 1)
213
+ assert_almost_equal(poly.polyval(x, ptest),
214
+ poly.polyvalfromroots(x, r))
215
+
216
+ # check multidimensional arrays of roots and values
217
+ # check tensor=False
218
+ rshape = (3, 5)
219
+ x = np.arange(-3, 2)
220
+ r = np.random.randint(-5, 5, size=rshape)
221
+ res = poly.polyvalfromroots(x, r, tensor=False)
222
+ tgt = np.empty(r.shape[1:])
223
+ for ii in range(tgt.size):
224
+ tgt[ii] = poly.polyvalfromroots(x[ii], r[:, ii])
225
+ assert_equal(res, tgt)
226
+
227
+ # check tensor=True
228
+ x = np.vstack([x, 2*x])
229
+ res = poly.polyvalfromroots(x, r, tensor=True)
230
+ tgt = np.empty(r.shape[1:] + x.shape)
231
+ for ii in range(r.shape[1]):
232
+ for jj in range(x.shape[0]):
233
+ tgt[ii, jj, :] = poly.polyvalfromroots(x[jj], r[:, ii])
234
+ assert_equal(res, tgt)
235
+
236
+ def test_polyval2d(self):
237
+ x1, x2, x3 = self.x
238
+ y1, y2, y3 = self.y
239
+
240
+ #test exceptions
241
+ assert_raises_regex(ValueError, 'incompatible',
242
+ poly.polyval2d, x1, x2[:2], self.c2d)
243
+
244
+ #test values
245
+ tgt = y1*y2
246
+ res = poly.polyval2d(x1, x2, self.c2d)
247
+ assert_almost_equal(res, tgt)
248
+
249
+ #test shape
250
+ z = np.ones((2, 3))
251
+ res = poly.polyval2d(z, z, self.c2d)
252
+ assert_(res.shape == (2, 3))
253
+
254
+ def test_polyval3d(self):
255
+ x1, x2, x3 = self.x
256
+ y1, y2, y3 = self.y
257
+
258
+ #test exceptions
259
+ assert_raises_regex(ValueError, 'incompatible',
260
+ poly.polyval3d, x1, x2, x3[:2], self.c3d)
261
+
262
+ #test values
263
+ tgt = y1*y2*y3
264
+ res = poly.polyval3d(x1, x2, x3, self.c3d)
265
+ assert_almost_equal(res, tgt)
266
+
267
+ #test shape
268
+ z = np.ones((2, 3))
269
+ res = poly.polyval3d(z, z, z, self.c3d)
270
+ assert_(res.shape == (2, 3))
271
+
272
+ def test_polygrid2d(self):
273
+ x1, x2, x3 = self.x
274
+ y1, y2, y3 = self.y
275
+
276
+ #test values
277
+ tgt = np.einsum('i,j->ij', y1, y2)
278
+ res = poly.polygrid2d(x1, x2, self.c2d)
279
+ assert_almost_equal(res, tgt)
280
+
281
+ #test shape
282
+ z = np.ones((2, 3))
283
+ res = poly.polygrid2d(z, z, self.c2d)
284
+ assert_(res.shape == (2, 3)*2)
285
+
286
+ def test_polygrid3d(self):
287
+ x1, x2, x3 = self.x
288
+ y1, y2, y3 = self.y
289
+
290
+ #test values
291
+ tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
292
+ res = poly.polygrid3d(x1, x2, x3, self.c3d)
293
+ assert_almost_equal(res, tgt)
294
+
295
+ #test shape
296
+ z = np.ones((2, 3))
297
+ res = poly.polygrid3d(z, z, z, self.c3d)
298
+ assert_(res.shape == (2, 3)*3)
299
+
300
+
301
+ class TestIntegral:
302
+
303
+ def test_polyint(self):
304
+ # check exceptions
305
+ assert_raises(TypeError, poly.polyint, [0], .5)
306
+ assert_raises(ValueError, poly.polyint, [0], -1)
307
+ assert_raises(ValueError, poly.polyint, [0], 1, [0, 0])
308
+ assert_raises(ValueError, poly.polyint, [0], lbnd=[0])
309
+ assert_raises(ValueError, poly.polyint, [0], scl=[0])
310
+ assert_raises(TypeError, poly.polyint, [0], axis=.5)
311
+ with assert_warns(DeprecationWarning):
312
+ poly.polyint([1, 1], 1.)
313
+
314
+ # test integration of zero polynomial
315
+ for i in range(2, 5):
316
+ k = [0]*(i - 2) + [1]
317
+ res = poly.polyint([0], m=i, k=k)
318
+ assert_almost_equal(res, [0, 1])
319
+
320
+ # check single integration with integration constant
321
+ for i in range(5):
322
+ scl = i + 1
323
+ pol = [0]*i + [1]
324
+ tgt = [i] + [0]*i + [1/scl]
325
+ res = poly.polyint(pol, m=1, k=[i])
326
+ assert_almost_equal(trim(res), trim(tgt))
327
+
328
+ # check single integration with integration constant and lbnd
329
+ for i in range(5):
330
+ scl = i + 1
331
+ pol = [0]*i + [1]
332
+ res = poly.polyint(pol, m=1, k=[i], lbnd=-1)
333
+ assert_almost_equal(poly.polyval(-1, res), i)
334
+
335
+ # check single integration with integration constant and scaling
336
+ for i in range(5):
337
+ scl = i + 1
338
+ pol = [0]*i + [1]
339
+ tgt = [i] + [0]*i + [2/scl]
340
+ res = poly.polyint(pol, m=1, k=[i], scl=2)
341
+ assert_almost_equal(trim(res), trim(tgt))
342
+
343
+ # check multiple integrations with default k
344
+ for i in range(5):
345
+ for j in range(2, 5):
346
+ pol = [0]*i + [1]
347
+ tgt = pol[:]
348
+ for k in range(j):
349
+ tgt = poly.polyint(tgt, m=1)
350
+ res = poly.polyint(pol, m=j)
351
+ assert_almost_equal(trim(res), trim(tgt))
352
+
353
+ # check multiple integrations with defined k
354
+ for i in range(5):
355
+ for j in range(2, 5):
356
+ pol = [0]*i + [1]
357
+ tgt = pol[:]
358
+ for k in range(j):
359
+ tgt = poly.polyint(tgt, m=1, k=[k])
360
+ res = poly.polyint(pol, m=j, k=list(range(j)))
361
+ assert_almost_equal(trim(res), trim(tgt))
362
+
363
+ # check multiple integrations with lbnd
364
+ for i in range(5):
365
+ for j in range(2, 5):
366
+ pol = [0]*i + [1]
367
+ tgt = pol[:]
368
+ for k in range(j):
369
+ tgt = poly.polyint(tgt, m=1, k=[k], lbnd=-1)
370
+ res = poly.polyint(pol, m=j, k=list(range(j)), lbnd=-1)
371
+ assert_almost_equal(trim(res), trim(tgt))
372
+
373
+ # check multiple integrations with scaling
374
+ for i in range(5):
375
+ for j in range(2, 5):
376
+ pol = [0]*i + [1]
377
+ tgt = pol[:]
378
+ for k in range(j):
379
+ tgt = poly.polyint(tgt, m=1, k=[k], scl=2)
380
+ res = poly.polyint(pol, m=j, k=list(range(j)), scl=2)
381
+ assert_almost_equal(trim(res), trim(tgt))
382
+
383
+ def test_polyint_axis(self):
384
+ # check that axis keyword works
385
+ c2d = np.random.random((3, 4))
386
+
387
+ tgt = np.vstack([poly.polyint(c) for c in c2d.T]).T
388
+ res = poly.polyint(c2d, axis=0)
389
+ assert_almost_equal(res, tgt)
390
+
391
+ tgt = np.vstack([poly.polyint(c) for c in c2d])
392
+ res = poly.polyint(c2d, axis=1)
393
+ assert_almost_equal(res, tgt)
394
+
395
+ tgt = np.vstack([poly.polyint(c, k=3) for c in c2d])
396
+ res = poly.polyint(c2d, k=3, axis=1)
397
+ assert_almost_equal(res, tgt)
398
+
399
+
400
+ class TestDerivative:
401
+
402
+ def test_polyder(self):
403
+ # check exceptions
404
+ assert_raises(TypeError, poly.polyder, [0], .5)
405
+ assert_raises(ValueError, poly.polyder, [0], -1)
406
+
407
+ # check that zeroth derivative does nothing
408
+ for i in range(5):
409
+ tgt = [0]*i + [1]
410
+ res = poly.polyder(tgt, m=0)
411
+ assert_equal(trim(res), trim(tgt))
412
+
413
+ # check that derivation is the inverse of integration
414
+ for i in range(5):
415
+ for j in range(2, 5):
416
+ tgt = [0]*i + [1]
417
+ res = poly.polyder(poly.polyint(tgt, m=j), m=j)
418
+ assert_almost_equal(trim(res), trim(tgt))
419
+
420
+ # check derivation with scaling
421
+ for i in range(5):
422
+ for j in range(2, 5):
423
+ tgt = [0]*i + [1]
424
+ res = poly.polyder(poly.polyint(tgt, m=j, scl=2), m=j, scl=.5)
425
+ assert_almost_equal(trim(res), trim(tgt))
426
+
427
+ def test_polyder_axis(self):
428
+ # check that axis keyword works
429
+ c2d = np.random.random((3, 4))
430
+
431
+ tgt = np.vstack([poly.polyder(c) for c in c2d.T]).T
432
+ res = poly.polyder(c2d, axis=0)
433
+ assert_almost_equal(res, tgt)
434
+
435
+ tgt = np.vstack([poly.polyder(c) for c in c2d])
436
+ res = poly.polyder(c2d, axis=1)
437
+ assert_almost_equal(res, tgt)
438
+
439
+
440
+ class TestVander:
441
+ # some random values in [-1, 1)
442
+ x = np.random.random((3, 5))*2 - 1
443
+
444
+ def test_polyvander(self):
445
+ # check for 1d x
446
+ x = np.arange(3)
447
+ v = poly.polyvander(x, 3)
448
+ assert_(v.shape == (3, 4))
449
+ for i in range(4):
450
+ coef = [0]*i + [1]
451
+ assert_almost_equal(v[..., i], poly.polyval(x, coef))
452
+
453
+ # check for 2d x
454
+ x = np.array([[1, 2], [3, 4], [5, 6]])
455
+ v = poly.polyvander(x, 3)
456
+ assert_(v.shape == (3, 2, 4))
457
+ for i in range(4):
458
+ coef = [0]*i + [1]
459
+ assert_almost_equal(v[..., i], poly.polyval(x, coef))
460
+
461
+ def test_polyvander2d(self):
462
+ # also tests polyval2d for non-square coefficient array
463
+ x1, x2, x3 = self.x
464
+ c = np.random.random((2, 3))
465
+ van = poly.polyvander2d(x1, x2, [1, 2])
466
+ tgt = poly.polyval2d(x1, x2, c)
467
+ res = np.dot(van, c.flat)
468
+ assert_almost_equal(res, tgt)
469
+
470
+ # check shape
471
+ van = poly.polyvander2d([x1], [x2], [1, 2])
472
+ assert_(van.shape == (1, 5, 6))
473
+
474
+ def test_polyvander3d(self):
475
+ # also tests polyval3d for non-square coefficient array
476
+ x1, x2, x3 = self.x
477
+ c = np.random.random((2, 3, 4))
478
+ van = poly.polyvander3d(x1, x2, x3, [1, 2, 3])
479
+ tgt = poly.polyval3d(x1, x2, x3, c)
480
+ res = np.dot(van, c.flat)
481
+ assert_almost_equal(res, tgt)
482
+
483
+ # check shape
484
+ van = poly.polyvander3d([x1], [x2], [x3], [1, 2, 3])
485
+ assert_(van.shape == (1, 5, 24))
486
+
487
+ def test_polyvandernegdeg(self):
488
+ x = np.arange(3)
489
+ assert_raises(ValueError, poly.polyvander, x, -1)
490
+
491
+
492
+ class TestCompanion:
493
+
494
+ def test_raises(self):
495
+ assert_raises(ValueError, poly.polycompanion, [])
496
+ assert_raises(ValueError, poly.polycompanion, [1])
497
+
498
+ def test_dimensions(self):
499
+ for i in range(1, 5):
500
+ coef = [0]*i + [1]
501
+ assert_(poly.polycompanion(coef).shape == (i, i))
502
+
503
+ def test_linear_root(self):
504
+ assert_(poly.polycompanion([1, 2])[0, 0] == -.5)
505
+
506
+
507
+ class TestMisc:
508
+
509
+ def test_polyfromroots(self):
510
+ res = poly.polyfromroots([])
511
+ assert_almost_equal(trim(res), [1])
512
+ for i in range(1, 5):
513
+ roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
514
+ tgt = Tlist[i]
515
+ res = poly.polyfromroots(roots)*2**(i-1)
516
+ assert_almost_equal(trim(res), trim(tgt))
517
+
518
+ def test_polyroots(self):
519
+ assert_almost_equal(poly.polyroots([1]), [])
520
+ assert_almost_equal(poly.polyroots([1, 2]), [-.5])
521
+ for i in range(2, 5):
522
+ tgt = np.linspace(-1, 1, i)
523
+ res = poly.polyroots(poly.polyfromroots(tgt))
524
+ assert_almost_equal(trim(res), trim(tgt))
525
+
526
+ def test_polyfit(self):
527
+ def f(x):
528
+ return x*(x - 1)*(x - 2)
529
+
530
+ def f2(x):
531
+ return x**4 + x**2 + 1
532
+
533
+ # Test exceptions
534
+ assert_raises(ValueError, poly.polyfit, [1], [1], -1)
535
+ assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)
536
+ assert_raises(TypeError, poly.polyfit, [], [1], 0)
537
+ assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)
538
+ assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)
539
+ assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)
540
+ assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])
541
+ assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])
542
+ assert_raises(ValueError, poly.polyfit, [1], [1], [-1,])
543
+ assert_raises(ValueError, poly.polyfit, [1], [1], [2, -1, 6])
544
+ assert_raises(TypeError, poly.polyfit, [1], [1], [])
545
+
546
+ # Test fit
547
+ x = np.linspace(0, 2)
548
+ y = f(x)
549
+ #
550
+ coef3 = poly.polyfit(x, y, 3)
551
+ assert_equal(len(coef3), 4)
552
+ assert_almost_equal(poly.polyval(x, coef3), y)
553
+ coef3 = poly.polyfit(x, y, [0, 1, 2, 3])
554
+ assert_equal(len(coef3), 4)
555
+ assert_almost_equal(poly.polyval(x, coef3), y)
556
+ #
557
+ coef4 = poly.polyfit(x, y, 4)
558
+ assert_equal(len(coef4), 5)
559
+ assert_almost_equal(poly.polyval(x, coef4), y)
560
+ coef4 = poly.polyfit(x, y, [0, 1, 2, 3, 4])
561
+ assert_equal(len(coef4), 5)
562
+ assert_almost_equal(poly.polyval(x, coef4), y)
563
+ #
564
+ coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
565
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
566
+ coef2d = poly.polyfit(x, np.array([y, y]).T, [0, 1, 2, 3])
567
+ assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
568
+ # test weighting
569
+ w = np.zeros_like(x)
570
+ yw = y.copy()
571
+ w[1::2] = 1
572
+ yw[0::2] = 0
573
+ wcoef3 = poly.polyfit(x, yw, 3, w=w)
574
+ assert_almost_equal(wcoef3, coef3)
575
+ wcoef3 = poly.polyfit(x, yw, [0, 1, 2, 3], w=w)
576
+ assert_almost_equal(wcoef3, coef3)
577
+ #
578
+ wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
579
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
580
+ wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
581
+ assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
582
+ # test scaling with complex values x points whose square
583
+ # is zero when summed.
584
+ x = [1, 1j, -1, -1j]
585
+ assert_almost_equal(poly.polyfit(x, x, 1), [0, 1])
586
+ assert_almost_equal(poly.polyfit(x, x, [0, 1]), [0, 1])
587
+ # test fitting only even Polyendre polynomials
588
+ x = np.linspace(-1, 1)
589
+ y = f2(x)
590
+ coef1 = poly.polyfit(x, y, 4)
591
+ assert_almost_equal(poly.polyval(x, coef1), y)
592
+ coef2 = poly.polyfit(x, y, [0, 2, 4])
593
+ assert_almost_equal(poly.polyval(x, coef2), y)
594
+ assert_almost_equal(coef1, coef2)
595
+
596
+ def test_polytrim(self):
597
+ coef = [2, -1, 1, 0]
598
+
599
+ # Test exceptions
600
+ assert_raises(ValueError, poly.polytrim, coef, -1)
601
+
602
+ # Test results
603
+ assert_equal(poly.polytrim(coef), coef[:-1])
604
+ assert_equal(poly.polytrim(coef, 1), coef[:-3])
605
+ assert_equal(poly.polytrim(coef, 2), [0])
606
+
607
+ def test_polyline(self):
608
+ assert_equal(poly.polyline(3, 4), [3, 4])
609
+
610
+ def test_polyline_zero(self):
611
+ assert_equal(poly.polyline(3, 0), [3])
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_polyutils.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for polyutils module.
2
+
3
+ """
4
+ import numpy as np
5
+ import numpy.polynomial.polyutils as pu
6
+ from numpy.testing import (
7
+ assert_almost_equal, assert_raises, assert_equal, assert_,
8
+ )
9
+
10
+
11
+ class TestMisc:
12
+
13
+ def test_trimseq(self):
14
+ for i in range(5):
15
+ tgt = [1]
16
+ res = pu.trimseq([1] + [0]*5)
17
+ assert_equal(res, tgt)
18
+
19
+ def test_as_series(self):
20
+ # check exceptions
21
+ assert_raises(ValueError, pu.as_series, [[]])
22
+ assert_raises(ValueError, pu.as_series, [[[1, 2]]])
23
+ assert_raises(ValueError, pu.as_series, [[1], ['a']])
24
+ # check common types
25
+ types = ['i', 'd', 'O']
26
+ for i in range(len(types)):
27
+ for j in range(i):
28
+ ci = np.ones(1, types[i])
29
+ cj = np.ones(1, types[j])
30
+ [resi, resj] = pu.as_series([ci, cj])
31
+ assert_(resi.dtype.char == resj.dtype.char)
32
+ assert_(resj.dtype.char == types[i])
33
+
34
+ def test_trimcoef(self):
35
+ coef = [2, -1, 1, 0]
36
+ # Test exceptions
37
+ assert_raises(ValueError, pu.trimcoef, coef, -1)
38
+ # Test results
39
+ assert_equal(pu.trimcoef(coef), coef[:-1])
40
+ assert_equal(pu.trimcoef(coef, 1), coef[:-3])
41
+ assert_equal(pu.trimcoef(coef, 2), [0])
42
+
43
+ def test_vander_nd_exception(self):
44
+ # n_dims != len(points)
45
+ assert_raises(ValueError, pu._vander_nd, (), (1, 2, 3), [90])
46
+ # n_dims != len(degrees)
47
+ assert_raises(ValueError, pu._vander_nd, (), (), [90.65])
48
+ # n_dims == 0
49
+ assert_raises(ValueError, pu._vander_nd, (), (), [])
50
+
51
+ def test_div_zerodiv(self):
52
+ # c2[-1] == 0
53
+ assert_raises(ZeroDivisionError, pu._div, pu._div, (1, 2, 3), [0])
54
+
55
+ def test_pow_too_large(self):
56
+ # power > maxpower
57
+ assert_raises(ValueError, pu._pow, (), [1, 2, 3], 5, 4)
58
+
59
+ class TestDomain:
60
+
61
+ def test_getdomain(self):
62
+ # test for real values
63
+ x = [1, 10, 3, -1]
64
+ tgt = [-1, 10]
65
+ res = pu.getdomain(x)
66
+ assert_almost_equal(res, tgt)
67
+
68
+ # test for complex values
69
+ x = [1 + 1j, 1 - 1j, 0, 2]
70
+ tgt = [-1j, 2 + 1j]
71
+ res = pu.getdomain(x)
72
+ assert_almost_equal(res, tgt)
73
+
74
+ def test_mapdomain(self):
75
+ # test for real values
76
+ dom1 = [0, 4]
77
+ dom2 = [1, 3]
78
+ tgt = dom2
79
+ res = pu.mapdomain(dom1, dom1, dom2)
80
+ assert_almost_equal(res, tgt)
81
+
82
+ # test for complex values
83
+ dom1 = [0 - 1j, 2 + 1j]
84
+ dom2 = [-2, 2]
85
+ tgt = dom2
86
+ x = dom1
87
+ res = pu.mapdomain(x, dom1, dom2)
88
+ assert_almost_equal(res, tgt)
89
+
90
+ # test for multidimensional arrays
91
+ dom1 = [0, 4]
92
+ dom2 = [1, 3]
93
+ tgt = np.array([dom2, dom2])
94
+ x = np.array([dom1, dom1])
95
+ res = pu.mapdomain(x, dom1, dom2)
96
+ assert_almost_equal(res, tgt)
97
+
98
+ # test that subtypes are preserved.
99
+ class MyNDArray(np.ndarray):
100
+ pass
101
+
102
+ dom1 = [0, 4]
103
+ dom2 = [1, 3]
104
+ x = np.array([dom1, dom1]).view(MyNDArray)
105
+ res = pu.mapdomain(x, dom1, dom2)
106
+ assert_(isinstance(res, MyNDArray))
107
+
108
+ def test_mapparms(self):
109
+ # test for real values
110
+ dom1 = [0, 4]
111
+ dom2 = [1, 3]
112
+ tgt = [1, .5]
113
+ res = pu. mapparms(dom1, dom2)
114
+ assert_almost_equal(res, tgt)
115
+
116
+ # test for complex values
117
+ dom1 = [0 - 1j, 2 + 1j]
118
+ dom2 = [-2, 2]
119
+ tgt = [-1 + 1j, 1 - 1j]
120
+ res = pu.mapparms(dom1, dom2)
121
+ assert_almost_equal(res, tgt)
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_printing.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import nan, inf
2
+ import pytest
3
+ from numpy.core import array, arange, printoptions
4
+ import numpy.polynomial as poly
5
+ from numpy.testing import assert_equal, assert_
6
+
7
+ # For testing polynomial printing with object arrays
8
+ from fractions import Fraction
9
+ from decimal import Decimal
10
+
11
+
12
+ class TestStrUnicodeSuperSubscripts:
13
+
14
+ @pytest.fixture(scope='class', autouse=True)
15
+ def use_unicode(self):
16
+ poly.set_default_printstyle('unicode')
17
+
18
+ @pytest.mark.parametrize(('inp', 'tgt'), (
19
+ ([1, 2, 3], "1.0 + 2.0·x + 3.0·x²"),
20
+ ([-1, 0, 3, -1], "-1.0 + 0.0·x + 3.0·x² - 1.0·x³"),
21
+ (arange(12), ("0.0 + 1.0·x + 2.0·x² + 3.0·x³ + 4.0·x⁴ + 5.0·x⁵ + "
22
+ "6.0·x⁶ + 7.0·x⁷ +\n8.0·x⁸ + 9.0·x⁹ + 10.0·x¹⁰ + "
23
+ "11.0·x¹¹")),
24
+ ))
25
+ def test_polynomial_str(self, inp, tgt):
26
+ res = str(poly.Polynomial(inp))
27
+ assert_equal(res, tgt)
28
+
29
+ @pytest.mark.parametrize(('inp', 'tgt'), (
30
+ ([1, 2, 3], "1.0 + 2.0·T₁(x) + 3.0·T₂(x)"),
31
+ ([-1, 0, 3, -1], "-1.0 + 0.0·T₁(x) + 3.0·T₂(x) - 1.0·T₃(x)"),
32
+ (arange(12), ("0.0 + 1.0·T₁(x) + 2.0·T₂(x) + 3.0·T₃(x) + 4.0·T₄(x) + "
33
+ "5.0·T₅(x) +\n6.0·T₆(x) + 7.0·T₇(x) + 8.0·T₈(x) + "
34
+ "9.0·T₉(x) + 10.0·T₁₀(x) + 11.0·T₁₁(x)")),
35
+ ))
36
+ def test_chebyshev_str(self, inp, tgt):
37
+ res = str(poly.Chebyshev(inp))
38
+ assert_equal(res, tgt)
39
+
40
+ @pytest.mark.parametrize(('inp', 'tgt'), (
41
+ ([1, 2, 3], "1.0 + 2.0·P₁(x) + 3.0·P₂(x)"),
42
+ ([-1, 0, 3, -1], "-1.0 + 0.0·P₁(x) + 3.0·P₂(x) - 1.0·P₃(x)"),
43
+ (arange(12), ("0.0 + 1.0·P₁(x) + 2.0·P₂(x) + 3.0·P₃(x) + 4.0·P₄(x) + "
44
+ "5.0·P₅(x) +\n6.0·P₆(x) + 7.0·P₇(x) + 8.0·P₈(x) + "
45
+ "9.0·P₉(x) + 10.0·P₁₀(x) + 11.0·P₁₁(x)")),
46
+ ))
47
+ def test_legendre_str(self, inp, tgt):
48
+ res = str(poly.Legendre(inp))
49
+ assert_equal(res, tgt)
50
+
51
+ @pytest.mark.parametrize(('inp', 'tgt'), (
52
+ ([1, 2, 3], "1.0 + 2.0·H₁(x) + 3.0·H₂(x)"),
53
+ ([-1, 0, 3, -1], "-1.0 + 0.0·H₁(x) + 3.0·H₂(x) - 1.0·H₃(x)"),
54
+ (arange(12), ("0.0 + 1.0·H₁(x) + 2.0·H₂(x) + 3.0·H₃(x) + 4.0·H₄(x) + "
55
+ "5.0·H₅(x) +\n6.0·H₆(x) + 7.0·H₇(x) + 8.0·H₈(x) + "
56
+ "9.0·H₉(x) + 10.0·H₁₀(x) + 11.0·H₁₁(x)")),
57
+ ))
58
+ def test_hermite_str(self, inp, tgt):
59
+ res = str(poly.Hermite(inp))
60
+ assert_equal(res, tgt)
61
+
62
+ @pytest.mark.parametrize(('inp', 'tgt'), (
63
+ ([1, 2, 3], "1.0 + 2.0·He₁(x) + 3.0·He₂(x)"),
64
+ ([-1, 0, 3, -1], "-1.0 + 0.0·He₁(x) + 3.0·He₂(x) - 1.0·He₃(x)"),
65
+ (arange(12), ("0.0 + 1.0·He₁(x) + 2.0·He₂(x) + 3.0·He₃(x) + "
66
+ "4.0·He₄(x) + 5.0·He₅(x) +\n6.0·He₆(x) + 7.0·He₇(x) + "
67
+ "8.0·He₈(x) + 9.0·He₉(x) + 10.0·He₁₀(x) +\n"
68
+ "11.0·He₁₁(x)")),
69
+ ))
70
+ def test_hermiteE_str(self, inp, tgt):
71
+ res = str(poly.HermiteE(inp))
72
+ assert_equal(res, tgt)
73
+
74
+ @pytest.mark.parametrize(('inp', 'tgt'), (
75
+ ([1, 2, 3], "1.0 + 2.0·L₁(x) + 3.0·L₂(x)"),
76
+ ([-1, 0, 3, -1], "-1.0 + 0.0·L₁(x) + 3.0·L₂(x) - 1.0·L₃(x)"),
77
+ (arange(12), ("0.0 + 1.0·L₁(x) + 2.0·L₂(x) + 3.0·L₃(x) + 4.0·L₄(x) + "
78
+ "5.0·L₅(x) +\n6.0·L₆(x) + 7.0·L₇(x) + 8.0·L₈(x) + "
79
+ "9.0·L₉(x) + 10.0·L₁₀(x) + 11.0·L₁₁(x)")),
80
+ ))
81
+ def test_laguerre_str(self, inp, tgt):
82
+ res = str(poly.Laguerre(inp))
83
+ assert_equal(res, tgt)
84
+
85
+
86
+ class TestStrAscii:
87
+
88
+ @pytest.fixture(scope='class', autouse=True)
89
+ def use_ascii(self):
90
+ poly.set_default_printstyle('ascii')
91
+
92
+ @pytest.mark.parametrize(('inp', 'tgt'), (
93
+ ([1, 2, 3], "1.0 + 2.0 x + 3.0 x**2"),
94
+ ([-1, 0, 3, -1], "-1.0 + 0.0 x + 3.0 x**2 - 1.0 x**3"),
95
+ (arange(12), ("0.0 + 1.0 x + 2.0 x**2 + 3.0 x**3 + 4.0 x**4 + "
96
+ "5.0 x**5 + 6.0 x**6 +\n7.0 x**7 + 8.0 x**8 + "
97
+ "9.0 x**9 + 10.0 x**10 + 11.0 x**11")),
98
+ ))
99
+ def test_polynomial_str(self, inp, tgt):
100
+ res = str(poly.Polynomial(inp))
101
+ assert_equal(res, tgt)
102
+
103
+ @pytest.mark.parametrize(('inp', 'tgt'), (
104
+ ([1, 2, 3], "1.0 + 2.0 T_1(x) + 3.0 T_2(x)"),
105
+ ([-1, 0, 3, -1], "-1.0 + 0.0 T_1(x) + 3.0 T_2(x) - 1.0 T_3(x)"),
106
+ (arange(12), ("0.0 + 1.0 T_1(x) + 2.0 T_2(x) + 3.0 T_3(x) + "
107
+ "4.0 T_4(x) + 5.0 T_5(x) +\n6.0 T_6(x) + 7.0 T_7(x) + "
108
+ "8.0 T_8(x) + 9.0 T_9(x) + 10.0 T_10(x) +\n"
109
+ "11.0 T_11(x)")),
110
+ ))
111
+ def test_chebyshev_str(self, inp, tgt):
112
+ res = str(poly.Chebyshev(inp))
113
+ assert_equal(res, tgt)
114
+
115
+ @pytest.mark.parametrize(('inp', 'tgt'), (
116
+ ([1, 2, 3], "1.0 + 2.0 P_1(x) + 3.0 P_2(x)"),
117
+ ([-1, 0, 3, -1], "-1.0 + 0.0 P_1(x) + 3.0 P_2(x) - 1.0 P_3(x)"),
118
+ (arange(12), ("0.0 + 1.0 P_1(x) + 2.0 P_2(x) + 3.0 P_3(x) + "
119
+ "4.0 P_4(x) + 5.0 P_5(x) +\n6.0 P_6(x) + 7.0 P_7(x) + "
120
+ "8.0 P_8(x) + 9.0 P_9(x) + 10.0 P_10(x) +\n"
121
+ "11.0 P_11(x)")),
122
+ ))
123
+ def test_legendre_str(self, inp, tgt):
124
+ res = str(poly.Legendre(inp))
125
+ assert_equal(res, tgt)
126
+
127
+ @pytest.mark.parametrize(('inp', 'tgt'), (
128
+ ([1, 2, 3], "1.0 + 2.0 H_1(x) + 3.0 H_2(x)"),
129
+ ([-1, 0, 3, -1], "-1.0 + 0.0 H_1(x) + 3.0 H_2(x) - 1.0 H_3(x)"),
130
+ (arange(12), ("0.0 + 1.0 H_1(x) + 2.0 H_2(x) + 3.0 H_3(x) + "
131
+ "4.0 H_4(x) + 5.0 H_5(x) +\n6.0 H_6(x) + 7.0 H_7(x) + "
132
+ "8.0 H_8(x) + 9.0 H_9(x) + 10.0 H_10(x) +\n"
133
+ "11.0 H_11(x)")),
134
+ ))
135
+ def test_hermite_str(self, inp, tgt):
136
+ res = str(poly.Hermite(inp))
137
+ assert_equal(res, tgt)
138
+
139
+ @pytest.mark.parametrize(('inp', 'tgt'), (
140
+ ([1, 2, 3], "1.0 + 2.0 He_1(x) + 3.0 He_2(x)"),
141
+ ([-1, 0, 3, -1], "-1.0 + 0.0 He_1(x) + 3.0 He_2(x) - 1.0 He_3(x)"),
142
+ (arange(12), ("0.0 + 1.0 He_1(x) + 2.0 He_2(x) + 3.0 He_3(x) + "
143
+ "4.0 He_4(x) +\n5.0 He_5(x) + 6.0 He_6(x) + "
144
+ "7.0 He_7(x) + 8.0 He_8(x) + 9.0 He_9(x) +\n"
145
+ "10.0 He_10(x) + 11.0 He_11(x)")),
146
+ ))
147
+ def test_hermiteE_str(self, inp, tgt):
148
+ res = str(poly.HermiteE(inp))
149
+ assert_equal(res, tgt)
150
+
151
+ @pytest.mark.parametrize(('inp', 'tgt'), (
152
+ ([1, 2, 3], "1.0 + 2.0 L_1(x) + 3.0 L_2(x)"),
153
+ ([-1, 0, 3, -1], "-1.0 + 0.0 L_1(x) + 3.0 L_2(x) - 1.0 L_3(x)"),
154
+ (arange(12), ("0.0 + 1.0 L_1(x) + 2.0 L_2(x) + 3.0 L_3(x) + "
155
+ "4.0 L_4(x) + 5.0 L_5(x) +\n6.0 L_6(x) + 7.0 L_7(x) + "
156
+ "8.0 L_8(x) + 9.0 L_9(x) + 10.0 L_10(x) +\n"
157
+ "11.0 L_11(x)")),
158
+ ))
159
+ def test_laguerre_str(self, inp, tgt):
160
+ res = str(poly.Laguerre(inp))
161
+ assert_equal(res, tgt)
162
+
163
+
164
+ class TestLinebreaking:
165
+
166
+ @pytest.fixture(scope='class', autouse=True)
167
+ def use_ascii(self):
168
+ poly.set_default_printstyle('ascii')
169
+
170
+ def test_single_line_one_less(self):
171
+ # With 'ascii' style, len(str(p)) is default linewidth - 1 (i.e. 74)
172
+ p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 123])
173
+ assert_equal(len(str(p)), 74)
174
+ assert_equal(str(p), (
175
+ '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
176
+ '12345678.0 x**3 + 123.0 x**4'
177
+ ))
178
+
179
+ def test_num_chars_is_linewidth(self):
180
+ # len(str(p)) == default linewidth == 75
181
+ p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 1234])
182
+ assert_equal(len(str(p)), 75)
183
+ assert_equal(str(p), (
184
+ '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
185
+ '12345678.0 x**3 +\n1234.0 x**4'
186
+ ))
187
+
188
+ def test_first_linebreak_multiline_one_less_than_linewidth(self):
189
+ # Multiline str where len(first_line) + len(next_term) == lw - 1 == 74
190
+ p = poly.Polynomial(
191
+ [12345678, 12345678, 12345678, 12345678, 1, 12345678]
192
+ )
193
+ assert_equal(len(str(p).split('\n')[0]), 74)
194
+ assert_equal(str(p), (
195
+ '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
196
+ '12345678.0 x**3 + 1.0 x**4 +\n12345678.0 x**5'
197
+ ))
198
+
199
+ def test_first_linebreak_multiline_on_linewidth(self):
200
+ # First line is one character longer than previous test
201
+ p = poly.Polynomial(
202
+ [12345678, 12345678, 12345678, 12345678.12, 1, 12345678]
203
+ )
204
+ assert_equal(str(p), (
205
+ '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
206
+ '12345678.12 x**3 +\n1.0 x**4 + 12345678.0 x**5'
207
+ ))
208
+
209
+ @pytest.mark.parametrize(('lw', 'tgt'), (
210
+ (75, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
211
+ '500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
212
+ '900.0 x**9')),
213
+ (45, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 +\n40000.0 x**4 + '
214
+ '500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 +\n'
215
+ '900.0 x**9')),
216
+ (132, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
217
+ '500000.0 x**5 + 600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
218
+ '900.0 x**9')),
219
+ ))
220
+ def test_linewidth_printoption(self, lw, tgt):
221
+ p = poly.Polynomial(
222
+ [0, 10, 200, 3000, 40000, 500000, 600000, 70000, 8000, 900]
223
+ )
224
+ with printoptions(linewidth=lw):
225
+ assert_equal(str(p), tgt)
226
+ for line in str(p).split('\n'):
227
+ assert_(len(line) < lw)
228
+
229
+
230
+ def test_set_default_printoptions():
231
+ p = poly.Polynomial([1, 2, 3])
232
+ c = poly.Chebyshev([1, 2, 3])
233
+ poly.set_default_printstyle('ascii')
234
+ assert_equal(str(p), "1.0 + 2.0 x + 3.0 x**2")
235
+ assert_equal(str(c), "1.0 + 2.0 T_1(x) + 3.0 T_2(x)")
236
+ poly.set_default_printstyle('unicode')
237
+ assert_equal(str(p), "1.0 + 2.0·x + 3.0·x²")
238
+ assert_equal(str(c), "1.0 + 2.0·T₁(x) + 3.0·T₂(x)")
239
+ with pytest.raises(ValueError):
240
+ poly.set_default_printstyle('invalid_input')
241
+
242
+
243
+ def test_complex_coefficients():
244
+ """Test both numpy and built-in complex."""
245
+ coefs = [0+1j, 1+1j, -2+2j, 3+0j]
246
+ # numpy complex
247
+ p1 = poly.Polynomial(coefs)
248
+ # Python complex
249
+ p2 = poly.Polynomial(array(coefs, dtype=object))
250
+ poly.set_default_printstyle('unicode')
251
+ assert_equal(str(p1), "1j + (1+1j)·x - (2-2j)·x² + (3+0j)·x³")
252
+ assert_equal(str(p2), "1j + (1+1j)·x + (-2+2j)·x² + (3+0j)·x³")
253
+ poly.set_default_printstyle('ascii')
254
+ assert_equal(str(p1), "1j + (1+1j) x - (2-2j) x**2 + (3+0j) x**3")
255
+ assert_equal(str(p2), "1j + (1+1j) x + (-2+2j) x**2 + (3+0j) x**3")
256
+
257
+
258
+ @pytest.mark.parametrize(('coefs', 'tgt'), (
259
+ (array([Fraction(1, 2), Fraction(3, 4)], dtype=object), (
260
+ "1/2 + 3/4·x"
261
+ )),
262
+ (array([1, 2, Fraction(5, 7)], dtype=object), (
263
+ "1 + 2·x + 5/7·x²"
264
+ )),
265
+ (array([Decimal('1.00'), Decimal('2.2'), 3], dtype=object), (
266
+ "1.00 + 2.2·x + 3·x²"
267
+ )),
268
+ ))
269
+ def test_numeric_object_coefficients(coefs, tgt):
270
+ p = poly.Polynomial(coefs)
271
+ poly.set_default_printstyle('unicode')
272
+ assert_equal(str(p), tgt)
273
+
274
+
275
+ @pytest.mark.parametrize(('coefs', 'tgt'), (
276
+ (array([1, 2, 'f'], dtype=object), '1 + 2·x + f·x²'),
277
+ (array([1, 2, [3, 4]], dtype=object), '1 + 2·x + [3, 4]·x²'),
278
+ ))
279
+ def test_nonnumeric_object_coefficients(coefs, tgt):
280
+ """
281
+ Test coef fallback for object arrays of non-numeric coefficients.
282
+ """
283
+ p = poly.Polynomial(coefs)
284
+ poly.set_default_printstyle('unicode')
285
+ assert_equal(str(p), tgt)
286
+
287
+
288
+ class TestFormat:
289
+ def test_format_unicode(self):
290
+ poly.set_default_printstyle('ascii')
291
+ p = poly.Polynomial([1, 2, 0, -1])
292
+ assert_equal(format(p, 'unicode'), "1.0 + 2.0·x + 0.0·x² - 1.0·x³")
293
+
294
+ def test_format_ascii(self):
295
+ poly.set_default_printstyle('unicode')
296
+ p = poly.Polynomial([1, 2, 0, -1])
297
+ assert_equal(
298
+ format(p, 'ascii'), "1.0 + 2.0 x + 0.0 x**2 - 1.0 x**3"
299
+ )
300
+
301
+ def test_empty_formatstr(self):
302
+ poly.set_default_printstyle('ascii')
303
+ p = poly.Polynomial([1, 2, 3])
304
+ assert_equal(format(p), "1.0 + 2.0 x + 3.0 x**2")
305
+ assert_equal(f"{p}", "1.0 + 2.0 x + 3.0 x**2")
306
+
307
+ def test_bad_formatstr(self):
308
+ p = poly.Polynomial([1, 2, 0, -1])
309
+ with pytest.raises(ValueError):
310
+ format(p, '.2f')
311
+
312
+
313
+ @pytest.mark.parametrize(('poly', 'tgt'), (
314
+ (poly.Polynomial, '1.0 + 2.0·z + 3.0·z²'),
315
+ (poly.Chebyshev, '1.0 + 2.0·T₁(z) + 3.0·T₂(z)'),
316
+ (poly.Hermite, '1.0 + 2.0·H₁(z) + 3.0·H₂(z)'),
317
+ (poly.HermiteE, '1.0 + 2.0·He₁(z) + 3.0·He₂(z)'),
318
+ (poly.Laguerre, '1.0 + 2.0·L₁(z) + 3.0·L₂(z)'),
319
+ (poly.Legendre, '1.0 + 2.0·P₁(z) + 3.0·P₂(z)'),
320
+ ))
321
+ def test_symbol(poly, tgt):
322
+ p = poly([1, 2, 3], symbol='z')
323
+ assert_equal(f"{p:unicode}", tgt)
324
+
325
+
326
+ class TestRepr:
327
+ def test_polynomial_str(self):
328
+ res = repr(poly.Polynomial([0, 1]))
329
+ tgt = (
330
+ "Polynomial([0., 1.], domain=[-1, 1], window=[-1, 1], "
331
+ "symbol='x')"
332
+ )
333
+ assert_equal(res, tgt)
334
+
335
+ def test_chebyshev_str(self):
336
+ res = repr(poly.Chebyshev([0, 1]))
337
+ tgt = (
338
+ "Chebyshev([0., 1.], domain=[-1, 1], window=[-1, 1], "
339
+ "symbol='x')"
340
+ )
341
+ assert_equal(res, tgt)
342
+
343
+ def test_legendre_repr(self):
344
+ res = repr(poly.Legendre([0, 1]))
345
+ tgt = (
346
+ "Legendre([0., 1.], domain=[-1, 1], window=[-1, 1], "
347
+ "symbol='x')"
348
+ )
349
+ assert_equal(res, tgt)
350
+
351
+ def test_hermite_repr(self):
352
+ res = repr(poly.Hermite([0, 1]))
353
+ tgt = (
354
+ "Hermite([0., 1.], domain=[-1, 1], window=[-1, 1], "
355
+ "symbol='x')"
356
+ )
357
+ assert_equal(res, tgt)
358
+
359
+ def test_hermiteE_repr(self):
360
+ res = repr(poly.HermiteE([0, 1]))
361
+ tgt = (
362
+ "HermiteE([0., 1.], domain=[-1, 1], window=[-1, 1], "
363
+ "symbol='x')"
364
+ )
365
+ assert_equal(res, tgt)
366
+
367
+ def test_laguerre_repr(self):
368
+ res = repr(poly.Laguerre([0, 1]))
369
+ tgt = (
370
+ "Laguerre([0., 1.], domain=[0, 1], window=[0, 1], "
371
+ "symbol='x')"
372
+ )
373
+ assert_equal(res, tgt)
374
+
375
+
376
+ class TestLatexRepr:
377
+ """Test the latex repr used by Jupyter"""
378
+
379
+ def as_latex(self, obj):
380
+ # right now we ignore the formatting of scalars in our tests, since
381
+ # it makes them too verbose. Ideally, the formatting of scalars will
382
+ # be fixed such that tests below continue to pass
383
+ obj._repr_latex_scalar = lambda x, parens=False: str(x)
384
+ try:
385
+ return obj._repr_latex_()
386
+ finally:
387
+ del obj._repr_latex_scalar
388
+
389
+ def test_simple_polynomial(self):
390
+ # default input
391
+ p = poly.Polynomial([1, 2, 3])
392
+ assert_equal(self.as_latex(p),
393
+ r'$x \mapsto 1.0 + 2.0\,x + 3.0\,x^{2}$')
394
+
395
+ # translated input
396
+ p = poly.Polynomial([1, 2, 3], domain=[-2, 0])
397
+ assert_equal(self.as_latex(p),
398
+ r'$x \mapsto 1.0 + 2.0\,\left(1.0 + x\right) + 3.0\,\left(1.0 + x\right)^{2}$')
399
+
400
+ # scaled input
401
+ p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5])
402
+ assert_equal(self.as_latex(p),
403
+ r'$x \mapsto 1.0 + 2.0\,\left(2.0x\right) + 3.0\,\left(2.0x\right)^{2}$')
404
+
405
+ # affine input
406
+ p = poly.Polynomial([1, 2, 3], domain=[-1, 0])
407
+ assert_equal(self.as_latex(p),
408
+ r'$x \mapsto 1.0 + 2.0\,\left(1.0 + 2.0x\right) + 3.0\,\left(1.0 + 2.0x\right)^{2}$')
409
+
410
+ def test_basis_func(self):
411
+ p = poly.Chebyshev([1, 2, 3])
412
+ assert_equal(self.as_latex(p),
413
+ r'$x \mapsto 1.0\,{T}_{0}(x) + 2.0\,{T}_{1}(x) + 3.0\,{T}_{2}(x)$')
414
+ # affine input - check no surplus parens are added
415
+ p = poly.Chebyshev([1, 2, 3], domain=[-1, 0])
416
+ assert_equal(self.as_latex(p),
417
+ r'$x \mapsto 1.0\,{T}_{0}(1.0 + 2.0x) + 2.0\,{T}_{1}(1.0 + 2.0x) + 3.0\,{T}_{2}(1.0 + 2.0x)$')
418
+
419
+ def test_multichar_basis_func(self):
420
+ p = poly.HermiteE([1, 2, 3])
421
+ assert_equal(self.as_latex(p),
422
+ r'$x \mapsto 1.0\,{He}_{0}(x) + 2.0\,{He}_{1}(x) + 3.0\,{He}_{2}(x)$')
423
+
424
+ def test_symbol_basic(self):
425
+ # default input
426
+ p = poly.Polynomial([1, 2, 3], symbol='z')
427
+ assert_equal(self.as_latex(p),
428
+ r'$z \mapsto 1.0 + 2.0\,z + 3.0\,z^{2}$')
429
+
430
+ # translated input
431
+ p = poly.Polynomial([1, 2, 3], domain=[-2, 0], symbol='z')
432
+ assert_equal(
433
+ self.as_latex(p),
434
+ (
435
+ r'$z \mapsto 1.0 + 2.0\,\left(1.0 + z\right) + 3.0\,'
436
+ r'\left(1.0 + z\right)^{2}$'
437
+ ),
438
+ )
439
+
440
+ # scaled input
441
+ p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5], symbol='z')
442
+ assert_equal(
443
+ self.as_latex(p),
444
+ (
445
+ r'$z \mapsto 1.0 + 2.0\,\left(2.0z\right) + 3.0\,'
446
+ r'\left(2.0z\right)^{2}$'
447
+ ),
448
+ )
449
+
450
+ # affine input
451
+ p = poly.Polynomial([1, 2, 3], domain=[-1, 0], symbol='z')
452
+ assert_equal(
453
+ self.as_latex(p),
454
+ (
455
+ r'$z \mapsto 1.0 + 2.0\,\left(1.0 + 2.0z\right) + 3.0\,'
456
+ r'\left(1.0 + 2.0z\right)^{2}$'
457
+ ),
458
+ )
459
+
460
+
461
+ SWITCH_TO_EXP = (
462
+ '1.0 + (1.0e-01) x + (1.0e-02) x**2',
463
+ '1.2 + (1.2e-01) x + (1.2e-02) x**2',
464
+ '1.23 + 0.12 x + (1.23e-02) x**2 + (1.23e-03) x**3',
465
+ '1.235 + 0.123 x + (1.235e-02) x**2 + (1.235e-03) x**3',
466
+ '1.2346 + 0.1235 x + 0.0123 x**2 + (1.2346e-03) x**3 + (1.2346e-04) x**4',
467
+ '1.23457 + 0.12346 x + 0.01235 x**2 + (1.23457e-03) x**3 + '
468
+ '(1.23457e-04) x**4',
469
+ '1.234568 + 0.123457 x + 0.012346 x**2 + 0.001235 x**3 + '
470
+ '(1.234568e-04) x**4 + (1.234568e-05) x**5',
471
+ '1.2345679 + 0.1234568 x + 0.0123457 x**2 + 0.0012346 x**3 + '
472
+ '(1.2345679e-04) x**4 + (1.2345679e-05) x**5')
473
+
474
+ class TestPrintOptions:
475
+ """
476
+ Test the output is properly configured via printoptions.
477
+ The exponential notation is enabled automatically when the values
478
+ are too small or too large.
479
+ """
480
+
481
+ @pytest.fixture(scope='class', autouse=True)
482
+ def use_ascii(self):
483
+ poly.set_default_printstyle('ascii')
484
+
485
+ def test_str(self):
486
+ p = poly.Polynomial([1/2, 1/7, 1/7*10**8, 1/7*10**9])
487
+ assert_equal(str(p), '0.5 + 0.14285714 x + 14285714.28571429 x**2 '
488
+ '+ (1.42857143e+08) x**3')
489
+
490
+ with printoptions(precision=3):
491
+ assert_equal(str(p), '0.5 + 0.143 x + 14285714.286 x**2 '
492
+ '+ (1.429e+08) x**3')
493
+
494
+ def test_latex(self):
495
+ p = poly.Polynomial([1/2, 1/7, 1/7*10**8, 1/7*10**9])
496
+ assert_equal(p._repr_latex_(),
497
+ r'$x \mapsto \text{0.5} + \text{0.14285714}\,x + '
498
+ r'\text{14285714.28571429}\,x^{2} + '
499
+ r'\text{(1.42857143e+08)}\,x^{3}$')
500
+
501
+ with printoptions(precision=3):
502
+ assert_equal(p._repr_latex_(),
503
+ r'$x \mapsto \text{0.5} + \text{0.143}\,x + '
504
+ r'\text{14285714.286}\,x^{2} + \text{(1.429e+08)}\,x^{3}$')
505
+
506
+ def test_fixed(self):
507
+ p = poly.Polynomial([1/2])
508
+ assert_equal(str(p), '0.5')
509
+
510
+ with printoptions(floatmode='fixed'):
511
+ assert_equal(str(p), '0.50000000')
512
+
513
+ with printoptions(floatmode='fixed', precision=4):
514
+ assert_equal(str(p), '0.5000')
515
+
516
+ def test_switch_to_exp(self):
517
+ for i, s in enumerate(SWITCH_TO_EXP):
518
+ with printoptions(precision=i):
519
+ p = poly.Polynomial([1.23456789*10**-i
520
+ for i in range(i//2+3)])
521
+ assert str(p).replace('\n', ' ') == s
522
+
523
+ def test_non_finite(self):
524
+ p = poly.Polynomial([nan, inf])
525
+ assert str(p) == 'nan + inf x'
526
+ assert p._repr_latex_() == r'$x \mapsto \text{nan} + \text{inf}\,x$'
527
+ with printoptions(nanstr='NAN', infstr='INF'):
528
+ assert str(p) == 'NAN + INF x'
529
+ assert p._repr_latex_() == \
530
+ r'$x \mapsto \text{NAN} + \text{INF}\,x$'
deepseekvl2/lib/python3.10/site-packages/numpy/polynomial/tests/test_symbol.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests related to the ``symbol`` attribute of the ABCPolyBase class.
3
+ """
4
+
5
+ import pytest
6
+ import numpy.polynomial as poly
7
+ from numpy.core import array
8
+ from numpy.testing import assert_equal, assert_raises, assert_
9
+
10
+
11
+ class TestInit:
12
+ """
13
+ Test polynomial creation with symbol kwarg.
14
+ """
15
+ c = [1, 2, 3]
16
+
17
+ def test_default_symbol(self):
18
+ p = poly.Polynomial(self.c)
19
+ assert_equal(p.symbol, 'x')
20
+
21
+ @pytest.mark.parametrize(('bad_input', 'exception'), (
22
+ ('', ValueError),
23
+ ('3', ValueError),
24
+ (None, TypeError),
25
+ (1, TypeError),
26
+ ))
27
+ def test_symbol_bad_input(self, bad_input, exception):
28
+ with pytest.raises(exception):
29
+ p = poly.Polynomial(self.c, symbol=bad_input)
30
+
31
+ @pytest.mark.parametrize('symbol', (
32
+ 'x',
33
+ 'x_1',
34
+ 'A',
35
+ 'xyz',
36
+ 'β',
37
+ ))
38
+ def test_valid_symbols(self, symbol):
39
+ """
40
+ Values for symbol that should pass input validation.
41
+ """
42
+ p = poly.Polynomial(self.c, symbol=symbol)
43
+ assert_equal(p.symbol, symbol)
44
+
45
+ def test_property(self):
46
+ """
47
+ 'symbol' attribute is read only.
48
+ """
49
+ p = poly.Polynomial(self.c, symbol='x')
50
+ with pytest.raises(AttributeError):
51
+ p.symbol = 'z'
52
+
53
+ def test_change_symbol(self):
54
+ p = poly.Polynomial(self.c, symbol='y')
55
+ # Create new polynomial from p with different symbol
56
+ pt = poly.Polynomial(p.coef, symbol='t')
57
+ assert_equal(pt.symbol, 't')
58
+
59
+
60
+ class TestUnaryOperators:
61
+ p = poly.Polynomial([1, 2, 3], symbol='z')
62
+
63
+ def test_neg(self):
64
+ n = -self.p
65
+ assert_equal(n.symbol, 'z')
66
+
67
+ def test_scalarmul(self):
68
+ out = self.p * 10
69
+ assert_equal(out.symbol, 'z')
70
+
71
+ def test_rscalarmul(self):
72
+ out = 10 * self.p
73
+ assert_equal(out.symbol, 'z')
74
+
75
+ def test_pow(self):
76
+ out = self.p ** 3
77
+ assert_equal(out.symbol, 'z')
78
+
79
+
80
+ @pytest.mark.parametrize(
81
+ 'rhs',
82
+ (
83
+ poly.Polynomial([4, 5, 6], symbol='z'),
84
+ array([4, 5, 6]),
85
+ ),
86
+ )
87
+ class TestBinaryOperatorsSameSymbol:
88
+ """
89
+ Ensure symbol is preserved for numeric operations on polynomials with
90
+ the same symbol
91
+ """
92
+ p = poly.Polynomial([1, 2, 3], symbol='z')
93
+
94
+ def test_add(self, rhs):
95
+ out = self.p + rhs
96
+ assert_equal(out.symbol, 'z')
97
+
98
+ def test_sub(self, rhs):
99
+ out = self.p - rhs
100
+ assert_equal(out.symbol, 'z')
101
+
102
+ def test_polymul(self, rhs):
103
+ out = self.p * rhs
104
+ assert_equal(out.symbol, 'z')
105
+
106
+ def test_divmod(self, rhs):
107
+ for out in divmod(self.p, rhs):
108
+ assert_equal(out.symbol, 'z')
109
+
110
+ def test_radd(self, rhs):
111
+ out = rhs + self.p
112
+ assert_equal(out.symbol, 'z')
113
+
114
+ def test_rsub(self, rhs):
115
+ out = rhs - self.p
116
+ assert_equal(out.symbol, 'z')
117
+
118
+ def test_rmul(self, rhs):
119
+ out = rhs * self.p
120
+ assert_equal(out.symbol, 'z')
121
+
122
+ def test_rdivmod(self, rhs):
123
+ for out in divmod(rhs, self.p):
124
+ assert_equal(out.symbol, 'z')
125
+
126
+
127
+ class TestBinaryOperatorsDifferentSymbol:
128
+ p = poly.Polynomial([1, 2, 3], symbol='x')
129
+ other = poly.Polynomial([4, 5, 6], symbol='y')
130
+ ops = (p.__add__, p.__sub__, p.__mul__, p.__floordiv__, p.__mod__)
131
+
132
+ @pytest.mark.parametrize('f', ops)
133
+ def test_binops_fails(self, f):
134
+ assert_raises(ValueError, f, self.other)
135
+
136
+
137
+ class TestEquality:
138
+ p = poly.Polynomial([1, 2, 3], symbol='x')
139
+
140
+ def test_eq(self):
141
+ other = poly.Polynomial([1, 2, 3], symbol='x')
142
+ assert_(self.p == other)
143
+
144
+ def test_neq(self):
145
+ other = poly.Polynomial([1, 2, 3], symbol='y')
146
+ assert_(not self.p == other)
147
+
148
+
149
+ class TestExtraMethods:
150
+ """
151
+ Test other methods for manipulating/creating polynomial objects.
152
+ """
153
+ p = poly.Polynomial([1, 2, 3, 0], symbol='z')
154
+
155
+ def test_copy(self):
156
+ other = self.p.copy()
157
+ assert_equal(other.symbol, 'z')
158
+
159
+ def test_trim(self):
160
+ other = self.p.trim()
161
+ assert_equal(other.symbol, 'z')
162
+
163
+ def test_truncate(self):
164
+ other = self.p.truncate(2)
165
+ assert_equal(other.symbol, 'z')
166
+
167
+ @pytest.mark.parametrize('kwarg', (
168
+ {'domain': [-10, 10]},
169
+ {'window': [-10, 10]},
170
+ {'kind': poly.Chebyshev},
171
+ ))
172
+ def test_convert(self, kwarg):
173
+ other = self.p.convert(**kwarg)
174
+ assert_equal(other.symbol, 'z')
175
+
176
+ def test_integ(self):
177
+ other = self.p.integ()
178
+ assert_equal(other.symbol, 'z')
179
+
180
+ def test_deriv(self):
181
+ other = self.p.deriv()
182
+ assert_equal(other.symbol, 'z')
183
+
184
+
185
+ def test_composition():
186
+ p = poly.Polynomial([3, 2, 1], symbol="t")
187
+ q = poly.Polynomial([5, 1, 0, -1], symbol="λ_1")
188
+ r = p(q)
189
+ assert r.symbol == "λ_1"
190
+
191
+
192
+ #
193
+ # Class methods that result in new polynomial class instances
194
+ #
195
+
196
+
197
+ def test_fit():
198
+ x, y = (range(10),)*2
199
+ p = poly.Polynomial.fit(x, y, deg=1, symbol='z')
200
+ assert_equal(p.symbol, 'z')
201
+
202
+
203
+ def test_froomroots():
204
+ roots = [-2, 2]
205
+ p = poly.Polynomial.fromroots(roots, symbol='z')
206
+ assert_equal(p.symbol, 'z')
207
+
208
+
209
+ def test_identity():
210
+ p = poly.Polynomial.identity(domain=[-1, 1], window=[5, 20], symbol='z')
211
+ assert_equal(p.symbol, 'z')
212
+
213
+
214
+ def test_basis():
215
+ p = poly.Polynomial.basis(3, symbol='z')
216
+ assert_equal(p.symbol, 'z')
falcon/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolver.so.11 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10287abc7ce9c5fc7e7c163761566b599eae1b362c47e1000911d198443d6d52
3
+ size 114481816
infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__init__.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .pyutils.version import get_version
2
+
3
+
4
+ try:
5
+ # This variable is injected in the __builtins__ by the build
6
+ # process. It used to enable importing subpackages when
7
+ # the required packages are not installed
8
+ __SETUP__ # type: ignore
9
+ except NameError:
10
+ __SETUP__ = False
11
+
12
+
13
+ VERSION = (2, 3, 0, "final", 0)
14
+
15
+ __version__ = get_version(VERSION)
16
+
17
+ if not __SETUP__:
18
+ from .promise import (
19
+ Promise,
20
+ promise_for_dict,
21
+ promisify,
22
+ is_thenable,
23
+ async_instance,
24
+ get_default_scheduler,
25
+ set_default_scheduler,
26
+ )
27
+ from .schedulers.immediate import ImmediateScheduler
28
+
29
+ __all__ = [
30
+ "Promise",
31
+ "promise_for_dict",
32
+ "promisify",
33
+ "is_thenable",
34
+ "async_instance",
35
+ "get_default_scheduler",
36
+ "set_default_scheduler",
37
+ "ImmediateScheduler",
38
+ ]
infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/async_.cpython-310.pyc ADDED
Binary file (3.95 kB). View file
 
infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/compat.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ from inspect import iscoroutine
3
+ except ImportError:
4
+
5
+ def iscoroutine(obj): # type: ignore
6
+ return False
7
+
8
+
9
+ try:
10
+ from asyncio import Future, ensure_future # type: ignore
11
+ except ImportError:
12
+
13
+ class Future: # type: ignore
14
+ def __init__(self):
15
+ raise Exception("You need asyncio for using Futures")
16
+
17
+ def set_result(self):
18
+ raise Exception("You need asyncio for using Futures")
19
+
20
+ def set_exception(self):
21
+ raise Exception("You need asyncio for using Futures")
22
+
23
+ def ensure_future(): # type: ignore
24
+ raise Exception("ensure_future needs asyncio for executing")
25
+
26
+
27
+ try:
28
+ from .iterate_promise import iterate_promise
29
+ except (SyntaxError, ImportError):
30
+
31
+ def iterate_promise(promise): # type: ignore
32
+ raise Exception('You need "yield from" syntax for iterate in a Promise.')
infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__pycache__/gevent.cpython-310.pyc ADDED
Binary file (1.04 kB). View file
 
infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__pycache__/immediate.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/gevent.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from gevent.event import Event # type: ignore
4
+ import gevent # type: ignore
5
+
6
+
7
+ class GeventScheduler(object):
8
+ def call(self, fn):
9
+ # print fn
10
+ gevent.spawn(fn)
11
+
12
+ def wait(self, promise, timeout=None):
13
+ e = Event()
14
+
15
+ def on_resolve_or_reject(_):
16
+ e.set()
17
+
18
+ promise._then(on_resolve_or_reject, on_resolve_or_reject)
19
+ waited = e.wait(timeout)
20
+ if not waited:
21
+ raise Exception("Timeout")
infer_4_33_0/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/immediate.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from threading import Event
2
+
3
+ if False:
4
+ from ..promise import Promise
5
+ from typing import Callable, Any, Optional # flake8: noqa
6
+
7
+
8
+ class ImmediateScheduler(object):
9
+ def call(self, fn):
10
+ # type: (Callable) -> None
11
+ try:
12
+ fn()
13
+ except:
14
+ pass
15
+
16
+ def wait(self, promise, timeout=None):
17
+ # type: (Promise, Optional[float]) -> None
18
+ e = Event()
19
+
20
+ def on_resolve_or_reject(_):
21
+ # type: (Any) -> None
22
+ e.set()
23
+
24
+ promise._then(on_resolve_or_reject, on_resolve_or_reject)
25
+ waited = e.wait(timeout)
26
+ if not waited:
27
+ raise Exception("Timeout")