polyutils.py 22 KB

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