hermite_e.py 52 KB

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