def roots(self): from numpy.lib.scimath import sqrt x1 = (-self.b + sqrt(self.b**2 - 4 * self.a * self.c)) / float( 2 * self.a) x2 = (-self.b - sqrt(self.b**2 - 4 * self.a * self.c)) / float( 2 * self.a) return x1, x2
def genSolve(e): k = sc.sqrt(2. * (e) * m_e / (hbar**2)) kw = sc.sqrt(2. * (e - V0) * m_e / (hbar**2)) res = opt.fsolve(f2p_as_reals, [10., -740., -10., 25, 58.213, -127., 150., 0.], (F, k, kw)) return reals_as_complex(res)
def roots(self): """ Return the two roots of the quadratic polynomial. The roots are real or complex, depending on the coefficients in the polynomial. Let us define a quadratic polynomial: >>> q = Quadratic(a=2, b=4, c=-16) >>> print q 2*x**2 + 4*x - 16 The roots are then found by >>> r1, r2 = q.roots() >>> r1 2.0 >>> r2 -4.0 """ a, b, c = self.a, self.b, self.c # short names q = b**2 - 4 * a * c root1 = (-b + sqrt(q)) / float(2 * a) root2 = (-b - sqrt(q)) / float(2 * a) return root1, root2
def lmat(k, K, m, alp, bet, gam): ko = sqrt(eo[m]) * k qo = sqrt(ko**2 - K**2) ed = ee[m] - eo[m] egam = eo[m] + gam**2 * ed qbar = sqrt(eo[m] * (ee[m] * egam * k**2 - K**2 * (ee[m] - bet**2 * ed)) / egam**2) qep = qbar - alp * gam * K * ed / egam qem = -qbar - alp * gam * K * ed / egam p = np.asmatrix([[np.exp(1j * qo * d), 0, 0, 0], [0, np.exp(-1j * qo * d), 0, 0], [0, 0, np.exp(1j * qep * d), 0], [0, 0, 0, np.exp(1j * qem * d)]]) m = np.asmatrix([[ -bet * qo, bet * qo, alp * qo**2 - gam * qep * K, alp * qo**2 - gam * qem * K ], [alp * qo - gam * K, -alp * qo - gam * K, bet * ko**2, bet * ko**2], [ -bet * ko**2, -bet * ko**2, (alp * qep - gam * K) * ko**2, (alp * qem - gam * K) * ko**2 ], [(alp * qo - gam * K) * qo, (alp * qo + gam * K) * qo, bet * qep * ko**2, bet * qem * ko**2]]) return np.matmul(m, np.matmul(p, np.linalg.inv(m)))
def QR_algorithm(A, niter, tol): """Return the eigenvalues of A using the QR algorithm.""" A = la.hessenberg(A).astype(float) eigenvalues = [] n = 0 for i in xrange(1, niter): Q, R = la.qr(A) A = np.dot(np.dot(la.inv(Q), A), Q) while n < np.shape(A)[1]: if n == np.shape(A)[1] - 1: eigenvalues.append(A[n][n]) elif abs(A[n + 1][n]) < tol: eigenvalues.append(A[n][n]) else: two_two = A[n:n + 2, n:n + 2] a = 1 b = -1 * (two_two[0][0] + two_two[1][1]) c = la.det(two_two) x = (-b + (scimath.sqrt(b**2 - 4 * a * c))) / 2 x2 = (-b - (scimath.sqrt(b**2 - 4 * a * c))) / 2 eigenvalues.append(x) eigenvalues.append(x2) n += 1 n += 1 return eigenvalues
def update_frequency(self, omega): """ Computes the JCA parameters (see Notes on the class). Parameters ---------- omega : Circular frequency of interest """ # Johnson et al model for rho_eq_til self.omega_0 = self.sigma * self.phi / (Air.rho * self.alpha) self.omega_infty = (self.sigma * self.phi * self.Lambda)**2 / ( 4 * Air.mu * Air.rho * self.alpha**2) self.F_JKD = sqrt(1 + 1j * omega / self.omega_infty) self.rho_eq_til = (Air.rho * self.alpha / self.phi) * (1 + (self.omega_0 / (1j * omega)) * self.F_JKD) self.alpha_til = self.phi * self.rho_eq_til / Air.rho # Champoux-Allard model for K_eq_til self.omega_prime_infty = (16 * Air.nu_prime) / (self.Lambda_prime**2) self.F_prime_CA = sqrt(1 + 1j * omega / self.omega_prime_infty) self.alpha_prime_til = 1 + self.omega_prime_infty * self.F_prime_CA / ( 2 * 1j * omega) self.K_eq_til = (Air.gamma * Air.P / self.phi) / (Air.gamma - (Air.gamma - 1) / self.alpha_prime_til) self.c_eq_til = sqrt(self.K_eq_til / self.rho_eq_til) self.k = omega / self.c_eq_til
def crystal_embed(e,eta): """ Evaluates crystal embedding potential by solving the one-dimensional Schroedinger equation through one unit cell in both directions. """ y0=[1.0,0.0,0.0,0.0] z1=np.linspace(-z_left,-z_left+alat,101) sol1=odeint(schroed,y0,z1,args=(e,eta)) z2=np.linspace(-z_left+alat,-z_left,101) sol2=odeint(schroed,y0,z2,args=(e,eta)) psi1=complex(sol1[50,0],sol1[50,1]) psi1_prime=complex(sol1[50,2],sol1[50,3]) psi2=complex(sol2[50,0],sol2[50,1]) psi2_prime=complex(sol2[50,2],sol2[50,3]) wronskian=psi1*psi2_prime-psi2*psi1_prime psi1=complex(sol1[100,0],sol1[100,1]) psi2=complex(sol2[100,0],sol2[100,1]) cos_ka=0.5*(psi1+psi2) ka=arccos(cos_ka) if ka.imag<0: ka=np.conj(ka) exp_ka=cos_ka+1.0j*sqrt(1.0-cos_ka**2) emb_cryst=0.5*wronskian/(exp_ka-psi2) if emb_cryst.imag>0.0: exp_ka=cos_ka-1.0j*sqrt(1.0-cos_ka**2) emb_cryst=0.5*wronskian/(exp_ka-psi2) return emb_cryst
def __init__(self, nq, mudelta_mesh=_default_mudelta_mesh, psi_mesh=_default_psi_mesh, value=None, **P): self.psi_1D = psi_mesh self.mudelta_1D = mudelta_mesh self.nq = nq mudelta_2D = np.zeros((len(mudelta_mesh), len(psi_mesh))) + \ mudelta_mesh[:, np.newaxis] psi_2D = np.zeros_like(mudelta_2D) + psi_mesh[np.newaxis, :] if value is None: self.value = Fq(sqrt(psi_2D * psi_2D - mudelta_2D), psi_2D, self.nq) else: self.value = value self.interpolator = RegularGridInterpolator( (self.mudelta_1D, self.psi_1D), self.value, bounds_error=False, fill_value=0, **P) self.phi_bounds = ((sqrt(psi_mesh[0] - mudelta_mesh[0]), sqrt(psi_mesh[0] - mudelta_mesh[-1])), (sqrt(psi_mesh[-1] - mudelta_mesh[0]), sqrt(psi_mesh[-1] - mudelta_mesh[-1]))) self.psi_bounds = (psi_mesh[0], psi_mesh[-1])
def _eff_index_refr(self, c, zb, dzb2): """ Compute the effective index of refraction, including the artificial bottom absorption term. Args: c: numpy.array Sound speed in m/s zb: numpy.array Seafloor depth in meters dzb2: numpy.array Seafloor gradient squared Returns: : numpy.array Effective index of refraction : numpy.array Square root of density """ # refractive index squared n2 = np.zeros((self.grid.nz, self.grid.nq)) n2[self.grid.below_qz] = index_refr_sq(self.c0, c) n2 = self.grid.mirror(n2) # effective refr. index squared n2, rho = eff_index_refr_sq(z=self.grid.z_qz, zb=zb, dzb2=dzb2, k0=self.k0, L=np.pi/self.k0, n2=n2, n2b=self.n2b, r=self.water_density, rb=self.bottom['density'], return_density=True) # add absorption n2 += self.absorp return scimath.sqrt(n2), scimath.sqrt(rho)
def QR_algorithm(A, niter, tol): """Return the eigenvalues of A using the QR algorithm.""" A = la.hessenberg(A) m, n = A.shape eigen_vals = [] for x in xrange(0, niter): Q, R = la.qr(A) A_new = np.dot(R, Q) A = A_new x = 0 while x < m: if x == m - 1: eigen_vals.append(A[x][x]) break elif abs(A[x + 1][x]) < tol: eigen_vals.append(A[x][x]) else: a = A[x][x] b = A[x][x + 1] c = A[x + 1][x] d = A[x + 1][x + 1] t = a + d d = a * d - b * c eigen_vals.append(t / 2.0 + scimath.sqrt(t**2 / (4 - d))) eigen_vals.append(t / 2.0 - scimath.sqrt(t**2 / (4 - d))) x += 1 x += 1 return eigen_vals
def QR_algorithm(A,niter,tol): """Return the eigenvalues of A using the QR algorithm.""" H = la.hessenberg(A) for i in xrange(niter): Q,R = la.qr(H) H = np.dot(R,Q) S = H print S eigenvalues = [] i = 0 while i < S.shape[0]: if i == S.shape[0]-1: eigenvalues.append(S[i,i]) elif abs(S[i+1,i]) < tol: eigenvalues.append(S[i,i]) else: a = S[i,i] b = S[i,i+1] c = S[i+1,i] d = S[i+1,i+1] B = -1*(a+d) C = a*d-b*c eigen_plus = (-B + sm.sqrt(B**2 - 4*C))/2. eigen_minus = (-B - sm.sqrt(B**2 - 4*C))/2. eigenvalues.append(eigen_plus) eigenvalues.append(eigen_minus) i+=1 i+=1 return eigenvalues
def __eigs(self, freq, K): N_t = K.x.shape[0] I = np.eye(N_t) EPS = self._fft_eps EPSxy = self._fft_eps_ix EPSyx = self._fft_eps_iy F11 = -K.x @ la.solve(EPS, K.y) F12 = I + K.x @ la.solve(EPS, K.x) F21 = -I - K.y @ la.solve(EPS, K.y) F22 = K.y @ la.solve(EPS, K.x) self.L_eh = np.block([[F11, F12], [F21, F22]]) G11 = -K.x @ K.y G12 = EPSyx + K.x ** 2 G21 = -EPSxy - K.y ** 2 G22 = K.x @ K.y self.L_he = np.block([[G11, G12], [G21, G22]]) if EPS.size > 1 and not np.count_nonzero(EPS - np.diag(np.diag(EPS))): self.U = np.eye(2 * N_t) k_z = sqrt(np.diag(EPS) - np.diag(K.intensity())) k_z = np.conj(k_z) self.gamma = 1j * np.hstack((k_z, k_z)) else: (Q, self.U) = la.eig(self.L_eh @ self.L_he) self.gamma = sqrt(Q) self.V = -self.L_he @ self.U / self.gamma self._K = K self._freq = freq
def hybridWith(self, v2, w2): """Create a weighted average of two voters. The weight of v1 is always 1; w2 is the weight of v2 relative to that. If both are standard normal to start with, the result will be standard normal too. Length must be the same >>> Voter([1,2]).hybridWith(Voter([1,2,3]),1) Traceback (most recent call last): ... AssertionError A couple of basic sanity checks: >>> v2 = Voter([1,2]).hybridWith(Voter([3,2]),1) >>> [round(u,5) for u in v2.hybridWith(v2,1)] [4.0, 4.0] >>> Voter([1,2,5]).hybridWith(Voter([-0.5,-1,0]),0.75) (0.5, 1.0, 4.0) """ assert len(self) == len(v2) return self.copyWithUtils( ((self[i] / sqrt(1 + w2 ** 2)) + (w2 * v2[i] / sqrt(1 + w2 ** 2))) for i in range(len(self)))
def roots(self): """ Return the two roots of the quadratic polynomial. The roots are real or complex, depending on the coefficients in the polynomial. Let us define a quadratic polynomial: >>> q = Quadratic(a=2, b=4, c=-16) >>> print q 2*x**2 + 4*x - 16 The roots are then found by >>> r1, r2 = q.roots() >>> r1 2.0 >>> r2 -4.0 """ a, b, c = self.a, self.b, self.c # short names q = b**2 - 4*a*c root1 = (-b + sqrt(q))/float(2*a) root2 = (-b - sqrt(q))/float(2*a) return root1, root2
def _hexagonalPositions(nrow, ncol, radius): X = np.tile(np.arange(ncol) * 1.5 * radius, (nrow, 1)) + radius Y = np.tile(np.arange(nrow) * sqrt(3) * radius, (ncol, 1)).T + radius Y = Y + np.tile([0, sqrt(3) / 2 * radius], (nrow, np.floor(ncol / 2))) X = np.reshape(X, (X.size), order = 'F') Y = np.reshape(Y, (Y.size), order = 'F') return np.array([X, Y]).T
def hybridWith(self, v2, w2): """Create a weighted average of two voters. The weight of v1 is always 1; w2 is the weight of v2 relative to that. If both are standard normal to start with, the result will be standard normal too. Length must be the same >>> Voter([1,2]).hybridWith(Voter([1,2,3]),1) Traceback (most recent call last): ... AssertionError A couple of basic sanity checks: >>> v2 = Voter([1,2]).hybridWith(Voter([3,2]),1) >>> [round(u,5) for u in v2.hybridWith(v2,1)] [4.0, 4.0] >>> Voter([1,2,5]).hybridWith(Voter([-0.5,-1,0]),0.75) (0.5, 1.0, 4.0) """ assert len(self) == len(v2) return self.copyWithUtils( ((self[i] / sqrt(1 + w2**2)) + (w2 * v2[i] / sqrt(1 + w2**2))) for i in range(len(self)))
def R_C(x, y, rtol=2e-4): r"""Computes a degenerate case of `R_J` .. math:: R_C(x, y) = \frac{1}{2}\int_0^\infty (t + x)^{1-\frac{1}{2}}(t + y)^{-1} dt """ factor = 1 if _is_neg_real(y): factor = scimath.sqrt(x / (x + abs(y))) x = x + abs(y) y = abs(y) A0 = (x + 2 * y) / 3 Q = (3 * rtol)**(-1 / 8) * abs(A0 - x) A = _A_gen(x, y, y) for n, Am in enumerate(A): if 4**(-n) * Q < abs(Am): s = (y - A0) / (4**n * Am) result = (1 / scimath.sqrt(Am)) * (1 + s**2 * (3 / 10) + s**3 * (1 / 7) + s**4 * (3 / 8) + s**5 * (9 / 22) + s**6 * (159 / 208) + s**7 * (9 / 8)) return factor * result
def __init__(self, ordinaryIndex, extraIndex, ordinaryLoss, extraLoss, name, materialType='isotropic'): """ Creates an instance of a material class object. Inputs are: ordinaryIndex - (float) real part of the refractive index for the ordinary axes. extraIndex - (float) real part of the refractive index for the extraordinary axis. ordinaryLoss - (float) ratio of the imaginary part of the dielectric constant to the real part for ordinary ray. extraLoss - (float) ratio of the imaginary part of the dielectric constant to the real part for extraordinary ray. name - (string) name of the material in question. materialType - (string) 'isotropic' or 'uniaxial'. If 'isotropic' ordinaryIndex = extraIndex. """ self.ordinaryIndex = ordinaryIndex self.extraIndex = extraIndex self.extraLoss = extraLoss self.ordinaryLoss = ordinaryLoss self.name = name self.materialType = materialType # Now create complex dielectric constant and refractive indices. self.ordinaryEpsilon \ = (1 - 1j*ordinaryLoss) * ordinaryIndex**2 self.extraEpsilon \ = (1 - 1j*extraLoss) * extraIndex**2 self.ordinaryComplexIndex = sqrt(self.ordinaryEpsilon) self.extraComplexIndex = sqrt(self.extraEpsilon)
def plotThroughput(logFile, windowSize = 10000, marker = 's', iteration = 50): fileHandle = open(logFile, 'r') wholeFile = fileHandle.read(); wholeFile = wholeFile.split("\n")[:-1] wholeFileSorted = sorted(wholeFile, key = lambda x : float(x.split()[2])); globalMin = float(wholeFileSorted[0].split()[2]) currentStart = globalMin currentEnd = currentStart + windowSize data = {(currentStart, currentEnd) : 0} for line in wholeFileSorted: min_val = float(line.split()[2]) if min_val > currentEnd: currentStart = currentEnd currentEnd = currentStart + windowSize data[(currentStart, currentEnd)] = 0 data[(currentStart, currentEnd)] += 1 x = [] y = [] for key in sorted(data.keys()): x.append(((key[1] + key[0])/2.0 - globalMin)/1000.0) y.append(data[key]*1000/(key[1] - key[0])) p1, = plt.plot(x,y, marker = marker) ax = plt.gca() #ax.set_ylim([-10, 300]) ax.set_xlabel('Experiment time (s)') ax.set_ylabel('Messages read per second') ax.set_title('Throughput of read operations') total = [] for key in data: if((key[0] - globalMin)/1000. > 1500): continue if((key[0] - globalMin)/1000. < 300): continue total.append(data[key]*1000/(key[1] - key[0])) n, min_max, mean, var, _, _ = stats.describe(total) t_test = stats.t.interval(0.95, n - 1, loc=mean, scale=sqrt(var) / sqrt(n)) chisquare = stats.chi2.interval(0.95, n - 1) #print "Data samples: %d" % n #print "Average response time: %s ms" % mean #print "Sample standard deviation: %s ms" % sqrt(var) # print "95%% confidence interval for the mean (t-student test): (%s, %s) ms" % stats.t.interval(0.95, n - 1,loc = mean, scale = sqrt(var)/sqrt(n)) #chisquare = stats.chi2.interval(0.95, n - 1) #print "95%% confidence interval for the stdev (chi-square test): (%s, %s) ms" % (sqrt((n - 1)*var/chisquare[1]), sqrt((n - 1)*var/chisquare[0])) #m,b = polyfit(x, y, 1) #print "slope: %s, intercept: %s" % (m, b) #print "$%d$ & $%.1f$ & $%.1f$ & $%.1f-%.1f$ & $%.1f-%.1f$" % (iteration, mean, sqrt(var), stats.t.interval(0.95, n - 1, loc=mean, scale=sqrt(var) / sqrt(n))[0], # stats.t.interval(0.95, n - 1, loc=mean, scale=sqrt(var) / sqrt(n))[1], # sqrt((n - 1)*var/chisquare[1]), # sqrt((n - 1)*var/chisquare[0])) print "$%d$ & $%d$ & $%d$ & $%.1f$ & $%.1f$ & $%.1f-%.1f$ & $%.1f-%.1f$ \\\\" % (iteration[0], iteration[1], iteration[2], mean, sqrt(var), t_test[0], t_test[1], sqrt((n - 1)*var/chisquare[1]), sqrt((n - 1)*var/chisquare[0])) fileHandle.close(); return p1
def limite_large_barriere(E, V, d): """Tranmission par effet tunnel: Cas d'une barriere épaisse, ou la formule se simplifie """ k = sqrt(2 * m * E) / hbar # Vecteur d'onde a l'exterieur de la barriere K = sqrt(2 * m * (V - E)) / hbar # Vecteur d'onde a l'interieur de la barriere T = np.real(16 * K**2 * k**2 / (K**2 + k**2)**2 * np.exp(-2 * K * d)) validite = (E < V) & (K * d > approx) return T, validite
def XY_to_L(x, y): ''' Dato un segmento di coordinate x,y, calcola la coordinata propria (solidale al segmento). L'origine della nuova coordinata L viene assunta a metà della lunghezza degli array di ingresso (che ha senso finché x,y definiscono un segmento di retta). ''' N2 = int(np.floor(len(x) / 2)) L = 0 * x L[0:N2] = -1 * sqrt((x[0:N2] - x[N2])**2 + (y[0:N2] - y[N2])**2) L[N2:] = 1 * sqrt((x[N2:] - x[N2])**2 + (y[N2:] - y[N2])**2) return L
def theta_between_two_vector(vec1,vec2): if ((sqrt(vec1[0]**2 + vec1[1]**2)*(sqrt(vec2[0]**2 + vec2[1]**2)))!=0): a = math.asin(float((vec1[0]*vec2[1] + vec1[1]*vec2[0])/(sqrt(vec1[0]**2 + vec1[1]**2)*(sqrt(vec2[0]**2 + vec2[1]**2))))) format(a, ".2f") if(a != math.nan ): return a else: return 360 else: return 360
def getShortestDist(pointX, segment): u,v = getUV(segment, pointX) if u<1 and u>0: return abs(v) elif u<0: px = segment.P - pointX return sqrt(np.vdot(px, px)) else: qx = segment.Q - pointX return sqrt(np.vdot(qx, qx))
def Intro_Crack_xyz(self,k1,p1,p2,q1,q2,u1,u2): from numpy.lib import scimath as SM filelist = glob.glob("./xyz/*") filename = filelist[-1] x, y, z , AtomNumber, xlo, xhi, ylo, yhi, zlo, zhi = self.read_xyz(filename) xnew,ynew,znew = [],[],[] xc ,yc = 0 ,0 AtomNumber = len(x) for i in range(AtomNumber): xnew.append(float(x[i])) ; ynew.append(float(y[i])); znew.append(float(z[i])) for i in range(len(xnew)): dx , dy = xnew[i] - xc , ynew[i] - yc r = np.sqrt(dx * dx + dy * dy) coeff = 100 * k1 * np.sqrt(2 * r / self.pi) if ynew[i] < yc: theta = np.arctan2(-dy, dx) ux = 1./(u1-u2) * (u1 * p2 * SM.sqrt(np.cos(theta) - u2 * np.sin(theta)) - u2 * p1 * SM.sqrt(np.cos(theta) - u1 * np.sin(theta))) uy = 1./(u1-u2) * (u1 * q2 * SM.sqrt(np.cos(theta) - u2 * np.sin(theta)) - u2 * q1 * SM.sqrt(np.cos(theta) - u1 * np.sin(theta))) ux = coeff * ux.real uy = coeff * uy.real if ynew[i] >= yc: theta = np.arctan2(dy, dx) ux = 1./(u1-u2) * (u1 * p2 * SM.sqrt(np.cos(theta) - u2 * np.sin(theta)) - u2 * p1 * SM.sqrt(np.cos(theta) - u1 * np.sin(theta))) uy = 1./(u1-u2) * (u1 * q2 * SM.sqrt(np.cos(theta) - u2 * np.sin(theta)) - u2 * q1 * SM.sqrt(np.cos(theta) - u1 * np.sin(theta))) ux = coeff * ux.real uy = -coeff * uy.real print ux print uy xnew[i] += ux ynew[i] += uy xlo , xhi, ylo, yhi = min(xnew) - 4 , max(xnew) + 4 , min(ynew) - 4 , max(ynew) + 4 # import matplotlib.pylab as plt # from mpl_toolkits.mplot3d import Axes3D # fig = plt.figure() # ax = fig.gca(projection='3d') # ax.scatter(xnew,ynew,znew) # plt.show() AtomNumberOut = len(xnew) filename = "Crack.txt" with open(filename,mode="w") as fout: fout.write("#Edge_dislocation for bcc [111](110)\n") fout.write("\n") fout.write("%d atoms\n"%(AtomNumberOut)) fout.write("1 atom types\n") fout.write("%f\t%f xlo xhi\n"%(xlo,xhi)) fout.write("%f\t%f ylo yhi\n"%(ylo,yhi)) fout.write("%f\t%f zlo zhi\n"%(zlo,zhi)) fout.write("xy xz yz = %8.5f %8.5f %8.5f"%(0,0,0)) fout.write("\n") fout.write("Atoms\n") fout.write("\n") for i in range(AtomNumberOut): fout.write("%d 1 %12.7f %12.7f %12.7f\n"%(i+1, xnew[i],ynew[i] ,znew[i])) fout.close() return
def var_driver_gen(): # Driver with varing emittance n0_per_cc = 5.0334e15 N = int(2e7) z = np.linspace(5., 13., 128) current = driver_profile(z) samp_generator = beam_gen.DistGen(z, current) sample_z = samp_generator.sample_gen_direct(N * 1.01) sample_z = sample_z[:N] # discard extra particles hist, z_bins = np.histogram(sample_z, bins=len(z)) hist = hist * (np.max(current) / hist.max()) plt.plot(z_bins[:-1], hist, 'k.-') n_emit0 = 20.e-6 # emittance at beam head in SI units # varying emittance z_max = sample_z.max() z_min = sample_z.min() #n_emit = ((z_max - sample_z)/(z_max - z_min)*99.+1.)*n_emit0 z_trans = z_max - (z_max - z_min) * 0.05 n_emit = np.piecewise(sample_z, [sample_z < z_trans], [ lambda sample_z: ((z_trans - sample_z) / (z_trans - z_min) * 99. + 1.) * n_emit0, n_emit0 ]) k0 = np.sqrt(4 * constants.pi * constants.physical_constants['classical electron radius'][0] * n0_per_cc * 1e6) gamma_beam = 19569.5 # Matched beam size sig_r = sqrt(sqrt(2. / gamma_beam) / k0) * np.sqrt(n_emit) sample_z = sample_z / k0 # Transform to meter beam_generator = beam_gen.BeamGen(sig_x=sig_r, sig_y=sig_r, n_emit_x=n_emit, n_emit_y=n_emit, gamma0=gamma_beam, sig_gamma=1., n_macroparticles=N, zf_x=0., zf_y=0., z_array=sample_z) beam_generator.beam_gen() #beam_generator.x_array *= (z_max - beam_generator.z_array)/ratio +1. #beam_generator.y_array *= (z_max - beam_generator.z_array)/ratio +1. #beam_generator.beam_symmetrization() beam_generator.h5_file_name = './driver.h5' #beam_generator.h5_file_name = './driver_symmetric.h5' beam_generator.save_sample_h5(sim_bound=[[0., 13.], [-6., 6.], [-6., 6.]], nx=[512, 512, 512], n0_per_cc=n0_per_cc, Q_beam=-6.e-9) beam_generator.plot_hist2D(xaxis='z', yaxis='x') plt.show()
def num_divisors(num): divisors = 0 for i in range(1, int(sqrt(num))): if num % i == 0: divisors += 1 divisors *= 2 if sqrt(num).is_integer(): divisors += 1 return divisors
def transmission(E, V, d): """ Tranmission par effet tunnel: formule exacte""" k = sqrt(2 * m * E) / hbar # Vecteur d'onde a l'exterieur de la barriere K = sqrt(2 * m * (V - E)) / hbar # Vecteur d'onde a l'interieur de la barriere #t = 2*i*k*K*np.exp(-i*k*d)*1/ ( (K**2+k**2)*np.sinh(K*d) + 2*i*K*k*np.cosh(K*d) ) # coefficient de transmission en amplitude T = np.real( 4 * K**2 * k**2 / ((K**2 + k**2)**2 * np.sinh(K * d)**2 + 4 * K**2 * k**2)) # coefficient de transmission en probabilite return T
def bs_put(S, X, T, rf, sigma): """ Black-Scholes-Merton option model put S: current stock price X: exercise price T: maturity date in years rf: risk-free rate (continusouly compounded) sigma: volatility of underlying security """ d1 = (log(S / X) + (rf + sigma * sigma / 2.) * T) / (sigma * sqrt(T)) d2 = d1 - sigma * sqrt(T) return -S * stats.norm.cdf(-d1) + X * exp(-rf * T) * stats.norm.cdf(-d2)
def CF_gz_AC(parms, tau, wixi=wixi): u""" Axial (1D) diffusion in a TIR-FCS setup. From Two species (bound/unbound) this is the cross correlation part. This function is called by other functions within this module. *parms* - a list of parameters. Parameters (parms[i]): [0] D_3D 3D Diffusion coefficient (species A) [1] D_2D 2D Diffusion coefficient of bound species C [2] sigma lateral size of the point spread function sigma = simga_0 * lambda / NA [3] a side size of the square pinhole [4] d_eva evanescent decay length (decay to 1/e) [5] Conc_3D 3-dimensional concentration of species A [6] Conc_2D 2-dimensional concentration of species C [7] eta_3D molecular brightness of species A [8] eta_2D molecular brightness of species C [9] k_a Surface association rate constant [10] k_d Surface dissociation rate constant *tau* - lag time """ D = parms[0] #D_2D = parms[1] #sigma = parms[2] # a = parms[3] d_eva = parms[4] Conc_3D = parms[5] # ligand concentration in solution Conc_2D = parms[6] eta_3D = parms[7] eta_2D = parms[8] k_a = parms[9] k_d = parms[10] # Define some other constants: K = k_a / k_d # equilibrium constant Beta = 1 / (1 + K * Conc_3D) Re = D / d_eva**2 Rt = D * (Conc_3D / (Beta * Conc_2D))**2 Rr = k_a * Conc_3D + k_d # Define even more constants: sqrtR1 = -Rr / (2 * nps.sqrt(Rt)) + nps.sqrt(Rr**2 / (4 * Rt) - Rr) sqrtR2 = -Rr / (2 * nps.sqrt(Rt)) - nps.sqrt(Rr**2 / (4 * Rt) - Rr) R1 = sqrtR1**2 R2 = sqrtR2**2 # And even more more: sqrtR3 = sqrtR1 + nps.sqrt(Re) sqrtR4 = sqrtR2 + nps.sqrt(Re) #R3 = sqrtR3 **2 #R4 = sqrtR4 **2 # Calculate return function A1 = eta_2D * Conc_2D * k_d / (eta_3D * Conc_3D) A2 = sqrtR4 * wixi(-nps.sqrt(tau * R1)) - sqrtR3 * wixi(-nps.sqrt(tau * R2)) A3 = (sqrtR1 - sqrtR2) * wixi(nps.sqrt(tau * Re)) A4 = (sqrtR1 - sqrtR2) * sqrtR3 * sqrtR4 Solution = A1 * (A2 + A3) / A4 # There are some below numerical errors-imaginary numbers. # We do not want them. return np.real_if_close(Solution)
def roots(a, b, c): dis = b**2 - 4 * a * c #Calcular el discriminante if dis >= 0: #Caso de raices reales x1 = (-b + sqrt(dis)) / (2 * a) #Calcular primera raiz x2 = (-b - sqrt(dis)) / (2 * a) #Calcular segunda raiz return x1, x2 elif dis < 0: #Caso de raices complejas x1 = (-b + sqrt(dis)) / (2 * a) #Calcular primera raiz x2 = x1.conjugate() #Calcular segunda raiz return x1, x2
def assertPointsAlmostEquals(self, pts1, pts2, numPoints, noise): for i in range(0, pts1.GetNumberOfPoints(), pts1.GetNumberOfPoints() // numPoints): self.assertTrue( abs(pts1.GetPoint(i)[0] - pts2.GetPoint(i)[0]) <= max(sqrt(noise), 1e-2)) self.assertTrue( abs(pts1.GetPoint(i)[1] - pts2.GetPoint(i)[1]) <= max(sqrt(noise), 1e-2)) self.assertTrue( abs(pts1.GetPoint(i)[2] - pts2.GetPoint(i)[2]) <= max(sqrt(noise), 1e-2))
def CF_gz_AC(parms, tau, wixi=wixi): u""" Axial (1D) diffusion in a TIR-FCS setup. From Two species (bound/unbound) this is the cross correlation part. This function is called by other functions within this module. *parms* - a list of parameters. Parameters (parms[i]): [0] D_3D 3D Diffusion coefficient (species A) [1] D_2D 2D Diffusion coefficient of bound species C [2] sigma lateral size of the point spread function sigma = simga_0 * lambda / NA [3] a side size of the square pinhole [4] d_eva evanescent decay length (decay to 1/e) [5] Conc_3D 3-dimensional concentration of species A [6] Conc_2D 2-dimensional concentration of species C [7] eta_3D molecular brightness of species A [8] eta_2D molecular brightness of species C [9] k_a Surface association rate constant [10] k_d Surface dissociation rate constant *tau* - lag time """ D = parms[0] #D_2D = parms[1] #sigma = parms[2] # a = parms[3] d_eva = parms[4] Conc_3D = parms[5] # ligand concentration in solution Conc_2D = parms[6] eta_3D = parms[7] eta_2D = parms[8] k_a = parms[9] k_d = parms[10] # Define some other constants: K = k_a/k_d # equilibrium constant Beta = 1/(1 + K*Conc_3D) Re = D / d_eva**2 Rt = D * (Conc_3D / (Beta * Conc_2D))**2 Rr = k_a * Conc_3D + k_d # Define even more constants: sqrtR1 = -Rr/(2*nps.sqrt(Rt)) + nps.sqrt( Rr**2/(4*Rt) - Rr ) sqrtR2 = -Rr/(2*nps.sqrt(Rt)) - nps.sqrt( Rr**2/(4*Rt) - Rr ) R1 = sqrtR1 **2 R2 = sqrtR2 **2 # And even more more: sqrtR3 = sqrtR1 + nps.sqrt(Re) sqrtR4 = sqrtR2 + nps.sqrt(Re) #R3 = sqrtR3 **2 #R4 = sqrtR4 **2 # Calculate return function A1 = eta_2D * Conc_2D * k_d / (eta_3D * Conc_3D) A2 = sqrtR4*wixi(-nps.sqrt(tau*R1)) - sqrtR3*wixi(-nps.sqrt(tau*R2)) A3 = ( sqrtR1 - sqrtR2 ) * wixi( nps.sqrt(tau*Re) ) A4 = ( sqrtR1 - sqrtR2 ) * sqrtR3 * sqrtR4 Solution = A1 * ( A2 + A3 ) / A4 # There are some below numerical errors-imaginary numbers. # We do not want them. return np.real_if_close(Solution)
def roots(self): #calculate roots a = self.a2 b = self.a1 c = self.a0 if (b**2 - 4*a*c) < 0: #if imaginary return None #drop else: x1 = (-b + sqrt(b**2 - 4*a*c))/(2*a) x2 = (-b - sqrt(b**2 - 4*a*c))/(2*a) if x1 == x2: #if equal return x1 #return one else: return x1, x2
def get_fresnel_r_s(zenith_incoming, n_2=1.3, n_1=1.): """ returns the coefficient r which is the ratio of the reflected wave's electric field amplitude to that of the incident wave for perpendicular polarization (s-wave) this polarization corresponds to the ePhi polarization parallel and perpendicular refers to the signal's polarization with respect to the 'plane of incident' which is defindes as: "the plane of incidence is the plane which contains the surface normal and the propagation vector of the incoming radiation." """ n = n_2 / n_1 return (np.cos(zenith_incoming) - SM.sqrt(n**2 - np.sin(zenith_incoming)**2)) / \ (np.cos(zenith_incoming) + SM.sqrt(n**2 - np.sin(zenith_incoming)**2))
def reflectrometry(a, n2, n3, s1, s2, z): a0 = 5 * 10**7 kz1 = k * scimath.sqrt(n1**2 - (np.cos(a))**2) kz2 = k * scimath.sqrt(n2**2 - (np.cos(a))**2) kz3 = k * scimath.sqrt(n3**2 - (np.cos(a))**2) r12 = (kz1 - kz2) / (kz1 + kz2) * np.exp(-2 * kz1 * kz2 * s1**2) r23 = (kz2 - kz3) / (kz2 + kz3) * np.exp(-2 * kz2 * kz3 * s2**2) x2 = np.exp(-2 * 1j * kz2 * 0.96 * z) * r23 x1 = (r12 + x2) / (1 + r12 * x2) rr = a0 * (np.absolute(x1))**2 return rr
def rp(k, K, n, alp, bet, gam): costh1 = sqrt(1 - (K / (sqrt(ea[i]) * k))**2) costh2 = sqrt(1 - (K / (sqrt(es[i]) * k))**2) l_ = lmat(k, K, n, alp, bet, gam) k1 = sqrt(ea[n]) * k k2 = sqrt(es[n]) * k q1 = sqrt(ea[n] * k**2 - K**2) q2 = sqrt(es[n] * k**2 - K**2) p1 = k2 * (costh1 * l_[0, 0] + k1 * l_[0, 2]) - costh2 * (costh1 * l_[2, 0] + k1 * l_[2, 2]) p2 = q2 * (costh1 * l_[1, 0] + k1 * l_[1, 2]) - costh1 * l_[3, 0] - k1 * l_[3, 2] a1 = k2 * (l_[0, 1] - q1 * l_[0, 3]) - costh2 * (l_[2, 1] - q1 * l_[2, 3]) a2 = q2 * (l_[1, 1] - q1 * l_[1, 3]) - l_[3, 1] + q1 * l_[3, 3] b1 = k2 * (costh1 * l_[0, 0] - k1 * l_[0, 2]) - costh2 * (costh1 * l_[2, 0] - k1 * l_[2, 2]) b2 = q2 * (costh1 * l_[1, 0] - k1 * l_[1, 2]) - costh1 * l_[3, 0] + k1 * l_[3, 2] rpp = -(p1 * a2 - a1 * p2) / (a1 * b2 - b1 * a2) rps = -(b1 * p2 - p1 * b2) / (a1 * b2 - b1 * a2) return rpp + rps
def test_roots_complex(): """Test if roots are correct complex objects""" a = 1 b = 2 c = 3 exact_x1 = -1 + sqrt(-2) # Håndregnet verdi exact_x2 = -1 - sqrt(-2) # Håndregnet verdi x1 = roots(a, b, c)[0] x2 = roots(a, b, c)[1] success = (exact_x1 - x1) + (exact_x2 - x2) < 1e-14 msg = """program values: x1={:.2f}, x2={:.2f}, exact values: x1={:.2f} x2={:.2f}""".format((x1), (x2), (exact_x1), (exact_x2)) assert success, msg
def updata_position(x, y, xc, yc): for i in range(len(x)): dx, dy = x[i] - xc, y[i] - yc r = np.sqrt(dx * dx + dy * dy) coeff = 100 * k1 * np.sqrt(2 * r / self.pi) if y[i] < yc: theta = np.arctan2(-dy, dx) ux = 1. / (u1 - u2) * ( u1 * p2 * SM.sqrt(np.cos(theta) - u2 * np.sin(theta)) - u2 * p1 * SM.sqrt(np.cos(theta) - u1 * np.sin(theta))) uy = 1. / (u1 - u2) * ( u1 * q2 * SM.sqrt(np.cos(theta) - u2 * np.sin(theta)) - u2 * q1 * SM.sqrt(np.cos(theta) - u1 * np.sin(theta))) ux = coeff * ux.real uy = coeff * uy.real if y[i] >= yc: theta = np.arctan2(dy, dx) ux = 1. / (u1 - u2) * ( u1 * p2 * SM.sqrt(np.cos(theta) - u2 * np.sin(theta)) - u2 * p1 * SM.sqrt(np.cos(theta) - u1 * np.sin(theta))) uy = 1. / (u1 - u2) * ( u1 * q2 * SM.sqrt(np.cos(theta) - u2 * np.sin(theta)) - u2 * q1 * SM.sqrt(np.cos(theta) - u1 * np.sin(theta))) ux = coeff * ux.real uy = -coeff * uy.real print(ux) print(uy) x[i] += ux y[i] += uy return (x, y)
def get_gap_statistics(data, refs=None, nrefs=30, ks=range(1, 11)): # calculating distance dst = scipy.spatial.distance.euclidean # defining shape shape = data.shape # checking condition for given refs if refs == None: tops = data.max(axis=0) bots = data.min(axis=0) dists = scipy.matrix(np.diag(tops - bots)) rands = scipy.random.random_sample(size=(shape[0], shape[1], nrefs)) for i in range(nrefs): rands[:, :, i] = rands[:, :, i] * dists + bots else: rands = refs gaps = np.zeros((len(ks), )) errors = np.zeros((len(ks), )) labels = dict((el, []) for el in ks) for (i, k) in enumerate(ks): (kmc, kml) = scipy.cluster.vq.kmeans2(data, k) disp = sum([dst(data[m, :], kmc[kml[m], :]) for m in range(shape[0])]) labels[k] = kml refdisps = np.zeros((rands.shape[2], )) for j in range(rands.shape[2]): (kmc, kml) = scipy.cluster.vq.kmeans2(rands[:, :, j], k) refdisps[j] = sum( [dst(rands[m, :, j], kmc[kml[m], :]) for m in range(shape[0])]) # Computing gaps gaps[i] = scimath.log(np.mean(refdisps)) - scimath.log(disp) # Computing errors errors[i] = scimath.sqrt( sum(((scimath.log(refdisp) - np.mean(scimath.log(refdisps)))**2) for refdisp in refdisps) / float(nrefs)) * scimath.sqrt(1 + 1 / nrefs) xval = range(1, len(gaps) + 1) yval = gaps plt.errorbar(xval, yval, xerr=None, yerr=errors) plt.xlabel('K Clusters') plt.ylabel('Gap_Statistics') plt.title('Gap Statistics for : nref={}'.format(nrefs)) plt.show() return
def __call__(self, coords): r""" evaluate complex eletric field amplitude at coords :param coords: coordinates of points in lab frame :type coords: list of ndarrays, NOTE: the order is [Z, Y, X] :return: complex electric field amplitude at coords :rtype: ndarray of complex with same shape as coords[0] """ zn = np.copy(coords[0]) yn = np.copy(coords[1]) xn = np.copy(coords[2]) # Coordinate transform into beam frame # step 1, move to beam frame origin xn = xn-self.waist_loc[2] yn = yn-self.waist_loc[1] zn = zn-self.waist_loc[0] # step 2, rotate along y' axis xn, yn, zn = rotate('y', self.tilt_h, [xn, yn, zn]) # step 3, rotate along z' axis xn, yn, zn = rotate('z', -self.tilt_v, [xn, yn, zn]) # step 4, rotate along x' axis xn, yn, zn = rotate('x', -self.rotation, [xn, yn, zn]) # step 5, coordinate substitution z = -xn y = yn x = zn # now, we can evaluate electric field zry, zrx = self.reighlay_range k = 2*np.pi/self.wave_length qx = z - 1j*zrx qy = z - 1j*zry ux = 1/sqrt(qx)*np.exp(1j*k*x*x/(2*qx)) uy = 1/sqrt(qy)*np.exp(1j*k*y*y/(2*qy)) return self.E0*ux*uy*np.exp(1j*k*z)*np.sqrt(zry*zrx)
def readSamples(self, fileName, key,recalc=False,samples=None): fn = fileName + ".pre" try: if recalc: raise IOError() with open(fn): pass print "precalculated file present" self.mu, self.cov = hsplit(mat(fromfile(fn).reshape((3,-1))),[1]) except IOError: if samples != None: self._samples = samples print "got samples: " , self._samples else: print "no file present, calculating..." smpls = loadmat(fileName)[key] print "loaded from mat file" self._samples = mat(smpls) print "reshaped into samples" self.mu = sum(self._samples, axis=1) / self._samples.shape[1] print "mu=", str(self.mu) sampdiffmu = self._samples - self.mu self.cov = sampdiffmu*sampdiffmu.T / self._samples.shape[1] print"cov=", str(self.cov) mat(hstack((self.mu,self.cov))).tofile(fn) self._invCov = self.cov.I self._detCov = det(self.cov) self._multConst = 1 / sqrt((2 * pi) ** 3 * self._detCov)
def R_F(x, y, z, rtol=3e-4): r"""Computes the symmetric integral of the first kind .. math:: R_F(x, y, z) = \frac{1}{2}\int_0^\infty [(t + x)(t + y)(t + z)]^\frac{1}{2}dt """ # Properly deal with the degenerate case if y == z: return R_C(x, y) A0 = (x + y + z) / 3.0 M = max(abs(A0 - x), abs(A0 - y), abs(A0 - z)) Q = ((3*rtol) ** (-1.0/6.0)) * M A = _A_gen(x, y, z) for n, Am in enumerate(A): if 4**(-n) * Q < abs(Am): X = (A0 - x) / (Am * 4**n) Y = (A0 - y) / (Am * 4**n) Z = -X-Y E2 = X * Y - Z**2 E3 = X * Y * Z result = (1/scimath.sqrt(Am)) * (1 - E2*(1/10) + E3*(1/14) + (E2**2)*(1/24) - (E2*E3)*(3/44)) return result
def bessel_series(a, b, z, maxiters=500, tol=tol): """Compute hyp1f1 using a series of Bessel functions; see (3.20) in _[pop]. """ Do, Dm, Dn = 1, 0, b/2 r = sqrt(z*(2*b - 4*a)) w = z**2 / r**(b + 1) # Ao is the first coefficient, and An is the second. Ao = 0 # The first summand comes from the zeroth term. So = Do*jv(b - 1, r) / r**(b - 1) + Ao An = Dn*w*jv(b + 1, r) Sn = So + An i = 3 while i <= maxiters: if np.abs(Ao/So) < tol and np.abs(An/Sn) < tol: break tmp = Dn Dn = ((i - 2 + b)*Dm + (2*a - b)*Do) / i Do = Dm Dm = tmp w *= z/r Ao = An An = Dn*w*jv(b - 1 + i, r) So = Sn Sn += An i += 1 # if i > maxiters: # warnings.warn("Number of evaluations exceeded maxiters on " # "a = {}, b = {}, z = {}.".format(a, b, z)) return gamma(b)*np.exp(z/2)*2**(b - 1)*Sn
def montar_quadrados(tam_quadrados=[]): qd = [] for i in range(len(tam_quadrados)): qd.append(figuras.Quadrado(tam_quadrados[i], color(i))) if len(qd) < 2: print ("ERRO: A lista de tamanho de quadrados tem que ser maior ou igual a 2.") return ERRO elif len(qd) >= 2: # Criar as imagens de todos os quadrados dados. for quad_i in qd: img, draw = desenhar_quadrado(quad_i) nome_arquivo = salvar_arquivo(quad_i.lado_cm, img) quad_i.nome_arquivo = nome_arquivo x_risco = calcula_x_risco(qd[1], qd[0]) img1 = Image.open(qd[1].nome_arquivo) draw1 = ImageDraw.Draw(img1) riscar_quadrado(qd[1], img1, draw1, x_risco) salvar_arquivo(qd[1].lado_cm, img1, riscado=1) # Novo quadrado montado n_area = qd[0].lado_px * qd[1].lado_px n_lado = int(sqrt(n_area)) # x_risco = calcula_x_risco(qd[1],qd[0]) # riscar_quadrado(qd[1],img1,draw1,x_risco) # salvar_arquivo(qd[1].lado_cm, img1,riscado=1) # return qd
def init(): width = 640 height = 640 glfw.Init() glfw.OpenWindow(width, height, 8, 8, 8, 0, 24, 0, glfw.WINDOW) glfw.SetWindowTitle("glfw line") glfw.SetWindowSizeCallback(Reshape) glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL); glfw.SetMouseButtonCallback(MouseHandler) glfw.SetKeyCallback(KeyboardHandler) glfw.SetWindowCloseCallback(WindowCLose) global heightmap, terrain_size tmpheightmap = open("heightmap.raw", 'rb').read() for c in tmpheightmap: heightmap.append(ord(c)) print heightmap terrain_size = int(sqrt(len(heightmap))) print terrain_size if(glFogCoordfEXT): # test print 'ok'
def normalizeData(data, meanOnly = False): """ normalize data by subtracting mean and dividing by sd per COLUMN @param data: an array @param meanOnly: if True subtract mean only; otherwise divide by sd too @return: (an array with the same dimension as data, mean, stds, the transformer) """ # compute the new data m = mean(data, axis=0) res = data - m if meanOnly: stds = 1 else: stds = sqrt(var(data, axis=0)) stds[stds==0] = 1 # to avoid dividing by 0 res /= stds # figure out the transformer def foo(givenData): assert givenData.shape[1]==data.shape[1], "Only arrays of %d columns are handled." % data.shape[1] return (givenData - m)/stds return res, m, stds, foo
def fresnel_coefficients(n1, n2, theta): cos_out = scimath.sqrt(1-(n1/n2*np.sin(theta)**2)) cos_in = np.cos(theta) rs = (n1*cos_in - n2*cos_out)/(n1*cos_in + n2*cos_out) rp = (n1*cos_out - n2*cos_in )/(n1*cos_out + n2*cos_in ) ts = (2*n1*cos_in)/(n1*cos_in + n2*cos_out) tp = (2*n1*cos_in)/(n1*cos_out + n2*cos_in ) return rs, rp, ts, tp
def generate_hamiltonian(n,m,n0,q,c): n_states = int((n-m)/2) ham = np.zeros((n_states,n_states),dtype = complex) for i in range(n_states): n0 = (n-m-2*i) #first for diagonal ham[i,i] = c/2*(m**2 + n + n0 + 2*n*n0-2*n0**2)+q*(n-n0) #now for off diagonal- use try statements to catch edge case try: ham[i,i+1] = c/2*scimath.sqrt(n0*(n0-1)*(n+m-n0+2)*(n-m-n0+2)) except: pass try: ham[i,i-1] = c/2*scimath.sqrt((n0+1)*(n0+2)*(n+m-n0)*(n-m-n0)) except: pass return ham
def sigma(self, r): """Compute the surface mass density of the halo at distance r (in Mpc) from the halo center.""" r = unit_checker(r, u.Mpc) x = r / self.r_s val1 = 1 / (x**2 - 1) val2 = (arcsec(x) / (sm.sqrt(x**2 - 1))**3).real return 2 * self.r_s * self.rho_c * self.delta_c * (val1-val2)
def rmsd(p1, p2): if len(p1) != len(p2): raise Exception("Degree of points must be the same") total = 0 for t in range(len(p1)): d = (p1[t] - p2[t]) total += d * d return sqrt(total / len(p1)) #todo remove sqrt?
def calcKappa(self): array=np.zeros(self.iP.number, dtype=np.complex128) for index,r in enumerate(self.dC.radialCells.rValues): array[index]=np.complex128( 4*self.Omega[index]**2 +2*r*self.Omega[index]*self.DOmega[index] ) return sqrt(array)
def simplify( self ): devisors = self.get_possible_divisors() for devisor in reversed( devisors ): if self.number % devisor == 0: self.number /= devisor self.multiplier *= sqrt( devisor ) if self.order == 2 else pow( devisor, 1.0 / self.order ) break
def NormalDisStarEndStanDiviation(self): average = self.calculateAverage() standardDiviation = float() for number in self._listOfNumber: standardDiviation += (average - number) **2 standardDiviation = standardDiviation/len(self._listOfNumber) # print('average '+str(average)) # print ('variance '+ str(standardDiviation)) standardDiviation = sqrt(standardDiviation) return [standardDiviation,average-3*standardDiviation,average+3*standardDiviation]
def GetTaoFromQ(self,el): ''' Computing wall shear stress in terms of the flow rate, using inverse womersley method of Cezeaux et al.1997 ''' self.radius = mean(el.Radius) self.Res = el.R self.length = el.Length self.Name = el.Name #WOMERSLEY NUMBER self.alpha = self.radius * sqrt((2.0 *pi*self.density)/(self.tPeriod*self.viscosity)) #FOURIER SIGNAL k = len(self.signal) n = 0 while n < (self.nHarmonics): An = 0 Bn = 0 for i in arange(k): An += self.signal[i] * cos(n*(2.0*pi/self.tPeriod)*self.dt*self.nSteps[i]) Bn += self.signal[i] * sin(n*(2.0*pi/self.tPeriod)*self.dt*self.nSteps[i]) An = An * (2.0/k) Bn = Bn * (2.0/k) self.fourierModes.append(complex(An, Bn)) n+=1 self.Steps = linspace(0,self.tPeriod,self.samples) self.WssSignal = [] self.Tauplot = [] for step in self.Steps: self.tao = -self.fourierModes[0].real * 2.0 k=1 while k < self.nHarmonics: cI = complex(0.,1.) cA = (self.alpha * pow((1.0*k),0.5)) * pow(cI,1.5) c1 = 2.0 * jn(1, cA) c0 = cA * jn(0, cA) cT = complex(0, -2.0*pi*k*self.t/self.tPeriod) '''tao computation''' taoNum = self.alpha**2*cI**3*jn(1,cA) taoDen = c0-c1 taoFract = taoNum/taoDen cTao = self.fourierModes[k] * exp(cT) * taoFract self.tao += cTao.real k+=1 self.tao *= -(self.viscosity/(self.radius**3*pi)) self.Tauplot.append(self.tao*10) #dynes/cm2 self.WssSignal.append(self.tao) self.t += self.dtPlot return self.WssSignal #Pascal
def generate_states(N1,N0,Nm1,theta,s): """generate quasi probability distribution""" N = N1 + N0 + Nm1 r0 = N0/N r1 = N1/N rm1 = Nm1/N #need to divide by N a = np.sqrt(2*r0*r1) b = np.sqrt(2*r0*rm1) sx_mean = np.cos(theta/2)*(a+b) sy_mean = np.sin(theta/2)*(b-a) nyz_mean = -np.sin(theta/2)*(a+b) nxz_mean = np.cos(theta/2)*(a-b) var_one = N*np.sqrt(r0**2-2*r0*np.sqrt(r1)*np.sqrt(rm1)*np.cos(theta)-r0*r1-r0*rm1+r1**(3/2)*np.sqrt(rm1)*np.cos(theta)+np.sqrt(r1)*rm1**(3/2)*np.cos(theta)+0.25*r1**2+0.5*r1*rm1*np.cos(2*theta) + r1*rm1 + 0.25*rm1**2) var_two = N*np.sqrt(r0**2+2*r0*np.sqrt(r1)*np.sqrt(rm1)*np.cos(theta)-r0*r1-r0*rm1-r1**(3/2)*np.sqrt(rm1)*np.cos(theta)-np.sqrt(r1)*rm1**(3/2)*np.cos(theta)+0.25*r1**2+0.5*r1*rm1*np.cos(2*theta) + r1*rm1 + 0.25*rm1**2) sx = np.random.normal(loc = sx_mean, scale = 1/np.sqrt(var_one), size = s) sy = np.random.normal(loc = sy_mean, scale = 1/np.sqrt(var_two), size =s) nyz = np.random.normal(loc = nyz_mean, scale = 1/np.sqrt(var_one), size = s) nxz = np.random.normal(loc = nxz_mean, scale = 1/np.sqrt(var_two), size = s) txip = np.where((sx+nxz)>0,np.arctan(-(sy + nyz)/(sx+ nxz)),np.arctan(-(sy + nyz)/(sx+ nxz))+np.pi) txim = np.where((sx-nxz)>0,np.arctan((sy-nyz)/(sx-nxz)),np.arctan((sy-nyz)/(sx-nxz))+np.pi) a = (sx+nxz)**2/(np.cos(txip))**2 b = (sx-nxz)**2/(np.cos(txim))**2 rho_0 = 1/2 + scimath.sqrt(1/4-(a+b)/8) m = 1/rho_0*(a-b)/8 states = np.zeros((len(m),3),dtype = complex) states[:,0] = scimath.sqrt((1-rho_0+m)/2) * np.exp(txip*1j) states[:,1] = scimath.sqrt(rho_0) states[:,2] = scimath.sqrt((1-rho_0-m)/2) * np.exp(txim*1j) return states
def delta_sigma(self, r): """Compute the Delta surface mass density of the halo at radius r (in Mpc) from the halo center.""" r = unit_checker(r, u.Mpc) x = r / self.r_s fac = 2 * self.r_s * self.rho_c * self.delta_c val1 = 1 / (1 - x**2) num = ((3 * x**2) - 2) * arcsec(x) div = x**2 * (sm.sqrt(x**2 - 1))**3 val2 = (num / div).real val3 = 2 * np.log(x / 2) / x**2 return fac * (val1+val2+val3)
def _lambda_m(x, y, z): r""" .. math:: \lambda_m = \sqrt{x_m}\sqrt{y_m} + \sqrt{x_m}\sqrt{y_m} + \sqrt{y_m}\sqrt{z_m} Note that :math:\sqrt{x_m}\sqrt{y_m} is chosen instead of :math:\sqrt{x_m y_m} to avoid problems due to the branch cut """ a, b, c = scimath.sqrt([x, y, z]) lm = a*b + a*c + b*c return lm
def asDims(self, v, i): result = [] dim = 0 cares = [] for c in range(self.numClusters): clusterMean = self.clusterMeans[c][self.clusters[i][c]] for m in clusterMean: acare = self.clusterCaring[c][self.clusters[i][c]] result.append(m + (v[dim] * sqrt(1-acare))) cares.append(acare) dim += 1 v = PersonalityVoter(result) #TODO: do personality right v.cares = cares return v
def fromDims(cls, v, e, caring = None): if caring==None: caring = [1] * len(v) totCaring = e.totWeight else: totCaring = sum((c*w)**2 for c,w in zip(caring, e.dimWeights)) me = cls(-sqrt( sum(((vd - cd)*w*cares)**2 for (vd, cd, w, cares) in zip(v,c,e.dimWeights,caring)) / totCaring) for c in e.cands) me.copyAttrsFrom(v) me.dims = v me.elec = e return me
def roots(a, b, c): """Find the roots and solution to the equation on the form ax² + bx + c = 0 The solution is the equation: √(b² - 4ac) x = -b ± ----------- 2a """ root_part = npsci.sqrt(b**2 - 4*a*c) x1 = (-b + root_part)/(2*a) x2 = (-b - root_part)/(2*a) return (x1, x2)