def lpKernel(N, freq): # # Lowpass filter kernel generator # # N is the filter half-size, must be odd # freq is the normalised cutoff frequency # # Returns the filter kernel of size (2N+1,2N+1) # num = 2 * N + 1 result = np.zeros((num, num, 1)) for m in range(N + 1): i = m + N im = -m + N for n in range(N + 1): j = n + N jm = -n + N if (m == 0 and n == 0): result[i, j] = np.pi * freq**2 / 4 else: pandq = m % 2 + n % 2 mandn = np.sqrt(m * m + n * n) val = (sm.factorial2(N)**4 * np.pi**pandq * freq * ss.jn(1, np.pi * freq * mandn)) / ( 2**(pandq + 1) * sm.factorial2(N + m) * sm.factorial2(N - m) * sm.factorial2(N + n) * sm.factorial2(N - n) * mandn) result[i, j] = val result[j, i] = val result[im, j] = val result[i, jm] = val result[im, jm] = val return result / np.sum(result)
def normalisation(self): """Calculates normalisation constant for the basis set and stores in self.normalisation once called. Returns ------- self.normalisation_memo : float """ if self.normalisation_memo is None: l, m, n = self.integral_exponents if len(self.primitive_gaussian_array) == 1: self.normalisation_memo = 1 else: ans = 0.0 for primitive_a, primitive_b in itertools.product( self.primitive_gaussian_array, repeat=2): a_1 = primitive_a.exponent a_2 = primitive_b.exponent c_1 = primitive_a.contraction c_2 = primitive_b.contraction n_1 = primitive_a.normalisation n_2 = primitive_b.normalisation out1 = factorial2(2 * l - 1) * factorial2( 2 * m - 1) * factorial2(2 * n - 1) out2 = (pi / (a_1 + a_2))**(3 / 2) out3 = (2 * (a_1 + a_2))**(l + m + n) ans += (c_1 * c_2 * n_1 * n_2 * out1 * out2) / out3 self.normalisation_memo = 1 / sqrt(ans) return self.normalisation_memo
def normalise(self): l, m, n = self.shell self.norm = np.sqrt( np.power(2, 2 * (l + m + n) + 1.5) * np.power(self.exps, l + m + n + 1.5) / factorial2(2 * l - 1) / factorial2(2 * m - 1) / factorial2(2 * n - 1) / np.power(np.pi, 1.5))
def norm(ax, ay, az, aa): """ General cartesian Gaussian normalization factor. INPUT: AX: Angular momentum lx AY: Angular momentum ly AZ: Angular momentum lz AA: Gaussian exponential coefficient OUTPUT: N: Normalization coefficient (to be multiplied with the Gaussian) Source: Handbook of Computational Chemistry David Cook Oxford University Press 1998 """ # Compute normalization coefficient N = (2 * aa / np.pi)**(3. / 4.) N *= (4 * aa)**((ax + ay + az) / 2) N /= np.sqrt( misc.factorial2(2 * ax - 1) * misc.factorial2(2 * ay - 1) * misc.factorial2(2 * az - 1)) return N
def b_mat(ind_mat): r""" Calculates the B coefficients from [1]_ Eq. 27. Parameters ---------- index_matrix : array, shape (N,3) ordering of the basis in x, y, z Returns ------- B : array, shape (N,) B coefficients for the basis References ---------- .. [1] Ozarslan E. et. al, "Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure", NeuroImage, 2013. """ B = np.zeros(ind_mat.shape[0]) for i in range(ind_mat.shape[0]): n1, n2, n3 = ind_mat[i] K = int(not (n1 % 2) and not (n2 % 2) and not (n3 % 2)) B[i] = K * np.sqrt(factorial(n1) * factorial(n2) * factorial(n3)) / ( factorial2(n1) * factorial2(n2) * factorial2(n3)) return B
def norm(ax,ay,az,aa): """ General cartesian Gaussian normalization factor. INPUT: AX: Angular momentum lx AY: Angular momentum ly AZ: Angular momentum lz AA: Gaussian exponential coefficient OUTPUT: N: Normalization coefficient (to be multiplied with the Gaussian) Source: Handbook of Computational Chemistry David Cook Oxford University Press 1998 """ # Compute normalization coefficient N = (2*aa/np.pi)**(3./4.) N *= (4*aa)**((ax+ay+az)/2) N /= np.sqrt( misc.factorial2(2*ax-1) * misc.factorial2(2*ay-1) * misc.factorial2(2*az-1) ) return N
def ellke2(k, tol=100 * eps, maxiter=100): """Compute complete elliptic integrals of the first kind (K) and second kind (E) using the series expansions.""" # 2011-04-24 21:14 IJMC: Created k = np.array(k, copy=False) ksum = 0 * k kprevsum = ksum.copy() kresidual = ksum + 1 #esum = 0*k #eprevsum = esum.copy() #eresidual = esum + 1 n = 0 sqrtpi = np.sqrt(np.pi) #kpow = k**0 #ksq = k*k while (np.abs(kresidual) > tol).any() and n <= maxiter: #kpow *= (ksq) #print kpow==(k**(2*n)) ksum += ((misc.factorial2(2 * n - 1) / misc.factorial2(2 * n))** 2) * k**(2 * n) #ksum += (special.gamma(n + 0.5)/special.gamma(n + 1) / sqrtpi) * k**(2*n) kresidual = ksum - kprevsum kprevsum = ksum.copy() n += 1 #print n, kresidual return ksum * (np.pi / 2.)
def b_mat(ind_mat): r""" Calculates the B coefficients from [1]_ Eq. 27. Parameters ---------- index_matrix : array, shape (N,3) ordering of the basis in x, y, z Returns ------- B : array, shape (N,) B coefficients for the basis References ---------- .. [1] Ozarslan E. et. al, "Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure", NeuroImage, 2013. """ B = np.zeros(ind_mat.shape[0]) for i in range(ind_mat.shape[0]): n1, n2, n3 = ind_mat[i] K = int(not(n1 % 2) and not(n2 % 2) and not(n3 % 2)) B[i] = K * np.sqrt(factorial(n1) * factorial(n2) * factorial(n3) ) / (factorial2(n1) * factorial2(n2) * factorial2(n3)) return B
def lpKernel(N, freq): # # Lowpass filter kernel generator # # N is the filter half-size, must be odd # freq is the normalised cutoff frequency # # Returns the filter kernel of size (2N+1,2N+1) # num = 2*N + 1 result = np.zeros((num,num,1)) for m in range(N+1): i = m+N im = -m+N for n in range(N+1): j = n+N jm = -n+N if (m==0 and n==0): result[i,j] = np.pi*freq**2/4 else: pandq = m%2 + n%2 mandn = np.sqrt(m*m+n*n) val = (sm.factorial2(N)**4 * np.pi**pandq * freq * ss.jn(1,np.pi * freq * mandn)) / ( 2**(pandq+1) * sm.factorial2(N+m) * sm.factorial2(N-m) * sm.factorial2(N+n) *sm.factorial2(N-n) *mandn ) result[i,j] = val result[j,i] = val result[im,j] = val result[i,jm] = val result[im,jm] = val return result/np.sum(result)
def sph_i2n(n, z, terms=50): n = np.asarray(n, dtype=int) z = np.asarray(z) s1 = np.zeros(np.shape(n + z)) for k in xrange(np.max(n + 1)): s = (-z**2 / 2)**k * factorial2(2 * n - 2 * k - 1) / factorial(k) s1[k <= n] += s[k <= n] s2 = np.zeros(s1.shape) for k in xrange(np.min(n + 1), terms): with np.errstate(divide='ignore'): s = (z**2 / 2)**k / (factorial(k) * factorial2(2 * k - 2 * n - 1)) s2[k >= n + 1] += s[k >= n + 1] return (-1)**n * z**(n + 1) * s1 + z**(-n - 1) * s2
def generate_kernel(name, *args): if name == 'uniform': K = lambda x: np.array(np.array(1/2*(np.abs(x)<=1)).T, ndmin=2).prod(0) elif name == 'triangular': K = lambda x: np.array(np.array((1-np.abs(x))*(np.abs(x)<=1)).T, ndmin=2).prod(0) elif name == 'epanechnikov': K = lambda x: np.array(np.array(3/4*(1-x**2)*(np.abs(x)<=1)).T, ndmin=2).prod(0) elif name == 'normal': K = lambda x: np.array(np.array(1/np.sqrt(2*np.pi)*np.exp(-x**2/2)).T, ndmin=2).prod(0) elif name == 'mvnormal': mu = args[0] sigma = args[1] s = multivariate_normal(mu, sigma) K = lambda x: s.pdf(x) elif name == 's-kernel': """ s-kernel of order r """ s = args[0] r = args[1] k_s = lambda x: np.array(factorial2(2*s+1)/(2**(s+1)*factorial(s))\ *(1-x**2)**s*(np.abs(x)<=1)) K = lambda x: np.array(np.array(hansen_coefficient(s, r, x)*k_s(x)).T, ndmin=2).prod(0) else: print 'No such kernel found. Try another one.' K = () return K
def get_initializations(self, num_pol=5, copy_fun='relu'): k = [] if copy_fun == 'relu': for n in range(num_pol): if n == 0: k.append(1.0 / np.sqrt(2 * np.pi)) #k.append(0.0) #k.append(0.3821) elif n == 1: k.append(1.0 / 2) #k.append(0.0) #k.append(0.3775) elif n == 2: k.append(1.0 / np.sqrt(4 * np.pi)) #k.append(0.0) #k.append(0.5535) elif n > 2 and n % 2 == 0: #c = 1.0 * np.math.factorial(np.math.factorial(n-3))**2 / np.sqrt(2*np.pi*np.math.factorial(n)) c = 1.0 * factorial2(n - 3)**2 / np.sqrt( 2 * np.pi * np.math.factorial(n)) k.append(c) #k.append(0.0) #k.append(-0.4244) elif n >= 2 and n % 2 != 0: k.append(0.0) #k.append(0.2126) #k.append(0.0655) return k
def _fast_isserli(powerlist, Sigma_x): """ Get higher order mixed centralized moments of a multivariate gaussian using isserlis theorem http://en.wikipedia.org/wiki/Isserlis%27_theorem This is optimized by assuming the x_i to be independent :math:`E[(x-\mu_x)^{k_x} (y-\mu_y)^{k_y}] = E[(x-\mu_x)^{k_x}] \cdot E [(y-\mu_y)^{k_y}]` => no need for isserli :param powerlist: list of powers of the random variables of the multivariate normal :param Sigma_x: The covariance matrix :return: """ from scipy.misc import factorial2 if powerlist.sum() % 2 != 0: #Odd order return 0 for power in powerlist: if power % 2 != 0: return 0 part = 1.0 for i, power in enumerate(powerlist): part *= Sigma_x[i][i]**(power / 2) part *= factorial2(power - 1, exact=True) return part
def sph_i2n(n, z, terms=50): n = np.asarray(n, dtype=int) z = np.asarray(z) s1 = np.zeros(np.shape(n + z)) for k in xrange(np.max(n + 1)): s = (-z**2/2)**k * factorial2(2*n - 2*k - 1)/factorial(k) s1[k <= n] += s[k <= n] s2 = np.zeros(s1.shape) for k in xrange(np.min(n + 1), terms): with np.errstate(divide='ignore'): s = (z**2/2)**k/(factorial(k) * factorial2(2*k - 2*n - 1)) s2[k >= n + 1] += s[k >= n + 1] return (-1)**n * z**(n + 1) * s1 + z**(-n - 1) * s2
def radon_transform_kb( y , kb_radius , kb_degree ): a = kb_radius m = int( kb_degree ) y[y > kb_radius] = 0.0 p = 2 * a * np.power( 2 , m ) * misc.factorial( m ) \ / misc.factorial2( 2*m + 1 ) * ( 1 - ( y / a )**2 ) ** ( m + 0.5 ) return p
def generate_kernel(name, *args): if name == 'uniform': K = lambda x: np.array(np.array(1 / 2 * (np.abs(x) <= 1)).T, ndmin=2).prod(0) elif name == 'triangular': K = lambda x: np.array(np.array((1 - np.abs(x)) * (np.abs(x) <= 1)).T, ndmin=2).prod(0) elif name == 'epanechnikov': K = lambda x: np.array(np.array(3 / 4 * (1 - x**2) * (np.abs(x) <= 1)).T, ndmin=2).prod(0) elif name == 'normal': K = lambda x: np.array(np.array(1 / np.sqrt(2 * np.pi) * np.exp(-x**2 / 2)).T, ndmin=2).prod(0) elif name == 'mvnormal': mu = args[0] sigma = args[1] s = multivariate_normal(mu, sigma) K = lambda x: s.pdf(x) elif name == 's-kernel': """ s-kernel of order r """ s = args[0] r = args[1] k_s = lambda x: np.array(factorial2(2*s+1)/(2**(s+1)*factorial(s))\ *(1-x**2)**s*(np.abs(x)<=1)) K = lambda x: np.array( np.array(hansen_coefficient(s, r, x) * k_s(x)).T, ndmin=2).prod(0) else: print 'No such kernel found. Try another one.' K = () return K
def _fast_isserli(powerlist,Sigma_x): """ Get higher order mixed centralized moments of a multivariate gaussian using isserlis theorem http://en.wikipedia.org/wiki/Isserlis%27_theorem This is optimized by assuming the x_i to be independent :math:`E[(x-\mu_x)^{k_x} (y-\mu_y)^{k_y}] = E[(x-\mu_x)^{k_x}] \cdot E [(y-\mu_y)^{k_y}]` => no need for isserli :param powerlist: list of powers of the random variables of the multivariate normal :param Sigma_x: The covariance matrix :return: """ from scipy.misc import factorial2 if powerlist.sum() % 2 != 0: #Odd order return 0 for power in powerlist: if power % 2 != 0: return 0 part = 1.0 for i,power in enumerate(powerlist): part *= Sigma_x[i][i]**(power/2) part *= factorial2(power-1, exact=True) return part
def normalisation(self): """Calculates normalisation constant for the primitive gaussian and stores in self.normalisation once called. Returns ------- self.normalisation_memo : float """ if self.normalisation_memo is None: l, m, n = self.integral_exponents out1 = factorial2(2 * l - 1) * factorial2(2 * m - 1) * factorial2(2 * n - 1) out2 = (pi / (2 * self.exponent))**(3 / 2) out3 = (4 * self.exponent)**(l + m + n) self.normalisation_memo = 1 / sqrt((out1 * out2) / out3) return self.normalisation_memo
def dlog_bessel_j(lmax, x): """Calculates logarithmic derivative of the spherical bessel functions It returns three quantities: (x*d/dx log(j_l(x)), j_l(x), the product of the first two) for l up to lmax The last entry is important for singular cases: when x is zero of bessel function. In this case the logarithmic derivative is diverging while j*dlog(j(x))/dx is not """ if (fabs(x) < 1e-5): #return [(l, x**l/misc.factorial2(2*l+1), l*x**l/misc.factorial2(2*l+1)) for l in range(lmax+1)] return [(l, pow(x, l) / misc.factorial2(2 * l + 1), l * pow(x, l) / misc.factorial2(2 * l + 1)) for l in range(lmax + 1)] else: (jls, djls) = special.sph_jn( lmax, x) # all jl's and derivatives for l=[0,...lmax] return [(x * djls[l] / jls[l], jls[l], x * djls[l]) for l in range(lmax + 1)]
def sph_yn(n, z, terms=25): n = np.asarray(n, dtype=int) z = np.asarray(z) s1 = np.zeros(np.shape(n + z), dtype=z.dtype) # complex if z complex for k in xrange(np.max(n + 1)): s = (z**2 / 2)**k * factorial2(2 * n - 2 * k - 1) / factorial(k) s1[k <= n] += s[k <= n] s2 = np.zeros(np.shape(s1), dtype=z.dtype) for k in xrange(np.min(n + 1), terms): with np.errstate(divide='ignore'): # Where k < n + 1, we get 0 from the factorials. This leads to a # division by zero, but the corresponding entries are not used. s = (-z**2 / 2)**k / (factorial(k) * factorial2(2 * k - 2 * n - 1)) s2[k >= n + 1] += s[k >= n + 1] return -1 / z**(n + 1) * s1 + (-z)**(-n - 1) * s2
def sph_yn(n, z, terms=25): n = np.asarray(n, dtype=int) z = np.asarray(z) s1 = np.zeros(np.shape(n + z), dtype=z.dtype) # complex if z complex for k in xrange(np.max(n + 1)): s = (z**2/2)**k * factorial2(2*n - 2*k - 1)/factorial(k) s1[k <= n] += s[k <= n] s2 = np.zeros(np.shape(s1), dtype=z.dtype) for k in xrange(np.min(n + 1), terms): with np.errstate(divide='ignore'): # Where k < n + 1, we get 0 from the factorials. This leads to a # division by zero, but the corresponding entries are not used. s = (-z**2/2)**k/(factorial(k) * factorial2(2*k - 2*n - 1)) s2[k >= n + 1] += s[k >= n + 1] return -1/z**(n + 1) * s1 + (-z)**(-n - 1) * s2
def Nrun(basisset): # Normalize primitive functions for i in range(len(basisset)): for j in range(len(basisset[i][5])): a = basisset[i][5][j][1] l = basisset[i][5][j][3] m = basisset[i][5][j][4] n = basisset[i][5][j][5] part1 = (2.0 / math.pi)**(3.0 / 4.0) part2 = 2.0**(l + m + n) * a**( (2.0 * l + 2.0 * m + 2.0 * n + 3.0) / (4.0)) part3 = math.sqrt( scm.factorial2(int(2 * l - 1)) * scm.factorial2(int(2 * m - 1)) * scm.factorial2(int(2 * n - 1))) basisset[i][5][j][0] = part1 * ((part2) / (part3)) """ # Normalize contractions for k in range(len(basisset)): if len(basisset[k][5]) != 1: l = basisset[k][5][0][3] m = basisset[k][5][0][4] n = basisset[k][5][0][5] L = l+m+n factor = (np.pi**(3.0/2.0)*scm.factorial2(int(2*l-1))*scm.factorial2(int(2*m-1))*scm.factorial2(int(2*n-1)))/(2.0**L) sum = 0 for i in range(len(basisset[k][5])): for j in range(len(basisset[k][5])): alphai = basisset[k][5][i][1] alphaj = basisset[k][5][j][1] ai = basisset[k][5][i][2]*basisset[k][5][i][0] aj = basisset[k][5][j][2]*basisset[k][5][j][0] sum += ai*aj/((alphai+alphaj)**(L+3.0/2.0)) Nc = (factor*sum)**(-1.0/2.0) for i in range(len(basisset[k][5])): basisset[k][5][i][0] *= Nc """ return basisset
def sin_gauss_asy_series(t, delta2, N): ''' Returns the asympototic expansion of the sine folded Gaussian with variance delta2, by taking the power series of sine up to degree N. ''' S = 0 delta = np.sqrt(delta2) for k in range(N + 1): S += (-1)**k * (t * delta)**(2 * k + 1) / misc.factorial2(2 * k + 1) return (np.sqrt(2 * pi))**-1 * S
def shore_e0(radial_order, coeff): ind_mat = shore_index_matrix(radial_order) n_elem = ind_mat.shape[0] s0 = 0 for n in range(n_elem): n1, n2, n3 = ind_mat[n] if (n1 % 2 == 0) and (n2 % 2 == 0) and (n3 % 2 == 0): num = (np.sqrt(factorial(n1) * factorial(n2) * factorial(n3))) den = factorial2(n1) * factorial2(n2) * factorial2(n3) s0 += (num / np.float(den)) * coeff[n] return s0
def hsphere_vol(d): """ This function computes the volume of a d dimensional hypersphere, using Monte Carlo integration. It generates N random points within the smallest cube enclosing the sphere, then finds the number of points that lie within the hypersphere. The volume of the hypersphere is then the ratio of points withing the hypersphere and the number of random points generated, times the volume of the cube. param d: dimension of the hypersphere """ # Calculate the value of the gamma function based on whether d is even or odd. if (d % 2 == 0): gamma_fnc = factorial(d / 2.) else: gamma_fnc = np.sqrt(2) * factorial2(d - 2) / 2.**((d - 1) / 2.) # Calculate the volume of the hypershpere from the analytic formula and print to screen. analytic_vol = np.pi**(d / 2.) / (gamma_fnc) print "The volume obtained from the analytic formula is: " + str( analytic_vol) + "." # Estimate the volume with samples ranging from 10 to 10^7 in steps of powers of 10. for i in range(1, 8): N = 10**i cube_pts = [] sphe_pts = 0 # Generate N*d random points within the smallest hypercube containing the hypersphere. Hypersphere has radius 1, so the hypercube has sides of length 2. for j in range(0, N): for k in range(0, d): pt = (2 * random.random()) - 1 cube_pts.append(pt) cube_pts = np.reshape(np.asarray(cube_pts), (N, d)) # Take each random point and calculate it's length, if it is less than 1, then add 1 to the count of points that lie in the hypersphere. for j in range(0, N): length = 0 for k in range(0, d): length += cube_pts[j][k]**2 if (length <= 1): sphe_pts += 1 # Caclculate volume and uncertainties of hypersphere by multiplying the ratio of points in the hypersphere to the number of points in the hypercube by the # volume of the hypercube. sphe_vol = sphe_pts * (2.0**d) / N err = (2.0**d) * np.sqrt( (float(sphe_pts) / N - (float(sphe_pts) / N)**2) / N) # Print result to screen. print "Number of Samples: " + str(N) + ", Estimated Volume of " + str( d) + "D sphere: " + str(sphe_vol) + " +/- " + str( err) + ", Number of Points in Sphere: " + str(sphe_pts)
def lpKernel(N, freq): # # Lowpass filter 1D MAXFLAT kernel generator # # N is the filter half-size, must be odd # freq is the normalised cutoff frequency # # Returns the filter kernel of size (2N+1) # num = 2*N + 1 result = np.zeros((num,1)) for n in range(N+1): i = n+N im = N-n if (n==0): result[i] = freq else: p = n%2 val = (sm.factorial2(N)**2 * np.pi**(p-1) * np.sin(n*np.pi*freq)) / ( 2**p * n * sm.factorial2(i) * sm.factorial2(im) ) result[i] = val result[im] = val return result/np.sum(result)
def gen_R_nl(n, l, nu): """ Generates a radial eigenfunction for the Spherical Harmonic Oscillator. Used to speed up calculations. """ norm = sp.sqrt( sp.sqrt(2*nu**3/sp.pi)* 2**(n + 2*l + 3)*factorial(n, exact=True)* nu**l/factorial2(2*n + 2*l + 1, exact=True) ) laguerre = genlaguerre(n, l + .5) def R_nl(r): return norm * r**l * sp.exp(-nu * r**2) * laguerre(2*nu*r**2) return R_nl
def sph_yn_v(n, z, terms=25): # Doesn't handle overflow errors properly n = int(n) s1 = 0 for k in xrange(n + 1): s = (z**2 / 2)**k * factorial2(2 * n - 2 * k - 1) / factorial(k) if np.isnan(s) or np.isinf(s): break else: s1 += s s2 = 0 for k in xrange(n + 1, terms): s = (-z**2 / 2)**k / (factorial(k) * factorial2(2 * k - 2 * n - 1)) if np.isnan(s) or np.isinf(s): break else: s2 += s try: return -1 / z**(n + 1) * s1 + (-z)**(-n - 1) * s2 except (OverflowError, ZeroDivisionError): return np.nan
def gauss_moment(delta2, m): ''' Returns the nth moment of the absolute Gaussian random variable (divided by 2) with variance delta2. ''' delta = np.sqrt(delta2) if m % 2 == 0: b = 1 / 2 else: b = 1 / np.sqrt(2 * pi) return b * delta**m * misc.factorial2(m - 1)
def sph_yn_v(n, z, terms=25): # Doesn't handle overflow errors properly n = int(n) s1 = 0 for k in xrange(n + 1): s = (z**2/2)**k * factorial2(2*n - 2*k - 1)/factorial(k) if np.isnan(s) or np.isinf(s): break else: s1 += s s2 = 0 for k in xrange(n + 1, terms): s = (-z**2/2)**k/(factorial(k) * factorial2(2*k - 2*n - 1)) if np.isnan(s) or np.isinf(s): break else: s2 += s try: return -1/z**(n + 1) * s1 + (-z)**(-n - 1) * s2 except (OverflowError, ZeroDivisionError): return np.nan
def gen_R_nl(n, l, nu): """ Generates a radial eigenfunction for the Spherical Harmonic Oscillator. Used to speed up calculations. """ norm = sp.sqrt( sp.sqrt(2 * nu**3 / sp.pi) * 2**(n + 2 * l + 3) * factorial(n, exact=True) * nu**l / factorial2(2 * n + 2 * l + 1, exact=True)) laguerre = genlaguerre(n, l + .5) def R_nl(r): return norm * r**l * sp.exp(-nu * r**2) * laguerre(2 * nu * r**2) return R_nl
def lpKernel(N, freq): # # Lowpass filter 1D MAXFLAT kernel generator # # N is the filter half-size, must be odd # freq is the normalised cutoff frequency # # Returns the filter kernel of size (2N+1) # num = 2 * N + 1 result = np.zeros((num, 1)) for n in range(N + 1): i = n + N im = N - n if (n == 0): result[i] = freq else: p = n % 2 val = (sm.factorial2(N)**2 * np.pi**(p - 1) * np.sin(n * np.pi * freq)) / (2**p * n * sm.factorial2(i) * sm.factorial2(im)) result[i] = val result[im] = val return result / np.sum(result)
def get_initializations(self, num_pol=5, copy_fun='relu'): k = [] if copy_fun == 'relu': for n in range(num_pol): if n == 0: k.append(1.0 / np.sqrt(2 * np.pi)) elif n == 1: k.append(1.0 / 2) elif n == 2: k.append(1.0 / np.sqrt(4 * np.pi)) elif n > 2 and n % 2 == 0: c = 1.0 * factorial2(n - 3)**2 / np.sqrt( 2 * np.pi * np.math.factorial(n)) k.append(c) elif n >= 2 and n % 2 != 0: k.append(0.0) return k
def t_series(self, x): sum = 0.0 pow2 = 1 for t in xrange(self.n_t): dt = 2 * t pow2 <<= 1 powX = 1.0 powS = 1.0 for i in xrange(dt): powX *= x powS *= self.s s = (self.plog[t] * powX) /\ (fac.factorial2(dt, exact=True) * pow2 * powS) if((t % 2) == 0): sum += s else: sum -= s return sum
def trig_power_gauss2(t, n, delta2, deg=2): ''' Returns the analytic power series for the integral cos(tx)*x^(2k)*rho(x) or sin(tx)*x^(2k+1)*rho(x), where n = 2k or n = 2k+1, from 0 to L, up to degree deg. ''' S = 0 delta = np.sqrt(delta2) k = math.ceil((n - 1) / 2) while (2 * k + 1 - n) <= deg: term = (-1)**k * t**(2 * k + 1 - n) * delta**( 2 * k + 1) / misc.factorial2(2 * k + 1) term *= deriv_fac(2 * k + 1, n) S += term k += 1 sign = (-1)**(math.floor(n / 2)) return sign * (np.sqrt(2 * pi)**-1) * S
def Plmc(x,m,maxk): Plm = zeros(maxk,dtype=float) Plm[0] = (-1)**m*factorial2(2*m-1)*sqrt((1-x**2)**m) Plm[1] = x*(2*m+1)*Plm[0] codep=""" double xl = x; double Pm0 = Plm(0); double Pm1 = Plm(1); for (int l=m+1; l<m+maxk-1; l++){ double c = l-m+1.; double beta = (2*l+1.)*xl/c; double gamma = (l+m)/c; double Pm2 = beta*Pm1-gamma*Pm0; Plm(l-m+1) = Pm2; Pm0 = Pm1; Pm1 = Pm2; } """ weave.inline(codep, ['Plm', 'x', 'm', 'maxk'], type_converters=weave.converters.blitz, compiler = 'gcc') return Plm
def print_opt_prim_gauss_cart(prim_gauss_sph,fullpath,atomlabel,l): #creating a dictionary of primitive cartesian gaussians from the fitted spherical gaussians import scipy.misc as spm # spherical to cartesian gaussians #l,m) : [ (Nlm , [( c, lx,ly,lz)]) s2c = { (0, 0) : (1/4 , [( 1, 0, 0, 0)] ) , (1,-1) : (1/4 , [( 1, 0, 1, 0)] ) , (1, 0) : (1/4 , [( 1, 0, 0, 1)] ) , (1, 1) : (1/4 , [( 1, 1, 0, 0)] ) , (2,-2) : (1/4 , [( 1, 1, 1, 0)] ) , (2,-1) : (1/4 , [( 1, 0, 1, 1)] ) , (2, 0) : ( 3 , [( 2, 0, 0, 2), (-1, 2, 0, 0), (-1, 0, 2, 0)] ) , (2, 1) : (1/4 , [( 1, 1, 0, 1)] ) , (2, 2) : ( 1 , [( 1, 2, 0, 0), (-1, 0, 2, 0)] ) } PCG = {} for m in range(-l,l+1): Nlm, mytuple = s2c[(l,m)] g_tuples = [] for counter,(d,lx,ly,lz) in enumerate(mytuple): factor_lm = 1/4*np.sqrt(spm.factorial2(2*l+1)/np.pi/Nlm) for prim_g in prim_gauss_sph: print(prim_g) g_tuples = g_tuples + [(lx, ly, lz, d*prim_g[1]*factor_lm,prim_g[0])] dict_field= {(l,m) : g_tuples} PCG.update(dict_field) llabel = { 0 : 's', 1 : 'p', 2 : 'd' } fullname = fullpath+'/'+atomlabel+'.'+llabel[l]+'.py' f = open(fullname,'w+') #f.write(atomlabel+'.'+llabel[l]+ '=' + repr(PCG) + '\n' ) f.write('cgto=' + repr(PCG) + '\n' ) f.close()
def Sxyz(a,b,aa,bb,Ra,Rb,R): """ Compute overlap integral between two unnormalized Cartesian gaussian functions along one direction. INPUT: A: Angular momentum along the chosen direction for Gaussian 1 B: Angular momentum along the chosen direction for Gaussian 2 AA: Exponential coefficient for Gaussian 1 BB: Exponential coefficient for Gaussian 2 RA: Coordinate (along chosen direction) of the center of Gaussian 1 RB: Coordinate (along chosen direction) of the center of Gaussian 2 R: Coordinate (along chosen direction) of the center of the product of the two gaussians OUTPUT: S: Overlap of the two gaussians along the chosen direction Source: The Mathematica Journal Evaluation of Gaussian Molecular Integrals I. Overlap Integrals Minhhuy Hô and Julio Manuel Hernández-Pérez """ S = 0 for i in range(a+1): for j in range(b+1): if (i+j) % 2 == 0: tmp = misc.comb(a,i,exact=True) tmp *= misc.comb(b,j,exact=True) tmp *= misc.factorial2(i + j - 1,exact=True) tmp /= (2.*(aa+bb))**((i+j)/2.) tmp *= (R-Ra)**(a-i) tmp *= (R-Rb)**(b-j) S += tmp return S
def Sxyz(a, b, aa, bb, Ra, Rb, R): """ Compute overlap integral between two unnormalized Cartesian gaussian functions along one direction. INPUT: A: Angular momentum along the chosen direction for Gaussian 1 B: Angular momentum along the chosen direction for Gaussian 2 AA: Exponential coefficient for Gaussian 1 BB: Exponential coefficient for Gaussian 2 RA: Coordinate (along chosen direction) of the center of Gaussian 1 RB: Coordinate (along chosen direction) of the center of Gaussian 2 R: Coordinate (along chosen direction) of the center of the product of the two gaussians OUTPUT: S: Overlap of the two gaussians along the chosen direction Source: The Mathematica Journal Evaluation of Gaussian Molecular Integrals I. Overlap Integrals Minhhuy Hô and Julio Manuel Hernández-Pérez """ S = 0 for i in range(a + 1): for j in range(b + 1): if (i + j) % 2 == 0: tmp = misc.comb(a, i, exact=True) tmp *= misc.comb(b, j, exact=True) tmp *= misc.factorial2(i + j - 1, exact=True) tmp /= (2. * (aa + bb))**((i + j) / 2.) tmp *= (R - Ra)**(a - i) tmp *= (R - Rb)**(b - j) S += tmp return S
def R_nl(n, l, nu, r): norm = sp.sqrt( sp.sqrt(2 * nu ** 3 / sp.pi) * 2 ** (n + 2 * l + 3) * factorial(n) * nu ** l / factorial2(2 * n + 2 * l + 1) ) lagge = genlaguerre(n, l + 0.5)(2 * nu * r ** 2) return norm * r ** l * sp.e ** (-nu * r ** 2) * lagge
def tt(n,m): import numpy as np import scipy.misc as spm tt_expression=4*sqrt(np.pi*get_Nnm(n,m)/spm.factorial2(2*n+1))*r**n*exp(-1*r**2)*Mathar_Y(n,m) return tt_expression
def s_function(l_1, l_2, a, b, g): s = 0 for j in range(((l_1 + l_2) // 2) + 1): s += binomial_coefficient(2 * j, l_1, l_2, a, b) * (factorial2(2 * j - 1) / (2 * g)**j) return s
def fact_double(x): """Inputs x and outputs (2x-1)!!.""" return misc.factorial2(2*x-1, exact=True)
# stop = 1 # odd n #for i in xrange(n, stop-1, -2): # result *= i #return result result = 1 for i in xrange(n, 0, -2): result *= i return result # ===== print "\nBegin double factorial function demo \n" n = 3 dfact = sm.factorial2(n) print "Double factorial of " + str(n) + " using misc.factorial2() = " print str(dfact) print "" n = 4 dfact = sm.factorial2(n) print "Double factorial of " + str(n) + " using misc.factorial2() = " print str(dfact) print "" n = 4 dfact = my_double_fact(n) print "Double factorial of " + str(n) + " using my_double_fact() = " print str(dfact) print ""
def gamma_factorial(m, n): return factorial(n) * factorial2(2 * m + 2 * n - 3) / ( 2.0 ** (m + 1) * factorial(m + n - 3) * factorial2(2 * n - 1))
else: raise ValueError() def generate(func, name, maxval, vals_per_row=3): n = 0 table = "" for i in range(maxval + 1): val = func(i) table += "%25.17e" % val table += ", " n += 1 if n == vals_per_row: n = 0 table += "\n" table = "double %s[] = \n{%s};" % (name, table[1:-2]) table = table.replace(" inf", " INFINITY") return table table = [None for i in range(6)] table[0] = generate(np.sqrt, 'sqrt_int', 300) table[1] = generate(lambda x: 1 / np.sqrt(x), 'invsqrt_int', 300) table[2] = generate(lambda x: factorial(x, exact=True), 'factorial', 170) table[3] = generate(lambda x: factorial2(x, exact=True), 'double_factorial', 300) table[4] = generate(hfp, 'half_factorial_pos', 340) table[5] = generate(hfn, 'half_factorial_neg', 340) print("\n\n".join(table))
def _norm_moment(n): # moments of N(0, 1) return (1 - n % 2) * factorial2(n - 1)
def ref_xfact(m): return factorial2(2*m-1)/np.sqrt(factorial(2*m))
def Ewald_lattice_sum(l, m, crystal_type='sc', N=5, alpha=np.pi): """ Accelerated lattice sums using the Ewald method from S. Adler, Physica 27, pp 1193-1201 (1961), equation (25) on page 1200. """ assert l >= 2 assert crystal_type in ['sc', 'bcc', 'fcc'] if l == 2 and m == 0: if crystal_type == 'sc': return 2.*np.pi/3. elif crystal_type == 'bcc': return 4.*np.pi/3. elif crystal_type == 'fcc': return 8.*np.pi/3. else: raise ValueError('unsupported crystal type') else: # -- Spherical coordinates of the direct-space lattice points spherical_coordinatesj = lattice_point_spherical_coordinates( a=1., crystal_type=crystal_type, N=N ) rj, thetaj, phij = spherical_coordinatesj.T angular_valuesj = Ylm(l, m, thetaj, phij) # -- Volume of the unit cell (used later on) if crystal_type == 'sc': V = 1. elif crystal_type == 'bcc': V = 1. / 2. elif crystal_type == 'fcc': V = 1. / 4. # -- Spherical coordinates of the reciprocal-space lattice points if crystal_type == 'bcc': spherical_coordinatesn = lattice_point_spherical_coordinates( a=4.*np.pi, crystal_type='fcc', N=N ) elif crystal_type == 'fcc': spherical_coordinatesn = lattice_point_spherical_coordinates( a=4.*np.pi, crystal_type='bcc', N=N ) elif crystal_type == 'sc': spherical_coordinatesn = lattice_point_spherical_coordinates( a=2.*np.pi, crystal_type='sc', N=N ) else: raise ValueError('unsupported crystal type') gn, thetan, phin = spherical_coordinatesn.T angular_valuesn = Ylm(l, m, thetan, phin) # -- now computing the lattice sum in two terms. The first is a sum over # the direct-space lattice while the second is a sum over the # reciprocal-space lattice lattice_sumj = np.sum( angular_valuesj * (1. / rj) ** (l+1) * \ (1. - gammainc(l+0.5, alpha*rj**2)) ) lattice_sumn = (1j)**l * 4.*np.pi / V * np.sum( angular_valuesn * gn**(l-2) * (1./factorial2(2*l-1, exact=False)) * np.exp(-gn**2/(4.*alpha)) ) lattice_sum_value = lattice_sumj + lattice_sumn return lattice_sum_value
def sph_jn(n, z, terms=50): s = sum((-z**2/2)**k/(factorial(k) * factorial2(2*n + 2*k + 1)) for k in xrange(terms)) return z**n * s
def factorial2(n): return misc.factorial2(n, exact=True)