chebyshev.py 61 KB

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