chebyshev.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048
  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. lc1 = len(z1)
  181. lc2 = len(z2)
  182. if lc2 == 1:
  183. z1 /= z2
  184. return z1, z1[:1]*0
  185. elif lc1 < lc2:
  186. return z1[:1]*0, z1
  187. else:
  188. dlen = lc1 - lc2
  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+lc2] -= tmp
  200. z1[j:j+lc2] -= tmp
  201. i += 1
  202. j -= 1
  203. r = z1[i]
  204. quo[i] = r
  205. tmp = r*z2
  206. z1[i:i+lc2] -= tmp
  207. quo /= scl
  208. rem = z1[i+1:i-1+lc2].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.], domain=[-1, 1], window=[-1, 1])
  337. >>> p = c.convert(kind=P.Polynomial)
  338. >>> p
  339. Polynomial([-2., -8., 4., 12.], domain=[-1., 1.], window=[-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, hermefromroots
  424. Examples
  425. --------
  426. >>> import numpy.polynomial.chebyshev as C
  427. >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis
  428. array([ 0. , -0.25, 0. , 0.25])
  429. >>> j = complex(0,1)
  430. >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis
  431. array([1.5+0.j, 0. +0.j, 0.5+0.j])
  432. """
  433. return pu._fromroots(chebline, chebmul, roots)
  434. def chebadd(c1, c2):
  435. """
  436. Add one Chebyshev series to another.
  437. Returns the sum of two Chebyshev series `c1` + `c2`. The arguments
  438. are sequences of coefficients ordered from lowest order term to
  439. highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  440. Parameters
  441. ----------
  442. c1, c2 : array_like
  443. 1-D arrays of Chebyshev series coefficients ordered from low to
  444. high.
  445. Returns
  446. -------
  447. out : ndarray
  448. Array representing the Chebyshev series of their sum.
  449. See Also
  450. --------
  451. chebsub, chebmulx, chebmul, chebdiv, chebpow
  452. Notes
  453. -----
  454. Unlike multiplication, division, etc., the sum of two Chebyshev series
  455. is a Chebyshev series (without having to "reproject" the result onto
  456. the basis set) so addition, just like that of "standard" polynomials,
  457. is simply "component-wise."
  458. Examples
  459. --------
  460. >>> from numpy.polynomial import chebyshev as C
  461. >>> c1 = (1,2,3)
  462. >>> c2 = (3,2,1)
  463. >>> C.chebadd(c1,c2)
  464. array([4., 4., 4.])
  465. """
  466. return pu._add(c1, c2)
  467. def chebsub(c1, c2):
  468. """
  469. Subtract one Chebyshev series from another.
  470. Returns the difference of two Chebyshev series `c1` - `c2`. The
  471. sequences of coefficients are from lowest order term to highest, i.e.,
  472. [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  473. Parameters
  474. ----------
  475. c1, c2 : array_like
  476. 1-D arrays of Chebyshev series coefficients ordered from low to
  477. high.
  478. Returns
  479. -------
  480. out : ndarray
  481. Of Chebyshev series coefficients representing their difference.
  482. See Also
  483. --------
  484. chebadd, chebmulx, chebmul, chebdiv, chebpow
  485. Notes
  486. -----
  487. Unlike multiplication, division, etc., the difference of two Chebyshev
  488. series is a Chebyshev series (without having to "reproject" the result
  489. onto the basis set) so subtraction, just like that of "standard"
  490. polynomials, is simply "component-wise."
  491. Examples
  492. --------
  493. >>> from numpy.polynomial import chebyshev as C
  494. >>> c1 = (1,2,3)
  495. >>> c2 = (3,2,1)
  496. >>> C.chebsub(c1,c2)
  497. array([-2., 0., 2.])
  498. >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2)
  499. array([ 2., 0., -2.])
  500. """
  501. return pu._sub(c1, c2)
  502. def chebmulx(c):
  503. """Multiply a Chebyshev series by x.
  504. Multiply the polynomial `c` by x, where x is the independent
  505. variable.
  506. Parameters
  507. ----------
  508. c : array_like
  509. 1-D array of Chebyshev series coefficients ordered from low to
  510. high.
  511. Returns
  512. -------
  513. out : ndarray
  514. Array representing the result of the multiplication.
  515. Notes
  516. -----
  517. .. versionadded:: 1.5.0
  518. Examples
  519. --------
  520. >>> from numpy.polynomial import chebyshev as C
  521. >>> C.chebmulx([1,2,3])
  522. array([1. , 2.5, 1. , 1.5])
  523. """
  524. # c is a trimmed copy
  525. [c] = pu.as_series([c])
  526. # The zero series needs special treatment
  527. if len(c) == 1 and c[0] == 0:
  528. return c
  529. prd = np.empty(len(c) + 1, dtype=c.dtype)
  530. prd[0] = c[0]*0
  531. prd[1] = c[0]
  532. if len(c) > 1:
  533. tmp = c[1:]/2
  534. prd[2:] = tmp
  535. prd[0:-2] += tmp
  536. return prd
  537. def chebmul(c1, c2):
  538. """
  539. Multiply one Chebyshev series by another.
  540. Returns the product of two Chebyshev series `c1` * `c2`. The arguments
  541. are sequences of coefficients, from lowest order "term" to highest,
  542. e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  543. Parameters
  544. ----------
  545. c1, c2 : array_like
  546. 1-D arrays of Chebyshev series coefficients ordered from low to
  547. high.
  548. Returns
  549. -------
  550. out : ndarray
  551. Of Chebyshev series coefficients representing their product.
  552. See Also
  553. --------
  554. chebadd, chebsub, chebmulx, chebdiv, chebpow
  555. Notes
  556. -----
  557. In general, the (polynomial) product of two C-series results in terms
  558. that are not in the Chebyshev polynomial basis set. Thus, to express
  559. the product as a C-series, it is typically necessary to "reproject"
  560. the product onto said basis set, which typically produces
  561. "unintuitive live" (but correct) results; see Examples section below.
  562. Examples
  563. --------
  564. >>> from numpy.polynomial import chebyshev as C
  565. >>> c1 = (1,2,3)
  566. >>> c2 = (3,2,1)
  567. >>> C.chebmul(c1,c2) # multiplication requires "reprojection"
  568. array([ 6.5, 12. , 12. , 4. , 1.5])
  569. """
  570. # c1, c2 are trimmed copies
  571. [c1, c2] = pu.as_series([c1, c2])
  572. z1 = _cseries_to_zseries(c1)
  573. z2 = _cseries_to_zseries(c2)
  574. prd = _zseries_mul(z1, z2)
  575. ret = _zseries_to_cseries(prd)
  576. return pu.trimseq(ret)
  577. def chebdiv(c1, c2):
  578. """
  579. Divide one Chebyshev series by another.
  580. Returns the quotient-with-remainder of two Chebyshev series
  581. `c1` / `c2`. The arguments are sequences of coefficients from lowest
  582. order "term" to highest, e.g., [1,2,3] represents the series
  583. ``T_0 + 2*T_1 + 3*T_2``.
  584. Parameters
  585. ----------
  586. c1, c2 : array_like
  587. 1-D arrays of Chebyshev series coefficients ordered from low to
  588. high.
  589. Returns
  590. -------
  591. [quo, rem] : ndarrays
  592. Of Chebyshev series coefficients representing the quotient and
  593. remainder.
  594. See Also
  595. --------
  596. chebadd, chebsub, chemulx, chebmul, chebpow
  597. Notes
  598. -----
  599. In general, the (polynomial) division of one C-series by another
  600. results in quotient and remainder terms that are not in the Chebyshev
  601. polynomial basis set. Thus, to express these results as C-series, it
  602. is typically necessary to "reproject" the results onto said basis
  603. set, which typically produces "unintuitive" (but correct) results;
  604. see Examples section below.
  605. Examples
  606. --------
  607. >>> from numpy.polynomial import chebyshev as C
  608. >>> c1 = (1,2,3)
  609. >>> c2 = (3,2,1)
  610. >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not
  611. (array([3.]), array([-8., -4.]))
  612. >>> c2 = (0,1,2,3)
  613. >>> C.chebdiv(c2,c1) # neither "intuitive"
  614. (array([0., 2.]), array([-2., -4.]))
  615. """
  616. # c1, c2 are trimmed copies
  617. [c1, c2] = pu.as_series([c1, c2])
  618. if c2[-1] == 0:
  619. raise ZeroDivisionError()
  620. # note: this is more efficient than `pu._div(chebmul, c1, c2)`
  621. lc1 = len(c1)
  622. lc2 = len(c2)
  623. if lc1 < lc2:
  624. return c1[:1]*0, c1
  625. elif lc2 == 1:
  626. return c1/c2[-1], c1[:1]*0
  627. else:
  628. z1 = _cseries_to_zseries(c1)
  629. z2 = _cseries_to_zseries(c2)
  630. quo, rem = _zseries_div(z1, z2)
  631. quo = pu.trimseq(_zseries_to_cseries(quo))
  632. rem = pu.trimseq(_zseries_to_cseries(rem))
  633. return quo, rem
  634. def chebpow(c, pow, maxpower=16):
  635. """Raise a Chebyshev series to a power.
  636. Returns the Chebyshev series `c` raised to the power `pow`. The
  637. argument `c` is a sequence of coefficients ordered from low to high.
  638. i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.``
  639. Parameters
  640. ----------
  641. c : array_like
  642. 1-D array of Chebyshev series coefficients ordered from low to
  643. high.
  644. pow : integer
  645. Power to which the series will be raised
  646. maxpower : integer, optional
  647. Maximum power allowed. This is mainly to limit growth of the series
  648. to unmanageable size. Default is 16
  649. Returns
  650. -------
  651. coef : ndarray
  652. Chebyshev series of power.
  653. See Also
  654. --------
  655. chebadd, chebsub, chebmulx, chebmul, chebdiv
  656. Examples
  657. --------
  658. >>> from numpy.polynomial import chebyshev as C
  659. >>> C.chebpow([1, 2, 3, 4], 2)
  660. array([15.5, 22. , 16. , ..., 12.5, 12. , 8. ])
  661. """
  662. # note: this is more efficient than `pu._pow(chebmul, c1, c2)`, as it
  663. # avoids converting between z and c series repeatedly
  664. # c is a trimmed copy
  665. [c] = pu.as_series([c])
  666. power = int(pow)
  667. if power != pow or power < 0:
  668. raise ValueError("Power must be a non-negative integer.")
  669. elif maxpower is not None and power > maxpower:
  670. raise ValueError("Power is too large")
  671. elif power == 0:
  672. return np.array([1], dtype=c.dtype)
  673. elif power == 1:
  674. return c
  675. else:
  676. # This can be made more efficient by using powers of two
  677. # in the usual way.
  678. zs = _cseries_to_zseries(c)
  679. prd = zs
  680. for i in range(2, power + 1):
  681. prd = np.convolve(prd, zs)
  682. return _zseries_to_cseries(prd)
  683. def chebder(c, m=1, scl=1, axis=0):
  684. """
  685. Differentiate a Chebyshev series.
  686. Returns the Chebyshev series coefficients `c` differentiated `m` times
  687. along `axis`. At each iteration the result is multiplied by `scl` (the
  688. scaling factor is for use in a linear change of variable). The argument
  689. `c` is an array of coefficients from low to high degree along each
  690. axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2``
  691. while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) +
  692. 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is
  693. ``y``.
  694. Parameters
  695. ----------
  696. c : array_like
  697. Array of Chebyshev series coefficients. If c is multidimensional
  698. the different axis correspond to different variables with the
  699. degree in each axis given by the corresponding index.
  700. m : int, optional
  701. Number of derivatives taken, must be non-negative. (Default: 1)
  702. scl : scalar, optional
  703. Each differentiation is multiplied by `scl`. The end result is
  704. multiplication by ``scl**m``. This is for use in a linear change of
  705. variable. (Default: 1)
  706. axis : int, optional
  707. Axis over which the derivative is taken. (Default: 0).
  708. .. versionadded:: 1.7.0
  709. Returns
  710. -------
  711. der : ndarray
  712. Chebyshev series of the derivative.
  713. See Also
  714. --------
  715. chebint
  716. Notes
  717. -----
  718. In general, the result of differentiating a C-series needs to be
  719. "reprojected" onto the C-series basis set. Thus, typically, the
  720. result of this function is "unintuitive," albeit correct; see Examples
  721. section below.
  722. Examples
  723. --------
  724. >>> from numpy.polynomial import chebyshev as C
  725. >>> c = (1,2,3,4)
  726. >>> C.chebder(c)
  727. array([14., 12., 24.])
  728. >>> C.chebder(c,3)
  729. array([96.])
  730. >>> C.chebder(c,scl=-1)
  731. array([-14., -12., -24.])
  732. >>> C.chebder(c,2,-1)
  733. array([12., 96.])
  734. """
  735. c = np.array(c, ndmin=1, copy=True)
  736. if c.dtype.char in '?bBhHiIlLqQpP':
  737. c = c.astype(np.double)
  738. cnt = pu._deprecate_as_int(m, "the order of derivation")
  739. iaxis = pu._deprecate_as_int(axis, "the axis")
  740. if cnt < 0:
  741. raise ValueError("The order of derivation must be non-negative")
  742. iaxis = normalize_axis_index(iaxis, c.ndim)
  743. if cnt == 0:
  744. return c
  745. c = np.moveaxis(c, iaxis, 0)
  746. n = len(c)
  747. if cnt >= n:
  748. c = c[:1]*0
  749. else:
  750. for i in range(cnt):
  751. n = n - 1
  752. c *= scl
  753. der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
  754. for j in range(n, 2, -1):
  755. der[j - 1] = (2*j)*c[j]
  756. c[j - 2] += (j*c[j])/(j - 2)
  757. if n > 1:
  758. der[1] = 4*c[2]
  759. der[0] = c[1]
  760. c = der
  761. c = np.moveaxis(c, 0, iaxis)
  762. return c
  763. def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
  764. """
  765. Integrate a Chebyshev series.
  766. Returns the Chebyshev series coefficients `c` integrated `m` times from
  767. `lbnd` along `axis`. At each iteration the resulting series is
  768. **multiplied** by `scl` and an integration constant, `k`, is added.
  769. The scaling factor is for use in a linear change of variable. ("Buyer
  770. beware": note that, depending on what one is doing, one may want `scl`
  771. to be the reciprocal of what one might expect; for more information,
  772. see the Notes section below.) The argument `c` is an array of
  773. coefficients from low to high degree along each axis, e.g., [1,2,3]
  774. represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]]
  775. represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) +
  776. 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
  777. Parameters
  778. ----------
  779. c : array_like
  780. Array of Chebyshev series coefficients. If c is multidimensional
  781. the different axis correspond to different variables with the
  782. degree in each axis given by the corresponding index.
  783. m : int, optional
  784. Order of integration, must be positive. (Default: 1)
  785. k : {[], list, scalar}, optional
  786. Integration constant(s). The value of the first integral at zero
  787. is the first value in the list, the value of the second integral
  788. at zero is the second value, etc. If ``k == []`` (the default),
  789. all constants are set to zero. If ``m == 1``, a single scalar can
  790. be given instead of a list.
  791. lbnd : scalar, optional
  792. The lower bound of the integral. (Default: 0)
  793. scl : scalar, optional
  794. Following each integration the result is *multiplied* by `scl`
  795. before the integration constant is added. (Default: 1)
  796. axis : int, optional
  797. Axis over which the integral is taken. (Default: 0).
  798. .. versionadded:: 1.7.0
  799. Returns
  800. -------
  801. S : ndarray
  802. C-series coefficients of the integral.
  803. Raises
  804. ------
  805. ValueError
  806. If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
  807. ``np.ndim(scl) != 0``.
  808. See Also
  809. --------
  810. chebder
  811. Notes
  812. -----
  813. Note that the result of each integration is *multiplied* by `scl`.
  814. Why is this important to note? Say one is making a linear change of
  815. variable :math:`u = ax + b` in an integral relative to `x`. Then
  816. :math:`dx = du/a`, so one will need to set `scl` equal to
  817. :math:`1/a`- perhaps not what one would have first thought.
  818. Also note that, in general, the result of integrating a C-series needs
  819. to be "reprojected" onto the C-series basis set. Thus, typically,
  820. the result of this function is "unintuitive," albeit correct; see
  821. Examples section below.
  822. Examples
  823. --------
  824. >>> from numpy.polynomial import chebyshev as C
  825. >>> c = (1,2,3)
  826. >>> C.chebint(c)
  827. array([ 0.5, -0.5, 0.5, 0.5])
  828. >>> C.chebint(c,3)
  829. array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, # may vary
  830. 0.00625 ])
  831. >>> C.chebint(c, k=3)
  832. array([ 3.5, -0.5, 0.5, 0.5])
  833. >>> C.chebint(c,lbnd=-2)
  834. array([ 8.5, -0.5, 0.5, 0.5])
  835. >>> C.chebint(c,scl=-2)
  836. array([-1., 1., -1., -1.])
  837. """
  838. c = np.array(c, ndmin=1, copy=True)
  839. if c.dtype.char in '?bBhHiIlLqQpP':
  840. c = c.astype(np.double)
  841. if not np.iterable(k):
  842. k = [k]
  843. cnt = pu._deprecate_as_int(m, "the order of integration")
  844. iaxis = pu._deprecate_as_int(axis, "the axis")
  845. if cnt < 0:
  846. raise ValueError("The order of integration must be non-negative")
  847. if len(k) > cnt:
  848. raise ValueError("Too many integration constants")
  849. if np.ndim(lbnd) != 0:
  850. raise ValueError("lbnd must be a scalar.")
  851. if np.ndim(scl) != 0:
  852. raise ValueError("scl must be a scalar.")
  853. iaxis = normalize_axis_index(iaxis, c.ndim)
  854. if cnt == 0:
  855. return c
  856. c = np.moveaxis(c, iaxis, 0)
  857. k = list(k) + [0]*(cnt - len(k))
  858. for i in range(cnt):
  859. n = len(c)
  860. c *= scl
  861. if n == 1 and np.all(c[0] == 0):
  862. c[0] += k[i]
  863. else:
  864. tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
  865. tmp[0] = c[0]*0
  866. tmp[1] = c[0]
  867. if n > 1:
  868. tmp[2] = c[1]/4
  869. for j in range(2, n):
  870. t = c[j]/(2*j + 1) # FIXME: t never used
  871. tmp[j + 1] = c[j]/(2*(j + 1))
  872. tmp[j - 1] -= c[j]/(2*(j - 1))
  873. tmp[0] += k[i] - chebval(lbnd, tmp)
  874. c = tmp
  875. c = np.moveaxis(c, 0, iaxis)
  876. return c
  877. def chebval(x, c, tensor=True):
  878. """
  879. Evaluate a Chebyshev series at points x.
  880. If `c` is of length `n + 1`, this function returns the value:
  881. .. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)
  882. The parameter `x` is converted to an array only if it is a tuple or a
  883. list, otherwise it is treated as a scalar. In either case, either `x`
  884. or its elements must support multiplication and addition both with
  885. themselves and with the elements of `c`.
  886. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
  887. `c` is multidimensional, then the shape of the result depends on the
  888. value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
  889. x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
  890. scalars have shape (,).
  891. Trailing zeros in the coefficients will be used in the evaluation, so
  892. they should be avoided if efficiency is a concern.
  893. Parameters
  894. ----------
  895. x : array_like, compatible object
  896. If `x` is a list or tuple, it is converted to an ndarray, otherwise
  897. it is left unchanged and treated as a scalar. In either case, `x`
  898. or its elements must support addition and multiplication with
  899. with themselves and with the elements of `c`.
  900. c : array_like
  901. Array of coefficients ordered so that the coefficients for terms of
  902. degree n are contained in c[n]. If `c` is multidimensional the
  903. remaining indices enumerate multiple polynomials. In the two
  904. dimensional case the coefficients may be thought of as stored in
  905. the columns of `c`.
  906. tensor : boolean, optional
  907. If True, the shape of the coefficient array is extended with ones
  908. on the right, one for each dimension of `x`. Scalars have dimension 0
  909. for this action. The result is that every column of coefficients in
  910. `c` is evaluated for every element of `x`. If False, `x` is broadcast
  911. over the columns of `c` for the evaluation. This keyword is useful
  912. when `c` is multidimensional. The default value is True.
  913. .. versionadded:: 1.7.0
  914. Returns
  915. -------
  916. values : ndarray, algebra_like
  917. The shape of the return value is described above.
  918. See Also
  919. --------
  920. chebval2d, chebgrid2d, chebval3d, chebgrid3d
  921. Notes
  922. -----
  923. The evaluation uses Clenshaw recursion, aka synthetic division.
  924. Examples
  925. --------
  926. """
  927. c = np.array(c, ndmin=1, copy=True)
  928. if c.dtype.char in '?bBhHiIlLqQpP':
  929. c = c.astype(np.double)
  930. if isinstance(x, (tuple, list)):
  931. x = np.asarray(x)
  932. if isinstance(x, np.ndarray) and tensor:
  933. c = c.reshape(c.shape + (1,)*x.ndim)
  934. if len(c) == 1:
  935. c0 = c[0]
  936. c1 = 0
  937. elif len(c) == 2:
  938. c0 = c[0]
  939. c1 = c[1]
  940. else:
  941. x2 = 2*x
  942. c0 = c[-2]
  943. c1 = c[-1]
  944. for i in range(3, len(c) + 1):
  945. tmp = c0
  946. c0 = c[-i] - c1
  947. c1 = tmp + c1*x2
  948. return c0 + c1*x
  949. def chebval2d(x, y, c):
  950. """
  951. Evaluate a 2-D Chebyshev series at points (x, y).
  952. This function returns the values:
  953. .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y)
  954. The parameters `x` and `y` are converted to arrays only if they are
  955. tuples or a lists, otherwise they are treated as a scalars and they
  956. must have the same shape after conversion. In either case, either `x`
  957. and `y` or their elements must support multiplication and addition both
  958. with themselves and with the elements of `c`.
  959. If `c` is a 1-D array a one is implicitly appended to its shape to make
  960. it 2-D. The shape of the result will be c.shape[2:] + x.shape.
  961. Parameters
  962. ----------
  963. x, y : array_like, compatible objects
  964. The two dimensional series is evaluated at the points `(x, y)`,
  965. where `x` and `y` must have the same shape. If `x` or `y` is a list
  966. or tuple, it is first converted to an ndarray, otherwise it is left
  967. unchanged and if it isn't an ndarray it is treated as a scalar.
  968. c : array_like
  969. Array of coefficients ordered so that the coefficient of the term
  970. of multi-degree i,j is contained in ``c[i,j]``. If `c` has
  971. dimension greater than 2 the remaining indices enumerate multiple
  972. sets of coefficients.
  973. Returns
  974. -------
  975. values : ndarray, compatible object
  976. The values of the two dimensional Chebyshev series at points formed
  977. from pairs of corresponding values from `x` and `y`.
  978. See Also
  979. --------
  980. chebval, chebgrid2d, chebval3d, chebgrid3d
  981. Notes
  982. -----
  983. .. versionadded:: 1.7.0
  984. """
  985. return pu._valnd(chebval, c, x, y)
  986. def chebgrid2d(x, y, c):
  987. """
  988. Evaluate a 2-D Chebyshev series on the Cartesian product of x and y.
  989. This function returns the values:
  990. .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * T_i(a) * T_j(b),
  991. where the points `(a, b)` consist of all pairs formed by taking
  992. `a` from `x` and `b` from `y`. The resulting points form a grid with
  993. `x` in the first dimension and `y` in the second.
  994. The parameters `x` and `y` are converted to arrays only if they are
  995. tuples or a lists, otherwise they are treated as a scalars. In either
  996. case, either `x` and `y` or their elements must support multiplication
  997. and addition both with themselves and with the elements of `c`.
  998. If `c` has fewer than two dimensions, ones are implicitly appended to
  999. its shape to make it 2-D. The shape of the result will be c.shape[2:] +
  1000. x.shape + y.shape.
  1001. Parameters
  1002. ----------
  1003. x, y : array_like, compatible objects
  1004. The two dimensional series is evaluated at the points in the
  1005. Cartesian product of `x` and `y`. If `x` or `y` is a list or
  1006. tuple, it is first converted to an ndarray, otherwise it is left
  1007. unchanged and, if it isn't an ndarray, it is treated as a scalar.
  1008. c : array_like
  1009. Array of coefficients ordered so that the coefficient of the term of
  1010. multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
  1011. greater than two the remaining indices enumerate multiple sets of
  1012. coefficients.
  1013. Returns
  1014. -------
  1015. values : ndarray, compatible object
  1016. The values of the two dimensional Chebyshev series at points in the
  1017. Cartesian product of `x` and `y`.
  1018. See Also
  1019. --------
  1020. chebval, chebval2d, chebval3d, chebgrid3d
  1021. Notes
  1022. -----
  1023. .. versionadded:: 1.7.0
  1024. """
  1025. return pu._gridnd(chebval, c, x, y)
  1026. def chebval3d(x, y, z, c):
  1027. """
  1028. Evaluate a 3-D Chebyshev series at points (x, y, z).
  1029. This function returns the values:
  1030. .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z)
  1031. The parameters `x`, `y`, and `z` are converted to arrays only if
  1032. they are tuples or a lists, otherwise they are treated as a scalars and
  1033. they must have the same shape after conversion. In either case, either
  1034. `x`, `y`, and `z` or their elements must support multiplication and
  1035. addition both with themselves and with the elements of `c`.
  1036. If `c` has fewer than 3 dimensions, ones are implicitly appended to its
  1037. shape to make it 3-D. The shape of the result will be c.shape[3:] +
  1038. x.shape.
  1039. Parameters
  1040. ----------
  1041. x, y, z : array_like, compatible object
  1042. The three dimensional series is evaluated at the points
  1043. `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
  1044. any of `x`, `y`, or `z` is a list or tuple, it is first converted
  1045. to an ndarray, otherwise it is left unchanged and if it isn't an
  1046. ndarray it is treated as a scalar.
  1047. c : array_like
  1048. Array of coefficients ordered so that the coefficient of the term of
  1049. multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
  1050. greater than 3 the remaining indices enumerate multiple sets of
  1051. coefficients.
  1052. Returns
  1053. -------
  1054. values : ndarray, compatible object
  1055. The values of the multidimensional polynomial on points formed with
  1056. triples of corresponding values from `x`, `y`, and `z`.
  1057. See Also
  1058. --------
  1059. chebval, chebval2d, chebgrid2d, chebgrid3d
  1060. Notes
  1061. -----
  1062. .. versionadded:: 1.7.0
  1063. """
  1064. return pu._valnd(chebval, c, x, y, z)
  1065. def chebgrid3d(x, y, z, c):
  1066. """
  1067. Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.
  1068. This function returns the values:
  1069. .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)
  1070. where the points `(a, b, c)` consist of all triples formed by taking
  1071. `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
  1072. a grid with `x` in the first dimension, `y` in the second, and `z` in
  1073. the third.
  1074. The parameters `x`, `y`, and `z` are converted to arrays only if they
  1075. are tuples or a lists, otherwise they are treated as a scalars. In
  1076. either case, either `x`, `y`, and `z` or their elements must support
  1077. multiplication and addition both with themselves and with the elements
  1078. of `c`.
  1079. If `c` has fewer than three dimensions, ones are implicitly appended to
  1080. its shape to make it 3-D. The shape of the result will be c.shape[3:] +
  1081. x.shape + y.shape + z.shape.
  1082. Parameters
  1083. ----------
  1084. x, y, z : array_like, compatible objects
  1085. The three dimensional series is evaluated at the points in the
  1086. Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
  1087. list or tuple, it is first converted to an ndarray, otherwise it is
  1088. left unchanged and, if it isn't an ndarray, it is treated as a
  1089. scalar.
  1090. c : array_like
  1091. Array of coefficients ordered so that the coefficients for terms of
  1092. degree i,j are contained in ``c[i,j]``. If `c` has dimension
  1093. greater than two the remaining indices enumerate multiple sets of
  1094. coefficients.
  1095. Returns
  1096. -------
  1097. values : ndarray, compatible object
  1098. The values of the two dimensional polynomial at points in the Cartesian
  1099. product of `x` and `y`.
  1100. See Also
  1101. --------
  1102. chebval, chebval2d, chebgrid2d, chebval3d
  1103. Notes
  1104. -----
  1105. .. versionadded:: 1.7.0
  1106. """
  1107. return pu._gridnd(chebval, c, x, y, z)
  1108. def chebvander(x, deg):
  1109. """Pseudo-Vandermonde matrix of given degree.
  1110. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
  1111. `x`. The pseudo-Vandermonde matrix is defined by
  1112. .. math:: V[..., i] = T_i(x),
  1113. where `0 <= i <= deg`. The leading indices of `V` index the elements of
  1114. `x` and the last index is the degree of the Chebyshev polynomial.
  1115. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
  1116. matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and
  1117. ``chebval(x, c)`` are the same up to roundoff. This equivalence is
  1118. useful both for least squares fitting and for the evaluation of a large
  1119. number of Chebyshev series of the same degree and sample points.
  1120. Parameters
  1121. ----------
  1122. x : array_like
  1123. Array of points. The dtype is converted to float64 or complex128
  1124. depending on whether any of the elements are complex. If `x` is
  1125. scalar it is converted to a 1-D array.
  1126. deg : int
  1127. Degree of the resulting matrix.
  1128. Returns
  1129. -------
  1130. vander : ndarray
  1131. The pseudo Vandermonde matrix. The shape of the returned matrix is
  1132. ``x.shape + (deg + 1,)``, where The last index is the degree of the
  1133. corresponding Chebyshev polynomial. The dtype will be the same as
  1134. the converted `x`.
  1135. """
  1136. ideg = pu._deprecate_as_int(deg, "deg")
  1137. if ideg < 0:
  1138. raise ValueError("deg must be non-negative")
  1139. x = np.array(x, copy=False, ndmin=1) + 0.0
  1140. dims = (ideg + 1,) + x.shape
  1141. dtyp = x.dtype
  1142. v = np.empty(dims, dtype=dtyp)
  1143. # Use forward recursion to generate the entries.
  1144. v[0] = x*0 + 1
  1145. if ideg > 0:
  1146. x2 = 2*x
  1147. v[1] = x
  1148. for i in range(2, ideg + 1):
  1149. v[i] = v[i-1]*x2 - v[i-2]
  1150. return np.moveaxis(v, 0, -1)
  1151. def chebvander2d(x, y, deg):
  1152. """Pseudo-Vandermonde matrix of given degrees.
  1153. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  1154. points `(x, y)`. The pseudo-Vandermonde matrix is defined by
  1155. .. math:: V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y),
  1156. where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
  1157. `V` index the points `(x, y)` and the last index encodes the degrees of
  1158. the Chebyshev polynomials.
  1159. If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
  1160. correspond to the elements of a 2-D coefficient array `c` of shape
  1161. (xdeg + 1, ydeg + 1) in the order
  1162. .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
  1163. and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same
  1164. up to roundoff. This equivalence is useful both for least squares
  1165. fitting and for the evaluation of a large number of 2-D Chebyshev
  1166. series of the same degrees and sample points.
  1167. Parameters
  1168. ----------
  1169. x, y : array_like
  1170. Arrays of point coordinates, all of the same shape. The dtypes
  1171. will be converted to either float64 or complex128 depending on
  1172. whether any of the elements are complex. Scalars are converted to
  1173. 1-D arrays.
  1174. deg : list of ints
  1175. List of maximum degrees of the form [x_deg, y_deg].
  1176. Returns
  1177. -------
  1178. vander2d : ndarray
  1179. The shape of the returned matrix is ``x.shape + (order,)``, where
  1180. :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
  1181. as the converted `x` and `y`.
  1182. See Also
  1183. --------
  1184. chebvander, chebvander3d, chebval2d, chebval3d
  1185. Notes
  1186. -----
  1187. .. versionadded:: 1.7.0
  1188. """
  1189. return pu._vander_nd_flat((chebvander, chebvander), (x, y), deg)
  1190. def chebvander3d(x, y, z, deg):
  1191. """Pseudo-Vandermonde matrix of given degrees.
  1192. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  1193. points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
  1194. then The pseudo-Vandermonde matrix is defined by
  1195. .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z),
  1196. where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
  1197. indices of `V` index the points `(x, y, z)` and the last index encodes
  1198. the degrees of the Chebyshev polynomials.
  1199. If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
  1200. of `V` correspond to the elements of a 3-D coefficient array `c` of
  1201. shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
  1202. .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
  1203. and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the
  1204. same up to roundoff. This equivalence is useful both for least squares
  1205. fitting and for the evaluation of a large number of 3-D Chebyshev
  1206. series of the same degrees and sample points.
  1207. Parameters
  1208. ----------
  1209. x, y, z : array_like
  1210. Arrays of point coordinates, all of the same shape. The dtypes will
  1211. be converted to either float64 or complex128 depending on whether
  1212. any of the elements are complex. Scalars are converted to 1-D
  1213. arrays.
  1214. deg : list of ints
  1215. List of maximum degrees of the form [x_deg, y_deg, z_deg].
  1216. Returns
  1217. -------
  1218. vander3d : ndarray
  1219. The shape of the returned matrix is ``x.shape + (order,)``, where
  1220. :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will
  1221. be the same as the converted `x`, `y`, and `z`.
  1222. See Also
  1223. --------
  1224. chebvander, chebvander3d, chebval2d, chebval3d
  1225. Notes
  1226. -----
  1227. .. versionadded:: 1.7.0
  1228. """
  1229. return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg)
  1230. def chebfit(x, y, deg, rcond=None, full=False, w=None):
  1231. """
  1232. Least squares fit of Chebyshev series to data.
  1233. Return the coefficients of a Chebyshev series of degree `deg` that is the
  1234. least squares fit to the data values `y` given at points `x`. If `y` is
  1235. 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
  1236. fits are done, one for each column of `y`, and the resulting
  1237. coefficients are stored in the corresponding columns of a 2-D return.
  1238. The fitted polynomial(s) are in the form
  1239. .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x),
  1240. where `n` is `deg`.
  1241. Parameters
  1242. ----------
  1243. x : array_like, shape (M,)
  1244. x-coordinates of the M sample points ``(x[i], y[i])``.
  1245. y : array_like, shape (M,) or (M, K)
  1246. y-coordinates of the sample points. Several data sets of sample
  1247. points sharing the same x-coordinates can be fitted at once by
  1248. passing in a 2D-array that contains one dataset per column.
  1249. deg : int or 1-D array_like
  1250. Degree(s) of the fitting polynomials. If `deg` is a single integer,
  1251. all terms up to and including the `deg`'th term are included in the
  1252. fit. For NumPy versions >= 1.11.0 a list of integers specifying the
  1253. degrees of the terms to include may be used instead.
  1254. rcond : float, optional
  1255. Relative condition number of the fit. Singular values smaller than
  1256. this relative to the largest singular value will be ignored. The
  1257. default value is len(x)*eps, where eps is the relative precision of
  1258. the float type, about 2e-16 in most cases.
  1259. full : bool, optional
  1260. Switch determining nature of return value. When it is False (the
  1261. default) just the coefficients are returned, when True diagnostic
  1262. information from the singular value decomposition is also returned.
  1263. w : array_like, shape (`M`,), optional
  1264. Weights. If not None, the contribution of each point
  1265. ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
  1266. weights are chosen so that the errors of the products ``w[i]*y[i]``
  1267. all have the same variance. The default value is None.
  1268. .. versionadded:: 1.5.0
  1269. Returns
  1270. -------
  1271. coef : ndarray, shape (M,) or (M, K)
  1272. Chebyshev coefficients ordered from low to high. If `y` was 2-D,
  1273. the coefficients for the data in column k of `y` are in column
  1274. `k`.
  1275. [residuals, rank, singular_values, rcond] : list
  1276. These values are only returned if `full` = True
  1277. resid -- sum of squared residuals of the least squares fit
  1278. rank -- the numerical rank of the scaled Vandermonde matrix
  1279. sv -- singular values of the scaled Vandermonde matrix
  1280. rcond -- value of `rcond`.
  1281. For more details, see `linalg.lstsq`.
  1282. Warns
  1283. -----
  1284. RankWarning
  1285. The rank of the coefficient matrix in the least-squares fit is
  1286. deficient. The warning is only raised if `full` = False. The
  1287. warnings can be turned off by
  1288. >>> import warnings
  1289. >>> warnings.simplefilter('ignore', np.RankWarning)
  1290. See Also
  1291. --------
  1292. polyfit, legfit, lagfit, hermfit, hermefit
  1293. chebval : Evaluates a Chebyshev series.
  1294. chebvander : Vandermonde matrix of Chebyshev series.
  1295. chebweight : Chebyshev weight function.
  1296. linalg.lstsq : Computes a least-squares fit from the matrix.
  1297. scipy.interpolate.UnivariateSpline : Computes spline fits.
  1298. Notes
  1299. -----
  1300. The solution is the coefficients of the Chebyshev series `p` that
  1301. minimizes the sum of the weighted squared errors
  1302. .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
  1303. where :math:`w_j` are the weights. This problem is solved by setting up
  1304. as the (typically) overdetermined matrix equation
  1305. .. math:: V(x) * c = w * y,
  1306. where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
  1307. coefficients to be solved for, `w` are the weights, and `y` are the
  1308. observed values. This equation is then solved using the singular value
  1309. decomposition of `V`.
  1310. If some of the singular values of `V` are so small that they are
  1311. neglected, then a `RankWarning` will be issued. This means that the
  1312. coefficient values may be poorly determined. Using a lower order fit
  1313. will usually get rid of the warning. The `rcond` parameter can also be
  1314. set to a value smaller than its default, but the resulting fit may be
  1315. spurious and have large contributions from roundoff error.
  1316. Fits using Chebyshev series are usually better conditioned than fits
  1317. using power series, but much can depend on the distribution of the
  1318. sample points and the smoothness of the data. If the quality of the fit
  1319. is inadequate splines may be a good alternative.
  1320. References
  1321. ----------
  1322. .. [1] Wikipedia, "Curve fitting",
  1323. https://en.wikipedia.org/wiki/Curve_fitting
  1324. Examples
  1325. --------
  1326. """
  1327. return pu._fit(chebvander, x, y, deg, rcond, full, w)
  1328. def chebcompanion(c):
  1329. """Return the scaled companion matrix of c.
  1330. The basis polynomials are scaled so that the companion matrix is
  1331. symmetric when `c` is a Chebyshev basis polynomial. This provides
  1332. better eigenvalue estimates than the unscaled case and for basis
  1333. polynomials the eigenvalues are guaranteed to be real if
  1334. `numpy.linalg.eigvalsh` is used to obtain them.
  1335. Parameters
  1336. ----------
  1337. c : array_like
  1338. 1-D array of Chebyshev series coefficients ordered from low to high
  1339. degree.
  1340. Returns
  1341. -------
  1342. mat : ndarray
  1343. Scaled companion matrix of dimensions (deg, deg).
  1344. Notes
  1345. -----
  1346. .. versionadded:: 1.7.0
  1347. """
  1348. # c is a trimmed copy
  1349. [c] = pu.as_series([c])
  1350. if len(c) < 2:
  1351. raise ValueError('Series must have maximum degree of at least 1.')
  1352. if len(c) == 2:
  1353. return np.array([[-c[0]/c[1]]])
  1354. n = len(c) - 1
  1355. mat = np.zeros((n, n), dtype=c.dtype)
  1356. scl = np.array([1.] + [np.sqrt(.5)]*(n-1))
  1357. top = mat.reshape(-1)[1::n+1]
  1358. bot = mat.reshape(-1)[n::n+1]
  1359. top[0] = np.sqrt(.5)
  1360. top[1:] = 1/2
  1361. bot[...] = top
  1362. mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5
  1363. return mat
  1364. def chebroots(c):
  1365. """
  1366. Compute the roots of a Chebyshev series.
  1367. Return the roots (a.k.a. "zeros") of the polynomial
  1368. .. math:: p(x) = \\sum_i c[i] * T_i(x).
  1369. Parameters
  1370. ----------
  1371. c : 1-D array_like
  1372. 1-D array of coefficients.
  1373. Returns
  1374. -------
  1375. out : ndarray
  1376. Array of the roots of the series. If all the roots are real,
  1377. then `out` is also real, otherwise it is complex.
  1378. See Also
  1379. --------
  1380. polyroots, legroots, lagroots, hermroots, hermeroots
  1381. Notes
  1382. -----
  1383. The root estimates are obtained as the eigenvalues of the companion
  1384. matrix, Roots far from the origin of the complex plane may have large
  1385. errors due to the numerical instability of the series for such
  1386. values. Roots with multiplicity greater than 1 will also show larger
  1387. errors as the value of the series near such points is relatively
  1388. insensitive to errors in the roots. Isolated roots near the origin can
  1389. be improved by a few iterations of Newton's method.
  1390. The Chebyshev series basis polynomials aren't powers of `x` so the
  1391. results of this function may seem unintuitive.
  1392. Examples
  1393. --------
  1394. >>> import numpy.polynomial.chebyshev as cheb
  1395. >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots
  1396. array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) # may vary
  1397. """
  1398. # c is a trimmed copy
  1399. [c] = pu.as_series([c])
  1400. if len(c) < 2:
  1401. return np.array([], dtype=c.dtype)
  1402. if len(c) == 2:
  1403. return np.array([-c[0]/c[1]])
  1404. # rotated companion matrix reduces error
  1405. m = chebcompanion(c)[::-1,::-1]
  1406. r = la.eigvals(m)
  1407. r.sort()
  1408. return r
  1409. def chebinterpolate(func, deg, args=()):
  1410. """Interpolate a function at the Chebyshev points of the first kind.
  1411. Returns the Chebyshev series that interpolates `func` at the Chebyshev
  1412. points of the first kind in the interval [-1, 1]. The interpolating
  1413. series tends to a minmax approximation to `func` with increasing `deg`
  1414. if the function is continuous in the interval.
  1415. .. versionadded:: 1.14.0
  1416. Parameters
  1417. ----------
  1418. func : function
  1419. The function to be approximated. It must be a function of a single
  1420. variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
  1421. extra arguments passed in the `args` parameter.
  1422. deg : int
  1423. Degree of the interpolating polynomial
  1424. args : tuple, optional
  1425. Extra arguments to be used in the function call. Default is no extra
  1426. arguments.
  1427. Returns
  1428. -------
  1429. coef : ndarray, shape (deg + 1,)
  1430. Chebyshev coefficients of the interpolating series ordered from low to
  1431. high.
  1432. Examples
  1433. --------
  1434. >>> import numpy.polynomial.chebyshev as C
  1435. >>> C.chebfromfunction(lambda x: np.tanh(x) + 0.5, 8)
  1436. array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17,
  1437. -5.42457905e-02, -2.71387850e-16, 4.51658839e-03,
  1438. 2.46716228e-17, -3.79694221e-04, -3.26899002e-16])
  1439. Notes
  1440. -----
  1441. The Chebyshev polynomials used in the interpolation are orthogonal when
  1442. sampled at the Chebyshev points of the first kind. If it is desired to
  1443. constrain some of the coefficients they can simply be set to the desired
  1444. value after the interpolation, no new interpolation or fit is needed. This
  1445. is especially useful if it is known apriori that some of coefficients are
  1446. zero. For instance, if the function is even then the coefficients of the
  1447. terms of odd degree in the result can be set to zero.
  1448. """
  1449. deg = np.asarray(deg)
  1450. # check arguments.
  1451. if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0:
  1452. raise TypeError("deg must be an int")
  1453. if deg < 0:
  1454. raise ValueError("expected deg >= 0")
  1455. order = deg + 1
  1456. xcheb = chebpts1(order)
  1457. yfunc = func(xcheb, *args)
  1458. m = chebvander(xcheb, deg)
  1459. c = np.dot(m.T, yfunc)
  1460. c[0] /= order
  1461. c[1:] /= 0.5*order
  1462. return c
  1463. def chebgauss(deg):
  1464. """
  1465. Gauss-Chebyshev quadrature.
  1466. Computes the sample points and weights for Gauss-Chebyshev quadrature.
  1467. These sample points and weights will correctly integrate polynomials of
  1468. degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
  1469. the weight function :math:`f(x) = 1/\\sqrt{1 - x^2}`.
  1470. Parameters
  1471. ----------
  1472. deg : int
  1473. Number of sample points and weights. It must be >= 1.
  1474. Returns
  1475. -------
  1476. x : ndarray
  1477. 1-D ndarray containing the sample points.
  1478. y : ndarray
  1479. 1-D ndarray containing the weights.
  1480. Notes
  1481. -----
  1482. .. versionadded:: 1.7.0
  1483. The results have only been tested up to degree 100, higher degrees may
  1484. be problematic. For Gauss-Chebyshev there are closed form solutions for
  1485. the sample points and weights. If n = `deg`, then
  1486. .. math:: x_i = \\cos(\\pi (2 i - 1) / (2 n))
  1487. .. math:: w_i = \\pi / n
  1488. """
  1489. ideg = pu._deprecate_as_int(deg, "deg")
  1490. if ideg <= 0:
  1491. raise ValueError("deg must be a positive integer")
  1492. x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg))
  1493. w = np.ones(ideg)*(np.pi/ideg)
  1494. return x, w
  1495. def chebweight(x):
  1496. """
  1497. The weight function of the Chebyshev polynomials.
  1498. The weight function is :math:`1/\\sqrt{1 - x^2}` and the interval of
  1499. integration is :math:`[-1, 1]`. The Chebyshev polynomials are
  1500. orthogonal, but not normalized, with respect to this weight function.
  1501. Parameters
  1502. ----------
  1503. x : array_like
  1504. Values at which the weight function will be computed.
  1505. Returns
  1506. -------
  1507. w : ndarray
  1508. The weight function at `x`.
  1509. Notes
  1510. -----
  1511. .. versionadded:: 1.7.0
  1512. """
  1513. w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x))
  1514. return w
  1515. def chebpts1(npts):
  1516. """
  1517. Chebyshev points of the first kind.
  1518. The Chebyshev points of the first kind are the points ``cos(x)``,
  1519. where ``x = [pi*(k + .5)/npts for k in range(npts)]``.
  1520. Parameters
  1521. ----------
  1522. npts : int
  1523. Number of sample points desired.
  1524. Returns
  1525. -------
  1526. pts : ndarray
  1527. The Chebyshev points of the first kind.
  1528. See Also
  1529. --------
  1530. chebpts2
  1531. Notes
  1532. -----
  1533. .. versionadded:: 1.5.0
  1534. """
  1535. _npts = int(npts)
  1536. if _npts != npts:
  1537. raise ValueError("npts must be integer")
  1538. if _npts < 1:
  1539. raise ValueError("npts must be >= 1")
  1540. x = np.linspace(-np.pi, 0, _npts, endpoint=False) + np.pi/(2*_npts)
  1541. return np.cos(x)
  1542. def chebpts2(npts):
  1543. """
  1544. Chebyshev points of the second kind.
  1545. The Chebyshev points of the second kind are the points ``cos(x)``,
  1546. where ``x = [pi*k/(npts - 1) for k in range(npts)]``.
  1547. Parameters
  1548. ----------
  1549. npts : int
  1550. Number of sample points desired.
  1551. Returns
  1552. -------
  1553. pts : ndarray
  1554. The Chebyshev points of the second kind.
  1555. Notes
  1556. -----
  1557. .. versionadded:: 1.5.0
  1558. """
  1559. _npts = int(npts)
  1560. if _npts != npts:
  1561. raise ValueError("npts must be integer")
  1562. if _npts < 2:
  1563. raise ValueError("npts must be >= 2")
  1564. x = np.linspace(-np.pi, 0, _npts)
  1565. return np.cos(x)
  1566. #
  1567. # Chebyshev series class
  1568. #
  1569. class Chebyshev(ABCPolyBase):
  1570. """A Chebyshev series class.
  1571. The Chebyshev class provides the standard Python numerical methods
  1572. '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
  1573. methods listed below.
  1574. Parameters
  1575. ----------
  1576. coef : array_like
  1577. Chebyshev coefficients in order of increasing degree, i.e.,
  1578. ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``.
  1579. domain : (2,) array_like, optional
  1580. Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
  1581. to the interval ``[window[0], window[1]]`` by shifting and scaling.
  1582. The default value is [-1, 1].
  1583. window : (2,) array_like, optional
  1584. Window, see `domain` for its use. The default value is [-1, 1].
  1585. .. versionadded:: 1.6.0
  1586. """
  1587. # Virtual Functions
  1588. _add = staticmethod(chebadd)
  1589. _sub = staticmethod(chebsub)
  1590. _mul = staticmethod(chebmul)
  1591. _div = staticmethod(chebdiv)
  1592. _pow = staticmethod(chebpow)
  1593. _val = staticmethod(chebval)
  1594. _int = staticmethod(chebint)
  1595. _der = staticmethod(chebder)
  1596. _fit = staticmethod(chebfit)
  1597. _line = staticmethod(chebline)
  1598. _roots = staticmethod(chebroots)
  1599. _fromroots = staticmethod(chebfromroots)
  1600. @classmethod
  1601. def interpolate(cls, func, deg, domain=None, args=()):
  1602. """Interpolate a function at the Chebyshev points of the first kind.
  1603. Returns the series that interpolates `func` at the Chebyshev points of
  1604. the first kind scaled and shifted to the `domain`. The resulting series
  1605. tends to a minmax approximation of `func` when the function is
  1606. continuous in the domain.
  1607. .. versionadded:: 1.14.0
  1608. Parameters
  1609. ----------
  1610. func : function
  1611. The function to be interpolated. It must be a function of a single
  1612. variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
  1613. extra arguments passed in the `args` parameter.
  1614. deg : int
  1615. Degree of the interpolating polynomial.
  1616. domain : {None, [beg, end]}, optional
  1617. Domain over which `func` is interpolated. The default is None, in
  1618. which case the domain is [-1, 1].
  1619. args : tuple, optional
  1620. Extra arguments to be used in the function call. Default is no
  1621. extra arguments.
  1622. Returns
  1623. -------
  1624. polynomial : Chebyshev instance
  1625. Interpolating Chebyshev instance.
  1626. Notes
  1627. -----
  1628. See `numpy.polynomial.chebfromfunction` for more details.
  1629. """
  1630. if domain is None:
  1631. domain = cls.domain
  1632. xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args)
  1633. coef = chebinterpolate(xfunc, deg)
  1634. return cls(coef, domain=domain)
  1635. # Virtual properties
  1636. nickname = 'cheb'
  1637. domain = np.array(chebdomain)
  1638. window = np.array(chebdomain)
  1639. basis_name = 'T'