legendre.py 51 KB

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