hermite.py 51 KB

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