コード例 #1
0
ファイル: stepindex.py プロジェクト: cbrunet/fibermodes
    def tetmConstants(self, ri, ro, neff, wl, EH, c, idx):
        a = numpy.empty((2, 2))
        n = self.maxIndex(wl)
        u = self.u(ro, neff, wl)
        urp = self.u(ri, neff, wl)

        if neff < n:
            B1 = j0(u)
            B2 = y0(u)
            F1 = j0(urp) / B1
            F2 = y0(urp) / B2
            F3 = -j1(urp) / B1
            F4 = -y1(urp) / B2
            c1 = wl.k0 * ro / u
        else:
            B1 = i0(u)
            B2 = k0(u)
            F1 = i0(urp) / B1
            F2 = k0(urp) / B2
            F3 = i1(urp) / B1
            F4 = -k1(urp) / B2
            c1 = -wl.k0 * ro / u
        c3 = c * c1

        a[0, 0] = F1
        a[0, 1] = F2
        a[1, 0] = F3 * c3
        a[1, 1] = F4 * c3

        return numpy.linalg.solve(a, EH.take(idx))
コード例 #2
0
def cutoffTE(b):
    # EXP: 2.4220557071361126
    a = rho * b
    return (i0(u1 * a) *
            (j0(u2 * b) * yn(2, u2 * a) - y0(u2 * b) * jn(2, u2 * a)) -
            iv(2, u1 * a) *
            (j0(u2 * a) * y0(u2 * b) - y0(u2 * a) * j0(u2 * b)))
コード例 #3
0
def qd(rd, td):
    
    from scipy.special import j1
    from scipy.special import j0
    import math
    
    if td < 0.01:
        return 2 * td ** 0.5 / 3.14159265359 ** 0.5
    else:
        b = [1.129552, 1.160436, 0.2642821, 0.01131791, 0.5900113, 0.04589742, 1.0, 0.5002034, 1.50, 1.979139]
        qd_inf = (b[0] * td ** b[7] + b[1] * td + b[2] * td ** b[8] + b[3] * td ** b[9]) / (
                    b[4] * td ** b[7] + b[5] * td + b[6])
        if rd > 100:
            return qd_inf

        b1 = [-0.00222107, -0.627638, 6.277915, -2.734405, 1.2708, -1.100417]
        b2 = [-0.00796608, -1.85408, 18.71169, -2.758326, 4.829162, -1.009021]

        alpha1 = beta(b1, rd)
        alpha2 = beta(b2, rd)
        J0Alpha1 = j0(alpha1)
        J0Alpha2 = j0(alpha2)
        J1Alpha1rd = j1(alpha1 * rd)
        J1Alpha2rd = j1(alpha2 * rd)

        qd_fin = (rd ** 2 - 1) / 2 - (2 * math.exp(-alpha1 ** 2 * td) * J1Alpha1rd ** 2) / (
                    alpha1 ** 2 * (J0Alpha1 ** 2 - J1Alpha1rd ** 2)) - (
                             2 * math.exp(-alpha2 ** 2 * td) * J1Alpha2rd ** 2) / (
                             alpha2 ** 2 * (J0Alpha2 ** 2 - J1Alpha2rd ** 2))
    return min(qd_inf, qd_fin)
コード例 #4
0
def main(L, N):

    A = 3.1926
    a = 180  # [m]
    H = a / 3  # [m]
    X0 = X = linspace(-a, a, N)  # [m]
    Y0 = Y = -H * 1 / 6.04844 * (sp.j0(A) * sp.i0(A * X / a) -
                                 sp.i0(A) * sp.j0(A * X / a))
    if L > 0:
        X = insert(X, 0, -L)
        X = append(X, L)
        Y = insert(Y, 0, 0)
        Y = append(Y, 0)
    h = 10

    # writing CSV
    g = column_stack((0 * X, X, Y))
    f = open('HillShape_X.csv', 'wb')
    csvWriter = csv.writer(f, delimiter=',')
    csvWriter.writerow(X)
    f.close()

    f = open('HillShape_Y.csv', 'wb')
    csvWriter = csv.writer(f, delimiter=',')
    csvWriter.writerow(Y)
    f.close()
    return X, Y
コード例 #5
0
def gradient(pos_previous, pos_current):
    #Calculate the concentration C
    cos_sum = 1 + 2 * (np.cos(pos_previous[:, 1] -
                              pos_current[1])) * np.exp(-k3)
    for i in range(2, 41):
        cos_sum += 2 * np.cos(
            i * (pos_previous[:, 1] - pos_current[1])) * np.exp(-k3 * i**2)
    sin_sum = -2 * (np.sin(pos_previous[:, 1] - pos_current[1])) * np.exp(-k3)
    for i in range(2, 41):
        sin_sum += -2 * i * np.sin(
            i * (pos_previous[:, 1] - pos_current[1])) * np.exp(-k3 * i**2)
    C = sp.j0(pos_previous[:, 0] - pos_current[0]) * cos_sum * np.exp(-(
        (pos_previous[:, 2] - pos_current[2])**2) / k5)

    # Calculate the gradients
    grad = threeCol
    # gradient in r direction
    posx = pos_previous[:, 0] - pos_current[0]
    Grad_2 = -1 * sp.jv(1, posx)
    grad[0] = np.sum(Grad_2)
    # gradient in theta direction
    grad[1] = np.sum(
        (sp.j0(pos_previous[:, 0] - pos_current[0]) / rad) * sin_sum *
        np.exp(-((pos_previous[:, 2] - pos_current[2])**2) / k5))
    # gradient in z direction
    grad[2] = np.sum(C * (-2) * (pos_previous[:, 1] - pos_current[1]) / k5)
    return grad
コード例 #6
0
def cutoffTM(b):
    # EXP: 2.604335468618898
    a = rho * b
    return (n22 / n12 *
            (j0(u2 * b) * yn(2, u2 * a) - y0(u2 * b) * jn(2, u2 * a)) +
            (n22 / n12 - 1 + iv(2, u1 * a) / i0(u1 * a)) *
            (j0(u2 * b) * y0(u2 * a) - y0(u2 * b) * j0(u2 * a)))
コード例 #7
0
ファイル: eigenvalues.py プロジェクト: orvedahl/Tayler-Spruit
def exact(k, R1, R2, derivs):

    if (derivs):
        # Bessel evaluated at R1
        J0_1 = special.j0(k * R1)
        Y0_1 = special.y0(k * R1)
        J1_1 = special.j1(k * R1)
        Y1_1 = special.y1(k * R1)

        # Bessel evaluated at R2
        J0_2 = special.j0(k * R2)
        Y0_2 = special.y0(k * R2)
        J1_2 = special.j1(k * R2)
        Y1_2 = special.y1(k * R2)

        #
        # d Z1(k r)/dr = k*Z0(k r) - Z1(k r) / r
        #
        Jprime_1 = k * J0_1 - J1_1 / R1
        Jprime_2 = k * J0_2 - J1_2 / R2
        Yprime_1 = k * Y0_1 - Y1_1 / R1
        Yprime_2 = k * Y0_2 - Y1_2 / R2

    else:
        Jprime_1 = special.jvp(1, k * R1, 1)
        Jprime_2 = special.jvp(1, k * R2, 1)
        Yprime_1 = special.yvp(1, k * R1, 1)
        Yprime_2 = special.yvp(1, k * R2, 1)

    # F(k r) = J'_m(kr R1) * Y'_m(kr R2) - J'_m(kr R2) * Y'_m(kr R1) = 0
    return Jprime_1 * Yprime_2 - Jprime_2 * Yprime_1
コード例 #8
0
ファイル: stepindex.py プロジェクト: timhellwig/fibermodes
    def tetmConstants(self, ri, ro, neff, wl, EH, c, idx):
        a = numpy.empty((2, 2))
        n = self.maxIndex(wl)
        u = self.u(ro, neff, wl)
        urp = self.u(ri, neff, wl)

        if neff < n:
            B1 = j0(u)
            B2 = y0(u)
            F1 = j0(urp) / B1
            F2 = y0(urp) / B2
            F3 = -j1(urp) / B1
            F4 = -y1(urp) / B2
            c1 = wl.k0 * ro / u
        else:
            B1 = i0(u)
            B2 = k0(u)
            F1 = i0(urp) / B1
            F2 = k0(urp) / B2
            F3 = i1(urp) / B1
            F4 = -k1(urp) / B2
            c1 = -wl.k0 * ro / u
        c3 = c * c1

        a[0, 0] = F1
        a[0, 1] = F2
        a[1, 0] = F3 * c3
        a[1, 1] = F4 * c3

        return numpy.linalg.solve(a, EH.take(idx))
コード例 #9
0
ファイル: g_functions.py プロジェクト: cgq-qgc/pygld
def g_int_lamarche(x, tt, Rt, rt, kt, gam, v):
    # tt = Fourier number
    # re = outer radius of the equivalent tube for concentric cylinders
    # rb = borehole radius
    # ks = soil thermal conductivity
    # kg = grout thermal conductivity
    # als = soil thermal diffusivity
    # alg = grout thermal diffusivity

    zeta1 = (1 - v * Rt * x**2) * y1(x) - v * x * y0(x)
    zeta2 = (1 - v * Rt * x**2) * j1(x) - v * x * j0(x)

    psi = (zeta2 * (j0(x * rt * gam) * y1(x * rt) -
                    j1(x * rt * gam) * y0(x * rt) * kt * gam) - zeta1 *
           (j0(x * rt * gam) * j1(x * rt) -
            j1(x * rt * gam) * j0(x * rt) * kt * gam))

    phi = (zeta1 * (y0(x * rt * gam) * j1(x * rt) -
                    y1(x * rt * gam) * j0(x * rt) * kt * gam) - zeta2 *
           (y0(x * rt * gam) * y1(x * rt) -
            y1(x * rt * gam) * y0(x * rt) * kt * gam))

    I = (1 - exp(-x**2 * tt)) / (x**5 * (phi**2 + psi**2))

    return I
コード例 #10
0
def u(r, t, eps, colslag, date=None):
    if date != None:
        updateParameret_array(date)

    numerator = (parameter_array['l'] * parameter_array['betta'] *
                 parameter_array['P'])
    denominator = (50 * sp.pi * parameter_array['alf'] *
                   parameter_array['a']**2)
    all = numerator / denominator
    x = ((-2 * parameter_array['alf'] * t) /
         (parameter_array['c'] * parameter_array['l']))
    u = all * (1 - np.exp(x))
    if (colslag == 0):
        if dataChanged[0] == 1:

            N = analitic_eps(eps)
            for i in np.arange(1, N, 1):
                u += An(i, t) * spc.j0((bessel0[i] * r) / parameter_array['R'])

        else:
            N = array_norm_N[str(eps)]

            for i in np.arange(1, N, 1):
                u += An(i, t) * spc.j0((bessel0[i] * r) / parameter_array['R'])

    else:
        for i in np.arange(1, colslag, 1):
            u += An(i, t) * spc.j0((bessel0[i] * r) / parameter_array['R'])

    return u
コード例 #11
0
def radialConvolve(r, f, sigma, fk=100, fr=1):
    from scipy.special import j0
    import special_functions as sf
    #mod = splrep(r,f,s=0,k=1)
    #norm = splint(r[0],r[-1],mod)
    r0 = r.copy()
    f0 = f.copy()
    r = r / sigma
    sigma = 1.

    kmin = numpy.log10(r.max()) * -1
    kmax = numpy.log10(r.min()) * -1
    k = numpy.logspace(kmin, kmax, r.size * fr)
    a = k * 0.
    for i in range(k.size):
        bessel = j0(r * k[i])
        A = splrep(r, r * bessel * f, s=0, k=1)
        a[i] = splint(0., r[-1], A)

    a0 = (2. * pi * sigma**2)**-0.5
    b = a0 * sigma * numpy.exp(-0.5 * k**2 * sigma**2)

    ab = a * b
    mod = splrep(k, ab, s=0, k=1)
    k = numpy.logspace(kmin, kmax, r.size * fk)
    ab = splev(k, mod)
    result = r * 0.
    for i in range(r.size):
        bessel = j0(k * r[i])
        mod = splrep(k, k * bessel * ab, s=0, k=1)
        result[i] = 2 * pi * splint(0., k[-1], mod)

    return result
コード例 #12
0
    def get_three_parts(self):

        # get rid of x1 as it's not needed
        x1 = -1.

        if self.physics.D == 3:

            A, _, _, x2 = self.get_coeff_three_part_3D(full_output=True)

            if x2 is None:
                # the search for the three-part coefficients did not converge:
                # the three-part solution may not be appropriate
                three_parts_lower = False
                three_parts_upper = False

            else:

                # tests for validity of three-part solution
                if self.physics.coupling == 'linear' and self.high_density:
                    three_parts_lower = (
                        self.phi_c + A * np.sin(self.x0) / self.x0 > 1. / 3.)
                    three_parts_upper = (
                        5. / 6. > self.phi_c + A * np.sin(self.x0) / self.x0)

                else:
                    three_parts_lower = (
                        self.phi_c +
                        A * np.sinh(self.nu_eff * self.x0) / self.x0 > 1. / 3.)
                    three_parts_upper = (
                        5. / 6. > self.phi_c +
                        A * np.sinh(self.nu_eff * self.x0) / self.x0)

        elif self.physics.D == 2:

            A, _, _, x2 = self.get_coeff_three_part_2D(full_output=True)

            if x2 is None:
                # the search for the three-part coefficients did not converge:
                # the three-part solution may not be appropriate
                three_parts_lower = False
                three_parts_upper = False

            else:

                if self.physics.coupling == 'linear' and self.high_density:
                    three_parts_lower = (self.phi_c + A * j0(self.x0) >
                                         1. / 3.)
                    three_parts_upper = (5. / 6. >
                                         self.phi_c + A * j0(self.x0))

                else:
                    three_parts_lower = (
                        self.phi_c + A * i0(self.nu_eff * self.x0) > 1. / 3.)
                    three_parts_upper = (
                        5. / 6. > self.phi_c + A * i0(self.nu_eff * self.x0))

        three_parts = three_parts_lower and three_parts_upper

        return x1, x2, three_parts
コード例 #13
0
ファイル: sensor.py プロジェクト: ronenroi/pyshdom
    def __init__(self):
        from scipy.special import j0, jv

        self.full_well = 200000
        # Table 5 of [1]
        bandwidths = [45, 46, 47]
        optical_throughput = [0.516, 0.605, 0.602]
        quantum_efficiencies = [0.4, 0.35, 0.13]
        self.polarized_bands = [0.47, 0.66, 0.862]

        num_subframes = 23
        p = np.linspace(0.0, 1.0, num_subframes + 1)
        p1 = p[0:-1]
        p2 = p[1:]
        x = 0.5 * (p1 + p2 - 1)
        delta0_list = [4.472, 3.081, 2.284]
        r = 0.0
        eta = 0.009

        self.p, self.correlation, self.w, self.reflectance_to_electrons = dict(
        ), dict(), dict(), dict()
        for wavelength, delta0, ot, qe, bw in zip(self.polarized_bands,
                                                  delta0_list,
                                                  optical_throughput,
                                                  quantum_efficiencies,
                                                  bandwidths):

            # Define z'(x_n) (Eq. 8in [1])
            z_idx = np.pi * x != eta
            z = np.full_like(x, r)
            z[z_idx] = -2 * delta0 * np.sin(np.pi * x - eta)[z_idx] * np.sqrt(
                1 + r**2 / np.tan(np.pi * x - eta)[z_idx])

            # Define s_n (Eq. 9 in [1])
            s = np.ones(shape=(num_subframes))
            s_idx = z_idx if r == 0 else np.ones_like(x, dtype=np.bool)
            s[s_idx] = (np.tan(np.pi * x - eta)**2 -
                        r)[s_idx] / (np.tan(np.pi * x - eta)**2 + r)[s_idx]

            # Define F(x_n) (Eq. 7 in [1])
            f = j0(z) + (1 / 3) * (np.pi * (p2 - p1) / 2)**2 * delta0**2 * (
                1 - r**2) * (s * jv(2, z) - np.cos(2 *
                                                   (np.pi * x - eta)) * j0(z))

            # P modulation matrix for I, Q, U with and idealized modulator (without the linear correction factor)
            # Eq. 15 of [1]
            pq = np.vstack((np.ones_like(x), f, np.zeros_like(x))).T
            pu = np.vstack((np.ones_like(x), np.zeros_like(x), f)).T
            self.p[wavelength] = np.vstack((pq, pu))
            self.correlation[wavelength] = np.matmul(self.p[wavelength].T,
                                                     self.p[wavelength])

            # W demodulation matrix (Eq. 16 of [1])
            self.w[wavelength] = np.linalg.pinv(self.p[wavelength])

            # Transform rho into S (Eq. (24) of [1])
            self.reflectance_to_electrons[wavelength] = (1.408 * 10**18 * ot * qe * bw) / \
                                                      ((1000*wavelength)**4 * (np.exp(2489.7/(1000*wavelength))) - 1)
コード例 #14
0
def modified_bessel(times, bes_A, bes_Omega, bes_s, res_begin, bes_Delta):
    """ Not Tested. """
    b = np.where(
        times > res_begin + bes_Delta / 2.,
        special.j0(bes_s * bes_Omega * (-res_begin + times - bes_Delta / 2.)),
        (np.where(times < res_begin - bes_Delta / 2.,
                  special.j0(bes_Omega *
                             (res_begin - times - bes_Delta / 2.)), 1)))
    return bes_A * b
コード例 #15
0
def update(val):
    dd = sdd.val
    II = []
    for t in tt:
        F1 = sp.j0(np.pi * (t - dd / 2.)) + sp.jn(2, np.pi * (t - dd / 2.))
        F2 = sp.j0(np.pi * (t + dd / 2.)) + sp.jn(2, np.pi * (t + dd / 2.))
        II.append(F1 * F1 + F2 * F2)
    l.set_ydata(II)
    fig.canvas.draw_idle()
コード例 #16
0
    def _kernel_ssc_integrand(self, chi, ktheta_a, ktheta_b, norm=1.0):
        D_z = self.cosmo.growth_factor(self.cosmo.redshift(chi))

        return (norm * self.window_function_a1.window_function(chi) *
                self.window_function_a2.window_function(chi) *
                self.window_function_b1.window_function(chi) *
                self.window_function_b2.window_function(chi) * D_z * D_z *
                D_z * D_z * D_z * D_z * self._sigma2(chi) / chi *
                special.j0(ktheta_a * chi) * special.j0(ktheta_b * chi))
コード例 #17
0
ファイル: kernel.py プロジェクト: karenyyng/chomp
 def _kernel_NG_integrand(self, chi, ktheta_a, ktheta_b, norm=1.0):
     D_z = self.cosmo.growth_factor(self.cosmo.redshift(chi))
     
     return (norm*self.window_function_a1.window_function(chi)*
             self.window_function_a2.window_function(chi)*
             self.window_function_b1.window_function(chi)*
             self.window_function_b2.window_function(chi)*
             D_z*D_z*D_z*D_z/(chi*chi)*
             special.j0(ktheta_a*chi)*special.j0(ktheta_b*chi))
コード例 #18
0
        def qd(rd, td):
            """
            Dimensionless cumulative production (QD) using Klins et al. Polynomial
            Approach to Bessel Functions in Aquifer
            """
            from scipy.special import j1
            from scipy.special import j0
            import math
            import mpmath

            def csch(x):
                if x > 100:
                    return 0
                else:
                    return float(mpmath.csch(x))

            def beta(b, rd):
                return b[0] + b[1] * csch(
                    rd) + b[2] * rd**b[3] + b[4] * rd**b[5]

            # Algorithm
            if td < 0.01:
                return 2 * td**0.5 / 3.14159265359**0.5
            else:
                b = [
                    1.129552, 1.160436, 0.2642821, 0.01131791, 0.5900113,
                    0.04589742, 1.0, 0.5002034, 1.50, 1.979139
                ]
                qd_inf = (b[0] * td**b[7] + b[1] * td + b[2] * td**b[8] +
                          b[3] * td**b[9]) / (b[4] * td**b[7] + b[5] * td +
                                              b[6])
                if rd > 100:
                    return qd_inf

                b1 = [
                    -0.00222107, -0.627638, 6.277915, -2.734405, 1.2708,
                    -1.100417
                ]
                b2 = [
                    -0.00796608, -1.85408, 18.71169, -2.758326, 4.829162,
                    -1.009021
                ]

                alpha1 = beta(b1, rd)
                alpha2 = beta(b2, rd)
                J0Alpha1 = j0(alpha1)
                J0Alpha2 = j0(alpha2)
                J1Alpha1rd = j1(alpha1 * rd)
                J1Alpha2rd = j1(alpha2 * rd)

                qd_fin = (rd**2 - 1) / 2 - (
                    2 * math.exp(-alpha1**2 * td) * J1Alpha1rd**2) / (
                        alpha1**2 * (J0Alpha1**2 - J1Alpha1rd**2)) - (
                            2 * math.exp(-alpha2**2 * td) *
                            J1Alpha2rd**2) / (alpha2**2 *
                                              (J0Alpha2**2 - J1Alpha2rd**2))
            return min(qd_inf, qd_fin)
コード例 #19
0
def nonlocal_model(p, en, get_G=False, get_N=False, pristine=False):
    af1, ef1, af2, ef2, c0, v1, v2, g1, g2, t1, t2 = p
    g0 = 3.0
    c0 = float(c0)
    b = 1600
    f1 = af1 * np.cos(k * np.pi) + ef1
    f2 = af2 * np.cos(k * np.pi) + ef2
    c = (k**2. - c0**2) * b / c0**2

    G = np.zeros([6, len(en), len(k)], dtype=np.complex128)
    for ix, enval in enumerate(en):
        w0 = enval + 1j * g0
        w1 = enval + 1j * g1
        w2 = enval + 1j * g2
        denominator = (c - w0) * (f1 - w1) * (f2 - w2) - (v2**2 *
                                                          (f1 - w1) + v1**2 *
                                                          (f2 - w2)) * (np.sin(
                                                              np.pi * k)**2)
        G[0, ix] = (-(f1 - w1) * (f2 - w2)) / denominator
        G[1, ix] = (-(c - w0) *
                    (f2 - w2) + v2**2 * np.sin(np.pi * k)**2) / denominator
        G[2, ix] = (-(c - w0) *
                    (f1 - w1) + v1**2 * np.sin(np.pi * k)**2) / denominator
        G[3, ix] = -(v1 * (f2 - w2)) / denominator
        G[4, ix] = -(v2 * (f1 - w1)) / denominator
        G[5, ix] = -v1 * v2 * np.sin(np.pi * k)**2 / denominator
    if get_G:
        return G
    N = np.zeros([9, len(en)], dtype=np.complex128)
    N[0] = (0.5 / np.pi) * np.sum(k * G[0], axis=1)
    N[1] = (0.5 / np.pi) * np.sum(k * G[1], axis=1)
    N[2] = (0.5 / np.pi) * np.sum(k * G[2], axis=1)
    N[3] = (0.5 / np.pi) * np.sum(k * G[5], axis=1)
    N[4] = (0.5 / np.pi) * np.sum(k * G[1] * j0(2 * k), axis=1)
    N[5] = (0.5 / np.pi) * np.sum(k * G[2] * j0(2 * k), axis=1)
    N[6] = (0.5 / np.pi) * np.sum(k * G[5] * j0(2 * k), axis=1)
    N[7] = (0.25 / np.pi) * np.sum(k * G[3] * (1 - j0(2 * k)), axis=1)
    N[8] = (0.25 / np.pi) * np.sum(k * G[4] * (1 - j0(2 * k)), axis=1)
    if get_N:
        return N
    if pristine:
        didv = -1 * (np.imag(N[0]) + 4 * t1**2 * np.imag(N[1]) +
                     4 * t2**2 * np.imag(N[2]) + 8 * t1 * t2 * np.imag(N[3]) -
                     4 * t1**2 * np.imag(N[4]) - 4 * t2**2 * np.imag(N[5]) -
                     8 * t1 * t2 * np.imag(N[6]) + 8 * t1 * np.imag(N[7]) +
                     8 * t2 * np.imag(N[8]))

    else:
        didv = -1 * (np.imag(N[0]) + 2 * t1**2 * np.imag(N[1]) +
                     2 * t2**2 * np.imag(N[2]) + 8 * t1 * t2 * np.imag(N[3]) -
                     4 * t1**2 * np.imag(N[4]) - 4 * t2**2 * np.imag(N[5]) -
                     8 * t1 * t2 * np.imag(N[6]) + 8 * t1 * np.imag(N[7]) +
                     8 * t2 * np.imag(N[8]))
    return didv
コード例 #20
0
def enframe(samples,
            beta=8.5,
            overlapping=0,
            window_length=240,
            window_type='Rectangle'):
    """
    divede samples into frame
    :param samples:
    :param beta: parameter for kaiser window
    :param frame_num:
    :param window_length:
    :param window_type:
    :return: enframed frames
    """

    frames_num = len(samples) // (window_length - overlapping)
    frames = np.zeros([frames_num, window_length])
    for i in range(frames_num):
        start = i * (window_length - overlapping)
        end = start + window_length
        data = samples[start:end]

        N = len(data)
        x = np.linspace(0, N - 1, N, dtype=np.int64)

        if window_type == 'Rectangle':
            data = data
        elif window_type == 'Triangle':
            for i in range(N):
                if i < N:
                    data[i] = 2 * i / (N - 1)
                else:
                    data[i] = 2 - 2 * i / (N - 1)
        elif window_type == 'Hamming':
            w = 0.54 - 0.46 * np.cos(2 * np.pi * x / (N - 1))
            data = data * w
        elif window_type == 'Hanning':
            w = 0.5 * (1 - np.cos(2 * np.pi * x / (N - 1)))
            data = data * w
        elif window_type == 'Blackman':
            w = 0.42 - 0.5 * (1 - np.cos(2 * np.pi * x /
                                         (N - 1))) + 0.08 * np.cos(
                                             4 * np.pi * x / (N - 1))
            data = data * w
        elif window_type == 'Kaiser':
            w = special.j0(
                beta * np.sqrt(1 - np.square(1 - 2 * x /
                                             (N - 1)))) / special.j0(beta)
            data = data * w
        else:
            raise NameError('Unrecongnized window type')

        frames[i] = data
    return frames
コード例 #21
0
ファイル: tlsif.py プロジェクト: timhellwig/fibermodes
 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
コード例 #22
0
		def tau_binf (a, c):
			# numerator :
			integrand = lambda x, a,c: (1-np.exp(-x**2/(4*a**2*c**2))) / x**3 * (ss.y0(x/a)*ss.j0(x)-ss.j0(x/a)*ss.y0(x)) / (ss.y0(x)**2+ss.j0(x)**2) - log(1/a)/(2*a**2*c**2*π) / (1 + 4/π**2 * (np.euler_gamma+np.log(x/2))**2) / x
			                         # |------------------- g1 -------------------------------------------------------------------------------------|   |-------------------------- g2 -----------------------------------------|
			cutoff = 100*max(1,c)
			I = sint.quad( integrand, 0, cutoff, args=(a,c), epsrel=1e-5, limit=1000 )[0]
			int_num = I + log(1/a)*int_2_rem(cutoff)/(4*a**2*c**2)
			# denominator :
			integrand = lambda x, a,c: ( np.exp(-x**2/(4*a**2*c**2)) * (ss.y0(x/a)*ss.j0(x)-ss.j0(x/a)*ss.y0(x)) / (ss.y0(x)**2+ss.j0(x)**2) - 2/π * log(1/a) / (1 + 4/π**2 * (np.euler_gamma+np.log(x/2))**2) ) / x
			                         #   |----------------- f1 ----------------------------------------------------------------------------|   |-------------------------- f2 -------------------------------|
			cutoff = max(10,2*c**2)
			I = sint.quad( integrand, 0, cutoff, args=(a,c), epsrel=1e-7, limit=1000 )[0]
			den = 1 - 2/π * (I + log(1/a)*int_2_rem(cutoff))
			return 8*a**2/π * int_num / den
コード例 #23
0
    def init_TST(self, Rmax_new, Nr_new):
        """
        Setup DHT transform and data buffers.

        Parameters
        ----------
        Rmax_new: float (m) (optional)
            New radial size for the output calculation domain. If not defined
            `Rmax` will be used.

        Nr_new: int
            New number of nodes of the radial grid. If is `None`, `Nr` will
            be used.
        """
        Rmax = self.Rmax
        Nr = self.Nr
        dtype = self.dtype

        self.Rmax_new = Rmax_new
        if self.Rmax_new is None:
            self.Rmax_new = Rmax

        self.Nr_new = Nr_new
        if self.Nr_new is None:
            self.Nr_new = Nr
        self.r_new = np.linspace(0, self.Rmax_new, self.Nr_new)

        alpha = jn_zeros(0, Nr + 1)
        alpha_np1 = alpha[-1]
        alpha = alpha[:-1]

        kr = self.bcknd.to_host(self.kr)

        self.TM = j0(self.r[:, None] * kr[None, :])
        self.TM = self.bcknd.inv(self.TM, dtype)

        self.invTM = self.bcknd.to_device(\
            j0(self.r_new[:,None]*kr[None,:]), dtype)

        self.shape_trns = (self.Nr, )
        self.shape_trns_new = (self.Nr_new, )

        self.u_loc = self.bcknd.zeros(self.Nr, dtype)
        self.u_ht = self.bcknd.zeros(self.Nr, dtype)
        self.u_iht = self.bcknd.zeros(self.Nr_new, dtype)

        self.TST_matmul = self.bcknd.make_matmul(self.TM, self.u_loc,
                                                 self.u_ht)
        self.iTST_matmul = self.bcknd.make_matmul(self.invTM, self.u_ht,
                                                  self.u_iht)
コード例 #24
0
def trunc_sgf(k, L):
    if type(k) == np.ndarray:
        out = np.zeros(k.shape, dtype=float)
        sel = k == 0
        nsel = ~sel
        knsel = k[nsel]
        out[sel] = -L**2 * np.log(L) + L**2 * (1 + 2 * np.log(L)) / 4
        out[nsel] = (1.0 - j0(L * knsel)) / knsel**2 - L * np.log(L) * j1(
            L * knsel) / knsel
        return out
    elif k == 0:
        return -L**2 * np.log(L) + L**2 * (1 + 2 * np.log(L)) / 4
    else:
        return (1.0 - j0(L * k)) / k**2 - L * np.log(L) * j1(L * k) / k
コード例 #25
0
    def _lpfield(self, wl, nu, neff, r):
        rho = self.fiber.outerRadius(0)
        k = wl.k0
        nco2 = self.fiber.maxIndex(0, wl)**2
        ncl2 = self.fiber.minIndex(1, wl)**2
        u = rho * k * sqrt(nco2 - neff**2)
        w = rho * k * sqrt(neff**2 - ncl2)

        if r < rho:
            ex = j0(u * r / rho) / j0(u)
        else:
            ex = k0(w * r / rho) / k0(w)
        hy = neff * Y0 * ex  # Snyder & Love uses nco, but Bures uses neff

        return numpy.array((ex, 0, 0)), numpy.array((0, hy, 0))
コード例 #26
0
ファイル: ssif.py プロジェクト: cbrunet/fibermodes
    def _lpfield(self, wl, nu, neff, r):
        rho = self.fiber.outerRadius(0)
        k = wl.k0
        nco2 = self.fiber.maxIndex(0, wl)**2
        ncl2 = self.fiber.minIndex(1, wl)**2
        u = rho * k * sqrt(nco2 - neff**2)
        w = rho * k * sqrt(neff**2 - ncl2)

        if r < rho:
            ex = j0(u * r / rho) / j0(u)
        else:
            ex = k0(w * r / rho) / k0(w)
        hy = neff * Y0 * ex  # Snyder & Love uses nco, but Bures uses neff

        return numpy.array((ex, 0, 0)), numpy.array((0, hy, 0))
コード例 #27
0
ファイル: tight_binding.py プロジェクト: harrispirie/stmpy
def nonlocal_model(p, en, get_G=False, get_N=False, pristine=False):
    af1, ef1, af2, ef2, c0, v1, v2, g1, g2, t1, t2 = p
    g0 = 3.0
    c0 = float(c0)
    b = 1600
    f1 = af1*np.cos(k*np.pi) + ef1
    f2 = af2*np.cos(k*np.pi) + ef2
    c = (k**2.-c0**2) * b/c0**2

    G = np.zeros([6, len(en), len(k)], dtype=np.complex128)
    for ix, enval in enumerate(en):
        w0 = enval + 1j*g0
        w1 = enval + 1j*g1
        w2 = enval + 1j*g2
        denominator =  (c - w0) * (f1 - w1) * (f2 - w2) - (v2**2 * (f1 - w1) + 
                v1**2 * (f2 - w2)) * (np.sin(np.pi*k)**2)
        G[0,ix] = (-(f1 - w1) * (f2 - w2)) /denominator
        G[1,ix] = (-(c - w0) * (f2 - w2) + v2**2 * np.sin(np.pi*k)**2) /denominator
        G[2,ix] = (-(c - w0) * (f1 - w1) + v1**2 * np.sin(np.pi*k)**2) /denominator
        G[3,ix] = -(v1 * (f2 - w2)) /denominator
        G[4,ix] = -(v2 * (f1 - w1)) /denominator 
        G[5,ix] = -v1*v2*np.sin(np.pi*k)**2 /denominator
    if get_G:
        return G
    N = np.zeros([9,len(en)],  dtype=np.complex128)
    N[0] = (0.5/np.pi)*np.sum(k*G[0], axis=1)
    N[1] = (0.5/np.pi)*np.sum(k*G[1], axis=1)
    N[2] = (0.5/np.pi)*np.sum(k*G[2], axis=1)
    N[3] = (0.5/np.pi)*np.sum(k*G[5], axis=1)
    N[4] = (0.5/np.pi)*np.sum(k*G[1]*j0(2*k), axis=1)
    N[5] = (0.5/np.pi)*np.sum(k*G[2]*j0(2*k), axis=1)
    N[6] = (0.5/np.pi)*np.sum(k*G[5]*j0(2*k), axis=1)
    N[7] = (0.25/np.pi)*np.sum(k*G[3]*(1-j0(2*k)), axis=1)
    N[8] = (0.25/np.pi)*np.sum(k*G[4]*(1-j0(2*k)), axis=1)
    if get_N:
        return N
    if pristine:
        didv = -1*(np.imag(N[0]) + 4*t1**2*np.imag(N[1]) + 
            4*t2**2*np.imag(N[2]) + 8*t1*t2*np.imag(N[3]) -
            4*t1**2*np.imag(N[4]) - 4*t2**2*np.imag(N[5]) -
            8*t1*t2*np.imag(N[6]) + 8*t1*np.imag(N[7]) + 8*t2*np.imag(N[8]))

    else:
        didv = -1*(np.imag(N[0]) + 2*t1**2*np.imag(N[1]) + 
            2*t2**2*np.imag(N[2]) + 8*t1*t2*np.imag(N[3]) -
            4*t1**2*np.imag(N[4]) - 4*t2**2*np.imag(N[5]) -
            8*t1*t2*np.imag(N[6]) + 8*t1*np.imag(N[7]) + 8*t2*np.imag(N[8]))
    return didv
コード例 #28
0
ファイル: cossif.py プロジェクト: cbrunet/fibermodes
def plotrcfte():
    V = numpy.linspace(1, 7)
    rho = 0.5

    f = j0(V) * yn(2, V*rho) - y0(V) * jn(2, rho*V)
    pyplot.plot(V, f)
    pyplot.show()
コード例 #29
0
def experimental_eps(r, t, eps, date=None):
    if date != None:
        updateParameret_array(date)

    numerator = (parameter_array['l'] * parameter_array['betta'] *
                 parameter_array['P'])
    denominator = (50 * sp.pi * parameter_array['alf'] *
                   parameter_array['a']**2)
    all = numerator / denominator
    x = ((-2 * parameter_array['alf'] * t) /
         (parameter_array['c'] * parameter_array['l']))
    u = all * (1 - np.exp(x))

    N = analitic_eps(eps)

    for i in np.arange(1, N + 1, 1):
        u += An(i, t) * spc.j0((bessel0[i] * r) / parameter_array['R'])
        flag.append(u)

    i = N - 2
    analit_eps = flag[N - 1]
    while (abs(analit_eps - flag[i]) <= eps) and (i > 0):
        i = i - 1
    if ((i + 2) > NMAX[0]):
        NMAX[0] = i + 2
    flag.clear()
    return NMAX[0]
コード例 #30
0
def calculate_1D_truncated_coulomb(pd, q_v=None, N_c=None):
    """ Simple 1D truncation of Coulomb kernel PRB 73, 205119.
    The periodic direction is determined from k-point grid.
    """

    from scipy.special import j1, k0, j0, k1

    qG_Gv = pd.get_reciprocal_vectors(add_q=True)
    if pd.kd.gamma:
        if q_v is not None:
            qG_Gv += q_v
        else:
            raise ValueError('Presently, calculations only work with a small q in the normal direction')

    # The periodic direction is determined from k-point grid
    Nn_c = np.where(N_c == 1)[0]
    Np_c = np.where(N_c != 1)[0]
    if len(Nn_c) != 2:
        # The k-point grid does not fit with boundary conditions
        Nn_c = [0, 1]    # Choose reduced cell vectors 0, 1
        Np_c = [2]       # Choose reduced cell vector 2
    # The radius is determined from area of non-periodic part of cell
    Acell_cv = pd.gd.cell_cv[Nn_c, :][:, Nn_c]
    R = (np.linalg.det(Acell_cv) / np.pi)**0.5

    qGnR_G = (qG_Gv[:, Nn_c[0]]**2 + qG_Gv[:, Nn_c[1]]**2)**0.5 * R
    qGpR_G = abs(qG_Gv[:, Np_c[0]]) * R
    v_G = 4 * np.pi / (qG_Gv**2).sum(axis=1)
    v_G *= (1.0 + qGnR_G * j1(qGnR_G) * k0(qGpR_G)
            - qGpR_G * j0(qGnR_G) * k1(qGpR_G))

    return v_G.astype(complex)
コード例 #31
0
ファイル: core.py プロジェクト: SqrtMinusOne/SEM5_LABS
 def get_roots(self):
     j0_rng = np.linspace(0, 40, 400)
     j0_value = [special.j0(i) for i in j0_rng]
     j0_interval = Bessel.get_intervals(j0_rng, j0_value, 10)
     if len(j0_interval) == 0:
         raise RuntimeError("No roots of Bessel function were found")
     self.roots = [optimize.bisect(special.j0, i[0], i[1]) for i in j0_interval]
コード例 #32
0
def angular_corr_func(thetas, zs, dn_dz_1, dn_dz_2):
    # thetas from degrees to radians
    thetas = (thetas * u.deg).to('radian').value

    # get dimensionless power spectrum
    deltasquare = power_spec_at_zs(zs, read=False, dimensionless=True)

    # power spectrum over k^2
    first_term = deltasquare / (k_grid**2)

    # everything inside Bessel function
    # has 3 dimensions, k, theta, and z
    # therefore need to do outer product of two arrays, then broadcast 3rd array to 3D and multiply
    besselterm = j0(
        cosmo.comovingDistance(np.zeros(len(zs)), zs)[:, None, None] *
        np.outer(k_grid, thetas))

    # Not sure if this is right
    # I think you need to convert H(z)/c from 1/Mpc to h/Mpc in order to cancel units of k, but not sure
    dz_d_chi = (apcosmo.H(zs) / const.c).to(u.littleh / u.Mpc,
                                            u.with_H0(apcosmo.H0)).value

    # product of redshift distributions, and dz/dchi
    differentials = dz_d_chi * dn_dz_1 * dn_dz_2

    # total integrand is all terms multiplied out. This is a 3D array
    integrand = np.pi * differentials * np.transpose(
        first_term) * np.transpose(besselterm)

    # do k integral first along k axis
    k_int = np.trapz(integrand, k_grid, axis=1)
    # then integrate along z axis
    total = np.trapz(k_int, zs, axis=1)

    return total
コード例 #33
0
ファイル: initials.py プロジェクト: natl/bg
def gravground( x          ,
                y          ,
                g          ,
                G          ,
                *args      ,
                **kwargs):
  '''
  def gravground( x       ,
                  y       ,
                  g       ,
                  G       ,
                  *args   ,
                  **kwargs):
  Create the Thomas-Fermi ground state for a gravitational system
  '''
  X,Y = np.meshgrid(x,y)
  R = np.sqrt( X ** 2. + Y ** 2. )
  bj0z1   = jn_zeros( 0, 1 ) #First zero of zeroth order besselj
  scaling = np.sqrt( 2 * np.pi * G / g  )
  gr0     = bj0z1 / scaling
  Rprime  = R * scaling
  
  gtfsol = j0( Rprime ) * np.array( [ map( int,ii ) for ii in map( 
                                      lambda rad: rad <= gr0, R ) ] )

      
  gtfsol *= scaling ** 2. / ( 2 * np.pi * j1( bj0z1 ) * bj0z1 ) 
  
  return gtfsol
コード例 #34
0
ファイル: Beams.py プロジェクト: SharperJBCA/SWGSimulator
    def BeamFunction(self, apfunc, r, sigma, wl, thetamax=5, nsamples=128):
        """
        apfunc - Aperture distribution function
        
        r     - Radius out to D/2 (m)
        sigma - taper width in wavelengths over dish
        wl    - wavelength (m)
        """

        # Convert to No. wavelength units
        rho = r / wl
        drho = np.abs(rho[1] - rho[0])

        # To store output beam pattern.
        beam = np.zeros(nsamples)

        # Line-of-sight angles to calculate beam power
        thetas = np.linspace(0, thetamax, nsamples) * np.pi / 180.

        # Loop over thetas
        for i, theta in enumerate(thetas):

            # Tools of Radio Astronomy 5th Ed. eqn. 6.67
            top = np.sum(
                apfunc(r, sigma, wl) * j0(2 * np.pi * np.sin(theta) * rho) *
                rho) * drho
            bot = np.sum(apfunc(r, sigma, wl) * rho) * drho
            beam[i] = np.abs(top / bot)**2

        return beam, thetas * 180 / np.pi
コード例 #35
0
def Bn(n):
    j0 = spc.j0(bessel0[n])
    j1 = spc.j1(bessel0[n] / 5)
    numerator = 2 * parameter_array['betta'] * parameter_array['P'] * j1
    denominator = 5 * parameter_array['c'] * np.pi * (
        parameter_array['a'])**2 * bessel0[n] * (j0)**2
    return numerator / denominator
コード例 #36
0
ファイル: analytical.py プロジェクト: petebachant/sharpy
def sears_lift_sin_gust(w0, L, Uinf, chord, tv):
    """
    Returns the lift coefficient for a sinusoidal gust (see set_gust.sin) as
    the imaginary part of the CL complex function defined below. The input gust
    must be the imaginary part of

    .. math::    wgust = w0*\exp(1.0j*C*(Ux*S.time[tt] - xcoord) )

    with:

    .. math:: C=2\pi/L

    and ``xcoord=0`` at the aerofoil half-chord.
    """

    # reduced frequency
    kg = np.pi * chord / L
    # Theo's funciton
    Ctheo = theo_fun(kg)
    # Sear's function
    J0, J1 = scsp.j0(kg), scsp.j1(kg)
    S = (J0 - 1.0j * J1) * Ctheo + 1.0j * J1

    phase = np.angle(S)
    CL = 2. * np.pi * w0 / Uinf * np.abs(S) * np.sin(2. * np.pi * Uinf / L *
                                                     tv + phase)

    return CL
コード例 #37
0
ファイル: kernel.py プロジェクト: ajmendez/stomp
 def _kernel_integrand(self, chi, ktheta):
     D_z = self.cosmo.growth_factor(self.cosmo.redshift(chi))
     z = self.cosmo.redshift(chi)
     
     return (self.window_function_a.window_function(chi)*
             self.window_function_b.window_function(chi)*
             D_z*D_z*special.j0(ktheta*chi))
コード例 #38
0
ファイル: tlsif.py プロジェクト: cbrunet/fibermodes
 def _tmcoeq(self, v0, nu):
     u1r1, u2r1, u2r2, s1, s2, n1sq, n2sq, n3sq = self.__params(v0)
     if s1 == 0:  # e
         f11a, f11b = 2, 1
     elif s1 > 0:  # a, b, d
         f11a, f11b = j0(u1r1) * u1r1, j1(u1r1)
     else:  # c
         f11a, f11b = i0(u1r1) * u1r1, i1(u1r1)
     if s2 > 0:
         f22a, f22b = j0(u2r2), y0(u2r2)
         f2a = j1(u2r1) * f22b - y1(u2r1) * f22a
         f2b = j0(u2r1) * f22b - y0(u2r1) * f22a
     else:  # a
         f22a, f22b = i0(u2r2), k0(u2r2)
         f2a = i1(u2r1) * f22b + k1(u2r1) * f22a
         f2b = i0(u2r1) * f22b - k0(u2r1) * f22a
     return f11a * n2sq * f2a - f11b * n1sq * f2b * u2r1
コード例 #39
0
 def function1D(self, x):
   A0 = self.getParameterValue("A0")
   alpha = self.getParameterValue("alpha")
   fi = self.getParameterValue("fi")
   nu = self.getParameterValue("nu")
   LamT = self.getParameterValue("LamT")
   LamL = self.getParameterValue("LamL")
   return A0*( alpha*(2.0*np.pi*nu*x+(np.pi)/180.0)*sp.j0(x)*np.exp(-LamT*x) + (1.0-alpha)*np.exp(-LamL*x) )
コード例 #40
0
ファイル: cossif.py プロジェクト: cbrunet/fibermodes
def plotCF():
    ncl = 1.444
    nco = ncl + 0.05
    V = numpy.linspace(1, 7)

    pyplot.plot(V, j0(V))
    pyplot.plot(V, j1(V))
    pyplot.plot(V, jn(2, V))

    n02 = ncl*ncl / (nco * nco)
    a = (1 - n02) / (1 + n02)
    pyplot.plot(V, a * jn(2, V) - j0(V))
    pyplot.plot(V, a * jn(3, V) - j1(V))
    pyplot.plot(V, a * jn(4, V) - jn(2, V))

    pyplot.axhline(0, ls='--', color='k')

    pyplot.show()
コード例 #41
0
ファイル: hankel.py プロジェクト: diazona/hankel
 def _j1(self, x):
     if self._nu == -1:
         return j0(x)
     elif self._nu == 0:
         return j1(x)
     elif isinstance(self._nu, int):
         return jn(self._nu + 1, x)
     else:
         return jv(self._nu + 1, x)
コード例 #42
0
ファイル: shear_correlation.py プロジェクト: akr89/Thesis
 def __integrand(self,theta):
     """
     theta and theta_R should be in radians
     """
     if theta==0:
         return self.F_ell
     else:
         return self.F_ell *\
             j0(theta*self.ell)
コード例 #43
0
ファイル: funcZeta.py プロジェクト: Ticonderoga/Routines
def funcZetaCyl(z, Bi):
    """
    zeta, Bi function for cylinder as f(z) = z*J1(z) - Bi*J0(z)
    note that J1 and J0 are bessel functions
    z = zeta values which are later solved for the positive roots for theta
    Bi = Biot number h*L/k, (-)
    """
    f = z*sp.j1(z) - Bi*sp.j0(z)
    return f
コード例 #44
0
ファイル: shear_correlation.py プロジェクト: akr89/Thesis
 def __integrand(self,theta):
     """
     Internal method to construct integrand.  
     Theta should be in radians
     """
     if theta==0:
         return self.F_ell
     else:
         return self.F_ell * j0(self.ell*theta)
コード例 #45
0
ファイル: hankel.py プロジェクト: steven-murray/hankel
 def _j1(self, x):
     if self._nu == -1:
         return j0(x)
     elif self._nu == 0:
         return j1(x)
     elif np.floor(self._nu) == self._nu:
         return jn(self._nu + 1, x)
     else:
         return jv(self._nu + 1, x)
コード例 #46
0
ファイル: plotting.py プロジェクト: cmft/sardana
def J0_plot(self):
    """Sample J0 at linspace(0, 20, 200)"""
    x = linspace(0, 20, 200)
    y = j0(x)
    x1 = x[::10]
    y1 = map(j0i, x1)
    self.pyplot.plot(x, y, label=r'$J_0(x)$') # 
    self.pyplot.plot(x1, y1, 'ro', label=r'$J_0^{integ}(x)$')
    self.pyplot.title(r'Verify $J_0(x)=\frac{1}{\pi}\int_0^{\pi}\cos(x \sin\phi)\,d\phi$')
    self.pyplot.xlabel('$x$')
    self.pyplot.legend()
コード例 #47
0
def main(sampleFile):
	
	A = 3.1926
	a = 180 # [m]
	H = a/3 # [m]
	X = linspace(-a,a,301)	# [m]	
	Y = - H * 1/6.04844 * ( sp.j0(A)*sp.i0(A*X/a) - sp.i0(A)*sp.j0(A*X/a) )
	X = insert(X,0,1000); X = append(X,1000)
	Y = insert(Y,0,0); Y = append(Y,0)
	h = 10

	# interpolating for a refined line
	xSample = linspace(-1000,1000,2000)
	ySample = interp(xSample,X,Y)
	# opening file
	infile  = open(sampleFile,"r")
	outfile = open(sampleFile + "_t","w")
	N = i = 0
	value = 0.0
	# reading first line
	line = infile.readline()
	while line:
		# finding the "nonuniform" line
		if line.find("points")>0 and line.find("//")<0:
			outfile.write(line)
			# writing new sample line shape
			for x,y in zip(xSample,ySample):
				sampleLine = "		(	 %12.10f	 %12.10f	%12.10f	)\n" % (x,value, y+h) 
				outfile.write(sampleLine)
			line = infile.readline()
		else:
			outfile.write(line)
			# reading new line
			line = infile.readline()
	# close files
	infile.close()
	outfile.close()
	# copying original to new and viceversa
	subprocess.call("cp -r " + sampleFile + " " + sampleFile + "_temp",shell=True)
	subprocess.call("cp -r " + sampleFile + "_t " + sampleFile,shell=True)
コード例 #48
0
ファイル: S_DD.py プロジェクト: akr89/Thesis
    def integrand_circ(self,theta):
        #circular window: F = 2*J_1(theta*ell)/(theta*ell)
        theta *= ARCMIN_TO_RAD

        A = 1E10
        factor = 2./ numpy.pi / self.theta_s_rad**2 / A

        integrand = lambda ell : \
                    A * self.P2D(ell) \
                    * special.j1(self.theta_s_rad*ell)**2 \
                    * special.j0(theta * ell) / ell

        return factor,integrand
コード例 #49
0
ファイル: S_DD.py プロジェクト: akr89/Thesis
    def integrand_gaus(self,theta):
        #gaussian window: F = exp( -0.5*(theta*ell)**2 )
        theta *= ARCMIN_TO_RAD

        A = 1E10
        factor = 0.5 / numpy.pi / A

        integrand = lambda ell: \
                        A * self.P2D(ell) \
                        * numpy.exp( -(theta*ell)**2 ) \
                        * special.j0(theta * ell) * ell

        return factor,integrand
コード例 #50
0
def funcCn(root, b):
    """
    First term in the theta function
    root = root from the zeta, Bi equation
    b = shape factor where 2 sphere, 1 cylinder, 0 slab
    """
    if b == 2:
        Cn = 4*(np.sin(root)-root*np.cos(root)) / (2*root-np.sin(2*root))
    elif b == 1:
        Cn = (2/root) * (sp.j1(root) / (sp.j0(root)**2 + sp.j1(root)**2))
    elif b == 0:
        Cn = (4*np.sin(root)) / (2*root + np.sin(2*root))
    return Cn
コード例 #51
0
def funcDn(r, root, b):
    """
    Second term in the theta function
    root = root from the zeta, Bi equation
    b = shape factor where 2 sphere, 1 cylinder, 0 slab
    """
    if b == 2:
        Dn = (1/(root*r)) * np.sin(root*r)
    elif b == 1:
        Dn = sp.j0(root * r)
    elif b == 0:
        Dn = np.cos(root * r)
    return Dn
コード例 #52
0
ファイル: GlauberModel.py プロジェクト: jdfreder/MCG
def NCD(Nucleus,Model,Range=2,Bins=100):
    """Returns the Nuclear Charge Distribution for a given Nucleus with specified
    model. Creates radial distribution from 0 to Range*nuclear radius with n 
    number of bins. If no values are set, defaults to 197Au using two-parameter
    Fermi model up to twice the nuclear radius with 100 bins."""
    #For multiple models of the same nucleus takes the first set of parameters and notifies the user which parameters are used.
    j=[]
    for index in range(len(pNucleus)):
        if pNucleus[index]==Nucleus and pModel[index]==Model:
            j.append(index)
            i=index
    j=np.array(j,dtype=int)
    if len(j)>1:
        #print "Multiple parameters detected for given model. Using primary values."
        i=j[0]
    r=np.linspace(0,Range*float(pr2[i]),Bins)
    if Model=='HO':
        return (1+float(pZ_Alpha[i])*(r/float(pC_A[i]))**2)*np.exp(-1*(r/float(pC_A[i]))**2)
    elif Model=='MHO':
        print "Warning: Model not yet supported\nPlease use a different model."
        return None
    elif Model=='Mi':
        print "Warning: Model not yet supported\nPlease use a different model."
        return None
    elif Model=='FB':
        #print "Warning: Fourier-Bessel Model currently contains support for He-3 only. If not simulating He-3 collisions, please choose another model."
        for FBindex in range(len(FBnucleus)):
            if FBnucleus[FBindex]==Nucleus:
                iFB=FBindex
        r=np.linspace(0,float(FBR[iFB]),Bins)
        p=np.zeros(np.size(r),float)
        v=np.arange(0,17,1)
        for i in range(len(r)):
            p[i]=abs(sum(FBa[iFB-1,v]*j0((v+1)*np.pi*r[i]/float(FBR[iFB]))))
        return p
    elif Model=='SOG':
        print "Warning: Model not yet supported\nPlease use a different model."
        return None
    elif Model=='2pF':
        return 1/(1+np.exp((r-float(pC_A[i]))/float(pZ_Alpha[i])))
    elif Model=='3pF':
        return (1+float(pw[i])*r**2/float(pC_A[i])**2)/(1+np.exp((r-float(pC_A[i]))/float(pZ_Alpha[i])))
    elif Model=='3pG':
        return (1+float(pw[i])*r**2/float(pC_A[i])**2)/(1+np.exp((r**2-float(pC_A[i])**2)/float(pZ_Alpha[i])**2))
    elif Model=='UG':
        print "Warning: Model not yet supported\nPlease use a different model."
        return None
    else:
        print 'Error: Model not found\nPlease check that the model was typed in correctly. (Case Sensitive)'
        return None
コード例 #53
0
def main(L,N):

	A = 3.1926
	a = 180 # [m]
	H = a/3 # [m]
	X0 = X = linspace(-a,a,N)	# [m]	
	Y0 = Y = - H * 1/6.04844 * ( sp.j0(A)*sp.i0(A*X/a) - sp.i0(A)*sp.j0(A*X/a) )
	if L>0:
		X = insert(X,0,-L); X = append(X,L)
		Y = insert(Y,0,0); Y = append(Y,0)
	h = 10

	# writing CSV
	g = column_stack((0*X,X,Y))
	f = open('HillShape_X.csv','wb')
	csvWriter = csv.writer(f, delimiter=',')
	csvWriter.writerow(X)
	f.close()

	f = open('HillShape_Y.csv','wb')
	csvWriter = csv.writer(f, delimiter=',')
	csvWriter.writerow(Y)
	f.close()
	return X,Y
コード例 #54
0
ファイル: powerspec.py プロジェクト: jgsuresh/DLA_script
def autofrompower_3d(k, pk,rr):
    """Cmpute the autocorrelation function a 3D dimensionful power spectrum, such as you might get from CAMB.
    From Challinor's structure notes:
        P(k) =  < δ δ*>
        Δ^2 = P(k) k^3/(2π^2)
        ζ(r) = int dk/k Δ^2 j_0(kr)
             = int dk (k^2) P(k) j_0(kr) / (2π^2)
        Arguments:
            k - k values
            pk - power spectrum
            r - values of r = | x-y |
                at which to evaluate the autocorrelation
    """
    auto = np.array([np.sum(pk*j0(k*r)*k**2/2/math.pi**2)/np.size(k) for r in rr])
    return auto
コード例 #55
0
ファイル: ssif.py プロジェクト: cbrunet/fibermodes
    def _tefield(self, wl, nu, neff, r):
        rho = self.fiber.outerRadius(0)
        k = wl.k0
        nco2 = self.fiber.maxIndex(0, wl)**2
        ncl2 = self.fiber.minIndex(1, wl)**2
        u = rho * k * sqrt(nco2 - neff**2)
        w = rho * k * sqrt(neff**2 - ncl2)

        if r < rho:
            hz = -Y0 * u / (k * rho) * j0(u * r / rho) / j1(u)
            ephi = -j1(u * r / rho) / j1(u)
        else:
            hz = Y0 * w / (k * rho) * k0(w * r / rho) / k1(w)
            ephi = -k1(w * r / rho) / k1(w)
        hr = -neff * Y0 * ephi

        return numpy.array((0, ephi, 0)), numpy.array((hr, 0, hz))
コード例 #56
0
ファイル: ssif.py プロジェクト: cbrunet/fibermodes
    def _tmfield(self, wl, nu, neff, r):
        rho = self.fiber.outerRadius(0)
        k = wl.k0
        nco2 = self.fiber.maxIndex(0, wl)**2
        ncl2 = self.fiber.minIndex(1, wl)**2
        u = rho * k * sqrt(nco2 - neff**2)
        w = rho * k * sqrt(neff**2 - ncl2)

        if r < rho:
            ez = -u / (k * neff * rho) * j0(u * r / rho) / j1(u)
            er = j1(u * r / rho) / j1(u)
            hphi = Y0 * nco2 / neff * er
        else:
            ez = nco2 / ncl2 * w / (k * neff * rho) * k0(w * r / rho) / k1(w)
            er = nco2 / ncl2 * k1(w * r / rho) / k1(w)
            hphi = Y0 * nco2 / ncl2 * k1(w * r / rho) / k1(w)

        return numpy.array((er, 0, ez)), numpy.array((0, hphi, 0))
コード例 #57
0
ファイル: kernel.py プロジェクト: robwarm/gpaw-symm
def v1D_Coulomb(qG, N_p, N_np, R):
    """Coulomb Potential in the 1D Periodic Case.
    
    Nanotube/Nanowire/Atomic Chain calculation.
    Cutoff in non-periodic N_np directions.
    No cutoff in periodic N_p direction.

    ::
    
      v1D = 4 pi/|q+G|^2 * [1 + |G_n|R J_1(|G_n|R) K_0(G_p R)
                              - G_p R J_0(|G_n| R) K_1(G_p R)]
    """

    from scipy.special import j1, k0, j0, k1

    G_nR = (qG[:, N_np[0]]**2 + qG[:, N_np[1]]**2)**0.5 * R
    G_pR = abs(qG[:, N_p[0]]) * R
    v_q = 1. / (qG**2).sum(axis=1)
    v_q *= (1. + G_nR * j1(G_nR) * k0(G_pR)
            - G_pR * j0(G_nR) * k1(G_pR))
    return v_q
コード例 #58
0
ファイル: fel.py プロジェクト: iagapov/ocelot
def calculateFelParameters(input):
    p = FelParameters()

    p.gamma0 = input.gamma0  
    p.delgam = input.delgam  
    p.xlamd = input.xlamd    # undulator period
    p.ex = input.emitx
    p.ey = input.emity
    p.rxbeam = input.rxbeam
    p.rybeam = input.rybeam
    p.aw0 = input.aw0
    p.Ip = input.curpeak
    
    p.deta =  p.delgam / p.gamma0
    
    p.lambda0 = p.xlamd / (2.0 * p.gamma0**2) *(1.0 + p.aw0**2)
    p.k0 = 2 * np.pi / p.lambda0 

    p.Ia = 17000.0
        
    a = p.aw0**2 / (2*(1+p.aw0**2))
    p.fc = sf.j0(a) - sf.j1(a)
    p.N = p.Ip * p.lambda0 / 1.4399644850445153e-10
    p.sigb = 0.5 * (p.rxbeam + p.rybeam)
    p.rho = (1.0 / p.gamma0) * np.power( (p.aw0 * p.fc * p.xlamd / (8.0 * np.pi * p.sigb) )**2 * p.Ip / p.Ia, 1.0/3.0)
    p.Pb = p.gamma0 * p.Ip * 510998.927
    p.power = 6.0 * np.sqrt(np.pi) * p.rho**2 * p.Pb / (p.N * np.log(p.N / p.rho) )
    p.lg = p.xlamd / (4*np.pi * np.sqrt(3) * p.rho)
    p.zr = 4 * np.pi * p.sigb**2 / p.lambda0
  
    xie_a = [0.45, 0.57, 0.55, 1.6, 3.0, 2.0, 0.35, 2.9, 2.4, 51.0, 0.95, 3.0, 5.4, 0.7, 1.9, 1140.0, 2.2, 2.9, 3.2]
      
    p.xie_etad = p.lg / (2 * p.k0 * p.sigb**2)
    p.xie_etae = 0
    p.xie_etagamma = p.deta / (p.rho * np.sqrt(3))
    p.xie_lscale = xie_a[0] * p.xie_etad ** xie_a[1] + xie_a[2] * p.xie_etae ** xie_a[3] + xie_a[4] * p.xie_etagamma ** xie_a[5] 
                    
    return p
コード例 #59
0
ファイル: InitialConditions.py プロジェクト: crocha700/NIWQG
def LambDipole(model, U=.01,R = 1.):

    """ Generate Lamb's dipole vorticity field.

       Parameters
       -----------
        U: float
                Translation speed (dipole's strength).
        R: float
                Diple's radius.

       Return
       -------
        q: array of floats
              Vorticity (physical space).

    """

    N = model.nx
    x, y = model.x, model.y
    x0,y0 = x[N//2,N//2],y[N//2,N//2]

    r = np.sqrt( (x-x0)**2 + (y-y0)**2 )
    s = np.zeros_like(r)

    for i in range(N):
        for j in range(N):
            if r[i,j] == 0.:
                s[i,j] = 0.
            else:
                s[i,j] = (y[i,j]-y0)/r[i,j]

    lam = (3.8317)/R
    C = -(2.*U*lam)/(special.j0(lam*R))
    q = np.zeros_like(r)
    q[r<=R] = C*special.j1(lam*r[r<=R])*s[r<=R]

    return q