legendre.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  1. """
  2. Legendre Series (:mod: `numpy.polynomial.legendre`)
  3. ===================================================
  4. .. currentmodule:: numpy.polynomial.polynomial
  5. This module provides a number of objects (mostly functions) useful for
  6. dealing with Legendre series, including a `Legendre` 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. Constants
  11. ---------
  12. .. autosummary::
  13. :toctree: generated/
  14. legdomain Legendre series default domain, [-1,1].
  15. legzero Legendre series that evaluates identically to 0.
  16. legone Legendre series that evaluates identically to 1.
  17. legx Legendre series for the identity map, ``f(x) = x``.
  18. Arithmetic
  19. ----------
  20. .. autosummary::
  21. :toctree: generated/
  22. legadd add two Legendre series.
  23. legsub subtract one Legendre series from another.
  24. legmulx multiply a Legendre series in ``P_i(x)`` by ``x``.
  25. legmul multiply two Legendre series.
  26. legdiv divide one Legendre series by another.
  27. legpow raise a Legendre series to a positive integer power.
  28. legval evaluate a Legendre series at given points.
  29. legval2d evaluate a 2D Legendre series at given points.
  30. legval3d evaluate a 3D Legendre series at given points.
  31. leggrid2d evaluate a 2D Legendre series on a Cartesian product.
  32. leggrid3d evaluate a 3D Legendre series on a Cartesian product.
  33. Calculus
  34. --------
  35. .. autosummary::
  36. :toctree: generated/
  37. legder differentiate a Legendre series.
  38. legint integrate a Legendre series.
  39. Misc Functions
  40. --------------
  41. .. autosummary::
  42. :toctree: generated/
  43. legfromroots create a Legendre series with specified roots.
  44. legroots find the roots of a Legendre series.
  45. legvander Vandermonde-like matrix for Legendre polynomials.
  46. legvander2d Vandermonde-like matrix for 2D power series.
  47. legvander3d Vandermonde-like matrix for 3D power series.
  48. leggauss Gauss-Legendre quadrature, points and weights.
  49. legweight Legendre weight function.
  50. legcompanion symmetrized companion matrix in Legendre form.
  51. legfit least-squares fit returning a Legendre series.
  52. legtrim trim leading coefficients from a Legendre series.
  53. legline Legendre series representing given straight line.
  54. leg2poly convert a Legendre series to a polynomial.
  55. poly2leg convert a polynomial to a Legendre series.
  56. Classes
  57. -------
  58. Legendre A Legendre series class.
  59. See also
  60. --------
  61. numpy.polynomial.polynomial
  62. numpy.polynomial.chebyshev
  63. numpy.polynomial.laguerre
  64. numpy.polynomial.hermite
  65. numpy.polynomial.hermite_e
  66. """
  67. from __future__ import division, absolute_import, print_function
  68. import warnings
  69. import numpy as np
  70. import numpy.linalg as la
  71. from numpy.core.multiarray import normalize_axis_index
  72. from . import polyutils as pu
  73. from ._polybase import ABCPolyBase
  74. __all__ = [
  75. 'legzero', 'legone', 'legx', 'legdomain', 'legline', 'legadd',
  76. 'legsub', 'legmulx', 'legmul', 'legdiv', 'legpow', 'legval', 'legder',
  77. 'legint', 'leg2poly', 'poly2leg', 'legfromroots', 'legvander',
  78. 'legfit', 'legtrim', 'legroots', 'Legendre', 'legval2d', 'legval3d',
  79. 'leggrid2d', 'leggrid3d', 'legvander2d', 'legvander3d', 'legcompanion',
  80. 'leggauss', 'legweight']
  81. legtrim = pu.trimcoef
  82. def poly2leg(pol):
  83. """
  84. Convert a polynomial to a Legendre series.
  85. Convert an array representing the coefficients of a polynomial (relative
  86. to the "standard" basis) ordered from lowest degree to highest, to an
  87. array of the coefficients of the equivalent Legendre series, ordered
  88. from lowest to highest degree.
  89. Parameters
  90. ----------
  91. pol : array_like
  92. 1-D array containing the polynomial coefficients
  93. Returns
  94. -------
  95. c : ndarray
  96. 1-D array containing the coefficients of the equivalent Legendre
  97. series.
  98. See Also
  99. --------
  100. leg2poly
  101. Notes
  102. -----
  103. The easy way to do conversions between polynomial basis sets
  104. is to use the convert method of a class instance.
  105. Examples
  106. --------
  107. >>> from numpy import polynomial as P
  108. >>> p = P.Polynomial(np.arange(4))
  109. >>> p
  110. Polynomial([ 0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
  111. >>> c = P.Legendre(P.legendre.poly2leg(p.coef))
  112. >>> c
  113. Legendre([ 1. , 3.25, 1. , 0.75], domain=[-1, 1], window=[-1, 1])
  114. """
  115. [pol] = pu.as_series([pol])
  116. deg = len(pol) - 1
  117. res = 0
  118. for i in range(deg, -1, -1):
  119. res = legadd(legmulx(res), pol[i])
  120. return res
  121. def leg2poly(c):
  122. """
  123. Convert a Legendre series to a polynomial.
  124. Convert an array representing the coefficients of a Legendre series,
  125. ordered from lowest degree to highest, to an array of the coefficients
  126. of the equivalent polynomial (relative to the "standard" basis) ordered
  127. from lowest to highest degree.
  128. Parameters
  129. ----------
  130. c : array_like
  131. 1-D array containing the Legendre series coefficients, ordered
  132. from lowest order term to highest.
  133. Returns
  134. -------
  135. pol : ndarray
  136. 1-D array containing the coefficients of the equivalent polynomial
  137. (relative to the "standard" basis) ordered from lowest order term
  138. to highest.
  139. See Also
  140. --------
  141. poly2leg
  142. Notes
  143. -----
  144. The easy way to do conversions between polynomial basis sets
  145. is to use the convert method of a class instance.
  146. Examples
  147. --------
  148. >>> c = P.Legendre(range(4))
  149. >>> c
  150. Legendre([ 0., 1., 2., 3.], [-1., 1.])
  151. >>> p = c.convert(kind=P.Polynomial)
  152. >>> p
  153. Polynomial([-1. , -3.5, 3. , 7.5], [-1., 1.])
  154. >>> P.leg2poly(range(4))
  155. array([-1. , -3.5, 3. , 7.5])
  156. """
  157. from .polynomial import polyadd, polysub, polymulx
  158. [c] = pu.as_series([c])
  159. n = len(c)
  160. if n < 3:
  161. return c
  162. else:
  163. c0 = c[-2]
  164. c1 = c[-1]
  165. # i is the current degree of c1
  166. for i in range(n - 1, 1, -1):
  167. tmp = c0
  168. c0 = polysub(c[i - 2], (c1*(i - 1))/i)
  169. c1 = polyadd(tmp, (polymulx(c1)*(2*i - 1))/i)
  170. return polyadd(c0, polymulx(c1))
  171. #
  172. # These are constant arrays are of integer type so as to be compatible
  173. # with the widest range of other types, such as Decimal.
  174. #
  175. # Legendre
  176. legdomain = np.array([-1, 1])
  177. # Legendre coefficients representing zero.
  178. legzero = np.array([0])
  179. # Legendre coefficients representing one.
  180. legone = np.array([1])
  181. # Legendre coefficients representing the identity x.
  182. legx = np.array([0, 1])
  183. def legline(off, scl):
  184. """
  185. Legendre series whose graph is a straight line.
  186. Parameters
  187. ----------
  188. off, scl : scalars
  189. The specified line is given by ``off + scl*x``.
  190. Returns
  191. -------
  192. y : ndarray
  193. This module's representation of the Legendre series for
  194. ``off + scl*x``.
  195. See Also
  196. --------
  197. polyline, chebline
  198. Examples
  199. --------
  200. >>> import numpy.polynomial.legendre as L
  201. >>> L.legline(3,2)
  202. array([3, 2])
  203. >>> L.legval(-3, L.legline(3,2)) # should be -3
  204. -3.0
  205. """
  206. if scl != 0:
  207. return np.array([off, scl])
  208. else:
  209. return np.array([off])
  210. def legfromroots(roots):
  211. """
  212. Generate a Legendre series with given roots.
  213. The function returns the coefficients of the polynomial
  214. .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
  215. in Legendre form, where the `r_n` are the roots specified in `roots`.
  216. If a zero has multiplicity n, then it must appear in `roots` n times.
  217. For instance, if 2 is a root of multiplicity three and 3 is a root of
  218. multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
  219. roots can appear in any order.
  220. If the returned coefficients are `c`, then
  221. .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x)
  222. The coefficient of the last term is not generally 1 for monic
  223. polynomials in Legendre form.
  224. Parameters
  225. ----------
  226. roots : array_like
  227. Sequence containing the roots.
  228. Returns
  229. -------
  230. out : ndarray
  231. 1-D array of coefficients. If all roots are real then `out` is a
  232. real array, if some of the roots are complex, then `out` is complex
  233. even if all the coefficients in the result are real (see Examples
  234. below).
  235. See Also
  236. --------
  237. polyfromroots, chebfromroots, lagfromroots, hermfromroots,
  238. hermefromroots.
  239. Examples
  240. --------
  241. >>> import numpy.polynomial.legendre as L
  242. >>> L.legfromroots((-1,0,1)) # x^3 - x relative to the standard basis
  243. array([ 0. , -0.4, 0. , 0.4])
  244. >>> j = complex(0,1)
  245. >>> L.legfromroots((-j,j)) # x^2 + 1 relative to the standard basis
  246. array([ 1.33333333+0.j, 0.00000000+0.j, 0.66666667+0.j])
  247. """
  248. if len(roots) == 0:
  249. return np.ones(1)
  250. else:
  251. [roots] = pu.as_series([roots], trim=False)
  252. roots.sort()
  253. p = [legline(-r, 1) for r in roots]
  254. n = len(p)
  255. while n > 1:
  256. m, r = divmod(n, 2)
  257. tmp = [legmul(p[i], p[i+m]) for i in range(m)]
  258. if r:
  259. tmp[0] = legmul(tmp[0], p[-1])
  260. p = tmp
  261. n = m
  262. return p[0]
  263. def legadd(c1, c2):
  264. """
  265. Add one Legendre series to another.
  266. Returns the sum of two Legendre series `c1` + `c2`. The arguments
  267. are sequences of coefficients ordered from lowest order term to
  268. highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
  269. Parameters
  270. ----------
  271. c1, c2 : array_like
  272. 1-D arrays of Legendre series coefficients ordered from low to
  273. high.
  274. Returns
  275. -------
  276. out : ndarray
  277. Array representing the Legendre series of their sum.
  278. See Also
  279. --------
  280. legsub, legmulx, legmul, legdiv, legpow
  281. Notes
  282. -----
  283. Unlike multiplication, division, etc., the sum of two Legendre series
  284. is a Legendre series (without having to "reproject" the result onto
  285. the basis set) so addition, just like that of "standard" polynomials,
  286. is simply "component-wise."
  287. Examples
  288. --------
  289. >>> from numpy.polynomial import legendre as L
  290. >>> c1 = (1,2,3)
  291. >>> c2 = (3,2,1)
  292. >>> L.legadd(c1,c2)
  293. array([ 4., 4., 4.])
  294. """
  295. # c1, c2 are trimmed copies
  296. [c1, c2] = pu.as_series([c1, c2])
  297. if len(c1) > len(c2):
  298. c1[:c2.size] += c2
  299. ret = c1
  300. else:
  301. c2[:c1.size] += c1
  302. ret = c2
  303. return pu.trimseq(ret)
  304. def legsub(c1, c2):
  305. """
  306. Subtract one Legendre series from another.
  307. Returns the difference of two Legendre series `c1` - `c2`. The
  308. sequences of coefficients are from lowest order term to highest, i.e.,
  309. [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
  310. Parameters
  311. ----------
  312. c1, c2 : array_like
  313. 1-D arrays of Legendre series coefficients ordered from low to
  314. high.
  315. Returns
  316. -------
  317. out : ndarray
  318. Of Legendre series coefficients representing their difference.
  319. See Also
  320. --------
  321. legadd, legmulx, legmul, legdiv, legpow
  322. Notes
  323. -----
  324. Unlike multiplication, division, etc., the difference of two Legendre
  325. series is a Legendre series (without having to "reproject" the result
  326. onto the basis set) so subtraction, just like that of "standard"
  327. polynomials, is simply "component-wise."
  328. Examples
  329. --------
  330. >>> from numpy.polynomial import legendre as L
  331. >>> c1 = (1,2,3)
  332. >>> c2 = (3,2,1)
  333. >>> L.legsub(c1,c2)
  334. array([-2., 0., 2.])
  335. >>> L.legsub(c2,c1) # -C.legsub(c1,c2)
  336. array([ 2., 0., -2.])
  337. """
  338. # c1, c2 are trimmed copies
  339. [c1, c2] = pu.as_series([c1, c2])
  340. if len(c1) > len(c2):
  341. c1[:c2.size] -= c2
  342. ret = c1
  343. else:
  344. c2 = -c2
  345. c2[:c1.size] += c1
  346. ret = c2
  347. return pu.trimseq(ret)
  348. def legmulx(c):
  349. """Multiply a Legendre series by x.
  350. Multiply the Legendre series `c` by x, where x is the independent
  351. variable.
  352. Parameters
  353. ----------
  354. c : array_like
  355. 1-D array of Legendre series coefficients ordered from low to
  356. high.
  357. Returns
  358. -------
  359. out : ndarray
  360. Array representing the result of the multiplication.
  361. See Also
  362. --------
  363. legadd, legmul, legmul, legdiv, legpow
  364. Notes
  365. -----
  366. The multiplication uses the recursion relationship for Legendre
  367. polynomials in the form
  368. .. math::
  369. xP_i(x) = ((i + 1)*P_{i + 1}(x) + i*P_{i - 1}(x))/(2i + 1)
  370. Examples
  371. --------
  372. >>> from numpy.polynomial import legendre as L
  373. >>> L.legmulx([1,2,3])
  374. array([ 0.66666667, 2.2, 1.33333333, 1.8])
  375. """
  376. # c is a trimmed copy
  377. [c] = pu.as_series([c])
  378. # The zero series needs special treatment
  379. if len(c) == 1 and c[0] == 0:
  380. return c
  381. prd = np.empty(len(c) + 1, dtype=c.dtype)
  382. prd[0] = c[0]*0
  383. prd[1] = c[0]
  384. for i in range(1, len(c)):
  385. j = i + 1
  386. k = i - 1
  387. s = i + j
  388. prd[j] = (c[i]*j)/s
  389. prd[k] += (c[i]*i)/s
  390. return prd
  391. def legmul(c1, c2):
  392. """
  393. Multiply one Legendre series by another.
  394. Returns the product of two Legendre series `c1` * `c2`. The arguments
  395. are sequences of coefficients, from lowest order "term" to highest,
  396. e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
  397. Parameters
  398. ----------
  399. c1, c2 : array_like
  400. 1-D arrays of Legendre series coefficients ordered from low to
  401. high.
  402. Returns
  403. -------
  404. out : ndarray
  405. Of Legendre series coefficients representing their product.
  406. See Also
  407. --------
  408. legadd, legsub, legmulx, legdiv, legpow
  409. Notes
  410. -----
  411. In general, the (polynomial) product of two C-series results in terms
  412. that are not in the Legendre polynomial basis set. Thus, to express
  413. the product as a Legendre series, it is necessary to "reproject" the
  414. product onto said basis set, which may produce "unintuitive" (but
  415. correct) results; see Examples section below.
  416. Examples
  417. --------
  418. >>> from numpy.polynomial import legendre as L
  419. >>> c1 = (1,2,3)
  420. >>> c2 = (3,2)
  421. >>> P.legmul(c1,c2) # multiplication requires "reprojection"
  422. array([ 4.33333333, 10.4 , 11.66666667, 3.6 ])
  423. """
  424. # s1, s2 are trimmed copies
  425. [c1, c2] = pu.as_series([c1, c2])
  426. if len(c1) > len(c2):
  427. c = c2
  428. xs = c1
  429. else:
  430. c = c1
  431. xs = c2
  432. if len(c) == 1:
  433. c0 = c[0]*xs
  434. c1 = 0
  435. elif len(c) == 2:
  436. c0 = c[0]*xs
  437. c1 = c[1]*xs
  438. else:
  439. nd = len(c)
  440. c0 = c[-2]*xs
  441. c1 = c[-1]*xs
  442. for i in range(3, len(c) + 1):
  443. tmp = c0
  444. nd = nd - 1
  445. c0 = legsub(c[-i]*xs, (c1*(nd - 1))/nd)
  446. c1 = legadd(tmp, (legmulx(c1)*(2*nd - 1))/nd)
  447. return legadd(c0, legmulx(c1))
  448. def legdiv(c1, c2):
  449. """
  450. Divide one Legendre series by another.
  451. Returns the quotient-with-remainder of two Legendre series
  452. `c1` / `c2`. The arguments are sequences of coefficients from lowest
  453. order "term" to highest, e.g., [1,2,3] represents the series
  454. ``P_0 + 2*P_1 + 3*P_2``.
  455. Parameters
  456. ----------
  457. c1, c2 : array_like
  458. 1-D arrays of Legendre series coefficients ordered from low to
  459. high.
  460. Returns
  461. -------
  462. quo, rem : ndarrays
  463. Of Legendre series coefficients representing the quotient and
  464. remainder.
  465. See Also
  466. --------
  467. legadd, legsub, legmulx, legmul, legpow
  468. Notes
  469. -----
  470. In general, the (polynomial) division of one Legendre series by another
  471. results in quotient and remainder terms that are not in the Legendre
  472. polynomial basis set. Thus, to express these results as a Legendre
  473. series, it is necessary to "reproject" the results onto the Legendre
  474. basis set, which may produce "unintuitive" (but correct) results; see
  475. Examples section below.
  476. Examples
  477. --------
  478. >>> from numpy.polynomial import legendre as L
  479. >>> c1 = (1,2,3)
  480. >>> c2 = (3,2,1)
  481. >>> L.legdiv(c1,c2) # quotient "intuitive," remainder not
  482. (array([ 3.]), array([-8., -4.]))
  483. >>> c2 = (0,1,2,3)
  484. >>> L.legdiv(c2,c1) # neither "intuitive"
  485. (array([-0.07407407, 1.66666667]), array([-1.03703704, -2.51851852]))
  486. """
  487. # c1, c2 are trimmed copies
  488. [c1, c2] = pu.as_series([c1, c2])
  489. if c2[-1] == 0:
  490. raise ZeroDivisionError()
  491. lc1 = len(c1)
  492. lc2 = len(c2)
  493. if lc1 < lc2:
  494. return c1[:1]*0, c1
  495. elif lc2 == 1:
  496. return c1/c2[-1], c1[:1]*0
  497. else:
  498. quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype)
  499. rem = c1
  500. for i in range(lc1 - lc2, - 1, -1):
  501. p = legmul([0]*i + [1], c2)
  502. q = rem[-1]/p[-1]
  503. rem = rem[:-1] - q*p[:-1]
  504. quo[i] = q
  505. return quo, pu.trimseq(rem)
  506. def legpow(c, pow, maxpower=16):
  507. """Raise a Legendre series to a power.
  508. Returns the Legendre series `c` raised to the power `pow`. The
  509. argument `c` is a sequence of coefficients ordered from low to high.
  510. i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``
  511. Parameters
  512. ----------
  513. c : array_like
  514. 1-D array of Legendre series coefficients ordered from low to
  515. high.
  516. pow : integer
  517. Power to which the series will be raised
  518. maxpower : integer, optional
  519. Maximum power allowed. This is mainly to limit growth of the series
  520. to unmanageable size. Default is 16
  521. Returns
  522. -------
  523. coef : ndarray
  524. Legendre series of power.
  525. See Also
  526. --------
  527. legadd, legsub, legmulx, legmul, legdiv
  528. Examples
  529. --------
  530. """
  531. # c is a trimmed copy
  532. [c] = pu.as_series([c])
  533. power = int(pow)
  534. if power != pow or power < 0:
  535. raise ValueError("Power must be a non-negative integer.")
  536. elif maxpower is not None and power > maxpower:
  537. raise ValueError("Power is too large")
  538. elif power == 0:
  539. return np.array([1], dtype=c.dtype)
  540. elif power == 1:
  541. return c
  542. else:
  543. # This can be made more efficient by using powers of two
  544. # in the usual way.
  545. prd = c
  546. for i in range(2, power + 1):
  547. prd = legmul(prd, c)
  548. return prd
  549. def legder(c, m=1, scl=1, axis=0):
  550. """
  551. Differentiate a Legendre series.
  552. Returns the Legendre series coefficients `c` differentiated `m` times
  553. along `axis`. At each iteration the result is multiplied by `scl` (the
  554. scaling factor is for use in a linear change of variable). The argument
  555. `c` is an array of coefficients from low to high degree along each
  556. axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``
  557. while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +
  558. 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is
  559. ``y``.
  560. Parameters
  561. ----------
  562. c : array_like
  563. Array of Legendre series coefficients. If c is multidimensional the
  564. different axis correspond to different variables with the degree in
  565. each axis given by the corresponding index.
  566. m : int, optional
  567. Number of derivatives taken, must be non-negative. (Default: 1)
  568. scl : scalar, optional
  569. Each differentiation is multiplied by `scl`. The end result is
  570. multiplication by ``scl**m``. This is for use in a linear change of
  571. variable. (Default: 1)
  572. axis : int, optional
  573. Axis over which the derivative is taken. (Default: 0).
  574. .. versionadded:: 1.7.0
  575. Returns
  576. -------
  577. der : ndarray
  578. Legendre series of the derivative.
  579. See Also
  580. --------
  581. legint
  582. Notes
  583. -----
  584. In general, the result of differentiating a Legendre series does not
  585. resemble the same operation on a power series. Thus the result of this
  586. function may be "unintuitive," albeit correct; see Examples section
  587. below.
  588. Examples
  589. --------
  590. >>> from numpy.polynomial import legendre as L
  591. >>> c = (1,2,3,4)
  592. >>> L.legder(c)
  593. array([ 6., 9., 20.])
  594. >>> L.legder(c, 3)
  595. array([ 60.])
  596. >>> L.legder(c, scl=-1)
  597. array([ -6., -9., -20.])
  598. >>> L.legder(c, 2,-1)
  599. array([ 9., 60.])
  600. """
  601. c = np.array(c, ndmin=1, copy=1)
  602. if c.dtype.char in '?bBhHiIlLqQpP':
  603. c = c.astype(np.double)
  604. cnt, iaxis = [int(t) for t in [m, axis]]
  605. if cnt != m:
  606. raise ValueError("The order of derivation must be integer")
  607. if cnt < 0:
  608. raise ValueError("The order of derivation must be non-negative")
  609. if iaxis != axis:
  610. raise ValueError("The axis must be integer")
  611. iaxis = normalize_axis_index(iaxis, c.ndim)
  612. if cnt == 0:
  613. return c
  614. c = np.moveaxis(c, iaxis, 0)
  615. n = len(c)
  616. if cnt >= n:
  617. c = c[:1]*0
  618. else:
  619. for i in range(cnt):
  620. n = n - 1
  621. c *= scl
  622. der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
  623. for j in range(n, 2, -1):
  624. der[j - 1] = (2*j - 1)*c[j]
  625. c[j - 2] += c[j]
  626. if n > 1:
  627. der[1] = 3*c[2]
  628. der[0] = c[1]
  629. c = der
  630. c = np.moveaxis(c, 0, iaxis)
  631. return c
  632. def legint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
  633. """
  634. Integrate a Legendre series.
  635. Returns the Legendre series coefficients `c` integrated `m` times from
  636. `lbnd` along `axis`. At each iteration the resulting series is
  637. **multiplied** by `scl` and an integration constant, `k`, is added.
  638. The scaling factor is for use in a linear change of variable. ("Buyer
  639. beware": note that, depending on what one is doing, one may want `scl`
  640. to be the reciprocal of what one might expect; for more information,
  641. see the Notes section below.) The argument `c` is an array of
  642. coefficients from low to high degree along each axis, e.g., [1,2,3]
  643. represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]]
  644. represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) +
  645. 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
  646. Parameters
  647. ----------
  648. c : array_like
  649. Array of Legendre series coefficients. If c is multidimensional the
  650. different axis correspond to different variables with the degree in
  651. each axis given by the corresponding index.
  652. m : int, optional
  653. Order of integration, must be positive. (Default: 1)
  654. k : {[], list, scalar}, optional
  655. Integration constant(s). The value of the first integral at
  656. ``lbnd`` is the first value in the list, the value of the second
  657. integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
  658. default), all constants are set to zero. If ``m == 1``, a single
  659. scalar can be given instead of a list.
  660. lbnd : scalar, optional
  661. The lower bound of the integral. (Default: 0)
  662. scl : scalar, optional
  663. Following each integration the result is *multiplied* by `scl`
  664. before the integration constant is added. (Default: 1)
  665. axis : int, optional
  666. Axis over which the integral is taken. (Default: 0).
  667. .. versionadded:: 1.7.0
  668. Returns
  669. -------
  670. S : ndarray
  671. Legendre series coefficient array of the integral.
  672. Raises
  673. ------
  674. ValueError
  675. If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
  676. ``np.ndim(scl) != 0``.
  677. See Also
  678. --------
  679. legder
  680. Notes
  681. -----
  682. Note that the result of each integration is *multiplied* by `scl`.
  683. Why is this important to note? Say one is making a linear change of
  684. variable :math:`u = ax + b` in an integral relative to `x`. Then
  685. :math:`dx = du/a`, so one will need to set `scl` equal to
  686. :math:`1/a` - perhaps not what one would have first thought.
  687. Also note that, in general, the result of integrating a C-series needs
  688. to be "reprojected" onto the C-series basis set. Thus, typically,
  689. the result of this function is "unintuitive," albeit correct; see
  690. Examples section below.
  691. Examples
  692. --------
  693. >>> from numpy.polynomial import legendre as L
  694. >>> c = (1,2,3)
  695. >>> L.legint(c)
  696. array([ 0.33333333, 0.4 , 0.66666667, 0.6 ])
  697. >>> L.legint(c, 3)
  698. array([ 1.66666667e-02, -1.78571429e-02, 4.76190476e-02,
  699. -1.73472348e-18, 1.90476190e-02, 9.52380952e-03])
  700. >>> L.legint(c, k=3)
  701. array([ 3.33333333, 0.4 , 0.66666667, 0.6 ])
  702. >>> L.legint(c, lbnd=-2)
  703. array([ 7.33333333, 0.4 , 0.66666667, 0.6 ])
  704. >>> L.legint(c, scl=2)
  705. array([ 0.66666667, 0.8 , 1.33333333, 1.2 ])
  706. """
  707. c = np.array(c, ndmin=1, copy=1)
  708. if c.dtype.char in '?bBhHiIlLqQpP':
  709. c = c.astype(np.double)
  710. if not np.iterable(k):
  711. k = [k]
  712. cnt, iaxis = [int(t) for t in [m, axis]]
  713. if cnt != m:
  714. raise ValueError("The order of integration must be integer")
  715. if cnt < 0:
  716. raise ValueError("The order of integration must be non-negative")
  717. if len(k) > cnt:
  718. raise ValueError("Too many integration constants")
  719. if np.ndim(lbnd) != 0:
  720. raise ValueError("lbnd must be a scalar.")
  721. if np.ndim(scl) != 0:
  722. raise ValueError("scl must be a scalar.")
  723. if iaxis != axis:
  724. raise ValueError("The axis must be integer")
  725. iaxis = normalize_axis_index(iaxis, c.ndim)
  726. if cnt == 0:
  727. return c
  728. c = np.moveaxis(c, iaxis, 0)
  729. k = list(k) + [0]*(cnt - len(k))
  730. for i in range(cnt):
  731. n = len(c)
  732. c *= scl
  733. if n == 1 and np.all(c[0] == 0):
  734. c[0] += k[i]
  735. else:
  736. tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
  737. tmp[0] = c[0]*0
  738. tmp[1] = c[0]
  739. if n > 1:
  740. tmp[2] = c[1]/3
  741. for j in range(2, n):
  742. t = c[j]/(2*j + 1)
  743. tmp[j + 1] = t
  744. tmp[j - 1] -= t
  745. tmp[0] += k[i] - legval(lbnd, tmp)
  746. c = tmp
  747. c = np.moveaxis(c, 0, iaxis)
  748. return c
  749. def legval(x, c, tensor=True):
  750. """
  751. Evaluate a Legendre series at points x.
  752. If `c` is of length `n + 1`, this function returns the value:
  753. .. math:: p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x)
  754. The parameter `x` is converted to an array only if it is a tuple or a
  755. list, otherwise it is treated as a scalar. In either case, either `x`
  756. or its elements must support multiplication and addition both with
  757. themselves and with the elements of `c`.
  758. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
  759. `c` is multidimensional, then the shape of the result depends on the
  760. value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
  761. x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
  762. scalars have shape (,).
  763. Trailing zeros in the coefficients will be used in the evaluation, so
  764. they should be avoided if efficiency is a concern.
  765. Parameters
  766. ----------
  767. x : array_like, compatible object
  768. If `x` is a list or tuple, it is converted to an ndarray, otherwise
  769. it is left unchanged and treated as a scalar. In either case, `x`
  770. or its elements must support addition and multiplication with
  771. with themselves and with the elements of `c`.
  772. c : array_like
  773. Array of coefficients ordered so that the coefficients for terms of
  774. degree n are contained in c[n]. If `c` is multidimensional the
  775. remaining indices enumerate multiple polynomials. In the two
  776. dimensional case the coefficients may be thought of as stored in
  777. the columns of `c`.
  778. tensor : boolean, optional
  779. If True, the shape of the coefficient array is extended with ones
  780. on the right, one for each dimension of `x`. Scalars have dimension 0
  781. for this action. The result is that every column of coefficients in
  782. `c` is evaluated for every element of `x`. If False, `x` is broadcast
  783. over the columns of `c` for the evaluation. This keyword is useful
  784. when `c` is multidimensional. The default value is True.
  785. .. versionadded:: 1.7.0
  786. Returns
  787. -------
  788. values : ndarray, algebra_like
  789. The shape of the return value is described above.
  790. See Also
  791. --------
  792. legval2d, leggrid2d, legval3d, leggrid3d
  793. Notes
  794. -----
  795. The evaluation uses Clenshaw recursion, aka synthetic division.
  796. Examples
  797. --------
  798. """
  799. c = np.array(c, ndmin=1, copy=0)
  800. if c.dtype.char in '?bBhHiIlLqQpP':
  801. c = c.astype(np.double)
  802. if isinstance(x, (tuple, list)):
  803. x = np.asarray(x)
  804. if isinstance(x, np.ndarray) and tensor:
  805. c = c.reshape(c.shape + (1,)*x.ndim)
  806. if len(c) == 1:
  807. c0 = c[0]
  808. c1 = 0
  809. elif len(c) == 2:
  810. c0 = c[0]
  811. c1 = c[1]
  812. else:
  813. nd = len(c)
  814. c0 = c[-2]
  815. c1 = c[-1]
  816. for i in range(3, len(c) + 1):
  817. tmp = c0
  818. nd = nd - 1
  819. c0 = c[-i] - (c1*(nd - 1))/nd
  820. c1 = tmp + (c1*x*(2*nd - 1))/nd
  821. return c0 + c1*x
  822. def legval2d(x, y, c):
  823. """
  824. Evaluate a 2-D Legendre series at points (x, y).
  825. This function returns the values:
  826. .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * L_i(x) * L_j(y)
  827. The parameters `x` and `y` are converted to arrays only if they are
  828. tuples or a lists, otherwise they are treated as a scalars and they
  829. must have the same shape after conversion. In either case, either `x`
  830. and `y` or their elements must support multiplication and addition both
  831. with themselves and with the elements of `c`.
  832. If `c` is a 1-D array a one is implicitly appended to its shape to make
  833. it 2-D. The shape of the result will be c.shape[2:] + x.shape.
  834. Parameters
  835. ----------
  836. x, y : array_like, compatible objects
  837. The two dimensional series is evaluated at the points `(x, y)`,
  838. where `x` and `y` must have the same shape. If `x` or `y` is a list
  839. or tuple, it is first converted to an ndarray, otherwise it is left
  840. unchanged and if it isn't an ndarray it is treated as a scalar.
  841. c : array_like
  842. Array of coefficients ordered so that the coefficient of the term
  843. of multi-degree i,j is contained in ``c[i,j]``. If `c` has
  844. dimension greater than two the remaining indices enumerate multiple
  845. sets of coefficients.
  846. Returns
  847. -------
  848. values : ndarray, compatible object
  849. The values of the two dimensional Legendre series at points formed
  850. from pairs of corresponding values from `x` and `y`.
  851. See Also
  852. --------
  853. legval, leggrid2d, legval3d, leggrid3d
  854. Notes
  855. -----
  856. .. versionadded:: 1.7.0
  857. """
  858. try:
  859. x, y = np.array((x, y), copy=0)
  860. except Exception:
  861. raise ValueError('x, y are incompatible')
  862. c = legval(x, c)
  863. c = legval(y, c, tensor=False)
  864. return c
  865. def leggrid2d(x, y, c):
  866. """
  867. Evaluate a 2-D Legendre series on the Cartesian product of x and y.
  868. This function returns the values:
  869. .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * L_i(a) * L_j(b)
  870. where the points `(a, b)` consist of all pairs formed by taking
  871. `a` from `x` and `b` from `y`. The resulting points form a grid with
  872. `x` in the first dimension and `y` in the second.
  873. The parameters `x` and `y` are converted to arrays only if they are
  874. tuples or a lists, otherwise they are treated as a scalars. In either
  875. case, either `x` and `y` or their elements must support multiplication
  876. and addition both with themselves and with the elements of `c`.
  877. If `c` has fewer than two dimensions, ones are implicitly appended to
  878. its shape to make it 2-D. The shape of the result will be c.shape[2:] +
  879. x.shape + y.shape.
  880. Parameters
  881. ----------
  882. x, y : array_like, compatible objects
  883. The two dimensional series is evaluated at the points in the
  884. Cartesian product of `x` and `y`. If `x` or `y` is a list or
  885. tuple, it is first converted to an ndarray, otherwise it is left
  886. unchanged and, if it isn't an ndarray, it is treated as a scalar.
  887. c : array_like
  888. Array of coefficients ordered so that the coefficient of the term of
  889. multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
  890. greater than two the remaining indices enumerate multiple sets of
  891. coefficients.
  892. Returns
  893. -------
  894. values : ndarray, compatible object
  895. The values of the two dimensional Chebyshev series at points in the
  896. Cartesian product of `x` and `y`.
  897. See Also
  898. --------
  899. legval, legval2d, legval3d, leggrid3d
  900. Notes
  901. -----
  902. .. versionadded:: 1.7.0
  903. """
  904. c = legval(x, c)
  905. c = legval(y, c)
  906. return c
  907. def legval3d(x, y, z, c):
  908. """
  909. Evaluate a 3-D Legendre series at points (x, y, z).
  910. This function returns the values:
  911. .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z)
  912. The parameters `x`, `y`, and `z` are converted to arrays only if
  913. they are tuples or a lists, otherwise they are treated as a scalars and
  914. they must have the same shape after conversion. In either case, either
  915. `x`, `y`, and `z` or their elements must support multiplication and
  916. addition both with themselves and with the elements of `c`.
  917. If `c` has fewer than 3 dimensions, ones are implicitly appended to its
  918. shape to make it 3-D. The shape of the result will be c.shape[3:] +
  919. x.shape.
  920. Parameters
  921. ----------
  922. x, y, z : array_like, compatible object
  923. The three dimensional series is evaluated at the points
  924. `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
  925. any of `x`, `y`, or `z` is a list or tuple, it is first converted
  926. to an ndarray, otherwise it is left unchanged and if it isn't an
  927. ndarray it is treated as a scalar.
  928. c : array_like
  929. Array of coefficients ordered so that the coefficient of the term of
  930. multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
  931. greater than 3 the remaining indices enumerate multiple sets of
  932. coefficients.
  933. Returns
  934. -------
  935. values : ndarray, compatible object
  936. The values of the multidimensional polynomial on points formed with
  937. triples of corresponding values from `x`, `y`, and `z`.
  938. See Also
  939. --------
  940. legval, legval2d, leggrid2d, leggrid3d
  941. Notes
  942. -----
  943. .. versionadded:: 1.7.0
  944. """
  945. try:
  946. x, y, z = np.array((x, y, z), copy=0)
  947. except Exception:
  948. raise ValueError('x, y, z are incompatible')
  949. c = legval(x, c)
  950. c = legval(y, c, tensor=False)
  951. c = legval(z, c, tensor=False)
  952. return c
  953. def leggrid3d(x, y, z, c):
  954. """
  955. Evaluate a 3-D Legendre series on the Cartesian product of x, y, and z.
  956. This function returns the values:
  957. .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c)
  958. where the points `(a, b, c)` consist of all triples formed by taking
  959. `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
  960. a grid with `x` in the first dimension, `y` in the second, and `z` in
  961. the third.
  962. The parameters `x`, `y`, and `z` are converted to arrays only if they
  963. are tuples or a lists, otherwise they are treated as a scalars. In
  964. either case, either `x`, `y`, and `z` or their elements must support
  965. multiplication and addition both with themselves and with the elements
  966. of `c`.
  967. If `c` has fewer than three dimensions, ones are implicitly appended to
  968. its shape to make it 3-D. The shape of the result will be c.shape[3:] +
  969. x.shape + y.shape + z.shape.
  970. Parameters
  971. ----------
  972. x, y, z : array_like, compatible objects
  973. The three dimensional series is evaluated at the points in the
  974. Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
  975. list or tuple, it is first converted to an ndarray, otherwise it is
  976. left unchanged and, if it isn't an ndarray, it is treated as a
  977. scalar.
  978. c : array_like
  979. Array of coefficients ordered so that the coefficients for terms of
  980. degree i,j are contained in ``c[i,j]``. If `c` has dimension
  981. greater than two the remaining indices enumerate multiple sets of
  982. coefficients.
  983. Returns
  984. -------
  985. values : ndarray, compatible object
  986. The values of the two dimensional polynomial at points in the Cartesian
  987. product of `x` and `y`.
  988. See Also
  989. --------
  990. legval, legval2d, leggrid2d, legval3d
  991. Notes
  992. -----
  993. .. versionadded:: 1.7.0
  994. """
  995. c = legval(x, c)
  996. c = legval(y, c)
  997. c = legval(z, c)
  998. return c
  999. def legvander(x, deg):
  1000. """Pseudo-Vandermonde matrix of given degree.
  1001. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
  1002. `x`. The pseudo-Vandermonde matrix is defined by
  1003. .. math:: V[..., i] = L_i(x)
  1004. where `0 <= i <= deg`. The leading indices of `V` index the elements of
  1005. `x` and the last index is the degree of the Legendre polynomial.
  1006. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
  1007. array ``V = legvander(x, n)``, then ``np.dot(V, c)`` and
  1008. ``legval(x, c)`` are the same up to roundoff. This equivalence is
  1009. useful both for least squares fitting and for the evaluation of a large
  1010. number of Legendre series of the same degree and sample points.
  1011. Parameters
  1012. ----------
  1013. x : array_like
  1014. Array of points. The dtype is converted to float64 or complex128
  1015. depending on whether any of the elements are complex. If `x` is
  1016. scalar it is converted to a 1-D array.
  1017. deg : int
  1018. Degree of the resulting matrix.
  1019. Returns
  1020. -------
  1021. vander : ndarray
  1022. The pseudo-Vandermonde matrix. The shape of the returned matrix is
  1023. ``x.shape + (deg + 1,)``, where The last index is the degree of the
  1024. corresponding Legendre polynomial. The dtype will be the same as
  1025. the converted `x`.
  1026. """
  1027. ideg = int(deg)
  1028. if ideg != deg:
  1029. raise ValueError("deg must be integer")
  1030. if ideg < 0:
  1031. raise ValueError("deg must be non-negative")
  1032. x = np.array(x, copy=0, ndmin=1) + 0.0
  1033. dims = (ideg + 1,) + x.shape
  1034. dtyp = x.dtype
  1035. v = np.empty(dims, dtype=dtyp)
  1036. # Use forward recursion to generate the entries. This is not as accurate
  1037. # as reverse recursion in this application but it is more efficient.
  1038. v[0] = x*0 + 1
  1039. if ideg > 0:
  1040. v[1] = x
  1041. for i in range(2, ideg + 1):
  1042. v[i] = (v[i-1]*x*(2*i - 1) - v[i-2]*(i - 1))/i
  1043. return np.moveaxis(v, 0, -1)
  1044. def legvander2d(x, y, deg):
  1045. """Pseudo-Vandermonde matrix of given degrees.
  1046. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  1047. points `(x, y)`. The pseudo-Vandermonde matrix is defined by
  1048. .. math:: V[..., (deg[1] + 1)*i + j] = L_i(x) * L_j(y),
  1049. where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
  1050. `V` index the points `(x, y)` and the last index encodes the degrees of
  1051. the Legendre polynomials.
  1052. If ``V = legvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
  1053. correspond to the elements of a 2-D coefficient array `c` of shape
  1054. (xdeg + 1, ydeg + 1) in the order
  1055. .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
  1056. and ``np.dot(V, c.flat)`` and ``legval2d(x, y, c)`` will be the same
  1057. up to roundoff. This equivalence is useful both for least squares
  1058. fitting and for the evaluation of a large number of 2-D Legendre
  1059. series of the same degrees and sample points.
  1060. Parameters
  1061. ----------
  1062. x, y : array_like
  1063. Arrays of point coordinates, all of the same shape. The dtypes
  1064. will be converted to either float64 or complex128 depending on
  1065. whether any of the elements are complex. Scalars are converted to
  1066. 1-D arrays.
  1067. deg : list of ints
  1068. List of maximum degrees of the form [x_deg, y_deg].
  1069. Returns
  1070. -------
  1071. vander2d : ndarray
  1072. The shape of the returned matrix is ``x.shape + (order,)``, where
  1073. :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
  1074. as the converted `x` and `y`.
  1075. See Also
  1076. --------
  1077. legvander, legvander3d. legval2d, legval3d
  1078. Notes
  1079. -----
  1080. .. versionadded:: 1.7.0
  1081. """
  1082. ideg = [int(d) for d in deg]
  1083. is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
  1084. if is_valid != [1, 1]:
  1085. raise ValueError("degrees must be non-negative integers")
  1086. degx, degy = ideg
  1087. x, y = np.array((x, y), copy=0) + 0.0
  1088. vx = legvander(x, degx)
  1089. vy = legvander(y, degy)
  1090. v = vx[..., None]*vy[..., None,:]
  1091. return v.reshape(v.shape[:-2] + (-1,))
  1092. def legvander3d(x, y, z, deg):
  1093. """Pseudo-Vandermonde matrix of given degrees.
  1094. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  1095. points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
  1096. then The pseudo-Vandermonde matrix is defined by
  1097. .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = L_i(x)*L_j(y)*L_k(z),
  1098. where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
  1099. indices of `V` index the points `(x, y, z)` and the last index encodes
  1100. the degrees of the Legendre polynomials.
  1101. If ``V = legvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
  1102. of `V` correspond to the elements of a 3-D coefficient array `c` of
  1103. shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
  1104. .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
  1105. and ``np.dot(V, c.flat)`` and ``legval3d(x, y, z, c)`` will be the
  1106. same up to roundoff. This equivalence is useful both for least squares
  1107. fitting and for the evaluation of a large number of 3-D Legendre
  1108. series of the same degrees and sample points.
  1109. Parameters
  1110. ----------
  1111. x, y, z : array_like
  1112. Arrays of point coordinates, all of the same shape. The dtypes will
  1113. be converted to either float64 or complex128 depending on whether
  1114. any of the elements are complex. Scalars are converted to 1-D
  1115. arrays.
  1116. deg : list of ints
  1117. List of maximum degrees of the form [x_deg, y_deg, z_deg].
  1118. Returns
  1119. -------
  1120. vander3d : ndarray
  1121. The shape of the returned matrix is ``x.shape + (order,)``, where
  1122. :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will
  1123. be the same as the converted `x`, `y`, and `z`.
  1124. See Also
  1125. --------
  1126. legvander, legvander3d. legval2d, legval3d
  1127. Notes
  1128. -----
  1129. .. versionadded:: 1.7.0
  1130. """
  1131. ideg = [int(d) for d in deg]
  1132. is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
  1133. if is_valid != [1, 1, 1]:
  1134. raise ValueError("degrees must be non-negative integers")
  1135. degx, degy, degz = ideg
  1136. x, y, z = np.array((x, y, z), copy=0) + 0.0
  1137. vx = legvander(x, degx)
  1138. vy = legvander(y, degy)
  1139. vz = legvander(z, degz)
  1140. v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:]
  1141. return v.reshape(v.shape[:-3] + (-1,))
  1142. def legfit(x, y, deg, rcond=None, full=False, w=None):
  1143. """
  1144. Least squares fit of Legendre series to data.
  1145. Return the coefficients of a Legendre series of degree `deg` that is the
  1146. least squares fit to the data values `y` given at points `x`. If `y` is
  1147. 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
  1148. fits are done, one for each column of `y`, and the resulting
  1149. coefficients are stored in the corresponding columns of a 2-D return.
  1150. The fitted polynomial(s) are in the form
  1151. .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x),
  1152. where `n` is `deg`.
  1153. Parameters
  1154. ----------
  1155. x : array_like, shape (M,)
  1156. x-coordinates of the M sample points ``(x[i], y[i])``.
  1157. y : array_like, shape (M,) or (M, K)
  1158. y-coordinates of the sample points. Several data sets of sample
  1159. points sharing the same x-coordinates can be fitted at once by
  1160. passing in a 2D-array that contains one dataset per column.
  1161. deg : int or 1-D array_like
  1162. Degree(s) of the fitting polynomials. If `deg` is a single integer
  1163. all terms up to and including the `deg`'th term are included in the
  1164. fit. For NumPy versions >= 1.11.0 a list of integers specifying the
  1165. degrees of the terms to include may be used instead.
  1166. rcond : float, optional
  1167. Relative condition number of the fit. Singular values smaller than
  1168. this relative to the largest singular value will be ignored. The
  1169. default value is len(x)*eps, where eps is the relative precision of
  1170. the float type, about 2e-16 in most cases.
  1171. full : bool, optional
  1172. Switch determining nature of return value. When it is False (the
  1173. default) just the coefficients are returned, when True diagnostic
  1174. information from the singular value decomposition is also returned.
  1175. w : array_like, shape (`M`,), optional
  1176. Weights. If not None, the contribution of each point
  1177. ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
  1178. weights are chosen so that the errors of the products ``w[i]*y[i]``
  1179. all have the same variance. The default value is None.
  1180. .. versionadded:: 1.5.0
  1181. Returns
  1182. -------
  1183. coef : ndarray, shape (M,) or (M, K)
  1184. Legendre coefficients ordered from low to high. If `y` was
  1185. 2-D, the coefficients for the data in column k of `y` are in
  1186. column `k`. If `deg` is specified as a list, coefficients for
  1187. terms not included in the fit are set equal to zero in the
  1188. returned `coef`.
  1189. [residuals, rank, singular_values, rcond] : list
  1190. These values are only returned if `full` = True
  1191. resid -- sum of squared residuals of the least squares fit
  1192. rank -- the numerical rank of the scaled Vandermonde matrix
  1193. sv -- singular values of the scaled Vandermonde matrix
  1194. rcond -- value of `rcond`.
  1195. For more details, see `linalg.lstsq`.
  1196. Warns
  1197. -----
  1198. RankWarning
  1199. The rank of the coefficient matrix in the least-squares fit is
  1200. deficient. The warning is only raised if `full` = False. The
  1201. warnings can be turned off by
  1202. >>> import warnings
  1203. >>> warnings.simplefilter('ignore', RankWarning)
  1204. See Also
  1205. --------
  1206. chebfit, polyfit, lagfit, hermfit, hermefit
  1207. legval : Evaluates a Legendre series.
  1208. legvander : Vandermonde matrix of Legendre series.
  1209. legweight : Legendre weight function (= 1).
  1210. linalg.lstsq : Computes a least-squares fit from the matrix.
  1211. scipy.interpolate.UnivariateSpline : Computes spline fits.
  1212. Notes
  1213. -----
  1214. The solution is the coefficients of the Legendre series `p` that
  1215. minimizes the sum of the weighted squared errors
  1216. .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
  1217. where :math:`w_j` are the weights. This problem is solved by setting up
  1218. as the (typically) overdetermined matrix equation
  1219. .. math:: V(x) * c = w * y,
  1220. where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
  1221. coefficients to be solved for, `w` are the weights, and `y` are the
  1222. observed values. This equation is then solved using the singular value
  1223. decomposition of `V`.
  1224. If some of the singular values of `V` are so small that they are
  1225. neglected, then a `RankWarning` will be issued. This means that the
  1226. coefficient values may be poorly determined. Using a lower order fit
  1227. will usually get rid of the warning. The `rcond` parameter can also be
  1228. set to a value smaller than its default, but the resulting fit may be
  1229. spurious and have large contributions from roundoff error.
  1230. Fits using Legendre series are usually better conditioned than fits
  1231. using power series, but much can depend on the distribution of the
  1232. sample points and the smoothness of the data. If the quality of the fit
  1233. is inadequate splines may be a good alternative.
  1234. References
  1235. ----------
  1236. .. [1] Wikipedia, "Curve fitting",
  1237. https://en.wikipedia.org/wiki/Curve_fitting
  1238. Examples
  1239. --------
  1240. """
  1241. x = np.asarray(x) + 0.0
  1242. y = np.asarray(y) + 0.0
  1243. deg = np.asarray(deg)
  1244. # check arguments.
  1245. if deg.ndim > 1 or deg.dtype.kind not in 'iu' or deg.size == 0:
  1246. raise TypeError("deg must be an int or non-empty 1-D array of int")
  1247. if deg.min() < 0:
  1248. raise ValueError("expected deg >= 0")
  1249. if x.ndim != 1:
  1250. raise TypeError("expected 1D vector for x")
  1251. if x.size == 0:
  1252. raise TypeError("expected non-empty vector for x")
  1253. if y.ndim < 1 or y.ndim > 2:
  1254. raise TypeError("expected 1D or 2D array for y")
  1255. if len(x) != len(y):
  1256. raise TypeError("expected x and y to have same length")
  1257. if deg.ndim == 0:
  1258. lmax = deg
  1259. order = lmax + 1
  1260. van = legvander(x, lmax)
  1261. else:
  1262. deg = np.sort(deg)
  1263. lmax = deg[-1]
  1264. order = len(deg)
  1265. van = legvander(x, lmax)[:, deg]
  1266. # set up the least squares matrices in transposed form
  1267. lhs = van.T
  1268. rhs = y.T
  1269. if w is not None:
  1270. w = np.asarray(w) + 0.0
  1271. if w.ndim != 1:
  1272. raise TypeError("expected 1D vector for w")
  1273. if len(x) != len(w):
  1274. raise TypeError("expected x and w to have same length")
  1275. # apply weights. Don't use inplace operations as they
  1276. # can cause problems with NA.
  1277. lhs = lhs * w
  1278. rhs = rhs * w
  1279. # set rcond
  1280. if rcond is None:
  1281. rcond = len(x)*np.finfo(x.dtype).eps
  1282. # Determine the norms of the design matrix columns.
  1283. if issubclass(lhs.dtype.type, np.complexfloating):
  1284. scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
  1285. else:
  1286. scl = np.sqrt(np.square(lhs).sum(1))
  1287. scl[scl == 0] = 1
  1288. # Solve the least squares problem.
  1289. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond)
  1290. c = (c.T/scl).T
  1291. # Expand c to include non-fitted coefficients which are set to zero
  1292. if deg.ndim > 0:
  1293. if c.ndim == 2:
  1294. cc = np.zeros((lmax+1, c.shape[1]), dtype=c.dtype)
  1295. else:
  1296. cc = np.zeros(lmax+1, dtype=c.dtype)
  1297. cc[deg] = c
  1298. c = cc
  1299. # warn on rank reduction
  1300. if rank != order and not full:
  1301. msg = "The fit may be poorly conditioned"
  1302. warnings.warn(msg, pu.RankWarning, stacklevel=2)
  1303. if full:
  1304. return c, [resids, rank, s, rcond]
  1305. else:
  1306. return c
  1307. def legcompanion(c):
  1308. """Return the scaled companion matrix of c.
  1309. The basis polynomials are scaled so that the companion matrix is
  1310. symmetric when `c` is an Legendre basis polynomial. This provides
  1311. better eigenvalue estimates than the unscaled case and for basis
  1312. polynomials the eigenvalues are guaranteed to be real if
  1313. `numpy.linalg.eigvalsh` is used to obtain them.
  1314. Parameters
  1315. ----------
  1316. c : array_like
  1317. 1-D array of Legendre series coefficients ordered from low to high
  1318. degree.
  1319. Returns
  1320. -------
  1321. mat : ndarray
  1322. Scaled companion matrix of dimensions (deg, deg).
  1323. Notes
  1324. -----
  1325. .. versionadded:: 1.7.0
  1326. """
  1327. # c is a trimmed copy
  1328. [c] = pu.as_series([c])
  1329. if len(c) < 2:
  1330. raise ValueError('Series must have maximum degree of at least 1.')
  1331. if len(c) == 2:
  1332. return np.array([[-c[0]/c[1]]])
  1333. n = len(c) - 1
  1334. mat = np.zeros((n, n), dtype=c.dtype)
  1335. scl = 1./np.sqrt(2*np.arange(n) + 1)
  1336. top = mat.reshape(-1)[1::n+1]
  1337. bot = mat.reshape(-1)[n::n+1]
  1338. top[...] = np.arange(1, n)*scl[:n-1]*scl[1:n]
  1339. bot[...] = top
  1340. mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*(n/(2*n - 1))
  1341. return mat
  1342. def legroots(c):
  1343. """
  1344. Compute the roots of a Legendre series.
  1345. Return the roots (a.k.a. "zeros") of the polynomial
  1346. .. math:: p(x) = \\sum_i c[i] * L_i(x).
  1347. Parameters
  1348. ----------
  1349. c : 1-D array_like
  1350. 1-D array of coefficients.
  1351. Returns
  1352. -------
  1353. out : ndarray
  1354. Array of the roots of the series. If all the roots are real,
  1355. then `out` is also real, otherwise it is complex.
  1356. See Also
  1357. --------
  1358. polyroots, chebroots, lagroots, hermroots, hermeroots
  1359. Notes
  1360. -----
  1361. The root estimates are obtained as the eigenvalues of the companion
  1362. matrix, Roots far from the origin of the complex plane may have large
  1363. errors due to the numerical instability of the series for such values.
  1364. Roots with multiplicity greater than 1 will also show larger errors as
  1365. the value of the series near such points is relatively insensitive to
  1366. errors in the roots. Isolated roots near the origin can be improved by
  1367. a few iterations of Newton's method.
  1368. The Legendre series basis polynomials aren't powers of ``x`` so the
  1369. results of this function may seem unintuitive.
  1370. Examples
  1371. --------
  1372. >>> import numpy.polynomial.legendre as leg
  1373. >>> leg.legroots((1, 2, 3, 4)) # 4L_3 + 3L_2 + 2L_1 + 1L_0, all real roots
  1374. array([-0.85099543, -0.11407192, 0.51506735])
  1375. """
  1376. # c is a trimmed copy
  1377. [c] = pu.as_series([c])
  1378. if len(c) < 2:
  1379. return np.array([], dtype=c.dtype)
  1380. if len(c) == 2:
  1381. return np.array([-c[0]/c[1]])
  1382. m = legcompanion(c)
  1383. r = la.eigvals(m)
  1384. r.sort()
  1385. return r
  1386. def leggauss(deg):
  1387. """
  1388. Gauss-Legendre quadrature.
  1389. Computes the sample points and weights for Gauss-Legendre quadrature.
  1390. These sample points and weights will correctly integrate polynomials of
  1391. degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
  1392. the weight function :math:`f(x) = 1`.
  1393. Parameters
  1394. ----------
  1395. deg : int
  1396. Number of sample points and weights. It must be >= 1.
  1397. Returns
  1398. -------
  1399. x : ndarray
  1400. 1-D ndarray containing the sample points.
  1401. y : ndarray
  1402. 1-D ndarray containing the weights.
  1403. Notes
  1404. -----
  1405. .. versionadded:: 1.7.0
  1406. The results have only been tested up to degree 100, higher degrees may
  1407. be problematic. The weights are determined by using the fact that
  1408. .. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k))
  1409. where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
  1410. is the k'th root of :math:`L_n`, and then scaling the results to get
  1411. the right value when integrating 1.
  1412. """
  1413. ideg = int(deg)
  1414. if ideg != deg or ideg < 1:
  1415. raise ValueError("deg must be a non-negative integer")
  1416. # first approximation of roots. We use the fact that the companion
  1417. # matrix is symmetric in this case in order to obtain better zeros.
  1418. c = np.array([0]*deg + [1])
  1419. m = legcompanion(c)
  1420. x = la.eigvalsh(m)
  1421. # improve roots by one application of Newton
  1422. dy = legval(x, c)
  1423. df = legval(x, legder(c))
  1424. x -= dy/df
  1425. # compute the weights. We scale the factor to avoid possible numerical
  1426. # overflow.
  1427. fm = legval(x, c[1:])
  1428. fm /= np.abs(fm).max()
  1429. df /= np.abs(df).max()
  1430. w = 1/(fm * df)
  1431. # for Legendre we can also symmetrize
  1432. w = (w + w[::-1])/2
  1433. x = (x - x[::-1])/2
  1434. # scale w to get the right value
  1435. w *= 2. / w.sum()
  1436. return x, w
  1437. def legweight(x):
  1438. """
  1439. Weight function of the Legendre polynomials.
  1440. The weight function is :math:`1` and the interval of integration is
  1441. :math:`[-1, 1]`. The Legendre polynomials are orthogonal, but not
  1442. normalized, with respect to this weight function.
  1443. Parameters
  1444. ----------
  1445. x : array_like
  1446. Values at which the weight function will be computed.
  1447. Returns
  1448. -------
  1449. w : ndarray
  1450. The weight function at `x`.
  1451. Notes
  1452. -----
  1453. .. versionadded:: 1.7.0
  1454. """
  1455. w = x*0.0 + 1.0
  1456. return w
  1457. #
  1458. # Legendre series class
  1459. #
  1460. class Legendre(ABCPolyBase):
  1461. """A Legendre series class.
  1462. The Legendre class provides the standard Python numerical methods
  1463. '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
  1464. attributes and methods listed in the `ABCPolyBase` documentation.
  1465. Parameters
  1466. ----------
  1467. coef : array_like
  1468. Legendre coefficients in order of increasing degree, i.e.,
  1469. ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``.
  1470. domain : (2,) array_like, optional
  1471. Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
  1472. to the interval ``[window[0], window[1]]`` by shifting and scaling.
  1473. The default value is [-1, 1].
  1474. window : (2,) array_like, optional
  1475. Window, see `domain` for its use. The default value is [-1, 1].
  1476. .. versionadded:: 1.6.0
  1477. """
  1478. # Virtual Functions
  1479. _add = staticmethod(legadd)
  1480. _sub = staticmethod(legsub)
  1481. _mul = staticmethod(legmul)
  1482. _div = staticmethod(legdiv)
  1483. _pow = staticmethod(legpow)
  1484. _val = staticmethod(legval)
  1485. _int = staticmethod(legint)
  1486. _der = staticmethod(legder)
  1487. _fit = staticmethod(legfit)
  1488. _line = staticmethod(legline)
  1489. _roots = staticmethod(legroots)
  1490. _fromroots = staticmethod(legfromroots)
  1491. # Virtual properties
  1492. nickname = 'leg'
  1493. domain = np.array(legdomain)
  1494. window = np.array(legdomain)
  1495. basis_name = 'P'