polyutils.py 23 KB

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