def cmpt_bunch_length_correction_factor(sigma_phi, noise_type): ''' This function computes the correction factor, C, due to the bunch length, sigma_phi, assuming a 2D gaussian longitudinal distribution. - phase_noise = True (False): computes C for phase (amplitude) noise case - sigma_phi: bunch length in radians at the CC frequency - Io, I2l: Modified Bessel functions of the first kind. - I2l: It converges to zero for larger orders. Therefore, a summation up to a large integer, here 10000 is used, gives us trustworthy resutls. Note: Possibility to compute the factors for a pillbox distribution which is the other extreme (email from Themis). ''' if noise_type == 'PN': Io = iv(0, sigma_phi ** 2) # The first argument is the order I2l_sum = 0 for order in range(2, 10000, 2): I2l_sum = I2l_sum + iv(order, sigma_phi ** 2) C = np.exp(-sigma_phi ** 2) * (Io + 2 * I2l_sum) else: I2ll_sum = 0 for order in range(0, 10000, 2): I2ll_sum = I2ll_sum + iv(order + 1, sigma_phi ** 2) C = np.exp(-sigma_phi ** 2) * I2ll_sum return C
def chebyshev_gaussian(self, A, a, order=10, mu=0.5, s=0.5): # NE Enhancement via Spectral Propagation print('Chebyshev Series -----------------') t1 = time.time() if order == 1: return a A = sp.eye(self.node_number) + A DA = preprocessing.normalize(A, norm='l1') L = sp.eye(self.node_number) - DA M = L - mu * sp.eye(self.node_number) Lx0 = a Lx1 = M.dot(a) Lx1 = 0.5 * M.dot(Lx1) - a conv = iv(0, s) * Lx0 conv -= 2 * iv(1, s) * Lx1 for i in range(2, order): Lx2 = M.dot(Lx1) Lx2 = (M.dot(Lx2) - 2 * Lx1) - Lx0 # Lx2 = 2*L.dot(Lx1) - Lx0 if i % 2 == 0: conv += 2 * iv(i, s) * Lx2 else: conv -= 2 * iv(i, s) * Lx2 Lx0 = Lx1 Lx1 = Lx2 del Lx2 print('Bessell time', i, time.time() - t1) mm = A.dot(a - conv) emb = self.get_embedding_dense(mm, self.dimension) return emb
def to_sigma(zes, azs): from scipy.special import iv az_sigma = np.sqrt(1 - iv(1, np.square(azs)) / iv(0, np.square(azs))) * 180 / np.pi ze_sigma = np.sqrt(1 - iv(1, np.square(zes)) / iv(0, np.square(zes))) * 180 / np.pi return ze_sigma, az_sigma
def __init__(self, mu, kappa): self._mu = mu self._kappa = kappa self.circular_mean = mu self.circular_var = 1 - iv(1, kappa) / iv(0, kappa) self.extent = (-numpy.pi, numpy.pi) self.name = 'vonmises'
def KL_guu(k, d): kld = k * ((sp.iv(d / 2.0 + 1.0, k) \ + sp.iv(d / 2.0, k) * d / (2.0 * k)) / sp.iv(d / 2.0, k) - d / (2.0 * k)) \ + d * np.log(k) / 2.0 - np.log(sp.iv(d / 2.0, k)) \ - sp.loggamma(d / 2 + 1) - d * np.log(2) / 2 return kld
def __init__(self, M, Betha): self.Betha = Betha alpha = M / 2 self.window = iv( 0, self.Betha * np.sqrt(1 - np.power( (np.arange(M) - alpha) / alpha, 2))) / iv(0, self.Betha)
def kaiserBesselCoeffs(windowSize, cutoff_f, sampling_f): coeffs = [] Np = (windowSize - 1) / 2 # Assume we always want a attenuation of 60dB at cutoff frequency alpha = 5.65326 Io_alpha = special.iv(0, alpha) # Calculate Kaiser-Bessel window coefficients window = [] for i in range(0, windowSize): val = alpha * math.sqrt(1 - math.pow((i - Np) / Np, 2)) window.append(special.iv(0, val) / Io_alpha) # Sinc function coefficients sinc = [] for i in range(0, windowSize): val = 2 * (i - Np) * cutoff_f / sampling_f sinc.append(SmoothingFilter.sinc(val)) # Multiple the coeffs together for i in range(0, windowSize): coeffs.append(window[i] * sinc[i]) return coeffs
def vonmises_modes(je, me, ji, mi, n=20): """ Computes Fourier modes of a given connectivity profile, built using Von Mises circular gaussian functions (see Marti, Rinzel, 2013) """ modes = np.arange(n) return je * special.iv(modes, me) / special.i0(me) - ji * special.iv( modes, mi) / special.i0(mi)
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 approximation(kn_mat, y, num_iter=10): n = kn_mat.shape[0] mode, g, p = None, None, None # mode, gradient and precision matrix kn_inv = np.linalg.inv(kn_mat) """Use Newton-Raphson method to find the mode""" for _ in range(num_iter): if mode is None: mode = np.random.normal(loc=0, scale=1, size=(2 * n, )) # initialization else: delta = np.linalg.solve(p, g) # alternative for inv(p).dot(g) mode += delta norm, bss0, bss1 = np.zeros(n), np.zeros(n), np.zeros(n) for i in range(n): norm[i] = np.sqrt(mode[i]**2 + mode[i + n]**2) bss0[i] = special.iv(0, norm[i]) # Bessel function of order 0 bss1[i] = special.iv(1, norm[i]) # Bessel function of order 1 g = get_oracle_gradient(mode, y, kn_inv, bss1 / (bss0 * norm)) if np.linalg.norm(g, ord=2) < 1e-5: break p = get_oracle_precision(mode, kn_inv, norm, bss0, bss1) return mode, g, p
def digital_filter(flow, fhigh, aGibbs, nterms): if fhigh < flow: fstop = float(1) else: fstop = float(0) # Computes Kaiser weights W(N,K) for digital filters # W = coef = returned array of Kaiser weights # N = value of N in W(N,K), ie number of terms # A = Size of gibbs phenomenon wiggles in -DB if aGibbs <= 21: alpha = 0. elif (aGibbs >= 50): alpha = 0.1102 * (aGibbs - 8.7) else: alpha = 0.5842 * (aGibbs - 21)**(0.4) + 0.07886 * (aGibbs - 21) arg = (np.arange(nterms) + 1) / nterms coef = special.iv(0, alpha * np.sqrt(1. - arg**2)) / special.iv(0, alpha) t = (np.arange(nterms) + 1) * np.pi coef = coef * (np.sin(t * fhigh) - np.sin(t * flow)) / t coef = np.concatenate((np.flip(coef), [fhigh - flow + fstop], coef)) return coef
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 rician_eqn(p, measured_mean, measured_variance): A, sigma = p nu = A**2/ (4.0 * sigma**2.0) b = (1+2.0*nu)*iv(0, nu) + 2.0*nu*iv(1,nu) mean = sigma *np.sqrt(np.pi/2.0)*np.exp(-nu)*(b) - measured_mean var = A + 2.0*sigma**2.0 - np.pi*sigma**2.0/2.0*np.exp(-2.0*nu)*b**2.0 - measured_variance return (mean, var)
def ChebyshevGaussian(A, a, order=5, mu=0.5, s=0.5): n = A.shape[0] logger.info('Chebyshev Series -----------------') t1 = time.time() if order == 1: return a A = sparse.eye(n) + A DA = preprocessing.normalize(A, norm='l1') L = sparse.eye(n) - DA M = L - mu * sparse.eye(n) Lx0 = a Lx1 = M.dot(a) Lx1 = 0.5 * M.dot(Lx1) - a conv = iv(0, s) * Lx0 conv -= 2 * iv(1, s) * Lx1 for i in range(2, order): Lx2 = M.dot(Lx1) Lx2 = (M.dot(Lx2) - 2 * Lx1) - Lx0 if i % 2 == 0: conv += 2 * iv(i, s) * Lx2 else: conv -= 2 * iv(i, s) * Lx2 Lx0 = Lx1 Lx1 = Lx2 del Lx2 logger.info('Bessell time %d %f', i, time.time() - t1) return A.dot(a - conv)
def _vmf_kld(k, d): return np.array([ (k * ((sp.iv(d / 2.0 + 1.0, k) + sp.iv(d / 2.0, k) * d / (2.0 * k)) / sp.iv(d / 2.0, k) - d / (2.0 * k)) + d * np.log(k) / 2.0 - np.log(sp.iv(d / 2.0, k)) - sp.loggamma(d / 2 + 1) - d * np.log(2) / 2).real ])
def magnetic_field(self, xy, field="secondary"): """Magnetic field due to a magnetic dipole over a half space The analytic expression is only valid for a source and receiver at the surface of the earth. For arbitrary source and receiver locations above the earth, use the layered solution. Parameters ---------- xy : numpy.ndarray receiver locations of shape (n_locations, 2) field : ("secondary", "total") Flag for the type of field to return. """ sig = self.sigma_hat # (n_freq, ) f = self.frequency w = 2*np.pi*f k = np.sqrt(-1j*w*mu_0*sig)[:, None] # This will get it to broadcast over locations dxy = xy[:, :2] - self.location[:2] r = np.linalg.norm(dxy, axis=-1) x = dxy[:, 0] y = dxy[:, 1] em_x = em_y = em_z = 0 src_x, src_y, src_z = self.orientation # Z component of source alpha = 1j*k*r/2. IK1 = iv(1, alpha)*kv(1, alpha) IK2 = iv(2, alpha)*kv(2, alpha) if src_z != 0.0: em_z += src_z*2.0/(k**2*r**5)*(9-(9+9*1j*k*r-4*k**2*r**2-1j*k**3*r**3)*np.exp(-1j*k*r)) Hr = (k**2/r)*(IK1 - IK2) angle = np.arctan2(y, x) em_x += src_z*np.cos(angle)*Hr em_y += src_z*np.sin(angle)*Hr if src_x != 0.0 or src_y != 0.0: # X component of source phi = 2/(k**2*r**4)*(3 + k**2*r**2 - (3 + 3j*k*r - k**2*r**2)*np.exp(-1j*k*r)) dphi_dr = 2/(k**2*r**5)*(-2*k**2*r**2 - 12 + (-1j*k**3*r**3 - 5*k**2*r**2 + 12j*k*r + 12)*np.exp(-1j*k*r)) if src_x != 0.0: em_x += src_x*(-1.0/r**3)*(y**2*phi + x**2*r*dphi_dr) em_y += src_x*(1.0/r**3)*x*y*(phi - r*dphi_dr) em_z -= src_x*(k**2*x/r**2)*(IK1 - IK2) # Y component of source if src_y != 0.0: em_x += src_y*(1.0/r**3)*x*y*(phi - r*dphi_dr) em_y += src_y*(-1.0/r**3)*(x**2*phi + y**2*r*dphi_dr) em_z -= src_y*(k**2*y/r**2)*(IK1 - IK2) if field == "secondary": # subtract out primary field from above mdotr = src_x*x + src_y*y# + m[2]*(z=0) em_x -= 3*x*mdotr/r**5 - src_x/r**3 em_y -= 3*y*mdotr/r**5 - src_y/r**3 em_z -= -src_z/r**3 # + 3*(z=0)*mdotr/r**5 return self.moment/(4*np.pi)*np.stack((em_x, em_y, em_z), axis=-1)
def update_jacobian(self): period, mscale, lscale, *_ = self.parameters.theta # index 0 dq20_lscale = self._tmp * lscale**(-3) dq20_lscale *= (iv(0, lscale**(-2)) - iv(1, lscale**(-2))) # index 1 --> J dq2J_lscale = self._tmp * lscale**(-3) * 2.0 dq2J_lscale *= ((1.0 + np.arange(1, self.J + 1) * lscale**2) * iv(range(1, self.J + 1), lscale**(-2)) - iv(range(0, self.J), lscale**(-2))) dq2_lscale = np.append(dq20_lscale, dq2J_lscale) if not np.all(np.isfinite(dq2_lscale)): raise ValueError("Derivative of spectral variance " "coefficients are not finite!") dq_lscale = 0.5 / self._q * dq2_lscale dq_mscale = 0.5 / self._q * self._q2 * 2.0 / mscale self.dA["period"] = self._kron / -period**2 self.dP0["lscale"][self._diag] = np.repeat(dq_lscale, 2) self.dP0["mscale"][self._diag] = np.repeat(dq_mscale, 2)
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 synth_3d_producer_hel(x, y, z, L, ns, ks, ABs): ''' Function used for generating a synthetic field. Should not be used in fitting routines. This function is not parallelized. ''' P = L/(2*np.pi) r = np.sqrt(x**2+y**2) phi = np.arctan2(y, x) model_r = np.zeros(r.shape) model_z = np.zeros(r.shape) model_phi = np.zeros(r.shape) for n in range(ns): print('n:', n) for k in range(ks): iv = special.iv(k, (n/P)*np.abs(r)) ivp = 0.5*(special.iv(-1+k, (n/P)*np.abs(r)) + special.iv(1+k, (n/P)*np.abs(r))) A = ABs[f'A_{n}_{k}'] B = ABs[f'B_{n}_{k}'] model_r += (n/P)*(ivp*(A*np.cos(n*z/P+k*phi) + B*np.sin(n*z/P+k*phi))) model_z += (n/P)*(iv*(-A*np.sin(n*z/P+k*phi) + B*np.cos(n*z/P+k*phi))) model_phi += (1.0/r)*(-k*iv*(A*np.sin(n*z/P+k*phi)-B*np.cos(n*z/P+k*phi))) model_x = model_r*np.cos(phi)-model_phi*np.sin(phi) model_y = model_r*np.sin(phi)+model_phi*np.cos(phi) return (model_x, model_y, model_z)
def Kzz(self): sum=np.sum(iv(self.n,self.l)*( self.zeta(self.n)*self.Zp(self.n) + self.zeta(-self.n)*self.Zp(-self.n) )) nn = 0 firstTerm = iv(nn,self.l)*( self.zeta(nn)*self.Zp(nn) + self.zeta(-nn)*self.Zp(-nn) ) return 1 - self.Bzz()*( sum + 0.5*firstTerm )
def hphi2(phi, mu, k1, k2, h1, h2): h1top = np.exp(k1 * np.cos(phi - mu)) h1bot = 2.0 * np.pi * special.iv(0, k1) h2top = np.exp(k2 * np.cos(phi - mu)) h2bot = 2.0 * np.pi * special.iv(0, k2) h = h1 * (h1top / h1bot) + h2 * (h2top / h2bot) return h
def _vmf_kld(k, d): tmp = (k * ((sp.iv(d / 2.0 + 1.0, k) + sp.iv(d / 2.0, k) * d / (2.0 * k)) / sp.iv(d / 2.0, k) - d / (2.0 * k)) \ + d * np.log(k) / 2.0 - np.log(sp.iv(d / 2.0, k)) \ - sp.loggamma(d / 2 + 1) - d * np.log(2) / 2).real if tmp != tmp: exit() return np.array([tmp])
def test_bessel(self): n = 1000 ds = math.pi/n ib0 = 0 ib1 = 0 x= 1.4 for j in range (0, n): tt = (j - 0.5)*ds ib0 += math.exp(x*math.cos(tt))*ds ib1 += +math.exp(x*math.cos(tt))*ds*math.cos(tt) ib0 = ib0/math.pi ib1 = ib1/math.pi kb0 = 0 kb1 = 0 ds = 2*math.pi/n for j in range(0, n): tt = (j - 0.5)*ds ch = (math.exp(tt) + math.exp(-tt))/2 kb1 += math.exp(-x*ch)*ch*ds kb0 += math.exp(-x*ch)*ds i0 = sp.iv(0, x) i1 = sp.iv(1, x) k0 = sp.kv(0, x) k1 = sp.kv(1, x) self.assertTrue(((abs(ib0 - i0)<0.005)&(abs(ib1 - i1)<0.005)&(abs(kb0 - k0)<0.005)&(abs(kb1 - k1)<0.005)), msg = 'Deltas I0, I1, K0, K1: ' + str(abs(i0 - ib0)) + ', ' + str(abs(i1 - ib1)) + ', ' + str(abs(k0 - kb0)) + ', ' + str(abs(k1 - kb1)))
def ecuacion_p4(z, N, ene): u = np.zeros(N) #Esto es para observar si la función es par. El código presenta un problema #pues sin(n*pi/2) donde n=par, ĺa función resulta ser demasiado pequeña #(de exponencias 10^{-16}), pero no es igual a 0, por lo que la función #presentara valores incorrectos en ciertos momentos. #Si el valor z es par, entonces hacemos que u[i]=0. if (z % 2 == 0): for i in range(0, N): u[i] = 0 #Si el numero es no par, entonces procedemos a calcular el código de forma #normal. else: for i in range(0, N): suma = 0 for n in range(1, ene, 2): valor = (n * math.pi) / 2 I0 = special.iv(0, valor * (i)) I0D = special.iv(0, valor) #La parte de arriba de la fracción. sumArriba = ((-1)**(n + 1)) * I0 #La parte de abajo de la fracción. sumAbajo = (n * I0D) #Suma final. suma += (sumArriba / sumAbajo) * np.sin((n * math.pi / 2) * z) #El valor de la función u. u[i] = (40 / math.pi) * suma return u
def _chebyshev_gaussian(self, A, a, order=10, mu=0.5, s=0.5): # NE Enhancement via Spectral Propagation if order == 1: return a A = sp.eye(self.num_node) + A DA = preprocessing.normalize(A, norm="l1") L = sp.eye(self.num_node) - DA M = L - mu * sp.eye(self.num_node) Lx0 = a Lx1 = M.dot(a) Lx1 = 0.5 * M.dot(Lx1) - a conv = iv(0, s) * Lx0 conv -= 2 * iv(1, s) * Lx1 for i in range(2, order): Lx2 = M.dot(Lx1) Lx2 = (M.dot(Lx2) - 2 * Lx1) - Lx0 # Lx2 = 2*L.dot(Lx1) - Lx0 if i % 2 == 0: conv += 2 * iv(i, s) * Lx2 else: conv -= 2 * iv(i, s) * Lx2 Lx0 = Lx1 Lx1 = Lx2 del Lx2 mm = A.dot(a - conv) emb = self._get_embedding_dense(mm, self.dimension) return emb
def update_continuous_dssm(self): period, mscale, lscale, _, decay, *_ = self.parameters.theta q2 = 2.0 * mscale**2 * np.exp(-(lscale**(-2))) * iv( range(self.J + 1), lscale**(-2)) q2[0] *= 0.5 q = np.sqrt(q2) dq2 = np.empty(int(self.J + 1)) dq2[:] = mscale**2 * lscale**(-3) * np.exp(-(lscale**(-2))) dq2[0] *= 2.0 * (iv(0, lscale**(-2)) - iv(1, lscale**(-2))) dq2[1:] *= -4.0 * iv(range(self.J), lscale**(-2)) + 4.0 * ( 1.0 + np.arange(1, self.J + 1) / (lscale**(-2))) * iv(range(1, self.J + 1), lscale**(-2)) if not np.all(np.isfinite(dq2)): raise ValueError( 'Derivative of spectral variance coefficients are not finite!') self.dA['period'][:] = self._kron / -(period**2) self.dA['decay'][:] = np.kron( np.eye(self.J + 1), np.array([[1.0 / (decay**2), 0.0], [0.0, 1.0 / (decay**2)]])) dql = 0.5 / q * dq2 dqm = 0.5 / q * q2 * 2.0 / mscale self.dP0['lscale'][self._diag] = np.repeat(dql, 2) self.dP0['mscale'][self._diag] = np.repeat(dqm, 2) self.dQ['lscale'][:] = self.dP0['lscale'] * 2.0**0.5 * decay**(-0.5) self.dQ['mscale'][:] = self.dP0['mscale'] * 2.0**0.5 * decay**(-0.5) self.dQ['decay'][:] = -0.5 * self.Q / decay
def __call__(self, A, a, order=10, mu=0.1, s=0.5): # NE Enhancement via Spectral Propagation print("Chebyshev Series -----------------") if order == 1: return a node_number = a.shape[0] A = sp.eye(node_number) + A DA = preprocessing.normalize(A, norm="l1") L = sp.eye(node_number) - DA M = L - mu * sp.eye(node_number) Lx0 = a Lx1 = M.dot(a) Lx1 = 0.5 * M.dot(Lx1) - a conv = iv(0, s) * Lx0 conv -= 2 * iv(1, s) * Lx1 for i in range(2, order): Lx2 = M.dot(Lx1) Lx2 = (M.dot(Lx2) - 2 * Lx1) - Lx0 # Lx2 = 2*L.dot(Lx1) - Lx0 if i % 2 == 0: conv += 2 * iv(i, s) * Lx2 else: conv -= 2 * iv(i, s) * Lx2 Lx0 = Lx1 Lx1 = Lx2 del Lx2 mm = A.dot(a - conv) return mm
def DeltaPs(s, rw, constantes, n, qw): (k, fi, pin, re, h, u, ct, B0) = constantes sn = math.sqrt(s/n) a = qw*u/(2*math.pi*k*h) b = s*sn*rw*(bessel.iv(1,sn*re)*bessel.kv(1,sn*rw)-bessel.iv(1,sn*rw)*bessel.kv(1,sn*re)) c = bessel.iv(0,sn*rw)*bessel.kv(1,sn*re)+bessel.iv(1,sn*re)*bessel.kv(0,sn*rw) return a*c/b
def Cyz(self): sum=np.sum(( iv(self.n,self.l) - ivp(self.n,self.l) )*( self.zeta(self.n)*self.Z(self.n) + self.zeta(-self.n)*self.Z(-self.n) )) firstTerm = ( iv(0,self.l) - ivp(0,self.l) )*( self.zeta(0)*self.Z(0) + self.zeta(0)*self.Z(0) ) return -self.Byz()*(sum + 0.5*firstTerm )
def fit_hypersphere(self, Z, kappa_prior = 0, mu_prior = None): """Fits the hypersphere using observations Z and von Mises-Fisher prior with parmeters kappa_prior (concentration parameter) and mu_prior (mean direction). If kappa_prior = 0, it is equivalent to a uniform prior.""" [n, d] = Z.shape if mu_prior is None : if kappa_prior == 0: mu_prior = np.zeros([d,1]) print("Uniform prior is used") else: raise ValueError("Please provide also a prior for mu") else: print("Von-Mises Fisher prior used with kappa =", kappa_prior,"and mu =",mu_prior) # Initialization c_em = np.mean(Z,axis=0) r_em = np.linalg.norm(Z-c_em,axis = 1).mean() sigma2_em = (1/d)*((np.linalg.norm(Z-c_em,axis = 1)**2).mean()-r_em**2) r_mem = np.zeros([self.n_iter+1]) c_mem = np.zeros([d,self.n_iter+1]) sigma2_mem = np.zeros([self.n_iter+1]) r_mem[0] = r_em c_mem[:,0] = c_em sigma2_mem[0] = sigma2_em for k in range(self.n_iter): # E-step delta_i = r_em*(Z-c_em).transpose()+sigma2_em*kappa_prior*mu_prior mu_i = delta_i/np.linalg.norm(delta_i,axis = 0) kappa_i = np.linalg.norm(delta_i,axis = 0)/sigma2_em alpha_i = iv(d/2,kappa_i)/iv(d/2-1,kappa_i)*mu_i f = np.r_[np.sum(alpha_i.transpose()*Z),np.sum(Z,axis=0)] alpha = np.sum(alpha_i, axis = 1) # M-step H_inv = 1/(n**2-np.inner(alpha,alpha))*np.r_[np.r_[n,-alpha].reshape(1,d+1),\ np.c_[-alpha,((n**2-np.inner(alpha,alpha))/n)*np.eye(d)+(1/n)*np.outer(alpha,alpha)]] sol_em = np.dot(H_inv,f) r_em = sol_em[0] c_em = sol_em[1:] M = np.sum(np.linalg.norm(Z,axis=1)**2)-np.dot(f,sol_em) sigma2_em = M/(n*d) r_mem[k] = r_em c_mem[:,k] = c_em sigma2_mem[k] = sigma2_em return r_em, c_em, sigma2_em, r_mem, c_mem, sigma2_mem
def constant_potential_twosphere_identical(phi01, phi02, r1, r2, R, kappa, epsilon): # From Carnie+Chan 1993 N = 20 # Number of terms in expansion qe = 1.60217646e-19 Na = 6.0221415e23 E_0 = 8.854187818e-12 cal2J = 4.184 index = arange(N, dtype=float) + 0.5 k1 = special.kv(index, kappa*r1)*sqrt(pi/(2*kappa*r1)) k2 = special.kv(index, kappa*r2)*sqrt(pi/(2*kappa*r2)) i1 = special.iv(index, kappa*r1)*sqrt(pi/(2*kappa*r1)) i2 = special.iv(index, kappa*r2)*sqrt(pi/(2*kappa*r2)) B = zeros((N,N), dtype=float) for n in range(N): for m in range(N): for nu in range(N): if n>=nu and m>=nu: g1 = gamma(n-nu+0.5) g2 = gamma(m-nu+0.5) g3 = gamma(nu+0.5) g4 = gamma(m+n-nu+1.5) f1 = factorial(n+m-nu) f2 = factorial(n-nu) f3 = factorial(m-nu) f4 = factorial(nu) Anm = g1*g2*g3*f1*(n+m-2*nu+0.5)/(pi*g4*f2*f3*f4) kB = special.kv(n+m-2*nu+0.5,kappa*R)*sqrt(pi/(2*kappa*R)) B[n,m] += Anm*kB M = zeros((N,N), float) for i in range(N): for j in range(N): M[i,j] = (2*i+1)*B[i,j]*i1[i] if i==j: M[i,j] += k1[i] RHS = zeros(N) RHS[0] = phi01 a = solve(M,RHS) a0 = a[0] U = 4*pi * ( -pi/2 * a0/phi01 * 1/sinh(kappa*r1) + kappa*r1 + kappa*r1/tanh(kappa*r1) ) # print 'E: %f'%U C0 = qe**2*Na*1e-3*1e10/(cal2J*E_0) C1 = r1*epsilon*phi01*phi01 E_inter = U*C1*C0 return E_inter
def test_phantom(): gtab = gen_gtab() DWI_clean = rfiw_phantom(gtab, snr=None) DWI, sigma = rfiw_phantom(gtab, snr=30) # To test without rician correction temp = (DWI_clean / sigma)**2 DWI_clean_wrc = (sigma * np.sqrt(np.pi / 2) * np.exp(-0.5 * temp) * ((1 + 0.5 * temp) * sps.iv(0, 0.25 * temp) + 0.5 * temp * sps.iv(1, 0.25 * temp))**2) DWI_den = localpca(DWI, sigma, patch_radius=3) rmse_den = np.sum(np.abs(DWI_clean - DWI_den)) / np.sum(np.abs(DWI_clean)) rmse_noisy = np.sum(np.abs(DWI_clean - DWI)) / np.sum(np.abs(DWI_clean)) rmse_den_wrc = np.sum(np.abs(DWI_clean_wrc - DWI_den) ) / np.sum(np.abs(DWI_clean_wrc)) rmse_noisy_wrc = np.sum(np.abs(DWI_clean_wrc - DWI)) / \ np.sum(np.abs(DWI_clean_wrc)) assert_(np.max(DWI_clean) / sigma < np.max(DWI_den) / sigma) assert_(np.max(DWI_den) / sigma < np.max(DWI) / sigma) assert_(rmse_den < rmse_noisy) assert_(rmse_den_wrc < rmse_noisy_wrc) # Check if the results of different PCA methods (eig, svd) are similar DWI_den_svd = localpca(DWI, sigma, pca_method='svd', patch_radius=3) assert_array_almost_equal(DWI_den, DWI_den_svd) assert_raises(ValueError, localpca, DWI, sigma, pca_method='empty') # Try this with a sigma volume, instead of a scalar sigma_vol = sigma * np.ones(DWI.shape[:-1]) mask = np.zeros_like(DWI, dtype=bool)[..., 0] mask[2:-2, 2:-2, 2:-2] = True DWI_den = localpca(DWI, sigma_vol, mask, patch_radius=3) DWI_clean_masked = DWI_clean.copy() DWI_clean_masked[~mask] = 0 DWI_masked = DWI.copy() DWI_masked[~mask] = 0 rmse_den = np.sum(np.abs(DWI_clean_masked - DWI_den)) / np.sum(np.abs( DWI_clean_masked)) rmse_noisy = np.sum(np.abs(DWI_clean_masked - DWI_masked)) / np.sum(np.abs( DWI_clean_masked)) DWI_clean_wrc_masked = DWI_clean_wrc.copy() DWI_clean_wrc_masked[~mask] = 0 rmse_den_wrc = np.sum(np.abs(DWI_clean_wrc_masked - DWI_den) ) / np.sum(np.abs(DWI_clean_wrc_masked)) rmse_noisy_wrc = np.sum(np.abs(DWI_clean_wrc_masked - DWI_masked)) / \ np.sum(np.abs(DWI_clean_wrc_masked)) assert_(np.max(DWI_clean) / sigma < np.max(DWI_den) / sigma) assert_(np.max(DWI_den) / sigma < np.max(DWI) / sigma) assert_(rmse_den < rmse_noisy) assert_(rmse_den_wrc < rmse_noisy_wrc)
def get_internal_energy(self, temperature, verbose=True): """Returns the internal energy (including the zero point energy), in eV, in the hindered translator and hindered rotor model at a specified temperature (K).""" from scipy.special import iv self.verbose = verbose write = self._vprint fmt = '%-15s%13.3f eV' write('Internal energy components at T = %.2f K:' % temperature) write('=' * 31) U = 0. write(fmt % ('E_pot', self.potentialenergy)) U += self.potentialenergy # Translational Energy T_t = units._k * temperature / (units._hplanck * self.freq_t) R_t = self.trans_barrier_energy / (units._hplanck * self.freq_t) dU_t = 2 * (-1. / 2 - 1. / T_t / (2 + 16 * R_t) + R_t / 2 / T_t - R_t / 2 / T_t * iv(1, R_t / 2 / T_t) / iv(0, R_t / 2 / T_t) + 1. / T_t / (np.exp(1. / T_t) - 1)) dU_t *= units.kB * temperature write(fmt % ('E_trans', dU_t)) U += dU_t # Rotational Energy T_r = units._k * temperature / (units._hplanck * self.freq_r) R_r = self.rot_barrier_energy / (units._hplanck * self.freq_r) dU_r = (-1. / 2 - 1. / T_r / (2 + 16 * R_r) + R_r / 2 / T_r - R_r / 2 / T_r * iv(1, R_r / 2 / T_r) / iv(0, R_r / 2 / T_r) + 1. / T_r / (np.exp(1. / T_r) - 1)) dU_r *= units.kB * temperature write(fmt % ('E_rot', dU_r)) U += dU_r # Vibrational Energy dU_v = self._vibrational_energy_contribution(temperature) write(fmt % ('E_vib', dU_v)) U += dU_v # Zero Point Energy dU_zpe = self.get_zero_point_energy() write(fmt % ('E_ZPE', dU_zpe)) U += dU_zpe write('-' * 31) write(fmt % ('U', U)) write('=' * 31) return U
def approxI1_I0(image): count = numpy.sum(image < 1.5) image_oct = 8 * image Mn = 1. - 3. / image_oct - 15. / 2. / (image_oct ** 2) - (3. * 5. * 21.) / 6. / (image_oct ** 3) Md = 1. + 1. / image_oct + 9. / 2. / (image_oct ** 2) + (25. * 9.) / 6. / (image_oct ** 3) M = Mn / Md if (count > 1): K = numpy.flatnonzero(image < 1.5) M.ravel()[K] = special.iv(1, image.ravel()[K]) / special.iv(0, image.ravel()[K]) K = numpy.flatnonzero(image == 0) M.ravel()[K] = 0 return M
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 MMSE(v, snr_post, Y): g = 0.8862269254527579 # gamma(1.5) output = np.zeros(len(v)) for idx in range(len(Y)): if v[idx] > 10: output[idx] = v[idx] * Y[idx] / snr_post[idx] else: output[idx] = g * ( np.sqrt(v[idx]) / (snr_post[idx] + eps)) *\ np.exp(-v[idx] / 2.) *\ ((1 + v[idx]) * iv(0., v[idx] / 2.) +\ v[idx] * iv(1., v[idx] / 2.)) * Y[idx] return output
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 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 __delta(self, nu, u1r1, u2r1, s1, s2, s3, n1sq, n2sq, n3sq): """s3 is sign of Delta""" if s1 < 0: f = ivp(nu, u1r1) / (iv(nu, u1r1) * u1r1) # c else: jnnuu1r1 = jn(nu, u1r1) if jnnuu1r1 == 0: # Avoid zero division error return float("inf") f = jvp(nu, u1r1) / (jnnuu1r1 * u1r1) # a b d if s1 == s2: # b d kappa1 = -(n1sq + n2sq) * f / n2sq kappa2 = (n1sq * f * f / n2sq - nu**2 * n3sq / n2sq * (1 / u1r1**2 - 1 / u2r1**2)**2) else: # a c kappa1 = (n1sq + n2sq) * f / n2sq kappa2 = (n1sq * f * f / n2sq - nu**2 * n3sq / n2sq * (1 / u1r1**2 + 1 / u2r1**2)**2) d = kappa1**2 - 4 * kappa2 if d < 0: return numpy.nan return u2r1 * (nu / u2r1**2 + (kappa1 + s3 * sqrt(d)) * 0.5)
def convolve1(fn,r,sig,rmax): r = np.asarray(r) if r.ndim == 0: r.resize((1)) nr = 200 rp = np.zeros(shape=(r.shape[0],nr)) rp[:] = np.linspace(0,rmax,nr) rp = rp.T dr = rmax/float(nr) sig2 = sig*sig x = r*rp/(sig2) j = spfn.iv(0,x) fnrp = fn(np.ravel(rp)) fnrp = fnrp.reshape(j.shape) # plt.figure() # plt.plot(np.degrees(rp[:,50]),x[:,50]) # plt.figure() # plt.plot(np.degrees(rp[:,50]), # rp[:,50]*j[:,50]*fnrp[:,50]* # np.exp(-(r[50]**2+rp[:,50]**2)/(2*sig2))) # plt.show() return np.sum(rp*j*fnrp/(sig2)*np.exp(-(r*r+rp*rp)/(2*sig2)),axis=0)*dr
def vmlogpdf(alpha, thetahat=0.0, kappa=1.0): """Computes the circular Von Mises log-PDF with preferred direction thetahat and concentration kappa at each of the angles in alpha. The vmpdf is given by f(phi) = (1/(2pi*I0(kappa))*exp(kappa*cos(phi-thetahat) Parameters ---------- alpha : np.ndarray The array of angles thetahat : number The preferred direction kappa : number Concentration at each of the angles in alpha Returns ------- out : np.ndarray The Von Mises log-PDF for alpha References ---------- Berens, P. (2009). CircStat: A MATLAB Toolbox for Circular Statistics. Journal of Statistical Software, 31(10). Available from http://www.jstatsoft.org/v31/i10 """ C = -np.log(2 * np.pi * iv(0, kappa)) p = C + (kappa * np.cos(alpha - thetahat)) return p
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 compute_fisher_information_theoretical(self, sigma=None): ''' Compute the theoretical, large N limit estimate of the Fisher Information This one assumes a diagonal covariance matrix, wrong for the complete model. ''' assert self.R <= 2, "Not implemented for R>2" if self.population_code_type == 'conjunctive': rho = 1. / (4 * np.pi**2 / (self.M)) # rho = 1./(2*np.pi/(self.M)) elif self.population_code_type == 'feature': # M/2 neuron per 2pi dimension. print "This looks wrong, doesnt fit at all" rho = 1. / (np.pi**2. / self.M**2.) else: print 'Fisher information not defined for population type ' + self.population_code_type return 0 kappa1 = self.rc_scale[0] kappa2 = self.rc_scale[1] return kappa1**2. * rho * ( scsp.i0(2 * kappa1) - scsp.iv(2, 2 * kappa1) ) * scsp.i0(2 * kappa2) / ( sigma**2. * 8 * np.pi**2. * scsp.i0(kappa1)**2. * scsp.i0(kappa2)**2.)
def mag_field_function(a,b,z,cart=False): '''give r,phi,z, (or x,y,z) and return br,bphi,bz (or bx,by,bz)''' if cart: r = np.sqrt(a**2+b**2) phi = np.arctan2(b,a) else: r = a phi = b iv = np.empty((ns,ms)) ivp = np.empty((ns,ms)) for n in range(ns): iv[n,:] = special.iv(n,kms[n,:]*np.abs(r)) ivp[n,:] = special.ivp(n,kms[n,:]*np.abs(r)) br = 0.0 bphi = 0.0 bz = 0.0 for n in range(ns): for m in range(ms): br += (Cs[n]*np.cos(n*phi)+Ds[n]*np.sin(n*phi))*ivp[n][m]*kms[n][m]*(As[n][m]*np.cos(kms[n][m]*z) + Bs[n][m]*np.sin(-kms[n][m]*z)) if abs(r)>1e-10: bphi += n*(-Cs[n]*np.sin(n*phi)+Ds[n]*np.cos(n*phi))*(1/abs(r))*iv[n][m]*(As[n][m]*np.cos(kms[n][m]*z) + Bs[n][m]*np.sin(-kms[n][m]*z)) bz += -(Cs[n]*np.cos(n*phi)+Ds[n]*np.sin(n*phi))*iv[n][m]*kms[n][m]*(As[n][m]*np.sin(kms[n][m]*z) + Bs[n][m]*np.cos(-kms[n][m]*z)) if cart: bx = br*np.cos(phi)-bphi*np.sin(phi) by = br*np.sin(phi)+bphi*np.cos(phi) return (bx,by,bz) else: return (br,bphi,bz)
def modifiedRician(I, Ic, Is): ''' MR pdf(I) = 1/Is * exp(-(I+Ic)/Is) * I0(2*sqrt(I*Ic)/Is) mean = Ic + Is variance = Is^2 + 2*Ic*Is ''' mr = 1.0/Is * np.exp(-1.0*(I+Ic)/Is)* special.iv(0,2.0*np.sqrt(I*Ic)/Is) return mr
def __init__(self): self.v=random.uniform(0.2,5) self.s=1 self.x=[] self.y=[] for i in np.arange(0,10,0.01): self.x.append(i) f=i*exp(-((i**2)+(self.v**2))/(2*self.s**2))*iv(0,(i*self.v)/(self.s**2))/(self.s**2) self.y.append(f)
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 Fj(x,t): floor = 1E-4 tmp = 3.0*M*M*M*nu/(l0*l0*l0*t) tmp = tmp*x**(.25)*exp(-(1+x*x)/t)*iv(.25,2*x/t) + floor for i in range(len(tmp)): if( isnan(tmp[i]) ): tmp[i] = floor return tmp
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 marginalizedPulsarPhaseLike(psr, theta, phi, phase, inc, psi, freq, h, maximize=False): """ Compute the log-likelihood marginalized over pulsar phases @param psr: List of pulsar object instances @param theta: GW polar angle [radian] @param phi: GW azimuthal angle [radian] @param phase: Initial GW phase [radian] @param inc: GW inclination angle [radian] @param psi: GW polarization angle [radian] @param freq: GW initial frequency [Hz] @param h: GW strain @param maximize: Option to maximize over pulsar phases instead of marginalize """ # get number of pulsars npsr = len(psr) # get c and d c = np.cos(phase) d = np.sin(phase) # construct xi = M**5/3/D and omega xi = 0.25 * np.sqrt(5/2) * (np.pi*freq)**(-2/3) * h omega = np.pi*freq lnlike = 0 for ct, pp in enumerate(psr): # compute relevant inner products cip = np.dot(np.cos(2*omega*pp.toas), np.dot(pp.invCov, pp.res)) sip = np.dot(np.sin(2*omega*pp.toas), np.dot(pp.invCov, pp.res)) N = np.dot(np.cos(2*omega*pp.toas), np.dot(pp.invCov, np.cos(2*omega*pp.toas))) # compute fplus and fcross fplus, fcross, cosMu = PALutils.createAntennaPatternFuncs(pp, theta, phi) # mind you p's and q's p = (1+np.cos(inc)**2) * (fplus*np.cos(2*psi) + fcross*np.sin(2*psi)) q = 2*np.cos(inc) * (fplus*np.sin(2*psi) - fcross*np.cos(2*psi)) # construct X Y and Z X = -xi/omega**(1/3) * (p*sip + q*cip - 0.5*xi/omega**(1/3)*N*c*(p**2+q**2)) Y = -xi/omega**(1/3) * (q*sip - p*cip - 0.5*xi/omega**(1/3)*N*d*(p**2+q**2)) Z = xi/omega**(1/3) * ((p*c+q*d)*sip - (p*d-q*c)*cip \ -0.5*xi/omega**(1/3)*N*(p**2+q**2)) # add to log-likelihood #print X, Y if maximize: lnlike += Z + np.sqrt(X**2 + Y**2) else: lnlike += Z + np.log(ss.iv(0, np.sqrt(X**2 + Y**2))) return lnlike
def K1RI1r(self, rin, iaq, ipint): r = rin / self.aq.lab2[iaq, ipint] R = self.R / self.aq.lab2[iaq, ipint] if np.isinf(self.i1R[iaq, ipint]).any(): rv = np.sqrt(1 / (4 * r * R)) * np.exp(r - R) * \ (1 + 3 / (8 * R) - 15 / (128 * R ** 2) + 315 / (3072 * R ** 3)) * \ (1 - 3 / (8 * r) - 15 / (128 * r ** 2) - 315 / (3072 * r ** 3)) else: rv = self.k1R[iaq, ipint] * iv(1, r) return rv
def sampleVMF(mu, tau, n): edmax = tau/(4.0*np.pi*spec.iv(0, tau))*np.exp(tau) #rejection sample from uniform tmpsamps = -np.pi+2.0*np.pi*np.random.rand(n) heights = np.random.rand(n)*edmax hits = tau/(4.0*np.pi*spec.iv(0, tau))*np.exp(tau*np.cos(tmpsamps)) > heights nhits = np.sum(hits.astype(int)) samps = tmpsamps[hits == True] n -= nhits while (n > 0): tmpsamps = -np.pi+2.0*np.pi*np.random.rand(n) heights = np.random.rand(n)*edmax hits = tau/(4.0*np.pi*spec.iv(0, tau))*np.exp(tau*np.cos(tmpsamps)) > heights nhits = np.sum(hits.astype(int)) samps = np.append(samps, tmpsamps[hits == True]) n -= nhits vecx = np.cos(samps)*mu[0] - np.sin(samps)*mu[1] vecy = np.sin(samps)*mu[0] + np.cos(samps)*mu[1] return np.vstack((vecx, vecy))
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 golovin(v,t,n0,v0,b): x = v/v0 T = b*n0*v0*t tau = 1-np.exp(-T) bessel = special.iv(1,2*x*np.sqrt(tau)) result = 0. if(not np.isinf(bessel)): result = n0/v0 * bessel * (1-tau) * np.exp(-x*(tau+1)) / x / np.sqrt(tau) if (np.isnan(result)): result = 0. return result
def n(t, x): # analytic solution if t == 0 or x == 0: return 0 else: ratio = exp(-t - 2 * x + x * exp(-t)) / (x * sqrt(1 - exp(-t))) if ratio == 0: return 0 else: bessel = iv(1, 2 * x * sqrt(1 - exp(-t))) result = ratio * bessel return result