Beispiel #1
0
def test_chebyshev2_mpmath():
    scheme = quadpy.line_segment.ChebyshevGauss2(4, mode="mpmath", decimal_places=51)

    tol = 1.0e-50

    x1 = mp.cos(2 * mp.pi / 5)
    x2 = mp.cos(1 * mp.pi / 5)
    assert (abs(scheme.points - [-x2, -x1, +x1, +x2]) < tol).all()

    w1 = mp.pi / 5 * mp.sin(2 * mp.pi / 5) ** 2
    w2 = mp.pi / 5 * mp.sin(1 * mp.pi / 5) ** 2
    assert (abs(scheme.weights - [w2, w1, w1, w2]) < tol).all()
    return
Beispiel #2
0
 def dTk(x):
     with mp.extradps(extradps):
         x = clip(x, -1.0, 1.0)
         if mp.almosteq(x, mp.one): return pos
         if mp.almosteq(x, -mp.one): return neg
         moredps = max(
             0,
             int(-math.log10(
                 min(abs(x - mp.one), abs(x + mp.one))) / 2))
         moredps = min(moredps, 100)
         with mp.extradps(moredps):
             t = mp.acos(x)
             return k * mp.sin(k * t) / mp.sin(t)
Beispiel #3
0
def test_chebyshev2_mpmath():
    mp.dps = 51
    scheme = quadpy.c1.chebyshev_gauss_2(4, mode="mpmath")

    tol = 1.0e-50

    x1 = mp.cos(2 * mp.pi / 5)
    x2 = mp.cos(1 * mp.pi / 5)
    assert (abs(scheme.points_symbolic - [+x2, +x1, -x1, -x2]) < tol).all()

    w1 = mp.pi / 5 * mp.sin(2 * mp.pi / 5)**2
    w2 = mp.pi / 5 * mp.sin(1 * mp.pi / 5)**2
    assert (abs(scheme.weights_symbolic - [w2, w1, w1, w2]) < tol).all()
Beispiel #4
0
 def __init__(self, domain=None, name='sin^2'):
     super(SinSquaredExpression,
           self).__init__(mp_terms=[
               lambda x: mp.sin(x)**2, lambda x: mp.sin(2 * x),
               lambda x: 2 * mp.cos(2 * x)
           ],
                          fp_terms=[
                              lambda x: math.sin(x)**2,
                              lambda x: math.sin(2 * x),
                              lambda x: 2 * math.cos(2 * x)
                          ],
                          desc="sin^2(x)",
                          domain=domain,
                          name=name)
Beispiel #5
0
def mp_cyl(x):
    f = mp.mpf
    theta = f(THETA) * mp.pi / f(180)
    qr = x * f(RADIUS) * mp.sin(theta)
    qh = x * f(LENGTH) / f(2) * mp.cos(theta)
    be = f(2) * mp.j1(qr) / qr
    si = mp.sin(qh) / qh
    background = f(0)
    #background = f(1)/f(1000)
    volume = mp.pi * f(RADIUS)**f(2) * f(LENGTH)
    contrast = f(5)
    units = f(1) / f(10000)
    #return be
    #return si
    return units * (volume * contrast * be * si)**f(2) / volume + background
Beispiel #6
0
 def ddTk(x):
     with mp.extradps(extradps):
         x = clip(x, -1.0, 1.0)
         if mp.almosteq(x, mp.one): return pos
         if mp.almosteq(x, -mp.one): return neg
         moredps = max(
             0,
             int(-math.log10(
                 min(abs(x - mp.one), abs(x + mp.one))) * 1.5) +
             2)
         moredps = min(moredps, 100)
         with mp.extradps(moredps):
             t = mp.acos(x)
             s = mp.sin(t)
             return -k**2 * mp.cos(k * t) / s**2 + k * mp.cos(
                 t) * mp.sin(k * t) / s**3
def chebyshev_gauss_2(n, mode="numpy", decimal_places=None):
    """Chebyshev-Gauss quadrature for \\int_{-1}^1 f(x) * sqrt(1+x^2) dx."""
    degree = n if n % 2 == 1 else n + 1

    # TODO make explicit for all modes
    if mode == "numpy":
        points = numpy.cos(numpy.pi * numpy.arange(1, n + 1) / (n + 1))
        weights = (
            numpy.pi
            / (n + 1)
            * (numpy.sin(numpy.pi * numpy.arange(1, n + 1) / (n + 1))) ** 2
        )
    elif mode == "sympy":
        points = numpy.array(
            [sympy.cos(sympy.Rational(k, n + 1) * sympy.pi) for k in range(1, n + 1)]
        )
        weights = numpy.array(
            [
                sympy.pi / (n + 1) * sympy.sin(sympy.pi * sympy.Rational(k, n + 1)) ** 2
                for k in range(1, n + 1)
            ]
        )
    else:
        assert mode == "mpmath"
        points = numpy.array(
            [mp.cos(mp.mpf(k) / (n + 1) * mp.pi) for k in range(1, n + 1)]
        )
        weights = numpy.array(
            [
                mp.pi / (n + 1) * mp.sin(mp.pi * mp.mpf(k) / (n + 1)) ** 2
                for k in range(1, n + 1)
            ]
        )
    return C1Scheme("Chebyshev-Gauss 2", degree, weights, points)
Beispiel #8
0
 def two_body_reference(self, t1, num_1 = 0, num_2 = 1):
     """ reference notations are same as Yoel's notes
     using a precision of 64 digits for max accuracy """
     mp.dps = 64
     self.load_data()
     t1 = mp.mpf(t1)
     m_1 = mp.mpf(self.planet_lst[num_1].mass)
     m_2 = mp.mpf(self.planet_lst[num_2].mass)
     x1_0 = mp.matrix(self.planet_lst[num_1].loc)
     x2_0 = mp.matrix(self.planet_lst[num_2].loc)
     v1_0 = mp.matrix(self.planet_lst[num_1].v)
     v2_0 = mp.matrix(self.planet_lst[num_2].v)
     M = m_1 + m_2
     x_cm = (1/M)*((m_1*x1_0)+(m_2*x2_0))
     v_cm = (1/M)*((m_1*v1_0)+(m_2*v2_0))
     u1_0 = v1_0 - v_cm
     w = x1_0 - x_cm
     r_0 = mp.norm(w)
     alpha = mp.acos((np.inner(u1_0,w))/(mp.norm(u1_0)*mp.norm(w)))
     K = mp.mpf(self.G) * (m_2**3)/(M**2)
     u1_0 = mp.norm(u1_0)
     L = r_0 * u1_0 * mp.sin(alpha)
     cosgamma = ((L**2)/(K*r_0)) - 1
     singamma = -((L*u1_0*mp.cos(alpha))/K)
     gamma = mp.atan2(singamma, cosgamma)
     e = mp.sqrt(((r_0*(u1_0**2)*(mp.sin(alpha)**2)/K)-1)**2 + \
              (((r_0**2)*(u1_0**4)*(mp.sin(alpha)**2)*(mp.cos(alpha)**2))/(K**2)) )        
     r_theta = lambda theta: (L**2)/(K*(1+(e*mp.cos(theta - gamma))))
     f = lambda x: r_theta(x)**2/L
     curr_theta = 0
     max_it = 30
     it = 1
     converged = 0
     while ((it < max_it) & (converged != 1)):
         t_val = mp.quad(f,[0,curr_theta]) - t1
         dt_val = f(curr_theta)
         delta = t_val/dt_val
         if (abs(delta)<1.0e-6):
             converged = 1
         curr_theta -= delta
         it += 1 
     x1_new = mp.matrix([r_theta(curr_theta)*mp.cos(curr_theta), r_theta(curr_theta)*mp.sin(curr_theta)]) 
     # x2_new = -(m_1/m_2)*(x1_new) +(x_cm + v_cm*t1)
     x1_new = x1_new + (x_cm + v_cm*t1)
     return x1_new
Beispiel #9
0
def f02(y, n, R, rh, l, pm1, Om, lam, sig):
    K = lam**2 * sig / 2 / fp.sqrt(2 * fp.pi)
    a = (R**2 - rh**2) * l**2 / 4 / sig**2 / rh**2
    b = fp.sqrt(R**2 - rh**2) * Om * l / rh
    Zp = mp.mpf((R**2 + rh**2) / (R**2 - rh**2))
    if Zp - mp.cosh(y) > 0:
        return fp.mpf(K * mp.exp(-a * y**2) * mp.cos(b * y) /
                      mp.sqrt(Zp - mp.cosh(y)))
    elif Zp - mp.cosh(y) < 0:
        return fp.mpf(-K * mp.exp(-a * y**2) * mp.sin(b * y) /
                      mp.sqrt(mp.cosh(y) - Zp))
    else:
        return 0
Beispiel #10
0
def Construct_Dp(Phi, Psi, Omega, tt):

    Cos = mp.matrix([[
        mp.cos(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])
    Sin = mp.matrix([[
        mp.sin(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])

    OmegaCosSin = Cos * Omega * Sin

    Dp = -Phi * (OmegaCosSin.T - OmegaCosSin) * Phi.T
    return (Dp)
Beispiel #11
0
def Construct_Dm(Phi, Psi, Omega, tt):

    Cos = mp.matrix([[
        mp.cos(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])
    Sin = mp.matrix([[
        mp.sin(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])

    OmegaSinCos = Sin * Omega * Cos

    Dm = -Psi * (OmegaSinCos - OmegaSinCos.T) * Psi.T
    return (Dm)
Beispiel #12
0
def fn1(y, n, R, rh, l, pm1, Om, lam, sig):
    K = lam**2 * sig / 2 / fp.sqrt(2 * fp.pi)
    a = (R**2 - rh**2) * l**2 / 4 / sig**2 / rh**2
    b = fp.sqrt(R**2 - rh**2) * Om * l / rh
    Zm = mp.mpf(rh**2 / (R**2 - rh**2) *
                (R**2 / rh**2 * fp.cosh(2 * fp.pi * rh / l * n) - 1))
    if Zm == mp.cosh(y):
        return 0
    elif Zm - fp.cosh(y) > 0:
        return fp.mpf(K * mp.exp(-a * y**2) * mp.cos(b * y) /
                      mp.sqrt(Zm - mp.cosh(y)))
    else:
        return fp.mpf(-K * mp.exp(-a * y**2) * mp.sin(b * y) /
                      mp.sqrt(mp.cosh(y) - Zm))
Beispiel #13
0
def Construct_K(Phi, Psi, Omega, tt):

    Cos = mp.matrix([[
        mp.cos(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])
    Sin = mp.matrix([[
        mp.sin(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])

    OmegaCos = Cos * Omega * Cos
    OmegaSin = Sin * Omega * Sin

    Kmatrix = -Phi * (OmegaCos + OmegaSin.T) * Psi.T
    return (Kmatrix)
Beispiel #14
0
 def verify(self, x0, x1, y0, y1, s, t, x, y):
     "Verify the transformation given by (s, t, x, y) on pentagon."
     pentagon = [(x0, 0), (x1, 0), (0, y0), (0, y1), (self.side, self.side)]
     # reference point in interior of pentagon
     ref = matrix([x0 + x1 + self.side, y0 + y1 + self.side]) / 5
     translation = matrix(
         [s * ref[0] + t * ref[1] + x, -t * ref[0] + s * ref[1] + y])
     # reconstruct rotation angle
     norm = mp.sqrt(s * s + t * t)
     if t < 0:
         angle = -mp.acos(s / norm)
     else:
         angle = mp.acos(s / norm)
     rotation = matrix([[mp.cos(angle), mp.sin(angle)],
                        [-mp.sin(angle), mp.cos(angle)]])
     pentagon = list(map(lambda pt: matrix(pt), pentagon))
     ipentagon = list(
         map(lambda pt: rotation * (pt - ref) + translation, pentagon))
     # Verify that ipentagon is a congruent image of pentagon
     eps = mp.mpf(10)**-(mp.dps - 2)  # accept error in last two digits
     for i in range(5):
         for j in range(i + 1, 5):
             d1 = mp.norm(pentagon[j] - pentagon[i])
             d2 = mp.norm(ipentagon[j] - ipentagon[i])
             dd = abs(d1 - d2)
             assert dd < eps, (pentagon, dd, eps)
     dists = []
     for p in ipentagon:
         dists.append(self.nleft * p)
         dists.append(self.ndown * p)
         dists.append(self.nright * p - self.offset)
     dist = max(map(lambda m: m[0], dists))
     if dist > -self.distance:
         sys.stderr.write("Pentagon failing slack test: %d %d %d %d\n" %
                          (x0, x1, y0, y1))
         return False
     return True
Beispiel #15
0
    def dRdEe_noint(self, lx, ly, band, fdm, mchi_index):
        if band == "pi":
            local_mchi = ct.mchi
            if mchi_index != 0:
                local_mchi = ct.m_chi_list[mchi_index - 1]

            qsqrt = lambda kr: mp.sqrt(local_mchi**2 * ct.vmax**2 - (
                local_mchi / ct.me) * kr**2 - 2 * local_mchi *
                                       (E_pi_minus(lx, ly) + ct.fi))

            qmini = lambda kr: local_mchi * ct.vmax - qsqrt(kr)
            qmaxi = lambda kr: local_mchi * ct.vmax + qsqrt(kr)

        else:
            local_mchi = ct.mchi
            qsqrt = lambda kr: mp.sqrt(ct.mchi**2 * ct.vmax**2 - (
                ct.mchi / ct.me) * kr**2 - 2 * ct.mchi *
                                       (E_sigma(lx, ly, band) + ct.fi))

            qmini = lambda kr: ct.mchi * ct.vmax - qsqrt(kr)
            qmaxi = lambda kr: ct.mchi * ct.vmax + qsqrt(kr)

        return lambda kr, kt, kp: (1 / 2) * mp.sin(kt) * self.dR(
            lx, ly, kr, kt, kp, qmini(kr), qmaxi(kr), band, fdm, local_mchi)
Beispiel #16
0
 def mp_factory(n):
     return (mp.cos, lambda x: -mp.sin(x), lambda x: -mp.cos(x),
             mp.sin)[n % 4]
Beispiel #17
0
#add_function(
#    name="fnlibJ1",
#    mp_function=mp.j1,
#    np_function=fnlib.J1,
#    ocl_function=make_ocl("return sas_J1(q);", "sas_J1", ["lib/polevl.c", "lib/sas_J1.c"]),
#)
add_function(
    name="sin(x)",
    mp_function=mp.sin,
    np_function=np.sin,
    #ocl_function=make_ocl("double sn, cn; SINCOS(q,sn,cn); return sn;", "sas_sin"),
    ocl_function=make_ocl("return sin(q);", "sas_sin"),
)
add_function(
    name="sin(x)/x",
    mp_function=lambda x: mp.sin(x) / x if x != 0 else 1,
    ## scipy sinc function is inaccurate and has an implied pi*x term
    #np_function=lambda x: scipy.special.sinc(x/pi),
    ## numpy sin(x)/x needs to check for x=0
    np_function=lambda x: np.sin(x) / x,
    ocl_function=make_ocl("return sas_sinx_x(q);", "sas_sinc"),
)
add_function(
    name="cos(x)",
    mp_function=mp.cos,
    np_function=np.cos,
    #ocl_function=make_ocl("double sn, cn; SINCOS(q,sn,cn); return cn;", "sas_cos"),
    ocl_function=make_ocl("return cos(q);", "sas_cos"),
)
add_function(
    name="gamma(x)",
Beispiel #18
0
def sin(z):
    return mp.sin(z)
Beispiel #19
0
from mpmath import mp
mp.dps = 50

N = int(sys.argv[1]) if len(sys.argv) > 1 else 20000

inicio = -1 * mp.pi
fim = 1 * mp.pi
dx = (fim - inicio) / (N - 1)
idx = 1 / dx

Idx = mp.mpf(1 / dx)

with open('Sin.h', 'w') as f:

    f.write("\n".join([
        '#define SIN_N {N}',
        '#define SIN_Idx {idx}',
        '#define SIN_inicio {inicio}',
        '#define SIN_fim {fim}',
        '',
        '',
    ]).format(**locals()))

    f.write('const double Sin[] = {')

    for i in range(N):
        f.write('' + str(mp.sin(i * dx + inicio)) + ',\n')

    f.write('\n};')
Beispiel #20
0
def sind(x):
    try:
        return mp.sin(x * mp.pi / 180)
    except:
        return math.sin(x * math.pi / 180)
def colourise(i):
    var = float(mp.sin(mp.radians(i)))
    return (var, var, var)
def log_cap(dim, theta):
    return -0.5 * log2(2 * mp.pi * dim) - log2(
        mp.cos(theta)) + (dim - 1) * log2(mp.sin(theta))
Beispiel #23
0
    def dR(self, lx, ly, kr, kt, kp, qmin, qmax, band, fdm, local_mchi):
        if band == "pi":
            if not self.lastlx == lx or not self.lastly == ly:
                self.P_pi = createP_pi(lx, ly)
                self.lastlx = lx
                self.lastly = ly
                self.E_b = E_pi_minus(lx, ly)

            sqP = lambda qr, qt, qp: mp.re(
                self.P_pi(
                    qr * mp.sin(qt) * mp.cos(qp) - kr * mp.sin(kt) * mp.cos(kp
                                                                            ),
                    qr * mp.sin(qt) * mp.sin(qp) - kr * mp.sin(kt) * mp.sin(kp
                                                                            ),
                    qr * mp.cos(qt) - kr * mp.cos(kt)))**2 + mp.im(
                        self.P_pi(
                            qr * mp.sin(qt) * mp.cos(qp) - kr * mp.sin(kt) * mp
                            .cos(kp),
                            qr * mp.sin(qt) * mp.sin(qp) - kr * mp.sin(
                                kt) * mp.sin(kp),
                            qr * mp.cos(qt) - kr * mp.cos(kt)))**2
        else:
            if not self.lastlx == lx or not self.lastly == ly:
                self.P_sigma = createP_sigma(lx, ly, band)
                self.lastlx = lx
                self.lastly = ly
                self.E_b = E_sigma(lx, ly, band)

            sqP = lambda qr, qt, qp: mp.re(
                self.P_sigma(
                    qr * mp.sin(qt) * mp.cos(qp) - kr * mp.sin(kt) * mp.cos(kp
                                                                            ),
                    qr * mp.sin(qt) * mp.sin(qp) - kr * mp.sin(kt) * mp.sin(kp
                                                                            ),
                    qr * mp.cos(qt) - kr * mp.cos(kt)))**2 + mp.im(
                        self.P_sigma(
                            qr * mp.sin(qt) * mp.cos(qp) - kr * mp.sin(kt) * mp
                            .cos(kp),
                            qr * mp.sin(qt) * mp.sin(qp) - kr * mp.sin(
                                kt) * mp.sin(kp),
                            qr * mp.cos(qt) - kr * mp.cos(kt)))**2

        integrand = lambda qr, qt, qp: (qr) * mp.sin(qt) / (
            4 * mp.pi) * self.eta(qr, kr, self.E_b, local_mchi) * F_DM(
                qr, fdm) * sqP(qr, qt, qp)

        result = mint.integrate(integrand, [qmin, qmax], [0, mp.pi],
                                [0, 2 * mp.pi], self.method)
        return result
Beispiel #24
0
def df3(x):
    return mp.e**x - 2**(-x) * mp.log(2) - 2 * mp.sin(x)
Beispiel #25
0
# goji houteishiki solver

from mpmath import mp

mp.dps = 20

K = lambda k: mp.quad(lambda x: 1/(mp.sqrt(1 - (k**2)*(mp.sin(x)**2))), [0, mp.pi/2])

latparam = lambda k: mp.j*K(mp.sqrt(1-k**2))/K(k)

J = lambda m, t: (phi5(t) + phi5m(t, 0))*(phi5m(t, 4) - phi5m(5, 1))*(phi5m(t, 3) - phi5m(t, 2))

inv_n = lambda n, t: -(1/(n + t))

phi = lambda t: 

kei = lambda R: (r*(5**(5/4)) + mp.sqrt((R**2)*mp.sqrt(5**5) - 16))/(r*(5**(5/4)) + mp.sqrt((R**2)*mp.sqrt(5**5) + 16))

Beispiel #26
0
dx = (fim-inicio)/(N-1)
idx = 1 / dx

Idx = mp.mpf(1/dx)

with open('Exponencial.h', 'w') as f:

    f.write("\n".join([
        '#include <complex>',
        '',
        'using namespace std;',
        '',
        '#define EXP_N {N}',
        '#define EXP_Idx {idx}',
        '#define EXP_inicio {inicio}',
        '#define EXP_fim {fim}',
        '',
        '',
    ]).format(**locals()))

    f.write('const complex<double> Exponencial[] = {')

    for i in range(N):
        value = mp.cos(i*dx + inicio)
        value2 = mp.sin(i*dx + inicio)
        v = "%.50e" % value
        v2 = "%.50e" % value2
        f.write('complex<double>(' + v + ',' + v2 + '),\n')

    f.write('\n};')
Beispiel #27
0
from mpmath import mp
mp.dps = 50

N = int(sys.argv[1]) if len(sys.argv) > 1 else 20000

inicio = -1*mp.pi
fim = 1*mp.pi
dx = (fim-inicio)/(N-1)
idx = 1 / dx

Idx = mp.mpf(1/dx)

with open('Sin.h', 'w') as f:

    f.write("\n".join([
        '#define SIN_N {N}',
        '#define SIN_Idx {idx}',
        '#define SIN_inicio {inicio}',
        '#define SIN_fim {fim}',
        '',
        '',
    ]).format(**locals()))

    f.write('const double Sin[] = {')

    for i in range(N):
        f.write('' + str(mp.sin(i*dx + inicio)) + ',\n')

    f.write('\n};')
Beispiel #28
0
N = long(sys.argv[1]) if len(sys.argv) > 1 else 20000

inicio = -1 * mp.pi
fim = 1 * mp.pi
dx = (fim - inicio) / (N - 1)
idx = 1 / dx

Idx = mp.mpf(1 / dx)

with open("Sin.h", "w") as f:

    f.write(
        "\n".join(
            [
                "#define SIN_N {N}",
                "#define SIN_Idx {idx}",
                "#define SIN_inicio {inicio}",
                "#define SIN_fim {fim}",
                "",
                "",
            ]
        ).format(**locals())
    )

    f.write("const double Sin[] = {")

    for i in range(N):
        f.write("" + str(mp.sin(i * dx + inicio)) + ",\n")

    f.write("\n};")
Beispiel #29
0
def sind(x):
    try:
        return mp.sin(x * mp.pi / 180)
    except:
        return math.sin(x * math.pi / 180)
Beispiel #30
0
def df1(x):
    return mp.cos(x) * mp.sinh(x) - mp.sin(x) * mp.cosh(x)
Beispiel #31
0
dx = (fim - inicio) / (N - 1)
idx = 1 / dx

Idx = mp.mpf(1 / dx)

with open('Exponencial.h', 'w') as f:

    f.write("\n".join([
        '#include <complex>',
        '',
        'using namespace std;',
        '',
        '#define EXP_N {N}',
        '#define EXP_Idx {idx}',
        '#define EXP_inicio {inicio}',
        '#define EXP_fim {fim}',
        '',
        '',
    ]).format(**locals()))

    f.write('const complex<double> Exponencial[] = {')

    for i in range(N):
        value = mp.cos(i * dx + inicio)
        value2 = mp.sin(i * dx + inicio)
        v = "%.50e" % value
        v2 = "%.50e" % value2
        f.write('complex<double>(' + v + ',' + v2 + '),\n')

    f.write('\n};')