def get_omegakappatau(n, m): """Return omega, kappa, tau integrals, required for the scattering cross-section evaluation""" dim = n - m + 1 delta11 = identity(dim) if dim - 1 > 0: delta21 = diag(ones(dim - 1), -1) delta12 = diag(ones(dim - 1), 1) else: delta21 = 0 delta12 = 0 if dim - 2 > 0: delta31 = diag(ones(dim - 2), -2) delta13 = diag(ones(dim - 2), 2) else: delta31 = 0 delta13 = 0 l = arange(m, n + 1) ff = factorial(l + m) / factorial(l - m) * 2 / (2 * l + 1.) ff = transpose(repeat([ff], len(l), 0)) l = transpose(repeat([l], len(l), 0)) omega = ( 2 * (l * (l + 1) + m ** 2 - 1) / ((2 * l + 3) * (2 * l - 1.)) * delta11\ - (l - m) * (l - m - 1) / ((2 * l - 1) * (2 * l - 3.)) * delta31\ - (l + m + 1) * (l + m + 2) / ((2 * l + 3) * (2 * l + 5.)) * delta13 )\ * ff kappa = ( (l + 1) * (l - m) / (2 * l - 1.) * delta21\ - l * (l + m + 1) / (2 * l + 3.) * delta12 )\ * ff tau = l * (l + 1) * ff * delta11 return omega, kappa, transpose(kappa), tau
def legendre_(l, m, x): """ Legendre polynomial. Check equation (3) from Townsend, 2002: >>> ls,x = [0,1,2,3,4,5],cos(linspace(0,pi,100)) >>> check = 0 >>> for l in ls: ... for m in range(-l,l+1,1): ... Ppos = legendre_(l,m,x) ... Pneg = legendre_(l,-m,x) ... mycheck = Pneg,(-1)**m * factorial(l-m)/factorial(l+m) * Ppos ... check += sum(abs(mycheck[0]-mycheck[1])>1e-10) >>> print check 0 """ m_ = abs(m) legendre_poly = legendre(l) deriv_legpoly_ = legendre_poly.deriv(m=m_) deriv_legpoly = np.polyval(deriv_legpoly_, x) P_l_m = (-1)**m_ * (1 - x**2)**(m_ / 2.) * deriv_legpoly if m < 0: P_l_m = (-1)**m_ * factorial(l - m_) / factorial(l + m_) * P_l_m return P_l_m
def legendre_(l,m,x): """ Legendre polynomial. Check equation (3) from Townsend, 2002: >>> ls,x = [0,1,2,3,4,5],cos(linspace(0,pi,100)) >>> check = 0 >>> for l in ls: ... for m in range(-l,l+1,1): ... Ppos = legendre_(l,m,x) ... Pneg = legendre_(l,-m,x) ... mycheck = Pneg,(-1)**m * factorial(l-m)/factorial(l+m) * Ppos ... check += sum(abs(mycheck[0]-mycheck[1])>1e-10) >>> print check 0 """ m_ = abs(m) legendre_poly = legendre(l) deriv_legpoly_ = legendre_poly.deriv(m=m_) deriv_legpoly = np.polyval(deriv_legpoly_,x) P_l_m = (-1)**m_ * (1-x**2)**(m_/2.) * deriv_legpoly if m<0: P_l_m = (-1)**m_ * factorial(l-m_)/factorial(l+m_) * P_l_m return P_l_m
def splitter(self, key, line): """The mapper for step 1. Splits the range of possible tours into reasonably sized chunks for the consumption of the step 2 mappers. At this point the 'line' input should come directly from the first line of the one-line json file contains the edge cost graph and the starting node. The key is not relevant. """ #loading the json description of the trip to get at the size #of the edge costgraph sales_trip = json.loads(line) m = numpy.matrix(sales_trip['graph']) num_nodes = m.shape[0] num_tours = factorial(num_nodes - 1) #Here we break down the full range of possible tours into smaller #pieces. Each piece is passed along as a key along with the trip #description. step_size = int(100 if num_tours < 100**2 else num_tours / 100) steps = range(0, num_tours, step_size) + [num_tours] ranges = zip(steps[0:-1], steps[1:]) for range_low, range_high in ranges: #The key prepresents the range of tours to cost yield (("%d-%d" % (range_low, range_high), sales_trip))
def splitter(self, key, line): """The mapper for step 1. Splits the range of possible tours into reasonably sized chunks for the consumption of the step 2 mappers. At this point the 'line' input should come directly from the first line of the one-line json file contains the edge cost graph and the starting node. The key is not relevant. """ #loading the json description of the trip to get at the size #of the edge costgraph sales_trip = json.loads(line) m = numpy.matrix(sales_trip['graph']) num_nodes = m.shape[0] num_tours = factorial(num_nodes - 1) #Here we break down the full range of possible tours into smaller #pieces. Each piece is passed along as a key along with the trip #description. step_size = int(100 if num_tours < 100**2 else num_tours / 100) steps = range(0, num_tours, step_size) + [num_tours] ranges = zip(steps[0:-1], steps[1:]) for range_low, range_high in ranges: #The key prepresents the range of tours to cost yield( ("%d-%d"%(range_low,range_high), sales_trip ))
def WignerD( the , l , m , n ) : """ Wigner D matrices: d_{mn}^{l}(the) the -- angle in radians l -- degree (integer) m -- order (integer) n -- order (integer) """ if m >= n : factor = (-1)**(l-m) * np.sqrt( ( scimcm.factorial( l+m ) * scimcm.factorial( l-m ) ) / ( scimcm.factorial( l+n ) * scimcm.factorial( l-n ) ) ) a = m + n b = m - n print a print b return factor * np.cos( the/2. )**a * ( -np.sin( the/2. ) )**b * scisp.jacobi( l-m , a , b )( -np.cos( the ) ) else : return (-1)**(m-n) * WignerD( the , l , n , m )
def factorial(n, method='reduce'): """ Compute the factorial n! using long integers. Different implementations are available (see source code for the methods). Here is an efficiency comparison of the methods (computing 80!): reduce | 1.00 lambda list comprehension | 1.70 lambda functional | 3.08 plain recursive | 5.83 lambda recursive | 21.73 scipy | 131.18 """ if not isinstance(n, (int, long, float)): raise TypeError, 'factorial(n): n must be integer not %s' % type(n) n = long(n) if n == 0 or n == 1: return 1 if method == 'plain iterative': f = 1 for i in range(1, n+1): f *= i return f elif method == 'plain recursive': if n == 1: return 1 else: return n*factorial(n-1, method) elif method == 'lambda recursive': fc = lambda n: n and fc(n-1)*long(n) or 1 return fc(n) elif method == 'lambda functional': fc = lambda n: n<=0 or \ reduce(lambda a,b: long(a)*long(b), xrange(1,n+1)) return fc(n) elif method == 'lambda list comprehension': fc = lambda n: [j for j in [1] for i in range(2,n+1) \ for j in [j*i]] [-1] return fc(n) elif method == 'reduce': return reduce(operator.mul, xrange(2, n+1)) elif method == 'scipy': try: import scipy.misc.common as sc return sc.factorial(n) except ImportError: print 'numpyutils.factorial: scipy is not available' print 'default method="reduce" is used instead' return reduce(operator.mul, xrange(2, n+1)) # or return factorial(n) else: raise ValueError, 'factorial: method="%s" is not supported' % method
def factorial(n, method='reduce'): """ Compute the factorial n! using long integers. Different implementations are available (see source code for the methods). Here is an efficiency comparison of the methods (computing 80!): reduce | 1.00 lambda list comprehension | 1.70 lambda functional | 3.08 plain recursive | 5.83 lambda recursive | 21.73 scipy | 131.18 """ if not isinstance(n, (int, long, float)): raise TypeError, 'factorial(n): n must be integer not %s' % type(n) n = long(n) if n == 0 or n == 1: return 1 if method == 'plain iterative': f = 1 for i in range(1, n + 1): f *= i return f elif method == 'plain recursive': if n == 1: return 1 else: return n * factorial(n - 1, method) elif method == 'lambda recursive': fc = lambda n: n and fc(n - 1) * long(n) or 1 return fc(n) elif method == 'lambda functional': fc = lambda n: n<=0 or \ reduce(lambda a,b: long(a)*long(b), xrange(1,n+1)) return fc(n) elif method == 'lambda list comprehension': fc = lambda n: [j for j in [1] for i in range(2,n+1) \ for j in [j*i]] [-1] return fc(n) elif method == 'reduce': return reduce(operator.mul, xrange(2, n + 1)) elif method == 'scipy': try: import scipy.misc.common as sc return sc.factorial(n) except ImportError: print 'numpyutils.factorial: scipy is not available' print 'default method="reduce" is used instead' return reduce(operator.mul, xrange(2, n + 1)) # or return factorial(n) else: raise ValueError, 'factorial: method="%s" is not supported' % method
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))
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))
def get_inc(self, n, m, axisymm=False): """Return incident field expansion coefficients""" #if (self.Pna is None) or (len(self.Pna)!=n): self.Pna, self.Pdna = lpmn(n, n, cos(self.alpha))[:] self.sina = sin(self.alpha) sina = self.sina Pna = self.Pna[m, m:] l = arange(m, n + 1) if axisymm: c_inc = 1j**l * (2 * l + 1.) / (l * (l + 1.)) * Pna else: Pdna = self.Pdna[m, m:] c_inc = zeros(2 * (n - m + 1), dtype=complex) if sina == 0. and m == 1: c_inc[:n - m + 1] = -1j**(l - 1) * (2 * l + 1) else: c_inc[:n - m + 1] = -1j ** (l - 1) / sina\ * 2 * (2 * l + 1)\ * factorial(l - m) / factorial(l + m)\ * Pna return c_inc
def get_inc(self, n, m, axisymm=False): """Return incident field expansion coefficients""" #if (self.Pna is None) or (len(self.Pna)!=n): self.Pna, self.Pdna = lpmn(n, n, cos(self.alpha))[:] self.sina = sin(self.alpha) sina = self.sina Pna = self.Pna[m, m:] l = arange(m, n + 1) if axisymm: c_inc = 1j ** l * (2 * l + 1.) / (l * (l + 1.)) * Pna else: Pdna = self.Pdna[m, m:] c_inc = zeros(2 * (n - m + 1), dtype=complex) if sina == 0. and m == 1: c_inc[:n - m + 1] = -1j ** (l - 1) * (2 * l + 1) else: c_inc[:n - m + 1] = -1j ** (l - 1) / sina\ * 2 * (2 * l + 1)\ * factorial(l - m) / factorial(l + m)\ * Pna return c_inc
def sph_harm(theta,phi,l=2,m=1): """ Spherical harmonic according to Townsend, 2002. This function is memoized: once a spherical harmonic is computed, the result is stored in memory >>> theta,phi = mgrid[0:pi:20j,0:2*pi:40j] >>> Ylm20 = sph_harm(theta,phi,2,0) >>> Ylm21 = sph_harm(theta,phi,2,1) >>> Ylm22 = sph_harm(theta,phi,2,2) >>> Ylm2_2 = sph_harm(theta,phi,2,-2) >>> p = figure() >>> p = gcf().canvas.set_window_title('test of function <sph_harm>') >>> p = subplot(411);p = title('l=2,m=0');p = imshow(Ylm20.real,cmap=cm.RdBu) >>> p = subplot(412);p = title('l=2,m=1');p = imshow(Ylm21.real,cmap=cm.RdBu) >>> p = subplot(413);p = title('l=2,m=2');p = imshow(Ylm22.real,cmap=cm.RdBu) >>> p = subplot(414);p = title('l=2,m=-2');p = imshow(Ylm2_2.real,cmap=cm.RdBu) """ factor = (-1)**m * sqrt( (2*l+1)/(4*pi) * factorial(l-m)/factorial(l+m)) Plm = legendre_(l,m,cos(theta)) return factor*Plm*exp(1j*m*phi)
def sph_harm(theta, phi, l=2, m=1): """ Spherical harmonic according to Townsend, 2002. This function is memoized: once a spherical harmonic is computed, the result is stored in memory >>> theta,phi = mgrid[0:pi:20j,0:2*pi:40j] >>> Ylm20 = sph_harm(theta,phi,2,0) >>> Ylm21 = sph_harm(theta,phi,2,1) >>> Ylm22 = sph_harm(theta,phi,2,2) >>> Ylm2_2 = sph_harm(theta,phi,2,-2) >>> p = figure() >>> p = gcf().canvas.set_window_title('test of function <sph_harm>') >>> p = subplot(411);p = title('l=2,m=0');p = imshow(Ylm20.real,cmap=cm.RdBu) >>> p = subplot(412);p = title('l=2,m=1');p = imshow(Ylm21.real,cmap=cm.RdBu) >>> p = subplot(413);p = title('l=2,m=2');p = imshow(Ylm22.real,cmap=cm.RdBu) >>> p = subplot(414);p = title('l=2,m=-2');p = imshow(Ylm2_2.real,cmap=cm.RdBu) """ factor = (-1)**m * sqrt( (2 * l + 1) / (4 * pi) * factorial(l - m) / factorial(l + m)) Plm = legendre_(l, m, cos(theta)) return factor * Plm * exp(1j * m * phi)
def convex_hull_vol(self, ind, g): # Compute the convex hull of the region try: tri = Delaunay(ind) except: # Just triangulate bounding box mins = ind.min(axis=0) maxes = ind.max(axis=0) maxes[maxes==mins] += 1 ind = array(list(itertools.product(*tuple(array([mins,maxes]).T)))) tri = Delaunay(ind) vol = 0 for simplex in tri.vertices: pts = tri.points[simplex].T pts = pts - repeat(pts[:,0][:,newaxis], pts.shape[1],axis=1) pts = pts[:,1:] vol += abs(1/float(factorial(pts.shape[0])) * det(pts)) return vol,tri
def convex_hull_vol(self, ind, g): # Compute the convex hull of the region try: tri = Delaunay(ind) except: # Just triangulate bounding box mins = ind.min(axis=0) maxes = ind.max(axis=0) maxes[maxes == mins] += 1 ind = np.array(list(it.product(*tuple(np.array([mins, maxes]).T)))) tri = Delaunay(ind) vol = 0 for simplex in tri.vertices: pts = tri.points[simplex].T pts = pts - np.repeat( pts[:, 0][:, np.newaxis], pts.shape[1], axis=1) pts = pts[:, 1:] vol += abs(1 / float(factorial(pts.shape[0])) * det(pts)) return vol, tri
def norm(m, l): return sqrt((2 * l + 1) / 2. * factorial(l - m) / factorial(l + m))
def simplex(d): # compute the simplex volume using coordinates D = np.ones((d.shape[0] + 1, d.shape[1])) D[1:, :] = d vol = np.abs(np.linalg.det(D)) / factorial(d.shape[1] - 1) return vol
else: hdat[ep][m][n]=atof(item) ep+=1 file.close() # close the coefficients file for n in range(1,11): # extrapolate over the next epoch for m in range(n+1): gdat[epochs-1][m][n]=gdat[epochs-2][m][n] +5.*gdat[epochs-1][m][n] hdat[epochs-1][m][n]=hdat[epochs-2][m][n] +5.*hdat[epochs-1][m][n] # ------ declare and initialize fixed parameters for all epochs --------- a=6371.2 # igrf earth radius [m,n]=mgrid[0:11,0:11] # set up 11X11 meshgrid from scipy.misc.common import factorial """ build up the "schmidt" coefficients !!! careful with this definition """ schmidt=sqrt(2*factorial(n-m)/factorial(n+m))*(-1)**m schmidt[0,:]=1. # # #fig=figure() #imshow(schmidt,interpolation='nearest') #colorbar() #title("schmidt_mn") #fig.show()
for item in dat[3:]: if coeff=="g": gdat[ep][m][n]=atof(item) else: hdat[ep][m][n]=atof(item) ep+=1 file.close() # close the coefficients file for n in range(1,11): # extrapolate over the next epoch for m in range(n+1): gdat[epochs-1][m][n]=gdat[epochs-2][m][n] +5.*gdat[epochs-1][m][n] hdat[epochs-1][m][n]=hdat[epochs-2][m][n] +5.*hdat[epochs-1][m][n] # ------ declare and initialize fixed parameters for all epochs --------- a=6371.2 # igrf earth radius [m,n]=mgrid[0:11,0:11] # set up 11X11 meshgrid from scipy.misc.common import factorial schmidt=sqrt(2*factorial(n-m)/factorial(n+m))*(-1)**m schmidt[0,:]=1. # build up the "schmidt" coefficients #!!! careful with this definition # #fig=figure() #imshow(schmidt,interpolation='nearest') #colorbar() #title("schmidt_mn") #fig.show()
def simplex(d): # compute the simplex volume using coordinates D = np.ones((d.shape[0]+1, d.shape[1])) D[1:,:] = d vol = np.abs(np.linalg.det(D)) / factorial(d.shape[1] - 1) return vol