def modelLine(self, theta, line=0, order=-1): """ Get only a single line. Update this to plot a continuous line rather than discretely at the same values of wavelengths. """ noise, center, scale, herm = self.unpackTheta(theta) # Shift and scale lambdas to evaluation points lamEv = (self.lam[:, np.newaxis] - center) / scale lamEdgeEv = (self.lamEdge[:, np.newaxis] - center) / scale # Evaluate gaussian functions gauss = np.exp(-lamEv**2 / 2.) gaussEdge = np.exp(-lamEdgeEv**2 / 2.) hn = np.zeros(lamEv.shape) hnEdge = np.zeros(lamEdgeEv.shape) i = line if order > len(herm[i]): order = len(herm[i]) hn[:, i] = hermeval(lamEv[:, i], herm[i]) * gauss[:, i] hnEdge[:, i] = hermeval(lamEdgeEv[:, i], herm[i]) * gaussEdge[:, i] # Compute integral over finite pixel size hnEv = (4 * hn + hnEdge[1:] + hnEdge[:-1]) / 6.0 * self.dlam / scale[np.newaxis, :] return np.sum(hnEv, axis=1)
def test_hermemul(self) : # check values of result for i in range(5) : pol1 = [0]*i + [1] val1 = herme.hermeval(self.x, pol1) for j in range(5) : msg = "At i=%d, j=%d" % (i,j) pol2 = [0]*j + [1] val2 = herme.hermeval(self.x, pol2) pol3 = herme.hermemul(pol1, pol2) val3 = herme.hermeval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1*val2, err_msg=msg)
def test_hermemul(self): # check values of result for i in range(5): pol1 = [0] * i + [1] val1 = herme.hermeval(self.x, pol1) for j in range(5): msg = "At i=%d, j=%d" % (i, j) pol2 = [0] * j + [1] val2 = herme.hermeval(self.x, pol2) pol3 = herme.hermemul(pol1, pol2) val3 = herme.hermeval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1 * val2, err_msg=msg)
def q(i, j): ''' copmute coefficient q_{ij} Set up Gauss-Hermite quadrature, weighting function is exp^{-x^2} ''' x, w = H.hermegauss(20) Q = sum([ w[ldx] * sum([ w[kdx] * Q_FEM_quad[ldx * 20 + kdx] * H.hermeval(x[kdx], Phi(i)) for kdx in range(20) ]) * H.hermeval(x[ldx], Phi(j)) for ldx in range(20) ]) q = Q / (2 * np.pi * factorial(i) * factorial(j)) return q
def test_hermevander(self) : # check for 1d x x = np.arange(3) v = herme.hermevander(x, 3) assert_(v.shape == (3,4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[...,i], herme.hermeval(x, coef)) # check for 2d x x = np.array([[1,2],[3,4],[5,6]]) v = herme.hermevander(x, 3) assert_(v.shape == (3,2,4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[...,i], herme.hermeval(x, coef))
def weights(dim, degree): # 1D sigma-points (x) and weights (w) x, w = hermegauss(degree) # hermegauss() provides weights that cause posdef errors w = factorial(degree) / (degree**2 * hermeval(x, [0] * (degree - 1) + [1])**2) return np.prod(cartesian([w] * dim), axis=1)
def test_hermevander(self): # check for 1d x x = np.arange(3) v = herme.hermevander(x, 3) assert_(v.shape == (3, 4)) for i in range(4): coef = [0] * i + [1] assert_almost_equal(v[..., i], herme.hermeval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = herme.hermevander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4): coef = [0] * i + [1] assert_almost_equal(v[..., i], herme.hermeval(x, coef))
def MollifyQuad(theta, c_j, a_n, x): """ Mollify the spectral reconstruction of a discontinuous function to reduce the effect of Gibbs phenomenon. Perform a real-space convolution of a spectral reconstruction with an adaptive unit-mass mollifier. Parameters ---------- theta : float free parameter to vary in the range 0 < theta < 1 c_j : 1D array, Array containing x positions of the discontinuities in the data a_n : 1D array, shape = (N+1,) N - highest order in the Chebyshev expansion vector of Chebyshev expansion coefficients x : 1D array, 1D grid of points in real space, where the function is evaluated Returns ---------- convolution : 1D array, shape = (len(x),) real space mollified representation of a discontinuous function """ N = a_n.shape[0] - 1 offset = x convolution = np.empty(len(x)) I_N = lambda y: T.chebval(y, a_n) I_Nf = lambda y: I_N(y) if -1 <= y <= 1 else 0 for idx, off_x in enumerate(offset): c_jx = c_j - off_x dx = lambda y: sqrt(theta * N * min(abs(y - c) for c in c_jx)) var = lambda y: N / (2 * theta * dx(y)) p_N = lambda y: (theta**2) * dx(y) * N j_max = int(np.amax(np.frompyfunc(p_N, 1, 1)(x))) h_j = np.zeros(2 * (j_max + 1)) for j in range(j_max + 1): h_j[2 * j] = ((-1)**j) / ((4**j) * factorial(j)) hermite = lambda y: H.hermeval(sqrt(var(y)) * y, h_j) expon = lambda y: (1. / sqrt(theta * N * dx(y))) * exp(-var(y) * (y**2)) phi = lambda y: hermite(y) * expon(y) phif = lambda y: phi(y - off_x) norm = quad(phi, -1.0, 1.0)[0] convfunc = lambda y: (phif(y) * I_Nf(y)) convolution[idx] = (1 / norm) * quad(convfunc, -1.0, 1.0)[0] return convolution
def __call__(self): ## Generate values of a hermite polynomial of the given order at the values ## of a fractional Gaussian Noise with the specified hurst index. increments = hermeval(fgn.__call__(self), self.__coef) ## The renorm-group transformation, without the renormalisation by the n^{-H} increments = np.cumsum(increments)[ self.__K - 1::self.__K] ## / ( self.__K ** self.__H ) return self.__t, np.concatenate( ([0], increments / np.max(np.abs(increments))))
def test_hermefit(self): def f(x): return x * (x - 1) * (x - 2) # Test exceptions assert_raises(ValueError, herme.hermefit, [1], [1], -1) assert_raises(TypeError, herme.hermefit, [[1]], [1], 0) assert_raises(TypeError, herme.hermefit, [], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0) assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = herme.hermefit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) # coef4 = herme.hermefit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # coef2d = herme.hermefit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = herme.hermefit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(herme.hermefit(x, x, 1), [0, 1])
def test_hermefit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, herme.hermefit, [1], [1], -1) assert_raises(TypeError, herme.hermefit, [[1]], [1], 0) assert_raises(TypeError, herme.hermefit, [], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0) assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1,1]) # Test fit x = np.linspace(0,2) y = f(x) # coef3 = herme.hermefit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) # coef4 = herme.hermefit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # coef2d = herme.hermefit(x, np.array([y,y]).T, 3) assert_almost_equal(coef2d, np.array([coef3,coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = herme.hermefit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = herme.hermefit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(herme.hermefit(x, x, 1), [0, 1])
def test_hermeval(self): #check empty input assert_equal(herme.hermeval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [polyval(x, c) for c in Helist] for i in range(10): msg = "At i=%d" % i tgt = y[i] res = herme.hermeval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3): dims = [2]*i x = np.zeros(dims) assert_equal(herme.hermeval(x, [1]).shape, dims) assert_equal(herme.hermeval(x, [1, 0]).shape, dims) assert_equal(herme.hermeval(x, [1, 0, 0]).shape, dims)
def test_hermefromroots(self) : res = herme.hermefromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1,5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) pol = herme.hermefromroots(roots) res = herme.hermeval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(herme.herme2poly(pol)[-1], 1) assert_almost_equal(res, tgt)
def test_hermeval(self): #check empty input assert_equal(herme.hermeval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [polyval(x, c) for c in Helist] for i in range(10): msg = "At i=%d" % i tgt = y[i] res = herme.hermeval(x, [0] * i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3): dims = [2] * i x = np.zeros(dims) assert_equal(herme.hermeval(x, [1]).shape, dims) assert_equal(herme.hermeval(x, [1, 0]).shape, dims) assert_equal(herme.hermeval(x, [1, 0, 0]).shape, dims)
def test_hermefromroots(self): res = herme.hermefromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5): roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2]) pol = herme.hermefromroots(roots) res = herme.hermeval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(herme.herme2poly(pol)[-1], 1) assert_almost_equal(res, tgt)
def gabor_k(k, grid_x, xi0=np.pi * 3 / 4, sigma0=.5, scale=0): xi = xi0 / 2**scale sigma = sigma0 * 2**scale k_choose_j = binom(k, np.arange(k + 1)) minus_one_power = (-1)**np.arange(k + 1) i_xi_power = (1j * xi * sigma)**(k - np.arange(k + 1)) herm_coef = k_choose_j * minus_one_power * i_xi_power hermite_eval = hermeval(grid_x / sigma, herm_coef) gauss = np.exp(-.5 * (grid_x / sigma)**2) / np.sqrt( 2 * np.pi * sigma**2) / sigma**k wave = np.exp(1j * xi * grid_x) return hermite_eval * gauss * wave
def _column_feats(self, X, shift): """ Apply Hermite function evaluations of degrees 0..`degree` differentiated `shift` times. When applied to the column `X` of shape(n,), the resulting array has shape(n, (degree + 1)). """ assert ndim(X) == 1 # this will have dimension (d,) + shape(X) coeffs = np.identity(self._degree + shift + 1)[:, shift:] feats = ((-1)**shift) * hermeval(X, coeffs) * np.exp(-X * X / 2) # send the first dimension to the end return transpose(feats)
def get_quadrature_weights( n_features: int, degree: int = 3, ) -> Array: """Generate normalizers for MCMC samples""" # 1D sigma-points (x) and weights (w) x, w = hermegauss(degree) # hermegauss() provides weights that cause posdef errors w = factorial(degree) / (degree**2 * hermeval(x, [0] * (degree - 1) + [1])**2) return jnp.prod(cartesian([w] * n_features), axis=1)
def test_hermeval(self) : def f(x) : return x*(x**2 - 1) #check empty input assert_equal(herme.hermeval([], [1]).size, 0) #check normal input) for i in range(10) : msg = "At i=%d" % i ser = np.zeros tgt = self.y[i] res = herme.hermeval(self.x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(herme.hermeval(x, [1]).shape, dims) assert_equal(herme.hermeval(x, [1,0]).shape, dims) assert_equal(herme.hermeval(x, [1,0,0]).shape, dims)
def test_consistent_eval(self): degree = 10 n_points = 10 quad = hm.Quad.gauss_hermite(n_points) nodes_scipy, _ = herm.hermegauss(n_points) for i in range(degree): coeffs = np.zeros(degree + 1) coeffs[i] = 1 factor = math.sqrt(math.factorial(i)) hi_nodes_scipy = herm.hermeval(nodes_scipy, coeffs) hi_nodes = quad.eval(coeffs) diff = sum(abs(hi_nodes_scipy / factor - hi_nodes)) self.assertAlmostEqual(diff, 0)
def modelPredict(self, theta): """ Full prediction given theta """ # issue: scale is sometimes coming out as ~9e-5 in PolyChord and this gives overflows... noise, center, scale, herm = self.unpackTheta(theta) # Shift and scale lambdas to evaluation points lamEv = (self.lam[:, np.newaxis] - center) / scale lamEdgeEv = (self.lamEdge[:, np.newaxis] - center) / scale gauss = np.exp(-lamEv**2 / 2.) gaussEdge = np.exp(-lamEdgeEv**2 / 2.) hn = np.zeros(lamEv.shape) hnEdge = np.zeros(lamEdgeEv.shape) # Compute hermite functions to model lineData for i in np.arange(self.nfit): hn[:, i] = hermeval(lamEv[:, i], herm[i]) * gauss[:, i] ## hnEdge[:, i] = hermeval(lamEdgeEv[:, i], herm[i]) * gaussEdge[:, i] # Compute integral over finite pixel size hnEv = (4 * hn + hnEdge[1:] + hnEdge[:-1]) / 6.0 * self.dlam / scale[np.newaxis, :] # Evaluate noise as 2nd order Legendre fit if self.noiseParams == 1: noiseEv = noise[0] elif self.noiseParams == 3: noiseEv = noise[0] + noise[1] * self.lamNorm + noise[2] * ( 3 * self.lamNorm**2 - 1) / 2 # Sum over all lineData pred = noiseEv + np.sum(hnEv, axis=1) return pred
def hermite_measures(_points, _degree): """ Evaluation of the first p=_dimension Hermite polynomials `[He_0(y), He_1(y), ..., He_{p-1}(y)]` on each point `y` in `_points`. """ num_samples, num_assets, num_steps = _points.shape tmp = hermeval( _points, np.eye(_degree + 1)) #NOTE: The Hermite polynomials are NOT normalized. assert tmp.shape == (_degree + 1, num_samples, num_assets, num_steps) mIs = list(multiIndices(_degree, num_assets)) assert len(mIs) == comb(_degree + num_assets, num_assets) j = np.arange(num_assets) ret = np.empty((len(mIs), num_samples, num_steps)) for i, mI in enumerate(mIs): ret[i] = np.prod(tmp[mI, :, j, :], axis=0) return ret.T
def Hermite(data, basis_order): from numpy.polynomial.hermite_e import hermeval #importing hermeval from hermite class if data.ndim == 2: data = data[:, :, np.newaxis] n, m, l = data.shape psi_data = data if basis_order > 1: psi_data = np.append(psi_data, np.ones((1, m, l)), axis=0) for i in np.arange(2, basis_order + 1): c = np.zeros(i + 1) # vector of coefficients of size i+1 c[i] = 1 # 1 at index n+1 for extracting H^i psi_data = np.append(psi_data, hermeval(data, c), axis=0) #appending H^i to psi # psi_data = np.append(psi_data,herm(data,i),axis = 0) return psi_data
def weights(dim, degree=3): """ Gauss-Hermite quadrature weights. Parameters ---------- dim : int Dimension of the input random variable. degree : int, optional Degree of the integration rule. Returns ------- : (num_points, ) ndarray GH quadrature weights of given degree. """ # 1D sigma-points (x) and weights (w) x, w = hermegauss(degree) # hermegauss() provides weights that cause posdef errors w = factorial(degree) / (degree**2 * hermeval(x, [0] * (degree - 1) + [1])**2) return np.prod(cartesian([w] * dim), axis=1)
def test_hermefit(self): def f(x): return x * (x - 1) * (x - 2) def f2(x): return x**4 + x**2 + 1 # Test exceptions assert_raises(ValueError, herme.hermefit, [1], [1], -1) assert_raises(TypeError, herme.hermefit, [[1]], [1], 0) assert_raises(TypeError, herme.hermefit, [], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0) assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1, 1]) assert_raises(ValueError, herme.hermefit, [1], [1], [ -1, ]) assert_raises(ValueError, herme.hermefit, [1], [1], [2, -1, 6]) assert_raises(TypeError, herme.hermefit, [1], [1], []) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = herme.hermefit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) coef3 = herme.hermefit(x, y, [0, 1, 2, 3]) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) # coef4 = herme.hermefit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) coef4 = herme.hermefit(x, y, [0, 1, 2, 3, 4]) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # check things still work if deg is not in strict increasing coef4 = herme.hermefit(x, y, [2, 3, 4, 1, 0]) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # coef2d = herme.hermefit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) coef2d = herme.hermefit(x, np.array([y, y]).T, [0, 1, 2, 3]) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = herme.hermefit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) wcoef3 = herme.hermefit(x, yw, [0, 1, 2, 3], w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(herme.hermefit(x, x, 1), [0, 1]) assert_almost_equal(herme.hermefit(x, x, [0, 1]), [0, 1]) # test fitting only even Legendre polynomials x = np.linspace(-1, 1) y = f2(x) coef1 = herme.hermefit(x, y, 4) assert_almost_equal(herme.hermeval(x, coef1), y) coef2 = herme.hermefit(x, y, [0, 2, 4]) assert_almost_equal(herme.hermeval(x, coef2), y) assert_almost_equal(coef1, coef2)
def test_hermeint(self): # check exceptions assert_raises(TypeError, herme.hermeint, [0], .5) assert_raises(ValueError, herme.hermeint, [0], -1) assert_raises(ValueError, herme.hermeint, [0], 1, [0, 0]) assert_raises(ValueError, herme.hermeint, [0], lbnd=[0]) assert_raises(ValueError, herme.hermeint, [0], scl=[0]) assert_raises(TypeError, herme.hermeint, [0], axis=.5) # test integration of zero polynomial for i in range(2, 5): k = [0] * (i - 2) + [1] res = herme.hermeint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5): scl = i + 1 pol = [0] * i + [1] tgt = [i] + [0] * i + [1 / scl] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i]) res = herme.herme2poly(hermeint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5): scl = i + 1 pol = [0] * i + [1] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i], lbnd=-1) assert_almost_equal(herme.hermeval(-1, hermeint), i) # check single integration with integration constant and scaling for i in range(5): scl = i + 1 pol = [0] * i + [1] tgt = [i] + [0] * i + [2 / scl] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i], scl=2) res = herme.herme2poly(hermeint) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = herme.hermeint(tgt, m=1) res = herme.hermeint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = herme.hermeint(tgt, m=1, k=[k]) res = herme.hermeint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = herme.hermeint(tgt, m=1, k=[k], lbnd=-1) res = herme.hermeint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = herme.hermeint(tgt, m=1, k=[k], scl=2) res = herme.hermeint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt))
def product3_herm(i,j,l): #compute \Phi_i*\Phi_j*\Phi_l return lambda x: H.hermeval(x, H.hermemul(H.hermemul(Phi(i),Phi(j)),Phi(l)))
def Q(i, x): return H.hermeval(x, coef[:(i + 1)])
def __call__(self, xi, coefficients): return hermite_e.hermeval(xi, coefficients)
def test_hermeint(self) : # check exceptions assert_raises(ValueError, herme.hermeint, [0], .5) assert_raises(ValueError, herme.hermeint, [0], -1) assert_raises(ValueError, herme.hermeint, [0], 1, [0,0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = herme.hermeint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i]) res = herme.herme2poly(hermeint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i], lbnd=-1) assert_almost_equal(herme.hermeval(-1, hermeint), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i], scl=2) res = herme.herme2poly(hermeint) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1) res = herme.hermeint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k]) res = herme.hermeint(pol, m=j, k=range(j)) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k], lbnd=-1) res = herme.hermeint(pol, m=j, k=range(j), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k], scl=2) res = herme.hermeint(pol, m=j, k=range(j), scl=2) assert_almost_equal(trim(res), trim(tgt))
def q(i,j): x, w=H.hermegauss(20) Q=sum([w[ldx]*sum([w[kdx] * Q_FEM_quad[ldx*20+kdx] * H.hermeval(x[kdx],Phi(i)) for kdx in range(20)])*H.hermeval(x[ldx],Phi(j)) for ldx in range(20)]) q= Q/(2*np.pi*factorial(i)*factorial(j)) return q
def test_hermefit(self): def f(x): return x*(x - 1)*(x - 2) def f2(x): return x**4 + x**2 + 1 # Test exceptions assert_raises(ValueError, herme.hermefit, [1], [1], -1) assert_raises(TypeError, herme.hermefit, [[1]], [1], 0) assert_raises(TypeError, herme.hermefit, [], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0) assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1, 1]) assert_raises(ValueError, herme.hermefit, [1], [1], [-1,]) assert_raises(ValueError, herme.hermefit, [1], [1], [2, -1, 6]) assert_raises(TypeError, herme.hermefit, [1], [1], []) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = herme.hermefit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) coef3 = herme.hermefit(x, y, [0, 1, 2, 3]) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) # coef4 = herme.hermefit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) coef4 = herme.hermefit(x, y, [0, 1, 2, 3, 4]) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # check things still work if deg is not in strict increasing coef4 = herme.hermefit(x, y, [2, 3, 4, 1, 0]) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # coef2d = herme.hermefit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) coef2d = herme.hermefit(x, np.array([y, y]).T, [0, 1, 2, 3]) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = herme.hermefit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) wcoef3 = herme.hermefit(x, yw, [0, 1, 2, 3], w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(herme.hermefit(x, x, 1), [0, 1]) assert_almost_equal(herme.hermefit(x, x, [0, 1]), [0, 1]) # test fitting only even Legendre polynomials x = np.linspace(-1, 1) y = f2(x) coef1 = herme.hermefit(x, y, 4) assert_almost_equal(herme.hermeval(x, coef1), y) coef2 = herme.hermefit(x, y, [0, 2, 4]) assert_almost_equal(herme.hermeval(x, coef2), y) assert_almost_equal(coef1, coef2)
def weights(dim, degree): # 1D sigma-points (x) and weights (w) x, w = hermegauss(degree) # hermegauss() provides weights that cause posdef errors w = factorial(degree) / (degree ** 2 * hermeval(x, [0] * (degree - 1) + [1]) ** 2) return np.prod(cartesian([w] * dim), axis=1)
def test_hermefit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, herme.hermefit, [1], [1], -1) assert_raises(TypeError, herme.hermefit, [[1]], [1], 0) assert_raises(TypeError, herme.hermefit, [], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0) assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1,1]) # Test fit x = np.linspace(0,2) y = f(x) # coef3 = herme.hermefit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) # coef4 = herme.hermefit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # coef2d = herme.hermefit(x, np.array([y,y]).T, 3) assert_almost_equal(coef2d, np.array([coef3,coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = herme.hermefit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = herme.hermefit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) #test NA y = f(x) y[10] = 100 xm = x.view(maskna=1) xm[10] = np.NA res = herme.hermefit(xm, y, 3) assert_almost_equal(res, coef3) ym = y.view(maskna=1) ym[10] = np.NA res = herme.hermefit(x, ym, 3) assert_almost_equal(res, coef3) y2 = np.vstack((y,y)).T y2[10,0] = 100 y2[15,1] = 100 y2m = y2.view(maskna=1) y2m[10,0] = np.NA y2m[15,1] = np.NA res = herme.hermefit(x, y2m, 3).T assert_almost_equal(res[0], coef3) assert_almost_equal(res[1], coef3) wm = np.ones_like(x, maskna=1) wm[10] = np.NA res = herme.hermefit(x, y, 3, w=wm) assert_almost_equal(res, coef3)
def PiecewiseMollify(theta, c_j, a_n, x): """ Piecewise mollify the spectral reconstruction of a discontinuous function to reduce the effect of Gibbs phenomenon. Perform a real-space convolution of a spectral reconstruction with an adaptive unit-mass mollifier. Parameters ---------- theta : float free parameter to vary in the range 0 < theta < 1 c_j : 1D array, Array containing x positions of the discontinuities in the data a_n : 1D array, shape = (N+1,) N - highest order in the Chebyshev expansion vector of Chebyshev expansion coefficients x : 1D array, 1D grid of points in real space, where the function is evaluated Returns ---------- mollified : 1D array, shape = (len(x),) real space mollified representation of a discontinuous function mollified_err : 1D array, shape = (len(x),) error estimate for each point in the convolution, derived from scipy.integrate.quad """ N = a_n.shape[0] - 1 sanity_check = np.empty(len(x)) mollified = np.array([]) mollified_err = np.array([]) I_N = lambda y: T.chebval(y, a_n) chi_top = lambda y, f: f(y) if -1 <= y <= 1 else 0 I_N_top = lambda y: chi_top(y, I_N) c_jplus = np.append(c_j, 1.0) for idx_c, pos in enumerate(c_jplus): if idx_c == 0: lim_left = -1.0 lim_right = pos offset = np.ma.masked_where(x > lim_right, x) offset = np.ma.compressed(offset) else: lim_left = c_jplus[idx_c - 1] lim_right = pos offset = np.ma.masked_where(x > lim_right, x) offset = np.ma.masked_where(x <= lim_left, offset) offset = np.ma.compressed(offset) chi_cut = lambda y, f: f(y) if lim_left <= y <= lim_right else 0 convolution = np.empty(len(offset)) convolution_err = np.empty(len(offset)) for idx_o, off_x in enumerate(offset): c_jx = c_j - off_x dx = lambda y: sqrt(theta * N * min(abs(y - c) for c in c_jx)) var = lambda y: N / (2 * theta * dx(y)) p_N = lambda y: (theta**2) * dx(y) * N j_max = int(np.amax(np.frompyfunc(p_N, 1, 1)(x))) h_j = np.zeros(2 * (j_max + 1)) for j in range(j_max + 1): h_j[2 * j] = ((-1)**j) / ((4**j) * factorial(j)) hermite = lambda y: H.hermeval(sqrt(var(y)) * y, h_j) expon = lambda y: (1. / sqrt(theta * N * dx(y))) * exp(-var(y) * (y**2)) phi0 = lambda y: hermite(y) * expon(y) phi_off = lambda y: phi0(y - off_x) phi = lambda y: chi_cut(y, phi_off) norm = quad(phi, lim_left, lim_right)[0] convfunc = lambda y: (1 / norm) * (phi(y) * I_N_top(y)) convolution[idx_o], convolution_err[idx_o] = quad( convfunc, lim_left, lim_right) mollified = np.append(mollified, convolution) mollified_err = np.append(mollified_err, convolution_err) assert mollified.shape == sanity_check.shape, "Piecewise mollification inconsistent with regular one" assert mollified_err.shape == sanity_check.shape, "Piecewise mollification inconsistent with regular one" return mollified, mollified_err
def test_hermefit(self): def f(x): return x * (x - 1) * (x - 2) # Test exceptions assert_raises(ValueError, herme.hermefit, [1], [1], -1) assert_raises(TypeError, herme.hermefit, [[1]], [1], 0) assert_raises(TypeError, herme.hermefit, [], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0) assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = herme.hermefit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) # coef4 = herme.hermefit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # coef2d = herme.hermefit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = herme.hermefit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) #test NA y = f(x) y[10] = 100 xm = x.view(maskna=1) xm[10] = np.NA res = herme.hermefit(xm, y, 3) assert_almost_equal(res, coef3) ym = y.view(maskna=1) ym[10] = np.NA res = herme.hermefit(x, ym, 3) assert_almost_equal(res, coef3) y2 = np.vstack((y, y)).T y2[10, 0] = 100 y2[15, 1] = 100 y2m = y2.view(maskna=1) y2m[10, 0] = np.NA y2m[15, 1] = np.NA res = herme.hermefit(x, y2m, 3).T assert_almost_equal(res[0], coef3) assert_almost_equal(res[1], coef3) wm = np.ones_like(x, maskna=1) wm[10] = np.NA res = herme.hermefit(x, y, 3, w=wm) assert_almost_equal(res, coef3)