chebyshev.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074
  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. """Covert Chebyshev series to z-series.
  105. Covert 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. """Covert z-series to a Chebyshev series.
  124. Covert 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. with 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 contribution of each point
  1277. ``(x[i],y[i])`` to the fit is weighted by ``w[i]``. Ideally the
  1278. weights are chosen so that the errors of the products ``w[i]*y[i]``
  1279. all have the same variance. The default value is None.
  1280. .. versionadded:: 1.5.0
  1281. Returns
  1282. -------
  1283. coef : ndarray, shape (M,) or (M, K)
  1284. Chebyshev coefficients ordered from low to high. If `y` was 2-D,
  1285. the coefficients for the data in column k of `y` are in column
  1286. `k`.
  1287. [residuals, rank, singular_values, rcond] : list
  1288. These values are only returned if `full` = True
  1289. resid -- sum of squared residuals of the least squares fit
  1290. rank -- the numerical rank of the scaled Vandermonde matrix
  1291. sv -- singular values of the scaled Vandermonde matrix
  1292. rcond -- value of `rcond`.
  1293. For more details, see `numpy.linalg.lstsq`.
  1294. Warns
  1295. -----
  1296. RankWarning
  1297. The rank of the coefficient matrix in the least-squares fit is
  1298. deficient. The warning is only raised if `full` = False. The
  1299. warnings can be turned off by
  1300. >>> import warnings
  1301. >>> warnings.simplefilter('ignore', np.RankWarning)
  1302. See Also
  1303. --------
  1304. numpy.polynomial.polynomial.polyfit
  1305. numpy.polynomial.legendre.legfit
  1306. numpy.polynomial.laguerre.lagfit
  1307. numpy.polynomial.hermite.hermfit
  1308. numpy.polynomial.hermite_e.hermefit
  1309. chebval : Evaluates a Chebyshev series.
  1310. chebvander : Vandermonde matrix of Chebyshev series.
  1311. chebweight : Chebyshev weight function.
  1312. numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
  1313. scipy.interpolate.UnivariateSpline : Computes spline fits.
  1314. Notes
  1315. -----
  1316. The solution is the coefficients of the Chebyshev series `p` that
  1317. minimizes the sum of the weighted squared errors
  1318. .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
  1319. where :math:`w_j` are the weights. This problem is solved by setting up
  1320. as the (typically) overdetermined matrix equation
  1321. .. math:: V(x) * c = w * y,
  1322. where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
  1323. coefficients to be solved for, `w` are the weights, and `y` are the
  1324. observed values. This equation is then solved using the singular value
  1325. decomposition of `V`.
  1326. If some of the singular values of `V` are so small that they are
  1327. neglected, then a `RankWarning` will be issued. This means that the
  1328. coefficient values may be poorly determined. Using a lower order fit
  1329. will usually get rid of the warning. The `rcond` parameter can also be
  1330. set to a value smaller than its default, but the resulting fit may be
  1331. spurious and have large contributions from roundoff error.
  1332. Fits using Chebyshev series are usually better conditioned than fits
  1333. using power series, but much can depend on the distribution of the
  1334. sample points and the smoothness of the data. If the quality of the fit
  1335. is inadequate splines may be a good alternative.
  1336. References
  1337. ----------
  1338. .. [1] Wikipedia, "Curve fitting",
  1339. https://en.wikipedia.org/wiki/Curve_fitting
  1340. Examples
  1341. --------
  1342. """
  1343. return pu._fit(chebvander, x, y, deg, rcond, full, w)
  1344. def chebcompanion(c):
  1345. """Return the scaled companion matrix of c.
  1346. The basis polynomials are scaled so that the companion matrix is
  1347. symmetric when `c` is a Chebyshev basis polynomial. This provides
  1348. better eigenvalue estimates than the unscaled case and for basis
  1349. polynomials the eigenvalues are guaranteed to be real if
  1350. `numpy.linalg.eigvalsh` is used to obtain them.
  1351. Parameters
  1352. ----------
  1353. c : array_like
  1354. 1-D array of Chebyshev series coefficients ordered from low to high
  1355. degree.
  1356. Returns
  1357. -------
  1358. mat : ndarray
  1359. Scaled companion matrix of dimensions (deg, deg).
  1360. Notes
  1361. -----
  1362. .. versionadded:: 1.7.0
  1363. """
  1364. # c is a trimmed copy
  1365. [c] = pu.as_series([c])
  1366. if len(c) < 2:
  1367. raise ValueError('Series must have maximum degree of at least 1.')
  1368. if len(c) == 2:
  1369. return np.array([[-c[0]/c[1]]])
  1370. n = len(c) - 1
  1371. mat = np.zeros((n, n), dtype=c.dtype)
  1372. scl = np.array([1.] + [np.sqrt(.5)]*(n-1))
  1373. top = mat.reshape(-1)[1::n+1]
  1374. bot = mat.reshape(-1)[n::n+1]
  1375. top[0] = np.sqrt(.5)
  1376. top[1:] = 1/2
  1377. bot[...] = top
  1378. mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5
  1379. return mat
  1380. def chebroots(c):
  1381. """
  1382. Compute the roots of a Chebyshev series.
  1383. Return the roots (a.k.a. "zeros") of the polynomial
  1384. .. math:: p(x) = \\sum_i c[i] * T_i(x).
  1385. Parameters
  1386. ----------
  1387. c : 1-D array_like
  1388. 1-D array of coefficients.
  1389. Returns
  1390. -------
  1391. out : ndarray
  1392. Array of the roots of the series. If all the roots are real,
  1393. then `out` is also real, otherwise it is complex.
  1394. See Also
  1395. --------
  1396. numpy.polynomial.polynomial.polyroots
  1397. numpy.polynomial.legendre.legroots
  1398. numpy.polynomial.laguerre.lagroots
  1399. numpy.polynomial.hermite.hermroots
  1400. numpy.polynomial.hermite_e.hermeroots
  1401. Notes
  1402. -----
  1403. The root estimates are obtained as the eigenvalues of the companion
  1404. matrix, Roots far from the origin of the complex plane may have large
  1405. errors due to the numerical instability of the series for such
  1406. values. Roots with multiplicity greater than 1 will also show larger
  1407. errors as the value of the series near such points is relatively
  1408. insensitive to errors in the roots. Isolated roots near the origin can
  1409. be improved by a few iterations of Newton's method.
  1410. The Chebyshev series basis polynomials aren't powers of `x` so the
  1411. results of this function may seem unintuitive.
  1412. Examples
  1413. --------
  1414. >>> import numpy.polynomial.chebyshev as cheb
  1415. >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots
  1416. array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) # may vary
  1417. """
  1418. # c is a trimmed copy
  1419. [c] = pu.as_series([c])
  1420. if len(c) < 2:
  1421. return np.array([], dtype=c.dtype)
  1422. if len(c) == 2:
  1423. return np.array([-c[0]/c[1]])
  1424. # rotated companion matrix reduces error
  1425. m = chebcompanion(c)[::-1,::-1]
  1426. r = la.eigvals(m)
  1427. r.sort()
  1428. return r
  1429. def chebinterpolate(func, deg, args=()):
  1430. """Interpolate a function at the Chebyshev points of the first kind.
  1431. Returns the Chebyshev series that interpolates `func` at the Chebyshev
  1432. points of the first kind in the interval [-1, 1]. The interpolating
  1433. series tends to a minmax approximation to `func` with increasing `deg`
  1434. if the function is continuous in the interval.
  1435. .. versionadded:: 1.14.0
  1436. Parameters
  1437. ----------
  1438. func : function
  1439. The function to be approximated. It must be a function of a single
  1440. variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
  1441. extra arguments passed in the `args` parameter.
  1442. deg : int
  1443. Degree of the interpolating polynomial
  1444. args : tuple, optional
  1445. Extra arguments to be used in the function call. Default is no extra
  1446. arguments.
  1447. Returns
  1448. -------
  1449. coef : ndarray, shape (deg + 1,)
  1450. Chebyshev coefficients of the interpolating series ordered from low to
  1451. high.
  1452. Examples
  1453. --------
  1454. >>> import numpy.polynomial.chebyshev as C
  1455. >>> C.chebfromfunction(lambda x: np.tanh(x) + 0.5, 8)
  1456. array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17,
  1457. -5.42457905e-02, -2.71387850e-16, 4.51658839e-03,
  1458. 2.46716228e-17, -3.79694221e-04, -3.26899002e-16])
  1459. Notes
  1460. -----
  1461. The Chebyshev polynomials used in the interpolation are orthogonal when
  1462. sampled at the Chebyshev points of the first kind. If it is desired to
  1463. constrain some of the coefficients they can simply be set to the desired
  1464. value after the interpolation, no new interpolation or fit is needed. This
  1465. is especially useful if it is known apriori that some of coefficients are
  1466. zero. For instance, if the function is even then the coefficients of the
  1467. terms of odd degree in the result can be set to zero.
  1468. """
  1469. deg = np.asarray(deg)
  1470. # check arguments.
  1471. if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0:
  1472. raise TypeError("deg must be an int")
  1473. if deg < 0:
  1474. raise ValueError("expected deg >= 0")
  1475. order = deg + 1
  1476. xcheb = chebpts1(order)
  1477. yfunc = func(xcheb, *args)
  1478. m = chebvander(xcheb, deg)
  1479. c = np.dot(m.T, yfunc)
  1480. c[0] /= order
  1481. c[1:] /= 0.5*order
  1482. return c
  1483. def chebgauss(deg):
  1484. """
  1485. Gauss-Chebyshev quadrature.
  1486. Computes the sample points and weights for Gauss-Chebyshev quadrature.
  1487. These sample points and weights will correctly integrate polynomials of
  1488. degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
  1489. the weight function :math:`f(x) = 1/\\sqrt{1 - x^2}`.
  1490. Parameters
  1491. ----------
  1492. deg : int
  1493. Number of sample points and weights. It must be >= 1.
  1494. Returns
  1495. -------
  1496. x : ndarray
  1497. 1-D ndarray containing the sample points.
  1498. y : ndarray
  1499. 1-D ndarray containing the weights.
  1500. Notes
  1501. -----
  1502. .. versionadded:: 1.7.0
  1503. The results have only been tested up to degree 100, higher degrees may
  1504. be problematic. For Gauss-Chebyshev there are closed form solutions for
  1505. the sample points and weights. If n = `deg`, then
  1506. .. math:: x_i = \\cos(\\pi (2 i - 1) / (2 n))
  1507. .. math:: w_i = \\pi / n
  1508. """
  1509. ideg = pu._deprecate_as_int(deg, "deg")
  1510. if ideg <= 0:
  1511. raise ValueError("deg must be a positive integer")
  1512. x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg))
  1513. w = np.ones(ideg)*(np.pi/ideg)
  1514. return x, w
  1515. def chebweight(x):
  1516. """
  1517. The weight function of the Chebyshev polynomials.
  1518. The weight function is :math:`1/\\sqrt{1 - x^2}` and the interval of
  1519. integration is :math:`[-1, 1]`. The Chebyshev polynomials are
  1520. orthogonal, but not normalized, with respect to this weight function.
  1521. Parameters
  1522. ----------
  1523. x : array_like
  1524. Values at which the weight function will be computed.
  1525. Returns
  1526. -------
  1527. w : ndarray
  1528. The weight function at `x`.
  1529. Notes
  1530. -----
  1531. .. versionadded:: 1.7.0
  1532. """
  1533. w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x))
  1534. return w
  1535. def chebpts1(npts):
  1536. """
  1537. Chebyshev points of the first kind.
  1538. The Chebyshev points of the first kind are the points ``cos(x)``,
  1539. where ``x = [pi*(k + .5)/npts for k in range(npts)]``.
  1540. Parameters
  1541. ----------
  1542. npts : int
  1543. Number of sample points desired.
  1544. Returns
  1545. -------
  1546. pts : ndarray
  1547. The Chebyshev points of the first kind.
  1548. See Also
  1549. --------
  1550. chebpts2
  1551. Notes
  1552. -----
  1553. .. versionadded:: 1.5.0
  1554. """
  1555. _npts = int(npts)
  1556. if _npts != npts:
  1557. raise ValueError("npts must be integer")
  1558. if _npts < 1:
  1559. raise ValueError("npts must be >= 1")
  1560. x = 0.5 * np.pi / _npts * np.arange(-_npts+1, _npts+1, 2)
  1561. return np.sin(x)
  1562. def chebpts2(npts):
  1563. """
  1564. Chebyshev points of the second kind.
  1565. The Chebyshev points of the second kind are the points ``cos(x)``,
  1566. where ``x = [pi*k/(npts - 1) for k in range(npts)]``.
  1567. Parameters
  1568. ----------
  1569. npts : int
  1570. Number of sample points desired.
  1571. Returns
  1572. -------
  1573. pts : ndarray
  1574. The Chebyshev points of the second kind.
  1575. Notes
  1576. -----
  1577. .. versionadded:: 1.5.0
  1578. """
  1579. _npts = int(npts)
  1580. if _npts != npts:
  1581. raise ValueError("npts must be integer")
  1582. if _npts < 2:
  1583. raise ValueError("npts must be >= 2")
  1584. x = np.linspace(-np.pi, 0, _npts)
  1585. return np.cos(x)
  1586. #
  1587. # Chebyshev series class
  1588. #
  1589. class Chebyshev(ABCPolyBase):
  1590. """A Chebyshev series class.
  1591. The Chebyshev class provides the standard Python numerical methods
  1592. '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
  1593. methods listed below.
  1594. Parameters
  1595. ----------
  1596. coef : array_like
  1597. Chebyshev coefficients in order of increasing degree, i.e.,
  1598. ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``.
  1599. domain : (2,) array_like, optional
  1600. Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
  1601. to the interval ``[window[0], window[1]]`` by shifting and scaling.
  1602. The default value is [-1, 1].
  1603. window : (2,) array_like, optional
  1604. Window, see `domain` for its use. The default value is [-1, 1].
  1605. .. versionadded:: 1.6.0
  1606. """
  1607. # Virtual Functions
  1608. _add = staticmethod(chebadd)
  1609. _sub = staticmethod(chebsub)
  1610. _mul = staticmethod(chebmul)
  1611. _div = staticmethod(chebdiv)
  1612. _pow = staticmethod(chebpow)
  1613. _val = staticmethod(chebval)
  1614. _int = staticmethod(chebint)
  1615. _der = staticmethod(chebder)
  1616. _fit = staticmethod(chebfit)
  1617. _line = staticmethod(chebline)
  1618. _roots = staticmethod(chebroots)
  1619. _fromroots = staticmethod(chebfromroots)
  1620. @classmethod
  1621. def interpolate(cls, func, deg, domain=None, args=()):
  1622. """Interpolate a function at the Chebyshev points of the first kind.
  1623. Returns the series that interpolates `func` at the Chebyshev points of
  1624. the first kind scaled and shifted to the `domain`. The resulting series
  1625. tends to a minmax approximation of `func` when the function is
  1626. continuous in the domain.
  1627. .. versionadded:: 1.14.0
  1628. Parameters
  1629. ----------
  1630. func : function
  1631. The function to be interpolated. It must be a function of a single
  1632. variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
  1633. extra arguments passed in the `args` parameter.
  1634. deg : int
  1635. Degree of the interpolating polynomial.
  1636. domain : {None, [beg, end]}, optional
  1637. Domain over which `func` is interpolated. The default is None, in
  1638. which case the domain is [-1, 1].
  1639. args : tuple, optional
  1640. Extra arguments to be used in the function call. Default is no
  1641. extra arguments.
  1642. Returns
  1643. -------
  1644. polynomial : Chebyshev instance
  1645. Interpolating Chebyshev instance.
  1646. Notes
  1647. -----
  1648. See `numpy.polynomial.chebfromfunction` for more details.
  1649. """
  1650. if domain is None:
  1651. domain = cls.domain
  1652. xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args)
  1653. coef = chebinterpolate(xfunc, deg)
  1654. return cls(coef, domain=domain)
  1655. # Virtual properties
  1656. domain = np.array(chebdomain)
  1657. window = np.array(chebdomain)
  1658. basis_name = 'T'