_polybase.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. """
  2. Abstract base class for the various polynomial Classes.
  3. The ABCPolyBase class provides the methods needed to implement the common API
  4. for the various polynomial classes. It operates as a mixin, but uses the
  5. abc module from the stdlib, hence it is only available for Python >= 2.6.
  6. """
  7. from __future__ import division, absolute_import, print_function
  8. from abc import ABCMeta, abstractmethod, abstractproperty
  9. import numbers
  10. import numpy as np
  11. from . import polyutils as pu
  12. __all__ = ['ABCPolyBase']
  13. class ABCPolyBase(object):
  14. """An abstract base class for immutable series classes.
  15. ABCPolyBase provides the standard Python numerical methods
  16. '+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the
  17. methods listed below.
  18. .. versionadded:: 1.9.0
  19. Parameters
  20. ----------
  21. coef : array_like
  22. Series coefficients in order of increasing degree, i.e.,
  23. ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where
  24. ``P_i`` is the basis polynomials of degree ``i``.
  25. domain : (2,) array_like, optional
  26. Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
  27. to the interval ``[window[0], window[1]]`` by shifting and scaling.
  28. The default value is the derived class domain.
  29. window : (2,) array_like, optional
  30. Window, see domain for its use. The default value is the
  31. derived class window.
  32. Attributes
  33. ----------
  34. coef : (N,) ndarray
  35. Series coefficients in order of increasing degree.
  36. domain : (2,) ndarray
  37. Domain that is mapped to window.
  38. window : (2,) ndarray
  39. Window that domain is mapped to.
  40. Class Attributes
  41. ----------------
  42. maxpower : int
  43. Maximum power allowed, i.e., the largest number ``n`` such that
  44. ``p(x)**n`` is allowed. This is to limit runaway polynomial size.
  45. domain : (2,) ndarray
  46. Default domain of the class.
  47. window : (2,) ndarray
  48. Default window of the class.
  49. """
  50. __metaclass__ = ABCMeta
  51. # Not hashable
  52. __hash__ = None
  53. # Opt out of numpy ufuncs and Python ops with ndarray subclasses.
  54. __array_ufunc__ = None
  55. # Limit runaway size. T_n^m has degree n*m
  56. maxpower = 100
  57. @abstractproperty
  58. def domain(self):
  59. pass
  60. @abstractproperty
  61. def window(self):
  62. pass
  63. @abstractproperty
  64. def nickname(self):
  65. pass
  66. @abstractproperty
  67. def basis_name(self):
  68. pass
  69. @abstractmethod
  70. def _add(self):
  71. pass
  72. @abstractmethod
  73. def _sub(self):
  74. pass
  75. @abstractmethod
  76. def _mul(self):
  77. pass
  78. @abstractmethod
  79. def _div(self):
  80. pass
  81. @abstractmethod
  82. def _pow(self):
  83. pass
  84. @abstractmethod
  85. def _val(self):
  86. pass
  87. @abstractmethod
  88. def _int(self):
  89. pass
  90. @abstractmethod
  91. def _der(self):
  92. pass
  93. @abstractmethod
  94. def _fit(self):
  95. pass
  96. @abstractmethod
  97. def _line(self):
  98. pass
  99. @abstractmethod
  100. def _roots(self):
  101. pass
  102. @abstractmethod
  103. def _fromroots(self):
  104. pass
  105. def has_samecoef(self, other):
  106. """Check if coefficients match.
  107. .. versionadded:: 1.6.0
  108. Parameters
  109. ----------
  110. other : class instance
  111. The other class must have the ``coef`` attribute.
  112. Returns
  113. -------
  114. bool : boolean
  115. True if the coefficients are the same, False otherwise.
  116. """
  117. if len(self.coef) != len(other.coef):
  118. return False
  119. elif not np.all(self.coef == other.coef):
  120. return False
  121. else:
  122. return True
  123. def has_samedomain(self, other):
  124. """Check if domains match.
  125. .. versionadded:: 1.6.0
  126. Parameters
  127. ----------
  128. other : class instance
  129. The other class must have the ``domain`` attribute.
  130. Returns
  131. -------
  132. bool : boolean
  133. True if the domains are the same, False otherwise.
  134. """
  135. return np.all(self.domain == other.domain)
  136. def has_samewindow(self, other):
  137. """Check if windows match.
  138. .. versionadded:: 1.6.0
  139. Parameters
  140. ----------
  141. other : class instance
  142. The other class must have the ``window`` attribute.
  143. Returns
  144. -------
  145. bool : boolean
  146. True if the windows are the same, False otherwise.
  147. """
  148. return np.all(self.window == other.window)
  149. def has_sametype(self, other):
  150. """Check if types match.
  151. .. versionadded:: 1.7.0
  152. Parameters
  153. ----------
  154. other : object
  155. Class instance.
  156. Returns
  157. -------
  158. bool : boolean
  159. True if other is same class as self
  160. """
  161. return isinstance(other, self.__class__)
  162. def _get_coefficients(self, other):
  163. """Interpret other as polynomial coefficients.
  164. The `other` argument is checked to see if it is of the same
  165. class as self with identical domain and window. If so,
  166. return its coefficients, otherwise return `other`.
  167. .. versionadded:: 1.9.0
  168. Parameters
  169. ----------
  170. other : anything
  171. Object to be checked.
  172. Returns
  173. -------
  174. coef
  175. The coefficients of`other` if it is a compatible instance,
  176. of ABCPolyBase, otherwise `other`.
  177. Raises
  178. ------
  179. TypeError
  180. When `other` is an incompatible instance of ABCPolyBase.
  181. """
  182. if isinstance(other, ABCPolyBase):
  183. if not isinstance(other, self.__class__):
  184. raise TypeError("Polynomial types differ")
  185. elif not np.all(self.domain == other.domain):
  186. raise TypeError("Domains differ")
  187. elif not np.all(self.window == other.window):
  188. raise TypeError("Windows differ")
  189. return other.coef
  190. return other
  191. def __init__(self, coef, domain=None, window=None):
  192. [coef] = pu.as_series([coef], trim=False)
  193. self.coef = coef
  194. if domain is not None:
  195. [domain] = pu.as_series([domain], trim=False)
  196. if len(domain) != 2:
  197. raise ValueError("Domain has wrong number of elements.")
  198. self.domain = domain
  199. if window is not None:
  200. [window] = pu.as_series([window], trim=False)
  201. if len(window) != 2:
  202. raise ValueError("Window has wrong number of elements.")
  203. self.window = window
  204. def __repr__(self):
  205. format = "%s(%s, domain=%s, window=%s)"
  206. coef = repr(self.coef)[6:-1]
  207. domain = repr(self.domain)[6:-1]
  208. window = repr(self.window)[6:-1]
  209. name = self.__class__.__name__
  210. return format % (name, coef, domain, window)
  211. def __str__(self):
  212. format = "%s(%s)"
  213. coef = str(self.coef)
  214. name = self.nickname
  215. return format % (name, coef)
  216. @classmethod
  217. def _repr_latex_term(cls, i, arg_str, needs_parens):
  218. if cls.basis_name is None:
  219. raise NotImplementedError(
  220. "Subclasses must define either a basis name, or override "
  221. "_repr_latex_term(i, arg_str, needs_parens)")
  222. # since we always add parens, we don't care if the expression needs them
  223. return "{{{basis}}}_{{{i}}}({arg_str})".format(
  224. basis=cls.basis_name, i=i, arg_str=arg_str
  225. )
  226. @staticmethod
  227. def _repr_latex_scalar(x):
  228. # TODO: we're stuck with disabling math formatting until we handle
  229. # exponents in this function
  230. return r'\text{{{}}}'.format(x)
  231. def _repr_latex_(self):
  232. # get the scaled argument string to the basis functions
  233. off, scale = self.mapparms()
  234. if off == 0 and scale == 1:
  235. term = 'x'
  236. needs_parens = False
  237. elif scale == 1:
  238. term = '{} + x'.format(
  239. self._repr_latex_scalar(off)
  240. )
  241. needs_parens = True
  242. elif off == 0:
  243. term = '{}x'.format(
  244. self._repr_latex_scalar(scale)
  245. )
  246. needs_parens = True
  247. else:
  248. term = '{} + {}x'.format(
  249. self._repr_latex_scalar(off),
  250. self._repr_latex_scalar(scale)
  251. )
  252. needs_parens = True
  253. mute = r"\color{{LightGray}}{{{}}}".format
  254. parts = []
  255. for i, c in enumerate(self.coef):
  256. # prevent duplication of + and - signs
  257. if i == 0:
  258. coef_str = '{}'.format(self._repr_latex_scalar(c))
  259. elif not isinstance(c, numbers.Real):
  260. coef_str = ' + ({})'.format(self._repr_latex_scalar(c))
  261. elif not np.signbit(c):
  262. coef_str = ' + {}'.format(self._repr_latex_scalar(c))
  263. else:
  264. coef_str = ' - {}'.format(self._repr_latex_scalar(-c))
  265. # produce the string for the term
  266. term_str = self._repr_latex_term(i, term, needs_parens)
  267. if term_str == '1':
  268. part = coef_str
  269. else:
  270. part = r'{}\,{}'.format(coef_str, term_str)
  271. if c == 0:
  272. part = mute(part)
  273. parts.append(part)
  274. if parts:
  275. body = ''.join(parts)
  276. else:
  277. # in case somehow there are no coefficients at all
  278. body = '0'
  279. return r'$x \mapsto {}$'.format(body)
  280. # Pickle and copy
  281. def __getstate__(self):
  282. ret = self.__dict__.copy()
  283. ret['coef'] = self.coef.copy()
  284. ret['domain'] = self.domain.copy()
  285. ret['window'] = self.window.copy()
  286. return ret
  287. def __setstate__(self, dict):
  288. self.__dict__ = dict
  289. # Call
  290. def __call__(self, arg):
  291. off, scl = pu.mapparms(self.domain, self.window)
  292. arg = off + scl*arg
  293. return self._val(arg, self.coef)
  294. def __iter__(self):
  295. return iter(self.coef)
  296. def __len__(self):
  297. return len(self.coef)
  298. # Numeric properties.
  299. def __neg__(self):
  300. return self.__class__(-self.coef, self.domain, self.window)
  301. def __pos__(self):
  302. return self
  303. def __add__(self, other):
  304. othercoef = self._get_coefficients(other)
  305. try:
  306. coef = self._add(self.coef, othercoef)
  307. except Exception:
  308. return NotImplemented
  309. return self.__class__(coef, self.domain, self.window)
  310. def __sub__(self, other):
  311. othercoef = self._get_coefficients(other)
  312. try:
  313. coef = self._sub(self.coef, othercoef)
  314. except Exception:
  315. return NotImplemented
  316. return self.__class__(coef, self.domain, self.window)
  317. def __mul__(self, other):
  318. othercoef = self._get_coefficients(other)
  319. try:
  320. coef = self._mul(self.coef, othercoef)
  321. except Exception:
  322. return NotImplemented
  323. return self.__class__(coef, self.domain, self.window)
  324. def __div__(self, other):
  325. # this can be removed when python 2 support is dropped.
  326. return self.__floordiv__(other)
  327. def __truediv__(self, other):
  328. # there is no true divide if the rhs is not a Number, although it
  329. # could return the first n elements of an infinite series.
  330. # It is hard to see where n would come from, though.
  331. if not isinstance(other, numbers.Number) or isinstance(other, bool):
  332. form = "unsupported types for true division: '%s', '%s'"
  333. raise TypeError(form % (type(self), type(other)))
  334. return self.__floordiv__(other)
  335. def __floordiv__(self, other):
  336. res = self.__divmod__(other)
  337. if res is NotImplemented:
  338. return res
  339. return res[0]
  340. def __mod__(self, other):
  341. res = self.__divmod__(other)
  342. if res is NotImplemented:
  343. return res
  344. return res[1]
  345. def __divmod__(self, other):
  346. othercoef = self._get_coefficients(other)
  347. try:
  348. quo, rem = self._div(self.coef, othercoef)
  349. except ZeroDivisionError as e:
  350. raise e
  351. except Exception:
  352. return NotImplemented
  353. quo = self.__class__(quo, self.domain, self.window)
  354. rem = self.__class__(rem, self.domain, self.window)
  355. return quo, rem
  356. def __pow__(self, other):
  357. coef = self._pow(self.coef, other, maxpower=self.maxpower)
  358. res = self.__class__(coef, self.domain, self.window)
  359. return res
  360. def __radd__(self, other):
  361. try:
  362. coef = self._add(other, self.coef)
  363. except Exception:
  364. return NotImplemented
  365. return self.__class__(coef, self.domain, self.window)
  366. def __rsub__(self, other):
  367. try:
  368. coef = self._sub(other, self.coef)
  369. except Exception:
  370. return NotImplemented
  371. return self.__class__(coef, self.domain, self.window)
  372. def __rmul__(self, other):
  373. try:
  374. coef = self._mul(other, self.coef)
  375. except Exception:
  376. return NotImplemented
  377. return self.__class__(coef, self.domain, self.window)
  378. def __rdiv__(self, other):
  379. # set to __floordiv__ /.
  380. return self.__rfloordiv__(other)
  381. def __rtruediv__(self, other):
  382. # An instance of ABCPolyBase is not considered a
  383. # Number.
  384. return NotImplemented
  385. def __rfloordiv__(self, other):
  386. res = self.__rdivmod__(other)
  387. if res is NotImplemented:
  388. return res
  389. return res[0]
  390. def __rmod__(self, other):
  391. res = self.__rdivmod__(other)
  392. if res is NotImplemented:
  393. return res
  394. return res[1]
  395. def __rdivmod__(self, other):
  396. try:
  397. quo, rem = self._div(other, self.coef)
  398. except ZeroDivisionError as e:
  399. raise e
  400. except Exception:
  401. return NotImplemented
  402. quo = self.__class__(quo, self.domain, self.window)
  403. rem = self.__class__(rem, self.domain, self.window)
  404. return quo, rem
  405. def __eq__(self, other):
  406. res = (isinstance(other, self.__class__) and
  407. np.all(self.domain == other.domain) and
  408. np.all(self.window == other.window) and
  409. (self.coef.shape == other.coef.shape) and
  410. np.all(self.coef == other.coef))
  411. return res
  412. def __ne__(self, other):
  413. return not self.__eq__(other)
  414. #
  415. # Extra methods.
  416. #
  417. def copy(self):
  418. """Return a copy.
  419. Returns
  420. -------
  421. new_series : series
  422. Copy of self.
  423. """
  424. return self.__class__(self.coef, self.domain, self.window)
  425. def degree(self):
  426. """The degree of the series.
  427. .. versionadded:: 1.5.0
  428. Returns
  429. -------
  430. degree : int
  431. Degree of the series, one less than the number of coefficients.
  432. """
  433. return len(self) - 1
  434. def cutdeg(self, deg):
  435. """Truncate series to the given degree.
  436. Reduce the degree of the series to `deg` by discarding the
  437. high order terms. If `deg` is greater than the current degree a
  438. copy of the current series is returned. This can be useful in least
  439. squares where the coefficients of the high degree terms may be very
  440. small.
  441. .. versionadded:: 1.5.0
  442. Parameters
  443. ----------
  444. deg : non-negative int
  445. The series is reduced to degree `deg` by discarding the high
  446. order terms. The value of `deg` must be a non-negative integer.
  447. Returns
  448. -------
  449. new_series : series
  450. New instance of series with reduced degree.
  451. """
  452. return self.truncate(deg + 1)
  453. def trim(self, tol=0):
  454. """Remove trailing coefficients
  455. Remove trailing coefficients until a coefficient is reached whose
  456. absolute value greater than `tol` or the beginning of the series is
  457. reached. If all the coefficients would be removed the series is set
  458. to ``[0]``. A new series instance is returned with the new
  459. coefficients. The current instance remains unchanged.
  460. Parameters
  461. ----------
  462. tol : non-negative number.
  463. All trailing coefficients less than `tol` will be removed.
  464. Returns
  465. -------
  466. new_series : series
  467. Contains the new set of coefficients.
  468. """
  469. coef = pu.trimcoef(self.coef, tol)
  470. return self.__class__(coef, self.domain, self.window)
  471. def truncate(self, size):
  472. """Truncate series to length `size`.
  473. Reduce the series to length `size` by discarding the high
  474. degree terms. The value of `size` must be a positive integer. This
  475. can be useful in least squares where the coefficients of the
  476. high degree terms may be very small.
  477. Parameters
  478. ----------
  479. size : positive int
  480. The series is reduced to length `size` by discarding the high
  481. degree terms. The value of `size` must be a positive integer.
  482. Returns
  483. -------
  484. new_series : series
  485. New instance of series with truncated coefficients.
  486. """
  487. isize = int(size)
  488. if isize != size or isize < 1:
  489. raise ValueError("size must be a positive integer")
  490. if isize >= len(self.coef):
  491. coef = self.coef
  492. else:
  493. coef = self.coef[:isize]
  494. return self.__class__(coef, self.domain, self.window)
  495. def convert(self, domain=None, kind=None, window=None):
  496. """Convert series to a different kind and/or domain and/or window.
  497. Parameters
  498. ----------
  499. domain : array_like, optional
  500. The domain of the converted series. If the value is None,
  501. the default domain of `kind` is used.
  502. kind : class, optional
  503. The polynomial series type class to which the current instance
  504. should be converted. If kind is None, then the class of the
  505. current instance is used.
  506. window : array_like, optional
  507. The window of the converted series. If the value is None,
  508. the default window of `kind` is used.
  509. Returns
  510. -------
  511. new_series : series
  512. The returned class can be of different type than the current
  513. instance and/or have a different domain and/or different
  514. window.
  515. Notes
  516. -----
  517. Conversion between domains and class types can result in
  518. numerically ill defined series.
  519. Examples
  520. --------
  521. """
  522. if kind is None:
  523. kind = self.__class__
  524. if domain is None:
  525. domain = kind.domain
  526. if window is None:
  527. window = kind.window
  528. return self(kind.identity(domain, window=window))
  529. def mapparms(self):
  530. """Return the mapping parameters.
  531. The returned values define a linear map ``off + scl*x`` that is
  532. applied to the input arguments before the series is evaluated. The
  533. map depends on the ``domain`` and ``window``; if the current
  534. ``domain`` is equal to the ``window`` the resulting map is the
  535. identity. If the coefficients of the series instance are to be
  536. used by themselves outside this class, then the linear function
  537. must be substituted for the ``x`` in the standard representation of
  538. the base polynomials.
  539. Returns
  540. -------
  541. off, scl : float or complex
  542. The mapping function is defined by ``off + scl*x``.
  543. Notes
  544. -----
  545. If the current domain is the interval ``[l1, r1]`` and the window
  546. is ``[l2, r2]``, then the linear mapping function ``L`` is
  547. defined by the equations::
  548. L(l1) = l2
  549. L(r1) = r2
  550. """
  551. return pu.mapparms(self.domain, self.window)
  552. def integ(self, m=1, k=[], lbnd=None):
  553. """Integrate.
  554. Return a series instance that is the definite integral of the
  555. current series.
  556. Parameters
  557. ----------
  558. m : non-negative int
  559. The number of integrations to perform.
  560. k : array_like
  561. Integration constants. The first constant is applied to the
  562. first integration, the second to the second, and so on. The
  563. list of values must less than or equal to `m` in length and any
  564. missing values are set to zero.
  565. lbnd : Scalar
  566. The lower bound of the definite integral.
  567. Returns
  568. -------
  569. new_series : series
  570. A new series representing the integral. The domain is the same
  571. as the domain of the integrated series.
  572. """
  573. off, scl = self.mapparms()
  574. if lbnd is None:
  575. lbnd = 0
  576. else:
  577. lbnd = off + scl*lbnd
  578. coef = self._int(self.coef, m, k, lbnd, 1./scl)
  579. return self.__class__(coef, self.domain, self.window)
  580. def deriv(self, m=1):
  581. """Differentiate.
  582. Return a series instance of that is the derivative of the current
  583. series.
  584. Parameters
  585. ----------
  586. m : non-negative int
  587. Find the derivative of order `m`.
  588. Returns
  589. -------
  590. new_series : series
  591. A new series representing the derivative. The domain is the same
  592. as the domain of the differentiated series.
  593. """
  594. off, scl = self.mapparms()
  595. coef = self._der(self.coef, m, scl)
  596. return self.__class__(coef, self.domain, self.window)
  597. def roots(self):
  598. """Return the roots of the series polynomial.
  599. Compute the roots for the series. Note that the accuracy of the
  600. roots decrease the further outside the domain they lie.
  601. Returns
  602. -------
  603. roots : ndarray
  604. Array containing the roots of the series.
  605. """
  606. roots = self._roots(self.coef)
  607. return pu.mapdomain(roots, self.window, self.domain)
  608. def linspace(self, n=100, domain=None):
  609. """Return x, y values at equally spaced points in domain.
  610. Returns the x, y values at `n` linearly spaced points across the
  611. domain. Here y is the value of the polynomial at the points x. By
  612. default the domain is the same as that of the series instance.
  613. This method is intended mostly as a plotting aid.
  614. .. versionadded:: 1.5.0
  615. Parameters
  616. ----------
  617. n : int, optional
  618. Number of point pairs to return. The default value is 100.
  619. domain : {None, array_like}, optional
  620. If not None, the specified domain is used instead of that of
  621. the calling instance. It should be of the form ``[beg,end]``.
  622. The default is None which case the class domain is used.
  623. Returns
  624. -------
  625. x, y : ndarray
  626. x is equal to linspace(self.domain[0], self.domain[1], n) and
  627. y is the series evaluated at element of x.
  628. """
  629. if domain is None:
  630. domain = self.domain
  631. x = np.linspace(domain[0], domain[1], n)
  632. y = self(x)
  633. return x, y
  634. @classmethod
  635. def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None,
  636. window=None):
  637. """Least squares fit to data.
  638. Return a series instance that is the least squares fit to the data
  639. `y` sampled at `x`. The domain of the returned instance can be
  640. specified and this will often result in a superior fit with less
  641. chance of ill conditioning.
  642. Parameters
  643. ----------
  644. x : array_like, shape (M,)
  645. x-coordinates of the M sample points ``(x[i], y[i])``.
  646. y : array_like, shape (M,) or (M, K)
  647. y-coordinates of the sample points. Several data sets of sample
  648. points sharing the same x-coordinates can be fitted at once by
  649. passing in a 2D-array that contains one dataset per column.
  650. deg : int or 1-D array_like
  651. Degree(s) of the fitting polynomials. If `deg` is a single integer
  652. all terms up to and including the `deg`'th term are included in the
  653. fit. For NumPy versions >= 1.11.0 a list of integers specifying the
  654. degrees of the terms to include may be used instead.
  655. domain : {None, [beg, end], []}, optional
  656. Domain to use for the returned series. If ``None``,
  657. then a minimal domain that covers the points `x` is chosen. If
  658. ``[]`` the class domain is used. The default value was the
  659. class domain in NumPy 1.4 and ``None`` in later versions.
  660. The ``[]`` option was added in numpy 1.5.0.
  661. rcond : float, optional
  662. Relative condition number of the fit. Singular values smaller
  663. than this relative to the largest singular value will be
  664. ignored. The default value is len(x)*eps, where eps is the
  665. relative precision of the float type, about 2e-16 in most
  666. cases.
  667. full : bool, optional
  668. Switch determining nature of return value. When it is False
  669. (the default) just the coefficients are returned, when True
  670. diagnostic information from the singular value decomposition is
  671. also returned.
  672. w : array_like, shape (M,), optional
  673. Weights. If not None the contribution of each point
  674. ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
  675. weights are chosen so that the errors of the products
  676. ``w[i]*y[i]`` all have the same variance. The default value is
  677. None.
  678. .. versionadded:: 1.5.0
  679. window : {[beg, end]}, optional
  680. Window to use for the returned series. The default
  681. value is the default class domain
  682. .. versionadded:: 1.6.0
  683. Returns
  684. -------
  685. new_series : series
  686. A series that represents the least squares fit to the data and
  687. has the domain and window specified in the call. If the
  688. coefficients for the unscaled and unshifted basis polynomials are
  689. of interest, do ``new_series.convert().coef``.
  690. [resid, rank, sv, rcond] : list
  691. These values are only returned if `full` = True
  692. resid -- sum of squared residuals of the least squares fit
  693. rank -- the numerical rank of the scaled Vandermonde matrix
  694. sv -- singular values of the scaled Vandermonde matrix
  695. rcond -- value of `rcond`.
  696. For more details, see `linalg.lstsq`.
  697. """
  698. if domain is None:
  699. domain = pu.getdomain(x)
  700. elif type(domain) is list and len(domain) == 0:
  701. domain = cls.domain
  702. if window is None:
  703. window = cls.window
  704. xnew = pu.mapdomain(x, domain, window)
  705. res = cls._fit(xnew, y, deg, w=w, rcond=rcond, full=full)
  706. if full:
  707. [coef, status] = res
  708. return cls(coef, domain=domain, window=window), status
  709. else:
  710. coef = res
  711. return cls(coef, domain=domain, window=window)
  712. @classmethod
  713. def fromroots(cls, roots, domain=[], window=None):
  714. """Return series instance that has the specified roots.
  715. Returns a series representing the product
  716. ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
  717. list of roots.
  718. Parameters
  719. ----------
  720. roots : array_like
  721. List of roots.
  722. domain : {[], None, array_like}, optional
  723. Domain for the resulting series. If None the domain is the
  724. interval from the smallest root to the largest. If [] the
  725. domain is the class domain. The default is [].
  726. window : {None, array_like}, optional
  727. Window for the returned series. If None the class window is
  728. used. The default is None.
  729. Returns
  730. -------
  731. new_series : series
  732. Series with the specified roots.
  733. """
  734. [roots] = pu.as_series([roots], trim=False)
  735. if domain is None:
  736. domain = pu.getdomain(roots)
  737. elif type(domain) is list and len(domain) == 0:
  738. domain = cls.domain
  739. if window is None:
  740. window = cls.window
  741. deg = len(roots)
  742. off, scl = pu.mapparms(domain, window)
  743. rnew = off + scl*roots
  744. coef = cls._fromroots(rnew) / scl**deg
  745. return cls(coef, domain=domain, window=window)
  746. @classmethod
  747. def identity(cls, domain=None, window=None):
  748. """Identity function.
  749. If ``p`` is the returned series, then ``p(x) == x`` for all
  750. values of x.
  751. Parameters
  752. ----------
  753. domain : {None, array_like}, optional
  754. If given, the array must be of the form ``[beg, end]``, where
  755. ``beg`` and ``end`` are the endpoints of the domain. If None is
  756. given then the class domain is used. The default is None.
  757. window : {None, array_like}, optional
  758. If given, the resulting array must be if the form
  759. ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
  760. the window. If None is given then the class window is used. The
  761. default is None.
  762. Returns
  763. -------
  764. new_series : series
  765. Series of representing the identity.
  766. """
  767. if domain is None:
  768. domain = cls.domain
  769. if window is None:
  770. window = cls.window
  771. off, scl = pu.mapparms(window, domain)
  772. coef = cls._line(off, scl)
  773. return cls(coef, domain, window)
  774. @classmethod
  775. def basis(cls, deg, domain=None, window=None):
  776. """Series basis polynomial of degree `deg`.
  777. Returns the series representing the basis polynomial of degree `deg`.
  778. .. versionadded:: 1.7.0
  779. Parameters
  780. ----------
  781. deg : int
  782. Degree of the basis polynomial for the series. Must be >= 0.
  783. domain : {None, array_like}, optional
  784. If given, the array must be of the form ``[beg, end]``, where
  785. ``beg`` and ``end`` are the endpoints of the domain. If None is
  786. given then the class domain is used. The default is None.
  787. window : {None, array_like}, optional
  788. If given, the resulting array must be if the form
  789. ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
  790. the window. If None is given then the class window is used. The
  791. default is None.
  792. Returns
  793. -------
  794. new_series : series
  795. A series with the coefficient of the `deg` term set to one and
  796. all others zero.
  797. """
  798. if domain is None:
  799. domain = cls.domain
  800. if window is None:
  801. window = cls.window
  802. ideg = int(deg)
  803. if ideg != deg or ideg < 0:
  804. raise ValueError("deg must be non-negative integer")
  805. return cls([0]*ideg + [1], domain, window)
  806. @classmethod
  807. def cast(cls, series, domain=None, window=None):
  808. """Convert series to series of this class.
  809. The `series` is expected to be an instance of some polynomial
  810. series of one of the types supported by by the numpy.polynomial
  811. module, but could be some other class that supports the convert
  812. method.
  813. .. versionadded:: 1.7.0
  814. Parameters
  815. ----------
  816. series : series
  817. The series instance to be converted.
  818. domain : {None, array_like}, optional
  819. If given, the array must be of the form ``[beg, end]``, where
  820. ``beg`` and ``end`` are the endpoints of the domain. If None is
  821. given then the class domain is used. The default is None.
  822. window : {None, array_like}, optional
  823. If given, the resulting array must be if the form
  824. ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
  825. the window. If None is given then the class window is used. The
  826. default is None.
  827. Returns
  828. -------
  829. new_series : series
  830. A series of the same kind as the calling class and equal to
  831. `series` when evaluated.
  832. See Also
  833. --------
  834. convert : similar instance method
  835. """
  836. if domain is None:
  837. domain = cls.domain
  838. if window is None:
  839. window = cls.window
  840. return series.convert(domain, cls, window)