def __fct2(self, nu, u1r1, u2r1, u2r2, s1, s2, s3, n1sq, n2sq, n3sq): with numpy.errstate(invalid='ignore'): delta = self.__delta(nu, u1r1, u2r1, s1, s2, s3, n1sq, n2sq, n3sq) n0sq = (n3sq - n2sq) / (n2sq + n3sq) if s2 < 0: # a b11 = iv(nu, u2r1) b12 = kn(nu, u2r1) b21 = iv(nu, u2r2) b22 = kn(nu, u2r2) b31 = iv(nu+1, u2r1) b32 = kn(nu+1, u2r1) b41 = iv(nu-2, u2r2) b42 = kn(nu-2, u2r2) g1 = b11 * delta + b31 g2 = b12 * delta - b32 f1 = b41*g2 - b42*g1 f2 = b21*g2 - b22*g1 else: b11 = jn(nu, u2r1) b12 = yn(nu, u2r1) b21 = jn(nu, u2r2) b22 = yn(nu, u2r2) b31 = jn(nu+1, u2r1) b32 = yn(nu+1, u2r1) b41 = jn(nu-2, u2r2) b42 = yn(nu-2, u2r2) g1 = b11 * delta - b31 g2 = b12 * delta - b32 f1 = b41*g2 - b42*g1 f2 = b22*g1 - b21*g2 return f1 + n0sq*f2
def besselmode(m, u, w, x, y, phioff=0): """Calculate the field of a bessel mode LP mode. Arguments: - m azimuthal number of periods (m=0,1,2,3...) - u, w radial phase constant and radial decay constant - x, y transverse coordinates - phioff: offset angle, allows to rotate the mode in the x-y plane Returns: - mode: calculated bessel mode """ xx,yy = np.meshgrid(x,y) rr = np.reshape( np.sqrt(xx**2 + yy**2), len(x)*len(y)) phi = np.reshape( np.arctan2(xx,yy), len(x)*len(y)) fak = jv(m,u)/kn(m, w) res = np.zeros(len(rr)) indx1 = rr<=1 res[indx1] = jv(m,u*rr[indx1])*np.cos(m*phi[indx1]+phioff) indx2 = rr>1 res[indx2] = fak * kn(m, w * rr[indx2]) * np.cos(m * phi[indx2] + phioff) res = res / np.max(np.abs(res)) return np.reshape(res, [len(y), len(x)])
def __fct1(self, nu, u1r1, u2r1, u2r2, s1, s2, s3, n1sq, n2sq, n3sq): if s2 < 0: # a b11 = iv(nu, u2r1) b12 = kn(nu, u2r1) b21 = iv(nu, u2r2) b22 = kn(nu, u2r2) b31 = iv(nu+1, u2r1) b32 = kn(nu+1, u2r1) f1 = b31*b22 + b32*b21 f2 = b11*b22 - b12*b21 else: b11 = jn(nu, u2r1) b12 = yn(nu, u2r1) b21 = jn(nu, u2r2) b22 = yn(nu, u2r2) if s1 == 0: f1 = 0 else: b31 = jn(nu+1, u2r1) b32 = yn(nu+1, u2r1) f1 = b31*b22 - b32*b21 f2 = b12*b21 - b11*b22 if s1 == 0: delta = 1 else: delta = self.__delta(nu, u1r1, u2r1, s1, s2, s3, n1sq, n2sq, n3sq) return f1 + f2 * delta
def mode_2d(V, r, j=0, n=0, sampling=0.3, sz=1024): """Create a 2D mode profile. Parameters ---------- V: Fiber V number r: core radius in microns sampling: microns per pixel n: radial order of the mode (0 is fundumental) j: azimuthal order of the mode (0 is pure radial modes) TODO: Nonradial modes.""" #First, find the neff values... u_all,n_per_j = neff(V) ix = np.sum(n_per_j[0:j]) + n U0 = u_all[ix] W0 = np.sqrt(V**2 - U0**2) x = (np.arange(sz)-sz/2)*sampling/r xy = np.meshgrid(x,x) r = np.sqrt(xy[0]**2 + xy[1]**2) win = np.where(r < 1) wout = np.where(r >= 1) the_mode = np.zeros( (sz,sz) ) the_mode[win] = special.jn(j,r[win]*U0) scale = special.jn(j,U0)/special.kn(j,W0) the_mode[wout] = scale * special.kn(j,r[wout]*W0) return the_mode/np.sqrt(np.sum(the_mode**2))
def neff(V, accurate_roots=True): """Find the effective indices of all modes for a given value of the fiber V number. """ delu = 0.04 U = np.arange(delu/2,V,delu) W = np.sqrt(V**2 - U**2) all_roots=np.array([]) n_per_j=np.array([],dtype=int) n_modes=0 for j in range(int(V+1)): f = U*special.jn(j+1,U)*special.kn(j,W) - W*special.kn(j+1,W)*special.jn(j,U) crossings = np.where(f[0:-1]*f[1:] < 0)[0] roots = U[crossings] - f[crossings]*( U[crossings+1] - U[crossings] )/( f[crossings+1] - f[crossings] ) if accurate_roots: for i,root in enumerate(roots): roots[i] = optimize.newton(join_bessel, root, args=(V,j)) #import pdb; pdb.set_trace() if (j == 0): n_modes = n_modes + len(roots) n_per_j = np.append(n_per_j, len(roots)) else: n_modes = n_modes + 2*len(roots) n_per_j = np.append(n_per_j, len(roots)) #could be 2*length(roots) to account for sin and cos. all_roots = np.append(all_roots,roots) return all_roots, n_per_j
def _hefield(self, wl, nu, neff, r): self._heceq(neff, wl, nu) for i, rho in enumerate(self.fiber._r): if r < rho: break else: i += 1 layer = self.fiber.layers[i] n = layer.maxIndex(wl) u = layer.u(rho, neff, wl) urp = u * r / rho c1 = rho / u c2 = wl.k0 * c1 c3 = nu * c1 / r if r else 0 # To avoid div by 0 c6 = constants.Y0 * n * n if neff < n: B1 = jn(nu, u) B2 = yn(nu, u) F1 = jn(nu, urp) / B1 F2 = yn(nu, urp) / B2 if i > 0 else 0 F3 = jvp(nu, urp) / B1 F4 = yvp(nu, urp) / B2 if i > 0 else 0 else: c2 = -c2 B1 = iv(nu, u) B2 = kn(nu, u) F1 = iv(nu, urp) / B1 F2 = kn(nu, urp) / B2 if i > 0 else 0 F3 = ivp(nu, urp) / B1 F4 = kvp(nu, urp) / B2 if i > 0 else 0 A, B, Ap, Bp = layer.C[:, 0] + layer.C[:, 1] * self.alpha Ez = A * F1 + B * F2 Ezp = A * F3 + B * F4 Hz = Ap * F1 + Bp * F2 Hzp = Ap * F3 + Bp * F4 if r == 0 and nu == 1: # Asymptotic expansion of Ez (or Hz): # J1(ur/p)/r (r->0) = u/(2p) if neff < n: f = 1 / (2 * jn(nu, u)) else: f = 1 / (2 * iv(nu, u)) c3ez = A * f c3hz = Ap * f else: c3ez = c3 * Ez c3hz = c3 * Hz Er = c2 * (neff * Ezp - constants.eta0 * c3hz) Ep = c2 * (neff * c3ez - constants.eta0 * Hzp) Hr = c2 * (neff * Hzp - c6 * c3ez) Hp = c2 * (-neff * c3hz + c6 * Ezp) return numpy.array((Er, Ep, Ez)), numpy.array((Hr, Hp, Hz))
def neff(V, accurate_roots=True): """For a cylindrical fiber, find the effective indices of all modes for a given value of the fiber V number. Parameters ---------- V: float The fiber V-number. accurate_roots: bool (optional) Do we find accurate roots using Newton-Rhapson iteration, or do we just use a first-order linear approach to zero-point crossing?""" delu = 0.04 U = np.arange(delu/2,V,delu) W = np.sqrt(V**2 - U**2) all_roots=np.array([]) n_per_j=np.array([],dtype=int) n_modes=0 for j in range(int(V+1)): f = U*special.jn(j+1,U)*special.kn(j,W) - W*special.kn(j+1,W)*special.jn(j,U) crossings = np.where(f[0:-1]*f[1:] < 0)[0] roots = U[crossings] - f[crossings]*( U[crossings+1] - U[crossings] )/( f[crossings+1] - f[crossings] ) if accurate_roots: for i,root in enumerate(roots): roots[i] = optimize.newton(join_bessel, root, args=(V,j)) #import pdb; pdb.set_trace() if (j == 0): n_modes = n_modes + len(roots) n_per_j = np.append(n_per_j, len(roots)) else: n_modes = n_modes + 2*len(roots) n_per_j = np.append(n_per_j, len(roots)) #could be 2*length(roots) to account for sin and cos. all_roots = np.append(all_roots,roots) return all_roots, n_per_j
def d2x2K2(k,x): x = abs(x) y = numpy.nan_to_num( x*(special.kn(1,k*x)/k -x*special.kn(0,k*x)) ) if(isinstance(x, numpy.ndarray)): y[x==0] = numpy.ones(len(y[x==0]))*1.0/k**2 elif(x == 0): return 1.0/k**2 return y
def enum2D(x0, x1, kappa, n, factor=1): ra = np.sqrt(x0 * x0 + x1 * x1) + 1e-13 kappara = kappa * ra k0 = sp.kn(0, kappara) k1 = sp.kn(1, kappara) tmp = -kappa * factor * kappara * (k0 * k0 + k1 * k1) / ra return (np.sum(tmp * x0) / n ** 2, np.sum(tmp * x1) / n ** 2)
def laplace_solution(self, s): """ """ x_d = np.array([float(i)/self.number_of_segments \ for i in range(self.number_of_segments)]) c_fd = self.param["frac_k"] c_fd *= self.param["frac_width"] c_fd /= self.param["res_k"] c_fd /= self.param["frac_length"] delta_x = 1./float(self.number_of_segments) lhs = np.zeros((self.number_of_segments+1, self.number_of_segments+1)) rhs = np.zeros(self.number_of_segments+1) for j in range(self.number_of_segments): x_dj = x_d[j]+.5*delta_x rhs[j] = np.pi*x_dj/(c_fd*s) for i in range(self.number_of_segments): x_di = x_d[i] if x_dj > x_di and x_dj < x_di+delta_x: integral_1 = lambda x: special.kn(0, abs(x_dj-x)*np.sqrt(s)) (quad1, error1) = integrate.quad(integral_1, x_di, x_di+delta_x, points = [x_dj], epsrel=1.e-16) else: integral_2 = lambda x: special.kn(0, abs(x_dj-x)*np.sqrt(s)) (quad1, error1) = integrate.quad(integral_2, x_di, x_di+delta_x, epsrel=1.e-16) (quad2, error2) = integrate.quad(lambda x: special.kn(0, abs(x_dj+x)*np.sqrt(s)), x_di, x_di+delta_x, epsrel=1.e-16) #assert (error1 < 1.e-8) #assert (error2 < 1.e-8) lhs[j, i] += -.5*(quad1+quad2) if i < j: lhs[j, i] += (np.pi/c_fd)*((delta_x**2)/2.+ (x_dj-(i+1)*delta_x)*delta_x) lhs[j, j] += (np.pi/c_fd)*(delta_x**2)/8. for i in range(self.number_of_segments): lhs[i, self.number_of_segments] += 1. for j in range(self.number_of_segments): lhs[self.number_of_segments, j] += delta_x rhs[self.number_of_segments] = 1./s solution = np.linalg.solve(lhs, rhs) min_singular_value = np.linalg.svd(lhs)[1][-1] assert(min_singular_value > 1.e-8) return solution
def join_bessel(U,V,j): """In order to solve the Laplace equation in cylindrical co-ordinates, both the electric field and its derivative must be continuous at the edge of the fiber... i.e. the Bessel J and Bessel K have to be joined together. The solution of this equation is the n_eff value that satisfies this continuity relationship""" W = np.sqrt(V**2 - U**2) return U*special.jn(j+1,U)*special.kn(j,W) - W*special.kn(j+1,W)*special.jn(j,U)
def G2_intra(r, kF): # xi == kF * r if kF * r > 15.0: return G2_intra_asympt(kF, r) print "r, KF = ", r, kF # print r1, r2, kF """ Integration routine --- for internal use in Q_intra """ # s = np.max([kF * r, 1.0]) s = 1.0 # # First, handle the difference between Pi_intra # and 2/3 1/(q^2 + 1) # def f(x): J1 = special.jn(0, x * kF * r / s) return Pi_intra3(x / s) * J1 * x / s ** 2 # print r1, r2 # # We shall split the integration domain # split_points = [0.0, 2.0, 3.0] split_points.sort() split_points.append(np.Inf) I = 0.0 eps = 0.0 for i in range(1, len(split_points)): nmax = 300 a = split_points[i - 1] b = split_points[i] if i < len(split_points) - 1: n1 = int(abs(b - a) * kF * r / s / 6.0 * 20.0) if n1 > nmax: nmax = n1 Ii, epsi = integrate.quad(f, a, b, limit=nmax) I += Ii print Ii, epsi, a, b, nmax eps += epsi # # Now add the missing contribution: # The integral for 1/(q^2 + 1) can be found as # Int q dq /(q^2 + 1) J_0(qr) ~ K_0(r) # With two Bessel functions, we can apply addition theorem, # which gives K_0(|r - r'|), averaged over angles # I2 = special.kn(0, kF * r) I2 *= 2.0 / 3.0 I3 = special.kn(1, kF * r) * kF * r / 2.0 I3 *= 2.0 / 5.0 # print "In G2: ", I, I2 return (I + I2 + I3) * kF ** 3 / (4.0 * math.pi ** 2)
def g_twiddle(N, epsilon, s, L): threshold = 50 ns = np.linspace(1, N, N) BK0 = special.kn(0,ns[ns*np.pi*epsilon/L<threshold]*np.pi*epsilon/L) BK1 = special.kn(1,ns[ns*np.pi*epsilon/L<threshold]*np.pi*epsilon/L) BI0 = special.iv(0,ns[ns*np.pi*epsilon/L<threshold]*np.pi*epsilon/L) BI1 = special.iv(1,ns[ns*np.pi*epsilon/L<threshold]*np.pi*epsilon/L) g = np.zeros(N) g[ns*np.pi*epsilon/L<threshold] = s*BK1*BI1*np.pi / (L**2 * (s*BK1*BI0 + BI1*BK0)) g[ns*np.pi*epsilon/L>=threshold] = s*np.pi/L**2*(1/(s+1)) return g*ns
def fundamental2D( cot ): ''' plots fundamental solution in 2D ''' x = dic[cot.mesh_name].source V = cot.V mesh_obj = cot.mesh_obj kappa = cot.kappa y = cot.mesh_obj.coordinates() x_y = x-y ra = x_y * x_y ra = np.sum( ra, axis = 1 ) ra = np.sqrt( ra ) + 1e-13 kappara = kappa * ra phi_arr = cot.factor * np.power( kappara, 1.0 ) * sp.kn( 1, kappara ) phi = Function( V ) phi.vector().set_local( phi_arr[dof_to_vertex_map(V)] ) helper.save_plots( phi, ["Free Space", "Greens Function"], cot )
def A(r, z, tau0=0.7, zd=0.29, hd=8.1): r = np.abs(r) kappa0 = tau0 / (2 * zd) return 1.086 * 2 * kappa0 * r * sps.kn(1, r / hd) * np.exp(-1 * z / zd)
def white_noise_product_modulus_pdf(r, sigma, n): """PDF of modulus of product of two white noise DFT coefficients. Suppose we have two white noise time sequences each with time domain standard deviation equal to sigma: a = [b_0, a_1, ..., a_{n-1}] and b = [a_0, b_1, ..., b_{n-1}] . Now we form the discrete Fourier transforms of each sequence A = [A_0, A_k, ..., A_n] B = [B_0, B_k, ..., B_n] where A_k = (1/n) \sum_{m=0}^{n-1} a_m \exp(-i 2 \pi m k / n) . Now we multiply the DFT's together to form C = [A_0 B_0^*, A_1 B_1^*, ..., A_{n-1} B_{n-1}^*] This function tells you the probability distribution P(r) where r = |C_k|. Note that since we're dealing with white noise the distribution is independent of k. Args: r (float): Modulus at which you want the probability density. sigma (float): Standard deviation of the time domain signal from whence came the Fourier amplitudes. n (int): Number of points in the time domain signal. Returns: (float): Probability density at the provided modulus value. """ return (2 * n / sigma**2)**2 * r * ss.kn(0, 2 * r * n / sigma**2)
def test_hrg(): ID, info = random.choice(list(species_dict.items())) m = info["mass"] g = info["degen"] sign = -1 if info["boson"] else 1 prefactor = g / (2 * np.pi ** 2 * hbarc ** 3) if info["has_anti"]: prefactor *= 2 T = np.random.uniform(0.13, 0.15) hrg = HRG(T, species=[ID], res_width=False) assert_almost_equal(hrg.T, T, delta=1e-15, msg="incorrect temperature") n = np.arange(1, 50) density = prefactor * m * m * T * ((-sign) ** (n - 1) / n * special.kn(2, n * m / T)).sum() assert_almost_equal(hrg.density(), density, delta=1e-12, msg="incorrect density") def integrand(p): E = np.sqrt(m * m + p * p) return p * p * E / (np.exp(E / T) + sign) energy_density = prefactor * integrate.quad(integrand, 0, 10)[0] assert_almost_equal(hrg.energy_density(), energy_density, delta=1e-12, msg="incorrect energy density") def integrand(p): E = np.sqrt(m * m + p * p) return p ** 4 / (3 * E) / (np.exp(E / T) + sign) pressure = prefactor * integrate.quad(integrand, 0, 10)[0] assert_almost_equal(hrg.pressure(), pressure, delta=1e-12, msg="incorrect pressure")
def density(self, x): """ Return the stellar density of an exponential profile input : x=r/rc (can be array-like) output : nuh Bessel0(x) / pi / rc """ return self.nuh * kn(0,x) / pi / self.rc
def x2K2(k,x): y = -x*x*special.kn(2, k*x)/(k*k) if(isinstance(x, numpy.ndarray)): y[x == 0] = numpy.ones(len(y[x == 0]))*-2.0/k**4 elif(x == 0): return -2.0/k**4 return y
def jkdiff(m,u,w): """Calculate the absolute difference diff = |Jm(u)/Jm+1(u)-Km(w)/Km+1(w)|. Can be used to determine the branches of LP modes in a step-index fiber. Arguments: - m azimuthal number of periods (m=0,1,2,3...) - u radial phase constant - w radial decay constant Returns: - diff - Difference """ return np.abs( jv(m, u)/(u * jv(m+1,u)) - (kn(m,w)/(w*kn(m+1,w))))
def _hefield(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) v = rho * k * sqrt(nco2 - ncl2) jnu = jn(nu, u) knw = kn(nu, w) Delta = (1 - ncl2/nco2)/2 b1 = jvp(nu, u) / (u * jnu) b2 = kvp(nu, w) / (w * knw) F1 = (u * w / v)**2 * (b1 + (1 - 2 * Delta)*b2) / nu F2 = (v / (u * w))**2 * nu / (b1 + b2) a1 = (F2 - 1) / 2 a2 = (F2 + 1) / 2 a3 = (F1 - 1) / 2 a4 = (F1 + 1) / 2 a5 = (F1 - 1 + 2 * Delta) / 2 a6 = (F1 + 1 - 2 * Delta) / 2 if r < rho: jmur = jn(nu-1, u * r / rho) jpur = jn(nu+1, u * r / rho) jnur = jn(nu, u * r / rho) er = -(a1 * jmur + a2 * jpur) / jnu ephi = -(a1 * jmur - a2 * jpur) / jnu ez = u / (k * neff * rho) * jnur / jnu hr = Y0 * nco2 / neff * (a3 * jmur - a4 * jpur) / jnu hphi = -Y0 * nco2 / neff * (a3 * jmur + a4 * jpur) / jnu hz = Y0 * u * F2 / (k * rho) * jnur / jnu else: kmur = kn(nu-1, w * r / rho) kpur = kn(nu+1, w * r / rho) knur = kn(nu, w * r / rho) er = -u / w * (a1 * kmur - a2 * kpur) / knw ephi = -u / w * (a1 * kmur + a2 * kpur) / knw ez = u / (k * neff * rho) * knur / knw hr = Y0 * nco2 / neff * u / w * (a5 * kmur + a6 * kpur) / knw hphi = -Y0 * nco2 / neff * u / w * (a5 * kmur - a6 * kpur) / knw hz = Y0 * u * F2 / (k * rho) * knur / knw return numpy.array((er, ephi, ez)), numpy.array((hr, hphi, hz))
def lpConstants(self, r, neff, wl, nu, A): u = self.u(r, neff, wl) if neff < self.maxIndex(wl): W = constants.pi / 2 return (W * (u * yvp(nu, u) * A[0] - yn(nu, u) * A[1]), W * (jn(nu, u) * A[1] - u * jvp(nu, u) * A[0])) else: return ((u * kvp(nu, u) * A[0] - kn(nu, u) * A[1]), (iv(nu, u) * A[1] - u * ivp(nu, u) * A[0]))
def _lpcoeq(self, v0, nu): u1r1, u2r1, u2r2, s1, s2, n1sq, n2sq, n3sq = self.__params(v0) if s1 == 0: # e return (jn(nu+1, u2r1) * yn(nu-1, u2r2) - yn(nu+1, u2r1) * jn(nu-1, u2r2)) (f11a, f11b) = ((jn(nu-1, u1r1), jn(nu, u1r1)) if s1 > 0 else (iv(nu-1, u1r1), iv(nu, u1r1))) if s2 > 0: f22a, f22b = jn(nu-1, u2r2), yn(nu-1, u2r2) f2a = jn(nu, u2r1) * f22b - yn(nu, u2r1) * f22a f2b = jn(nu-1, u2r1) * f22b - yn(nu-1, u2r1) * f22a else: # a f22a, f22b = iv(nu-1, u2r2), kn(nu-1, u2r2) f2a = iv(nu, u2r1) * f22b + kn(nu, u2r1) * f22a f2b = iv(nu-1, u2r1) * f22b - kn(nu-1, u2r1) * f22a return f11a * f2a * u1r1 - f11b * f2b * u2r1
def EH_fields(self, ri, ro, nu, neff, wl, EH, tm=True): """ modify EH in-place (for speed) """ n = self.maxIndex(wl) u = self.u(ro, neff, wl) if ri == 0: if nu == 0: if tm: self.C = numpy.array([1., 0., 0., 0.]) else: self.C = numpy.array([0., 0., 1., 0.]) else: self.C = numpy.zeros((4, 2)) self.C[0, 0] = 1 # Ez = 1 self.C[2, 1] = 1 # Hz = alpha elif nu == 0: self.C = numpy.zeros(4) if tm: c = constants.Y0 * n * n idx = (0, 3) self.C[:2] = self.tetmConstants(ri, ro, neff, wl, EH, c, idx) else: c = -constants.eta0 idx = (1, 2) self.C[2:] = self.tetmConstants(ri, ro, neff, wl, EH, c, idx) else: self.C = self.vConstants(ri, ro, neff, wl, nu, EH) # Compute EH fields if neff < n: c1 = wl.k0 * ro / u F3 = jvp(nu, u) / jn(nu, u) F4 = yvp(nu, u) / yn(nu, u) else: c1 = -wl.k0 * ro / u F3 = ivp(nu, u) / iv(nu, u) F4 = kvp(nu, u) / kn(nu, u) c2 = neff * nu / u * c1 c3 = constants.eta0 * c1 c4 = constants.Y0 * n * n * c1 EH[0] = self.C[0] + self.C[1] EH[1] = self.C[2] + self.C[3] EH[2] = (c2 * (self.C[0] + self.C[1]) - c3 * (F3 * self.C[2] + F4 * self.C[3])) EH[3] = (c4 * (F3 * self.C[0] + F4 * self.C[1]) - c2 * (self.C[2] + self.C[3])) return EH
def F(self,rho,tau): #tau = tau(:); #tau(find(tau > 100)) = 100; if tau>100: tau=100 #h_inf = besselk(0,rho); h_inf = kn(0,rho) expintrho = expn(1,rho) w = (expintrho-h_inf)/(expintrho-expn(1,rho/2)) I = h_inf - w*expn(1,rho/2*np.exp(abs(tau))) + (w-1)*expn(1,rho*np.cosh(tau)) h=h_inf+self.sign(tau)*I return h
def vConstants(self, ri, ro, neff, wl, nu, EH): a = numpy.zeros((4, 4)) n = self.maxIndex(wl) u = self.u(ro, neff, wl) urp = self.u(ri, neff, wl) if neff < n: B1 = jn(nu, u) B2 = yn(nu, u) F1 = jn(nu, urp) / B1 F2 = yn(nu, urp) / B2 F3 = jvp(nu, urp) / B1 F4 = yvp(nu, urp) / B2 c1 = wl.k0 * ro / u else: B1 = iv(nu, u) B2 = kn(nu, u) F1 = iv(nu, urp) / B1 if u else 1 F2 = kn(nu, urp) / B2 F3 = ivp(nu, urp) / B1 if u else 1 F4 = kvp(nu, urp) / B2 c1 = -wl.k0 * ro / u c2 = neff * nu / urp * c1 c3 = constants.eta0 * c1 c4 = constants.Y0 * n * n * c1 a[0, 0] = F1 a[0, 1] = F2 a[1, 2] = F1 a[1, 3] = F2 a[2, 0] = F1 * c2 a[2, 1] = F2 * c2 a[2, 2] = -F3 * c3 a[2, 3] = -F4 * c3 a[3, 0] = F3 * c4 a[3, 1] = F4 * c4 a[3, 2] = -F1 * c2 a[3, 3] = -F2 * c2 return numpy.linalg.solve(a, EH)
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 plot_Ai(self, histtype="stepfilled"): if histtype == "step": ALPHAG = 0.5 else: ALPHAG = ALPHA sG = np.sqrt(np.var(self.gAi.flatten())) print(sG) mG = np.mean(self.gAi.flatten()) amin, amax = np.min(self.gAi), np.max(self.gAi) alist = np.arange(2 * amin, amax * 2, amax / 250.0) theoryGdist = norm.pdf(alist, loc=mG, scale=sG) if self.TYPE != "gNL": plt.plot( alist, theoryGdist, self.clrs[0], linestyle=self.ls[0], linewidth=LW, label=self.TYPELABEL + "$=0$" ) plot_hist(plt, self.gAi.flatten(), clr="skyblue", alp=ALPHA, ht=histtype) for i in range(len(self.fgnls)): if self.theoryplot == False: lbl = self.TYPELABEL + "=" + NtoSTR(self.fgnls[i]) else: lbl = None plot_hist(plt, self.fgNLAi[i].flatten(), clr=self.clrs[i + 1], alp=ALPHA, labl=lbl) if self.theoryplot: if self.TYPE == "fNL": theorynGdist = norm.pdf( alist, loc=mG, scale=np.sqrt((self.A1const * self.fgnls[i]) ** 2.0 + sG ** 2.0) ) elif self.TYPE == "gNL": sigmax0 = np.sqrt(self.A0const * self.Nconst) sigmax1 = 8.0 * self.fgnls[i] * np.sqrt(3.0 * np.pi * self.A1const) theorynGdist = kn(0, np.abs(alist) / sigmax0 / sigmax1) / np.pi / sigmax0 / sigmax1 LW1 = self.get_LW1(i) plt.plot( alist, theorynGdist, self.clrs[i + 1], linestyle=self.ls[i + 1], linewidth=LW1, label=self.TYPELABEL + "$=$" + NtoSTR(self.fgnls[i]), ) plt.xlim(-0.15, 0.15) plt.xlabel(r"$A_i$") plt.ylabel(r"$p(A_i)$") plt.legend(fontsize=20)
def _lpceq(self, neff, wl, nu): N = len(self.fiber) C = numpy.zeros((N-1, 2)) C[0, 0] = 1 for i in range(1, N-1): r = self.fiber.innerRadius(i) A = self.fiber.layers[i-1].Psi(r, neff, wl, nu, C[i-1, :]) C[i, :] = self.fiber.layers[i].lpConstants(r, neff, wl, nu, A) r = self.fiber.innerRadius(-1) A = self.fiber.layers[N-2].Psi(r, neff, wl, nu, C[-1, :]) u = self.fiber.layers[N-1].u(r, neff, wl) return u * kvp(nu, u) * A[0] - kn(nu, u) * A[1]
def Psi(self, r, neff, wl, nu, C): u = self.u(r, neff, wl) if neff < self.maxIndex(wl): psi = (C[0] * jn(nu, u) + C[1] * yn(nu, u) if C[1] else C[0] * jn(nu, u)) psip = u * (C[0] * jvp(nu, u) + C[1] * yvp(nu, u) if C[1] else C[0] * jvp(nu, u)) else: psi = (C[0] * iv(nu, u) + C[1] * kn(nu, u) if C[1] else C[0] * iv(nu, u)) psip = u * (C[0] * ivp(nu, u) + C[1] * kvp(nu, u) if C[1] else C[0] * ivp(nu, u)) # if numpy.isnan(psi): # print(neff, self.maxIndex(wl), C, r) return psi, psip
def fragmentation(x): if (sublimate == 'small') and (x < (1. - facct)): return 0. if species == 'Ar': v_th = 6. # m/s for argon C = 8. # pellet material constant for argon elif species == 'Ne': v_th = 8. C = 5. elif species == 'D2': v_th = 20. C = 2.5 else: #species is mol(D)/[mol(D)+mol(Ne)] w_Ne = (1.0 - species) * 20.1797 w_Ne /= (1.0 - species) * 20.1797 + species * 2.014 v_th = 8. * w_Ne + 20. * (1. - w_Ne) C = 2.5 * (1.0 + w_Ne) D_cm = D_p * 1e2 # initial velocity: v_i = v/cos(bend) # normal velocity: v_n= v_i*sin(bend)= v*tan(bend) v_n = v * np.tan(np.pi * bend / 180.) X_R = (v_n / v_th)**2 b = X_R / (L_D * (D_cm) * C) d = np.linspace(0., D_cm, 10000) K1 = kn(1, b * d) K1[0] = 0. F = 1. - b * d * K1 F[0] = 0. try: dp = interp1d(F, d)(x) / 1e2 except ValueError: #print('Skipping x=%f, greater than pellet diameter at x=%f'%(x,F[-1])) dp = 0. return dp / 2 # divide by two to get radius
def nEQ(self, T): """Returns the equilibrium number density at temperature T. Returns zero for non-thermal components""" if not 'thermal' in self.Type: return 0. x = T / self.mass(T) if x < 0.1: neq = self.mass(T)**3 * (x / (2 * pi))**(3. / 2.) * exp(-1 / x) * ( 1. + (15. / 8.) * x + (105. / 128.) * x**2) #Non-relativistic elif x < 1.5: neq = self.mass(T)**3 * x * kn(2, 1 / x) / ( 2 * pi**2) #Non-relativistic/relativistic else: if self.dof > 0: neq = Zeta3 * T**3 / pi**2 #Relativistic Bosons if self.dof < 0: neq = (3. / 4.) * Zeta3 * T**3 / pi**2 #Relativistic Fermions neq = neq * abs(self.dof) return neq
def _lpfield(self, wl, nu, neff, r): N = len(self.fiber) C = numpy.array((1, 0)) for i in range(1, N): rho = self.fiber.innerRadius(i) if r < rho: layer = self.fiber.layers[i-1] break A = self.fiber.layers[i-1].Psi(rho, neff, wl, nu, C) C = self.fiber.layers[i].lpConstants(rho, neff, wl, nu, A) else: layer = self.fiber.layers[-1] u = layer.u(rho, neff, wl) C = (0, A[0] / kn(nu, u)) ex, _ = layer.Psi(r, neff, wl, nu, C) hy = neff * constants.Y0 * ex return numpy.array((ex, 0, 0)), numpy.array((0, hy, 0))
def sd_kazantzidis(X): """ Kazantzidis surface density, normalized according to the convention: SD(X = R/a) = SD_real(R) * pi * a^2 / N_infinty Parameters ---------- X : array_like (same shape as n), float Projected radius X = R/a Returns ------- SD : array_like (same shape as X), float Normalized surface density profile. """ sd = kn(0, X) / 2 return sd
def zmelement(q, Qz, r_b, z_max, zp_max, N_z=500): # q, Qz are single value variables (not arrays) hz = z_max / (N_z - 1) hzp = zp_max / (N_z - 1) epz = hz / 1000 #starting point for z-integration epzp = hzp / 1000 #starting point for z-prime integration z = np.linspace(epz, z_max, N_z) zp = np.linspace(epzp, zp_max, N_z) int_p = np.zeros(zp.shape) for i, zpi in enumerate(zp): #int_p[i] = np.sum(z**2/(z + zpi)*np.exp(-2*z/r_b)*np.sin(Qz*zpi)*kn(1, q*(z + zpi)) )*hz int_p[i] = scipy.integrate.simps( z**2 / (z + zpi) * np.exp(-2 * z / r_b) * np.sin(Qz * zpi) * kn(1, q * (z + zpi)), z) #melement = 4/r_b**3*np.sum(int_p)*hzp melement = 4 / r_b**3 * scipy.integrate.simps(int_p, zp) return melement
def n_kazantizidis(X): """ Kazantzidis projected number, normalized according to the convention: N(X = R/a) = N(R) / N_infinty Parameters ---------- X : array_like (same shape as n), float Projected radius X = R/a. Returns ------- N : array_like (same shape as n), float Kazantzidis projected number. """ N = 1 - X * kn(1, X) return N
def F(tm, B1, B2): #print B1, B2 Fi = 2. * np.sqrt(pi * (B1**2 - B2**2)) km = np.arctan(np.sqrt(tm)) I2 = 0.0 Nk = 5000 ks = np.linspace(km, pi / 2, Nk) dk = ks[1] - ks[0] for k in ks: t = np.tan(k)**2 dI = (2 * t + 1)**2 * (t / tm / (1 + t) - 1.) / t + t - np.sqrt( t * tm * (1 + t)) - (2 + 0.5 / t) * np.log(t / tm / (1 + t)) #print t, kn(0, B2*t), B1, B2, B2*t, dI #print -B1*t #print t, B1, ':', exp(-B1*t) dI *= np.exp(-B1 * t) * kn(0, B2 * t) * np.sqrt(1 + t) I2 += dI * dk return Fi * I2
def gammaEELS( w_all, # the range of wavelengths the Gam EELS is taken over, i.e. we need a val of GamEEL for many different wavelenths [1/s] w0, gamR, ebeam_loc, amp, ): v = 0.48 gamL = 1 / np.sqrt(1 - v**2) m = (2.0 * e**2) / (3.0 * gamR * hbar_eVs * c**3) gam = 0.07 + gamR * w_all**2 alpha = e**2 / m * hbar_eVs**2 / (-w_all**2 - 1j * gam * w_all + w0**2) rod_loc = np.array([0, 0]) magR = np.linalg.norm(ebeam_loc - rod_loc) constants = 4.0 * e**2 / ( (hbar_eVs) * hbar_cgs * np.pi * (v * c)**4 * gamL**2) * (w_all / hbar_eVs)**2 * (kn( 1, (w_all / hbar_eVs) * magR / (v * c * gamL)))**2 # print constants Gam_EELS = constants * np.imag(alpha) return amp * Gam_EELS #units of 1/eV
def _tmfield(self, wl, nu, neff, r): N = len(self.fiber) C = numpy.array((1, 0)) EH = numpy.zeros(4) ri = 0 for i in range(N-1): ro = self.fiber.outerRadius(i) layer = self.fiber.layers[i] n = layer.maxIndex(wl) u = layer.u(ro, neff, wl) if i > 0: C = layer.tetmConstants(ri, ro, neff, wl, EH, constants.Y0 * n * n, (0, 3)) if r < ro: break if neff < n: c1 = wl.k0 * ro / u F3 = jvp(nu, u) / jn(nu, u) F4 = yvp(nu, u) / yn(nu, u) else: c1 = -wl.k0 * ro / u F3 = ivp(nu, u) / iv(nu, u) F4 = kvp(nu, u) / kn(nu, u) c4 = constants.Y0 * n * n * c1 EH[0] = C[0] + C[1] EH[3] = c4 * (F3 * C[0] + F4 * C[1]) ri = ro else: layer = self.fiber.layers[-1] u = layer.u(ro, neff, wl) # C = return numpy.array((0, ephi, 0)), numpy.array((hr, 0, hz))
def plot_Ai(self, select=0.2): """ the select option is used to choose only those data that have power modulation less than this amount i.e. if abs(A0)<select this is necessary to only consider skies with the power spectra as what we see. """ sG=np.sqrt(np.var(self.gAi.flatten())) print (sG) mG=np.mean(self.gAi.flatten()) amin, amax = np.min(self.gAi), np.max(self.gAi) alist=np.arange(2*amin, amax*2, amax/250.) theoryGdist=norm.pdf(alist, loc=mG, scale=sG) for i in range(len(self.fgnls)): if (self.theoryplot==False): lbl=self.TYPELABEL+"="+NtoSTR(self.fgnls[i]) else: lbl=None Aiselected = self.fgNLAi[i][np.abs(self.fgNLA0[i/3])<select] gAiselected = self.gAi[np.abs(self.fgNLA0[i/3])<select] print (len(Aiselected)) plot_hist(plt, Aiselected - gAiselected, clr=self.clrs[i+1], alp=ALPHA, labl=lbl) if (self.theoryplot): sigmax=np.sqrt(6.*self.fgnls[i]*self.A0const*self.Nconst) sigmay=np.sqrt(72.*self.fgnls[i]*2.2188E-10) theorynGdist=kn(0, np.abs(alist)/sigmax/sigmay)/np.pi/sigmax/sigmay plt.plot(alist, theorynGdist, self.clrs[i+1], linestyle=self.ls[i+1], linewidth=LW, label=self.TYPELABEL+"="+NtoSTR(self.fgnls[i])) plt.xlim(-0.15, 0.15) plt.xlabel(r'$A_i$') plt.ylabel(r'$p(A_i)$') plt.legend(fontsize=20)
def g_v(self, R, v): z_dense = self.k_dense * R z_dilute = self.k_dilute * R b0_dense = (self.gamma / R - self.c_dense) / iv(0, z_dense) b0_dilute = (self.gamma / R - self.c_dilute) / kn(0, z_dilute) extra_term = self.gamma * (v * v - 1) / R**2 term1 = b0_dense * (self.k_dense** 2) * (iv(0, z_dense) - iv(1, z_dense) / z_dense) term2 = -b0_dilute * (self.k_dilute**2) * (kn(0, z_dilute) - kn(1, z_dilute) / z_dilute) term3 = (self.k_dense * iv(v - 1, z_dense) / iv(v, z_dense) - v / R) term3 *= (extra_term - b0_dense * self.k_dense * iv(1, z_dense)) term4 = (self.k_dilute * kn(v - 1, z_dilute) / kn(v, z_dilute) - v / R) term4 *= (extra_term + b0_dilute * self.k_dilute * kn(1, z_dilute)) return -term1 + term2 - term3 + term4
def dens(self, y=None, log_=True, paramvec=None): """ computes the density y - (n x 1) densites to computed log_ - (bool) return logarithm of density paramvec - (k x 1) the parameter to evalute the density f(y) = \sqrt{\nu} \sigma^{-1} \pi^{-1} \exp(\nu) ... \exp( \frac{1}{\sigma^2}(y - \delta + \mu) \mu ) ... \frac{a }{ b} K_{ 1 }(\sqrt{ ab }) """ if y is None: y = self.y delta, mu, nu, sigma = self._paramvec(paramvec) a = nu + mu**2 / sigma**2 delta_mu = delta - mu c0 = -np.log(np.pi) + 0.5 * np.log(nu) + nu - np.log(sigma) #n = y.shape[0] y_ = (y - delta_mu) / sigma b = nu + y_**2 const = c0 #* n logf = y_ * (mu / sigma) logf += const logf += 0.5 * (np.log(a) - np.log(b)) logf += np.log(sps.kn(1, np.sqrt(a * b))) if not log_: return np.exp(logf) return logf
def _heceq(self, neff, wl, nu): N = len(self.fiber) EH = numpy.empty((4, 2)) ri = 0 for i in range(N-1): ro = self.fiber.outerRadius(i) try: self.fiber.layers[i].EH_fields(ri, ro, nu, neff, wl, EH) except ZeroDivisionError: return float("inf") ri = ro # Last layer C = numpy.zeros((4, 2)) C[1, :] = EH[0, :] C[3, :] = EH[1, :] self.fiber.layers[N-1].C = C u = self.fiber.layers[N-1].u(ri, neff, wl) n = self.fiber.maxIndex(-1, wl) F4 = kvp(nu, u) / kn(nu, u) c1 = -wl.k0 * ri / u c2 = neff * nu / u * c1 c3 = constants.eta0 * c1 c4 = constants.Y0 * n * n * c1 E = EH[2, :] - (c2 * EH[0, :] - c3 * F4 * EH[1, :]) H = EH[3, :] - (c4 * F4 * EH[0, :] - c2 * EH[1, :]) if E[1] != 0: self.alpha = -E[0] / E[1] else: self.alpha = -H[0] / H[1] return E[0]*H[1] - E[1]*H[0]
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 laplace_solution(self, s): """ """ x_d = np.array([float(i)/self.number_of_segments \ for i in range(self.number_of_segments)]) c_fd = self.param["frac_k"] c_fd *= self.param["frac_width"] c_fd /= self.param["res_k"] c_fd /= self.param["frac_length"] delta_x = 1. / float(self.number_of_segments) lhs = np.zeros( (self.number_of_segments + 1, self.number_of_segments + 1)) rhs = np.zeros(self.number_of_segments + 1) for j in range(self.number_of_segments): x_dj = x_d[j] + .5 * delta_x rhs[j] = np.pi * x_dj / (c_fd * s) for i in range(self.number_of_segments): x_di = x_d[i] if x_dj > x_di and x_dj < x_di + delta_x: integral_1 = lambda x: special.kn( 0, abs(x_dj - x) * np.sqrt(s)) (quad1, error1) = integrate.quad(integral_1, x_di, x_di + delta_x, points=[x_dj], epsrel=1.e-16) else: integral_2 = lambda x: special.kn( 0, abs(x_dj - x) * np.sqrt(s)) (quad1, error1) = integrate.quad(integral_2, x_di, x_di + delta_x, epsrel=1.e-16) (quad2, error2) = integrate.quad( lambda x: special.kn(0, abs(x_dj + x) * np.sqrt(s)), x_di, x_di + delta_x, epsrel=1.e-16) #assert (error1 < 1.e-8) #assert (error2 < 1.e-8) lhs[j, i] += -.5 * (quad1 + quad2) if i < j: lhs[j, i] += (np.pi / c_fd) * ((delta_x**2) / 2. + (x_dj - (i + 1) * delta_x) * delta_x) lhs[j, j] += (np.pi / c_fd) * (delta_x**2) / 8. for i in range(self.number_of_segments): lhs[i, self.number_of_segments] += 1. for j in range(self.number_of_segments): lhs[self.number_of_segments, j] += delta_x rhs[self.number_of_segments] = 1. / s solution = np.linalg.solve(lhs, rhs) min_singular_value = np.linalg.svd(lhs)[1][-1] assert (min_singular_value > 1.e-8) return solution
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 get_precursor_diffusion_matrix(self, pc_consumption, dt): diffusion_matrix = np.zeros((self.len_xy, self.len_xy)) n_vec = self.directions.reshape(self.len_x, self.len_y, 3) k = par.A_PC * par.F_PC * par.S_PC kd = sqrt(k / par.D_COEFF) rhs = copy(-self.coverages) * self.areas / dt - self.areas[:] * k tp = extended_position_matrix( self) # ^^^^ should be old surface ^^^^ o.k. #direction decreasing y index v1 = tp[1:-1, 0:-2, :] - tp[1:-1, 1:-1, :] #direction increasing y index v4 = tp[1:-1, 2:, :] - tp[1:-1, 1:-1, :] #direction decreasing x index v2 = tp[0:-2, 1:-1, :] - tp[1:-1, 1:-1, :] #direction increasing x index v3 = tp[2:, 1:-1, :] - tp[1:-1, 1:-1, :] e1 = scale_array(v4 - v1) e2 = scale_array(v3 - v2) a1 = length_array(v4 - v1) / 2 #side length in y-direction a2 = length_array(v3 - v2) / 2 #side length in x-direction e1_ = scale_array_sqr(v1) e2_ = scale_array_sqr(v2) e3_ = scale_array_sqr(v3) e4_ = scale_array_sqr(v4) n1 = cross_product_array(e2, n_vec) n2 = cross_product_array(-e1, n_vec) n3 = cross_product_array(e1, n_vec) n4 = cross_product_array(-e2, n_vec) #generate prefactors and modify result vector flux_coeff = np.zeros((self.len_x, self.len_y, 4)) flux_coeff[:, :, 0] = par.D_COEFF * dot_array( e1_, n1) * a2 #flux point(i,j) -> point(i,j-1) flux_coeff[:, :, 1] = par.D_COEFF * dot_array( e2_, n2) * a1 #flux point(i,j) -> point(i-1,j) flux_coeff[:, :, 2] = par.D_COEFF * dot_array( e3_, n3) * a1 #flux point(i,j) -> point(i+1,j) flux_coeff[:, :, 3] = par.D_COEFF * dot_array( e4_, n4) * a2 #flux point(i,j) -> point(i,j+1) #write prefactors to matrix for index in range(self.len_xy): i = index / (self.len_y) j = index - i * (self.len_y) h_1 = 0.0 #check neighbor in neg. y direction if j - 1 >= 0: diffusion_matrix[index, index - 1] = flux_coeff[i, j, 0] else: h_1 = sqrt((tp[i, 0, 0] - tp[i, 1, 0])**2 + (tp[i, 0, 1] - tp[i, 1, 1])**2) rhs[index] -= (kd * kn(1, kd * h_1)) / (kn(0, kd * h_1) / h_1 - (kd + kn(1, kd * h_1)) / 2) diffusion_matrix[index, index] -= ( kn(0, kd * h_1) / h_1 + (kd * kn(1, kd * h_1)) / 2) / (kn(0, kd * h_1) / h_1 - (kd * kn(1, kd * h_1)) / 2) #check neighbor in neg. x direction if i - 1 >= 0: diffusion_matrix[index, index - self.len_y] = flux_coeff[i, j, 1] else: h_1 = sqrt((tp[0, j, 0] - tp[1, j, 0])**2 + (tp[0, j, 1] - tp[1, j, 1])**2) rhs[index] -= (kd * kn(1, kd * h_1)) / (kn(0, kd * h_1) / h_1 - (kd + kn(1, kd * h_1)) / 2) diffusion_matrix[index, index] -= ( kn(0, kd * h_1) / h_1 + (kd * kn(1, kd * h_1)) / 2) / (kn(0, kd * h_1) / h_1 - (kd * kn(1, kd * h_1)) / 2) #check neighbor in pos. y direction if i + 1 <= self.len_x - 1: diffusion_matrix[index, index + self.len_y] = flux_coeff[i, j, 2] else: h_1 = sqrt((tp[-1, j, 0] - tp[-2, j, 0])**2 + (tp[-1, j, 1] - tp[-2, j, 1])**2) rhs[index] -= (kd * kn(1, kd * h_1)) / (kn(0, kd * h_1) / h_1 - (kd + kn(1, kd * h_1)) / 2) diffusion_matrix[index, index] -= ( kn(0, kd * h_1) / h_1 + (kd * kn(1, kd * h_1)) / 2) / (kn(0, kd * h_1) / h_1 - (kd * kn(1, kd * h_1)) / 2) #check neighbor in pos. x direction if j + 1 <= self.len_y - 1: diffusion_matrix[index, index + 1] = flux_coeff[i, j, 3] else: h_1 = sqrt((tp[i, -1, 0] - tp[i, -2, 0])**2 + (tp[i, -1, 1] - tp[i, -2, 1])**2) rhs[index] -= (kd * kn(1, kd * h_1)) / (kn(0, kd * h_1) / h_1 - (kd + kn(1, kd * h_1)) / 2) diffusion_matrix[index, index] -= ( kn(0, kd * h_1) / h_1 + (kd * kn(1, kd * h_1)) / 2) / (kn(0, kd * h_1) / h_1 - (kd * kn(1, kd * h_1)) / 2) #surface elements are only approximated and are not area wide => flux coefficients of opposite direction are averaged diffusion_matrix = (diffusion_matrix + diffusion_matrix.T) / 2 for index in range(self.len_xy): diffusion_matrix[ index, index] += -sum(diffusion_matrix[index, :]) + diffusion_matrix[ index, index] - (k + pc_consumption[index] + 1 / dt) * self.areas[index] return np.mat(diffusion_matrix), rhs, self.len_x, self.len_y
def coeq(v0, nu, fiber): r1, r2 = fiber.rho n1, n2, n3 = fiber.n na = sqrt(max(fiber.n)**2 - n3**2) K0 = v0 / (na * r2) beta = K0 * n3 if n1 > n3: u1 = K0**2 * (n1**2 - n3**2) s1 = 1 else: u1 = K0**2 * (n3**2 - n1**2) s1 = -1 if n2 > n3: u2 = K0**2 * (n2**2 - n3**2) s2 = 1 else: u2 = K0**2 * (n3**2 - n2**2) s2 = -1 s = -s1 * s2 u1r1 = u1 * r1 u2r1 = u2 * r1 u2r2 = u2 * r2 X = (u2r1**2 + s * u1r1**2) * nu * beta if s1 == 1: Y = jvp(nu, u1r1) / jn(nu, u1r1) else: Y = ivp(nu, u1r1) / iv(nu, u1r1) ju2r1 = jn(nu, u2r1) if s2 == 1 else iv(nu, u2r1) nu2r1 = yn(nu, u2r1) if s2 == 1 else kn(nu, u2r1) jpu2r1 = jvp(nu, u2r1) if s2 == 1 else ivp(nu, u2r1) npu2r1 = yvp(nu, u2r1) if s2 == 1 else kvp(nu, u2r1) ju2r2 = jn(nu, u2r2) if s2 == 1 else iv(nu, u2r2) nu2r2 = yn(nu, u2r2) if s2 == 1 else kn(nu, u2r2) j1u2r2 = jn(nu + 1, u2r2) n1u2r2 = yn(nu + 1, u2r2) M = numpy.empty((4, 4)) M[0, 0] = X * ju2r1 M[0, 1] = X * nu2r1 M[0, 2] = -K0 * (jpu2r1 * u1r1 + s * Y * ju2r1 * u2r1) * u1r1 * u2r1 M[0, 3] = -K0 * (npu2r1 * u1r1 + s * Y * nu2r1 * u2r1) * u1r1 * u2r1 M[1, 0] = -K0 * (n2**2 * jpu2r1 * u1r1 + s * n1**2 * Y * ju2r1 * u2r1) * u1r1 * u2r1 M[1, 1] = -K0 * (n2**2 * npu2r1 * u1r1 + s * n1**2 * Y * nu2r1 * u2r1) * u1r1 * u2r1 M[1, 2] = X * ju2r1 M[1, 3] = X * nu2r1 D201 = nu * n3 / u2r2 * (j1u2r2 * nu2r2 - ju2r2 * yn(nu + 1, u2r2)) D202 = -( (n2**2 + n3**2) * nu * n1u2r2 * nu2r2 / u2r2 + n3**2 * nu * nu2r2**2 / (nu - 1)) D203 = -(n2**2 * nu * ju2r2 * n1u2r2 / u2r2 + n3**2 * nu * nu2r2 * j1u2r2 / u2r2 + n3**2 * nu * (j1u2r2 * nu2r2 + n1u2r2 * ju2r2) / (2 * (nu - 1))) D212 = -(n2**2 * nu * nu2r2 * j1u2r2 / u2r2 + n3**2 * nu * ju2r2 * n1u2r2 / u2r2 + n3**2 * nu * (n1u2r2 * ju2r2 + j1u2r2 * nu2r2) / (2 * (nu - 1))) D213 = -( (n2**2 + n3**2) * nu * j1u2r2 * ju2r2 / u2r2 + n3**2 * nu * ju2r2**2 / (nu - 1)) D223 = nu * n2**2 * n3 / u2r2 * (j1u2r2 * nu2r2 - ju2r2 * n1u2r2) D30 = M[1, 1] * D201 - M[1, 2] * D202 + M[1, 3] * D203 D31 = M[1, 0] * D201 - M[1, 2] * D212 + M[1, 3] * D213 D32 = M[1, 0] * D202 - M[1, 1] * D212 + M[1, 3] * D223 D33 = M[1, 0] * D203 - M[1, 1] * D213 + M[1, 2] * D223 return M[0, 0] * D30 - M[0, 1] * D31 + M[0, 2] * D32 - M[0, 3] * D33
def d3x2K2(k,x): y = abs(x) return numpy.nan_to_num(x*(y*k*special.kn(1,k*y) - 3*special.kn(0,k*y)))
def dx2K2(k,x): y = abs(x) return numpy.nan_to_num(x*y*special.kn(1,k*y)/k)
def solve_fn(b, V): v = V*np.sqrt(b) u = V*np.sqrt(1.-b) return (u * jn(1, u) * kn(0, v) - v * jn(0, u) * kn(1, v))
def growth_rate(R): J_plus = -k * (gamma / R - A_dense) * iv(1, k * R) / iv(0, k * R) J_minus = l * (gamma / R - A_dilute) * kn(1, l * R) / kn(0, l * R) return J_plus - J_minus
max = 100 / l if spinodal(phi_target, u): radii[i, j] = 0 g_v[i, j] = 0 elif (growth_rate(min) < 0) and (growth_rate(max) < 0): g_v[i, j] = 0 radii[i, j] = 2 elif (growth_rate(min) > 0) and (growth_rate(max) < 0): sol = root_scalar(growth_rate, bracket=[min, max], xtol=0.01, method='brentq') v = 2 R = sol.root b0_dense = (gamma / R - A_dense) / iv(0, k * R) b0_dilute = (gamma / R - A_dilute) / kn(0, l * R) extra_term = gamma * (v * v - 1) / R**2 term1 = b0_dense * k * k * (iv(0, k * R) - iv(1, k * R) / (k * R)) term2 = -b0_dilute * l * l * (kn(0, l * R) - kn(1, l * R) / (l * R)) term3 = (k * iv(v - 1, k * R) / iv(v, k * R) - v / R) * (extra_term - b0_dense * k * iv(1, k * R)) term4 = (l * kn(v - 1, l * R) / kn(v, l * R) - v / R) * (extra_term + b0_dilute * l * kn(1, l * R)) g_v[i, j] = -term1 + term2 - term3 + term4 radii[i, j] = 1 plt.rc('text', usetex=True) plt.rc('font', family='serif', size=18) max = np.max(np.abs(g_v)) min = -max x, y = np.meshgrid(np.log10(us * phi_shift), phi_ts)
from scipy.special import kn, gamma, loggamma from scipy.interpolate import RectBivariateSpline approximate_eta = False # Definition of auxillary functions lmin = lambda beta, kappa: max(1. / 2., beta * kappa) lminp = lambda beta, kappa: max(1., 2. * beta * kappa) turn = lambda beta, betalow, a: exp(-(max(beta, betalow) - betalow) * a) if approximate_eta: eta = lambda x: -2. * log(x / 2.) - 1 - 2. * euler_gamma + ( 1 - euler_gamma - log(x / 2.)) * x**2. else: eta = lambda x: x**2 * (-kn(1, x)**2 + kn(2, x) * kn(0, x)) zeta = lambda kappa, beta, lmin: (max(lmin, beta * kappa)**2 - lmin**2) / ( 2 * kappa**2 * beta**2) + eta(max(lmin, beta * kappa) / kappa) lambdaT = (1. + cos(2.) + 2 * sin(2.)) / 2. lambdaV = (9. - cos(4.) - 4. * sin(4.)) / 16. sigmaT_smallbeta = lambda beta, kappa: 2. * beta**2. * zeta(kappa, beta, 0.5) sigmaV_smallbeta = lambda beta, kappa, lmin: 4. * beta**2. * zeta( kappa, 2. * beta, lmin) def sigmaTatt(beta, kappa): if beta < 1: return sigmaT_smallbeta(beta, kappa) * turn(beta, 0.2, -0.64)
# NOTE: gamma ---> gamma-1 *** edist = np.copy(fe) pdist = np.copy(fp) masked_edist = np.ma.masked_where(fe < 1E-20, fe) masked_pdist = np.ma.masked_where(fp < 1E-20, fp) sim.exdata = gamma * (DataDict['me'][0] / DataDict['mi'][0]) / (sim.LF - 1) sim.eydata = masked_edist * sim.exdata sim.ixdata = gamma / (sim.LF - 1) sim.iydata = masked_pdist * sim.ixdata delgame0 = Te * DataDict['mi'][0] / DataDict['me'][0] if delgame0 >= 0.013: aconst = 1 / (delgame0 * np.exp(1.0 / delgame0) * kn(2, 1.0 / delgame0)) else: aconst = np.sqrt(2 / np.pi) / delgame0**1.5 aconst -= 15.0 / (4. * np.sqrt(delgame0) * np.sqrt(2 * np.pi)) aconst += (345 * np.sqrt(delgame0)) / (64. * np.sqrt(2 * np.pi)) aconst -= (3285 * delgame0**1.5) / (512. * np.sqrt(2 * np.pi)) aconst += (95355 * delgame0**2.5) / (16384. * np.sqrt(2 * np.pi)) aconst -= (232065 * delgame0**3.5) / (131072. * np.sqrt(2 * np.pi)) femax = aconst * gamma * (gamma + 1.0) * np.sqrt((gamma + 1.0)**2 - 1) femax *= np.exp(-gamma / delgame0) maxg = (delgame0) * 40 + 1. #!40 times the temperature is usually enough gamma_table = np.empty(200) for i in range(len(gamma_table)): gamma_table[i] = (maxg - 1.) / (len(gamma_table) - 1) * ( i) #!+1. remove 1. from definition to avoid underflows.
ux, uy, uz, u = boosted_maxwellian(T, Gamma, direction=-1) gamma = np.sqrt(1.0 + ux*ux + uy*uy + uz*uz) n1[n] = gamma ux, uy, uz, u = boosted_maxwellian(T+0.0001, Gamma, direction=-1) gamma = np.sqrt(1.0 + ux*ux + uy*uy + uz*uz) n2[n] = gamma axs[0].set_xscale('log') #axs[0].set_yscale('log') axs[0].set_xlim((1.0, 10.0)) axs[0].hist(n1, 100, color="black", alpha=0.3, density=True) axs[0].hist(n2, 100, color="red", alpha=0.3, density=True) #gamma grid (with beta) gs = np.logspace(0.0, 2.0, 100) + 0.01 beta = np.sqrt(1.0 - 1.0/gs**2) #maxwell-juttner distribution K2T = kn(2, 1.0/T) #modified Bessel function of the second kind (with integer order 2) mwj = (gs**2 * beta)/(T*K2T)*np.exp(-gs/T) axs[0].plot(gs, mwj, 'r-') fname = 'maxwells.pdf' plt.savefig(fname)
def EMMLEOld(data, alpha, beta, mu, delta, maxIter, tol, libPath): xBar = np.mean(data) n = len(data) # compute initial log-lik distrOld = NIGDistribution( { "delta": delta, "mu": mu, "alpha": alpha, "beta": beta }, libPath=libPath) distrNew = distrOld.copy() loglikOld = np.sum(distrOld.lPDF(data)) / n # Iterate in EM-algorithm for iterEM in np.arange(0, maxIter): # --- E-step --- phiSqrt = np.sqrt(1 + ((data - distrNew.mu) / distrNew.delta)**2) # compute besselk function values k0 = special.kn(0, distrNew.delta * distrNew.alpha * phiSqrt) k1 = special.kn(1, distrNew.delta * distrNew.alpha * phiSqrt) k2 = special.kn(2, distrNew.delta * distrNew.alpha * phiSqrt) # Compute pseudo values s = (distrNew.delta * phiSqrt * k0) / (distrNew.alpha * k1) w = (distrNew.alpha * k2) / (distrNew.delta * phiSqrt * k1) # --- M-step --- # Compute pseudo values sBar = np.mean(s, axis=0) wBar = np.mean(w, axis=0) Lambda = 1.0 / np.mean(w - 1.0 / sBar, axis=0) # Update parameters distrNew.delta = np.sqrt(Lambda) gamma = distrNew.delta / sBar distrNew.beta = (np.sum(data * w, axis=0) - xBar * wBar * n) / (n - sBar * wBar * n) distrNew.alpha = np.sqrt((gamma**2) + (distrNew.beta**2)) # Filter too large alphas filtered = NIGEstimation.filterParams(np.array([distrNew.alpha]), np.array([distrNew.beta]), np.array([distrNew.delta])) distrNew.alpha = filtered["alpha"][0] distrNew.beta = filtered["beta"][0] distrNew.delta = filtered["delta"][0] gamma = filtered["gamma"][0] distrNew.mu = xBar - distrNew.beta * distrNew.delta / gamma # --- Compute log-lik --- loglikNew = np.sum(distrNew.lPDF(data)) / n loglikdiff = loglikNew - loglikOld # Set new log-likelihood as old one if (loglikdiff > 0): loglikOld = loglikNew distrOld = distrNew.copy() # If should break due to tolerance if (loglikdiff < tol): break return (distrNew, loglikOld)
def root_func(u): w = np.sqrt(v**2 - u**2) return jv(m, u) / (u * jv(m - 1, u)) + kn(m, w) / (w * kn(m - 1, w))
sns.set_context("poster") rn = 13 # Ohm temperatures = [3, 4, 5, 6, 7] delta = np.multiply( 10. / 2. * k * 3.5, [.997, .985, .958, .907, .828]) # values form implicit BCS theory #delta = np.multiply(10./2. * k * 3.5 , np.sqrt(1-np.divide(temperatures,10))) #delta = 379e-6 *elementary_charge#Al eV = lambda v: np.multiply(elementary_charge, v) eV2kT = lambda v, t: np.divide(eV(v), 2 * k * t) temdecay = lambda t, d: np.exp(-np.divide(d, np.multiply(t, k)) ) # constant against voltage sqr = lambda v, d: np.sqrt(np.divide(2 * d, np.add(eV(v), 2 * d))) sinhK0 = lambda v, t: np.multiply(np.sinh(eV2kT(v, t)), kn(0, eV2kT(v, t)) ) #approaches expectation value current = lambda v, t, d: np.multiply( np.multiply( np.multiply( np.multiply( #np.divide(2,np.multiply(1,rn)), np.divide(2, np.multiply(elementary_charge, rn)), temdecay(t, d)), sqr(v, d)), np.add(eV(v), d)), sinhK0(v, t)) #unit is ok too voltages = np.arange(0, 3e-3, 0.001e-3) plt.figure() for t in range(len(temperatures)):
def solve_fn(b, V): v = V*np.sqrt(b) u = V*np.sqrt(1.-b) return (u * jn(l - 1, u) * kn(l, v) + v * jn(l, u) * kn(l - 1, v))