def _container_default(self): x = arange(-5.0, 15.0, 20.0/100) y = jn(0, x) left_plot = create_line_plot((x, y), bgcolor="white", add_grid=True, add_axis=True) left_plot.tools.append(PanTool(left_plot)) self.left_plot = left_plot y = jn(1, x) right_plot = create_line_plot((x, y), bgcolor="white", add_grid=True, add_axis=True) right_plot.tools.append(PanTool(right_plot)) right_plot.y_axis.orientation = "right" self.right_plot = right_plot # Tone down the colors on the grids right_plot.hgrid.line_color = (0.3, 0.3, 0.3, 0.5) right_plot.vgrid.line_color = (0.3, 0.3, 0.3, 0.5) left_plot.hgrid.line_color = (0.3, 0.3, 0.3, 0.5) left_plot.vgrid.line_color = (0.3, 0.3, 0.3, 0.5) container = HPlotContainer(spacing=20, padding=50, bgcolor="lightgray") container.add(left_plot) container.add(right_plot) return container
def fullDet(b, nu): a = rho * b i = ivp(nu, u1*a) / (u1*a * iv(nu, u1*a)) if nu == 1: k2 = -2 k = 0 else: k2 = 2 * nu / (u2 * b)**2 - 1 / (nu - 1) k = -1 X = (1 / (u1*a)**2 + 1 / (u2*a)**2) P1 = jn(nu, u2*a) * yn(nu, u2*b) - yn(nu, u2*a) * jn(nu, u2*b) P2 = (jvp(nu, u2*a) * yn(nu, u2*b) - yvp(nu, u2*a) * jn(nu, u2*b)) / (u2 * a) P3 = (jn(nu, u2*a) * yvp(nu, u2*b) - yn(nu, u2*a) * jvp(nu, u2*b)) / (u2 * b) P4 = (jvp(nu, u2*a) * yvp(nu, u2*b) - yvp(nu, u2*a) * jvp(nu, u2*b)) / (u2 * a * u2 * b) A = (n12 * i**2 - n32 * nu**2 * X**2) if nu == 1: B = 0 else: B = 2 * n22 * n32 * nu * X * (P1 * P4 - P2 * P3) return (n32 * k2 * A * P1**2 + (n12 + n22) * n32 * i * k2 * P1 * P2 - (n22 + n32) * k * A * P1 * P3 - (n12*n32 + n22*n22) * i * k * P1 * P4 + n22 * n32 * k2 * P2**2 - n22 * (n12 + n32) * i * k * P2 * P3 - n22 * (n22 + n32) * k * P2 * P4 - B)
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 __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 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 _create_window(self): numpoints = 50 low = -5 high = 15.0 x = arange(low, high, (high-low)/numpoints) container = OverlayPlotContainer(bgcolor="lightgray") common_index = None index_range = None value_range = None self.animated_plots = [] for i, color in enumerate(COLOR_PALETTE): if not common_index: animated_plot = AnimatedPlot(x, jn(i,x), color) common_index = animated_plot.plot.index index_range = animated_plot.plot.index_mapper.range value_range = animated_plot.plot.value_mapper.range else: animated_plot = AnimatedPlot(common_index, jn(i,x), color) animated_plot.plot.index_mapper.range = index_range animated_plot.plot.value_mapper.range = value_range container.add(animated_plot.plot) self.animated_plots.append(animated_plot) for i, a_plot in enumerate(self.animated_plots): a_plot.plot.position = [50 + (i%3)*(PLOT_SIZE+50), 50 + (i//3)*(PLOT_SIZE+50)] self.timer = Timer(100.0, self.onTimer) self.container = container return Window(self, -1, component=container)
def esa_edge_2d_line(omega, x0, xs, alpha=3/2*np.pi, Nc=None, c=None): """Line source by two-dimensional ESA for an edge-shaped secondary source distribution constisting of monopole line sources. One leg of the secondary sources have to be located on the x-axis (y0=0), the edge at the origin. Derived from :cite:`Spors2016` Parameters ---------- omega : float Angular frequency. x0 : int(N, 3) array_like Sequence of secondary source positions. xs : (3,) array_like Position of synthesized line source. alpha : float, optional Outer angle of edge. Nc : int, optional Number of elements for series expansion of driving function. Estimated if not given. c : float, optional Speed of sound Returns ------- (N,) numpy.ndarray Complex weights of secondary sources. """ x0 = np.asarray(x0) k = util.wavenumber(omega, c) phi_s = np.arctan2(xs[1], xs[0]) if phi_s < 0: phi_s = phi_s + 2*np.pi r_s = np.linalg.norm(xs) L = x0.shape[0] r = np.linalg.norm(x0, axis=1) phi = np.arctan2(x0[:, 1], x0[:, 0]) phi = np.where(phi < 0, phi+2*np.pi, phi) if Nc is None: Nc = np.ceil(2 * k * np.max(r) * alpha/np.pi) epsilon = np.ones(Nc) # weights for series expansion epsilon[0] = 2 d = np.zeros(L, dtype=complex) idx = (r <= r_s) for m in np.arange(Nc): nu = m*np.pi/alpha f = 1/epsilon[m] * np.sin(nu*phi_s) * np.cos(nu*phi) * nu/r d[idx] = d[idx] + f[idx] * jn(nu, k*r[idx]) * hankel2(nu, k*r_s) d[~idx] = d[~idx] + f[~idx] * jn(nu, k*r_s) * hankel2(nu, k*r[~idx]) d[phi > 0] = -d[phi > 0] return -1j*np.pi/alpha * d
def test_deriv(): """ Test the derivative functionality """ # form bessel j1 f = Cheb(lambda x: jn(1,x),(0,100)) anald = lambda x: 0.5*(jn(0,x) - jn(2,x)) xs = np.random.uniform(0,100,1000) np.testing.assert_allclose( f.deriv()(xs), anald(xs) )
def efieldTE(m, k, pts, phase = "re"): pts = numpy.asarray(pts, dtype = 'd') r, phi, z = toCyl(pts) if phase == "re": rTrig = -numpy.sin(m * phi) phiTrig = numpy.cos(m * phi) else: rTrig = numpy.cos(m * phi) phiTrig = numpy.sin(m * phi) res = numpy.zeros(r.shape + (3, ), dtype = 'd') indsIn = numpy.logical_and(r > 0.0, r < a) xIn = rtEpsIn * k * r[indsIn] er = m * jn(m, xIn) * rTrig[indsIn] / (epsIn * r[indsIn]) print numpy.sum(numpy.abs(er)) ephi = -k * djn(m, xIn, 1) * phiTrig[indsIn] / rtEpsIn print numpy.sum(numpy.abs(ephi)) phiIn = phi[indsIn] res[indsIn, 0] = er * numpy.cos(phiIn) - ephi * numpy.sin(phiIn) res[indsIn, 1] = er * numpy.sin(phiIn) + ephi * numpy.cos(phiIn) indsOut = numpy.logical_and(r >= a, r < b) xOut = rtEpsOut * k * r[indsOut] er = m * (aTE(m, k) * jn(m, xOut) + bTE(m, k) * yn(m, xOut)) * rTrig[indsOut] / (epsOut * r[indsOut]) print numpy.sum(numpy.abs(er)) ephi = -k * (aTE(m, k) * djn(m, xOut, 1) + bTE(m, k) * dyn(m, xOut, 1)) * phiTrig[indsOut] / rtEpsOut print numpy.sum(numpy.abs(ephi)) phiOut = phi[indsOut] res[indsOut, 0] = er * numpy.cos(phiOut) - ephi * numpy.sin(phiOut) res[indsOut, 1] = er * numpy.sin(phiOut) + ephi * numpy.cos(phiOut) return res
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 bc_solve(x, k, a, b): F = (sp.jn(k - 1, x * a) - sp.jn(k + 1, x * a)) * \ (sp.yn(k - 1, x * b) - sp.yn(k + 1, x * b)) / 4.0 \ - \ (sp.jn(k - 1, x * b) - sp.jn(k + 1, x * b)) * \ (sp.yn(k - 1, x * a) - sp.yn(k + 1, x * a)) / 4.0 return F
def _create_plot_component(): # Create some x-y data series (with NaNs) to plot x = linspace(-5.0, 15.0, 500) x[75:125] = nan x[200:250] = nan x[300:330] = nan pd = ArrayPlotData(index = x) pd.set_data("value1", jn(0, x)) pd.set_data("value2", jn(1, x)) # Create some line and scatter plots of the data plot = Plot(pd) plot.plot(("index", "value1"), name="j_0(x)", color="red", width=2.0) plot.plot(("index", "value2"), type="scatter", marker_size=1, name="j_1(x)", color="green") # Tweak some of the plot properties plot.title = "Plots with NaNs" plot.padding = 50 plot.legend.visible = True # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) return plot
def get_bn(n, mc, dl, h0, F, e): """ Compute b_n from Eq. 22 of Taylor et al. (2015). :param n: Harmonic number :param mc: Chirp mass of binary [Solar Mass] :param dl: Luminosity distance [Mpc] :param F: Orbital frequency of binary [Hz] :param e: Orbital Eccentricity :returns: b_n """ # convert to seconds mc *= const.Tsun dl *= const.Mpc / const.c omega = 2 * np.pi * F if h0 is None: amp = n * mc**(5/3) * omega**(2/3) / dl elif h0 is not None: amp = n * h0 / 2.0 ret = (-amp * np.sqrt(1-e**2) * (ss.jn(n-2,n*e) - 2*ss.jn(n,n*e) + ss.jn(n+2,n*e))) return ret
def get_bn(n, mc, dl, F, e): """ Compute b_n from Eq. 22 of Taylor et al. (2015). :param n: Harmonic number :param mc: Chirp mass of binary [Solar Mass] :param dl: Luminosity distance [Mpc] :param F: Orbital frequency of binary [Hz] :param e: Orbital Eccentricity :returns: b_n """ # convert to seconds mc *= SOLAR2S dl *= MPC2S omega = 2 * np.pi * F amp = n * mc ** (5 / 3) * omega ** (2 / 3) / dl ret = -amp * np.sqrt(1 - e ** 2) * (ss.jn(n - 2, n * e) - 2 * ss.jn(n, n * e) + ss.jn(n + 2, n * e)) return ret
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 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 save_bessel_functions(N): """Generate N 2D shapelets and plot.""" beta2 = beta ** 2 B = empty((grid_size, grid_size)) # Don't want matrix behaviour here # --------------------------------------------------------------------------- # Basis function constants, and hermite polynomials # --------------------------------------------------------------------------- vals = [[n, 1.0 / sqrt((2 ** n) * sqrt(pi) * factorial(n, 1) * beta), 0, 0, 0] for n in xrange(N)] expreal = exp(-theta.real ** 2 / (2 * beta2)) expimag = exp(-theta.imag ** 2 / (2 * beta2)) for n, K, H, _, _ in vals: vals[n][3] = K * jn(n, theta.real) * expreal vals[n][4] = K * jn(n, theta.imag) * expimag pylab.figure() l = 0 for v1 in vals: for v2 in vals: B = v1[3] * v2[4] pylab.subplot(N, N, l + 1) pylab.axis("off") pylab.imshow(B.T) l += 1 pylab.suptitle("Shapelets N=%i Beta=%.4f" % (N, beta)) # pylab.savefig("B%i.png" % N) pylab.show()
def _doubleExponentialDiskPotentialR2derivIntegrandSmallk(k,R,z,gamma): """Internal function that gives the integrand for the double exponential disk radial force for k < 1/gamma""" gammak= gamma*k return k*k*0.5*(special.jn(0,k*R)-special.jn(2,k*R))\ *(1.+k**2.)**-1.5*(nu.exp(-gammak*z) -gammak*nu.exp(-z))/(1.-gammak**2.)
def debye_integral_at_point(x,y,z, k,NA, n_int = 1000): from scipy.special import jn a = np.arcsin(NA) kr = k*np.sqrt(x**2+y**2) phi = np.arctan2(y,x) kz = k*z t = np.linspace(0.,a,n_int) dt = a/(n_int-1.) f_0 = np.sqrt(np.cos(t))*np.sin(t)*(np.cos(t)+1.)*jn(0,kr*np.sin(t))*np.exp(1.j*kz*np.cos(t)) f_1 = np.sqrt(np.cos(t))*np.sin(t)**2*jn(1,kr*np.sin(t))*np.exp(1.j*kz*np.cos(t)) f_2 = np.sqrt(np.cos(t))*np.sin(t)*(np.cos(t)-1.)*jn(2,kr*np.sin(t))*np.exp(1.j*kz*np.cos(t)) I0 = dt*(np.sum(f_0)-.5*(f_0[0]+f_0[-1])) I1 = dt*(np.sum(f_1)-.5*(f_1[0]+f_1[-1])) I2 = dt*(np.sum(f_2)-.5*(f_2[0]+f_2[-1])) ex = I0 +I2*np.cos(2*phi) ey = I2*np.sin(2*phi) ez = -2.j*I1*np.cos(phi) u = abs(ex)**2+abs(ey)**2+abs(ez)**2 return u,ex,ey,ez
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 True: if isinstance(R,nu.ndarray): if not isinstance(z,nu.ndarray): z= nu.ones_like(R)*z out= nu.array([self._R2deriv(rr,zz) for rr,zz in zip(R,z)]) return out if R > 16.*self._hr or R > 6.: return self._kp.R2deriv(R,z) if R < 1.: R4max= 1. else: R4max= R kmax= 2.*self._kmaxFac*self._beta maxj0zeroIndx= nu.argmin((self._j0zeros-kmax*R4max)**2.) #close enough maxj2zeroIndx= nu.argmin((self._j2zeros-kmax*R4max)**2.) #close enough ks0= nu.array([0.5*(self._glx+1.)*self._dj0zeros[ii+1] + self._j0zeros[ii] for ii in range(maxj0zeroIndx)]).flatten() weights0= nu.array([self._glw*self._dj0zeros[ii+1] for ii in range(maxj0zeroIndx)]).flatten() ks2= nu.array([0.5*(self._glx+1.)*self._dj2zeros[ii+1] + self._j2zeros[ii] for ii in range(maxj2zeroIndx)]).flatten() weights2= nu.array([self._glw*self._dj2zeros[ii+1] for ii in range(maxj2zeroIndx)]).flatten() evalInt0= ks0**2.*special.jn(0,ks0*R)*(self._alpha**2.+ks0**2.)**-1.5*(self._beta*nu.exp(-ks0*nu.fabs(z))-ks0*nu.exp(-self._beta*nu.fabs(z)))/(self._beta**2.-ks0**2.) evalInt2= ks2**2.*special.jn(2,ks2*R)*(self._alpha**2.+ks2**2.)**-1.5*(self._beta*nu.exp(-ks2*nu.fabs(z))-ks2*nu.exp(-self._beta*nu.fabs(z)))/(self._beta**2.-ks2**2.) return nu.pi*self._alpha*(nu.sum(weights0*evalInt0) -nu.sum(weights2*evalInt2))
def aTM(m, k): kaIn = rtEpsIn * k * a kaOut = rtEpsOut * k * a kbOut = rtEpsOut * k * b res = jn(m, kaIn) res /= jn(m, kaOut) - jn(m, kbOut) * yn(m, kaOut) / yn(m, kbOut) return res
def aTE(m, k): kaIn = rtEpsIn * k * a kaOut = rtEpsOut * k * a kbOut = rtEpsOut * k * b res = jn(m, kaIn) res /= jn(m, kaOut) - djn(m, kbOut, 1) * yn(m, kaOut) / dyn(m, kbOut, 1) return res
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 Fn(self,n): if n%2==1 : K=self.magnetic_structure.K cst1=((n*K)/(1.+(K**2)/2.))**2 cst2 = (n * K**2) / (4. + (2.*K ** 2)) Fn=cst1*(jn(0.5*(n-1),cst2)-jn(0.5*(n+1),cst2))**2 else : Fn=0.0 return Fn
def highm(Ef, r, Mmax, U0): Jsum = np.zeros((len(r))) Efr = Ef + Uvals(U0,r)/2.0 for i in range (-Mmax, Mmax+1): Jsum += 2.0 * (special.jn(i,(Ef*r)))**2 drhohm = 2.0 - Jsum drhohm += (special.jn(-Mmax,(Ef*r)))**2 drhohm -= (special.jn(1+Mmax,(Ef*r)))**2 drhohm *= - abs(Ef) / 4.0 / np.pi * Uvals(U0,r) return drhohm
def an(n, mass, dL, omega, ecc, t, l0): # integrating over time for residual (assuming omega and ecc not changing) mass *= Msol dL *= (10.**6.)*sc.parsec amp = mass**(5./3.) / ( dL * omega**(1./3.) ) amp *= sc.G**(5./3.) / sc.c**4. return -amp * ( ss.jn(n-2,n*ecc) - 2.*ecc*ss.jn(n-1,n*ecc) + (2./n)*ss.jn(n,n*ecc) + \ 2.*ecc*ss.jn(n+1,n*ecc) - ss.jn(n+2,n*ecc) ) * np.sin(n*omega*t + n*l0)
def bn(n, mass, dL, omega, ecc, t, l0): # integrating over time for residual (assuming omega and ecc not changing) mass *= Msol dL *= (10.**6.)*sc.parsec amp = mass**(5./3.) / ( dL * omega**(1./3.) ) amp *= sc.G**(5./3.) / sc.c**4. return amp * np.sqrt(1.-ecc**2.) * ( ss.jn(n-2,n*ecc) - 2.*ss.jn(n,n*ecc) + \ ss.jn(n+2,n*ecc) ) * np.cos(n*omega*t + n*l0)
def _create_plot_component(): # Create the index numpoints = 100 low = -5 high = 15.0 x = arange(low, high, (high - low) / numpoints) plotdata = ArrayPlotData(x=x, y1=jn(0, x), y2=jn(1, x)) # Create the left plot left_plot = Plot(plotdata) left_plot.x_axis.title = 'X' left_plot.y_axis.title = 'j0(x)' renderer = left_plot.plot(('x', 'y1'), type='line', color='blue', width=2.0)[0] renderer.overlays.append(LineInspector(renderer, axis='value', write_metadata=True, is_listener=True)) renderer.overlays.append(LineInspector(renderer, axis='index', write_metadata=True, is_listener=True)) left_plot.overlays.append(ZoomTool(left_plot, tool_mode='range')) left_plot.tools.append(PanTool(left_plot)) # Create the right plot right_plot = Plot(plotdata) right_plot.index_range = left_plot.index_range right_plot.orientation = 'v' right_plot.x_axis.title = 'j1(x)' right_plot.y_axis.title = 'X' renderer2 = right_plot.plot(('x', 'y2'), type='line', color='red', width=2.0)[0] renderer2.index = renderer.index renderer2.overlays.append(LineInspector(renderer2, write_metadata=True, is_listener=True)) renderer2.overlays.append(LineInspector(renderer2, axis='value', is_listener=True)) right_plot.overlays.append(ZoomTool(right_plot, tool_mode='range')) right_plot.tools.append(PanTool(right_plot)) container = HPlotContainer(background='lightgray') container.add(left_plot) container.add(right_plot) right_plot = Plot(plotdata) right_plot.index_range = left_plot.index_range right_plot.orientation = 'v' right_plot.x_axis.title = 'j1(x)' right_plot.y_axis.title = 'X' renderer2 = right_plot.plot(('x', 'y2'), type='line', color='red', width=2.0)[0] renderer2.index = renderer.index renderer2.overlays.append(LineInspector(renderer2, write_metadata=True, is_listener=True)) renderer2.overlays.append(LineInspector(renderer2, axis='value', is_listener=True)) right_plot.overlays.append(ZoomTool(right_plot, tool_mode='range')) right_plot.tools.append(PanTool(right_plot)) container.add(right_plot) return container
def piston( f, # frequency a_h, a_v, theta, phi, c=343 ): # speed of sound, in m/s. """Rigid elliptical piston in an infinite baffle, at frequency f Hz, with horizontal radius a_h (in meters) and vertical radius a_v. following description in the book by Beranek, Leo L. (1954). Acoustics. (yes, there is a more recent edition, but I don't have a copy...) Theta and phi, which are azimuth and elevation, resp., have units of radians. P is sound pressure in units of N/m^2 (? this should be verified). If theta and phi are scalars, or one is a vector, then behavior is as you would expect: you get a scalar or vector back. If both theta and phi are vectors, then P is a matrix where where columns correspond to values of theta, and rows correspond to values of phi. NOTES: - It is possible I have made a mistake in the below computations. The returned values from besselj are complex with, in some places, small but nonzero imaginary components. I address this by taking absolute value of P (i.e. complex magnitude); this matches intuition but awaits confirmation till I learn more acoustics theory """ k = 2*np.pi*f/c # wave number if type(theta) is types.IntType or type(theta) is types.FloatType or type(theta) is np.float64: theta = np.array([theta], dtype=np.float64) else: theta = np.array(theta, dtype=np.float64) if type(phi) is types.IntType or type(phi) is types.FloatType or type(phi) is np.float64: phi = np.array([phi], dtype=np.float64) else: phi = np.array(phi, dtype=np.float64) h_term = k*a_h*np.sin(theta) v_term = k*a_v*np.sin(phi) h_factor = .5*np.ones(shape=h_term.shape) for k in range(len(h_factor)): if np.abs(h_term[k]) > 4*np.finfo(np.float64).eps: h_factor[k] = sp_special.jn(1, h_term[k])/h_term[k] v_factor = .5*np.ones(shape=v_term.shape) for k in range(len(v_factor)): if np.abs(v_term[k]) > 4*np.finfo(np.float64).eps: v_factor[k] = sp_special.jn(1, v_term[k])/v_term[k] if v_factor.shape[0] > 1 and h_factor.shape[0] > 1: return 4*np.outer(np.abs(v_factor), np.abs(h_factor)) # make P from outer product. else: return 4*np.abs(v_factor*h_factor)
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 create_plot(): numpoints = 100 low = -5 high = 15.0 x = linspace(low, high, numpoints) pd = ArrayPlotData(index=x) p = Plot(pd, bgcolor="oldlace", padding=50, border_visible=True) for i in range(10): pd.set_data("y" + str(i), jn(i, x)) p.plot(("index", "y" + str(i)), color=tuple(COLOR_PALETTE[i]), width=2.0 * dpi_scale) p.x_grid.visible = True p.x_grid.line_width *= dpi_scale p.y_grid.visible = True p.y_grid.line_width *= dpi_scale p.legend.visible = True return p
def _generate_transfer_matrix(self): source_diameters = np.array(self.sources.get_arbit_param('Diameter')) source_xs = np.array(self.sources.get_arbit_param('x')) source_ys = np.array(self.sources.get_arbit_param('y')) source_zs = np.array(self.sources.get_arbit_param('z')) source_as = np.array(self.sources.get_arbit_param('Elevation')) source_bs = np.array(self.sources.get_arbit_param('Azimuth')) receiver_xs = np.array(self.receivers['x'].values) receiver_ys = np.array(self.receivers['y'].values) receiver_zs = np.array(self.receivers['z'].values) # GREEN FUNC. distance_x = source_xs - receiver_xs[:, np.newaxis] distance_y = source_ys - receiver_ys[:, np.newaxis] distance_z = source_zs - receiver_zs[:, np.newaxis] distance_matrix = np.sqrt(distance_x**2 + distance_y**2 + distance_z**2) greens_tensor = np.exp( 1j * np.einsum('i,jk->ijk', self.wavenums, distance_matrix)) / distance_matrix[np.newaxis, :] # DIRECTIVITY FUNC. normal_vecs = np.array([ np.sin(source_as) * np.cos(source_bs), np.sin(source_as) * np.sin(source_bs), np.cos(source_as) ]) normal_vecs_norm = np.linalg.norm(normal_vecs, axis=0) inner_matrix = normal_vecs[0] * receiver_xs[:, np.newaxis] \ + normal_vecs[1] * receiver_ys[:, np.newaxis] \ + normal_vecs[2] * receiver_zs[:, np.newaxis] theta_matrix = np.arccos( inner_matrix / (normal_vecs_norm[np.newaxis, :] * distance_matrix)) inside_vessel = np.einsum( 'i,jk->ijk', self.wavenums, np.sin(theta_matrix)) * source_diameters[np.newaxis, np.newaxis, :] * 0.5 directivity_tensor = jn(1, inside_vessel) / inside_vessel np.nan_to_num(directivity_tensor, nan=0.5, copy=False) self.transfer_matrix = directivity_tensor * greens_tensor
def _evaluate(self,R,z,phi=0.,t=0.,dR=0,dphi=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: 2010-04-16 - Written - Bovy (NYU) 2012-12-26 - New method using Gaussian quadrature between zeros - Bovy (IAS) DOCTEST: >>> doubleExpPot= DoubleExponentialDiskPotential() >>> r= doubleExpPot(1.,0) #doctest: +ELLIPSIS ... >>> assert( r+1.89595350484)**2.< 10.**-6. """ if True: if isinstance(R,float): floatIn= True R= nu.array([R]) z= nu.array([z]) else: floatIn= False out= nu.empty(len(R)) indx= (R <= 6.) out[True^indx]= self._kp(R[True^indx],z[True^indx]) R4max= nu.copy(R) R4max[(R < 1.)]= 1. kmax= self._kmaxFac*self._beta for jj in range(len(R)): if not indx[jj]: continue maxj0zeroIndx= nu.argmin((self._j0zeros-kmax*R4max[jj])**2.) #close enough ks= nu.array([0.5*(self._glx+1.)*self._dj0zeros[ii+1] + self._j0zeros[ii] for ii in range(maxj0zeroIndx)]).flatten() weights= nu.array([self._glw*self._dj0zeros[ii+1] for ii in range(maxj0zeroIndx)]).flatten() evalInt= special.jn(0,ks*R[jj])*(self._alpha**2.+ks**2.)**-1.5*(self._beta*nu.exp(-ks*nu.fabs(z[jj]))-ks*nu.exp(-self._beta*nu.fabs(z[jj])))/(self._beta**2.-ks**2.) out[jj]= -2.*nu.pi*self._alpha*nu.sum(weights*evalInt) if floatIn: return out[0] else: return out
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: 2010-04-16 - Written - Bovy (NYU) DOCTEST: """ if True: if isinstance(R, nu.ndarray): if not isinstance(z, nu.ndarray): z = nu.ones_like(R) * z out = nu.array([self._Rforce(rr, zz) for rr, zz in zip(R, z)]) return out if (R > 16. * self._hr or R > 6.) and hasattr(self, '_kp'): return self._kp.Rforce(R, z) if R < 1.: R4max = 1. else: R4max = R kmax = self._kmaxFac * self._beta kmax = 2. * self._kmaxFac * self._beta maxj1zeroIndx = nu.argmin( (self._j1zeros - kmax * R4max)**2.) #close enough ks = nu.array([ 0.5 * (self._glx + 1.) * self._dj1zeros[ii + 1] + self._j1zeros[ii] for ii in range(maxj1zeroIndx) ]).flatten() weights = nu.array([ self._glw * self._dj1zeros[ii + 1] for ii in range(maxj1zeroIndx) ]).flatten() evalInt = ks * special.jn( 1, ks * R) * (self._alpha**2. + ks**2.)**-1.5 * ( self._beta * nu.exp(-ks * nu.fabs(z)) - ks * nu.exp(-self._beta * nu.fabs(z))) / (self._beta**2. - ks**2.) return -2. * nu.pi * self._alpha * nu.sum(weights * evalInt)
def matter_correlation_function_fixed(self, r=None, rmin=10, rmax=200, pk=None, kh=None, khw=None, redshifts=[ 0, ], npoints=200, bias_f=None): if bias_f is None: bias_f = np.ones(pk) if r is None: r = np.linspace(rmin, rmax, npoints)[None, None, :] xi = np.zeros([len(redshifts), r.shape[0]]) kh = kh[None, :, None] xi = np.sum( khw[None, :, None] * kh**3 * np.log(10.) * jn(0, kh*r)\ * pk[:, :, None] * bias_f[:, :, None], axis=1) / 2. / np.pi**2 ##lgk_min = np.log10(kh.min()) ##lgk_max = np.log10(kh.max()) ##pkf = lambda lgk, i: np.interp(lgk, np.log10(kh), pk[i]) ##itf = lambda lgk, r, i: 10.**(lgk*3) * np.log(10.) * pkf(lgk, i)\ ## * jn(0, (10.**lgk)*r) / 2. / np.pi**2 ##xif = np.vectorize(lambda r, i: \ ## fixed_quad(itf, lgk_min, lgk_max, args=(r, i), n=10000)[0]) #if bias_f is not None: # pkf = lambda k, i: np.interp(k, kh, pk[i]) * bias_f(k, i) #else: # pkf = lambda k, i: np.interp(k, kh, pk[i]) #itf = lambda k, r, i: k**2 * pkf(k, i) * jn(0, k*r) / 2. / np.pi**2 #xif = np.vectorize(lambda r, i: \ # fixed_quad(itf, k_min, k_max, args=(r, i), n=10000)[0]) #for i in range(len(redshifts)): # #print "z = %3.1f"%redshifts[i] # xi[i,:] = xif(r, i) return xi, r.flatten()
def _z2deriv(self, R, z, phi=0., t=0.): """ NAME: z2deriv PURPOSE: evaluate z2 derivative INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: -d K_Z (R,z) d Z HISTORY: 2012-12-26 - Written - Bovy (IAS) """ if True: if isinstance(R, numpy.ndarray): if not isinstance(z, numpy.ndarray): z = numpy.ones_like(R) * z out = numpy.array( [self._z2deriv(rr, zz) for rr, zz in zip(R, z)]) return out if R > 16. * self._hr or R > 6.: return self._kp.z2deriv(R, z) if R < 1.: R4max = 1. else: R4max = R kmax = self._kmaxFac * self._beta maxj0zeroIndx = numpy.argmin( (self._j0zeros - kmax * R4max)**2.) #close enough ks = numpy.array([ 0.5 * (self._glx + 1.) * self._dj0zeros[ii + 1] + self._j0zeros[ii] for ii in range(maxj0zeroIndx) ]).flatten() weights = numpy.array([ self._glw * self._dj0zeros[ii + 1] for ii in range(maxj0zeroIndx) ]).flatten() evalInt = ks * special.jn( 0, ks * R) * (self._alpha**2. + ks**2.)**-1.5 * ( ks * numpy.exp(-ks * numpy.fabs(z)) - self._beta * numpy.exp(-self._beta * numpy.fabs(z))) / ( self._beta**2. - ks**2.) return -2. * numpy.pi * self._alpha * self._beta * numpy.sum( weights * evalInt)
def f(self, r, theta, t, m, n): '''============================================================= (m,n) Modo normal: Calcula el modo normal (m,n) de oscilación de la mebrana circular, donde n es el numero cuantico radial y m el numero angular. ARGUMENTOS: *Variable r r *Variable theta theta *Variable t t *Numero cuantico angular m *Numero cuantico radial n =============================================================''' lambda_mn = sp.jn_zeros(m, n)[-1] return sp.jn( m, lambda_mn*r/self.R )*\ np.cos( lambda_mn*self.c*t/self.R )*\ np.cos( m* theta )
def create_plot(): numpoints = 100 low = -5 high = 15.0 x = linspace(low, high, numpoints) pd = ArrayPlotData(index=x) p = Plot(pd, bgcolor="lightgray", padding=50, border_visible=True) for t, i in zip(cycle(['line', 'scatter']), list(range(10))): pd.set_data("y" + str(i), jn(i, x)) p.plot(("index", "y" + str(i)), color=tuple(COLOR_PALETTE[i]), width=2.0 * dpi_scale, type=t) p.x_grid.visible = True p.x_grid.line_width *= dpi_scale p.y_grid.visible = True p.y_grid.line_width *= dpi_scale p.legend.visible = True return p
def elliptic_airy(k_in, beam): '''# TODO: Descriptive doc string. a = radius f = frequency I_0 = gain at center ''' phi = np.pi * coord.angle_deg(beam.on_axis, beam.plane_normal) / 180.0 #F[ g(ct) ] = G(f/c)/|c| theta = np.pi * coord.angle_deg(beam.on_axis, k_in) / 180.0 lam = c.c / beam.f k = 2.0 * np.pi / lam f_circ = lambda r, phi: beam.I_0 * ( (2.0 * s.jn(1, k * beam.a * np.sin(theta)) / (k * beam.a * np.sin(theta))))**2.0 return ()
def J(self, order, x): """ Return the value of the Bessel function with the given order ar the given point. Parameters ---------- order : number Order of the Bessel function x : number Value where we want the Bessel function evaluation. Returns ------- y : number Bessel function value at 'x' """ from scipy.special import jn return jn(order, x)
def _create_plot_component(): # Create some x-y data series to plot x = linspace(-2.0, 10.0, 100) pd = ArrayPlotData(index=x) for i in range(5): pd.set_data("y" + str(i), jn(i, x)) # Create some line plots of some of the data plot1 = Plot(pd) plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red") plot1.plot(("index", "y3"), name="j_3", color="blue") # Tweak some of the plot properties plot1.title = "Inset Plot" plot1.padding = 50 # Attach some tools to the plot plot1.tools.append(PanTool(plot1)) zoom = ZoomTool(component=plot1, tool_mode="box", always_on=False) plot1.overlays.append(zoom) # Create a second scatter plot of one of the datasets, linking its # range to the first plot plot2 = Plot(pd, range2d=plot1.range2d, padding=50) plot2.plot(('index', 'y3'), type="scatter", color="blue", marker="circle") plot2.resizable = "" plot2.bounds = [250, 250] plot2.position = [550, 150] plot2.bgcolor = "white" plot2.border_visible = True plot2.unified_draw = True plot2.tools.append(PanTool(plot2)) plot2.tools.append(MoveTool(plot2, drag_button="right")) zoom = ZoomTool(component=plot2, tool_mode="box", always_on=False) plot2.overlays.append(zoom) # Create a container and add our plots container = OverlayPlotContainer() container.add(plot1) container.add(plot2) return container
def show_asymptotic(nvals, x, x_asym, jn_asym): """Illustrate an asymptotic relation. This function creates a matplotlib figure. Parameters ---------- nvals : list List of values of n (Bessel order) to evaluate. x : array Array of values where the function should be sampled. x_asym : function A function taking (n, x) arguments that should return the values of x where the desired asymptotic form is valid. jn_asym : function A function taking (n, x) arguments and returning an asymptotic form of the Bessel function Jn(x). Returns ------- fig : matplotlib figure object. A new figure containing all the plots. """ # Start by plotting the well-known J0 and J1, as well as J5: fig = plt.figure() # Now, compute and plot the asymptotic forms (valid for x>>n, where n is # the order). We must first find the valid range of x where at least x>n. for n in nvals: xa = x_asym(n, x) plt.plot(x, special.jn(n, x), label='$J_{%s}$' % n) plt.plot(xa, jn_asym(n, xa), '--', lw=3, label='$J_{%s}$ (asymp.)' % n) # Finish off the plot plt.legend(loc='best') # horizontal line at 0 to show x-axis, but after the legend plt.axhline(0) return fig
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 patch_impedance(w, l, r, h, f0): """ Compute an estimate of the patch impedance, for patch of width w and length l, inset feed at distance r, and height above ground h, at frequency f0. """ c0 = 299792458 l0 = c0 / f0 k0 = 2 * np.pi / l0 si = lambda x: quad(lambda t: np.sin(t) / t, 0, x)[0] x = k0 * w i1 = -2 + np.cos(x) + x * si(x) + np.sin(x) / x g1 = i1 / (120 * np.pi**2) g12 = 1 / (120 * np.pi**2) * quad( lambda th: (np.sin((k0 * w) / 2 * np.cos(th)) / np.cos(th))**2 * jn( 0, k0 * l * np.sin(th)) * np.sin(th)**3, 0, np.pi)[0] rin0 = 1 / (2 * (g1 + g12)) rin = rin0 * np.cos(np.pi * r / l)**2 print("l0={:.4f} g1={:.4e} g12={:.4e} rin0={:.2f} rin={:.2f}".format( l0, g1, g12, rin0, rin)) return rin
def hwhmIsotropicRotationalDiffusion(q, radius, DR): eisf = np.zeros(q.size) numberLorentz = 6 qisf = np.zeros((q.size, numberLorentz)) hwhm = np.zeros((q.size, numberLorentz)) jl = np.zeros((q.size, numberLorentz)) arg = q * radius idx = np.argwhere(arg == 0) for i in range(numberLorentz): jl[:,i] = np.sqrt(np.pi/2/arg) * jn(i+0.5, arg) #to solve warnings for arg=0 hwhm[:,i] = np.repeat(i * (i+1) * DR, q.size) if idx.size > 0: if i == 0: jl[idx,i] = 1.0 else: jl[idx,i] = 0.0 eisf = jl[:,0]**2 for i in range(1,numberLorentz): qisf[:,i] = (2*i+1) * jl[:,i]**2 return hwhm, eisf, qisf
def _set_secondhalo_params(self, r_h): ''' Precomputes some parameters ''' kh_npoints = 1e7 # Something like 1e7 self.kh_min = 1e-4 self.kh_max = 1e4 self.kh_bins = np.geomspace(self.kh_min, self.kh_max, kh_npoints, endpoint=True) Dang_h = self.cosmo.angular_diameter_distance( self.z).value * self.cosmo.h # in Mpc/h self.l_bins = self.kh_bins * (1 + self.z) * Dang_h theta = r_h / Dang_h self.J2 = sp.jn(2, self.l_bins * theta[:, np.newaxis]) return None #J2
def createSpeckle(self, kx, ky, amplitude, phase, source): xLoc = kx / (2 * np.pi) yLoc = ky / (2 * np.pi) distCoords = np.copy(self.imageCoords) distCoords[0] -= xLoc distCoords[1] -= yLoc distCoords = np.sqrt(distCoords[0]**2 + distCoords[1]**2) if np.any(distCoords == 0): distCoords[np.where(distCoords == 0)] = 0.01 speckle = amplitude * 2 * np.exp(phase * 1j) * spfun.jn( 1, np.pi * distCoords) / (np.pi * distCoords) if source == 'probe': self.probeSpeckleImage += speckle elif source == 'real': self.speckleFieldImage += speckle else: raise Exception('Specify speckle source: probe or real')
def _create_plot_component(): numpoints = 100 low = -5 high = 15.0 x = arange(low, high, (high - low) / numpoints) container = container_class(resizable="hv", bgcolor="lightgray", fill_padding=True, padding=10) # Plot some bessel functions value_range = None for i in range(10): y = jn(i, x) plot = create_line_plot((x, y), color=tuple(COLOR_PALETTE[i]), width=2.0, orientation=plot_orientation) plot.origin_axis_visible = True plot.origin = "top left" plot.padding_left = 10 plot.padding_right = 10 plot.border_visible = True plot.bgcolor = "white" if value_range is None: value_range = plot.value_mapper.range else: plot.value_range = value_range value_range.add(plot.value) if i % 2 == 1: plot.line_style = "dash" container.add(plot) container.padding_top = 50 container.overlays.append( PlotLabel("Bessel Functions in a Strip Plot", component=container, font="swiss 16", overlay_position="top")) return container
def oneD_Airy_log(x, amplitude, xo, F): ''' Model function. 1D log10(Airy). ''' r = (x - xo) * F nx = x.shape[0] maxmap = np.where(r == 0, np.ones(nx), np.zeros(nx)) nbmax = np.sum(maxmap) if nbmax == 1: indmax = np.argmax(maxmap) r[indmax] = 1. elif nbmax > 1: print('ERROR in oneD_Airy: several nulls') J = spe.jn(1, r) Airy = amplitude * (2 * J / r)**2 if nbmax == 1: Airy[indmax] = amplitude return np.log10(Airy)
def excitation_force(w, draft, radius, water_depth): """Excitation force on cylinder using Drake's first_order_excitation""" k = w**2 / 9.81 ka = k * radius kd = k * draft kh = k * water_depth rho = 1025 g = 9.81 # XXX check this! f1 = -1j * (jn(1, ka) - jnd(1, ka) * hankel2(1, ka) / hankel2d(1, ka)) #f1 = -1j * (jn(1, ka) - jnd(1, ka) * hankel1(1, ka) / hankel1d(1, ka)) M = (kd * sinh(kh - kd) + cosh(kh - kd) - cosh(kh)) / (k**2 * cosh(kh)) F = (-sinh(kh - kd) + sinh(kh)) / (k * cosh(kh)) zs = zeros_like(F, dtype=np.complex) X = np.c_[F, zs, zs, zs, M, zs] X *= (-rho * g * pi * radius) * 2 * f1[:, newaxis] return X
def squarehole_beam(x, y, rw, d): """ Intensity profile of a SquareHoleBeam which propagates along z and has its waist at the origin (0,0,0) Parameters ---------- x, y : These can be single floats, or can be array-like for full vectorization. rw : the width of squareholebeam d : The size of squarehole Returns ------- Intensity : The intensity of the squarehole beam. """ r = np.maximum(np.abs(x), np.abs(y)) k = 2.581 * 2 / rw a = k * np.abs(r - d / 2) + 1e-10 # add a small number to avoid divide 0 j = jn(1, a) intensity = 4 * np.power(j / a, 2) intensity[a > 3.83] = 0 return intensity
def IntKernel(self, j, z, ns, omega, k, r, mt): qSH2, qSH1, qPS2, qPS1, qPS0 = self.GetQ(j, z, ns, omega, k, mt) x = k * r j2 = special.jn(2, x) j2p = (special.jn(1, x) - special.jn(3, x)) / 2 j1 = special.jn(1, x) j1p = (special.jn(0, x) - special.jn(2, x)) / 2 j0 = special.jn(0, x) j0p = special.jn(-1, x) #print(self.GetQ(j,z,ns,omega,k,mt)) kr1 = 2 * qSH2 * j2 / r + qPS2[0] * k * j2p kr2 = 1 / r * qSH1 * j1 + qPS1[0] * k * j1p kr3 = -qPS2[0] * j0p * k kr4 = qPS0[0] * j0p * k ko1 = qSH2 * k * j2p + 2 / r * qPS2[0] * j2 ko2 = qSH1 * k * j1p + 1 / r * qPS1[0] * j1 kz1 = qPS2[1] * k * j2 kz2 = qPS1[1] * k * j1 kz3 = qPS0[1] * k * j0 kz4 = -qPS2[1] * k * j0 return (kr1, kr2, kr3, kr4, ko1, ko2, kz1, kz2, kz3, kz4)
def _create_plot_component(): # Create some x-y data series to plot x = linspace(-2.0, 10.0, 100) pd = ArrayPlotData(index=x) for i in range(5): pd.set_data("y" + str(i), jn(i, x)) # Create some line plots of some of the data plot1 = Plot(pd, title="Line Plot", padding=60, border_visible=True) plot1.legend.visible = True plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red") plot1.plot(("index", "y3"), name="j_3", color="blue") plot1.value_axis.title = "J0, J1, J2, J3" # Attach some tools to the plot plot1.tools.append(PanTool(plot1)) zoom = ZoomTool(component=plot1, tool_mode="box", always_on=False) plot1.overlays.append(zoom) # Create a second scatter plot of one of the datasets, linking its # range to the first plot plot2 = Plot(pd, range2d=plot1.range2d, title="Scatter plot", padding=60, border_visible=True) plot2.plot(('index', 'y3'), type="scatter", color="blue", marker="circle") # Configure the vertical axis: plot2.value_axis.title = "J3" plot2.value_axis.orientation = "right" plot2.value_axis.title_angle = 0.0 # instead of default 270 deg # Create a container and add our plots container = HPlotContainer() container.add(plot1) container.add(plot2) return container
def _create_plot_component(): # Create a GridContainer to hold all of our plots container = GridContainer(padding=20, fill_padding=True, bgcolor="lightgray", use_backbuffer=True, shape=(3, 3), spacing=(12, 12)) # Create the initial series of data x = linspace(-5, 15.0, 100) pd = ArrayPlotData(index=x) # Plot some bessel functions and add the plots to our container for i in range(9): pd.set_data("y" + str(i), jn(i, x)) plot = Plot(pd) plot.plot(("index", "y" + str(i)), color=tuple(COLOR_PALETTE[i]), line_width=2.0, bgcolor="white", border_visible=True) # Tweak some of the plot properties plot.border_width = 1 plot.padding = 10 # Set each plot's aspect ratio based on its position in the # 3x3 grid of plots. n, m = divmod(i, 3) plot.aspect_ratio = float(n + 1) / (m + 1) # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) # Add to the grid container container.add(plot) return container
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 _generate_pswf_quad(self, n, bandlimit, phi_approximate_error, lambda_max, epsilon): """ Generate Gaussian quadrature points and weights for 2D PSWF functions """ radial_quad_points, radial_quad_weights = self._generate_pswf_radial_quad( n, bandlimit, phi_approximate_error, lambda_max) num_angular_points = np.ceil(np.e * radial_quad_points * bandlimit / 2 - np.log(epsilon)).astype('int') + 1 for i in range(len(radial_quad_points)): ang_error_vec = np.absolute( jn(range(1, 2 * num_angular_points[i] + 1), bandlimit * radial_quad_points[i])) num_angular_points[i] = self._sum_minus_cumsum_smaller_eps( ang_error_vec, epsilon) if num_angular_points[i] % 2 == 1: num_angular_points[i] += 1 temp = 2 * np.pi / num_angular_points t = 2 quad_rule_radial_weights = temp * radial_quad_points * radial_quad_weights quad_rule_weights = np.repeat(quad_rule_radial_weights, repeats=num_angular_points) quad_rule_pts_r = np.repeat(radial_quad_points, repeats=(num_angular_points / t).astype('int')) quad_rule_pts_theta = np.concatenate([ temp[i] * np.arange(num_angular_points[i] / t) for i in range(len(radial_quad_points)) ]) pts_x = quad_rule_pts_r * np.cos(quad_rule_pts_theta) pts_y = quad_rule_pts_r * np.sin(quad_rule_pts_theta) return pts_x, pts_y, quad_rule_weights, radial_quad_points, quad_rule_radial_weights, num_angular_points
def _create_plot_component(): numpoints = 100 low = -5 high = 15.001 x = arange(low, high, (high - low) / numpoints) # Plot a bessel function y = jn(0, x) plot = create_line_plot((x, y), color=(0, 0, 1, 1), width=2.0, index_sort="ascending") value_range = plot.value_mapper.range plot.active_tool = RangeSelection(plot, left_button_selects=True) plot.overlays.append(RangeSelectionOverlay(component=plot)) plot.bgcolor = "white" plot.padding = 50 add_default_grids(plot) add_default_axes(plot) return plot
def _create_window(self): numpoints = 50 low = -5 high = 15.0 x = arange(low, high, (high - low) / numpoints) container = OverlayPlotContainer(bgcolor="lightgray") self.animated_plots = [] for i, color in enumerate(COLOR_PALETTE): animated_plot = AnimatedPlot(x, jn(i, x), color) container.add(animated_plot.plot) self.animated_plots.append(animated_plot) for i, a_plot in enumerate(self.animated_plots): a_plot.plot.position = [ 50 + (i % 3) * (PLOT_SIZE + 50), 50 + (i // 3) * (PLOT_SIZE + 50) ] self.timer = Timer(100.0, self.onTimer) self.container = container return Window(self, -1, component=container)
def sheet_beam(x, y, rw, length, d): """ Intensity profile of a sheetbeam which propagates along z, sheet along y Parameters ---------- x, y : These can be single floats, or can be array-like for full vectorization. rw : the width of sheet beam length : the length of sheet beam ,along y d : the distence between sheet beams Returns ------- Intensity : The intensity of the sheet beam. """ r = np.abs(x) k = 2.581 * 2 / rw a = k * np.abs(r - d / 2) + 1e-10 # add a small number to avoid divide 0 j = jn(1, a) intensity = 4 * np.power(j / a, 2) intensity[a > 3.83] = 0 intensity[np.abs(y) > length / 2] = 0 return intensity
def create_chaco_plot(parent): x = linspace(-2.0, 10.0, 100) pd = ArrayPlotData(index=x) for i in range(5): pd.set_data("y" + str(i), jn(i, x)) # Create some line plots of some of the data plot = Plot(pd, title="Line Plot", padding=50, border_visible=True) plot.legend.visible = True plot.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red") plot.plot(("index", "y3"), name="j_3", color="blue") # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) # This Window object bridges the Enable and Qt4 worlds, and handles events # and drawing. We can create whatever hierarchy of nested containers we # want, as long as the top-level item gets set as the .component attribute # of a Window. return Window(parent, -1, component=plot)