def eval_basis_chan(self, mode, x, y, chan): """Evaluate a basis function at a specific frequency channel. Parameters ---------- mode : (int, int) What Hermite polynomial to evalutate. x, y : arrays Coordinate locations to evalutate the polynomial. If 1D array, evaluate the polynomial at the same location at for each channel. chan : int Index of the frequency channel. """ x, y = np.broadcast_arrays(x, y) # Include the center offsets. x = x - self.center[chan,0] y = y - self.center[chan,1] # Get Gaussian factor. sigma = self.width[chan] / (2 * np.sqrt(2 * np.log(2))) gauss = np.exp(-(x**2 + y**2) / (2 * sigma**2)) # In the Hermite polynomials, the coordinates have to be scaled by the # width of the Gaussian **squared** (the weight function). window_sigma = sigma # Physicist Hermite polynomials. x /= window_sigma y /= window_sigma # Construct the basis function. poly_x = special.eval_hermite(mode[0], x) norm = 1. / math.sqrt(2**mode[0] * math.factorial(mode[0])) poly_y = special.eval_hermite(mode[1], y) norm = norm / math.sqrt(2**mode[1] * math.factorial(mode[1])) out = poly_x * poly_y * norm * gauss return out
def eval_basis_chan(self, mode, x, y, chan): """Evaluate a basis function at a specific frequency channel. Parameters ---------- mode : (int, int) What Hermite polynomial to evalutate. x, y : arrays Coordinate locations to evalutate the polynomial. If 1D array, evaluate the polynomial at the same location at for each channel. chan : int Index of the frequency channel. """ x, y = np.broadcast_arrays(x, y) # Include the center offsets. x = x - self.center[chan, 0] y = y - self.center[chan, 1] # Get Gaussian factor. sigma = self.width[chan] / (2 * np.sqrt(2 * np.log(2))) gauss = np.exp(-(x**2 + y**2) / (2 * sigma**2)) # In the Hermite polynomials, the coordinates have to be scaled by the # width of the Gaussian **squared** (the weight function). window_sigma = sigma # Physicist Hermite polynomials. x /= window_sigma y /= window_sigma # Construct the basis function. poly_x = special.eval_hermite(mode[0], x) norm = 1. / math.sqrt(2**mode[0] * math.factorial(mode[0])) poly_y = special.eval_hermite(mode[1], y) norm = norm / math.sqrt(2**mode[1] * math.factorial(mode[1])) out = poly_x * poly_y * norm * gauss return out
def test_hermite(): allTrue = True for order in range(ORDER_MAX): x = np.random.rand(1).item() valuePy = sp.eval_hermite(order, x) valueCpp = NumCpp.hermite_Scaler(order, x) if np.round(valuePy, DECIMALS_ROUND) != np.round( valueCpp, DECIMALS_ROUND): allTrue = False assert allTrue allTrue = True for order in range(ORDER_MAX): shapeInput = np.random.randint(10, 100, [ 2, ], dtype=np.uint32) shape = NumCpp.Shape(*shapeInput) cArray = NumCpp.NdArray(shape) x = np.random.rand(*shapeInput) cArray.setArray(x) valuePy = sp.eval_hermite(order, x) valueCpp = NumCpp.hermite_Array(order, cArray) if not np.array_equal(np.round(valuePy, DECIMALS_ROUND), np.round(valueCpp, DECIMALS_ROUND)): allTrue = False assert allTrue
def houghTilde(s, sig, m, lam, q): L = lam**.5 Lnu = L * q prefactor = m * np.sqrt(Lnu) / (m**2 - L**2) minhermite = s * ((L / m) + 1) * special.eval_hermite(s - 1, sig) maxhermite = .5 * ((L / m) - 1) * special.eval_hermite(s + 1, sig) exp = np.exp(-(sig**2) / 2.) hermites = minhermite + maxhermite return prefactor * hermites * exp
def scalar_angular_spectrum(self, theta, phi, k): HG_l = eval_hermite( self.l, k * self.width / np.sqrt(2) * np.tan(theta) * np.cos(phi)) HG_m = eval_hermite( self.m, k * self.width / np.sqrt(2) * np.tan(theta) * np.sin(phi)) exp = np.exp(-(k * self.width * np.tan(theta) / 2)**2) factor = (-1j)**(self.l + self.m) return factor * HG_l * HG_m * exp
def potential_operator(self, potential): grid = np.linspace(-self.phimax, self.phimax, self.D) r = np.tile(row_indices(self.N, self.N), (self.D, 1, 1)) c = np.tile(column_indices(self.N, self.N), (self.D, 1, 1)) phis = np.rollaxis(np.tile(grid, (self.N, self.N, 1)), 2) fs = np.exp(-phis**2) * eval_hermite(r, phis) * eval_hermite(c, phis) fs *= potential(self.rescaling_factor() * phis + self.flux) fs /= hermite_norm(r) * hermite_norm(c) vop = simps(fs, np.linspace(-self.phimax, self.phimax, self.D), axis=0) return vop
def fcint(v1, v2): aa = 0.0 for k1 in range(v1 + 1): for k2 in range(v2 + 1): if (k1 + k2) % 2 == 0: ik = factorial2(k1 + k2 - 1) / (a1 + a2)**((k1 + k2) / 2) else: ik = 0 aa += comb(v1,k1)*comb(v2,k2)*eval_hermite(v1-k1,b1)\ *eval_hermite(v2-k2,b2)*(2*sqrt(a1))**k1*(2*sqrt(a2))**k2*ik bb = aa * A * exp(-S) / 2**(v1 + v2) / factorial(v1) / factorial(v2) * aa #bb = A*exp(-S)/2**(v1+v2) return bb
def gaussian_hermite(n, m, mode_field_diameter=1, grid=None): r'''Creates a Gaussian-Hermite mode. This function evaluates a (n, m) order Gaussian-Hermite mode on a grid. The definition of the modes are the following, .. math:: \exp{\left(-\frac{r^2}{w_0^2}\right)} H_n\left(\sqrt{2}\frac{x}{w_0}\right) H_m\left(\sqrt{2}\frac{y}{w_0}\right). Here :math:`w_0` is the mode_field_radius, which is :math:`\mathrm{MFD}/2`. This defintion follows the Physicists definition of the Hermite polynomials. The modes are numerical normalized to have a total power of 1. More details on the Hermite Polynomials can be found on: http://mathworld.wolfram.com/HermitePolynomial.html Parameters ---------- n : int The x order. m : int The y order. mode_field_diameter : scalar The mode field diameter of the Gaussian-Laguerre mode. grid : Grid The grid on which to evaluate the mode. Returns ------- Field The evaluated mode. ''' from ..field import Field if grid.is_separated and grid.is_('cartesian'): x = grid.x y = grid.y r2 = (x**2 + y**2) / (mode_field_diameter / 2)**2 else: x, y = grid.as_('cartesian').coords r2 = (2 * grid.r / mode_field_diameter)**2 # Calculate the mode. hg = np.exp(-r2) * eval_hermite( n, 2 * sqrt(2) * x / mode_field_diameter) * eval_hermite( m, 2 * sqrt(2) * y / mode_field_diameter) # Numerically normalize the mode hg /= np.sum(np.abs(hg)**2 * grid.weights) return Field(hg, grid)
def eval_psi(x, y, nx, ny, omega0, xdisp): "This evaluates the wave function at cartesian coordinates x and y" pi = math.acos(-1.0) psix = 1.0 / math.sqrt(2.0**nx * math.factorial(nx)) psix *= (omega0 / pi)**0.25 psix *= math.exp(-0.5 * omega0 * (x - xdisp) * (x - xdisp)) psix *= sp.eval_hermite(nx, math.sqrt(omega0) * (x - xdisp)) psiy = 1.0 / math.sqrt(2.0**ny * math.factorial(ny)) psiy *= (omega0 / pi)**0.25 psiy *= math.exp(-0.5 * omega0 * y * y) psiy *= sp.eval_hermite(ny, math.sqrt(omega0) * y) psi = psix * psiy return psi
def gen(n, x, name): """Generate fixture data and write to file. # Arguments * `n`: degree(s) * `x`: domain * `name::str`: output filename # Examples ``` python python> n = 1 python> x = linspace(-1000, 1000, 2001) python> gen(n, x, './data.json') ``` """ y = eval_hermite(n, x) if isinstance(n, np.ndarray): data = {"n": n.tolist(), "x": x.tolist(), "expected": y.tolist()} else: data = {"n": n, "x": x.tolist(), "expected": y.tolist()} # Based on the script directory, create an output filepath: filepath = os.path.join(DIR, name) # Write the data to the output filepath as JSON: with open(filepath, "w") as outfile: json.dump(data, outfile)
def evaluate_basis(self, x, i=0, output_array=None): x = np.atleast_1d(x) if output_array is None: output_array = np.zeros(x.shape) output_array = eval_hermite(i, x, out=output_array) output_array *= np.exp(-x**2 / 2) * self.factor(i) return output_array
def eval_wavefunction(self, x_array: iterable): """ Computes wave function, based on eigenfunctions psi_n(x) = A_n * H_n(alpha * x) * exp(-alpha^2 * x^2 / 2) :parameter x_array: array containing points on the x-position axis :returns dictionary of two arrays containing wavefunction's real and imaginary parts evaluated in x_array key = 'real' : real part key = 'imaginary': imaginary part """ # in general psi_tot will be a complex function psi_tot = { 'real': np.zeros(len(x_array)), 'imaginary': np.zeros(len(x_array)) } for n in self.n_coeffs.keys(): # compute factorial via np.math.factorial() if n <= 16: a_n = np.float_power(self.mass * self.omega / (np.pi * self.h_bar), 0.25) \ / np.sqrt(2**n * np.math.factorial(n)) # compute factorial via Stirling Approximation else: a_n = np.float_power(self.mass * self.omega / (np.pi * self.h_bar), 0.25) \ / (np.float_power(2 * np.pi * n, 0.25) * np.float_power(2 * n / np.e, n * 0.5)) hermite_n = special.eval_hermite(n, self.alpha * x_array) psi_n = a_n * hermite_n * np.exp((-(self.alpha * x_array)**2 / 2)) # iteratively add real and imaginary parts of psi_tot psi_tot['real'] += complex(self.n_coeffs[n]).real * psi_n psi_tot['imaginary'] += complex(self.n_coeffs[n]).imag * psi_n return psi_tot
def get_slice(self, x, y): m = self.coefficients.shape[1] n_chan = len(self.freq) # Convert, x and y to 2D arrays broadcastable to the length of the # frequency axis. x, y = np.broadcast_arrays(x, y) if x.ndim == 0: shape = (1, 1) elif x.ndim == 1: shape = (1, x.shape[0]) elif x.ndim == 2: if x.shape[0] != n_chan and x.shape[0] != 1: msg = "Coordinate shapes not compatible with number of" msg += " channels." raise ValueError(msg) shape = x.shape else: msg = "Coordinates must be broadcastable to (n_chan, n_coord)." raise ValueError(msg) x.shape = shape y.shape = shape n_points = x.shape[1] # Get the Gaussian factor. sigma = self.width / (2 * np.sqrt(2 * np.log(2))) sigma.shape = (n_chan, 1) gauss = np.exp(-(x**2 + y**2) / (2 * sigma**2)) # Following line normalizes integral, but we want normalized amplitude. # gauss /= sigma * np.sqrt(2 * np.pi) # In the Hermite polynomials, the coordinates have to be scaled my the # width of the Gaussian **squared** (the weight function). window_sigma = sigma # Physicist Hermite polynomials. # Scale coordinates. x = x / window_sigma y = y / window_sigma # Allocate memory for output. out = np.zeros((n_chan, 4, n_points), dtype=np.float64) # Loop over the Hermite polynomials and add up the contributions. for ii in range(m): poly_x = special.eval_hermite(ii, x)[:,None,:] norm_x = 1. / math.sqrt(2**ii * math.factorial(ii)) for jj in range(m - ii): poly_y = special.eval_hermite(jj, y)[:,None,:] norm = norm_x / math.sqrt(2**jj * math.factorial(jj)) factor = norm * gauss[:,None,:] out += (self.coefficients[:,ii,jj,:,None] * poly_x * poly_y * factor) return out
def get_slice(self, x, y): m = self.coefficients.shape[1] n_chan = len(self.freq) # Convert, x and y to 2D arrays broadcastable to the length of the # frequency axis. x, y = np.broadcast_arrays(x, y) if x.ndim == 0: shape = (1, 1) elif x.ndim == 1: shape = (1, x.shape[0]) elif x.ndim == 2: if x.shape[0] != n_chan and x.shape[0] != 1: msg = "Coordinate shapes not compatible with number of" msg += " channels." raise ValueError(msg) shape = x.shape else: msg = "Coordinates must be broadcastable to (n_chan, n_coord)." raise ValueError(msg) x.shape = shape y.shape = shape n_points = x.shape[1] # Get the Gaussian factor. sigma = self.width / (2 * np.sqrt(2 * np.log(2))) sigma.shape = (n_chan, 1) gauss = np.exp(-(x**2 + y**2) / (2 * sigma**2)) # Following line normalizes integral, but we want normalized amplitude. # gauss /= sigma * np.sqrt(2 * np.pi) # In the Hermite polynomials, the coordinates have to be scaled my the # width of the Gaussian **squared** (the weight function). window_sigma = sigma # Physicist Hermite polynomials. # Scale coordinates. x = x / window_sigma y = y / window_sigma # Allocate memory for output. out = np.zeros((n_chan, 4, n_points), dtype=np.float64) # Loop over the Hermite polynomials and add up the contributions. for ii in range(m): poly_x = special.eval_hermite(ii, x)[:, None, :] norm_x = 1. / math.sqrt(2**ii * math.factorial(ii)) for jj in range(m - ii): poly_y = special.eval_hermite(jj, y)[:, None, :] norm = norm_x / math.sqrt(2**jj * math.factorial(jj)) factor = norm * gauss[:, None, :] out += (self.coefficients[:, ii, jj, :, None] * poly_x * poly_y * factor) return out
def test_boundstate(name, x, n, params = {}): Nx = len(x) # Infinite square well if name == "box": return np.sqrt(2/(x[-1]-x[0]))*np.sin(n*np.pi*(x-x[0])/(x[-1]-x[0]),dtype=np.complex_) # Single Delta Potential if name == "delta": if (params["Str"] >= 0): return np.zeros(len(x), dtype = complex) x0 = params["x0"] k = -params["Str"] return np.sqrt(k)*np.exp(-k*np.abs(x-x0), dtype = complex) # Double Delta Potential if name == "double delta": # energy equations are transendental def fEven(x,x0,a): return np.exp(-2*x*x0)+1-x/a def fOdd(x,x0,a): return np.exp(-2*x*x0)-1+x/a # If the delta is positive, we have scattering states, not bound if (params["Str"] >= 0): return np.zeros(len(x), dtype = complex) x0 = params["x0"] x1 = -x0 k = -params["Str"] if n == 0: kEven = newton(fEven, k, args=(x1, k)) even = np.empty(len(x), dtype = complex) even[x<x0] = np.cosh(kEven*x0)*np.exp(kEven*(x[i]-x0)) even[np.logical_and(x>=x0,x<x1)] = np.cosh(kEven*x[i]) even[x>=x1] = np.cosh(kEven*x1)*np.exp(-kEven*(x[i]-x1)) even /= np.sqrt(complex_quadrature(np.abs(even)**2, x)) return even else: if k <= 0.5/x0: return np.zeros(len(x), dtype = complex) kOdd = newton(fOdd, k, args=(x1, k)) odd = np.empty(len(x), dtype = complex) odd[x<x0] = np.sinh(kOdd*x0)*np.exp(kOdd*(x[i]-x0)) odd[np.logical_and(x>=x0,x<x1)] = odd[i] = np.sinh(kOdd*x[i]) odd[x>=x1] = np.sinh(kOdd*x1)*np.exp(-kOdd*(x[i]-x1)) odd /= np.sqrt(complex_quadrature(np.abs(odd)**2, x)) return odd # Harmonic Oscillator if name == "sho": x0 = params["x0"] w0 = -params["w0"] m0 = -params["m0"] a = m0*w0 y = np.sqrt(a)*(x-x0) A = (a/np.pi)**0.25/np.sqrt(2**n*factorial(n)) return A*eval_hermite(n, y)*np.exp(-0.5*y**2, dtype = complex)
def mpfun(self, ene, mporder): from scipy.special import eval_hermite dsum = 0.0 for nn in range(mporder): an = (-1.0)**float(nn) / (np.math.factorial(nn) * 4.0**float(nn) * np.sqrt(np.pi)) dsum += an * eval_hermite(2 * nn, ene) * np.exp(-ene**2.0) return dsum
def PsiIni(xx, yy): k = 10 m = 1. hbar = 1. w = np.sqrt(k / m) a = 0 b = 0 zetx = np.sqrt(m * w / hbar) * xx zety = np.sqrt(m * w / hbar) * yy Hx = ss.eval_hermite(a, zetx) Hy = ss.eval_hermite(b, zety) c_ab = (2**(a + b) * np.math.factorial(a) * np.math.factorial(b))**(-0.5) cte = (m * w / (np.pi * hbar))**0.5 return c_ab * cte * np.exp(-(zetx**2 + zety**2) / 2) * Hx * Hy
def psi(x, we, n, mu): alpha = np.sqrt(mu * we / hbar) A = np.sqrt(alpha / (np.sqrt(np.pi) * (2**n) * factorial(n))) return A * np.exp(-0.5 * alpha**2 * x**2) * eval_hermite( n, alpha * x) #, out=None)
def phi(self, n, x): c = self.c() h_n = special.eval_hermite(n, x * np.sqrt(2 * c)) res = ((2 * c / np.pi)**0.25) * np.exp(-c * x**2) res *= h_n * (1.0 / np.sqrt(2**n * special.factorial(n))) return res
def oscillator_wavefunction(n,x,alpha): """ Calculates wavefunctions of harmonic oscillator """ z = x*m.sqrt(alpha) N = (alpha/m.pi)**(1/4)/m.sqrt(2**n*sp.factorial(n)) h = sp.eval_hermite(n,z) psi = N*h*np.exp(-z**2/2) return psi
def timedep_eigenfunc(self, t, n, particle, h_bar=6.626e-34 / (2 * np.pi)): """ Returns the normalized eigenfunction for the Harmonic Oscillator with time dependance included. Parameters ------------------------------------------------------- t : number The time at which the eigenfunction is to be evaluated. n : `int` The order of the eigenfunction. particle : Particle class (see Particle.py for more details) Particle whose mass will determine the energy and therefore the time dependance of the eigenfunction. h_bar : number, optional The reduced planck constant. Defaults to 6.626e-34/2pi. For natural units, set to 1. Returns ------------------------------------------------------ out : `complex ndarray` The output is a complex array representing the nth normalized eigenfunction at time t for the Harmonic Oscillator Examples ------------------------------------------------------ Return the first excited state for a Harmonic Oscillator with k = 1 at time t = 3. Units are natural units such that the electron rest mass and the reduced planck constant is 1. >>> import Particle as p >>> x = np.linspace(-5, 5, 10) >>> electron = p.Particle(1) >>> ho = HarmonicOscillator(x, 1) >>> ho.timedep_eigenfunc(3, 0, electron, h_bar = 1) array([2.79918439e-06+0.j, 3.90567063e-04+0.j, 1.58560022e-02+0.j, 1.87294814e-01+0.j, 6.43712257e-01+0.j, 6.43712257e-01+0.j, 1.87294814e-01+0.j, 1.58560022e-02+0.j, 3.90567063e-04+0.j, 2.79918439e-06+0.j]) """ if n < 0 or n % 1 != 0: raise Exception( 'for the harmonic oscillator, n must be a positive integer starting from 0' ) n = int( n ) #coverts n datatype to the native Python int type to ensure number of bits is enough for calculating the square root of large numbers w = np.sqrt(self.k / particle.m) alpha = particle.m * w / h_bar y = np.sqrt(alpha) * self.x Hermite = sp.eval_hermite(n, y) C = (1 / np.sqrt(float(2**n) * np.math.factorial(n))) * ( alpha / np.pi)**(1 / 4) return C * np.exp(-y**2 / 2) * Hermite * np.exp( -1j * self.eigenvalue(n, particle, h_bar=h_bar) * t / h_bar)
def hermite_gaussian_paraxial(src, x, y, z, k): factor = 1 / src.width * np.sqrt(2 / (np.pi * 2**src.l * 2**src.m * factorial(src.l) * factorial(src.m))) E0 = factor * np.sqrt((2 * Z0 * src.power)) rho_sq = x**2 + y**2 wav = 2 * np.pi / k wz = w(z, src.width, wav) HG_l = eval_hermite(src.l, np.sqrt(2) * x / wz) HG_m = eval_hermite(src.m, np.sqrt(2) * y / wz) N = src.l + src.m amp = E0 * src.width / wz * HG_l * HG_m * np.exp(-rho_sq / wz**2) phase = k * z + k * rho_sq * Rinv( z, src.width, wav) / 2 - (N + 1) * gouy(z, src.width, wav) return amp * np.exp(1j * phase)
def test_reduction_to_physicists_polys(): """Tests that the multidimensional hermite polynomials reduce to the regular physicists' hermite polynomials in the appropriate limit""" x = np.arange(-1, 1, 0.1) init = 1 n_max = 5 A = np.ones([init, init], dtype=complex) vals = np.array( [hermite_multidimensional(2 * A, n_max, y=np.array([x0], dtype=complex)) for x0 in x] ).T expected = np.array([eval_hermite(i, x) for i in range(len(vals))]) assert np.allclose(vals, expected)
def EigenOsci(x, y): # k=20. m = 1. a = 0 b = 0 if (k == 0.): return (2. / 5.) * np.sin(np.pi * (x - 2.5) / 5) * np.sin(np.pi * (y - 2.5) / 5) else: w = np.sqrt(k / m) zetx = np.sqrt(m * w / hbar) * (x - 2.5) zety = np.sqrt(m * w / hbar) * (y - 2.5) Hx = ss.eval_hermite(a, zetx) Hy = ss.eval_hermite(b, zety) c_ab = (2**(a + b) * np.math.factorial(a) * np.math.factorial(b))**(-0.5) cte = (m * w / (np.pi * hbar))**0.5 return c_ab * cte * np.exp(-(zetx**2 + zety**2) / 2) * Hx * Hy
def hermite_function(n, x): """ Evaluates the hermite function of order n at a point x """ n = np.atleast_2d(n) x = np.atleast_2d(x) coef = np.sqrt((2**n) * factorial(n) * np.sqrt(np.pi)) * np.exp( (x**2) / 2, dtype=np.float128, ) return eval_hermite(n, x) / coef
def eigenfunc(self, n, particle, h_bar=6.626e-34 / (2 * np.pi)): """ Returns the normalized eigenfunction for the Harmonic Oscillator. Does not include time dependance. This is equivalent to the eigenfunction at time t = 0. For the eigenfunction with the time dependance included, see timedep_eigenfunc(). Parameters --------------------------------------------- n : `int` The order of the eigenfunction. particle : Particle class (see Particle.py for more details) Particle whose mass will determine the angular frequency from the force constant h_bar : number, optional The reduced planck constant. Defaults to 6.626e-34/2pi. For natural units, set to 1. Returns --------------------------------------------- out : `ndarray` The output is an array representing the nth normalized eigenfunction for the Harmonic Oscillator. Examples -------------------------------------------- Return the ground state eigenfunction for a Harmonic Oscillator with force constant k = 1. Units are natural units such that the electron rest mass and reduced Planck constant is 1. >>> import Particle as p >>> x = np.linspace(-5, 5, 10) >>> ho = HarmonicOscillator(x, 1) >>> electron = p.Particle(1) >>> ho.eigenfunc(0, electron, h_bar = 1) array([2.79918439e-06, 3.90567063e-04, 1.58560022e-02, 1.87294814e-01, 6.43712257e-01, 6.43712257e-01, 1.87294814e-01, 1.58560022e-02, 3.90567063e-04, 2.79918439e-06]) """ if n < 0 or n % 1 != 0: raise Exception( 'for the harmonic oscillator, n must be a positive integer starting from 0' ) n = int( n ) #coverts n datatype to the native Python int type to ensure number of bits is enough for calculating the square root of large numbers w = np.sqrt(self.k / particle.m) alpha = particle.m * w / h_bar y = np.sqrt(alpha) * self.x Hermite = sp.eval_hermite(n, y) C = (1 / np.sqrt(float(2**n) * np.math.factorial(n))) * ( alpha / np.pi)**(1 / 4) return C * np.exp(-y**2 / 2) * Hermite
def test_h_roots(self): # this test is copied from numpy's TestGauss in test_hermite.py x, w = orth.h_roots(100) n = np.arange(100) v = eval_hermite(n[:, np.newaxis], x[np.newaxis,:]) vv = np.dot(v*w, v.T) vd = 1 / np.sqrt(vv.diagonal()) vv = vd[:, np.newaxis] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct assert_almost_equal(w.sum(), np.sqrt(np.pi))
def HG_nm(x, y, n, m, z=0, wavelength=0.001, w0=1): # Create Hermite Gauss modes k = 2 * np.pi / wavelength zR = (k * w0**2) / 2 wz = np.sqrt(2 * (z**2 + zR**2) / (k * zR)) # Define all coefficients cf1 = np.sqrt(2 / (np.pi * factorial(n) * factorial(m))) * 2**(-(n + m) / 2) cf2 = w0 / wz cf3 = np.exp(-(x**2 + y**2) / (wz**2)) cf4 = np.exp(-1j * (k * z * (x**2 + y**2)) / (2 * (z**2 + zR**2))) cf5 = np.exp(-1j * (n + m + 1) * np.arctan(z / zR)) # make hermite modes Hn = eval_hermite(int(n), np.sqrt(2) * x / wz) Hm = eval_hermite(int(m), np.sqrt(2) * y / wz) # Calculate HG mode HG = cf1 * cf2 * cf3 * cf4 * cf5 * Hn * Hm return (HG)
def test_hermite(): if NumCpp.NO_USE_BOOST and not NumCpp.STL_SPECIAL_FUNCTIONS: return for order in range(ORDER_MAX): x = np.random.rand(1).item() valuePy = sp.eval_hermite(order, x) valueCpp = NumCpp.hermite_Scaler(order, x) assert np.round(valuePy, DECIMALS_ROUND) == np.round(valueCpp, DECIMALS_ROUND) for order in range(ORDER_MAX): shapeInput = np.random.randint(10, 100, [ 2, ], dtype=np.uint32) shape = NumCpp.Shape(*shapeInput) cArray = NumCpp.NdArray(shape) x = np.random.rand(*shapeInput) cArray.setArray(x) valuePy = sp.eval_hermite(order, x) valueCpp = NumCpp.hermite_Array(order, cArray) assert np.array_equal(np.round(valuePy, DECIMALS_ROUND), np.round(valueCpp, DECIMALS_ROUND))
def OsciEigen(r, param): xx = r[0] #ROW yy = r[1] #COLUMN x0 = param[0] y0 = param[1] w = param[2] a = int(param[3]) b = int(param[4]) m = 1. hbar = 1. # w=np.sqrt(abs(k)/m) zetx = np.sqrt(m * w / hbar) * (xx - x0) zety = np.sqrt(m * w / hbar) * (yy - y0) Hx = ss.eval_hermite(a, zetx) Hy = ss.eval_hermite(b, zety) c_ab = (2**(a + b) * np.math.factorial(a) * np.math.factorial(b))**(-0.5) cte = (m * w / (np.pi * hbar))**0.5 return c_ab * cte * np.exp(-(zetx**2 + zety**2) / 2) * Hx * Hy
def gen_shape_basis_direct(n1=None,n2=None,xrot=None,yrot=None,b1=None,b2=None,convolve_kern=False,shape=False): '''Generates the shapelet basis function for given n1,n2,b1,b2 parameters, at the given coords xrot,yrot b1,b2 should be in radians''' this_xrot = deepcopy(xrot) this_yrot = deepcopy(yrot) gauss = exp(-0.5*(array(this_xrot)**2+array(this_yrot)**2)) n1 = int(n1) n2 = int(n2) norm = 1.0 / (sqrt(2**n1*factorial(n1))*sqrt(2**n2*factorial(n2))) norm *= 1.0 / (b1 * b2) norm *= sqrt(pi) / 2 if type(convolve_kern) == ndarray: this_xrot.shape = shape this_yrot.shape = shape gauss.shape = shape h1 = eval_hermite(n1,this_xrot) h2 = eval_hermite(n2,this_yrot) basis = gauss*norm*h1*h2 basis = fftconvolve(basis, convolve_kern, 'same') basis = basis.flatten() else: h1 = eval_hermite(n1,this_xrot) h2 = eval_hermite(n2,this_yrot) basis = gauss*norm*h1*h2 return basis
def evaluate_basis_derivative(self, x=None, i=0, k=0, output_array=None): if x is None: x = self.mesh(False, False) x = np.atleast_1d(x) v = eval_hermite(i, x, out=output_array) if k == 1: D = np.zeros((self.N, self.N)) D[:-1, :] = hermite.hermder(np.eye(self.N), 1) V = np.dot(v, D) V -= v*x[:, np.newaxis] V *= np.exp(-x**2/2)[:, np.newaxis]*self.factor(i) v[:] = V elif k == 2: W = (x[:, np.newaxis]**2 - 1 - 2*i)*V v[:] = W*self.factor(i)*np.exp(-x**2/2)[:, np.newaxis] elif k == 0: v *= np.exp(-x**2/2)[:, np.newaxis]*self.factor(i) else: raise NotImplementedError return v
def evalNormPoly(self,x,n): norm = self.norm(n) return norm*polys.eval_hermite(n,x)
def eval_hermite_ld(n, x): return eval_hermite(n.astype('l'), x)
def evalNormPoly(self,x,n): norm = 1.0/(np.sqrt(np.sqrt(np.pi)*(2.0**n)*factorial(n))) return norm*polys.eval_hermite(n,x)
def test_hermite(self): assert_mpmath_equal(lambda n, x: sc.eval_hermite(int(n), x), _exception_to_nan(mpmath.hermite), [IntArg(0, 10000), Arg()])
def uVu(x): # integrand $u_m V u_n$ y, c = x/a0, a0*np.sqrt(np.pi*gamma(m+1)*gamma(n+1)*2**(m+n)) return V(x)*eval_hermite(m,y)*eval_hermite(n,y)*np.exp(-y*y)/c
def hermite_norm(n, x): """Normalized Hermite polynomials""" return eval_hermite(n, x)/ hermite_mag(n)