def Combinations(values, k):
    """This function outputs all the possible combinations of k elements from the vector values"""

    if int(k) < 0:
        raise ValueError("k must a positive integer")

    #Make input vectors column vectors
    if values.shape == (1, values.size):
        values = sp.atleast2d(values).T.copy()

    out = sp.array([]).reshape(0, 1)
    n = max(values.shape)
    if k == 1:
        out = values
    else:
        #the following loop interates through all the elements of the vector values that have at least k elements after them.  For each element it then calls Combinations(values[i+1:], k-1) which returns combinations of size k-1 for the elements succeeding the current element.  This is so that we do not get repeats of combinations
        #nck = sp.misc.comb(n,k, exact=True)
        #out = sp.zeros((nck, k))
        for i in range(n - (k - 1)):
            #Calculate the number of possible combinations (to allow proper concatenation in the recursive call
            nCombs = int(
                sp.factorial(n - i) /
                (sp.factorial(k - 1) * sp.factorial(n - i - (k - 1))))
            #This is the recursive call

            print Combinations(values[i + 1:], k - 1).reshape((-1, 1))
            out = sp.r_[out, sp.c_[values[i] * sp.ones((nCombs, 1)),
                                   Combinations(values[i + 1:], k -
                                                1).reshape(-1, 1)]]

    return out
示例#2
0
def _sch_lpmv(n, x):
    '''
	Outputs array of Schmidt Seminormalized Associated Legendre Functions S_{n}^{m} for m<=n.
	
	Parameters
	----------
	n : int 
	    Degree of polynomial.
	
	x : float 
	    Point at which to evaluate
	
	Returns
	-------
	array of values for Legendre functions. 
	
	'''
    from scipy.special import lpmv
    sch = array([1.0])
    sch2 = array([(-1.0)**m * sqrt((2.0 * factorial(n - m)) / factorial(n + m))
                  for m in range(1, n + 1)])
    sch = append(sch, sch2)
    if isinstance(x, float) or len(x) == 1:
        leg = lpmv(arange(0, n + 1), n, x)
        return array([sch * leg]).T
    else:
        for j in range(0, len(x)):
            leg = lpmv(range(0, n + 1), n, x[j])
            if j == 0:
                out = array([sch * leg]).T
            else:
                out = append(out, array([sch * leg]).T, axis=1)
    return out
def Combinations(values, k):
    """This function outputs all possible combinations of k elements from the column vector values"""
    n = len(values)
    try:
        values = sp.row_stack(values)
    except:
        raise ValueError, "I need a 2d column array"

    if k > n:
        raise ValueError, "k must be <= %d" % n
    elif k <= 0 or k % 1 != 0:
        raise ValueError, "k must be > 0"

    #out = sp.array([],ndmin=2)
    if k == 1:
        return values
    else:
        #This loop iterates through all the elements of the values that have at least
        #k elements.  For each element it then calls Combinations(values[i+1:], k-1) which
        #returns combinations of size k-1 for the elements succeeding the current element
        #We do not want to get repeats of combinations
        #print "for i in range(%d)" % (n-(k-1))
        for i in range(n - (k - 1)):
            #Calculate the number of possible combinations (to allow proper concatenation
            #in the recursive call
            numCombs = sp.factorial(n - i) / (sp.factorial(k - 1) *
                                              sp.factorial(n - i - (k - 1)))
            combs = Combinations(values[i:], k - 1)
            ones = values[i] * sp.ones((numCombs, 1))
            #print "ones: %s \t\t combs: %s" % (str(ones.shape), str(combs.shape))
            print combs
示例#4
0
def prehamiltonian( genlags, EC, EJ, EL ):
    ### NB: omits a factor of EJ (on top of the flux dependency and the 
    ### diagonal terms) for use as a derivative later
    size = len(genlags)
    hbar_w0 = sqrt( 8. * EL * EC )
    phi0 = ( 8. * EC / EL ) ** .25 
    arg = phi0**2/2
    
    genlags = [[ f(arg) for f in row ] for row in genlags]
    ret = [ range(size) for i in range(size) ] #values set below

    for row in range(size):
        for col in range(size):
            #the nonzero cosine elements
            if (col-row)%2==0:
                n = min(row,col)
                m = abs(col-row)/2 # because of Hermitianness
                ret[row][col] = -(-2)**-m \
                    * sqrt(factorial(n)/factorial(n+2*m)) \
                    * phi0**(2*m) * exp(phi0**2/-4) \
                    * genlags[n][2*m]
            #the nonzero sine elements
            else:
                ### IS THIS PART RIGHT?
                n = min(row,col)
                m = (abs(col-row)-1)/2
                ret[row][col] = -(-2)**(-m) * 2**-.5 \
                    * sqrt(factorial(n)/factorial(n+2*m+1)) \
                    * phi0**(2*m+1) * exp(phi0**2/-4) \
                    * genlags[n][2*m+1] ## Check overall signs
    return array(ret)
示例#5
0
 def alpha(k, m, n):
     tau = t_intervals[n - 1]
     i = np.arange(m + 1)[:, np.newaxis]
     the_sum = np.sum((1j*k*omega)**(-m+i-1) * \
                          tau[:,np.newaxis]**i / factorial(i), axis=-2)
     integral = -factorial(m) * np.exp(-1j * k * omega * tau) * the_sum
     return integral[:, 1] - integral[:, 0]
示例#6
0
 def alpha(k,m,n):
     tau = t_intervals[n-1]
     i = np.arange(m+1)[:,np.newaxis]
     the_sum = np.sum((1j*k*omega)**(-m+i-1) * \
                          tau[:,np.newaxis]**i / factorial(i), axis=-2)
     integral = -factorial(m) * np.exp(-1j * k * omega * tau) * the_sum
     return integral[:,1] - integral[:,0]
示例#7
0
def _sch_lpmv(n,x):
	'''
	Outputs array of Schmidt Seminormalized Associated Legendre Functions S_{n}^{m} for m<=n.
	
	Parameters
	----------
	n : int 
	    Degree of polynomial.
	
	x : float 
	    Point at which to evaluate
	
	Returns
	-------
	array of values for Legendre functions. 
	
	'''
	from scipy.special import lpmv
	sch=array([1.0])
	sch2=array([(-1.0)**m*sqrt((2.0*factorial(n-m))/factorial(n+m)) for m in range(1,n+1)])
	sch=append(sch,sch2)
	if isinstance(x,float) or len(x)==1:
		leg=lpmv(arange(0,n+1),n,x)
		return array([sch*leg]).T
	else:
		for j in range(0,len(x)):
			leg=lpmv(range(0,n+1),n,x[j])
			if j==0:
				out=array([sch*leg]).T
			else:
				out=append(out,array([sch*leg]).T,axis=1)
	return out
def Combinations(values, k):
    """This function outputs all possible combinations of k elements from the column vector values"""
    n = len(values)
    try:
        values = sp.row_stack(values)
    except:
        raise ValueError, "I need a 2d column array"

    if k > n:
        raise ValueError, "k must be <= %d" % n
    elif k<=0 or k%1 != 0:
        raise ValueError, "k must be > 0"

    #out = sp.array([],ndmin=2)
    if k == 1:
        return values
    else:
        #This loop iterates through all the elements of the values that have at least
        #k elements.  For each element it then calls Combinations(values[i+1:], k-1) which
        #returns combinations of size k-1 for the elements succeeding the current element
        #We do not want to get repeats of combinations
        #print "for i in range(%d)" % (n-(k-1))
        for i in range(n-(k-1)):
            #Calculate the number of possible combinations (to allow proper concatenation
            #in the recursive call
            numCombs = sp.factorial(n-i)/(sp.factorial(k-1)*sp.factorial(n-i-(k-1)))
            combs = Combinations(values[i:], k-1)
            ones = values[i]*sp.ones((numCombs,1))
            #print "ones: %s \t\t combs: %s" % (str(ones.shape), str(combs.shape))
            print combs
def Combinations(values, k):
    """This function outputs all the possible combinations of k elements from the vector values"""
    
    if int(k) < 0:
        raise ValueError("k must a positive integer")
    
    #Make input vectors column vectors
    if values.shape == (1,values.size):
        values = sp.atleast2d(values).T.copy()
    
    out = sp.array([]).reshape(0,1)
    n = max(values.shape)
    if k == 1:
        out = values
    else:
        #the following loop interates through all the elements of the vector values that have at least k elements after them.  For each element it then calls Combinations(values[i+1:], k-1) which returns combinations of size k-1 for the elements succeeding the current element.  This is so that we do not get repeats of combinations
        #nck = sp.misc.comb(n,k, exact=True)
        #out = sp.zeros((nck, k))
        for i in range(n-(k-1)):
            #Calculate the number of possible combinations (to allow proper concatenation in the recursive call
            nCombs = int(sp.factorial(n-i)/(sp.factorial(k-1)*sp.factorial(n-i-(k-1))))
            #This is the recursive call
            
            print Combinations(values[i+1:], k-1).reshape((-1,1))
            out = sp.r_[out, sp.c_[values[i]*sp.ones((nCombs,1)), Combinations(values[i+1:], k-1).reshape(-1,1)]]
            
    return out
示例#10
0
 def delta(a,b,c):
     """ Calculate delta """
     fac = zeros(4,long)
     fac[0] = factorial(a+b-c)
     fac[1] = factorial(a-b+c)
     fac[2] = factorial(-a+b+c)
     fac[3] = factorial(a+b+c+1)
     return sqrt(prod(fac[0:3])/fac[3]);
示例#11
0
def basis2d(n0,n1,beta=[1.,1.]):
    """2d dimensionless Cartesian basis function"""
    b=hermite2d(n0,n1)
    b[0]*=((2**n0)*(n.pi**(.5))*scipy.factorial(n0))**(-.5)
    exp0=lambda x: beta[0] * b[0](x) * n.exp(-.5*(x**2))
    b[1]*=((2**n1)*(n.pi**(.5))*scipy.factorial(n1))**(-.5)
    exp1=lambda x: beta[1] * b[1](x) * n.exp(-.5*(x**2))
    return [exp0,exp1]
示例#12
0
文件: e4a8.py 项目: laevar/mapy
def bernstein(n):
    """ Bernstein-Polynome (n!/(i!(n-i)!)* t^i (1-t)^(n-i)"""
    t = linspace(0,1,20)

    bmat = zeros((20,n+1))
    for i in range(0,n+1):
        bmat[:,i] = sp.factorial(n)/(sp.factorial(i)*sp.factorial(n-i))*t**i*(1-t)**(n-i)
    return bmat
示例#13
0
def dimBasis2d(n0,n1,beta=[1.,1.],phs=[1.,1.]):
    """2d dimensional Cartesian basis function of characteristic size beta
    phs: additional phase factor, used in the Fourier Transform"""
    b=hermite2d(n0,n1)
    b[0]*=(beta[0]**(-.5))*(((2**n0)*(n.pi**(.5))*scipy.factorial(n0))**(-.5))
    exp0=lambda x: b[0](x/beta[0]) * n.exp(-.5*((x/beta[0])**2)) * phs[0]
    b[1]*=(beta[1]**(-.5))*(((2**n1)*(n.pi**(.5))*scipy.factorial(n1))**(-.5))
    exp1=lambda x: b[1](x/beta[1]) * n.exp(-.5*((x/beta[1])**2)) * phs[1]
    return [exp0,exp1]
示例#14
0
def C(n, r):
    if n - r > r:
        num = np.prod(np.arange(n - r + 1, n+1))
        den = factorial(r)
        return num / den
    else:
        num = np.prod(np.arange(r + 1, n+1))
        den = factorial(n - r)
        return num / den
示例#15
0
def plot_messung(n, t, b_len, y_lim, lens, rate):
    mu, sigma = np.mean(n), np.std(n)
    print "Mittelwert: %.3f" % mu
    print "Varianz: %.3f Poisson: %.3f" % (sigma ** 2, mu)
    print "Standardabweichung: %.3f Poisson: %.3f" % (sigma, np.sqrt(mu))
    print "Standardabweichung des Mittelwerts: %.3f Poisson: %.3f" % (
        sigma / np.sqrt(len(n)),
        np.sqrt(mu) / np.sqrt(len(n)),
    )
    print "Gesamtanzahl der Ereignisse:", np.sum(n)
    print "mittlere Zaehlrate: %.3f 1/s" % (np.mean(n) / (rate))
    print "Standardabweichung der Zaehlrate: %.3f 1/s" % (np.std(n) / rate)
    print "Standardabweichung der mittleren Zaehlrate: %.3f 1/s" % (np.std(n) / rate / np.sqrt(len(n)))
    print "Schiefe: %.3f Poisson: %.3f" % (np.mean((n - n.mean()) ** 3) / sigma ** 3, 1 / np.sqrt(mu))
    print "Kurtosis: %.3f Poisson: %.3f" % (np.mean((n - n.mean()) ** 4) / sigma ** 4 - 3, 1 / (mu))
    print ""
    fig = plt.figure(figsize=(16, 12))
    ax = fig.add_subplot(111)

    # the histogram of the data
    n, bins, patches = ax.hist(n, lens, normed=1, facecolor="yellow", alpha=0.75)

    bincenters = 0.5 * (bins[1:] + bins[:-1])
    b = np.linspace(0, b_len, 1000)
    b2 = np.arange(0, b_len, 1) + 0.5

    # add a 'best fit' line for the normal PDF
    # y = mlab.normpdf( b, mu, sigma)
    # y2 =mlab.normpdf( b2, mu, sigma)
    # l = ax.plot(b, y, 'b--', linewidth=1)
    poisson = lambda k: 1.0 / (sc.factorial(k) * np.exp(mu)) * mu ** k
    poisson2 = lambda k: 1.0 / (sc.factorial(k) * np.exp(mu + sigma)) * (mu + sigma) ** k
    poisson3 = lambda k: 1.0 / (sc.factorial(k) * np.exp(mu - sigma)) * (mu - sigma) ** k
    normal_k = lambda k: 1.0 / np.sqrt(2 * np.pi * mu) * np.exp(-(k - mu) ** 2 / (2 * mu))
    normal_k2 = (
        lambda k: 1.0 / np.sqrt(2 * np.pi * (mu + sigma)) * np.exp(-(k - (mu + sigma)) ** 2 / (2 * (mu + sigma)))
    )
    normal_k3 = (
        lambda k: 1.0 / np.sqrt(2 * np.pi * (mu - sigma)) * np.exp(-(k - (mu - sigma)) ** 2 / (2 * (mu - sigma)))
    )

    nk = ax.plot(b, normal_k(b), "g--", linewidth=1)
    nk = ax.plot(b, normal_k2(b), "g--", linewidth=1)
    nk = ax.plot(b, normal_k3(b), "g--", linewidth=1)
    p = ax.plot(b, poisson(b), "r--", linewidth=1)
    p = ax.plot(b, poisson2(b), "r--", linewidth=1)
    p = ax.plot(b, poisson3(b), "r--", linewidth=1)
    l = ax.scatter(b2, normal_k(b2), marker="x", c="b")
    p = ax.scatter(b2, poisson(b2), marker="x", c="b")

    ax.set_xlabel("Anzahl der Impulse")
    ax.set_ylabel("Wahrscheinlichkeit")
    plt.xlim(0, b_len)
    plt.ylim(0, y_lim)
    ax.grid(True)

    plt.show()
示例#16
0
def factorialQuotient(numerator, denominator):
    """
    result=numerator!/(denominator!)
    """
    diff = numerator - denominator
    if diff > 0:
        result = factorial(diff)
    else:
        result = 1.0 / factorial(-diff)
    return result
def plot_pdf(order, N, iterations):
	order_stats = []
	for it in range(iterations):
		numbers = [np.random.uniform(0,1) for i in range(N)]
		numbers.sort()
		order_stats.append(numbers[order-1])
	plt.figure()
	n, bins, patches = plt.hist(order_stats, iterations/20, normed=1, facecolor='green')
	y = lambda x: int(sp.factorial(N))/(int(sp.factorial(N-order))*int(sp.factorial(order-1))) * x**(order-1) * (1-x)**(N-order)
	plt.plot(bins, y(bins), 'r--', linewidth=3)
示例#18
0
def Wigner6j(j1,j2,j3,J1,J2,J3):
#======================================================================
# Calculating the Wigner6j-Symbols using the Racah-Formula                
# Author: Ulrich Krohn                                            
# Date: 13th November 2009
#                                                                         
# Based upon Wigner3j.m from David Terr, Raytheon                         
# Reference: http://mathworld.wolfram.com/Wigner6j-Symbol.html            
#
# Usage: 
# from wigner import Wigner6j
# WignerReturn = Wigner6j(j1,j2,j3,J1,J2,J3)
#
#  / j1 j2 j3 \
# <            >  
#  \ J1 J2 J3 /
#
#======================================================================

    # Check that the js and Js are only integer or half integer
    if ( ( 2*j1 != round(2*j1) ) | ( 2*j2 != round(2*j2) ) | ( 2*j2 != round(2*j2) ) | ( 2*J1 != round(2*J1) ) | ( 2*J2 != round(2*J2) ) | ( 2*J3 != round(2*J3) ) ):
        print 'All arguments must be integers or half-integers.'
        return -1
    
# Check if the 4 triads ( (j1 j2 j3), (j1 J2 J3), (J1 j2 J3), (J1 J2 j3) ) satisfy the triangular inequalities
    if ( ( abs(j1-j2) > j3 ) | ( j1+j2 < j3 ) | ( abs(j1-J2) > J3 ) | ( j1+J2 < J3 ) | ( abs(J1-j2) > J3 ) | ( J1+j2 < J3 ) | ( abs(J1-J2) > j3 ) | ( J1+J2 < j3 ) ):
        print '6j-Symbol is not triangular!'
        return 0
    
    # Check if the sum of the elements of each traid is an integer
    if ( ( 2*(j1+j2+j3) != round(2*(j1+j2+j3)) ) | ( 2*(j1+J2+J3) != round(2*(j1+J2+J3)) ) | ( 2*(J1+j2+J3) != round(2*(J1+j2+J3)) ) | ( 2*(J1+J2+j3) != round(2*(J1+J2+j3)) ) ):
        print '6j-Symbol is not triangular!'
        return 0
    
    # Arguments for the factorials
    t1 = j1+j2+j3
    t2 = j1+J2+J3
    t3 = J1+j2+J3
    t4 = J1+J2+j3
    t5 = j1+j2+J1+J2
    t6 = j2+j3+J2+J3
    t7 = j1+j3+J1+J3

    # Finding summation borders
    tmin = max(0, max(t1, max(t2, max(t3,t4))))
    tmax = min(t5, min(t6,t7))
    tvec = arange(tmin,tmax+1,1)
        
    # Calculation the sum part of the 6j-Symbol
    WignerReturn = 0
    for t in tvec:
        WignerReturn += (-1)**t*factorial(t+1)/( factorial(t-t1)*factorial(t-t2)*factorial(t-t3)*factorial(t-t4)*factorial(t5-t)*factorial(t6-t)*factorial(t7-t) )

    # Calculation of the 6j-Symbol
    return WignerReturn*sqrt( TriaCoeff(j1,j2,j3)*TriaCoeff(j1,J2,J3)*TriaCoeff(J1,j2,J3)*TriaCoeff(J1,J2,j3) )
def multivariate_polya_vectorized(x,alpha):
    """Multivariate Pólya PDF. Vectorized implementation.
    """
    x = np.atleast_1d(x)
    alpha = np.atleast_1d(alpha)
    assert(x.size==alpha.size)
    N = x.sum()
    A = alpha.sum()
    likelihood = factorial(N) / factorial(x).prod() * gamma(A) / gamma(N + A)
    likelihood *= (gamma(x + alpha) / gamma(alpha)).prod()
    return likelihood
def multivariate_polya(x, alpha):
    """Multivariate Pólya PDF. Basic implementation.
    """
    x = np.atleast_1d(x).flatten()
    alpha = np.atleast_1d(alpha).flatten()
    assert(x.size==alpha.size)
    N = x.sum()
    A = alpha.sum()
    likelihood = factorial(N) * gamma(A) / gamma(N + A)
    # likelihood = gamma(A) / gamma(N + A)
    for i in range(len(x)):
        likelihood /= factorial(x[i])
        likelihood *= gamma(x[i] + alpha[i]) / gamma(alpha[i])
    return likelihood
示例#21
0
def plot_messung3():
    H = np.array([6.45 * 10 ** 2, 3.45 * 10 ** 2, 9.5 * 10, 14, 2])
    mu = np.sum(H * np.arange(0, 5, 1)) / np.sum(H)
    n = np.arange(0, 5, 1)
    sigma = np.sqrt((np.sum(H * (np.arange(0, 5, 1) - mu) ** 2) / (np.sum(H) - 1)))
    print "Mittelwert: %.3f" % mu
    print "Varianz: %.3f Poisson: %.3f" % (sigma ** 2, mu)
    print "Standardabweichung: %.3f Poisson: %.3f" % (sigma, np.sqrt(mu))
    print "Standardabweichung des Mittelwerts: %.3f Poisson: %.3f" % (
        sigma / np.sqrt(np.sum(H)),
        np.sqrt(mu) / np.sqrt(np.sum(H)),
    )
    print "Gesamtanzahl der Ereignisse:", np.sum(H * n)
    print "mittlere Zaehlrate: %.3f 1/s" % (mu / (0.5))
    print "Standardabweichung der Zaehlrate: %.3f 1/s" % (sigma / 0.5)
    print "Standardabweichung der mittleren Zaehlrate: %.3f 1/s" % (sigma / 0.5 / np.sqrt(np.sum(H)))
    print "Schiefe: %.3f Poisson: %.3f" % ((np.sum(H * (n - mu) ** 3) / np.sum(H)) / sigma ** 3, 1 / np.sqrt(mu))
    print "Kurtosis: %.3f Poisson: %.3f" % ((np.sum(H * (n - mu) ** 4) / np.sum(H)) / sigma ** 4 - 3, 1 / (mu))

    print ""

    fig = plt.figure(figsize=(16, 12))
    plt.scatter(np.arange(0, 4 + 1, 1), H / 1101, marker="^", s=80)
    poisson = lambda k: 1.0 / (sc.factorial(k) * np.exp(mu)) * mu ** k
    poisson_min = lambda k: 1.0 / (sc.factorial(k) * np.exp(mu - sigma)) * (mu - sigma) ** k
    poisson_max = lambda k: 1.0 / (sc.factorial(k) * np.exp(mu + sigma)) * (mu + sigma) ** k
    normal_k = lambda k: 1.0 / np.sqrt(2 * np.pi * mu) * np.exp(-(k - mu) ** 2 / (2 * mu))
    normal_k_min = (
        lambda k: 1.0 / np.sqrt(2 * np.pi * (mu - sigma)) * np.exp(-(k - mu - sigma) ** 2 / (2 * mu - 2 * sigma))
    )
    normal_k_max = (
        lambda k: 1.0 / np.sqrt(2 * np.pi * (mu + sigma)) * np.exp(-(k - mu + sigma) ** 2 / (2 * mu + 2 * sigma))
    )
    b = np.linspace(0, 5, 100)
    b2 = np.arange(0, 5, 1)
    # plt.plot(b, normal_k(b), 'g--', linewidth=1)
    plt.plot(b, normal_k_min(b), "g--", linewidth=1)
    # plt.plot(b, normal_k_max(b), 'g--', linewidth=1)
    # plt.plot(b, poisson(b), 'r--', linewidth=1)
    plt.plot(b, poisson_min(b), "r--", linewidth=1)
    # plt.plot(b, poisson_max(b), 'r--', linewidth=1)
    plt.scatter(b2, normal_k(b2), marker="x", c="b")
    plt.scatter(b2, poisson(b2), marker="x", c="b")
    plt.title("Messung 3")
    plt.xlabel("Anzahl der Pulse")
    plt.ylabel("Wahrscheinlichkeit")
    plt.grid(True)
    plt.xlim(0, 5)
    plt.ylim(0, 0.7)
    plt.show()
示例#22
0
def _wigner_laguerre(rho, xvec, yvec, g, parallel):
    """
    Using Laguerre polynomials from scipy to evaluate the Wigner function for
    the density matrices :math:`|m><n|`, :math:`W_{mn}`. The total Wigner
    function is calculated as :math:`W = \sum_{mn} \\rho_{mn} W_{mn}`.
    """

    M = prod(rho.shape[0])
    X, Y = meshgrid(xvec, yvec)
    A = 0.5 * g * (X + 1.0j * Y)
    W = zeros(np.shape(A))

    # compute wigner functions for density matrices |m><n| and
    # weight by all the elements in the density matrix
    B = 4 * abs(A) ** 2
    if sp.isspmatrix_csr(rho.data):
        # for compress sparse row matrices
        if parallel:
            iterator = (
                (m, rho, A, B) for m in range(len(rho.data.indptr) - 1))
            W1_out = parfor(_par_wig_eval, iterator)
            W += sum(W1_out)
        else:
            for m in range(len(rho.data.indptr) - 1):
                for jj in range(rho.data.indptr[m], rho.data.indptr[m + 1]):
                    n = rho.data.indices[jj]

                    if m == n:
                        W += real(rho[m, m] * (-1) ** m * genlaguerre(m, 0)(B))

                    elif n > m:
                        W += 2.0 * real(rho[m, n] * (-1) ** m *
                                        (2 * A) ** (n - m) *
                                        sqrt(factorial(m) / factorial(n)) *
                                        genlaguerre(m, n - m)(B))
    else:
        # for dense density matrices
        B = 4 * abs(A) ** 2
        for m in range(M):
            if abs(rho[m, m]) > 0.0:
                W += real(rho[m, m] * (-1) ** m * genlaguerre(m, 0)(B))
            for n in range(m + 1, M):
                if abs(rho[m, n]) > 0.0:
                    W += 2.0 * real(rho[m, n] * (-1) ** m *
                                    (2 * A) ** (n - m) *
                                    sqrt(factorial(m) / factorial(n)) *
                                    genlaguerre(m, n - m)(B))

    return 0.5 * W * g ** 2 * np.exp(-B / 2) / pi
示例#23
0
def Negbin(x, r, p):
    """
    Negative Binomial Log-Likelihood 

    :param x: data
    :param r:
    :param p:

    >>> Negbin([2,3],6,0.3)
    -9.16117424315
    """
    x = array(x)
    like = sum(r * log(p) + x * log(1 - p) + log(scipy.factorial(x + r - 1)) - log(scipy.factorial(x)) - log(
        scipy.factorial(r - 1)))
    return like
示例#24
0
def Binomial(x, n, p):
    """
    Binomial Log-Likelihood 

    :param x: data
    :param n:
    :param p:

    >>> Binomial([2,3],6,0.3)
    -2.81280615454
    """
    x = array(x)
    like = sum(x * log(p) + (n - x) * log(1. - p) + log(scipy.factorial(n)) - log(scipy.factorial(x)) - log(
        scipy.factorial(n - x)))
    return like
示例#25
0
def polarDimBasis(n0, m0, beta=1.0, phs=1.0):
    """Polar dimensional basis function based on Laguerre polynomials of characteristic size beta
    phs: additional phase factor, used in the Fourier Transform"""
    b0 = laguerre(n0, m0)
    norm = (((-1.0) ** ((n0 - n.abs(m0)) / 2)) / (beta ** (n.abs(m0) + 1))) * (
        (float(scipy.factorial(int((n0 - n.abs(m0)) / 2))) / float(scipy.factorial(int((n0 + n.abs(m0)) / 2)))) ** 0.5
    )
    exp0 = (
        lambda r, th: norm
        * r ** (n.abs(m0))
        * b0((r ** 2.0) / (beta ** 2.0))
        * n.exp(-0.5 * (r ** 2.0) / (beta ** 2.0))
        * n.exp(-1j * m0 * th)
    )
    return exp0
示例#26
0
def _wigner_laguerre(rho, xvec, yvec, g, parallel):
    """
    Using Laguerre polynomials from scipy to evaluate the Wigner function for
    the density matrices :math:`|m><n|`, :math:`W_{mn}`. The total Wigner
    function is calculated as :math:`W = \sum_{mn} \\rho_{mn} W_{mn}`.
    """

    M = prod(rho.shape[0])
    X, Y = meshgrid(xvec, yvec)
    A = 0.5 * g * (X + 1.0j * Y)
    W = zeros(np.shape(A))

    # compute wigner functions for density matrices |m><n| and
    # weight by all the elements in the density matrix
    B = 4 * abs(A)**2
    if sp.isspmatrix_csr(rho.data):
        # for compress sparse row matrices
        if parallel:
            iterator = ((m, rho, A, B)
                        for m in range(len(rho.data.indptr) - 1))
            W1_out = parfor(_par_wig_eval, iterator)
            W += sum(W1_out)
        else:
            for m in range(len(rho.data.indptr) - 1):
                for jj in range(rho.data.indptr[m], rho.data.indptr[m + 1]):
                    n = rho.data.indices[jj]

                    if m == n:
                        W += real(rho[m, m] * (-1)**m * genlaguerre(m, 0)(B))

                    elif n > m:
                        W += 2.0 * real(rho[m, n] * (-1)**m *
                                        (2 * A)**(n - m) *
                                        sqrt(factorial(m) / factorial(n)) *
                                        genlaguerre(m, n - m)(B))
    else:
        # for dense density matrices
        B = 4 * abs(A)**2
        for m in range(M):
            if abs(rho[m, m]) > 0.0:
                W += real(rho[m, m] * (-1)**m * genlaguerre(m, 0)(B))
            for n in range(m + 1, M):
                if abs(rho[m, n]) > 0.0:
                    W += 2.0 * real(rho[m, n] * (-1)**m * (2 * A)**(n - m) *
                                    sqrt(factorial(m) / factorial(n)) *
                                    genlaguerre(m, n - m)(B))

    return 0.5 * W * g**2 * np.exp(-B / 2) / pi
示例#27
0
def zernike2taylor(n, m):
    """
    Returns the 2D taylor polynomial, that represents the given zernike
    polynomial
    
    **ARGUMENTS**
    
        n,m     n and m orders of the Zernike polynomials
    
    **RETURN VALUE**
        poly2d instance containing the polynomial
    """
    TC = zeros((n + 1, n + 1))
    mm = (n - m) / 2
    am = abs(m)
    if m > 0:
        B = mm
        if n % 2 == 0:
            p = 1
            q = (m / 2) - 1
        else:
            p = 1
            q = (m - 1) / 2
    else:
        B = n - mm
        if n % 2 == 0:
            p = 0
            q = -(m / 2)
        else:
            p = 0
            q = -(m + 1) / 2
    for i in range(q + 1):
        for j in range(B + 1):
            for k in range(B - j + 1):
                c = pow(-1, i + j) * binomial(am, 2 * i + p) * binomial(
                    B - j, k) * int(factorial(n - j)) / (
                        int(factorial(j)) * int(factorial(mm - j)) *
                        int(factorial(n - mm - j)))
                x_pow = 2 * (i + k) + p
                y_pow = n - 2 * (i + j + k) - p
                TC[y_pow, x_pow] = TC[y_pow, x_pow] + c

    n = TC.shape[0] - 1
    cohef = [0.] * ord2i(n)
    for i in range(ord2i(n)):
        px, py = i2pxpy(i)
        cohef[i] = TC[px, py]
    return poly2d(cohef)
示例#28
0
def PNbarplot(npoints=10000, N=2):
    lx = list(np.arange(npoints)*15.0/npoints)
    fig = Figure(figsize=(6,6))

# Create a canvas and add the figure to it.
    canvas = FigureCanvas(fig)

# Create a subplot.
    ax = fig.add_subplot(111)

# Set the title.
    ax.set_title('P(N=2, Nbar)',fontsize=14)

# Set the X Axis label.
    ax.set_ylabel('P(N=2, Nbar)',fontsize=12)

# Set the Y Axis label.
    ax.set_xlabel('Nbar',fontsize=12)

# Display Grid.
    ax.grid(True,linestyle='-',color='0.75')

# Generate the Scatter Plot.
    ly = [np.exp(-x)*x**(float(N))/sp.factorial(N) for x in lx]
    print sum(ly)

    ax.scatter(lx,ly,s=.05,color='tomato');
    canvas.print_figure('hw4PNbarplot',dpi=500)
示例#29
0
 def logfact(n):
     if memo.has_key(n):
         return memo[n]
     else:
         memo[n] = math.log(scipy.factorial(n))
         print "(memoized logfact(%d) = %f)" % (n, memo[n])
         return memo[n]
示例#30
0
def shapelet_image(basis, beta, centre, hc, nx, ny, size):
    """ Takes basis, beta, centre (2-tuple), hc matrix, x, y, size and returns the image of the shapelet of
    order nx,ny on an image of size size. Does what getcartim.f does in fBDSM. nx,ny -> 0-nmax
    Centre is by Python convention, for retards who count from zero. """
    from math import sqrt, pi
    try:
        from scipy import factorial
    except ImportError:
        try:
            from scipy.misc.common import factorial
        except ImportError:
            from scipy.misc import factorial

    hcx = hc[nx, :]
    hcy = hc[ny, :]
    ind = N.array([nx, ny])
    fact = factorial(ind)
    dumr1 = N.sqrt((2.0**(ind)) * sqrt(pi) * fact)

    x = (N.arange(size[0], dtype=float) - centre[0]) / beta
    y = (N.arange(size[1], dtype=float) - centre[1]) / beta

    dumr3 = N.zeros(size[0])
    for i in range(size[0]):
        for j in range(ind[0] + 1):
            dumr3[i] += hcx[j] * (x[i]**j)
    B_nx = N.exp(-0.50 * x * x) * dumr3 / dumr1[0] / sqrt(beta)

    dumr3 = N.zeros(size[1])
    for i in range(size[1]):
        for j in range(ind[1] + 1):
            dumr3[i] += hcy[j] * (y[i]**j)
    B_ny = N.exp(-0.50 * y * y) * dumr3 / dumr1[1] / sqrt(beta)

    return N.outer(B_nx, B_ny)
示例#31
0
    def get_volume(el, nd):

        dim = nd.shape[1]
        nnd = el.shape[1]

        etype = '%d_%d' % (dim, nnd)
        if etype == '2_4' or etype == '3_8':
            el = elems_q2t(el)

        vol = 0.0
        bc = nm.zeros((dim, ), dtype=nm.double)
        mtx = nm.ones((dim + 1, dim + 1), dtype=nm.double)
        mul = 1.0 / sc.factorial(dim)
        if dim == 3:
            mul *= -1.0

        for iel in el:
            mtx[:, :-1] = nd[iel, :]
            ve = mul * nm.linalg.det(mtx)
            vol += ve
            bc += ve * mtx.sum(0)[:-1] / nnd

        bc /= vol

        return vol, bc
示例#32
0
    def get_volume(el, nd):

        dim = nd.shape[1]
        nnd = el.shape[1]

        etype = '%d_%d' % (dim, nnd)
        if etype == '2_4' or etype == '3_8':
            el = elems_q2t(el)

        vol = 0.0
        bc = nm.zeros((dim, ), dtype=nm.double)
        mtx = nm.ones((dim + 1, dim + 1), dtype=nm.double)
        mul = 1.0 / sc.factorial(dim)
        if dim == 3:
            mul *= -1.0

        for iel in el:
            mtx[:,:-1] = nd[iel,:]
            ve = mul * nm.linalg.det(mtx)
            vol += ve
            bc += ve * mtx.sum(0)[:-1] / nnd

        bc /= vol

        return vol, bc
示例#33
0
def shapelet_image(basis, beta, centre, hc, nx, ny, size):
    """ Takes basis, beta, centre (2-tuple), hc matrix, x, y, size and returns the image of the shapelet of
    order nx,ny on an image of size size. Does what getcartim.f does in fBDSM. nx,ny -> 0-nmax
    Centre is by Python convention, for retards who count from zero. """
    from math import sqrt, pi

    try:
        from scipy import factorial
    except ImportError:
        from scipy.misc.common import factorial

    hcx = hc[nx, :]
    hcy = hc[ny, :]
    ind = N.array([nx, ny])
    fact = factorial(ind)
    dumr1 = N.sqrt((2.0 ** (ind)) * sqrt(pi) * fact)

    x = (N.arange(size[0], dtype=float) - centre[0]) / beta
    y = (N.arange(size[1], dtype=float) - centre[1]) / beta

    dumr3 = N.zeros(size[0])
    for i in range(size[0]):
        for j in range(ind[0] + 1):
            dumr3[i] += hcx[j] * (x[i] ** j)
    B_nx = N.exp(-0.50 * x * x) * dumr3 / dumr1[0] / sqrt(beta)

    dumr3 = N.zeros(size[1])
    for i in range(size[1]):
        for j in range(ind[1] + 1):
            dumr3[i] += hcy[j] * (y[i] ** j)
    B_ny = N.exp(-0.50 * y * y) * dumr3 / dumr1[1] / sqrt(beta)

    return N.outer(B_nx, B_ny)
示例#34
0
文件: wigner.py 项目: partus/qutip
def _par_wig_eval(args):
    """
    Private function for calculating terms of Laguerre Wigner function in parfor.
    """
    m,rho,A,B=args
    W1 = zeros(shape(A))
    for jj in range(rho.data.indptr[m], rho.data.indptr[m+1]):        
        n = rho.data.indices[jj]

        if m == n:
            W1 += real(rho[m,m] * (-1)**m * genlaguerre(m,0)(B))

        elif n > m:
            W1 += 2.0 * real(rho[m,n] * (-1)**m * (2*A)**(n-m) * \
                 sqrt(factorial(m)/factorial(n)) * genlaguerre(m,n-m)(B))
    return W1
示例#35
0
文件: wigner.py 项目: rkdarst/fitz
 def f(t):
     args = [t-j1-j2-j3, t-j1-J2-J3, t-J1-j2-J3,
             t-J1-J2-j3, j1+j2+J1+J2-t, j2+j3+J2+J3-t,
             j3+j1+J3+J1-t]
     args = factorial(array(args))
     result = args.prod()
     return result
示例#36
0
def _series(A, Ts, n=10):
    """Matrix power series"""
    S = np.eye(A.shape[0]) * Ts
    Am = np.matrix(A)
    for i in xrange(1, n):
        S += (Am ** i) * Ts ** (i + 1) / scipy.factorial(i + 1)
    return S
示例#37
0
def _series(A, Ts, n=10):
    """Matrix power series"""
    S = np.eye(A.shape[0]) * Ts
    Am = np.matrix(A)
    for i in xrange(1, n):
        S += (Am**i) * Ts**(i + 1) / scipy.factorial(i + 1)
    return S
    def _build_pc_features(self, X):
        """Build polynomial features from X up to self.degree

        Assume Xj = [c1, c2, c3, ..., cD] with cI as the Ith feature of the jth
        element.
        Then build polynomial feature list, e.g. for self.degree=2:
        Pj = [1, c1, c2, ..., cD, c1*c1, c1*c2, ..., cD*cD]

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.

        Returns
        -------
        P : ndarray, shape = [n_samples, n_polynomials]
            Polynomial features.
            n_polynomials = (n_features+self.degree)! /
                            (n_features! * self.degree!)
        """
        N, D = X.shape

        # number of polynomials
        numP = lambda n, p: (sp.factorial(n + p) /
               (sp.factorial(n) * sp.factorial(p)))
        # build up index list to combine features, -1 indicates unused feature
        I = np.zeros((numP(D, self.degree), self.degree), dtype=int) - 1
        for i in range(1, I.shape[0]):
            I[i, :] = I[i - 1, :]
            for j in range(self.degree):
                if I[i - 1, j] + 1 < D:
                    I[i, j] = I[i - 1, j] + 1
                    break
            j -= 1
            while j >= 0:
                I[i, j] = I[i, j + 1]
                j -= 1

        # use index list to build combined polynomial features P
        P = np.ones((N, numP(D, self.degree)))
        for i in range(I.shape[0]):
            for d in range(self.degree):
                if I[i, d] > -1:
                    P[:, i] = P[:, i] * X[:, I[i, d]]

        return P
示例#39
0
    def __init__(self, xi, yi):
        """Construct an interpolator passing through the specified points

        The polynomial passes through all the pairs (xi,yi). One may additionally
        specify a number of derivatives at each point xi; this is done by
        repeating the value xi and specifying the derivatives as successive
        yi values.

        Parameters
        ----------
        xi : array-like, length N
            known x-coordinates
        yi : array-like, N by R
            known y-coordinates, interpreted as vectors of length R,
            or scalars if R=1

        Example
        -------
        To produce a polynomial that is zero at 0 and 1 and has
        derivative 2 at 0, call

        >>> KroghInterpolator([0,0,1],[0,2,0])
        """
        self.xi = np.asarray(xi)
        self.yi = np.asarray(yi)
        if len(self.yi.shape) == 1:
            self.vector_valued = False
            self.yi = self.yi[:, np.newaxis]
        elif len(self.yi.shape) > 2:
            raise ValueError("y coordinates must be either scalars or vectors")
        else:
            self.vector_valued = True

        n = len(xi)
        self.n = n
        nn, r = self.yi.shape
        if nn != n:
            raise ValueError(
                "%d x values provided and %d y values; must be equal" %
                (n, nn))
        self.r = r

        c = np.zeros((n + 1, r))
        c[0] = yi[0]
        Vk = np.zeros((n, r))
        for k in xrange(1, n):
            s = 0
            while s <= k and xi[k - s] == xi[k]:
                s += 1
            s -= 1
            Vk[0] = yi[k] / float(factorial(s))
            for i in xrange(k - s):
                assert xi[i] != xi[k]
                if s == 0:
                    Vk[i + 1] = (c[i] - Vk[i]) / (xi[i] - xi[k])
                else:
                    Vk[i + 1] = (Vk[i + 1] - Vk[i]) / (xi[i] - xi[k])
            c[k] = Vk[k - s]
        self.c = c
示例#40
0
def _par_wig_eval(args):
    """
    Private function for calculating terms of Laguerre Wigner function in
    parfor.
    """
    m, rho, A, B = args
    W1 = zeros(np.shape(A))
    for jj in range(rho.data.indptr[m], rho.data.indptr[m + 1]):
        n = rho.data.indices[jj]

        if m == n:
            W1 += real(rho[m, m] * (-1)**m * genlaguerre(m, 0)(B))

        elif n > m:
            W1 += 2.0 * real(rho[m, n] * (-1)**m * (2 * A)**(n - m) * sqrt(
                factorial(m) / factorial(n)) * genlaguerre(m, n - m)(B))
    return W1
示例#41
0
文件: minimize.py 项目: Nikea/pyXPCS
def func_duri(x,q,gamma0,delta,alfa,n=101):
   gn=resize(0*x,[n,len(x)])
   alfa=abs(cos(alfa))
   for k in range(n):
       P_k=(exp(-abs(gamma0)*x)*(abs(gamma0)*x)**k)/factorial(k)
       gn[k,:]= P_k*exp(-(q*abs(delta)*k**abs(alfa))**2)
   g1=sum(gn,axis=0)
   return g1
示例#42
0
def poiss_prob(x, count):
    x = array(x)
    P = zeros(x.shape)
    i = 0
    for xx in x:
        P[i] = count**xx * exp(-count) / s.factorial(xx)
        i = i + 1
    return P
示例#43
0
def sixj(j1,j2,j3,l1,l2,l3):
    """ Calculate the Wigner six-j symbol of six angular momenta
    """
    def bad_values(j1,j2,j3,l1,l2,l3):
        """ Check triangular rules for supplied values """
        if (j1<(abs(j2-j3)) or j1>(j2+j3)):
            return 1
        if (j1<(abs(l2-l3)) or j1>(l2+l3)): 
            return 1
        if (l1<(abs(j2-l3)) or l1>(j2+l3)):
            return 1
        if (l1<(abs(l2-j3)) or l1>(l2+j3)):
            return 1
        return 0

    def delta(a,b,c):
        """ Calculate delta """
        fac = zeros(4,long)
        fac[0] = factorial(a+b-c)
        fac[1] = factorial(a-b+c)
        fac[2] = factorial(-a+b+c)
        fac[3] = factorial(a+b+c+1)
        return sqrt(prod(fac[0:3])/fac[3]);

    if bad_values(j1,j2,j3,l1,l2,l3):
        return 0

    jphase=(-1)**(j1+j2+l1+l2);
    proddelt=delta(j1,j2,j3)*delta(l1,l2,j3)*delta(l1,j2,l3)*delta(j1,l2,l3);

    val = zeros(7,long)
    val[0] = j1+j2+l1+l2+1
    val[1] = j1+j2-j3
    val[2] = l1+l2-j3
    val[3] = j1+l2-l3
    val[4] = l1+j2-l3
    val[5] = -j1-l1+j3+l3
    val[6] = -j2-l2+j3+l3

    kmax = min(val[0:5])
    kmin = max([0, -val[5], -val[6]])

    jsum = 0
    for k in range(kmin,kmax+1):
        jsfac = zeros(8,long)
        jsfac[0] = factorial(val[0]-k);
        jsfac[1] = factorial(k);
        jsfac[2] = factorial(val[1]-k);
        jsfac[3] = factorial(val[2]-k);
        jsfac[4] = factorial(val[3]-k);
        jsfac[5] = factorial(val[4]-k);
        jsfac[6] = factorial(val[5]+k);
        jsfac[7] = factorial(val[6]+k);
        jsum += (-1)**k * jsfac[0] / prod(jsfac[1:])
    return jphase*proddelt*jsum
示例#44
0
def taylor(p):
    r"""
        Return the Taylor polynomial of the exponential, up to order p.
    """
    from scipy import factorial

    coeffs = 1. / factorial(np.arange(p + 1))

    return np.poly1d(coeffs[::-1])
示例#45
0
def kuiper_FPP(D,N):
    """Compute the false positive probability for the Kuiper statistic

    Uses the set of four formulas described in Paltani 2004; they report the resulting function never underestimates the false positive probability but can be a bit high in the N=40..50 range. (They quote a factor 1.5 at the 1e-7 level.
    """
    if D<0. or D>2.:
        raise ValueError("Must have 0<=D<=2")

    if D<2./N:
        return 1. - factorial(N)*(D-1./N)**(N-1)
    elif D<3./N:
        k = -(N*D-1.)/2.
        r = sqrt(k**2 - (N*D-2.)/2.)
        a, b = -k+r, -k-r
        return 1. - factorial(N-1)*(b**(N-1.)*(1.-a)-a**(N-1.)*(1.-b))/float(N)**(N-2)*(b-a)
    elif (D>0.5 and N%2==0) or (D>(N-1.)/(2.*N) and N%2==1):
        def T(t):
            y = D+t/float(N)
            return y**(t-3)*(y**3*N-y**2*t*(3.-2./N)/N-t*(t-1)*(t-2)/float(N)**2)
        s = 0.
        # NOTE: the upper limit of this sum is taken from Stephens 1965
        for t in xrange(int(floor(N*(1-D)))+1):
            term = T(t)*binomial(N,t)*(1-D-t/float(N))**(N-t-1)
            s += term
        return s
    else:
        z = D*sqrt(N) 
        S1 = 0.
        term_eps = 1e-12
        abs_eps = 1e-100
        for m in itertools.count(1):
            T1 = 2.*(4.*m**2*z**2-1.)*exp(-2.*m**2*z**2)
            so = S1
            S1 += T1
            if abs(S1-so)/(abs(S1)+abs(so))<term_eps or abs(S1-so)<abs_eps:
                break
        S2 = 0.
        for m in itertools.count(1):
            T2 = m**2*(4.*m**2*z**2-3.)*exp(-2*m**2*z**2)
            so = S2
            S2 += T2
            if abs(S2-so)/(abs(S2)+abs(so))<term_eps or abs(S1-so)<abs_eps:
                break
        return S1 - 8*D/(3.*sqrt(N))*S2
示例#46
0
def cmdet(d):
    # compute the CMD determinant of the euclidean distance matrix d
    # -> d should not be squared!
    D = np.ones((d.shape[0] + 1, d.shape[0] + 1))
    D[0, 0] = 0.0
    D[1:, 1:] = d**2
    j = np.float32(D.shape[0] - 2)
    f1 = (-1.0)**(j + 1) / ((2**j) * ((factorial(j))**2))
    cmd = f1 * np.linalg.det(D)
    # sometimes, for very small values "cmd" might be negative ...
    return np.sqrt(np.abs(cmd))
示例#47
0
def log_factorial(n, N_max=200):
    """
    log_factorial(n, N_max = 50)
    return Stirling approximation of log of factorial of n if n > N_max
    """
    #   n = asarray(n)
    if n > N_max:
        return n * log(n) - n + 0.5 * log(
            2 * pi * n) + 1. / 12 / n - 1. / 360 / (n**3)
    else:
        return log(factorial(n))
示例#48
0
def rnm(n, m, rho):
    """
    Return an array with the zernike Rnm polynomial calculated at rho points.
    
    
    **ARGUMENTS:**
    
        === ==========================================
        n    n order of the Zernike polynomial
        m    m order of the Zernike polynomial
        rho  Matrix containing the radial coordinates. 
        === ==========================================       
    
    .. note:: For rho>1 the returned value is 0
    
    .. note:: Values for rho<0 are silently returned as rho=0
    
    """

    if (type(n) is not int):
        raise Exception("n must be integer")
    if (type(m) is not int):
        raise Exception("m must be integer")
    if (n - m) % 2 != 0:
        raise Exception("n-m must be even")
    if abs(m) > n:
        raise Exception("The following must be true |m|<=n")
    mask = where(rho <= 1, False, True)

    if (n == 0 and m == 0):
        return masked_array(data=ones(rho.shape), mask=mask)
    rho = where(rho < 0, 0, rho)
    Rnm = zeros(rho.shape)
    S = (n - abs(m)) / 2
    for s in range(0, S + 1):
        CR=pow(-1,s)*factorial(n-s)/ \
            (factorial(s)*factorial(-s+(n+abs(m))/2)* \
            factorial(-s+(n-abs(m))/2))
        p = CR * pow(rho, n - 2 * s)
        Rnm = Rnm + p
    return masked_array(data=Rnm, mask=mask)
示例#49
0
def approximate_taylor_polynomial(f,x,degree,scale,order=None):
    """Estimate the Taylor polynomial of f at x by polynomial fitting

    A polynomial
    Parameters
    ----------
    f : callable
        The function whose Taylor polynomial is sought. Should accept
        a vector of x values.
    x : scalar
        The point at which the polynomial is to be evaluated.
    degree : integer
        The degree of the Taylor polynomial
    scale : scalar
        The width of the interval to use to evaluate the Taylor polynomial.
        Function values spread over a range this wide are used to fit the
        polynomial. Must be chosen carefully.
    order : integer or None
        The order of the polynomial to be used in the fitting; f will be
        evaluated order+1 times. If None, use degree.

    Returns
    -------
    p : poly1d
        the Taylor polynomial (translated to the origin, so that
        for example p(0)=f(x)).

    Notes
    -----
    The appropriate choice of "scale" is a tradeoff - too large and the
    function differs from its Taylor polynomial too much to get a good
    answer, too small and roundoff errors overwhelm the higher-order terms.
    The algorithm used becomes numerically unstable around order 30 even
    under ideal circumstances.

    Choosing order somewhat larger than degree may improve the higher-order
    terms.
    """
    if order is None:
        order=degree

    n = order+1
    # Choose n points that cluster near the endpoints of the interval in
    # a way that avoids the Runge phenomenon. Ensure, by including the
    # endpoint or not as appropriate, that one point always falls at x
    # exactly.
    xs = scale*np.cos(np.linspace(0,np.pi,n,endpoint=n%1)) + x

    P = KroghInterpolator(xs, f(xs))
    d = P.derivatives(x,der=degree+1)

    return np.poly1d((d/factorial(np.arange(degree+1)))[::-1])
示例#50
0
 def EvalWellFunction(self, u, rB):
     '''Evaluates the Hantush-Jacob well function.
        u     dimensionless time
        rB    dimensionless radius'''
     #return zero for large u to avoid numerical issues
     if u > 14:
         return 0.0        
     #set number of terms used in summation. as u increases more
     #terms are needed
     if u <= 2:
         endmember = 10
     elif u <= 7:
         endmember = 20
     else:
         endmember = 30
     #compute temporary variable
     r4B = rB**2 / 4.0
     #compute summation term
     last_term = 0.0
     for i in range(1,endmember):
         for j in range(1,i+1):
             last_term += (-1)**(i+j) * spy.factorial(i - j + 1) / \
                          (spy.factorial(i+2))**2 * u**(i-j) * r4B**j
     #for rB values close to 0 one term is dropped to avoid numerical
     #problems
     if abs(sci.iv(0.0,rB) - 1.0) < 1e-15:
         WellFuncHJ = 2.0 * sci.kv(0.0,rB) \
              - sci.iv(0.0,rB) * sci.expn(1,r4B / u) \
              + mth.exp(-1.0 * r4B / u) * (0.5772156649015328606 \
              + mth.log(u) + sci.expn(1,u) - u - u**2 * last_term)
     else:
     #full expression
         WellFuncHJ = 2.0 * sci.kv(0.0,rB) \
              - sci.iv(0.0,rB) * sci.expn(1,r4B / u) \
              + mth.exp(-1.0 * r4B / u) * (0.5772156649015328606 \
              + mth.log(u) + sci.expn(1,u) - u + u * (sci.iv(0.0,rB) - 1.0) \
                 / r4B - u**2 * last_term)
     return WellFuncHJ
示例#51
0
def ispline(n,dtk,t):
    '''Uniform integrated b-splines
       n   - Order
       dtk - Spacing
       t   - Time vector'''
    x = (t/dtk)+n+1
    b = np.zeros(len(x))
    for k in range(n+2):
        m = x-k-(n+1)/2
        up = m**(n+1)
        b += ((-1)**k)*nCk(n+1,k)*up*(m>=0)

    b = b*dtk/((n+1.0)*factorial(n))
    return b
示例#52
0
def bspline(n,dtk,t):
    '''Uniform b-splines.
       n    -  Order
       dtk  -  Spacing
       t    -  Time vector'''
    x = (t/dtk) + n +1
    b = np.zeros(len(x))
    for k in range(n+2):
        m = x-k-(n+1)/2
        up = np.power(m,n)
        b = b+((-1)**k)*nCk(n+1,k)*up*(m>=0)

    b = b/(1.0*factorial(n))
    return b
示例#53
0
def expSS(x, i=100):
    """Calculate e**x by scaling and squaring"""

    from scipy import factorial

    results = []
    for val in x:
        (t, r) = (0, 0)
        val = float(val)
        while val >= 10:
            val = val / 2
            t += 2.0

        # calculate sum
        results.append(sum([val**z / factorial(z) for z in range(i)])**t)
    return results
示例#54
0
def _qfunc_pure(psi, alpha_mat):
    """
    Calculate the Q-function for a pure state.
    """
    n = prod(psi.shape)
    if isinstance(psi, Qobj):
        psi = psi.full().flatten()
    else:
        psi = psi.T

    qmat = abs(
        polyval(
            fliplr([psi / sqrt(factorial(arange(n)))])[0],
            conjugate(alpha_mat)))**2

    return real(qmat) * exp(-abs(alpha_mat)**2) / pi
示例#55
0
def qfunc1(psi, alpha_mat):
    """
    private function used by qfunc
    """
    n = prod(psi.shape)
    if isinstance(psi, Qobj):
        psi = array(psi.trans().full())[0, :]
    else:
        psi = psi.T

    qmat1 = abs(
        polyval(
            fliplr([psi / sqrt(factorial(arange(0, n)))])[0],
            conjugate(alpha_mat)))**2
    qmat1 = real(qmat1) * exp(-abs(alpha_mat)**2) / pi

    return qmat1
示例#56
0
def _qfunc_pure(psi, alpha_mat):
    """
    Calculate the Q-function for a pure state.
    """
    n = prod(psi.shape)
    if isinstance(psi, Qobj):
        psi = array(psi.trans().full())[0, :]
    else:
        psi = psi.T

    qmat1 = abs(
        polyval(
            fliplr([psi / sqrt(factorial(arange(0, n)))])[0],
            conjugate(alpha_mat)))**2
    qmat1 = real(qmat1) * exp(-abs(alpha_mat)**2) / pi

    return qmat1
示例#57
0
    def Stehfest(self, t):
        """
        Stehfest method works for smooth function
        f(t) = ln(2)/t \sum_{i=1}^{N}V_i*F(u),
        where u = (i*ln(2))/t is the Laplace variable,
        and
        V_i = (-1)^(N/2 + i)*sum_int((i+1)/2)^min(i, N/2) K^(N/2 +1)*(2K)! /(N/2-K)!*K!*(K-1)!*(i-K)!*(2K-i)!,
        in which N is even number, 8, 10, or 12, (or 16).

        @param t is time
        @param F is the laplace image function
        """
        F = self.F
        N = 10
        N2 = N / 2
        ln2 = np.log(2)
        G = sci.factorial(np.array(range(0, N + 1, 1)))  # factorial 0!...N!

        V = np.zeros_like(range(0, N + 1, 1))
        sign = 1
        if N2 % 2:
            sign = -1
        for i in range(1, N + 1, 1):
            kmin = (i + 1) / 2
            kmax = np.minimum(i, N2)
            sign = -sign
            for K in range(kmin, kmax + 1, 1):
                V[i] += np.power(K,N2)*G[2*K]/\
                              (G[N/2-K]*G[K]*G[K-1]*G[i-K]*G[2*K-i])
            V[i] = sign * V[i]
        #print "V[1..N] = ", V     #debug

        f = np.zeros_like(t)
        for j in range(0, len(t), 1):
            ln2t = ln2 / t[j]
            u = 0
            for i in range(1, N + 1, 1):
                u += ln2t  # u = i*ln2/t
                f[j] += V[i] * F(u)
            f[j] = ln2t * f[j]

        return f
示例#58
0
def perm_unique_trans(n, startk=0, verbose=False):
    """
    Generate unique permutations of n numbers, with the constraint
    that none of the transitions can be the same. Continues to generate
    sequences until all the possible permutations have been tested.

    This is not a terribly fast algorithm.
    """
    from scipy import factorial
    out = []
    seqpairs = []
    maxk = factorial(n, exact=True)
    k = startk
    while k < maxk:
        perm = perm_dfr(perm_rr(n, k))
        k += 1
        permpairs = set("%d%d" % (perm[i], perm[i + 1]) for i in range(len(perm) - 1))
        pairmatches = [len(x.intersection(permpairs)) for x in seqpairs]
        if len(pairmatches) == 0 or max(pairmatches) == 0:
            out.append(perm)
            seqpairs.append(permpairs)
            yield k, perm
        elif verbose and k % 10000 == 0:
            print("Checked to permutation %d" % k)