Exemplo n.º 1
0
    def pre_calc(self, x, y, beta, n_order, center_x, center_y):
        """
        calculates the H_n(x) and H_n(y) for a given x-array and y-array
        :param x:
        :param y:
        :param amp:
        :param beta:
        :param n_order:
        :param center_x:
        :param center_y:
        :return: list of H_n(x) and H_n(y)
        """

        n = len(np.atleast_1d(x))
        x_ = x - center_x
        y_ = y - center_y
        H_x = np.empty((n_order+1, n))
        H_y = np.empty((n_order+1, n))
        for n in range(0,n_order+1):
            prefactor = 1./np.sqrt(2**n*np.sqrt(np.pi)*math.factorial(n))
            n_array = np.zeros(n+1)
            n_array[n] = 1
            H_x[n] = hermite.hermval(x_/beta, n_array) * prefactor * np.exp(-(x_/beta)**2/2.)
            H_y[n] = hermite.hermval(y_/beta, n_array) * prefactor * np.exp(-(y_/beta)**2/2.)
        return H_x, H_y
Exemplo n.º 2
0
    def d2psi(x, c):
        """Second derivative of psi"""
        from numpy.polynomial.hermite import hermval, hermder

        yp = hermval(x, hermder(hermder(c))) * np.exp(-x**2 / 2)
        yp += -x * hermval(x, hermder(c)) * np.exp(-x**2 / 2)
        yp += -psi(x, c) - x * dpsi(x, c)
        return yp
Exemplo n.º 3
0
    def getA(self, coords, z):

        # Unpack the coordinates
        x, px, y, py, theta, gamma = coords

        # Compute the Hermite-Gauss coefficients, which have some
        # z-dependence that requires they be computed for every time step.
        # This multiplies the base laser mode coefficients, and therefore
        # has to be created as a temporary variable to avoid modifying the
        # original laser parameters. This assumes a 2D laser
        qxz = (z - self.zWaistX) + self.qx0
        xrFac  = 0.5 * self.k0 / qxz
        xzFac  = (np.sqrt(2)/self.waistX)/\
                 np.sqrt(1+((z-self.zWaistX)/self.zRx)**2)

        qyz = (z - self.zWaistY) + self.qy0
        yrFac  = 0.5 * self.k0 / qyz
        yzFac  = (np.sqrt(2)/self.waistY)/\
                 np.sqrt(1+((z-self.zWaistY)/self.zRy)**2)

        # Iterate over the coefficients, computing the particle-dependent
        # normalization coefficients for the Hermite-Gauss series
        # Have to compute the Hermite-Gauss series explicitly for optimal
        # control -- recommend against attempting to use hermval2d
        ptclCoefs = copy.deepcopy(self.hermCoeffs)

        for nidx in range(0,self.hermCoeffs.shape[0]):
            for midx in range(0,self.hermCoeffs.shape[1]):
                ptclCoefs[nidx,midx] *= (self.piWxFac)*np.sqrt(
                    self.qx0/qxz)
                ptclCoefs[nidx,midx] *= (self.qx0*qxz.conjugate()/
                    self.qx0.conjugate()/qxz)**(0.5*(midx))

                ptclCoefs[nidx,midx] *= (self.piWyFac)*np.sqrt(
                    self.qy0/qyz)
                ptclCoefs[nidx,midx] *= (self.qy0*qxz.conjugate()/
                    self.qy0.conjugate()/qyz)**(0.5*(nidx))

        # Explicitly iterate through the particles, since this seems to be
        # the only way to keep control over the Hermite functions
        myNewCoeffs = np.zeros(self.hermCoeffs.shape[0], dtype=complex)
        for xidx in range(0, self.hermCoeffs.shape[0]):
            myNewCoeffs[xidx] = hermval(yzFac*y,ptclCoefs[xidx])

        Alaser = hermval(xzFac*x, myNewCoeffs)

        Alaser *= np.exp(-(xrFac*(x**2)*1j))

        Alaser *= np.exp(-(yrFac*(y**2)*1j))
        Alaser /= self.omega*1j
        Alaser *= np.sqrt(np.dot(self.polVector, self.polVector))

        return abs(Alaser)
Exemplo n.º 4
0
 def test_hermmul(self):
     # check values of result
     for i in range(5):
         pol1 = [0] * i + [1]
         val1 = herm.hermval(self.x, pol1)
         for j in range(5):
             msg = f"At i={i}, j={j}"
             pol2 = [0] * j + [1]
             val2 = herm.hermval(self.x, pol2)
             pol3 = herm.hermmul(pol1, pol2)
             val3 = herm.hermval(self.x, pol3)
             assert_(len(pol3) == i + j + 1, msg)
             assert_almost_equal(val3, val1 * val2, err_msg=msg)
Exemplo n.º 5
0
 def test_hermmul(self) :
     # check values of result
     for i in range(5) :
         pol1 = [0]*i + [1]
         val1 = herm.hermval(self.x, pol1)
         for j in range(5) :
             msg = "At i=%d, j=%d" % (i,j)
             pol2 = [0]*j + [1]
             val2 = herm.hermval(self.x, pol2)
             pol3 = herm.hermmul(pol1, pol2)
             val3 = herm.hermval(self.x, pol3)
             assert_(len(pol3) == i + j + 1, msg)
             assert_almost_equal(val3, val1*val2, err_msg=msg)
Exemplo n.º 6
0
 def test_hermmul(self):
     # get_inds values of result
     for i in range(5):
         pol1 = [0] * i + [1]
         val1 = herm.hermval(self.x, pol1)
         for j in range(5):
             msg = "At i=%d, j=%d" % (i, j)
             pol2 = [0] * j + [1]
             val2 = herm.hermval(self.x, pol2)
             pol3 = herm.hermmul(pol1, pol2)
             val3 = herm.hermval(self.x, pol3)
             assert_(len(pol3) == i + j + 1, msg)
             assert_almost_equal(val3, val1 * val2, err_msg=msg)
 def forward(self, x, coef):
     x = self.conv1(x)
     x = x.detach().numpy()
     x = hermval(x, coef, tensor=True)
     x = self.pool1(torch.from_numpy(x))
     x = x.float()
     x = self.conv2(x)
     x = x.detach().numpy()
     x = hermval(x, coef, tensor=True)
     x = self.pool2(torch.from_numpy(x))
     x = x.view(-1, x.shape[1] * x.shape[2] * x.shape[3])
     x = hermval(self.fc1(x), coef, tensor=True)
     x = x.float()
     out = self.fc2(x)
     return out
Exemplo n.º 8
0
def harmonic_osc(x, n, omega=1.0):
    # Returns the n^th exited state of a 1D harmonic
    # oscillator evaluated at x
    xs = np.sqrt(omega) * x
    c = [1.0 if i == n else 0.0 for i in range(0, n + 1)]
    norm = (2**n * factorial(n))**(-0.5) * (omega / np.pi)**(0.25)
    return norm * np.exp(-0.5 * xs**2) * hermval(xs, c)
Exemplo n.º 9
0
 def eval(self, x, u, output_array=None):
     if output_array is None:
         output_array = np.zeros(x.shape)
     w = u*self.factor(np.arange(self.N))
     y = hermite.hermval(x, w)
     output_array[:] = y * np.exp(-x**2/2)
     return output_array
Exemplo n.º 10
0
def psi (alpha,eqgeom,R,state):
    n=state
    prefactor=pow(alpha/pi,0.25)/(sqrt(pow(2.0,n)*factorial(n)))
    coeffs=zeros(n+1,float)
    coeffs[n]=1.0
    hermpoly=hermval(sqrt(alpha)*(R-eqgeom),coeffs)
    return prefactor*exp(-0.5*alpha*(R-eqgeom)**2)*hermpoly
Exemplo n.º 11
0
    def test_hermvander(self) :
        # check for 1d x
        x = np.arange(3)
        v = herm.hermvander(x, 3)
        assert_(v.shape == (3, 4))
        for i in range(4) :
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], herm.hermval(x, coef))

        # check for 2d x
        x = np.array([[1, 2], [3, 4], [5, 6]])
        v = herm.hermvander(x, 3)
        assert_(v.shape == (3, 2, 4))
        for i in range(4) :
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], herm.hermval(x, coef))
Exemplo n.º 12
0
    def test_hermitefunction(self):
        '''Test routines to compute using Hermite polynomials.'''
        from scipy.linalg import funm
        from numpy.polynomial.hermite import hermfit, hermval
        from numpy import cos, linspace, sin
        # Starting Matrix
        matrix1 = self.create_matrix(scaled=True)
        self.write_matrix(matrix1, self.input_file)

        # Function
        x = linspace(-1.0, 1.0, 200)
        y = [cos(i) + sin(i) for i in x]
        coef = hermfit(x, y, 10)

        # Check Matrix
        dense_check = funm(matrix1.todense(), lambda x: hermval(x, coef))
        self.CheckMat = csr_matrix(dense_check)

        # Result Matrix
        input_matrix = nt.Matrix_ps(self.input_file, False)
        poly_matrix = nt.Matrix_ps(self.mat_dim)

        polynomial = nt.HermitePolynomial(len(coef))
        for j in range(0, len(coef)):
            polynomial.SetCoefficient(j, coef[j])

        permutation = nt.Permutation(input_matrix.GetLogicalDimension())
        permutation.SetRandomPermutation()
        self.fsp.SetLoadBalance(permutation)
        polynomial.Compute(input_matrix, poly_matrix, self.fsp)
        poly_matrix.WriteToMatrixMarket(result_file)
        comm.barrier()

        self.check_result()
Exemplo n.º 13
0
def squeezed_coherent_state(series_length=DEF_SERIES_LEN,
                            alpha=1,
                            squeezing_amp=1,
                            squeezing_phase=0):
    """
    Generating a squezed coherent state in a Fock basis.
    :param series_length: Lenght of the state.
    :param alpha: Coheret parameter alpha.
    :param squeezing_amp: Squeezing parameter amplitude.
    :param squeezing_phase: Squeezing parameter phase.
    :return: Squezed coherent state as an array.
    """
    if series_length < 1:
        raise ValueError('The series length should be a positive integer')
    state = np.zeros(series_length, dtype=np.complex128)
    const = (1 / sqrt(np.cosh(squeezing_amp))
             ) * cm.exp(-0.5 * abs(alpha)**2 - 0.5 * np.conj(alpha)**2 *
                        cm.exp(1j * squeezing_phase) * np.tanh(squeezing_amp))
    for n in range(series_length):
        herm_coeff_arr = np.zeros(series_length)
        herm_coeff_arr[n] = 1
        gamma = alpha * np.cosh(squeezing_amp) + np.conj(alpha) * cm.exp(
            1j * squeezing_phase) * np.sinh(squeezing_amp)
        state[n] = 1 / sqrt(factorial(n)) * const * (
            0.5 * cm.exp(1j * squeezing_phase) * np.tanh(squeezing_amp)
        )**(n / 2) / cm.sqrt(factorial(n)) * herm.hermval((gamma / cm.sqrt(
            cm.exp(1j * squeezing_phase) * np.sinh(2 * squeezing_amp))),
                                                          herm_coeff_arr)
    return state
Exemplo n.º 14
0
    def kernel(self, x: np.ndarray) -> np.ndarray:
        """Creates convolution kernel for LOSVD.

        Args:
            x: x Array to create kernel on.

        Returns:
            Kernel on given x values.
        """

        # get values
        v, sig = self._losvd[:2]
        herm = self._losvd[2:]

        # helpers
        t = (x - v) / sig
        t2 = t * t

        # calculate Gaussian kernel
        k = np.exp(-0.5 * t2) / (np.sqrt(2. * np.pi) * sig)

        # Hermite polynomials normalized as in Appendix A of van der Marel &
        # Franx (1993). They are given e.g. in Appendix C of Cappellari et al. (2002)
        n = np.arange(3 + len(herm))
        nrm = np.sqrt(scipy.special.factorial(n) * 2**n)

        # normalize coefficients
        c = np.array([1., 0., 0.] + herm) / nrm

        # add hermites
        k *= hermite.hermval(t, c)

        # normalize kernel
        return k / np.sum(k)
Exemplo n.º 15
0
    def test_hermvander(self):
        # get_inds for 1d x
        x = np.arange(3)
        v = herm.hermvander(x, 3)
        assert_(v.shape == (3, 4))
        for i in range(4):
            coef = [0] * i + [1]
            assert_almost_equal(v[..., i], herm.hermval(x, coef))

        # get_inds for 2d x
        x = np.array([[1, 2], [3, 4], [5, 6]])
        v = herm.hermvander(x, 3)
        assert_(v.shape == (3, 2, 4))
        for i in range(4):
            coef = [0] * i + [1]
            assert_almost_equal(v[..., i], herm.hermval(x, coef))
Exemplo n.º 16
0
def wavefunc(n, x):
    ns = np.zeros(n + 1)
    ns[n] = 1
    pre = 1 / np.sqrt(2**n * np.math.factorial(n)) * np.pi**(-0.25)
    wfunc = pre * np.exp(-x**2 / 2) * hermval(x, ns)

    return wfunc
Exemplo n.º 17
0
def count_hermvals(n, x, dtype=torch.float64, device=torch.device('cpu')):
    """Returns tensor of shape [len(x), len(n)] with hermitian polynomes values H_n(x)."""
    hermvals = torch.zeros(len(x), len(n), dtype=dtype, device=device)
    for i, nval in enumerate(n):
        coef = torch.zeros(n[-1] + 1, dtype=dtype, device=device)
        coef[nval] = 1
        hermvals[:, i] = hermval(x, coef)
    return hermvals
Exemplo n.º 18
0
 def H2p_psi(self, x, n):
     # n'th harmonic wavefunction for H2+
     tmp = self.reduced_mass * self.omega_p
     prefactor = pow(tmp / np.pi, 0.25) / np.sqrt(2.0**n * factorial(n))
     coeffs = np.zeros(n + 1, float)
     coeffs[n] = 1.0
     hermpoly = hermval(np.sqrt(tmp) * (x - self.x_eq_p), coeffs)
     return prefactor * np.exp(-0.5 * tmp * (x - self.x_eq_p)**2) * hermpoly
Exemplo n.º 19
0
def psi(x, t, n):
    global b, B, ω
    a = np.exp(-1j * ω * t / 2. - b * x**2 / 2.)
    c = np.array([
        np.exp(-1j * k * ω * t) / np.sqrt(float(2**k * factorial(k)))
        for k in range(n + 1)
    ])
    ret = a * hermval(x * B, c, tensor=False)
    return ret
Exemplo n.º 20
0
 def get_psi_n(self, n):
     psi = np.sqrt(1 / float(np.math.factorial(n - 1) * 2**(n - 1))) * (
         self.m * self.omega / np.pi)**(0.25) * np.exp(
             -self.m * self.omega * self.x**2 / 2) * hermite.hermval(
                 np.sqrt(self.m * self.omega) * self.x, [0] *
                 (n - 1) + [1.0])
     psi[self.x > self.L / 2.0] = 0
     psi[self.x < -self.L / 2.0] = 0
     return psi
Exemplo n.º 21
0
def Hermite(n, x):

    cn = []
    for i in xrange(n):
        cn.append(0.0)
    cn.append(1.0)

    Hnx = hermval(x, cn)
    return Hnx
    def generate_eigenstates(self, n):

        self.eigenstates = np.zeros((n,self.x.size), dtype=np.complex128)
        self.En = hbar*self.w*(np.arange(n) + 0.5)
        tmp = self.M*self.w/hbar
        gauss = (tmp/np.pi)**0.25*np.exp(-1/2*tmp*(self.x-self.x0)**2)
        for i in range(n):
            pre_factor = sqrt(1/(2**i * np.math.factorial(i)))
            self.eigenstates[i,:] = pre_factor*gauss*hermval(sqrt(tmp)*(self.x-self.x0), [int(i == j) for j in range(i+1)])
        self.generate_initial_cn(n)
Exemplo n.º 23
0
    def test_hermfit(self) :
        def f(x) :
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, herm.hermfit, [1],    [1],     -1)
        assert_raises(TypeError,  herm.hermfit, [[1]],  [1],      0)
        assert_raises(TypeError,  herm.hermfit, [],     [1],      0)
        assert_raises(TypeError,  herm.hermfit, [1],    [[[1]]],  0)
        assert_raises(TypeError,  herm.hermfit, [1, 2], [1],      0)
        assert_raises(TypeError,  herm.hermfit, [1],    [1, 2],   0)
        assert_raises(TypeError,  herm.hermfit, [1],    [1],   0, w=[[1]])
        assert_raises(TypeError,  herm.hermfit, [1],    [1],   0, w=[1,1])

        # Test fit
        x = np.linspace(0,2)
        y = f(x)
        #
        coef3 = herm.hermfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(herm.hermval(x, coef3), y)
        #
        coef4 = herm.hermfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(herm.hermval(x, coef4), y)
        #
        coef2d = herm.hermfit(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 = herm.hermfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = herm.hermfit(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(herm.hermfit(x, x, 1), [0, .5])
Exemplo n.º 24
0
    def test_hermfit(self):
        def f(x):
            return x * (x - 1) * (x - 2)

        # Test exceptions
        assert_raises(ValueError, herm.hermfit, [1], [1], -1)
        assert_raises(TypeError, herm.hermfit, [[1]], [1], 0)
        assert_raises(TypeError, herm.hermfit, [], [1], 0)
        assert_raises(TypeError, herm.hermfit, [1], [[[1]]], 0)
        assert_raises(TypeError, herm.hermfit, [1, 2], [1], 0)
        assert_raises(TypeError, herm.hermfit, [1], [1, 2], 0)
        assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[1, 1])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = herm.hermfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(herm.hermval(x, coef3), y)
        #
        coef4 = herm.hermfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(herm.hermval(x, coef4), y)
        #
        coef2d = herm.hermfit(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 = herm.hermfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = herm.hermfit(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(herm.hermfit(x, x, 1), [0, .5])
Exemplo n.º 25
0
    def test_hermval(self):
        #check empty input
        assert_equal(herm.hermval([], [1]).size, 0)

        #check normal input)
        x = np.linspace(-1, 1)
        y = [polyval(x, c) for c in Hlist]
        for i in range(10):
            msg = "At i=%d" % i
            tgt = y[i]
            res = herm.hermval(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(herm.hermval(x, [1]).shape, dims)
            assert_equal(herm.hermval(x, [1, 0]).shape, dims)
            assert_equal(herm.hermval(x, [1, 0, 0]).shape, dims)
Exemplo n.º 26
0
 def test_hermfromroots(self) :
     res = herm.hermfromroots([])
     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 = herm.hermfromroots(roots)
         res = herm.hermval(roots, pol)
         tgt = 0
         assert_(len(pol) == i + 1)
         assert_almost_equal(herm.herm2poly(pol)[-1], 1)
         assert_almost_equal(res, tgt)
Exemplo n.º 27
0
def basis(order, stamp_sz, beta, origin_shift=(0.5, 0.5)):

    stamp_origin = np.array(stamp_sz) / 2.0 + np.array(origin_shift)
    x, y = np.meshgrid(range(stamp_sz[0]), range(stamp_sz[1]))
    x = (x - stamp_origin[0]) / beta
    y = (y - stamp_origin[1]) / beta
    basis_ = np.zeros(np.hstack((order, stamp_sz)))
    W = np.exp(-(x**2 + y**2) / 2.0)
    for i in range(order[0]):
        for j in range(order[1]):
            coeff_x = [0] * (i + 1)
            coeff_y = [0] * (j + 1)
            coeff_x[i] = 1.0
            coeff_y[j] = 1.0
            Hx = hermval(x, coeff_x)
            Hy = hermval(y, coeff_y)
            norm = (2**(i + j) * ma.factorial(i) * ma.factorial(j) *
                    ma.pi)**(-0.5)
            basis_[i, j, :, :] = Hx * Hy * W * norm / beta
    return basis_
Exemplo n.º 28
0
    def test_hermval(self):
        #get_inds empty input
        assert_equal(herm.hermval([], [1]).size, 0)

        #get_inds normal input)
        x = np.linspace(-1, 1)
        y = [polyval(x, c) for c in Hlist]
        for i in range(10):
            msg = "At i=%d" % i
            tgt = y[i]
            res = herm.hermval(x, [0] * i + [1])
            assert_almost_equal(res, tgt, err_msg=msg)

        #get_inds that shape is preserved
        for i in range(3):
            dims = [2] * i
            x = np.zeros(dims)
            assert_equal(herm.hermval(x, [1]).shape, dims)
            assert_equal(herm.hermval(x, [1, 0]).shape, dims)
            assert_equal(herm.hermval(x, [1, 0, 0]).shape, dims)
Exemplo n.º 29
0
 def __call__(self,X):
     '''
     Evaluates the fit at x
     '''
     X = np.atleast_2d(X)
     if X.shape[1] != self.N:
         X = X.T
     assert X.shape[1] == self.N
     #evaluate basis fuctionslong each rowof X
     B = np.vstack(map(lambda x:np.prod(hermval(x,self.coef,False),1),X))
     return B.dot(self.c)
Exemplo n.º 30
0
 def test_hermfromroots(self):
     res = herm.hermfromroots([])
     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 = herm.hermfromroots(roots)
         res = herm.hermval(roots, pol)
         tgt = 0
         assert_(len(pol) == i + 1)
         assert_almost_equal(herm.herm2poly(pol)[-1], 1)
         assert_almost_equal(res, tgt)
Exemplo n.º 31
0
 def funcion_de_onda(self, x, n):
     import numpy as np
     from numpy.polynomial.hermite import hermval
     from math import factorial
     m = 9.10938291e-31  #kg
     meff = 0.067 * m  #masa efectiva GaAs
     hbar = 1.05457e-34  #J*s
     x0 = np.sqrt((hbar**2) / (meff * self.omegaHbar))
     c = np.zeros(n + 1)
     c[n] = np.exp(-(x**2) / (2 * (x0**2))) / (np.sqrt(
         np.sqrt(np.pi) * x0 * factorial(n) * 2**n))
     return hermval(x / x0, c)
Exemplo n.º 32
0
def LastnaFunkcija(N, x):
    return float(
        np.multiply(
            np.multiply(
                Decimal(hermval(x,
                                [0 if d != N else 1 for d in range(N + 1)])),
                np.multiply(
                    Decimal(np.exp(-Decimal(x)**2 / Decimal(2))),
                    np.sqrt(
                        np.reciprocal(
                            np.multiply(Decimal(math.pow(2, N)),
                                        Decimal(math.factorial(N))))))),
            np.reciprocal(pi4)))
Exemplo n.º 33
0
 def OneDSol(n, w, x):
     b = np.sqrt(m * w / hbar)
         #So, hermval calls the Hermite polynomial corresponding to a set of
         #coefficients c. If you only want on term of a Hermite polynomial, 
         #you make an array of all 0 with the last term being 1 to grab the
         #nth term
     c = np.zeros(n+1)
     c[-1] = 1
     psi =( (b**2 / math.pi)**0.25 * 
         1 / math.sqrt(2**(n) * math.factorial(n)) * 
         np.exp(-0.5 * b**2 * x**2) * 
         hermval(b * x, c, tensor=False) )
     return psi
Exemplo n.º 34
0
 def fit(self,X,y):
     '''
     Fits the data usng the bais functions
     '''
     #first get Phi matrix bt evaluating basis functions allong each row of X
     Phi = np.vstack(map(lambda x:np.prod(hermval(x,self.coef,False),1),X))
     if self.eta == 0.:
         self.c = np.linalg.lstsq(Phi,y)[0]
     else:
         A = Phi.T.dot(Phi)
         A -= self.eta*np.eye(len(A))
         b = Phi.T.dot(y)
         self.c = np.linalg.solve(A,b)
Exemplo n.º 35
0
    def test_hermval(self) :
        def f(x) :
            return x*(x**2 - 1)

        #check empty input
        assert_equal(herm.hermval([], [1]).size, 0)

        #check normal input)
        for i in range(10) :
            msg = "At i=%d" % i
            ser = np.zeros
            tgt = self.y[i]
            res = herm.hermval(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(herm.hermval(x, [1]).shape, dims)
            assert_equal(herm.hermval(x, [1,0]).shape, dims)
            assert_equal(herm.hermval(x, [1,0,0]).shape, dims)
Exemplo n.º 36
0
  def pdf_mvsk(x,pdf0,dm=0.,dv=.99,ds=0.,dk=0.,p6=False):
    from numpy.polynomial.hermite import hermval
    from scipy.stats import norm
    from astropy.convolution import convolve

    v,m=norm.fit(pdf0)

    if dv>=1.:
      if dv==1:
        dv+=1e-4
      pdf2=norm.pdf(x,loc=np.median(x)-dm,scale=np.sqrt((dv*v)**2-v**2))
      pdf=convolve(pdf0,pdf2,normalize_kernel=True)
    else:
      v2=np.sqrt(1./(1./(v*dv)**2-1./v**2))
      m2=v2**2*((m+dm)/(v*dv)**2-m/v**2)
      pdf2=norm.pdf(x,loc=m2,scale=v2)
      norm=1./np.sqrt(2.*np.pi*v**2*v2**2/(v*dv)**2)*np.exp(-(v*dv)**2*(m-m2)**2/v2**2/v**2/2.)
      pdf=pdf0*pdf2/norm
    if p6:
      return hermval(x-m,[1.,0.,0.,ds/6.,dk/24.,0.,ds**2./72.])*pdf
    else:
      return hermval(x-m,[1.,0.,0.,ds/6.,dk/24.])*pdf
    def test_hermval(self):
        def f(x):
            return x * (x**2 - 1)

        #check empty input
        assert_equal(herm.hermval([], [1]).size, 0)

        #check normal input)
        for i in range(10):
            msg = "At i=%d" % i
            ser = np.zeros
            tgt = self.y[i]
            res = herm.hermval(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(herm.hermval(x, [1]).shape, dims)
            assert_equal(herm.hermval(x, [1, 0]).shape, dims)
            assert_equal(herm.hermval(x, [1, 0, 0]).shape, dims)
Exemplo n.º 38
0
    def test_hermval(self):
        x = np.linspace(0, 2000, 2001)
        n_array = [1, 2, 3, 0, 1]
        import numpy.polynomial.hermite as hermite
        out_true = hermite.hermval(x, n_array)
        out_approx = self.shapelets.hermval(x, n_array)
        shape_true = out_true * np.exp(-x**2 / 2.)
        shape_approx = out_approx * np.exp(-x**2 / 2.)
        npt.assert_almost_equal(shape_approx, shape_true, decimal=6)

        x = 2
        n_array = [1, 2, 3, 0, 1]
        out_true = hermite.hermval(x, n_array)
        out_approx = self.shapelets.hermval(x, n_array)
        npt.assert_almost_equal(out_approx, out_true, decimal=6)

        x = 2001
        n_array = [1, 2, 3, 0, 1]
        out_true = hermite.hermval(x, n_array)
        out_approx = self.shapelets.hermval(x, n_array)
        shape_true = out_true * np.exp(-x**2 / 2.)
        shape_approx = out_approx * np.exp(-x**2 / 2.)
        npt.assert_almost_equal(shape_approx, shape_true, decimal=6)
    def eigenFunction(self, n=0):
        """
		Parameters
		--------
		n : int, quantum number of eigenstate
		--------
		"""
        if n > 0:
            coeff = [0 for _ in range(n)]
            coeff.append(1)
        else:
            coeff = [1]
        return (self.alpha / np.pi)**(0.25) * (2**n * factorial(n))**(
            -0.5) * hermval(self.y, coeff) * np.exp(-0.5 * self.y**2)
Exemplo n.º 40
0
def phi_gaussian(e, n, X):
    """
    Evaluates the desired eigenfunction of the gaussian kernel

    Usage
      Phi = phi_gaussian(e, n, X)
    Arguments
      e   = scaling coefficient in K(x, y) = exp(-e**2 * (x - y)**2)
      n   = index
      X   = array of function input points
    Returns
      Phi = array of function values

    References
      Gregory E. Fasshauer, "Positive Definite Kernels: Past, Present and Future"
    """
    c = 1 + power(2 * e / alp, 2)
    k = power(c, 0.125) / sqrt(2**n * factorial(n)) * \
      exp(-(sqrt(c) - 1) * alp**2 * power(X, 2) / 2.)
    Xi = power(c, 0.25) * alp * X

    return k * hermite.hermval(Xi, [0] * (n - 1) + [1])
def psi(n, xs):
    return 0.4 * sqrt(1. / (2**n * factorial(n)) * sqrt(pi)) \
        * numpy.exp(-xs**2 / 2) \
        * hermval(xs, [0] * n + [1])
Exemplo n.º 42
0
    def test_hermfit(self) :
        def f(x) :
            return x*(x - 1)*(x - 2)

        # Test exceptions
        assert_raises(ValueError, herm.hermfit, [1],    [1],     -1)
        assert_raises(TypeError,  herm.hermfit, [[1]],  [1],      0)
        assert_raises(TypeError,  herm.hermfit, [],     [1],      0)
        assert_raises(TypeError,  herm.hermfit, [1],    [[[1]]],  0)
        assert_raises(TypeError,  herm.hermfit, [1, 2], [1],      0)
        assert_raises(TypeError,  herm.hermfit, [1],    [1, 2],   0)
        assert_raises(TypeError,  herm.hermfit, [1],    [1],   0, w=[[1]])
        assert_raises(TypeError,  herm.hermfit, [1],    [1],   0, w=[1,1])

        # Test fit
        x = np.linspace(0,2)
        y = f(x)
        #
        coef3 = herm.hermfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(herm.hermval(x, coef3), y)
        #
        coef4 = herm.hermfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(herm.hermval(x, coef4), y)
        #
        coef2d = herm.hermfit(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 = herm.hermfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = herm.hermfit(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 = herm.hermfit(xm, y, 3)
        assert_almost_equal(res, coef3)

        ym = y.view(maskna=1)
        ym[10] = np.NA
        res = herm.hermfit(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 = herm.hermfit(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 = herm.hermfit(x, y, 3, w=wm)
        assert_almost_equal(res, coef3)
Exemplo n.º 43
0
    def evalEnvelopeEx(self, xArray, yArray, z):

        # assume array input; try to create temporary array
        try:
            numVals = xArray.size
            result = np.zeros(numVals, complex)
        except AttributeError:
            # above failed, so input must be a float
            result = 0.0

        # rotate and shift the x,y coordinates as necessary
        rotArg = (xArray - self.xShift) * math.cos(self.wRotAngle) + (yArray - self.yShift) * math.sin(self.wRotAngle)

        # z-dependent temporary variables
        qxz = (z - self.zWaistX) + self.qx0
        xrFac = 0.5 * self.k0 / qxz
        xzFac = math.sqrt(2) / self.waistX / math.sqrt(1 + ((z - self.zWaistX) / self.zRx) ** 2)

        # load up array of mode-dependent factors
        xCoefs = np.zeros(self.mMax, complex)
        for mMode in range(self.mMax):
            xCoefs[mMode] = (
                self.hCoefs[mMode]
                * self.piWxFac
                * cmath.sqrt(self.qx0 / qxz)
                / math.sqrt(math.factorial(mMode) * (2.0 ** mMode))
                * (self.qx0 * qxz.conjugate() / self.qx0.conjugate() / qxz) ** (0.5 * mMode)
            )

        # evaluate the product of Hermite series
        result = hermval(xzFac * rotArg, xCoefs)
        result *= np.exp(-(xrFac * rotArg ** 2) * 1j)

        #
        # rinse and repeat:  do the same for the y-dependent Hermite series --
        #

        # rotate and shift the x,y coordinates as necessary
        rotArg = (yArray - self.yShift) * math.cos(self.wRotAngle) - (xArray - self.xShift) * math.sin(self.wRotAngle)

        # z-dependent temporary variables
        qyz = (z - self.zWaistY) + self.qy0
        yrFac = 0.5 * self.k0 / qyz
        yzFac = math.sqrt(2) / self.waistY / math.sqrt(1 + ((z - self.zWaistY) / self.zRy) ** 2)

        # load up array of mode-dependent factors
        xCoefs = np.zeros(self.mMax, complex)
        for mMode in range(self.mMax):
            xCoefs[mMode] = (
                self.hCoefs[mMode]
                * self.piWxFac
                * cmath.sqrt(self.qx0 / qxz)
                / math.sqrt(math.factorial(mMode) * (2.0 ** mMode))
                * (self.qx0 * qxz.conjugate() / self.qx0.conjugate() / qxz) ** (0.5 * mMode)
            )

        # load up array of mode-dependent factors (y-dependence)
        yCoefs = np.zeros(self.nMax, complex)
        for nMode in range(self.nMax):
            yCoefs[nMode] = (
                self.vCoefs[nMode]
                * self.piWyFac
                * cmath.sqrt(self.qy0 / qyz)
                / math.sqrt(math.factorial(nMode) * (2.0 ** nMode))
                * (self.qy0 * qyz.conjugate() / self.qy0.conjugate() / qyz) ** (0.5 * nMode)
            )

        # evaluate product of Hermite series (multiplying into previous value)
        result *= hermval(yzFac * rotArg, yCoefs)
        result *= np.exp(-(yrFac * rotArg ** 2) * 1j)

        # return the complex valued result
        return result
Exemplo n.º 44
0
    def test_hermint(self) :
        # check exceptions
        assert_raises(ValueError, herm.hermint, [0], .5)
        assert_raises(ValueError, herm.hermint, [0], -1)
        assert_raises(ValueError, herm.hermint, [0], 1, [0,0])

        # test integration of zero polynomial
        for i in range(2, 5):
            k = [0]*(i - 2) + [1]
            res = herm.hermint([0], m=i, k=k)
            assert_almost_equal(res, [0, .5])

        # check single integration with integration constant
        for i in range(5) :
            scl = i + 1
            pol = [0]*i + [1]
            tgt = [i] + [0]*i + [1/scl]
            hermpol = herm.poly2herm(pol)
            hermint = herm.hermint(hermpol, m=1, k=[i])
            res = herm.herm2poly(hermint)
            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]
            hermpol = herm.poly2herm(pol)
            hermint = herm.hermint(hermpol, m=1, k=[i], lbnd=-1)
            assert_almost_equal(herm.hermval(-1, hermint), 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]
            hermpol = herm.poly2herm(pol)
            hermint = herm.hermint(hermpol, m=1, k=[i], scl=2)
            res = herm.herm2poly(hermint)
            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 = herm.hermint(tgt, m=1)
                res = herm.hermint(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 = herm.hermint(tgt, m=1, k=[k])
                res = herm.hermint(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 = herm.hermint(tgt, m=1, k=[k], lbnd=-1)
                res = herm.hermint(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 = herm.hermint(tgt, m=1, k=[k], scl=2)
                res = herm.hermint(pol, m=j, k=list(range(j)), scl=2)
                assert_almost_equal(trim(res), trim(tgt))
Exemplo n.º 45
0
    def test_hermfit(self):
        def f(x):
            return x*(x - 1)*(x - 2)

        def f2(x):
            return x**4 + x**2 + 1

        # Test exceptions
        assert_raises(ValueError, herm.hermfit, [1], [1], -1)
        assert_raises(TypeError, herm.hermfit, [[1]], [1], 0)
        assert_raises(TypeError, herm.hermfit, [], [1], 0)
        assert_raises(TypeError, herm.hermfit, [1], [[[1]]], 0)
        assert_raises(TypeError, herm.hermfit, [1, 2], [1], 0)
        assert_raises(TypeError, herm.hermfit, [1], [1, 2], 0)
        assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[1, 1])
        assert_raises(ValueError, herm.hermfit, [1], [1], [-1,])
        assert_raises(ValueError, herm.hermfit, [1], [1], [2, -1, 6])
        assert_raises(TypeError, herm.hermfit, [1], [1], [])

        # Test fit
        x = np.linspace(0, 2)
        y = f(x)
        #
        coef3 = herm.hermfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(herm.hermval(x, coef3), y)
        coef3 = herm.hermfit(x, y, [0, 1, 2, 3])
        assert_equal(len(coef3), 4)
        assert_almost_equal(herm.hermval(x, coef3), y)
        #
        coef4 = herm.hermfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(herm.hermval(x, coef4), y)
        coef4 = herm.hermfit(x, y, [0, 1, 2, 3, 4])
        assert_equal(len(coef4), 5)
        assert_almost_equal(herm.hermval(x, coef4), y)
        # check things still work if deg is not in strict increasing
        coef4 = herm.hermfit(x, y, [2, 3, 4, 1, 0])
        assert_equal(len(coef4), 5)
        assert_almost_equal(herm.hermval(x, coef4), y)
        #
        coef2d = herm.hermfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        coef2d = herm.hermfit(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 = herm.hermfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        wcoef3 = herm.hermfit(x, yw, [0, 1, 2, 3], w=w)
        assert_almost_equal(wcoef3, coef3)
        #
        wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        wcoef2d = herm.hermfit(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(herm.hermfit(x, x, 1), [0, .5])
        assert_almost_equal(herm.hermfit(x, x, [0, 1]), [0, .5])
        # test fitting only even Legendre polynomials
        x = np.linspace(-1, 1)
        y = f2(x)
        coef1 = herm.hermfit(x, y, 4)
        assert_almost_equal(herm.hermval(x, coef1), y)
        coef2 = herm.hermfit(x, y, [0, 2, 4])
        assert_almost_equal(herm.hermval(x, coef2), y)
        assert_almost_equal(coef1, coef2)
 def get_hermite_polynomial(self, n, x):
     return hermval(x, [0]*n+[1])
Exemplo n.º 47
0
    def evaluateEField(self, coords, t):
        """ Calculate the electric field for an array of particles with
        positions x at time t in a Hermite-Gauss laser field

        :param x: numpy array of particle positions
        :param t: time as a float
        :return: numpy array of electric field 3-component vectors
        """

        # Create empty electric field holder
        theEFields = np.zeros(coords.shape[0] * 3, dtype=complex)\
            .reshape(coords.shape[0], 3)

        # Create a temporary variable to store rotated coordinates. This
        # prevents accidental re-assignment. Only access the rotatedCoords
        # from here on out
        #rotatedCoords = np.zeros(coords.shape[0]*3).reshape(coords.shape[
        # 0], 3)
        rotatedCoords = np.dot(self.rotationMatrix, coords.T).T

        # Compute the Hermite-Gauss coefficients, which have some
        # z-dependence that requires they be computed for every time step.
        # This multiplies the base laser mode coefficients, and therefore
        # has to be created as a temporary variable to avoid modifying the
        # original laser parameters. This assumes a 2D laser
        qxz    = np.zeros(rotatedCoords.shape[0], dtype=complex)
        qxz[:] = (rotatedCoords[:,2] - self.zWaistX) + self.qx0
        xrFac  = 0.5 * self.k0 / qxz
        xzFac  = (np.sqrt(2)/self.waistX)/\
                 np.sqrt(1+((coords[:,2]-self.zWaistX)/self.zRx)**2)

        qyz    = np.zeros(rotatedCoords.shape[0], dtype=complex)
        qyz[:] = (rotatedCoords[:,2] - self.zWaistY) + self.qy0
        yrFac  = 0.5 * self.k0 / qyz
        yzFac  = (np.sqrt(2)/self.waistY)/\
                 np.sqrt(1+((coords[:,2]-self.zWaistY)/self.zRy)**2)

        # Iterate over the coefficients, computing the particle-dependent
        # normalization coefficients for the Hermite-Gauss series
        # Have to compute the Hermite-Gauss series explicitly for optimal
        # control -- recommend against attempting to use hermval2d
        ptclCoefs = copy.deepcopy([self.hermCoeffs]*coords.shape[0])

        for idx in range(0,coords.shape[0]):
            for nidx in range(0,self.hermCoeffs.shape[0]):
                for midx in range(0,self.hermCoeffs.shape[1]):
                    ptclCoefs[idx][nidx,midx] /=\
                        np.sqrt(np.math.factorial(midx)*(2.**midx)*
                                np.math.factorial(nidx)*(2.**nidx))
                    ptclCoefs[idx][nidx,midx] *= (self.piWxFac)*np.sqrt(
                        self.qx0/qxz[idx])
                    ptclCoefs[idx][nidx,midx] *= (self.qx0*qxz[idx].conjugate()/
                        self.qx0.conjugate()/qxz[idx])**(0.5*(midx))

                    ptclCoefs[idx][nidx,midx] *= (self.piWyFac)*np.sqrt(
                        self.qy0/qyz[idx])
                    ptclCoefs[idx][nidx,midx] *= (self.qy0*qxz[idx].conjugate()/
                        self.qy0.conjugate()/qyz[idx])**(0.5*(nidx))

        # Explicitly iterate through the particles, since this seems to be
        # the only way to keep control over the Hermite functions
        myNewCoeffs = np.zeros(self.hermCoeffs.shape[0], dtype=complex)
        for idx in range(0,coords.shape[0]):
            for xidx in range(0, self.hermCoeffs.shape[0]):
                myNewCoeffs[xidx] = hermval(yzFac[idx]*coords[idx,1],
                                            ptclCoefs[idx][xidx])

            theEFields[idx,:] = self.polVector[:]* \
                                hermval(xzFac[idx]*coords[idx,0], myNewCoeffs)

            theEFields[idx]*=\
                np.exp(-(xrFac[idx]*(coords[idx,0]**2+coords[idx,1]**2)*1j))

            theEFields[idx,:] *= \
                np.exp(-(yrFac[idx]*(coords[idx,0]**2+coords[idx,1]**2)*1j))


            theEFields[idx]*=\
                np.exp((self.omega * t - self.k0 * coords[idx,2])*1j)

        return theEFields.real