def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at (R,z) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: potential at (R,z) HISTORY: 2012-12-26 - Written - Bovy (IAS) """ if self._new: #if R > 6.: return self._kp(R,z) if nu.fabs(z) < 10.**-6.: y= 0.5*self._alpha*R return -nu.pi*R*(special.i0(y)*special.k1(y)-special.i1(y)*special.k0(y)) kalphamax= 10. ks= kalphamax*0.5*(self._glx+1.) weights= kalphamax*self._glw sqrtp= nu.sqrt(z**2.+(ks+R)**2.) sqrtm= nu.sqrt(z**2.+(ks-R)**2.) evalInt= nu.arcsin(2.*ks/(sqrtp+sqrtm))*ks*special.k0(self._alpha*ks) return -2.*self._alpha*nu.sum(weights*evalInt) raise NotImplementedError("Not new=True not implemented for RazorThinExponentialDiskPotential")
def _evaluate(self, R, z, phi=0., t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at (R,z) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: potential at (R,z) HISTORY: 2012-12-26 - Written - Bovy (IAS) """ if self._new: #if R > 6.: return self._kp(R,z) if nu.fabs(z) < 10.**-6.: y = 0.5 * self._alpha * R return -nu.pi * R * (special.i0(y) * special.k1(y) - special.i1(y) * special.k0(y)) kalphamax = 10. ks = kalphamax * 0.5 * (self._glx + 1.) weights = kalphamax * self._glw sqrtp = nu.sqrt(z**2. + (ks + R)**2.) sqrtm = nu.sqrt(z**2. + (ks - R)**2.) evalInt = nu.arcsin(2. * ks / (sqrtp + sqrtm)) * ks * special.k0( self._alpha * ks) return -2. * self._alpha * nu.sum(weights * evalInt) raise NotImplementedError( "Not new=True not implemented for RazorThinExponentialDiskPotential" )
def c2(z, dp): term_1 = k0(k * r1) - i0( k * r1) * (k0(k * r1) - k0(k * r2(z))) / (i0(k * r1) - i0(k * r2(z))) term_1 = pow(term_1, -1) term_2 = (dp * (1 + pow(m, 2)) / M) - (i0(k * r1) / (i0(k * r1) - i0(k * r2(z)))) + 1 return term_1 * term_2
def tetmConstants(self, ri, ro, neff, wl, EH, c, idx): a = numpy.empty((2, 2)) n = self.maxIndex(wl) u = self.u(ro, neff, wl) urp = self.u(ri, neff, wl) if neff < n: B1 = j0(u) B2 = y0(u) F1 = j0(urp) / B1 F2 = y0(urp) / B2 F3 = -j1(urp) / B1 F4 = -y1(urp) / B2 c1 = wl.k0 * ro / u else: B1 = i0(u) B2 = k0(u) F1 = i0(urp) / B1 F2 = k0(urp) / B2 F3 = i1(urp) / B1 F4 = -k1(urp) / B2 c1 = -wl.k0 * ro / u c3 = c * c1 a[0, 0] = F1 a[0, 1] = F2 a[1, 0] = F3 * c3 a[1, 1] = F4 * c3 return numpy.linalg.solve(a, EH.take(idx))
def PotDisk(n, r): "n: order of differentiation" rratio = 0.5 * r / r0 if n == 1: dPhidr_disk = (G * Md * r / (2. * r0 * r0 * r0)) * (i0(rratio) * k0(rratio) - i1(rratio) * k1(rratio)) return dPhidr_disk elif n == 2: d2Phidr2_disk = (G * Md / (4. * r0 * r0 * r0)) * ( -rratio * iv(2, rratio) * k1(rratio) + i0(rratio) * (2 * k0(rratio) - 3. * rratio * k1(rratio)) + i1(rratio) * (3. * rratio * k0(rratio) - 2. * k1(rratio) + rratio * kn(2, rratio))) return d2Phidr2_disk elif n == 'v': dPhidr_disk = (G * Md * r / (2. * r0 * r0 * r0)) * (i0(rratio) * k0(rratio) - i1(rratio) * k1(rratio)) Vc = np.sqrt(r * dPhidr_disk) return Vc else: Phi_disk = (-G * Md * r / (2. * r0 * r0)) * (i0(rratio) * k1(rratio) - i1(rratio) * k0(rratio)) return Phi_disk
def T6fun(i, x): betah = (locs['a'])[i] * (locs['k'])[i] * locs['alpha'][i] betam = par['am'] * par['km'] * par['alpha_m'] a = numpy.zeros([2, 2]) a[0, 0] = i0(locs['alpha'][i] * locs['rad'][i]) a[1, 0] = betah * i1(locs['alpha'][i] * locs['rad'][i]) a[0, 1] = -k0(par['alpha_m'] * locs['rad'][i]) a[1, 1] = betam * k1(par['alpha_m'] * locs['rad'][i]) ## b is markedly different in zheng2009 and confirm.nb ## this is now the confirm.nb version b = numpy.zeros([2, 1]) b[0] = (1.0 / par['cm']) - (locs['rad'][i] * k0(locs['alpha'][i] * locs['rad'][i]) * i1(locs['alpha'][i] * locs['rad'][i]) / ((locs['a'])[i] * locs['alpha'][i])) b[1] = ((locs['k'])[i] * locs['rad'][i] * k1(locs['alpha'][i] * locs['rad'][i]) * i1(locs['alpha'][i] * locs['rad'][i])) const = (inv(a)).dot(b) qh = ((1.0 / (locs['c'])[i]) * (1.0 - locs['alpha'][i] * locs['rad'][i] * i0(locs['alpha'][i] * x) * k1(locs['alpha'][i] * locs['rad'][i]))) if (x < locs['rad'][i]): return const[0] * i0(locs['alpha'][i] * x) + qh else: return const[1] * k0(par['alpha_m'] * x) + (1.0 / par['cm'])
def B2B1(s, H_g, kappa, r_Db): numerator = kappa * math.sqrt(H_g * s / kappa) * sp.i1(r_Db * math.sqrt( H_g * s / kappa)) * sp.k0(r_Db * math.sqrt(s)) + math.sqrt(s) * sp.i0( r_Db * math.sqrt(H_g * s / kappa)) * sp.k1(r_Db * math.sqrt(s)) denominator = kappa * math.sqrt(H_g * s / kappa) * sp.k1(r_Db * math.sqrt( H_g * s / kappa)) * sp.k0(r_Db * math.sqrt(s)) - math.sqrt(s) * sp.k0( r_Db * math.sqrt(H_g * s / kappa)) * sp.k1(r_Db * math.sqrt(s)) rt = numerator / denominator return rt
def func_int_potencial(k, r, z, zd, r_cond = 65e-3 /2, r_malla = 113.9e-3 /2): #r_cond radio del anillo conductor en metros. #r_malla radio de la malla conductora externa en metros. f = special.i0(k*r_cond) * np.cos(k*(z-zd)) * (special.k0(k*r) - special.i0(k *r)*special.k0(k*r_malla)/special.i0(k*r_malla)) return f
def test_nu0_f_x_on_x2(): """ Test f(x) = x/(x**2 + 1), nu=0 This test is done in the Ogata (2005) paper, section 5" """ ht = HankelTransform(nu=0, N=50, h=10 ** -1.5) ans = ht.integrate(lambda x: x / (x ** 2 + 1), False, False) print("Numerical Result: ", ans, " (required %s)" % k0(1)) assert np.isclose(ans, k0(1), rtol=1e-3)
def test_nu0_f_x_on_x2(): """ Test f(x) = x/(x**2 + 1), nu=0 This test is done in the Ogata (2005) paper, section 5" """ ht = HankelTransform(nu=0, N=50, h=10**-1.5) ans = ht.integrate(lambda x: x / (x**2 + 1), False, False) print("Numerical Result: ", ans, " (required %s)" % k0(1)) assert np.isclose(ans, k0(1), rtol=1e-3)
def Gamma(nw_rad, lay_ox, L_d, L_tf, eps_1, eps_2, eps_3): fact1 = (nw_rad + lay_ox) / L_d fact2 = nw_rad / L_tf fact3 = fact1**(-1) fact4 = (nw_rad + lay_ox) / nw_rad num = eps_1 * k0(fact1) * (L_d / L_tf) * i1(fact2) denom1 = k0(fact1) * fact3 denom2 = log(fact4) * k1(fact1) * (eps_3 / eps_2) denom3 = (denom1 + denom2) * eps_1 * fact2 * i1(fact2) denom = denom3 + eps_3 * k1(fact1) * i0(fact2) gamma = num / denom return gamma
def Gamma(nw_rad, lay_ox, L_d, L_tf, eps_1, eps_2, eps_3): fact1 = (nw_rad + lay_ox)/L_d fact2 = nw_rad/L_tf fact3 = fact1**(-1) fact4 = (nw_rad + lay_ox)/nw_rad num = eps_1*k0(fact1)*(L_d/L_tf)*i1(fact2) denom1 = k0(fact1)*fact3 denom2 = log(fact4)*k1(fact1)*(eps_3/eps_2) denom3 = (denom1 + denom2)*eps_1*fact2*i1(fact2) denom = denom3 + eps_3*k1(fact1)*i0(fact2) gamma = num/denom return gamma
def _tecoeq(self, v0, nu): u1r1, u2r1, u2r2, s1, s2, n1sq, n2sq, n3sq = self.__params(v0) (f11a, f11b) = ((j0(u1r1), jn(2, u1r1)) if s1 > 0 else (i0(u1r1), -iv(2, u1r1))) if s2 > 0: f22a, f22b = j0(u2r2), y0(u2r2) f2a = jn(2, u2r1) * f22b - yn(2, u2r1) * f22a f2b = j0(u2r1) * f22b - y0(u2r1) * f22a else: # a f22a, f22b = i0(u2r2), k0(u2r2) f2a = kn(2, u2r1) * f22a - iv(2, u2r1) * f22b f2b = i0(u2r1) * f22b - k0(u2r1) * f22a return f11a * f2a - f11b * f2b
def _Rforce(self, R, z, phi=0., t=0.): """ NAME: Rforce PURPOSE: evaluate radial force K_R (R,z) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: K_R (R,z) HISTORY: 2012-12-27 - Written - Bovy (IAS) """ if self._new: #if R > 6.: return self._kp(R,z) if nu.fabs(z) < 10.**-6.: y = 0.5 * self._alpha * R return -2. * nu.pi * y * (special.i0(y) * special.k0(y) - special.i1(y) * special.k1(y)) kalphamax1 = R ks1 = kalphamax1 * 0.5 * (self._glx + 1.) weights1 = kalphamax1 * self._glw sqrtp = nu.sqrt(z**2. + (ks1 + R)**2.) sqrtm = nu.sqrt(z**2. + (ks1 - R)**2.) evalInt1 = ks1**2. * special.k0(ks1 * self._alpha) * ( (ks1 + R) / sqrtp - (ks1 - R) / sqrtm) / nu.sqrt(R**2. + z**2. - ks1**2. + sqrtp * sqrtm) / (sqrtp + sqrtm) if R < 10.: kalphamax2 = 10. ks2 = (kalphamax2 - kalphamax1) * 0.5 * (self._glx + 1.) + kalphamax1 weights2 = (kalphamax2 - kalphamax1) * self._glw sqrtp = nu.sqrt(z**2. + (ks2 + R)**2.) sqrtm = nu.sqrt(z**2. + (ks2 - R)**2.) evalInt2 = ks2**2. * special.k0(ks2 * self._alpha) * ( (ks2 + R) / sqrtp - (ks2 - R) / sqrtm) / nu.sqrt(R**2. + z**2. - ks2**2. + sqrtp * sqrtm) / (sqrtp + sqrtm) return -2. * nu.sqrt(2.) * self._alpha * nu.sum( weights1 * evalInt1 + weights2 * evalInt2) else: return -2. * nu.sqrt(2.) * self._alpha * nu.sum( weights1 * evalInt1) raise NotImplementedError( "Not new=True not implemented for RazorThinExponentialDiskPotential" )
def func (a,b,c): if b > 18.5: if not np.isinf(b): print("warning : approximating b={:.3f} by b=inf".format(b)) return ss.k0(a*c) / ss.k0(c) - 1 else: # regularization of fD, not needed : # # fDreg = lambda z, b,c: z * np.exp(-z**2/2) * ( ss.k0(c/b*z) * ss.i0(b*z) + np.log(z) ) # # d = -(a*b)**2/2 # # np.exp(-b**2/2) * sint.quad(fD, a*b, np.inf, args=(b,c))[0] - np.exp(d)*np.log(a*b) + ss.expi(d)/2 fDg = lambda z, b,c: z * np.exp(-b**2/2-z**2/2) * (ss.k0(c/b*z)/ss.k0(a*c)-1) * ss.i0(b*z) Dg, Dgerr = sint.quad(fDg, a*b, max(10,2*b), args=(b,c), epsrel=1e-8) # todo error checks return 1/( 1 + Dg ) - 1
def potinf(self, x, y, aq=None): if aq is None: aq = self.model.aq.find_aquifer_data(x, y) rv = np.zeros((self.nparam, aq.naq)) if aq == self.aq: pot = np.zeros(aq.naq) r = np.sqrt((x - self.xw)**2 + (y - self.yw)**2) if r < self.rw: r = self.rw # If at well, set to at radius if aq.ilap: pot[0] = np.log(r / self.rw) / (2 * np.pi) pot[1:] = -k0(r / aq.lab[1:]) / (2 * np.pi) else: pot[:] = -k0(r / aq.lab) / (2 * np.pi) rv[:] = self.aq.coef[self.layers] * pot return rv
def potinf(self, x, y, aq=None): if aq is None: aq = self.model.aq.find_aquifer_data(x, y) rv = np.zeros((self.nparam, aq.naq)) if aq == self.aq: pot = np.zeros(aq.naq) r = np.sqrt((x - self.xw) ** 2 + (y - self.yw) ** 2) if r < self.rw: r = self.rw # If at well, set to at radius if aq.ilap: pot[0] = np.log(r / self.rw) / (2 * np.pi) pot[1:] = -k0(r / aq.lab[1:]) / (2 * np.pi) else: pot[:] = -k0(r / aq.lab) / (2 * np.pi) rv[:] = self.aq.coef[self.layers] * pot return rv
def _lpfield(self, wl, nu, neff, r): rho = self.fiber.outerRadius(0) k = wl.k0 nco2 = self.fiber.maxIndex(0, wl)**2 ncl2 = self.fiber.minIndex(1, wl)**2 u = rho * k * sqrt(nco2 - neff**2) w = rho * k * sqrt(neff**2 - ncl2) if r < rho: ex = j0(u * r / rho) / j0(u) else: ex = k0(w * r / rho) / k0(w) hy = neff * Y0 * ex # Snyder & Love uses nco, but Bures uses neff return numpy.array((ex, 0, 0)), numpy.array((0, hy, 0))
def main(): import omega as om from pwkit.ndshow_gtk3 import cycle, view ###xg, yg, grid1 = calculate_dynat(n_pseudo_particles=2048, n_steps=30000) ###xg, yg, grid1 = calculate_fixed(n_pseudo_particles=16384, delta_t=0.00001) ###xg, yg, grid1 = calculate_debug(n_pseudo_particles=4096, n_steps=10000, delta_t=0.00001) ###_, _, grid2 = calculate(delta_t=0.00005) y_bins = 40 y_edges = np.linspace(YMIN, YMAX, y_bins + 1) y_centers = 0.5 * (y_edges[1:] + y_edges[:-1]) yg = y_centers.reshape((-1, 1)) x_bins = 40 x_edges = np.linspace(XMIN, XMAX, x_bins + 1) x_centers = 0.5 * (x_edges[1:] + x_edges[:-1]) xg = x_centers.reshape((1, -1)) rho = np.sqrt(np.log(xg / x0)**2 + np.log(yg / y0)**2) / u0 exact = ((xg * y0 / (x0 * yg))**(1. / (2 * u0 * D0)) * k0(rho * np.sqrt(1 + D0**2 * u0**2) / (np.sqrt(2) * D0)) / (2 * np.pi * D0 * u0**2 * np.sqrt(xg * yg * x0 * y0))) ###grid1 *= np.percentile(exact, 95) / np.percentile(grid1, 95) ###cycle([exact[::-1], grid1[::-1]], yflip=True) view(exact[::-1], yflip=True) p = om.RectPlot() p.addXY(xg, exact[10], 'exact') ###p.addXY(xg, grid1[10], 'mine') p.show()
def hd(g, b, s, p): if isiterable(p): return np.array([hd(g, b, s, pi) for pi in p]) # logic for number of terms - from WTAQ2 NTMS = 30 N = np.max([4, int(NTMS * 2**((-np.log10(b) - 2.)))]) out = 0. en0 = None for n in range(N): # find root rhs = p / (s * b + p / g) f2 = partial(f_mn, rhs) f2 = partial(f_mn, p / (s * b)) if en0 is None: if rhs < 1: en0 = np.sqrt(rhs) else: en0 = np.arctan(rhs) else: en0 = en + np.pi en = root(f2, [ en0, ]).x[0] xn = np.sqrt(b * en**2 + p) xn = np.min([708., xn]) # compute correction outi = 2 * k0(xn) * np.sin(en)**2 / ( p * en * (0.5 * en + 0.25 * np.sin(2 * en))) out += outi return out
def phi(k): # use log10 transform to enforce positivity k = 10**k A = r[:, None] * k0(r[:, None] * k) v_i = A @ np.linalg.solve(A.T @ A, A.T @ e) dv = (e - v_i) / len(r) return np.linalg.norm(dv)
def forward(ctx, input): ctx.save_for_backward(input) dev = input.device with torch.no_grad(): x = special.k0(input.detach().cpu()).to(dev) input.to(dev) return x
def logk0(x): """Logarithm of modified bessel function of the second kind of order 0. Infinite values may still be returned if argument is too close to zero.""" y = k0(x) # if array try: xs = x.shape logy = np.zeros(x.shape, dtype=float) # attempt to calculate bessel function for all elements in x logy[y != 0] = np.log(y[y != 0]) # for zero-valued elements use approximation logy[y == 0] = -x[y == 0] - np.log(x[y == 0]) + np.log(np.sqrt(np.pi / 2)) return logy except: if y == 0: return -x - np.log(x) + np.log(np.sqrt(np.pi / 2)) else: return np.log(y)
def Vd(R, Rd, sigma_0): y = R / (2 * Rd) return np.sqrt( 4 * np.pi * G * sigma_0 * Rd * y**2 * [special.i0(y) * special.k0(y) - special.i1(y) * special.k1(y)][0])
def log_k0(x): """Logarithm of modified bessel function of the second kind of order 0. Infinite values may still be returned if argument is too close to zero.""" y = k0(x) # if array try: logy = np.zeros(x.shape, dtype=float) # attempt to calculate bessel function for all elements in x logy[y != 0] = np.log(y[y != 0]) # for zero-valued elements use approximation logy[y == 0] = -x[y == 0] - np.log(x[y == 0]) + np.log( np.sqrt(np.pi / 2)) return logy except: if y == 0: return -x - np.log(x) + np.log(np.sqrt(np.pi / 2)) else: return np.log(y)
def limit(temp, freq, tc, d=0, bcs=BCS): """ Calculate the approximate complex conductivity to normal conductivity ratio in the limit hf << ∆ and kB T << ∆ given some temperature, frequency and transition temperature. Parameters ---------- temp : float, iterable of size N Temperature in units of Kelvin. freq : float, iterable of size N Frequency in units of Hz. tc: float The transition temperature in units of Kelvin. d: float (optional) Ratio of the imaginary gap to the real gap energy at zero temperature. bcs: float (optional) BCS constant that relates the gap to the transition temperature. ∆ = bcs * kB * Tc. The default is superconductivity.utils.BCS. Returns ------- sigma : numpy.ndarray, dtype=numpy.complex128 The complex conductivity at temp and freq. Notes ----- Extension of Mattis-Bardeen theory to a complex gap parameter covered in Noguchi T. et al. Physics Proc., 36, 2012. Noguchi T. et al. IEEE Trans. Appl. SuperCon., 28, 4, 2018. The real part of the gap is assumed to follow the BCS temperature dependence expanded at low temperatures. See equation 2.53 in Gao J. 2008. CalTech. PhD dissertation. No temperature dependence is assumed for the complex portion of the gap parameter. """ # coerce inputs into numpy array temp, freq = coerce_arrays(temp, freq) assert (temp >= 0).all(), "Temperature must be >= 0." # break up gap into real and imaginary parts delta1 = delta_bcs(0, tc, bcs=bcs) delta2 = d * delta1 # allocate memory for complex conductivity sigma1 = np.zeros(freq.size) sigma2 = np.zeros(freq.size) # separate out zero temperature zero = (temp == 0) not_zero = (temp != 0) freq0 = freq[zero] freq1 = freq[not_zero] temp1 = temp[not_zero] # define some parameters xi = sc.h * freq1 / (2 * sc.k * temp1) eta = delta1 / (sc.k * temp1) # calculate complex conductivity sigma1[zero] = np.pi * delta2 / (sc.h * freq0) sigma2[zero] = np.pi * delta1 / (sc.h * freq0) sigma1[not_zero] = (4 * delta1 / (sc.h * freq1) * np.exp(-eta) * np.sinh(xi) * sp.k0(xi) + np.pi * delta2 / (sc.h * freq1) * (1 + 2 * delta1 / (sc.k * temp1) * np.exp(-eta) * np.exp(-xi) * sp.i0(xi))) sigma2[not_zero] = np.pi * delta1 / (sc.h * freq1) * (1 - np.sqrt(2 * np.pi / eta) * np.exp(-eta) - 2 * np.exp(-eta) * np.exp(-xi) * sp.i0(xi)) return combine_sigma(sigma1, sigma2)
def test_besselk0(self): xs = [0.1, 1.0, 10.0] for x in xs: sp = k0(x) hal = besselk0(x) relerr = abs((sp - hal) / sp) self.assertLessEqual(relerr, 0.05)
def calculate_1D_truncated_coulomb(pd, q_v=None, N_c=None): """ Simple 1D truncation of Coulomb kernel PRB 73, 205119. The periodic direction is determined from k-point grid. """ from scipy.special import j1, k0, j0, k1 qG_Gv = pd.get_reciprocal_vectors(add_q=True) if pd.kd.gamma: if q_v is not None: qG_Gv += q_v else: raise ValueError('Presently, calculations only work with a small q in the normal direction') # The periodic direction is determined from k-point grid Nn_c = np.where(N_c == 1)[0] Np_c = np.where(N_c != 1)[0] if len(Nn_c) != 2: # The k-point grid does not fit with boundary conditions Nn_c = [0, 1] # Choose reduced cell vectors 0, 1 Np_c = [2] # Choose reduced cell vector 2 # The radius is determined from area of non-periodic part of cell Acell_cv = pd.gd.cell_cv[Nn_c, :][:, Nn_c] R = (np.linalg.det(Acell_cv) / np.pi)**0.5 qGnR_G = (qG_Gv[:, Nn_c[0]]**2 + qG_Gv[:, Nn_c[1]]**2)**0.5 * R qGpR_G = abs(qG_Gv[:, Np_c[0]]) * R v_G = 4 * np.pi / (qG_Gv**2).sum(axis=1) v_G *= (1.0 + qGnR_G * j1(qGnR_G) * k0(qGpR_G) - qGpR_G * j0(qGnR_G) * k1(qGpR_G)) return v_G.astype(complex)
def equation_2_20(f, T, Delta_0): xi = equation_2_9(f, T) S_1 = (2 / pi * (2 * Delta_0 / (pi * k * T))**(1/2) * (np.exp(xi) - np.exp(-xi)) / 2 * k0(xi)) return S_1
def exponential_velocity(r, rd, vmax): """ Velocity function for an exponential profile r and rd must be in the same units Parameters ---------- r : array radial positions where the model is to be computed rd : float radius at which the maximum velocity is reached vmax : float Maximum velocity of the model Returns ------- Array with the same shape of r, containing the model velocity curve/map """ # disk scale length rd2 = rd / 2.15 vr = np.zeros(np.shape(r)) # to prevent any problem in the center q = np.where(r != 0) vr[q] = r[q] / rd2 * vmax / 0.88 * np.sqrt( i0(0.5 * r[q] / rd2) * k0(0.5 * r[q] / rd2) - i1(0.5 * r[q] / rd2) * k1(0.5 * r[q] / rd2)) return vr
def gendata(X): l = '%5s%23s%23s%23s%23s%23s%23s%23s%23s\n' % ('x', 'I0', 'I1', 'I2', 'I3', 'K0', 'K1', 'K2', 'K3') for i, x in enumerate(X): l += '%5.2f%23.15e%23.15e%23.15e%23.15e%23.15e%23.15e%23.15e%23.15e\n' % ( x, sp.i0(x), sp.i1(x), sp.iv(2, x), sp.iv( 3, x), sp.k0(x), sp.k1(x), sp.kn(2, x), sp.kn(3, x)) return l
def C0(s, N_s, N_w, H_g, kappa, r_Db): rt = 1.0 - 1.0 / ( 1.0 - kappa * N_s / 2 / N_w * math.sqrt(H_g * s / kappa) * (sp.i1(math.sqrt(H_g * s / kappa)) - B2B1(s, H_g, kappa, r_Db) * sp.k1(math.sqrt(H_g * s / kappa))) / (sp.i0(math.sqrt(H_g * s / kappa)) + B2B1(s, H_g, kappa, r_Db) * sp.k0(math.sqrt(H_g * s / kappa)))) return rt
def get_tmax(self, p, cutoff=None): # approximate formula for tmax if cutoff is None: cutoff = self.cutoff rho = p[1] cS = p[2] k0rho = k0(rho) return lambertw(1 / ((1 - cutoff) * k0rho)).real * cS
def _tmcoeq(self, v0, nu): u1r1, u2r1, u2r2, s1, s2, n1sq, n2sq, n3sq = self.__params(v0) if s1 == 0: # e f11a, f11b = 2, 1 elif s1 > 0: # a, b, d f11a, f11b = j0(u1r1) * u1r1, j1(u1r1) else: # c f11a, f11b = i0(u1r1) * u1r1, i1(u1r1) if s2 > 0: f22a, f22b = j0(u2r2), y0(u2r2) f2a = j1(u2r1) * f22b - y1(u2r1) * f22a f2b = j0(u2r1) * f22b - y0(u2r1) * f22a else: # a f22a, f22b = i0(u2r2), k0(u2r2) f2a = i1(u2r1) * f22b + k1(u2r1) * f22a f2b = i0(u2r1) * f22b - k0(u2r1) * f22a return f11a * n2sq * f2a - f11b * n1sq * f2b * u2r1
def rotation_velocity(pos): rho = (pos[0]**2 + pos[1]**2)**0.5 phi = np.arctan2(pos[1], pos[0]) y = rho/(2*Rd) sigma0 = M_dm / (2*pi*Rd**2) speed = (4*pi*G*sigma0*y**2*(i0(y)*k0(y) - i1(y)*k1(y)) + (G*M_dm*rho)/(rho+a_dm)**2 + (G*M_bulge*rho)/(rho+a_bulge)**2)**0.5 return (-speed*sin(phi), speed*cos(phi), 0)
def get_tmax(self, p, cutoff=None): r = 1.0 if len(p) == 3 else p[3] # approximate formula for tmax if cutoff is None: cutoff = self.cutoff cS = p[1] rho = np.sqrt(4 * r**2 * p[2]) k0rho = k0(rho) return lambertw(1 / ((1 - cutoff) * k0rho)).real * cS
def response_function(x): if x == 0.: return 0. elif x < -max_impulse_length: return 0. elif x > max_impulse_length: return 0. else: return special.k0(abs(x))
def _Rforce(self,R,z,phi=0.,t=0.): """ NAME: Rforce PURPOSE: evaluate radial force K_R (R,z) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: K_R (R,z) HISTORY: 2012-12-27 - Written - Bovy (IAS) """ if self._new: #if R > 6.: return self._kp(R,z) if nu.fabs(z) < 10.**-6.: y= 0.5*self._alpha*R return -2.*nu.pi*y*(special.i0(y)*special.k0(y)-special.i1(y)*special.k1(y)) kalphamax1= R ks1= kalphamax1*0.5*(self._glx+1.) weights1= kalphamax1*self._glw sqrtp= nu.sqrt(z**2.+(ks1+R)**2.) sqrtm= nu.sqrt(z**2.+(ks1-R)**2.) evalInt1= ks1**2.*special.k0(ks1*self._alpha)*((ks1+R)/sqrtp-(ks1-R)/sqrtm)/nu.sqrt(R**2.+z**2.-ks1**2.+sqrtp*sqrtm)/(sqrtp+sqrtm) if R < 10.: kalphamax2= 10. ks2= (kalphamax2-kalphamax1)*0.5*(self._glx+1.)+kalphamax1 weights2= (kalphamax2-kalphamax1)*self._glw sqrtp= nu.sqrt(z**2.+(ks2+R)**2.) sqrtm= nu.sqrt(z**2.+(ks2-R)**2.) evalInt2= ks2**2.*special.k0(ks2*self._alpha)*((ks2+R)/sqrtp-(ks2-R)/sqrtm)/nu.sqrt(R**2.+z**2.-ks2**2.+sqrtp*sqrtm)/(sqrtp+sqrtm) return -2.*nu.sqrt(2.)*self._alpha*nu.sum(weights1*evalInt1 +weights2*evalInt2) else: return -2.*nu.sqrt(2.)*self._alpha*nu.sum(weights1*evalInt1) raise NotImplementedError("Not new=True not implemented for RazorThinExponentialDiskPotential")
def _R2deriv(self,R,z,phi=0.,t=0.): """ NAME: R2deriv PURPOSE: evaluate R2 derivative INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: -d K_R (R,z) d R HISTORY: 2012-12-27 - Written - Bovy (IAS) """ if self._new: if nu.fabs(z) < 10.**-6.: y= 0.5*self._alpha*R return nu.pi*self._alpha*(special.i0(y)*special.k0(y)-special.i1(y)*special.k1(y)) \ +nu.pi/4.*self._alpha**2.*R*(special.i1(y)*(3.*special.k0(y)+special.kn(2,y))-special.k1(y)*(3.*special.i0(y)+special.iv(2,y))) raise AttributeError("'R2deriv' for RazorThinExponentialDisk not implemented for z =/= 0")
def _teceq(self, neff, wl, nu): N = len(self.fiber) EH = numpy.empty(4) ri = 0 for i in range(N-1): ro = self.fiber.outerRadius(i) self.fiber.layers[i].EH_fields(ri, ro, nu, neff, wl, EH, False) ri = ro # Last layer _, Hz, Ep, _ = EH u = self.fiber.layers[-1].u(ri, neff, wl) F4 = k1(u) / k0(u) return Ep + wl.k0 * ri / u * constants.eta0 * Hz * F4
def I1RK0r(self, rin): rv = np.zeros(len(self.lab)) if self.islarge.any(): index = (rin - self.R) / self.labbig < 10 if index.any(): r = rin / self.labbig[index] R = self.R / self.labbig[index] rv[self.islarge * index] = np.sqrt(1 / (4 * r * R)) * np.exp(R - r) * \ (1 - 3 / (8 * R) - 15 / (128 * R ** 2) - 315 / (3072 * R ** 3)) * \ (1 - 1 / (8 * r) + 9 / (128 * r ** 2) - 225 / (3072 * r ** 3)) if ~self.islarge.any(): index = (self.R - rin) / self.labsmall < 10 if index.any(): r = rin / self.labsmall[index] rv[~self.islarge * index] = self.i1Roverlab[index] * k0(r) return rv
def _tmceq(self, neff, wl, nu): N = len(self.fiber) EH = numpy.empty(4) ri = 0 for i in range(N-1): ro = self.fiber.outerRadius(i) self.fiber.layers[i].EH_fields(ri, ro, nu, neff, wl, EH, True) ri = ro # Last layer Ez, _, _, Hp = EH u = self.fiber.layers[-1].u(ri, neff, wl) n = self.fiber.maxIndex(-1, wl) F4 = k1(u) / k0(u) return Hp - wl.k0 * ri / u * constants.Y0 * n * n * Ez * F4
def _tefield(self, wl, nu, neff, r): rho = self.fiber.outerRadius(0) k = wl.k0 nco2 = self.fiber.maxIndex(0, wl)**2 ncl2 = self.fiber.minIndex(1, wl)**2 u = rho * k * sqrt(nco2 - neff**2) w = rho * k * sqrt(neff**2 - ncl2) if r < rho: hz = -Y0 * u / (k * rho) * j0(u * r / rho) / j1(u) ephi = -j1(u * r / rho) / j1(u) else: hz = Y0 * w / (k * rho) * k0(w * r / rho) / k1(w) ephi = -k1(w * r / rho) / k1(w) hr = -neff * Y0 * ephi return numpy.array((0, ephi, 0)), numpy.array((hr, 0, hz))
def _tmfield(self, wl, nu, neff, r): rho = self.fiber.outerRadius(0) k = wl.k0 nco2 = self.fiber.maxIndex(0, wl)**2 ncl2 = self.fiber.minIndex(1, wl)**2 u = rho * k * sqrt(nco2 - neff**2) w = rho * k * sqrt(neff**2 - ncl2) if r < rho: ez = -u / (k * neff * rho) * j0(u * r / rho) / j1(u) er = j1(u * r / rho) / j1(u) hphi = Y0 * nco2 / neff * er else: ez = nco2 / ncl2 * w / (k * neff * rho) * k0(w * r / rho) / k1(w) er = nco2 / ncl2 * k1(w * r / rho) / k1(w) hphi = Y0 * nco2 / ncl2 * k1(w * r / rho) / k1(w) return numpy.array((er, 0, ez)), numpy.array((0, hphi, 0))
def step(self, p, dt=1, cutoff=None): rho = p[1] cS = p[2] k0rho = k0(rho) if isinstance(dt, np.ndarray): t = dt else: self.tmax = max(self.get_tmax(p, cutoff), 10 * dt) t = np.arange(dt, self.tmax, dt) tau = t / cS tau1 = tau[tau < rho / 2] tau2 = tau[tau >= rho / 2] w = (exp1(rho) - k0rho) / (exp1(rho) - exp1(rho / 2)) F = np.zeros_like(tau) F[tau < rho / 2] = w * exp1(rho ** 2 / (4 * tau1)) - (w - 1) * exp1( tau1 + rho ** 2 / (4 * tau1)) F[tau >= rho / 2] = 2 * k0rho - w * exp1(tau2) + (w - 1) * exp1( tau2 + rho ** 2 / (4 * tau2)) return p[0] * F / (2 * k0rho)
def v1D_Coulomb(qG, N_p, N_np, R): """Coulomb Potential in the 1D Periodic Case. Nanotube/Nanowire/Atomic Chain calculation. Cutoff in non-periodic N_np directions. No cutoff in periodic N_p direction. :: v1D = 4 pi/|q+G|^2 * [1 + |G_n|R J_1(|G_n|R) K_0(G_p R) - G_p R J_0(|G_n| R) K_1(G_p R)] """ from scipy.special import j1, k0, j0, k1 G_nR = (qG[:, N_np[0]]**2 + qG[:, N_np[1]]**2)**0.5 * R G_pR = abs(qG[:, N_p[0]]) * R v_q = 1. / (qG**2).sum(axis=1) v_q *= (1. + G_nR * j1(G_nR) * k0(G_pR) - G_pR * j0(G_nR) * k1(G_pR)) return v_q
def d_cross_dist_nonvector(z, dof): ''' Probability density function for cross-wavelet spectrum, assuming both wavelet spectra are chi-squared distributed. From equation (30) in Torrence and Compo, 1998. Parameters ---------- z : float The random variable. dof : int Degrees of freedom of the wavelet (1 for real wavelets, 2 for complex ones). Returns ------- d : float Probability density at z. ''' if z == 0: return 0. else: return (2.**(2 - dof) / special.gamma(dof / 2)**2 * z**(dof - 1) * special.k0(z))
def qi_tlsAndMBT(params, temps, powers, data=None, eps=None, **kwargs): """A model of internal quality factor vs temperature and power, weighted by uncertainties. Parameters ---------- params : ``lmfit.Parameters`` object Parameters must include ``['Fd', 'q0', 'f0', 'alpha', 'delta0']``. temps : ``numpy.Array`` Array of temperature values to evaluate model at. May be 2D. powers : ``numpy.Array`` Array of power values to evaluate model at. May be 2D. data : ``numpy.Array`` Data values to compare to model. May also be ``None``, in which case function returns model. eps : ``numpy.Array`` Uncertianties with which to weight residual. May also be ``None``, in which case residual is unwieghted. Returns ------- residual : ``numpy.Array`` The weighted or unweighted vector of residuals if ``data`` is passed. Otherwise, it returns the model. Note ---- The following constraint must be satisfied:: all(numpy.shape(x) == numpy.shape(data) for x in [temps, powers, eps]) It is almost certain that this model does NOT apply to your device as the assumptions it makes are highly constraining and ignore several material parameters. It is included here more as an example for how to write a model than anything else, and it does at least qualitatively describe the behavior of most superconducting resonators. This model is taken from J. Gao's Caltech dissertation (2008) and the below equations are from that work. (2.54) gives for MBD: ``1/Q(T)-1/Q(0) = alpha * R(T)/X(0)`` (5.72) and (5.65) give for TLS: ``1/Q(T)-1/Q(0) = Fd*tanh(hf/2kT)/sqrt(1+P/P0)`` R(T)/X(0) calculated from (2.80), (2.89), and (2.90), using the ``deltaBCS`` function in this module for returning gap as a function of temperature. """ Fd = params['Fd'].value Pc = params['Pc'].value f0 = params['f0'].value q0 = params['q0'].value delta0 = params['delta0'].value*sc.e alpha = params['alpha'].value units = kwargs.pop('units', 'mK') assert units in ['mK', 'K'], "Units must be 'mK' or 'K'." if units == 'mK': ts = temps*0.001 #Assuming thick film local limit #Other good options are 1 or 1/3 gamma = kwargs.pop('gamma', 0.5) #Calculate tc from BCS relation tc = delta0/(1.76*sc.k) #Get the reduced energy gap deltaR = deltaBCS(ts/tc) #And the energy gap at T deltaT = delta0*deltaR #Pack all these together for convenience zeta = sc.h*f0/(2*sc.k*ts) #An optional power calibration in dB #Without this, the parameter Pc is meaningless pwr_cal_dB = kwargs.pop('pwr_cal_dB', 0) ps = powers+pwr_cal_dB #Working in inverse Q since they add and subtract nicely #Calculate the inverse Q from TLS invQtls = Fd*np.tanh(zeta)/np.sqrt(1.0+10**(ps/10.0)/Pc) #Calculte the inverse Q from MBD invQmbd = alpha*gamma*4*deltaR*np.exp(-deltaT/(sc.k*ts))*np.sinh(zeta)*k0(zeta) #Get the difference from the total Q and model = 1.0/(invQtls + invQmbd + 1.0/q0) #Weight the residual if eps is supplied if data is not None: if eps is not None: residual = (model-data)/eps else: residual = (model-data) return residual else: return model
def gdisk(r): y = r / (2 * RD) return 4 * pi * G * Sigma0 * (RD / r) * (y ** 2) * (sp.i0(y) * sp.k0(y) - sp.i1(y) * sp.k1(y))
import scipy.special as scsp # In[137]: R = np.arange(0,14*10**3) R_d = 4.*10**3 #in pc M_star = 3.*10**10*2*10**30 M_dm = 10.**11.8*2*10**30 c_mod = 10. r_s = 250.*10**3/10 #in pc sigma_0 = M_star/(2*np.pi*R_d**2) arg = R/(2*R_d) G = 4.302*10**(-3)/(2*10**30) v_d = np.sqrt(np.pi*G*sigma_0*((R**2)/R_d)*(scsp.i0(arg)*scsp.k0(arg)-scsp.i1(arg)*scsp.k1(arg))) v_dm = np.sqrt((G*M_dm)*(np.log((r_s+R)/r_s)-R/(r_s+R))/(R*(np.log(1+c_mod)-c_mod/(1+c_mod)))) v_comb = np.sqrt(v_d**2+v_dm**2) # In[240]: plt.clf() plt.errorbar(np.array(radii)*1000,vrts,yerr=verr,marker='*',color='g') plt.errorbar(np.array(radii)*1000,vrts,xerr=np.array(rerr)*1000,marker='*',color='k') plt.plot(R,v_d, label='Disk profile') plt.plot(R,v_dm, label='DM profile') plt.plot(R,v_comb, label='Disk + DM profile') plt.title('Rotation Curves')
def S_1(self, f, T): Delta = BCS * k_B * self.T_c xi = h * f / (2 * k_B * T) return 2 / pi * (2 * Delta / (pi * k_B * T)) ** (1 / 2) * np.sinh(xi) * k0(xi)
def bessel(self, x): t = (x / float(self.s)) * self.sqrz return sp.k0(t)
! NUMBER OF COLLISION TEMPERATURES 1 ! COLLISION TEMPERATURES %.1f ! TRANS + UP + LOW + RATE COEFFS(cm^3 s^-1)""" % comet.Tkin for i in transitions: print "%d %d %d %.3e" % (transitions.index(i)+1, i[0]+1, i[1]+1, Ch2o[transitions.index(i)]) print """!COLLISIONS BETWEEN 3 H2O - electrons from Zakharov et al (2007) !NUMBER OF COLL TRANS %d !NUMBER OF COLL TEMPS %d !COLL TEMPS""" % (freq.size, temp.size) for i in temp: print i, print """ !TRANS + UP + LOW + COLLRATES(cm^3 s^-1)""" # deexcitation coefficients (i->j) for i in range(freq.size): aij = pc.h*freq[i]/2./pc.k_B/temp gigj = weight[transitions[i][0]]/weight[transitions[i][1]] Ceij = ve*sigmaeij[i]*2.*aij*numpy.exp(aij)*special.k0(aij) Ceji = ve*gigj*sigmaeij[i]*2.*aij*numpy.exp(-aij)*special.k0(aij) print i+1, transitions[i][0]+1, transitions[i][1]+1, for j in Ceij: print "%.3e"%j, print # print 2*i+2, transitions[i][1]+1, transitions[i][0]+1, # for j in Ceji: print "%.3e"%j, # print
def func_seaton(b1, c1): '''Implicit equation to solve for Seaton IPM method ''' return ss.k0(b1)**2 + ss.k1(b1)**2 - c1
def zeta(x): ''' Function for the IPM (Seaton, 1962) ''' return x**2 * (ss.k0(x)**2 + ss.k1(x)**2)