polyutils.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. """
  2. Utility classes and functions for the polynomial modules.
  3. This module provides: error and warning objects; a polynomial base class;
  4. and some routines used in both the `polynomial` and `chebyshev` modules.
  5. Warning objects
  6. ---------------
  7. .. autosummary::
  8. :toctree: generated/
  9. RankWarning raised in least-squares fit for rank-deficient matrix.
  10. Functions
  11. ---------
  12. .. autosummary::
  13. :toctree: generated/
  14. as_series convert list of array_likes into 1-D arrays of common type.
  15. trimseq remove trailing zeros.
  16. trimcoef remove small trailing coefficients.
  17. getdomain return the domain appropriate for a given set of abscissae.
  18. mapdomain maps points between domains.
  19. mapparms parameters of the linear map between domains.
  20. """
  21. import operator
  22. import functools
  23. import warnings
  24. import numpy as np
  25. __all__ = [
  26. 'RankWarning', 'as_series', 'trimseq',
  27. 'trimcoef', 'getdomain', 'mapdomain', 'mapparms']
  28. #
  29. # Warnings and Exceptions
  30. #
  31. class RankWarning(UserWarning):
  32. """Issued by chebfit when the design matrix is rank deficient."""
  33. pass
  34. #
  35. # Helper functions to convert inputs to 1-D arrays
  36. #
  37. def trimseq(seq):
  38. """Remove small Poly series coefficients.
  39. Parameters
  40. ----------
  41. seq : sequence
  42. Sequence of Poly series coefficients. This routine fails for
  43. empty sequences.
  44. Returns
  45. -------
  46. series : sequence
  47. Subsequence with trailing zeros removed. If the resulting sequence
  48. would be empty, return the first element. The returned sequence may
  49. or may not be a view.
  50. Notes
  51. -----
  52. Do not lose the type info if the sequence contains unknown objects.
  53. """
  54. if len(seq) == 0:
  55. return seq
  56. else:
  57. for i in range(len(seq) - 1, -1, -1):
  58. if seq[i] != 0:
  59. break
  60. return seq[:i+1]
  61. def as_series(alist, trim=True):
  62. """
  63. Return argument as a list of 1-d arrays.
  64. The returned list contains array(s) of dtype double, complex double, or
  65. object. A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of
  66. size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays
  67. of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array
  68. raises a Value Error if it is not first reshaped into either a 1-d or 2-d
  69. array.
  70. Parameters
  71. ----------
  72. alist : array_like
  73. A 1- or 2-d array_like
  74. trim : boolean, optional
  75. When True, trailing zeros are removed from the inputs.
  76. When False, the inputs are passed through intact.
  77. Returns
  78. -------
  79. [a1, a2,...] : list of 1-D arrays
  80. A copy of the input data as a list of 1-d arrays.
  81. Raises
  82. ------
  83. ValueError
  84. Raised when `as_series` cannot convert its input to 1-d arrays, or at
  85. least one of the resulting arrays is empty.
  86. Examples
  87. --------
  88. >>> from numpy.polynomial import polyutils as pu
  89. >>> a = np.arange(4)
  90. >>> pu.as_series(a)
  91. [array([0.]), array([1.]), array([2.]), array([3.])]
  92. >>> b = np.arange(6).reshape((2,3))
  93. >>> pu.as_series(b)
  94. [array([0., 1., 2.]), array([3., 4., 5.])]
  95. >>> pu.as_series((1, np.arange(3), np.arange(2, dtype=np.float16)))
  96. [array([1.]), array([0., 1., 2.]), array([0., 1.])]
  97. >>> pu.as_series([2, [1.1, 0.]])
  98. [array([2.]), array([1.1])]
  99. >>> pu.as_series([2, [1.1, 0.]], trim=False)
  100. [array([2.]), array([1.1, 0. ])]
  101. """
  102. arrays = [np.array(a, ndmin=1, copy=False) for a in alist]
  103. if min([a.size for a in arrays]) == 0:
  104. raise ValueError("Coefficient array is empty")
  105. if any(a.ndim != 1 for a in arrays):
  106. raise ValueError("Coefficient array is not 1-d")
  107. if trim:
  108. arrays = [trimseq(a) for a in arrays]
  109. if any(a.dtype == np.dtype(object) for a in arrays):
  110. ret = []
  111. for a in arrays:
  112. if a.dtype != np.dtype(object):
  113. tmp = np.empty(len(a), dtype=np.dtype(object))
  114. tmp[:] = a[:]
  115. ret.append(tmp)
  116. else:
  117. ret.append(a.copy())
  118. else:
  119. try:
  120. dtype = np.common_type(*arrays)
  121. except Exception as e:
  122. raise ValueError("Coefficient arrays have no common type") from e
  123. ret = [np.array(a, copy=True, dtype=dtype) for a in arrays]
  124. return ret
  125. def trimcoef(c, tol=0):
  126. """
  127. Remove "small" "trailing" coefficients from a polynomial.
  128. "Small" means "small in absolute value" and is controlled by the
  129. parameter `tol`; "trailing" means highest order coefficient(s), e.g., in
  130. ``[0, 1, 1, 0, 0]`` (which represents ``0 + x + x**2 + 0*x**3 + 0*x**4``)
  131. both the 3-rd and 4-th order coefficients would be "trimmed."
  132. Parameters
  133. ----------
  134. c : array_like
  135. 1-d array of coefficients, ordered from lowest order to highest.
  136. tol : number, optional
  137. Trailing (i.e., highest order) elements with absolute value less
  138. than or equal to `tol` (default value is zero) are removed.
  139. Returns
  140. -------
  141. trimmed : ndarray
  142. 1-d array with trailing zeros removed. If the resulting series
  143. would be empty, a series containing a single zero is returned.
  144. Raises
  145. ------
  146. ValueError
  147. If `tol` < 0
  148. See Also
  149. --------
  150. trimseq
  151. Examples
  152. --------
  153. >>> from numpy.polynomial import polyutils as pu
  154. >>> pu.trimcoef((0,0,3,0,5,0,0))
  155. array([0., 0., 3., 0., 5.])
  156. >>> pu.trimcoef((0,0,1e-3,0,1e-5,0,0),1e-3) # item == tol is trimmed
  157. array([0.])
  158. >>> i = complex(0,1) # works for complex
  159. >>> pu.trimcoef((3e-4,1e-3*(1-i),5e-4,2e-5*(1+i)), 1e-3)
  160. array([0.0003+0.j , 0.001 -0.001j])
  161. """
  162. if tol < 0:
  163. raise ValueError("tol must be non-negative")
  164. [c] = as_series([c])
  165. [ind] = np.nonzero(np.abs(c) > tol)
  166. if len(ind) == 0:
  167. return c[:1]*0
  168. else:
  169. return c[:ind[-1] + 1].copy()
  170. def getdomain(x):
  171. """
  172. Return a domain suitable for given abscissae.
  173. Find a domain suitable for a polynomial or Chebyshev series
  174. defined at the values supplied.
  175. Parameters
  176. ----------
  177. x : array_like
  178. 1-d array of abscissae whose domain will be determined.
  179. Returns
  180. -------
  181. domain : ndarray
  182. 1-d array containing two values. If the inputs are complex, then
  183. the two returned points are the lower left and upper right corners
  184. of the smallest rectangle (aligned with the axes) in the complex
  185. plane containing the points `x`. If the inputs are real, then the
  186. two points are the ends of the smallest interval containing the
  187. points `x`.
  188. See Also
  189. --------
  190. mapparms, mapdomain
  191. Examples
  192. --------
  193. >>> from numpy.polynomial import polyutils as pu
  194. >>> points = np.arange(4)**2 - 5; points
  195. array([-5, -4, -1, 4])
  196. >>> pu.getdomain(points)
  197. array([-5., 4.])
  198. >>> c = np.exp(complex(0,1)*np.pi*np.arange(12)/6) # unit circle
  199. >>> pu.getdomain(c)
  200. array([-1.-1.j, 1.+1.j])
  201. """
  202. [x] = as_series([x], trim=False)
  203. if x.dtype.char in np.typecodes['Complex']:
  204. rmin, rmax = x.real.min(), x.real.max()
  205. imin, imax = x.imag.min(), x.imag.max()
  206. return np.array((complex(rmin, imin), complex(rmax, imax)))
  207. else:
  208. return np.array((x.min(), x.max()))
  209. def mapparms(old, new):
  210. """
  211. Linear map parameters between domains.
  212. Return the parameters of the linear map ``offset + scale*x`` that maps
  213. `old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``.
  214. Parameters
  215. ----------
  216. old, new : array_like
  217. Domains. Each domain must (successfully) convert to a 1-d array
  218. containing precisely two values.
  219. Returns
  220. -------
  221. offset, scale : scalars
  222. The map ``L(x) = offset + scale*x`` maps the first domain to the
  223. second.
  224. See Also
  225. --------
  226. getdomain, mapdomain
  227. Notes
  228. -----
  229. Also works for complex numbers, and thus can be used to calculate the
  230. parameters required to map any line in the complex plane to any other
  231. line therein.
  232. Examples
  233. --------
  234. >>> from numpy.polynomial import polyutils as pu
  235. >>> pu.mapparms((-1,1),(-1,1))
  236. (0.0, 1.0)
  237. >>> pu.mapparms((1,-1),(-1,1))
  238. (-0.0, -1.0)
  239. >>> i = complex(0,1)
  240. >>> pu.mapparms((-i,-1),(1,i))
  241. ((1+1j), (1-0j))
  242. """
  243. oldlen = old[1] - old[0]
  244. newlen = new[1] - new[0]
  245. off = (old[1]*new[0] - old[0]*new[1])/oldlen
  246. scl = newlen/oldlen
  247. return off, scl
  248. def mapdomain(x, old, new):
  249. """
  250. Apply linear map to input points.
  251. The linear map ``offset + scale*x`` that maps the domain `old` to
  252. the domain `new` is applied to the points `x`.
  253. Parameters
  254. ----------
  255. x : array_like
  256. Points to be mapped. If `x` is a subtype of ndarray the subtype
  257. will be preserved.
  258. old, new : array_like
  259. The two domains that determine the map. Each must (successfully)
  260. convert to 1-d arrays containing precisely two values.
  261. Returns
  262. -------
  263. x_out : ndarray
  264. Array of points of the same shape as `x`, after application of the
  265. linear map between the two domains.
  266. See Also
  267. --------
  268. getdomain, mapparms
  269. Notes
  270. -----
  271. Effectively, this implements:
  272. .. math ::
  273. x\\_out = new[0] + m(x - old[0])
  274. where
  275. .. math ::
  276. m = \\frac{new[1]-new[0]}{old[1]-old[0]}
  277. Examples
  278. --------
  279. >>> from numpy.polynomial import polyutils as pu
  280. >>> old_domain = (-1,1)
  281. >>> new_domain = (0,2*np.pi)
  282. >>> x = np.linspace(-1,1,6); x
  283. array([-1. , -0.6, -0.2, 0.2, 0.6, 1. ])
  284. >>> x_out = pu.mapdomain(x, old_domain, new_domain); x_out
  285. array([ 0. , 1.25663706, 2.51327412, 3.76991118, 5.02654825, # may vary
  286. 6.28318531])
  287. >>> x - pu.mapdomain(x_out, new_domain, old_domain)
  288. array([0., 0., 0., 0., 0., 0.])
  289. Also works for complex numbers (and thus can be used to map any line in
  290. the complex plane to any other line therein).
  291. >>> i = complex(0,1)
  292. >>> old = (-1 - i, 1 + i)
  293. >>> new = (-1 + i, 1 - i)
  294. >>> z = np.linspace(old[0], old[1], 6); z
  295. array([-1. -1.j , -0.6-0.6j, -0.2-0.2j, 0.2+0.2j, 0.6+0.6j, 1. +1.j ])
  296. >>> new_z = pu.mapdomain(z, old, new); new_z
  297. array([-1.0+1.j , -0.6+0.6j, -0.2+0.2j, 0.2-0.2j, 0.6-0.6j, 1.0-1.j ]) # may vary
  298. """
  299. x = np.asanyarray(x)
  300. off, scl = mapparms(old, new)
  301. return off + scl*x
  302. def _nth_slice(i, ndim):
  303. sl = [np.newaxis] * ndim
  304. sl[i] = slice(None)
  305. return tuple(sl)
  306. def _vander_nd(vander_fs, points, degrees):
  307. r"""
  308. A generalization of the Vandermonde matrix for N dimensions
  309. The result is built by combining the results of 1d Vandermonde matrices,
  310. .. math::
  311. W[i_0, \ldots, i_M, j_0, \ldots, j_N] = \prod_{k=0}^N{V_k(x_k)[i_0, \ldots, i_M, j_k]}
  312. where
  313. .. math::
  314. N &= \texttt{len(points)} = \texttt{len(degrees)} = \texttt{len(vander\_fs)} \\
  315. M &= \texttt{points[k].ndim} \\
  316. V_k &= \texttt{vander\_fs[k]} \\
  317. x_k &= \texttt{points[k]} \\
  318. 0 \le j_k &\le \texttt{degrees[k]}
  319. Expanding the one-dimensional :math:`V_k` functions gives:
  320. .. math::
  321. W[i_0, \ldots, i_M, j_0, \ldots, j_N] = \prod_{k=0}^N{B_{k, j_k}(x_k[i_0, \ldots, i_M])}
  322. where :math:`B_{k,m}` is the m'th basis of the polynomial construction used along
  323. dimension :math:`k`. For a regular polynomial, :math:`B_{k, m}(x) = P_m(x) = x^m`.
  324. Parameters
  325. ----------
  326. vander_fs : Sequence[function(array_like, int) -> ndarray]
  327. The 1d vander function to use for each axis, such as ``polyvander``
  328. points : Sequence[array_like]
  329. Arrays of point coordinates, all of the same shape. The dtypes
  330. will be converted to either float64 or complex128 depending on
  331. whether any of the elements are complex. Scalars are converted to
  332. 1-D arrays.
  333. This must be the same length as `vander_fs`.
  334. degrees : Sequence[int]
  335. The maximum degree (inclusive) to use for each axis.
  336. This must be the same length as `vander_fs`.
  337. Returns
  338. -------
  339. vander_nd : ndarray
  340. An array of shape ``points[0].shape + tuple(d + 1 for d in degrees)``.
  341. """
  342. n_dims = len(vander_fs)
  343. if n_dims != len(points):
  344. raise ValueError(
  345. f"Expected {n_dims} dimensions of sample points, got {len(points)}")
  346. if n_dims != len(degrees):
  347. raise ValueError(
  348. f"Expected {n_dims} dimensions of degrees, got {len(degrees)}")
  349. if n_dims == 0:
  350. raise ValueError("Unable to guess a dtype or shape when no points are given")
  351. # convert to the same shape and type
  352. points = tuple(np.array(tuple(points), copy=False) + 0.0)
  353. # produce the vandermonde matrix for each dimension, placing the last
  354. # axis of each in an independent trailing axis of the output
  355. vander_arrays = (
  356. vander_fs[i](points[i], degrees[i])[(...,) + _nth_slice(i, n_dims)]
  357. for i in range(n_dims)
  358. )
  359. # we checked this wasn't empty already, so no `initial` needed
  360. return functools.reduce(operator.mul, vander_arrays)
  361. def _vander_nd_flat(vander_fs, points, degrees):
  362. """
  363. Like `_vander_nd`, but flattens the last ``len(degrees)`` axes into a single axis
  364. Used to implement the public ``<type>vander<n>d`` functions.
  365. """
  366. v = _vander_nd(vander_fs, points, degrees)
  367. return v.reshape(v.shape[:-len(degrees)] + (-1,))
  368. def _fromroots(line_f, mul_f, roots):
  369. """
  370. Helper function used to implement the ``<type>fromroots`` functions.
  371. Parameters
  372. ----------
  373. line_f : function(float, float) -> ndarray
  374. The ``<type>line`` function, such as ``polyline``
  375. mul_f : function(array_like, array_like) -> ndarray
  376. The ``<type>mul`` function, such as ``polymul``
  377. roots
  378. See the ``<type>fromroots`` functions for more detail
  379. """
  380. if len(roots) == 0:
  381. return np.ones(1)
  382. else:
  383. [roots] = as_series([roots], trim=False)
  384. roots.sort()
  385. p = [line_f(-r, 1) for r in roots]
  386. n = len(p)
  387. while n > 1:
  388. m, r = divmod(n, 2)
  389. tmp = [mul_f(p[i], p[i+m]) for i in range(m)]
  390. if r:
  391. tmp[0] = mul_f(tmp[0], p[-1])
  392. p = tmp
  393. n = m
  394. return p[0]
  395. def _valnd(val_f, c, *args):
  396. """
  397. Helper function used to implement the ``<type>val<n>d`` functions.
  398. Parameters
  399. ----------
  400. val_f : function(array_like, array_like, tensor: bool) -> array_like
  401. The ``<type>val`` function, such as ``polyval``
  402. c, args
  403. See the ``<type>val<n>d`` functions for more detail
  404. """
  405. args = [np.asanyarray(a) for a in args]
  406. shape0 = args[0].shape
  407. if not all((a.shape == shape0 for a in args[1:])):
  408. if len(args) == 3:
  409. raise ValueError('x, y, z are incompatible')
  410. elif len(args) == 2:
  411. raise ValueError('x, y are incompatible')
  412. else:
  413. raise ValueError('ordinates are incompatible')
  414. it = iter(args)
  415. x0 = next(it)
  416. # use tensor on only the first
  417. c = val_f(x0, c)
  418. for xi in it:
  419. c = val_f(xi, c, tensor=False)
  420. return c
  421. def _gridnd(val_f, c, *args):
  422. """
  423. Helper function used to implement the ``<type>grid<n>d`` functions.
  424. Parameters
  425. ----------
  426. val_f : function(array_like, array_like, tensor: bool) -> array_like
  427. The ``<type>val`` function, such as ``polyval``
  428. c, args
  429. See the ``<type>grid<n>d`` functions for more detail
  430. """
  431. for xi in args:
  432. c = val_f(xi, c)
  433. return c
  434. def _div(mul_f, c1, c2):
  435. """
  436. Helper function used to implement the ``<type>div`` functions.
  437. Implementation uses repeated subtraction of c2 multiplied by the nth basis.
  438. For some polynomial types, a more efficient approach may be possible.
  439. Parameters
  440. ----------
  441. mul_f : function(array_like, array_like) -> array_like
  442. The ``<type>mul`` function, such as ``polymul``
  443. c1, c2
  444. See the ``<type>div`` functions for more detail
  445. """
  446. # c1, c2 are trimmed copies
  447. [c1, c2] = as_series([c1, c2])
  448. if c2[-1] == 0:
  449. raise ZeroDivisionError()
  450. lc1 = len(c1)
  451. lc2 = len(c2)
  452. if lc1 < lc2:
  453. return c1[:1]*0, c1
  454. elif lc2 == 1:
  455. return c1/c2[-1], c1[:1]*0
  456. else:
  457. quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype)
  458. rem = c1
  459. for i in range(lc1 - lc2, - 1, -1):
  460. p = mul_f([0]*i + [1], c2)
  461. q = rem[-1]/p[-1]
  462. rem = rem[:-1] - q*p[:-1]
  463. quo[i] = q
  464. return quo, trimseq(rem)
  465. def _add(c1, c2):
  466. """ Helper function used to implement the ``<type>add`` functions. """
  467. # c1, c2 are trimmed copies
  468. [c1, c2] = as_series([c1, c2])
  469. if len(c1) > len(c2):
  470. c1[:c2.size] += c2
  471. ret = c1
  472. else:
  473. c2[:c1.size] += c1
  474. ret = c2
  475. return trimseq(ret)
  476. def _sub(c1, c2):
  477. """ Helper function used to implement the ``<type>sub`` functions. """
  478. # c1, c2 are trimmed copies
  479. [c1, c2] = as_series([c1, c2])
  480. if len(c1) > len(c2):
  481. c1[:c2.size] -= c2
  482. ret = c1
  483. else:
  484. c2 = -c2
  485. c2[:c1.size] += c1
  486. ret = c2
  487. return trimseq(ret)
  488. def _fit(vander_f, x, y, deg, rcond=None, full=False, w=None):
  489. """
  490. Helper function used to implement the ``<type>fit`` functions.
  491. Parameters
  492. ----------
  493. vander_f : function(array_like, int) -> ndarray
  494. The 1d vander function, such as ``polyvander``
  495. c1, c2
  496. See the ``<type>fit`` functions for more detail
  497. """
  498. x = np.asarray(x) + 0.0
  499. y = np.asarray(y) + 0.0
  500. deg = np.asarray(deg)
  501. # check arguments.
  502. if deg.ndim > 1 or deg.dtype.kind not in 'iu' or deg.size == 0:
  503. raise TypeError("deg must be an int or non-empty 1-D array of int")
  504. if deg.min() < 0:
  505. raise ValueError("expected deg >= 0")
  506. if x.ndim != 1:
  507. raise TypeError("expected 1D vector for x")
  508. if x.size == 0:
  509. raise TypeError("expected non-empty vector for x")
  510. if y.ndim < 1 or y.ndim > 2:
  511. raise TypeError("expected 1D or 2D array for y")
  512. if len(x) != len(y):
  513. raise TypeError("expected x and y to have same length")
  514. if deg.ndim == 0:
  515. lmax = deg
  516. order = lmax + 1
  517. van = vander_f(x, lmax)
  518. else:
  519. deg = np.sort(deg)
  520. lmax = deg[-1]
  521. order = len(deg)
  522. van = vander_f(x, lmax)[:, deg]
  523. # set up the least squares matrices in transposed form
  524. lhs = van.T
  525. rhs = y.T
  526. if w is not None:
  527. w = np.asarray(w) + 0.0
  528. if w.ndim != 1:
  529. raise TypeError("expected 1D vector for w")
  530. if len(x) != len(w):
  531. raise TypeError("expected x and w to have same length")
  532. # apply weights. Don't use inplace operations as they
  533. # can cause problems with NA.
  534. lhs = lhs * w
  535. rhs = rhs * w
  536. # set rcond
  537. if rcond is None:
  538. rcond = len(x)*np.finfo(x.dtype).eps
  539. # Determine the norms of the design matrix columns.
  540. if issubclass(lhs.dtype.type, np.complexfloating):
  541. scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
  542. else:
  543. scl = np.sqrt(np.square(lhs).sum(1))
  544. scl[scl == 0] = 1
  545. # Solve the least squares problem.
  546. c, resids, rank, s = np.linalg.lstsq(lhs.T/scl, rhs.T, rcond)
  547. c = (c.T/scl).T
  548. # Expand c to include non-fitted coefficients which are set to zero
  549. if deg.ndim > 0:
  550. if c.ndim == 2:
  551. cc = np.zeros((lmax+1, c.shape[1]), dtype=c.dtype)
  552. else:
  553. cc = np.zeros(lmax+1, dtype=c.dtype)
  554. cc[deg] = c
  555. c = cc
  556. # warn on rank reduction
  557. if rank != order and not full:
  558. msg = "The fit may be poorly conditioned"
  559. warnings.warn(msg, RankWarning, stacklevel=2)
  560. if full:
  561. return c, [resids, rank, s, rcond]
  562. else:
  563. return c
  564. def _pow(mul_f, c, pow, maxpower):
  565. """
  566. Helper function used to implement the ``<type>pow`` functions.
  567. Parameters
  568. ----------
  569. mul_f : function(array_like, array_like) -> ndarray
  570. The ``<type>mul`` function, such as ``polymul``
  571. c : array_like
  572. 1-D array of array of series coefficients
  573. pow, maxpower
  574. See the ``<type>pow`` functions for more detail
  575. """
  576. # c is a trimmed copy
  577. [c] = as_series([c])
  578. power = int(pow)
  579. if power != pow or power < 0:
  580. raise ValueError("Power must be a non-negative integer.")
  581. elif maxpower is not None and power > maxpower:
  582. raise ValueError("Power is too large")
  583. elif power == 0:
  584. return np.array([1], dtype=c.dtype)
  585. elif power == 1:
  586. return c
  587. else:
  588. # This can be made more efficient by using powers of two
  589. # in the usual way.
  590. prd = c
  591. for i in range(2, power + 1):
  592. prd = mul_f(prd, c)
  593. return prd
  594. def _deprecate_as_int(x, desc):
  595. """
  596. Like `operator.index`, but emits a deprecation warning when passed a float
  597. Parameters
  598. ----------
  599. x : int-like, or float with integral value
  600. Value to interpret as an integer
  601. desc : str
  602. description to include in any error message
  603. Raises
  604. ------
  605. TypeError : if x is a non-integral float or non-numeric
  606. DeprecationWarning : if x is an integral float
  607. """
  608. try:
  609. return operator.index(x)
  610. except TypeError as e:
  611. # Numpy 1.17.0, 2019-03-11
  612. try:
  613. ix = int(x)
  614. except TypeError:
  615. pass
  616. else:
  617. if ix == x:
  618. warnings.warn(
  619. f"In future, this will raise TypeError, as {desc} will "
  620. "need to be an integer not just an integral float.",
  621. DeprecationWarning,
  622. stacklevel=3
  623. )
  624. return ix
  625. raise TypeError(f"{desc} must be an integer") from e