chebyshev.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  1. """
  2. Objects for dealing with Chebyshev series.
  3. This module provides a number of objects (mostly functions) useful for
  4. dealing with Chebyshev series, including a `Chebyshev` class that
  5. encapsulates the usual arithmetic operations. (General information
  6. on how this module represents and works with such polynomials is in the
  7. docstring for its "parent" sub-package, `numpy.polynomial`).
  8. Constants
  9. ---------
  10. - `chebdomain` -- Chebyshev series default domain, [-1,1].
  11. - `chebzero` -- (Coefficients of the) Chebyshev series that evaluates
  12. identically to 0.
  13. - `chebone` -- (Coefficients of the) Chebyshev series that evaluates
  14. identically to 1.
  15. - `chebx` -- (Coefficients of the) Chebyshev series for the identity map,
  16. ``f(x) = x``.
  17. Arithmetic
  18. ----------
  19. - `chebadd` -- add two Chebyshev series.
  20. - `chebsub` -- subtract one Chebyshev series from another.
  21. - `chebmulx` -- multiply a Chebyshev series in ``P_i(x)`` by ``x``.
  22. - `chebmul` -- multiply two Chebyshev series.
  23. - `chebdiv` -- divide one Chebyshev series by another.
  24. - `chebpow` -- raise a Chebyshev series to a positive integer power.
  25. - `chebval` -- evaluate a Chebyshev series at given points.
  26. - `chebval2d` -- evaluate a 2D Chebyshev series at given points.
  27. - `chebval3d` -- evaluate a 3D Chebyshev series at given points.
  28. - `chebgrid2d` -- evaluate a 2D Chebyshev series on a Cartesian product.
  29. - `chebgrid3d` -- evaluate a 3D Chebyshev series on a Cartesian product.
  30. Calculus
  31. --------
  32. - `chebder` -- differentiate a Chebyshev series.
  33. - `chebint` -- integrate a Chebyshev series.
  34. Misc Functions
  35. --------------
  36. - `chebfromroots` -- create a Chebyshev series with specified roots.
  37. - `chebroots` -- find the roots of a Chebyshev series.
  38. - `chebvander` -- Vandermonde-like matrix for Chebyshev polynomials.
  39. - `chebvander2d` -- Vandermonde-like matrix for 2D power series.
  40. - `chebvander3d` -- Vandermonde-like matrix for 3D power series.
  41. - `chebgauss` -- Gauss-Chebyshev quadrature, points and weights.
  42. - `chebweight` -- Chebyshev weight function.
  43. - `chebcompanion` -- symmetrized companion matrix in Chebyshev form.
  44. - `chebfit` -- least-squares fit returning a Chebyshev series.
  45. - `chebpts1` -- Chebyshev points of the first kind.
  46. - `chebpts2` -- Chebyshev points of the second kind.
  47. - `chebtrim` -- trim leading coefficients from a Chebyshev series.
  48. - `chebline` -- Chebyshev series representing given straight line.
  49. - `cheb2poly` -- convert a Chebyshev series to a polynomial.
  50. - `poly2cheb` -- convert a polynomial to a Chebyshev series.
  51. - `chebinterpolate` -- interpolate a function at the Chebyshev points.
  52. Classes
  53. -------
  54. - `Chebyshev` -- A Chebyshev series class.
  55. See also
  56. --------
  57. `numpy.polynomial`
  58. Notes
  59. -----
  60. The implementations of multiplication, division, integration, and
  61. differentiation use the algebraic identities [1]_:
  62. .. math ::
  63. T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\
  64. z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}.
  65. where
  66. .. math :: x = \\frac{z + z^{-1}}{2}.
  67. These identities allow a Chebyshev series to be expressed as a finite,
  68. symmetric Laurent series. In this module, this sort of Laurent series
  69. is referred to as a "z-series."
  70. References
  71. ----------
  72. .. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev
  73. Polynomials," *Journal of Statistical Planning and Inference 14*, 2008
  74. (preprint: https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4)
  75. """
  76. from __future__ import division, absolute_import, print_function
  77. import warnings
  78. import numpy as np
  79. import numpy.linalg as la
  80. from numpy.core.multiarray import normalize_axis_index
  81. from . import polyutils as pu
  82. from ._polybase import ABCPolyBase
  83. __all__ = [
  84. 'chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd',
  85. 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval',
  86. 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots',
  87. 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1',
  88. 'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d',
  89. 'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion',
  90. 'chebgauss', 'chebweight', 'chebinterpolate']
  91. chebtrim = pu.trimcoef
  92. #
  93. # A collection of functions for manipulating z-series. These are private
  94. # functions and do minimal error checking.
  95. #
  96. def _cseries_to_zseries(c):
  97. """Covert Chebyshev series to z-series.
  98. Covert a Chebyshev series to the equivalent z-series. The result is
  99. never an empty array. The dtype of the return is the same as that of
  100. the input. No checks are run on the arguments as this routine is for
  101. internal use.
  102. Parameters
  103. ----------
  104. c : 1-D ndarray
  105. Chebyshev coefficients, ordered from low to high
  106. Returns
  107. -------
  108. zs : 1-D ndarray
  109. Odd length symmetric z-series, ordered from low to high.
  110. """
  111. n = c.size
  112. zs = np.zeros(2*n-1, dtype=c.dtype)
  113. zs[n-1:] = c/2
  114. return zs + zs[::-1]
  115. def _zseries_to_cseries(zs):
  116. """Covert z-series to a Chebyshev series.
  117. Covert a z series to the equivalent Chebyshev series. The result is
  118. never an empty array. The dtype of the return is the same as that of
  119. the input. No checks are run on the arguments as this routine is for
  120. internal use.
  121. Parameters
  122. ----------
  123. zs : 1-D ndarray
  124. Odd length symmetric z-series, ordered from low to high.
  125. Returns
  126. -------
  127. c : 1-D ndarray
  128. Chebyshev coefficients, ordered from low to high.
  129. """
  130. n = (zs.size + 1)//2
  131. c = zs[n-1:].copy()
  132. c[1:n] *= 2
  133. return c
  134. def _zseries_mul(z1, z2):
  135. """Multiply two z-series.
  136. Multiply two z-series to produce a z-series.
  137. Parameters
  138. ----------
  139. z1, z2 : 1-D ndarray
  140. The arrays must be 1-D but this is not checked.
  141. Returns
  142. -------
  143. product : 1-D ndarray
  144. The product z-series.
  145. Notes
  146. -----
  147. This is simply convolution. If symmetric/anti-symmetric z-series are
  148. denoted by S/A then the following rules apply:
  149. S*S, A*A -> S
  150. S*A, A*S -> A
  151. """
  152. return np.convolve(z1, z2)
  153. def _zseries_div(z1, z2):
  154. """Divide the first z-series by the second.
  155. Divide `z1` by `z2` and return the quotient and remainder as z-series.
  156. Warning: this implementation only applies when both z1 and z2 have the
  157. same symmetry, which is sufficient for present purposes.
  158. Parameters
  159. ----------
  160. z1, z2 : 1-D ndarray
  161. The arrays must be 1-D and have the same symmetry, but this is not
  162. checked.
  163. Returns
  164. -------
  165. (quotient, remainder) : 1-D ndarrays
  166. Quotient and remainder as z-series.
  167. Notes
  168. -----
  169. This is not the same as polynomial division on account of the desired form
  170. of the remainder. If symmetric/anti-symmetric z-series are denoted by S/A
  171. then the following rules apply:
  172. S/S -> S,S
  173. A/A -> S,A
  174. The restriction to types of the same symmetry could be fixed but seems like
  175. unneeded generality. There is no natural form for the remainder in the case
  176. where there is no symmetry.
  177. """
  178. z1 = z1.copy()
  179. z2 = z2.copy()
  180. len1 = len(z1)
  181. len2 = len(z2)
  182. if len2 == 1:
  183. z1 /= z2
  184. return z1, z1[:1]*0
  185. elif len1 < len2:
  186. return z1[:1]*0, z1
  187. else:
  188. dlen = len1 - len2
  189. scl = z2[0]
  190. z2 /= scl
  191. quo = np.empty(dlen + 1, dtype=z1.dtype)
  192. i = 0
  193. j = dlen
  194. while i < j:
  195. r = z1[i]
  196. quo[i] = z1[i]
  197. quo[dlen - i] = r
  198. tmp = r*z2
  199. z1[i:i+len2] -= tmp
  200. z1[j:j+len2] -= tmp
  201. i += 1
  202. j -= 1
  203. r = z1[i]
  204. quo[i] = r
  205. tmp = r*z2
  206. z1[i:i+len2] -= tmp
  207. quo /= scl
  208. rem = z1[i+1:i-1+len2].copy()
  209. return quo, rem
  210. def _zseries_der(zs):
  211. """Differentiate a z-series.
  212. The derivative is with respect to x, not z. This is achieved using the
  213. chain rule and the value of dx/dz given in the module notes.
  214. Parameters
  215. ----------
  216. zs : z-series
  217. The z-series to differentiate.
  218. Returns
  219. -------
  220. derivative : z-series
  221. The derivative
  222. Notes
  223. -----
  224. The zseries for x (ns) has been multiplied by two in order to avoid
  225. using floats that are incompatible with Decimal and likely other
  226. specialized scalar types. This scaling has been compensated by
  227. multiplying the value of zs by two also so that the two cancels in the
  228. division.
  229. """
  230. n = len(zs)//2
  231. ns = np.array([-1, 0, 1], dtype=zs.dtype)
  232. zs *= np.arange(-n, n+1)*2
  233. d, r = _zseries_div(zs, ns)
  234. return d
  235. def _zseries_int(zs):
  236. """Integrate a z-series.
  237. The integral is with respect to x, not z. This is achieved by a change
  238. of variable using dx/dz given in the module notes.
  239. Parameters
  240. ----------
  241. zs : z-series
  242. The z-series to integrate
  243. Returns
  244. -------
  245. integral : z-series
  246. The indefinite integral
  247. Notes
  248. -----
  249. The zseries for x (ns) has been multiplied by two in order to avoid
  250. using floats that are incompatible with Decimal and likely other
  251. specialized scalar types. This scaling has been compensated by
  252. dividing the resulting zs by two.
  253. """
  254. n = 1 + len(zs)//2
  255. ns = np.array([-1, 0, 1], dtype=zs.dtype)
  256. zs = _zseries_mul(zs, ns)
  257. div = np.arange(-n, n+1)*2
  258. zs[:n] /= div[:n]
  259. zs[n+1:] /= div[n+1:]
  260. zs[n] = 0
  261. return zs
  262. #
  263. # Chebyshev series functions
  264. #
  265. def poly2cheb(pol):
  266. """
  267. Convert a polynomial to a Chebyshev series.
  268. Convert an array representing the coefficients of a polynomial (relative
  269. to the "standard" basis) ordered from lowest degree to highest, to an
  270. array of the coefficients of the equivalent Chebyshev series, ordered
  271. from lowest to highest degree.
  272. Parameters
  273. ----------
  274. pol : array_like
  275. 1-D array containing the polynomial coefficients
  276. Returns
  277. -------
  278. c : ndarray
  279. 1-D array containing the coefficients of the equivalent Chebyshev
  280. series.
  281. See Also
  282. --------
  283. cheb2poly
  284. Notes
  285. -----
  286. The easy way to do conversions between polynomial basis sets
  287. is to use the convert method of a class instance.
  288. Examples
  289. --------
  290. >>> from numpy import polynomial as P
  291. >>> p = P.Polynomial(range(4))
  292. >>> p
  293. Polynomial([ 0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
  294. >>> c = p.convert(kind=P.Chebyshev)
  295. >>> c
  296. Chebyshev([ 1. , 3.25, 1. , 0.75], domain=[-1, 1], window=[-1, 1])
  297. >>> P.chebyshev.poly2cheb(range(4))
  298. array([ 1. , 3.25, 1. , 0.75])
  299. """
  300. [pol] = pu.as_series([pol])
  301. deg = len(pol) - 1
  302. res = 0
  303. for i in range(deg, -1, -1):
  304. res = chebadd(chebmulx(res), pol[i])
  305. return res
  306. def cheb2poly(c):
  307. """
  308. Convert a Chebyshev series to a polynomial.
  309. Convert an array representing the coefficients of a Chebyshev series,
  310. ordered from lowest degree to highest, to an array of the coefficients
  311. of the equivalent polynomial (relative to the "standard" basis) ordered
  312. from lowest to highest degree.
  313. Parameters
  314. ----------
  315. c : array_like
  316. 1-D array containing the Chebyshev series coefficients, ordered
  317. from lowest order term to highest.
  318. Returns
  319. -------
  320. pol : ndarray
  321. 1-D array containing the coefficients of the equivalent polynomial
  322. (relative to the "standard" basis) ordered from lowest order term
  323. to highest.
  324. See Also
  325. --------
  326. poly2cheb
  327. Notes
  328. -----
  329. The easy way to do conversions between polynomial basis sets
  330. is to use the convert method of a class instance.
  331. Examples
  332. --------
  333. >>> from numpy import polynomial as P
  334. >>> c = P.Chebyshev(range(4))
  335. >>> c
  336. Chebyshev([ 0., 1., 2., 3.], [-1., 1.])
  337. >>> p = c.convert(kind=P.Polynomial)
  338. >>> p
  339. Polynomial([ -2., -8., 4., 12.], [-1., 1.])
  340. >>> P.chebyshev.cheb2poly(range(4))
  341. array([ -2., -8., 4., 12.])
  342. """
  343. from .polynomial import polyadd, polysub, polymulx
  344. [c] = pu.as_series([c])
  345. n = len(c)
  346. if n < 3:
  347. return c
  348. else:
  349. c0 = c[-2]
  350. c1 = c[-1]
  351. # i is the current degree of c1
  352. for i in range(n - 1, 1, -1):
  353. tmp = c0
  354. c0 = polysub(c[i - 2], c1)
  355. c1 = polyadd(tmp, polymulx(c1)*2)
  356. return polyadd(c0, polymulx(c1))
  357. #
  358. # These are constant arrays are of integer type so as to be compatible
  359. # with the widest range of other types, such as Decimal.
  360. #
  361. # Chebyshev default domain.
  362. chebdomain = np.array([-1, 1])
  363. # Chebyshev coefficients representing zero.
  364. chebzero = np.array([0])
  365. # Chebyshev coefficients representing one.
  366. chebone = np.array([1])
  367. # Chebyshev coefficients representing the identity x.
  368. chebx = np.array([0, 1])
  369. def chebline(off, scl):
  370. """
  371. Chebyshev series whose graph is a straight line.
  372. Parameters
  373. ----------
  374. off, scl : scalars
  375. The specified line is given by ``off + scl*x``.
  376. Returns
  377. -------
  378. y : ndarray
  379. This module's representation of the Chebyshev series for
  380. ``off + scl*x``.
  381. See Also
  382. --------
  383. polyline
  384. Examples
  385. --------
  386. >>> import numpy.polynomial.chebyshev as C
  387. >>> C.chebline(3,2)
  388. array([3, 2])
  389. >>> C.chebval(-3, C.chebline(3,2)) # should be -3
  390. -3.0
  391. """
  392. if scl != 0:
  393. return np.array([off, scl])
  394. else:
  395. return np.array([off])
  396. def chebfromroots(roots):
  397. """
  398. Generate a Chebyshev series with given roots.
  399. The function returns the coefficients of the polynomial
  400. .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
  401. in Chebyshev form, where the `r_n` are the roots specified in `roots`.
  402. If a zero has multiplicity n, then it must appear in `roots` n times.
  403. For instance, if 2 is a root of multiplicity three and 3 is a root of
  404. multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
  405. roots can appear in any order.
  406. If the returned coefficients are `c`, then
  407. .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x)
  408. The coefficient of the last term is not generally 1 for monic
  409. polynomials in Chebyshev form.
  410. Parameters
  411. ----------
  412. roots : array_like
  413. Sequence containing the roots.
  414. Returns
  415. -------
  416. out : ndarray
  417. 1-D array of coefficients. If all roots are real then `out` is a
  418. real array, if some of the roots are complex, then `out` is complex
  419. even if all the coefficients in the result are real (see Examples
  420. below).
  421. See Also
  422. --------
  423. polyfromroots, legfromroots, lagfromroots, hermfromroots,
  424. hermefromroots.
  425. Examples
  426. --------
  427. >>> import numpy.polynomial.chebyshev as C
  428. >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis
  429. array([ 0. , -0.25, 0. , 0.25])
  430. >>> j = complex(0,1)
  431. >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis
  432. array([ 1.5+0.j, 0.0+0.j, 0.5+0.j])
  433. """
  434. if len(roots) == 0:
  435. return np.ones(1)
  436. else:
  437. [roots] = pu.as_series([roots], trim=False)
  438. roots.sort()
  439. p = [chebline(-r, 1) for r in roots]
  440. n = len(p)
  441. while n > 1:
  442. m, r = divmod(n, 2)
  443. tmp = [chebmul(p[i], p[i+m]) for i in range(m)]
  444. if r:
  445. tmp[0] = chebmul(tmp[0], p[-1])
  446. p = tmp
  447. n = m
  448. return p[0]
  449. def chebadd(c1, c2):
  450. """
  451. Add one Chebyshev series to another.
  452. Returns the sum of two Chebyshev series `c1` + `c2`. The arguments
  453. are sequences of coefficients ordered from lowest order term to
  454. highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  455. Parameters
  456. ----------
  457. c1, c2 : array_like
  458. 1-D arrays of Chebyshev series coefficients ordered from low to
  459. high.
  460. Returns
  461. -------
  462. out : ndarray
  463. Array representing the Chebyshev series of their sum.
  464. See Also
  465. --------
  466. chebsub, chebmulx, chebmul, chebdiv, chebpow
  467. Notes
  468. -----
  469. Unlike multiplication, division, etc., the sum of two Chebyshev series
  470. is a Chebyshev series (without having to "reproject" the result onto
  471. the basis set) so addition, just like that of "standard" polynomials,
  472. is simply "component-wise."
  473. Examples
  474. --------
  475. >>> from numpy.polynomial import chebyshev as C
  476. >>> c1 = (1,2,3)
  477. >>> c2 = (3,2,1)
  478. >>> C.chebadd(c1,c2)
  479. array([ 4., 4., 4.])
  480. """
  481. # c1, c2 are trimmed copies
  482. [c1, c2] = pu.as_series([c1, c2])
  483. if len(c1) > len(c2):
  484. c1[:c2.size] += c2
  485. ret = c1
  486. else:
  487. c2[:c1.size] += c1
  488. ret = c2
  489. return pu.trimseq(ret)
  490. def chebsub(c1, c2):
  491. """
  492. Subtract one Chebyshev series from another.
  493. Returns the difference of two Chebyshev series `c1` - `c2`. The
  494. sequences of coefficients are from lowest order term to highest, i.e.,
  495. [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  496. Parameters
  497. ----------
  498. c1, c2 : array_like
  499. 1-D arrays of Chebyshev series coefficients ordered from low to
  500. high.
  501. Returns
  502. -------
  503. out : ndarray
  504. Of Chebyshev series coefficients representing their difference.
  505. See Also
  506. --------
  507. chebadd, chebmulx, chebmul, chebdiv, chebpow
  508. Notes
  509. -----
  510. Unlike multiplication, division, etc., the difference of two Chebyshev
  511. series is a Chebyshev series (without having to "reproject" the result
  512. onto the basis set) so subtraction, just like that of "standard"
  513. polynomials, is simply "component-wise."
  514. Examples
  515. --------
  516. >>> from numpy.polynomial import chebyshev as C
  517. >>> c1 = (1,2,3)
  518. >>> c2 = (3,2,1)
  519. >>> C.chebsub(c1,c2)
  520. array([-2., 0., 2.])
  521. >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2)
  522. array([ 2., 0., -2.])
  523. """
  524. # c1, c2 are trimmed copies
  525. [c1, c2] = pu.as_series([c1, c2])
  526. if len(c1) > len(c2):
  527. c1[:c2.size] -= c2
  528. ret = c1
  529. else:
  530. c2 = -c2
  531. c2[:c1.size] += c1
  532. ret = c2
  533. return pu.trimseq(ret)
  534. def chebmulx(c):
  535. """Multiply a Chebyshev series by x.
  536. Multiply the polynomial `c` by x, where x is the independent
  537. variable.
  538. Parameters
  539. ----------
  540. c : array_like
  541. 1-D array of Chebyshev series coefficients ordered from low to
  542. high.
  543. Returns
  544. -------
  545. out : ndarray
  546. Array representing the result of the multiplication.
  547. Notes
  548. -----
  549. .. versionadded:: 1.5.0
  550. Examples
  551. --------
  552. >>> from numpy.polynomial import chebyshev as C
  553. >>> C.chebmulx([1,2,3])
  554. array([ 1., 2.5, 3., 1.5, 2.])
  555. """
  556. # c is a trimmed copy
  557. [c] = pu.as_series([c])
  558. # The zero series needs special treatment
  559. if len(c) == 1 and c[0] == 0:
  560. return c
  561. prd = np.empty(len(c) + 1, dtype=c.dtype)
  562. prd[0] = c[0]*0
  563. prd[1] = c[0]
  564. if len(c) > 1:
  565. tmp = c[1:]/2
  566. prd[2:] = tmp
  567. prd[0:-2] += tmp
  568. return prd
  569. def chebmul(c1, c2):
  570. """
  571. Multiply one Chebyshev series by another.
  572. Returns the product of two Chebyshev series `c1` * `c2`. The arguments
  573. are sequences of coefficients, from lowest order "term" to highest,
  574. e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  575. Parameters
  576. ----------
  577. c1, c2 : array_like
  578. 1-D arrays of Chebyshev series coefficients ordered from low to
  579. high.
  580. Returns
  581. -------
  582. out : ndarray
  583. Of Chebyshev series coefficients representing their product.
  584. See Also
  585. --------
  586. chebadd, chebsub, chebmulx, chebdiv, chebpow
  587. Notes
  588. -----
  589. In general, the (polynomial) product of two C-series results in terms
  590. that are not in the Chebyshev polynomial basis set. Thus, to express
  591. the product as a C-series, it is typically necessary to "reproject"
  592. the product onto said basis set, which typically produces
  593. "unintuitive live" (but correct) results; see Examples section below.
  594. Examples
  595. --------
  596. >>> from numpy.polynomial import chebyshev as C
  597. >>> c1 = (1,2,3)
  598. >>> c2 = (3,2,1)
  599. >>> C.chebmul(c1,c2) # multiplication requires "reprojection"
  600. array([ 6.5, 12. , 12. , 4. , 1.5])
  601. """
  602. # c1, c2 are trimmed copies
  603. [c1, c2] = pu.as_series([c1, c2])
  604. z1 = _cseries_to_zseries(c1)
  605. z2 = _cseries_to_zseries(c2)
  606. prd = _zseries_mul(z1, z2)
  607. ret = _zseries_to_cseries(prd)
  608. return pu.trimseq(ret)
  609. def chebdiv(c1, c2):
  610. """
  611. Divide one Chebyshev series by another.
  612. Returns the quotient-with-remainder of two Chebyshev series
  613. `c1` / `c2`. The arguments are sequences of coefficients from lowest
  614. order "term" to highest, e.g., [1,2,3] represents the series
  615. ``T_0 + 2*T_1 + 3*T_2``.
  616. Parameters
  617. ----------
  618. c1, c2 : array_like
  619. 1-D arrays of Chebyshev series coefficients ordered from low to
  620. high.
  621. Returns
  622. -------
  623. [quo, rem] : ndarrays
  624. Of Chebyshev series coefficients representing the quotient and
  625. remainder.
  626. See Also
  627. --------
  628. chebadd, chebsub, chemulx, chebmul, chebpow
  629. Notes
  630. -----
  631. In general, the (polynomial) division of one C-series by another
  632. results in quotient and remainder terms that are not in the Chebyshev
  633. polynomial basis set. Thus, to express these results as C-series, it
  634. is typically necessary to "reproject" the results onto said basis
  635. set, which typically produces "unintuitive" (but correct) results;
  636. see Examples section below.
  637. Examples
  638. --------
  639. >>> from numpy.polynomial import chebyshev as C
  640. >>> c1 = (1,2,3)
  641. >>> c2 = (3,2,1)
  642. >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not
  643. (array([ 3.]), array([-8., -4.]))
  644. >>> c2 = (0,1,2,3)
  645. >>> C.chebdiv(c2,c1) # neither "intuitive"
  646. (array([ 0., 2.]), array([-2., -4.]))
  647. """
  648. # c1, c2 are trimmed copies
  649. [c1, c2] = pu.as_series([c1, c2])
  650. if c2[-1] == 0:
  651. raise ZeroDivisionError()
  652. lc1 = len(c1)
  653. lc2 = len(c2)
  654. if lc1 < lc2:
  655. return c1[:1]*0, c1
  656. elif lc2 == 1:
  657. return c1/c2[-1], c1[:1]*0
  658. else:
  659. z1 = _cseries_to_zseries(c1)
  660. z2 = _cseries_to_zseries(c2)
  661. quo, rem = _zseries_div(z1, z2)
  662. quo = pu.trimseq(_zseries_to_cseries(quo))
  663. rem = pu.trimseq(_zseries_to_cseries(rem))
  664. return quo, rem
  665. def chebpow(c, pow, maxpower=16):
  666. """Raise a Chebyshev series to a power.
  667. Returns the Chebyshev series `c` raised to the power `pow`. The
  668. argument `c` is a sequence of coefficients ordered from low to high.
  669. i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.``
  670. Parameters
  671. ----------
  672. c : array_like
  673. 1-D array of Chebyshev series coefficients ordered from low to
  674. high.
  675. pow : integer
  676. Power to which the series will be raised
  677. maxpower : integer, optional
  678. Maximum power allowed. This is mainly to limit growth of the series
  679. to unmanageable size. Default is 16
  680. Returns
  681. -------
  682. coef : ndarray
  683. Chebyshev series of power.
  684. See Also
  685. --------
  686. chebadd, chebsub, chebmulx, chebmul, chebdiv
  687. Examples
  688. --------
  689. >>> from numpy.polynomial import chebyshev as C
  690. >>> C.chebpow([1, 2, 3, 4], 2)
  691. array([15.5, 22. , 16. , 14. , 12.5, 12. , 8. ])
  692. """
  693. # c is a trimmed copy
  694. [c] = pu.as_series([c])
  695. power = int(pow)
  696. if power != pow or power < 0:
  697. raise ValueError("Power must be a non-negative integer.")
  698. elif maxpower is not None and power > maxpower:
  699. raise ValueError("Power is too large")
  700. elif power == 0:
  701. return np.array([1], dtype=c.dtype)
  702. elif power == 1:
  703. return c
  704. else:
  705. # This can be made more efficient by using powers of two
  706. # in the usual way.
  707. zs = _cseries_to_zseries(c)
  708. prd = zs
  709. for i in range(2, power + 1):
  710. prd = np.convolve(prd, zs)
  711. return _zseries_to_cseries(prd)
  712. def chebder(c, m=1, scl=1, axis=0):
  713. """
  714. Differentiate a Chebyshev series.
  715. Returns the Chebyshev series coefficients `c` differentiated `m` times
  716. along `axis`. At each iteration the result is multiplied by `scl` (the
  717. scaling factor is for use in a linear change of variable). The argument
  718. `c` is an array of coefficients from low to high degree along each
  719. axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2``
  720. while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) +
  721. 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is
  722. ``y``.
  723. Parameters
  724. ----------
  725. c : array_like
  726. Array of Chebyshev series coefficients. If c is multidimensional
  727. the different axis correspond to different variables with the
  728. degree in each axis given by the corresponding index.
  729. m : int, optional
  730. Number of derivatives taken, must be non-negative. (Default: 1)
  731. scl : scalar, optional
  732. Each differentiation is multiplied by `scl`. The end result is
  733. multiplication by ``scl**m``. This is for use in a linear change of
  734. variable. (Default: 1)
  735. axis : int, optional
  736. Axis over which the derivative is taken. (Default: 0).
  737. .. versionadded:: 1.7.0
  738. Returns
  739. -------
  740. der : ndarray
  741. Chebyshev series of the derivative.
  742. See Also
  743. --------
  744. chebint
  745. Notes
  746. -----
  747. In general, the result of differentiating a C-series needs to be
  748. "reprojected" onto the C-series basis set. Thus, typically, the
  749. result of this function is "unintuitive," albeit correct; see Examples
  750. section below.
  751. Examples
  752. --------
  753. >>> from numpy.polynomial import chebyshev as C
  754. >>> c = (1,2,3,4)
  755. >>> C.chebder(c)
  756. array([ 14., 12., 24.])
  757. >>> C.chebder(c,3)
  758. array([ 96.])
  759. >>> C.chebder(c,scl=-1)
  760. array([-14., -12., -24.])
  761. >>> C.chebder(c,2,-1)
  762. array([ 12., 96.])
  763. """
  764. c = np.array(c, ndmin=1, copy=1)
  765. if c.dtype.char in '?bBhHiIlLqQpP':
  766. c = c.astype(np.double)
  767. cnt, iaxis = [int(t) for t in [m, axis]]
  768. if cnt != m:
  769. raise ValueError("The order of derivation must be integer")
  770. if cnt < 0:
  771. raise ValueError("The order of derivation must be non-negative")
  772. if iaxis != axis:
  773. raise ValueError("The axis must be integer")
  774. iaxis = normalize_axis_index(iaxis, c.ndim)
  775. if cnt == 0:
  776. return c
  777. c = np.moveaxis(c, iaxis, 0)
  778. n = len(c)
  779. if cnt >= n:
  780. c = c[:1]*0
  781. else:
  782. for i in range(cnt):
  783. n = n - 1
  784. c *= scl
  785. der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
  786. for j in range(n, 2, -1):
  787. der[j - 1] = (2*j)*c[j]
  788. c[j - 2] += (j*c[j])/(j - 2)
  789. if n > 1:
  790. der[1] = 4*c[2]
  791. der[0] = c[1]
  792. c = der
  793. c = np.moveaxis(c, 0, iaxis)
  794. return c
  795. def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
  796. """
  797. Integrate a Chebyshev series.
  798. Returns the Chebyshev series coefficients `c` integrated `m` times from
  799. `lbnd` along `axis`. At each iteration the resulting series is
  800. **multiplied** by `scl` and an integration constant, `k`, is added.
  801. The scaling factor is for use in a linear change of variable. ("Buyer
  802. beware": note that, depending on what one is doing, one may want `scl`
  803. to be the reciprocal of what one might expect; for more information,
  804. see the Notes section below.) The argument `c` is an array of
  805. coefficients from low to high degree along each axis, e.g., [1,2,3]
  806. represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]]
  807. represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) +
  808. 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
  809. Parameters
  810. ----------
  811. c : array_like
  812. Array of Chebyshev series coefficients. If c is multidimensional
  813. the different axis correspond to different variables with the
  814. degree in each axis given by the corresponding index.
  815. m : int, optional
  816. Order of integration, must be positive. (Default: 1)
  817. k : {[], list, scalar}, optional
  818. Integration constant(s). The value of the first integral at zero
  819. is the first value in the list, the value of the second integral
  820. at zero is the second value, etc. If ``k == []`` (the default),
  821. all constants are set to zero. If ``m == 1``, a single scalar can
  822. be given instead of a list.
  823. lbnd : scalar, optional
  824. The lower bound of the integral. (Default: 0)
  825. scl : scalar, optional
  826. Following each integration the result is *multiplied* by `scl`
  827. before the integration constant is added. (Default: 1)
  828. axis : int, optional
  829. Axis over which the integral is taken. (Default: 0).
  830. .. versionadded:: 1.7.0
  831. Returns
  832. -------
  833. S : ndarray
  834. C-series coefficients of the integral.
  835. Raises
  836. ------
  837. ValueError
  838. If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
  839. ``np.ndim(scl) != 0``.
  840. See Also
  841. --------
  842. chebder
  843. Notes
  844. -----
  845. Note that the result of each integration is *multiplied* by `scl`.
  846. Why is this important to note? Say one is making a linear change of
  847. variable :math:`u = ax + b` in an integral relative to `x`. Then
  848. :math:`dx = du/a`, so one will need to set `scl` equal to
  849. :math:`1/a`- perhaps not what one would have first thought.
  850. Also note that, in general, the result of integrating a C-series needs
  851. to be "reprojected" onto the C-series basis set. Thus, typically,
  852. the result of this function is "unintuitive," albeit correct; see
  853. Examples section below.
  854. Examples
  855. --------
  856. >>> from numpy.polynomial import chebyshev as C
  857. >>> c = (1,2,3)
  858. >>> C.chebint(c)
  859. array([ 0.5, -0.5, 0.5, 0.5])
  860. >>> C.chebint(c,3)
  861. array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667,
  862. 0.00625 ])
  863. >>> C.chebint(c, k=3)
  864. array([ 3.5, -0.5, 0.5, 0.5])
  865. >>> C.chebint(c,lbnd=-2)
  866. array([ 8.5, -0.5, 0.5, 0.5])
  867. >>> C.chebint(c,scl=-2)
  868. array([-1., 1., -1., -1.])
  869. """
  870. c = np.array(c, ndmin=1, copy=1)
  871. if c.dtype.char in '?bBhHiIlLqQpP':
  872. c = c.astype(np.double)
  873. if not np.iterable(k):
  874. k = [k]
  875. cnt, iaxis = [int(t) for t in [m, axis]]
  876. if cnt != m:
  877. raise ValueError("The order of integration must be integer")
  878. if cnt < 0:
  879. raise ValueError("The order of integration must be non-negative")
  880. if len(k) > cnt:
  881. raise ValueError("Too many integration constants")
  882. if np.ndim(lbnd) != 0:
  883. raise ValueError("lbnd must be a scalar.")
  884. if np.ndim(scl) != 0:
  885. raise ValueError("scl must be a scalar.")
  886. if iaxis != axis:
  887. raise ValueError("The axis must be integer")
  888. iaxis = normalize_axis_index(iaxis, c.ndim)
  889. if cnt == 0:
  890. return c
  891. c = np.moveaxis(c, iaxis, 0)
  892. k = list(k) + [0]*(cnt - len(k))
  893. for i in range(cnt):
  894. n = len(c)
  895. c *= scl
  896. if n == 1 and np.all(c[0] == 0):
  897. c[0] += k[i]
  898. else:
  899. tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
  900. tmp[0] = c[0]*0
  901. tmp[1] = c[0]
  902. if n > 1:
  903. tmp[2] = c[1]/4
  904. for j in range(2, n):
  905. t = c[j]/(2*j + 1) # FIXME: t never used
  906. tmp[j + 1] = c[j]/(2*(j + 1))
  907. tmp[j - 1] -= c[j]/(2*(j - 1))
  908. tmp[0] += k[i] - chebval(lbnd, tmp)
  909. c = tmp
  910. c = np.moveaxis(c, 0, iaxis)
  911. return c
  912. def chebval(x, c, tensor=True):
  913. """
  914. Evaluate a Chebyshev series at points x.
  915. If `c` is of length `n + 1`, this function returns the value:
  916. .. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)
  917. The parameter `x` is converted to an array only if it is a tuple or a
  918. list, otherwise it is treated as a scalar. In either case, either `x`
  919. or its elements must support multiplication and addition both with
  920. themselves and with the elements of `c`.
  921. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
  922. `c` is multidimensional, then the shape of the result depends on the
  923. value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
  924. x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
  925. scalars have shape (,).
  926. Trailing zeros in the coefficients will be used in the evaluation, so
  927. they should be avoided if efficiency is a concern.
  928. Parameters
  929. ----------
  930. x : array_like, compatible object
  931. If `x` is a list or tuple, it is converted to an ndarray, otherwise
  932. it is left unchanged and treated as a scalar. In either case, `x`
  933. or its elements must support addition and multiplication with
  934. with themselves and with the elements of `c`.
  935. c : array_like
  936. Array of coefficients ordered so that the coefficients for terms of
  937. degree n are contained in c[n]. If `c` is multidimensional the
  938. remaining indices enumerate multiple polynomials. In the two
  939. dimensional case the coefficients may be thought of as stored in
  940. the columns of `c`.
  941. tensor : boolean, optional
  942. If True, the shape of the coefficient array is extended with ones
  943. on the right, one for each dimension of `x`. Scalars have dimension 0
  944. for this action. The result is that every column of coefficients in
  945. `c` is evaluated for every element of `x`. If False, `x` is broadcast
  946. over the columns of `c` for the evaluation. This keyword is useful
  947. when `c` is multidimensional. The default value is True.
  948. .. versionadded:: 1.7.0
  949. Returns
  950. -------
  951. values : ndarray, algebra_like
  952. The shape of the return value is described above.
  953. See Also
  954. --------
  955. chebval2d, chebgrid2d, chebval3d, chebgrid3d
  956. Notes
  957. -----
  958. The evaluation uses Clenshaw recursion, aka synthetic division.
  959. Examples
  960. --------
  961. """
  962. c = np.array(c, ndmin=1, copy=1)
  963. if c.dtype.char in '?bBhHiIlLqQpP':
  964. c = c.astype(np.double)
  965. if isinstance(x, (tuple, list)):
  966. x = np.asarray(x)
  967. if isinstance(x, np.ndarray) and tensor:
  968. c = c.reshape(c.shape + (1,)*x.ndim)
  969. if len(c) == 1:
  970. c0 = c[0]
  971. c1 = 0
  972. elif len(c) == 2:
  973. c0 = c[0]
  974. c1 = c[1]
  975. else:
  976. x2 = 2*x
  977. c0 = c[-2]
  978. c1 = c[-1]
  979. for i in range(3, len(c) + 1):
  980. tmp = c0
  981. c0 = c[-i] - c1
  982. c1 = tmp + c1*x2
  983. return c0 + c1*x
  984. def chebval2d(x, y, c):
  985. """
  986. Evaluate a 2-D Chebyshev series at points (x, y).
  987. This function returns the values:
  988. .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y)
  989. The parameters `x` and `y` are converted to arrays only if they are
  990. tuples or a lists, otherwise they are treated as a scalars and they
  991. must have the same shape after conversion. In either case, either `x`
  992. and `y` or their elements must support multiplication and addition both
  993. with themselves and with the elements of `c`.
  994. If `c` is a 1-D array a one is implicitly appended to its shape to make
  995. it 2-D. The shape of the result will be c.shape[2:] + x.shape.
  996. Parameters
  997. ----------
  998. x, y : array_like, compatible objects
  999. The two dimensional series is evaluated at the points `(x, y)`,
  1000. where `x` and `y` must have the same shape. If `x` or `y` is a list
  1001. or tuple, it is first converted to an ndarray, otherwise it is left
  1002. unchanged and if it isn't an ndarray it is treated as a scalar.
  1003. c : array_like
  1004. Array of coefficients ordered so that the coefficient of the term
  1005. of multi-degree i,j is contained in ``c[i,j]``. If `c` has
  1006. dimension greater than 2 the remaining indices enumerate multiple
  1007. sets of coefficients.
  1008. Returns
  1009. -------
  1010. values : ndarray, compatible object
  1011. The values of the two dimensional Chebyshev series at points formed
  1012. from pairs of corresponding values from `x` and `y`.
  1013. See Also
  1014. --------
  1015. chebval, chebgrid2d, chebval3d, chebgrid3d
  1016. Notes
  1017. -----
  1018. .. versionadded:: 1.7.0
  1019. """
  1020. try:
  1021. x, y = np.array((x, y), copy=0)
  1022. except Exception:
  1023. raise ValueError('x, y are incompatible')
  1024. c = chebval(x, c)
  1025. c = chebval(y, c, tensor=False)
  1026. return c
  1027. def chebgrid2d(x, y, c):
  1028. """
  1029. Evaluate a 2-D Chebyshev series on the Cartesian product of x and y.
  1030. This function returns the values:
  1031. .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * T_i(a) * T_j(b),
  1032. where the points `(a, b)` consist of all pairs formed by taking
  1033. `a` from `x` and `b` from `y`. The resulting points form a grid with
  1034. `x` in the first dimension and `y` in the second.
  1035. The parameters `x` and `y` are converted to arrays only if they are
  1036. tuples or a lists, otherwise they are treated as a scalars. In either
  1037. case, either `x` and `y` or their elements must support multiplication
  1038. and addition both with themselves and with the elements of `c`.
  1039. If `c` has fewer than two dimensions, ones are implicitly appended to
  1040. its shape to make it 2-D. The shape of the result will be c.shape[2:] +
  1041. x.shape + y.shape.
  1042. Parameters
  1043. ----------
  1044. x, y : array_like, compatible objects
  1045. The two dimensional series is evaluated at the points in the
  1046. Cartesian product of `x` and `y`. If `x` or `y` is a list or
  1047. tuple, it is first converted to an ndarray, otherwise it is left
  1048. unchanged and, if it isn't an ndarray, it is treated as a scalar.
  1049. c : array_like
  1050. Array of coefficients ordered so that the coefficient of the term of
  1051. multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
  1052. greater than two the remaining indices enumerate multiple sets of
  1053. coefficients.
  1054. Returns
  1055. -------
  1056. values : ndarray, compatible object
  1057. The values of the two dimensional Chebyshev series at points in the
  1058. Cartesian product of `x` and `y`.
  1059. See Also
  1060. --------
  1061. chebval, chebval2d, chebval3d, chebgrid3d
  1062. Notes
  1063. -----
  1064. .. versionadded:: 1.7.0
  1065. """
  1066. c = chebval(x, c)
  1067. c = chebval(y, c)
  1068. return c
  1069. def chebval3d(x, y, z, c):
  1070. """
  1071. Evaluate a 3-D Chebyshev series at points (x, y, z).
  1072. This function returns the values:
  1073. .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z)
  1074. The parameters `x`, `y`, and `z` are converted to arrays only if
  1075. they are tuples or a lists, otherwise they are treated as a scalars and
  1076. they must have the same shape after conversion. In either case, either
  1077. `x`, `y`, and `z` or their elements must support multiplication and
  1078. addition both with themselves and with the elements of `c`.
  1079. If `c` has fewer than 3 dimensions, ones are implicitly appended to its
  1080. shape to make it 3-D. The shape of the result will be c.shape[3:] +
  1081. x.shape.
  1082. Parameters
  1083. ----------
  1084. x, y, z : array_like, compatible object
  1085. The three dimensional series is evaluated at the points
  1086. `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
  1087. any of `x`, `y`, or `z` is a list or tuple, it is first converted
  1088. to an ndarray, otherwise it is left unchanged and if it isn't an
  1089. ndarray it is treated as a scalar.
  1090. c : array_like
  1091. Array of coefficients ordered so that the coefficient of the term of
  1092. multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
  1093. greater than 3 the remaining indices enumerate multiple sets of
  1094. coefficients.
  1095. Returns
  1096. -------
  1097. values : ndarray, compatible object
  1098. The values of the multidimensional polynomial on points formed with
  1099. triples of corresponding values from `x`, `y`, and `z`.
  1100. See Also
  1101. --------
  1102. chebval, chebval2d, chebgrid2d, chebgrid3d
  1103. Notes
  1104. -----
  1105. .. versionadded:: 1.7.0
  1106. """
  1107. try:
  1108. x, y, z = np.array((x, y, z), copy=0)
  1109. except Exception:
  1110. raise ValueError('x, y, z are incompatible')
  1111. c = chebval(x, c)
  1112. c = chebval(y, c, tensor=False)
  1113. c = chebval(z, c, tensor=False)
  1114. return c
  1115. def chebgrid3d(x, y, z, c):
  1116. """
  1117. Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.
  1118. This function returns the values:
  1119. .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)
  1120. where the points `(a, b, c)` consist of all triples formed by taking
  1121. `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
  1122. a grid with `x` in the first dimension, `y` in the second, and `z` in
  1123. the third.
  1124. The parameters `x`, `y`, and `z` are converted to arrays only if they
  1125. are tuples or a lists, otherwise they are treated as a scalars. In
  1126. either case, either `x`, `y`, and `z` or their elements must support
  1127. multiplication and addition both with themselves and with the elements
  1128. of `c`.
  1129. If `c` has fewer than three dimensions, ones are implicitly appended to
  1130. its shape to make it 3-D. The shape of the result will be c.shape[3:] +
  1131. x.shape + y.shape + z.shape.
  1132. Parameters
  1133. ----------
  1134. x, y, z : array_like, compatible objects
  1135. The three dimensional series is evaluated at the points in the
  1136. Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
  1137. list or tuple, it is first converted to an ndarray, otherwise it is
  1138. left unchanged and, if it isn't an ndarray, it is treated as a
  1139. scalar.
  1140. c : array_like
  1141. Array of coefficients ordered so that the coefficients for terms of
  1142. degree i,j are contained in ``c[i,j]``. If `c` has dimension
  1143. greater than two the remaining indices enumerate multiple sets of
  1144. coefficients.
  1145. Returns
  1146. -------
  1147. values : ndarray, compatible object
  1148. The values of the two dimensional polynomial at points in the Cartesian
  1149. product of `x` and `y`.
  1150. See Also
  1151. --------
  1152. chebval, chebval2d, chebgrid2d, chebval3d
  1153. Notes
  1154. -----
  1155. .. versionadded:: 1.7.0
  1156. """
  1157. c = chebval(x, c)
  1158. c = chebval(y, c)
  1159. c = chebval(z, c)
  1160. return c
  1161. def chebvander(x, deg):
  1162. """Pseudo-Vandermonde matrix of given degree.
  1163. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
  1164. `x`. The pseudo-Vandermonde matrix is defined by
  1165. .. math:: V[..., i] = T_i(x),
  1166. where `0 <= i <= deg`. The leading indices of `V` index the elements of
  1167. `x` and the last index is the degree of the Chebyshev polynomial.
  1168. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
  1169. matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and
  1170. ``chebval(x, c)`` are the same up to roundoff. This equivalence is
  1171. useful both for least squares fitting and for the evaluation of a large
  1172. number of Chebyshev series of the same degree and sample points.
  1173. Parameters
  1174. ----------
  1175. x : array_like
  1176. Array of points. The dtype is converted to float64 or complex128
  1177. depending on whether any of the elements are complex. If `x` is
  1178. scalar it is converted to a 1-D array.
  1179. deg : int
  1180. Degree of the resulting matrix.
  1181. Returns
  1182. -------
  1183. vander : ndarray
  1184. The pseudo Vandermonde matrix. The shape of the returned matrix is
  1185. ``x.shape + (deg + 1,)``, where The last index is the degree of the
  1186. corresponding Chebyshev polynomial. The dtype will be the same as
  1187. the converted `x`.
  1188. """
  1189. ideg = int(deg)
  1190. if ideg != deg:
  1191. raise ValueError("deg must be integer")
  1192. if ideg < 0:
  1193. raise ValueError("deg must be non-negative")
  1194. x = np.array(x, copy=0, ndmin=1) + 0.0
  1195. dims = (ideg + 1,) + x.shape
  1196. dtyp = x.dtype
  1197. v = np.empty(dims, dtype=dtyp)
  1198. # Use forward recursion to generate the entries.
  1199. v[0] = x*0 + 1
  1200. if ideg > 0:
  1201. x2 = 2*x
  1202. v[1] = x
  1203. for i in range(2, ideg + 1):
  1204. v[i] = v[i-1]*x2 - v[i-2]
  1205. return np.moveaxis(v, 0, -1)
  1206. def chebvander2d(x, y, deg):
  1207. """Pseudo-Vandermonde matrix of given degrees.
  1208. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  1209. points `(x, y)`. The pseudo-Vandermonde matrix is defined by
  1210. .. math:: V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y),
  1211. where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
  1212. `V` index the points `(x, y)` and the last index encodes the degrees of
  1213. the Chebyshev polynomials.
  1214. If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
  1215. correspond to the elements of a 2-D coefficient array `c` of shape
  1216. (xdeg + 1, ydeg + 1) in the order
  1217. .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
  1218. and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same
  1219. up to roundoff. This equivalence is useful both for least squares
  1220. fitting and for the evaluation of a large number of 2-D Chebyshev
  1221. series of the same degrees and sample points.
  1222. Parameters
  1223. ----------
  1224. x, y : array_like
  1225. Arrays of point coordinates, all of the same shape. The dtypes
  1226. will be converted to either float64 or complex128 depending on
  1227. whether any of the elements are complex. Scalars are converted to
  1228. 1-D arrays.
  1229. deg : list of ints
  1230. List of maximum degrees of the form [x_deg, y_deg].
  1231. Returns
  1232. -------
  1233. vander2d : ndarray
  1234. The shape of the returned matrix is ``x.shape + (order,)``, where
  1235. :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
  1236. as the converted `x` and `y`.
  1237. See Also
  1238. --------
  1239. chebvander, chebvander3d. chebval2d, chebval3d
  1240. Notes
  1241. -----
  1242. .. versionadded:: 1.7.0
  1243. """
  1244. ideg = [int(d) for d in deg]
  1245. is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
  1246. if is_valid != [1, 1]:
  1247. raise ValueError("degrees must be non-negative integers")
  1248. degx, degy = ideg
  1249. x, y = np.array((x, y), copy=0) + 0.0
  1250. vx = chebvander(x, degx)
  1251. vy = chebvander(y, degy)
  1252. v = vx[..., None]*vy[..., None,:]
  1253. return v.reshape(v.shape[:-2] + (-1,))
  1254. def chebvander3d(x, y, z, deg):
  1255. """Pseudo-Vandermonde matrix of given degrees.
  1256. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  1257. points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
  1258. then The pseudo-Vandermonde matrix is defined by
  1259. .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z),
  1260. where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
  1261. indices of `V` index the points `(x, y, z)` and the last index encodes
  1262. the degrees of the Chebyshev polynomials.
  1263. If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
  1264. of `V` correspond to the elements of a 3-D coefficient array `c` of
  1265. shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
  1266. .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
  1267. and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the
  1268. same up to roundoff. This equivalence is useful both for least squares
  1269. fitting and for the evaluation of a large number of 3-D Chebyshev
  1270. series of the same degrees and sample points.
  1271. Parameters
  1272. ----------
  1273. x, y, z : array_like
  1274. Arrays of point coordinates, all of the same shape. The dtypes will
  1275. be converted to either float64 or complex128 depending on whether
  1276. any of the elements are complex. Scalars are converted to 1-D
  1277. arrays.
  1278. deg : list of ints
  1279. List of maximum degrees of the form [x_deg, y_deg, z_deg].
  1280. Returns
  1281. -------
  1282. vander3d : ndarray
  1283. The shape of the returned matrix is ``x.shape + (order,)``, where
  1284. :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will
  1285. be the same as the converted `x`, `y`, and `z`.
  1286. See Also
  1287. --------
  1288. chebvander, chebvander3d. chebval2d, chebval3d
  1289. Notes
  1290. -----
  1291. .. versionadded:: 1.7.0
  1292. """
  1293. ideg = [int(d) for d in deg]
  1294. is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
  1295. if is_valid != [1, 1, 1]:
  1296. raise ValueError("degrees must be non-negative integers")
  1297. degx, degy, degz = ideg
  1298. x, y, z = np.array((x, y, z), copy=0) + 0.0
  1299. vx = chebvander(x, degx)
  1300. vy = chebvander(y, degy)
  1301. vz = chebvander(z, degz)
  1302. v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:]
  1303. return v.reshape(v.shape[:-3] + (-1,))
  1304. def chebfit(x, y, deg, rcond=None, full=False, w=None):
  1305. """
  1306. Least squares fit of Chebyshev series to data.
  1307. Return the coefficients of a Chebyshev series of degree `deg` that is the
  1308. least squares fit to the data values `y` given at points `x`. If `y` is
  1309. 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
  1310. fits are done, one for each column of `y`, and the resulting
  1311. coefficients are stored in the corresponding columns of a 2-D return.
  1312. The fitted polynomial(s) are in the form
  1313. .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x),
  1314. where `n` is `deg`.
  1315. Parameters
  1316. ----------
  1317. x : array_like, shape (M,)
  1318. x-coordinates of the M sample points ``(x[i], y[i])``.
  1319. y : array_like, shape (M,) or (M, K)
  1320. y-coordinates of the sample points. Several data sets of sample
  1321. points sharing the same x-coordinates can be fitted at once by
  1322. passing in a 2D-array that contains one dataset per column.
  1323. deg : int or 1-D array_like
  1324. Degree(s) of the fitting polynomials. If `deg` is a single integer,
  1325. all terms up to and including the `deg`'th term are included in the
  1326. fit. For NumPy versions >= 1.11.0 a list of integers specifying the
  1327. degrees of the terms to include may be used instead.
  1328. rcond : float, optional
  1329. Relative condition number of the fit. Singular values smaller than
  1330. this relative to the largest singular value will be ignored. The
  1331. default value is len(x)*eps, where eps is the relative precision of
  1332. the float type, about 2e-16 in most cases.
  1333. full : bool, optional
  1334. Switch determining nature of return value. When it is False (the
  1335. default) just the coefficients are returned, when True diagnostic
  1336. information from the singular value decomposition is also returned.
  1337. w : array_like, shape (`M`,), optional
  1338. Weights. If not None, the contribution of each point
  1339. ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
  1340. weights are chosen so that the errors of the products ``w[i]*y[i]``
  1341. all have the same variance. The default value is None.
  1342. .. versionadded:: 1.5.0
  1343. Returns
  1344. -------
  1345. coef : ndarray, shape (M,) or (M, K)
  1346. Chebyshev coefficients ordered from low to high. If `y` was 2-D,
  1347. the coefficients for the data in column k of `y` are in column
  1348. `k`.
  1349. [residuals, rank, singular_values, rcond] : list
  1350. These values are only returned if `full` = True
  1351. resid -- sum of squared residuals of the least squares fit
  1352. rank -- the numerical rank of the scaled Vandermonde matrix
  1353. sv -- singular values of the scaled Vandermonde matrix
  1354. rcond -- value of `rcond`.
  1355. For more details, see `linalg.lstsq`.
  1356. Warns
  1357. -----
  1358. RankWarning
  1359. The rank of the coefficient matrix in the least-squares fit is
  1360. deficient. The warning is only raised if `full` = False. The
  1361. warnings can be turned off by
  1362. >>> import warnings
  1363. >>> warnings.simplefilter('ignore', RankWarning)
  1364. See Also
  1365. --------
  1366. polyfit, legfit, lagfit, hermfit, hermefit
  1367. chebval : Evaluates a Chebyshev series.
  1368. chebvander : Vandermonde matrix of Chebyshev series.
  1369. chebweight : Chebyshev weight function.
  1370. linalg.lstsq : Computes a least-squares fit from the matrix.
  1371. scipy.interpolate.UnivariateSpline : Computes spline fits.
  1372. Notes
  1373. -----
  1374. The solution is the coefficients of the Chebyshev series `p` that
  1375. minimizes the sum of the weighted squared errors
  1376. .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
  1377. where :math:`w_j` are the weights. This problem is solved by setting up
  1378. as the (typically) overdetermined matrix equation
  1379. .. math:: V(x) * c = w * y,
  1380. where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
  1381. coefficients to be solved for, `w` are the weights, and `y` are the
  1382. observed values. This equation is then solved using the singular value
  1383. decomposition of `V`.
  1384. If some of the singular values of `V` are so small that they are
  1385. neglected, then a `RankWarning` will be issued. This means that the
  1386. coefficient values may be poorly determined. Using a lower order fit
  1387. will usually get rid of the warning. The `rcond` parameter can also be
  1388. set to a value smaller than its default, but the resulting fit may be
  1389. spurious and have large contributions from roundoff error.
  1390. Fits using Chebyshev series are usually better conditioned than fits
  1391. using power series, but much can depend on the distribution of the
  1392. sample points and the smoothness of the data. If the quality of the fit
  1393. is inadequate splines may be a good alternative.
  1394. References
  1395. ----------
  1396. .. [1] Wikipedia, "Curve fitting",
  1397. https://en.wikipedia.org/wiki/Curve_fitting
  1398. Examples
  1399. --------
  1400. """
  1401. x = np.asarray(x) + 0.0
  1402. y = np.asarray(y) + 0.0
  1403. deg = np.asarray(deg)
  1404. # check arguments.
  1405. if deg.ndim > 1 or deg.dtype.kind not in 'iu' or deg.size == 0:
  1406. raise TypeError("deg must be an int or non-empty 1-D array of int")
  1407. if deg.min() < 0:
  1408. raise ValueError("expected deg >= 0")
  1409. if x.ndim != 1:
  1410. raise TypeError("expected 1D vector for x")
  1411. if x.size == 0:
  1412. raise TypeError("expected non-empty vector for x")
  1413. if y.ndim < 1 or y.ndim > 2:
  1414. raise TypeError("expected 1D or 2D array for y")
  1415. if len(x) != len(y):
  1416. raise TypeError("expected x and y to have same length")
  1417. if deg.ndim == 0:
  1418. lmax = deg
  1419. order = lmax + 1
  1420. van = chebvander(x, lmax)
  1421. else:
  1422. deg = np.sort(deg)
  1423. lmax = deg[-1]
  1424. order = len(deg)
  1425. van = chebvander(x, lmax)[:, deg]
  1426. # set up the least squares matrices in transposed form
  1427. lhs = van.T
  1428. rhs = y.T
  1429. if w is not None:
  1430. w = np.asarray(w) + 0.0
  1431. if w.ndim != 1:
  1432. raise TypeError("expected 1D vector for w")
  1433. if len(x) != len(w):
  1434. raise TypeError("expected x and w to have same length")
  1435. # apply weights. Don't use inplace operations as they
  1436. # can cause problems with NA.
  1437. lhs = lhs * w
  1438. rhs = rhs * w
  1439. # set rcond
  1440. if rcond is None:
  1441. rcond = len(x)*np.finfo(x.dtype).eps
  1442. # Determine the norms of the design matrix columns.
  1443. if issubclass(lhs.dtype.type, np.complexfloating):
  1444. scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
  1445. else:
  1446. scl = np.sqrt(np.square(lhs).sum(1))
  1447. scl[scl == 0] = 1
  1448. # Solve the least squares problem.
  1449. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond)
  1450. c = (c.T/scl).T
  1451. # Expand c to include non-fitted coefficients which are set to zero
  1452. if deg.ndim > 0:
  1453. if c.ndim == 2:
  1454. cc = np.zeros((lmax + 1, c.shape[1]), dtype=c.dtype)
  1455. else:
  1456. cc = np.zeros(lmax + 1, dtype=c.dtype)
  1457. cc[deg] = c
  1458. c = cc
  1459. # warn on rank reduction
  1460. if rank != order and not full:
  1461. msg = "The fit may be poorly conditioned"
  1462. warnings.warn(msg, pu.RankWarning, stacklevel=2)
  1463. if full:
  1464. return c, [resids, rank, s, rcond]
  1465. else:
  1466. return c
  1467. def chebcompanion(c):
  1468. """Return the scaled companion matrix of c.
  1469. The basis polynomials are scaled so that the companion matrix is
  1470. symmetric when `c` is a Chebyshev basis polynomial. This provides
  1471. better eigenvalue estimates than the unscaled case and for basis
  1472. polynomials the eigenvalues are guaranteed to be real if
  1473. `numpy.linalg.eigvalsh` is used to obtain them.
  1474. Parameters
  1475. ----------
  1476. c : array_like
  1477. 1-D array of Chebyshev series coefficients ordered from low to high
  1478. degree.
  1479. Returns
  1480. -------
  1481. mat : ndarray
  1482. Scaled companion matrix of dimensions (deg, deg).
  1483. Notes
  1484. -----
  1485. .. versionadded:: 1.7.0
  1486. """
  1487. # c is a trimmed copy
  1488. [c] = pu.as_series([c])
  1489. if len(c) < 2:
  1490. raise ValueError('Series must have maximum degree of at least 1.')
  1491. if len(c) == 2:
  1492. return np.array([[-c[0]/c[1]]])
  1493. n = len(c) - 1
  1494. mat = np.zeros((n, n), dtype=c.dtype)
  1495. scl = np.array([1.] + [np.sqrt(.5)]*(n-1))
  1496. top = mat.reshape(-1)[1::n+1]
  1497. bot = mat.reshape(-1)[n::n+1]
  1498. top[0] = np.sqrt(.5)
  1499. top[1:] = 1/2
  1500. bot[...] = top
  1501. mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5
  1502. return mat
  1503. def chebroots(c):
  1504. """
  1505. Compute the roots of a Chebyshev series.
  1506. Return the roots (a.k.a. "zeros") of the polynomial
  1507. .. math:: p(x) = \\sum_i c[i] * T_i(x).
  1508. Parameters
  1509. ----------
  1510. c : 1-D array_like
  1511. 1-D array of coefficients.
  1512. Returns
  1513. -------
  1514. out : ndarray
  1515. Array of the roots of the series. If all the roots are real,
  1516. then `out` is also real, otherwise it is complex.
  1517. See Also
  1518. --------
  1519. polyroots, legroots, lagroots, hermroots, hermeroots
  1520. Notes
  1521. -----
  1522. The root estimates are obtained as the eigenvalues of the companion
  1523. matrix, Roots far from the origin of the complex plane may have large
  1524. errors due to the numerical instability of the series for such
  1525. values. Roots with multiplicity greater than 1 will also show larger
  1526. errors as the value of the series near such points is relatively
  1527. insensitive to errors in the roots. Isolated roots near the origin can
  1528. be improved by a few iterations of Newton's method.
  1529. The Chebyshev series basis polynomials aren't powers of `x` so the
  1530. results of this function may seem unintuitive.
  1531. Examples
  1532. --------
  1533. >>> import numpy.polynomial.chebyshev as cheb
  1534. >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots
  1535. array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00])
  1536. """
  1537. # c is a trimmed copy
  1538. [c] = pu.as_series([c])
  1539. if len(c) < 2:
  1540. return np.array([], dtype=c.dtype)
  1541. if len(c) == 2:
  1542. return np.array([-c[0]/c[1]])
  1543. m = chebcompanion(c)
  1544. r = la.eigvals(m)
  1545. r.sort()
  1546. return r
  1547. def chebinterpolate(func, deg, args=()):
  1548. """Interpolate a function at the Chebyshev points of the first kind.
  1549. Returns the Chebyshev series that interpolates `func` at the Chebyshev
  1550. points of the first kind in the interval [-1, 1]. The interpolating
  1551. series tends to a minmax approximation to `func` with increasing `deg`
  1552. if the function is continuous in the interval.
  1553. .. versionadded:: 1.14.0
  1554. Parameters
  1555. ----------
  1556. func : function
  1557. The function to be approximated. It must be a function of a single
  1558. variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
  1559. extra arguments passed in the `args` parameter.
  1560. deg : int
  1561. Degree of the interpolating polynomial
  1562. args : tuple, optional
  1563. Extra arguments to be used in the function call. Default is no extra
  1564. arguments.
  1565. Returns
  1566. -------
  1567. coef : ndarray, shape (deg + 1,)
  1568. Chebyshev coefficients of the interpolating series ordered from low to
  1569. high.
  1570. Examples
  1571. --------
  1572. >>> import numpy.polynomial.chebyshev as C
  1573. >>> C.chebfromfunction(lambda x: np.tanh(x) + 0.5, 8)
  1574. array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17,
  1575. -5.42457905e-02, -2.71387850e-16, 4.51658839e-03,
  1576. 2.46716228e-17, -3.79694221e-04, -3.26899002e-16])
  1577. Notes
  1578. -----
  1579. The Chebyshev polynomials used in the interpolation are orthogonal when
  1580. sampled at the Chebyshev points of the first kind. If it is desired to
  1581. constrain some of the coefficients they can simply be set to the desired
  1582. value after the interpolation, no new interpolation or fit is needed. This
  1583. is especially useful if it is known apriori that some of coefficients are
  1584. zero. For instance, if the function is even then the coefficients of the
  1585. terms of odd degree in the result can be set to zero.
  1586. """
  1587. deg = np.asarray(deg)
  1588. # check arguments.
  1589. if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0:
  1590. raise TypeError("deg must be an int")
  1591. if deg < 0:
  1592. raise ValueError("expected deg >= 0")
  1593. order = deg + 1
  1594. xcheb = chebpts1(order)
  1595. yfunc = func(xcheb, *args)
  1596. m = chebvander(xcheb, deg)
  1597. c = np.dot(m.T, yfunc)
  1598. c[0] /= order
  1599. c[1:] /= 0.5*order
  1600. return c
  1601. def chebgauss(deg):
  1602. """
  1603. Gauss-Chebyshev quadrature.
  1604. Computes the sample points and weights for Gauss-Chebyshev quadrature.
  1605. These sample points and weights will correctly integrate polynomials of
  1606. degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
  1607. the weight function :math:`f(x) = 1/\\sqrt{1 - x^2}`.
  1608. Parameters
  1609. ----------
  1610. deg : int
  1611. Number of sample points and weights. It must be >= 1.
  1612. Returns
  1613. -------
  1614. x : ndarray
  1615. 1-D ndarray containing the sample points.
  1616. y : ndarray
  1617. 1-D ndarray containing the weights.
  1618. Notes
  1619. -----
  1620. .. versionadded:: 1.7.0
  1621. The results have only been tested up to degree 100, higher degrees may
  1622. be problematic. For Gauss-Chebyshev there are closed form solutions for
  1623. the sample points and weights. If n = `deg`, then
  1624. .. math:: x_i = \\cos(\\pi (2 i - 1) / (2 n))
  1625. .. math:: w_i = \\pi / n
  1626. """
  1627. ideg = int(deg)
  1628. if ideg != deg or ideg < 1:
  1629. raise ValueError("deg must be a non-negative integer")
  1630. x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg))
  1631. w = np.ones(ideg)*(np.pi/ideg)
  1632. return x, w
  1633. def chebweight(x):
  1634. """
  1635. The weight function of the Chebyshev polynomials.
  1636. The weight function is :math:`1/\\sqrt{1 - x^2}` and the interval of
  1637. integration is :math:`[-1, 1]`. The Chebyshev polynomials are
  1638. orthogonal, but not normalized, with respect to this weight function.
  1639. Parameters
  1640. ----------
  1641. x : array_like
  1642. Values at which the weight function will be computed.
  1643. Returns
  1644. -------
  1645. w : ndarray
  1646. The weight function at `x`.
  1647. Notes
  1648. -----
  1649. .. versionadded:: 1.7.0
  1650. """
  1651. w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x))
  1652. return w
  1653. def chebpts1(npts):
  1654. """
  1655. Chebyshev points of the first kind.
  1656. The Chebyshev points of the first kind are the points ``cos(x)``,
  1657. where ``x = [pi*(k + .5)/npts for k in range(npts)]``.
  1658. Parameters
  1659. ----------
  1660. npts : int
  1661. Number of sample points desired.
  1662. Returns
  1663. -------
  1664. pts : ndarray
  1665. The Chebyshev points of the first kind.
  1666. See Also
  1667. --------
  1668. chebpts2
  1669. Notes
  1670. -----
  1671. .. versionadded:: 1.5.0
  1672. """
  1673. _npts = int(npts)
  1674. if _npts != npts:
  1675. raise ValueError("npts must be integer")
  1676. if _npts < 1:
  1677. raise ValueError("npts must be >= 1")
  1678. x = np.linspace(-np.pi, 0, _npts, endpoint=False) + np.pi/(2*_npts)
  1679. return np.cos(x)
  1680. def chebpts2(npts):
  1681. """
  1682. Chebyshev points of the second kind.
  1683. The Chebyshev points of the second kind are the points ``cos(x)``,
  1684. where ``x = [pi*k/(npts - 1) for k in range(npts)]``.
  1685. Parameters
  1686. ----------
  1687. npts : int
  1688. Number of sample points desired.
  1689. Returns
  1690. -------
  1691. pts : ndarray
  1692. The Chebyshev points of the second kind.
  1693. Notes
  1694. -----
  1695. .. versionadded:: 1.5.0
  1696. """
  1697. _npts = int(npts)
  1698. if _npts != npts:
  1699. raise ValueError("npts must be integer")
  1700. if _npts < 2:
  1701. raise ValueError("npts must be >= 2")
  1702. x = np.linspace(-np.pi, 0, _npts)
  1703. return np.cos(x)
  1704. #
  1705. # Chebyshev series class
  1706. #
  1707. class Chebyshev(ABCPolyBase):
  1708. """A Chebyshev series class.
  1709. The Chebyshev class provides the standard Python numerical methods
  1710. '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
  1711. methods listed below.
  1712. Parameters
  1713. ----------
  1714. coef : array_like
  1715. Chebyshev coefficients in order of increasing degree, i.e.,
  1716. ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``.
  1717. domain : (2,) array_like, optional
  1718. Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
  1719. to the interval ``[window[0], window[1]]`` by shifting and scaling.
  1720. The default value is [-1, 1].
  1721. window : (2,) array_like, optional
  1722. Window, see `domain` for its use. The default value is [-1, 1].
  1723. .. versionadded:: 1.6.0
  1724. """
  1725. # Virtual Functions
  1726. _add = staticmethod(chebadd)
  1727. _sub = staticmethod(chebsub)
  1728. _mul = staticmethod(chebmul)
  1729. _div = staticmethod(chebdiv)
  1730. _pow = staticmethod(chebpow)
  1731. _val = staticmethod(chebval)
  1732. _int = staticmethod(chebint)
  1733. _der = staticmethod(chebder)
  1734. _fit = staticmethod(chebfit)
  1735. _line = staticmethod(chebline)
  1736. _roots = staticmethod(chebroots)
  1737. _fromroots = staticmethod(chebfromroots)
  1738. @classmethod
  1739. def interpolate(cls, func, deg, domain=None, args=()):
  1740. """Interpolate a function at the Chebyshev points of the first kind.
  1741. Returns the series that interpolates `func` at the Chebyshev points of
  1742. the first kind scaled and shifted to the `domain`. The resulting series
  1743. tends to a minmax approximation of `func` when the function is
  1744. continuous in the domain.
  1745. .. versionadded:: 1.14.0
  1746. Parameters
  1747. ----------
  1748. func : function
  1749. The function to be interpolated. It must be a function of a single
  1750. variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
  1751. extra arguments passed in the `args` parameter.
  1752. deg : int
  1753. Degree of the interpolating polynomial.
  1754. domain : {None, [beg, end]}, optional
  1755. Domain over which `func` is interpolated. The default is None, in
  1756. which case the domain is [-1, 1].
  1757. args : tuple, optional
  1758. Extra arguments to be used in the function call. Default is no
  1759. extra arguments.
  1760. Returns
  1761. -------
  1762. polynomial : Chebyshev instance
  1763. Interpolating Chebyshev instance.
  1764. Notes
  1765. -----
  1766. See `numpy.polynomial.chebfromfunction` for more details.
  1767. """
  1768. if domain is None:
  1769. domain = cls.domain
  1770. xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args)
  1771. coef = chebinterpolate(xfunc, deg)
  1772. return cls(coef, domain=domain)
  1773. # Virtual properties
  1774. nickname = 'cheb'
  1775. domain = np.array(chebdomain)
  1776. window = np.array(chebdomain)
  1777. basis_name = 'T'