Esempio n. 1
0
def reproject_axis_gen2(X, Y, Z, axis, cal):
    #(phase_cal, tilt_cal, curve_cal, gibPhase_cal, gibMag_cal, ogeePhase_cal, ogeeMag_cal) = cal

    B = atan2(Z, X)

    Ydeg = cal.tilt + (-1 if axis else 1) * math.pi / 6.
    tanA = tan(Ydeg)
    normXZ = sqrt(X * X + Z * Z)

    asinArg = tanA * Y / normXZ

    sinYdeg = sin(Ydeg)
    cosYdeg = cos(Ydeg)

    sinPart = sin(B - asin(asinArg) + cal.ogeephase) * cal.ogeemag

    normXYZ = sqrt(X * X + Y * Y + Z * Z)

    modAsinArg = Y / normXYZ / cosYdeg

    asinOut = asin(modAsinArg)

    mod, acc = calc_cal_series(asinOut)

    BcalCurved = sinPart + cal.curve
    asinArg2 = asinArg + mod * BcalCurved / (cosYdeg -
                                             acc * BcalCurved * sinYdeg)

    asinOut2 = asin(asinArg2)
    sinOut2 = sin(B - asinOut2 + cal.gibpha)

    return B - asinOut2 + sinOut2 * cal.gibmag - cal.phase - math.pi / 2.
Esempio n. 2
0
def test_conv7():
    x = Symbol("x")
    y = Symbol("y")
    assert sin(x / 3) == sin(sympy.Symbol("x") / 3)
    assert cos(x / 3) == cos(sympy.Symbol("x") / 3)
    assert tan(x / 3) == tan(sympy.Symbol("x") / 3)
    assert cot(x / 3) == cot(sympy.Symbol("x") / 3)
    assert csc(x / 3) == csc(sympy.Symbol("x") / 3)
    assert sec(x / 3) == sec(sympy.Symbol("x") / 3)
    assert asin(x / 3) == asin(sympy.Symbol("x") / 3)
    assert acos(x / 3) == acos(sympy.Symbol("x") / 3)
    assert atan(x / 3) == atan(sympy.Symbol("x") / 3)
    assert acot(x / 3) == acot(sympy.Symbol("x") / 3)
    assert acsc(x / 3) == acsc(sympy.Symbol("x") / 3)
    assert asec(x / 3) == asec(sympy.Symbol("x") / 3)

    assert sin(x / 3)._sympy_() == sympy.sin(sympy.Symbol("x") / 3)
    assert sin(x / 3)._sympy_() != sympy.cos(sympy.Symbol("x") / 3)
    assert cos(x / 3)._sympy_() == sympy.cos(sympy.Symbol("x") / 3)
    assert tan(x / 3)._sympy_() == sympy.tan(sympy.Symbol("x") / 3)
    assert cot(x / 3)._sympy_() == sympy.cot(sympy.Symbol("x") / 3)
    assert csc(x / 3)._sympy_() == sympy.csc(sympy.Symbol("x") / 3)
    assert sec(x / 3)._sympy_() == sympy.sec(sympy.Symbol("x") / 3)
    assert asin(x / 3)._sympy_() == sympy.asin(sympy.Symbol("x") / 3)
    assert acos(x / 3)._sympy_() == sympy.acos(sympy.Symbol("x") / 3)
    assert atan(x / 3)._sympy_() == sympy.atan(sympy.Symbol("x") / 3)
    assert acot(x / 3)._sympy_() == sympy.acot(sympy.Symbol("x") / 3)
    assert acsc(x / 3)._sympy_() == sympy.acsc(sympy.Symbol("x") / 3)
    assert asec(x / 3)._sympy_() == sympy.asec(sympy.Symbol("x") / 3)
Esempio n. 3
0
def qubit_op_to_expr(qubit_op, angle_folds=0):
    qubit_op.compress()
    dict_op = qubit_op.terms

    expr = 0
    for key in dict_op:
        term = dict_op[key]

        for var in key:
            num, char = var

            if char == 'X':
                term *= se.cos(se.Symbol('phi' + str(num))) * se.sin(
                    se.Symbol('the' + str(num)))
                if angle_folds == 3:
                    term *= se.Symbol('W' + str(num))
            if char == 'Y':
                term *= se.sin(se.Symbol('phi' + str(num))) * se.sin(
                    se.Symbol('the' + str(num)))
                if angle_folds > 1:
                    term *= se.Symbol('Q' + str(num))
            if char == 'Z':
                term *= se.cos(se.Symbol('the' + str(num)))
                if angle_folds > 0:
                    term *= se.Symbol('Z' + str(num))
        expr += term
    return expr
Esempio n. 4
0
def quaternion_from_rpy(roll, pitch, yaw):
    """
    :type roll: Union[float, Symbol]
    :type pitch: Union[float, Symbol]
    :type yaw: Union[float, Symbol]
    :return: 4x1 Matrix
    :type: Matrix
    """
    roll_half = roll / 2.0
    pitch_half = pitch / 2.0
    yaw_half = yaw / 2.0

    c_roll = se.cos(roll_half)
    s_roll = se.sin(roll_half)
    c_pitch = se.cos(pitch_half)
    s_pitch = se.sin(pitch_half)
    c_yaw = se.cos(yaw_half)
    s_yaw = se.sin(yaw_half)

    cc = c_roll * c_yaw
    cs = c_roll * s_yaw
    sc = s_roll * c_yaw
    ss = s_roll * s_yaw

    x = c_pitch * sc - s_pitch * cs
    y = c_pitch * ss + s_pitch * cc
    z = c_pitch * cs - s_pitch * sc
    w = c_pitch * cc + s_pitch * ss

    return se.Matrix([x, y, z, w])
Esempio n. 5
0
def diffable_slerp(q1, q2, t):
    """
    !takes a long time to compile!
    :param q1: 4x1 Matrix
    :type q1: Matrix
    :param q2: 4x1 Matrix
    :type q2: Matrix
    :param t: float, 0-1
    :type t:  Union[float, Symbol]
    :return: 4x1 Matrix; Return spherical linear interpolation between two quaternions.
    :rtype: Matrix
    """
    cos_half_theta = dot(q1, q2)

    if0 = -cos_half_theta
    q2 = diffable_if_greater_zero(if0, -q2, q2)
    cos_half_theta = diffable_if_greater_zero(if0, -cos_half_theta, cos_half_theta)

    if1 = diffable_abs(cos_half_theta) - 1.0

    # enforce acos(x) with -1 < x < 1
    cos_half_theta = diffable_min_fast(1, cos_half_theta)
    cos_half_theta = diffable_max_fast(-1, cos_half_theta)

    half_theta = acos(cos_half_theta)

    sin_half_theta = sqrt(1.0 - cos_half_theta * cos_half_theta)
    # prevent /0
    sin_half_theta = diffable_if_eq_zero(sin_half_theta, 1, sin_half_theta)
    if2 = 0.001 - diffable_abs(sin_half_theta)

    ratio_a = sin((1.0 - t) * half_theta) / sin_half_theta
    ratio_b = sin(t * half_theta) / sin_half_theta
    return diffable_if_greater_eq_zero(if1, se.Matrix(q1),
                                       diffable_if_greater_zero(if2, 0.5 * q1 + 0.5 * q2, ratio_a * q1 + ratio_b * q2))
Esempio n. 6
0
def test_conv7():
    x = Symbol("x")
    y = Symbol("y")
    assert sin(x/3) == sin(sympy.Symbol("x") / 3)
    assert cos(x/3) == cos(sympy.Symbol("x") / 3)
    assert tan(x/3) == tan(sympy.Symbol("x") / 3)
    assert cot(x/3) == cot(sympy.Symbol("x") / 3)
    assert csc(x/3) == csc(sympy.Symbol("x") / 3)
    assert sec(x/3) == sec(sympy.Symbol("x") / 3)
    assert asin(x/3) == asin(sympy.Symbol("x") / 3)
    assert acos(x/3) == acos(sympy.Symbol("x") / 3)
    assert atan(x/3) == atan(sympy.Symbol("x") / 3)
    assert acot(x/3) == acot(sympy.Symbol("x") / 3)
    assert acsc(x/3) == acsc(sympy.Symbol("x") / 3)
    assert asec(x/3) == asec(sympy.Symbol("x") / 3)

    assert sin(x/3)._sympy_() == sympy.sin(sympy.Symbol("x") / 3)
    assert sin(x/3)._sympy_() != sympy.cos(sympy.Symbol("x") / 3)
    assert cos(x/3)._sympy_() == sympy.cos(sympy.Symbol("x") / 3)
    assert tan(x/3)._sympy_() == sympy.tan(sympy.Symbol("x") / 3)
    assert cot(x/3)._sympy_() == sympy.cot(sympy.Symbol("x") / 3)
    assert csc(x/3)._sympy_() == sympy.csc(sympy.Symbol("x") / 3)
    assert sec(x/3)._sympy_() == sympy.sec(sympy.Symbol("x") / 3)
    assert asin(x/3)._sympy_() == sympy.asin(sympy.Symbol("x") / 3)
    assert acos(x/3)._sympy_() == sympy.acos(sympy.Symbol("x") / 3)
    assert atan(x/3)._sympy_() == sympy.atan(sympy.Symbol("x") / 3)
    assert acot(x/3)._sympy_() == sympy.acot(sympy.Symbol("x") / 3)
    assert acsc(x/3)._sympy_() == sympy.acsc(sympy.Symbol("x") / 3)
    assert asec(x/3)._sympy_() == sympy.asec(sympy.Symbol("x") / 3)
Esempio n. 7
0
def sin(expr):
    """Sine"""
    if type(expr) == GC:
        return GC(
            se.sin(expr.expr),
            {s: se.cos(expr.expr) * d
             for s, d in expr.gradients.items()})
    return se.sin(expr)
Esempio n. 8
0
def test_sin():
    x = Symbol("x")
    y = Symbol("y")
    e = sin(x)
    assert e.subs({x: y}) == sin(y)
    assert e.subs({x: y}) != sin(x)

    e = cos(x)
    assert e.subs({x: 0}) == 1
    assert e.subs(x, 0) == 1
Esempio n. 9
0
def test_sin():
    x = Symbol("x")
    y = Symbol("y")
    e = sin(x)
    assert e.subs({x: y}) == sin(y)
    assert e.subs({x: y}) != sin(x)

    e = cos(x)
    assert e.subs({x: 0}) == 1
    assert e.subs(x, 0) == 1
Esempio n. 10
0
def test_sin():
    x = Symbol("x")
    e = sin(x)
    assert e == sin(x)
    assert e != cos(x)

    assert sin(x).diff(x) == cos(x)
    assert cos(x).diff(x) == -sin(x)

    e = sqrt(x).diff(x).diff(x)
    f = sin(e)
    g = f.diff(x).diff(x)
    assert isinstance(g, Add)
Esempio n. 11
0
def quaternion_from_axis_angle(axis, angle):
    """
    :param axis: 3x1 Matrix
    :type axis: Matrix
    :type angle: Union[float, Symbol]
    :return: 4x1 Matrix
    :rtype: Matrix
    """
    half_angle = angle / 2
    return se.Matrix([axis[0] * se.sin(half_angle),
                      axis[1] * se.sin(half_angle),
                      axis[2] * se.sin(half_angle),
                      se.cos(half_angle)])
Esempio n. 12
0
def test_sin():
    x = Symbol("x")
    e = sin(x)
    assert e == sin(x)
    assert e != cos(x)

    assert sin(x).diff(x) == cos(x)
    assert cos(x).diff(x) == -sin(x)

    e = sqrt(x).diff(x).diff(x)
    f = sin(e)
    g = f.diff(x).diff(x)
    assert isinstance(g, Add)
Esempio n. 13
0
    def test_complex_expression(self):
        expression = 3**f(42) + 23 - f(
            43, 44) + f(45 + a) * sin(g(f(46, 47, 48) + 17) - g(4)) + sin(
                f(42))

        self.assertEqual(
            collect_arguments(expression, f),
            {(Integer(42), ), (Integer(43), Integer(44)), (45 + a, ),
             (Integer(46), Integer(47), Integer(48))})

        self.assertEqual(count_calls(expression, f), 5)
        self.assertTrue(has_function(expression, f))
        self.assertEqual(
            replace_function(expression, f, g), 3**g(42) + 23 - g(43, 44) +
            g(45 + a) * sin(g(g(46, 47, 48) + 17) - g(4)) + sin(g(42)))
Esempio n. 14
0
 def dydt(self, pre_syn_neurons):  # a list of pre-synaptic neurons
     # define how neurons are coupled here
     v_i = self.mem_pot
     coupling_sum = sum(
         symengine.sin(n.mem_pot - v_i) for n in pre_syn_neurons)
     coupling_term = couple_const * coupling_sum
     yield self.int_freq + coupling_term
Esempio n. 15
0
def run_benchmark(n):
    a0 = symbols("a0")
    a1 = symbols("a1")
    e = a0 + a1
    f = 0
    for i in range(2, n):
        s = symbols("a%s" % i)
        e = e + sin(s)
        f = f + sin(s)
    f = -f
    t1 = clock()
    e = expand(e**2)
    e = e.xreplace({a0: f})
    e = expand(e)
    t2 = clock()
    print("%s ms" % (1000 * (t2 - t1)))
Esempio n. 16
0
def rotation_matrix_from_axis_angle(axis, angle):
    """
    Conversion of unit axis and angle to 4x4 rotation matrix according to:
    http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm
    :param axis: 3x1 Matrix
    :type axis: Matrix
    :type angle: Union[float, Symbol]
    :return: 4x4 Matrix
    :rtype: Matrix
    """
    ct = se.cos(angle)
    st = se.sin(angle)
    vt = 1 - ct
    m_vt_0 = vt * axis[0]
    m_vt_1 = vt * axis[1]
    m_vt_2 = vt * axis[2]
    m_st_0 = axis[0] * st
    m_st_1 = axis[1] * st
    m_st_2 = axis[2] * st
    m_vt_0_1 = m_vt_0 * axis[1]
    m_vt_0_2 = m_vt_0 * axis[2]
    m_vt_1_2 = m_vt_1 * axis[2]
    return se.Matrix(
        [[ct + m_vt_0 * axis[0], -m_st_2 + m_vt_0_1, m_st_1 + m_vt_0_2, 0],
         [m_st_2 + m_vt_0_1, ct + m_vt_1 * axis[1], -m_st_0 + m_vt_1_2, 0],
         [-m_st_1 + m_vt_0_2, m_st_0 + m_vt_1_2, ct + m_vt_2 * axis[2], 0],
         [0, 0, 0, 1]])
Esempio n. 17
0
def axisanglerotationmatrix(axis_angle):
    R = axisanglemagnitude(axis_angle)

    x = axis_angle[0] / R
    y = axis_angle[1] / R
    z = axis_angle[2] / R

    csr = sp.cos(R)
    one_minus_csr = (1 - csr)
    snr = sp.sin(R)

    return sp.Matrix([[
        csr + x * x * (1 - csr), x * y * one_minus_csr - z * snr,
        x * z * one_minus_csr + y * snr
    ],
                      [
                          y * x * one_minus_csr + z * snr,
                          csr + y * y * one_minus_csr,
                          y * z * one_minus_csr - x * snr
                      ],
                      [
                          z * x * one_minus_csr - y * snr,
                          z * y * one_minus_csr + x * snr,
                          csr + z * z * one_minus_csr
                      ]])
Esempio n. 18
0
def axisangle2quat(axis_angle):
    qi, qj, qk = axis_angle
    mag = axisanglemagnitude(axis_angle)
    v = [qi / mag, qj / mag, qk / mag]

    sn = sin(mag / 2.0)
    return quatnormalize([cos(mag / 2.0), sn * v[0], sn * v[1], sn * v[2]])
Esempio n. 19
0
def test_eval_double1():
    x = Symbol("x")
    y = Symbol("y")
    e = sin(x)**2 + cos(x)**2
    e = e.subs(x, 7)
    assert abs(e.n(real=True) - 1) < 1e-9
    assert abs(e.n() - 1) < 1e-9
Esempio n. 20
0
    def integralKernelMinus(self, n):
        n = n - 1
        lala1 = sy.jacobi(n, si.Rational(1, 2), si.Rational(3, 2), r[0])
        lala2 = sy.jacobi(n, si.Rational(3, 2), si.Rational(1, 2), r[0])

        return self.prefactor(n) * (si.cos(r[0] / 2) * lala1 * ident +
                                    I * si.sin(r[0] / 2) * lala2 * sigma3)
Esempio n. 21
0
	def kuramotos():
		for i in range(n):
			yield ω + c/(n-1)*sum(
						sin(y(j,t-τ[i,j])-y(i))
						for j in range(n)
						if A[j,i]
					)
Esempio n. 22
0
def run_benchmark(n):
    a0 = symbols("a0")
    a1 = symbols("a1")
    e = a0 + a1
    f = 0;
    for i in range(2, n):
        s = symbols("a%s" % i)
        e = e + sin(s)
        f = f + sin(s)
    f = -f
    t1 = clock()
    e = expand(e**2)
    e = e.xreplace({a0: f})
    e = expand(e)
    t2 = clock()
    print("%s ms" % (1000 * (t2 - t1)))
Esempio n. 23
0
def axisanglerotationmatrix(axis_angle):
    R = axisanglemagnitude(axis_angle)

    x = Piecewise((axis_angle[0] / R, R > 0), (1, True))
    y = Piecewise((axis_angle[1] / R, R > 0), (0, True))
    z = Piecewise((axis_angle[2] / R, R > 0), (0, True))

    csr = sp.cos(R)
    one_minus_csr = (1 - csr)
    snr = sp.sin(R)

    return sp.Matrix([[
        csr + x * x * (1 - csr), x * y * one_minus_csr - z * snr,
        x * z * one_minus_csr + y * snr
    ],
                      [
                          y * x * one_minus_csr + z * snr,
                          csr + y * y * one_minus_csr,
                          y * z * one_minus_csr - x * snr
                      ],
                      [
                          z * x * one_minus_csr - y * snr,
                          z * y * one_minus_csr + x * snr,
                          csr + z * z * one_minus_csr
                      ]])
Esempio n. 24
0
def kuramotos_f():
	for i in range(n):
		coupling_sum = sum(
				sin(y(j)-y(i))
				for j in range(n)
				if A[j,i]
			)
		yield omega[i] + c/(n-1)*coupling_sum
Esempio n. 25
0
	def f():
		for i in range(N):
			coupling_sum = sum( y(3*j)-y(3*i) for j in range(N) if A[i,j] )
			coupling_term = k * symengine.sin(t) * coupling_sum
			yield -ω[i] * y(3*i+1) - y(3*i+2) + coupling_term
			yield  ω[i] * y(3*i) + a*y(3*i+1)
			coupling_term_2 = k * (sum_z-N*y(3*i+2))
			yield b + y(3*i+2) * (y(3*i) - c) + coupling_term_2
Esempio n. 26
0
def generate_schedule_blocks():
    """Standard QPY testcase for schedule blocks."""
    from qiskit.pulse import builder, channels, library
    from qiskit.utils import optionals

    # Parameterized schedule test is avoided.
    # Generated reference and loaded QPY object may induce parameter uuid mismatch.
    # As workaround, we need test with bounded parameters, however, schedule.parameters
    # are returned as Set and thus its order is random.
    # Since schedule parameters are validated, we cannot assign random numbers.
    # We need to upgrade testing framework.

    schedule_blocks = []

    # Instructions without parameters
    with builder.build() as block:
        with builder.align_sequential():
            builder.set_frequency(5e9, channels.DriveChannel(0))
            builder.shift_frequency(10e6, channels.DriveChannel(1))
            builder.set_phase(1.57, channels.DriveChannel(0))
            builder.shift_phase(0.1, channels.DriveChannel(1))
            builder.barrier(channels.DriveChannel(0), channels.DriveChannel(1))
            builder.play(library.Gaussian(160, 0.1, 40),
                         channels.DriveChannel(0))
            builder.play(library.GaussianSquare(800, 0.1, 64, 544),
                         channels.ControlChannel(0))
            builder.play(library.Drag(160, 0.1, 40, 1.5),
                         channels.DriveChannel(1))
            builder.play(library.Constant(800, 0.1),
                         channels.MeasureChannel(0))
            builder.acquire(1000, channels.AcquireChannel(0),
                            channels.MemorySlot(0))
    schedule_blocks.append(block)
    # Raw symbolic pulse
    if optionals.HAS_SYMENGINE:
        import symengine as sym
    else:
        import sympy as sym
    duration, amp, t = sym.symbols("duration amp t")  # pylint: disable=invalid-name
    expr = amp * sym.sin(2 * sym.pi * t / duration)
    my_pulse = library.SymbolicPulse(
        pulse_type="Sinusoidal",
        duration=100,
        parameters={"amp": 0.1},
        envelope=expr,
        valid_amp_conditions=sym.Abs(amp) <= 1.0,
    )
    with builder.build() as block:
        builder.play(my_pulse, channels.DriveChannel(0))
    schedule_blocks.append(block)
    # Raw waveform
    my_waveform = 0.1 * np.sin(2 * np.pi * np.linspace(0, 1, 100))
    with builder.build() as block:
        builder.play(my_waveform, channels.DriveChannel(0))
    schedule_blocks.append(block)

    return schedule_blocks
Esempio n. 27
0
def kuramoto_f(theta, _):
    dtheta = zeros(n, float)
    for i in range(n):
        coupling_sum = 0.0
        for j in range(n):
            if (networkMatrix[j, i] == 1):
                coupling_sum += sin(theta[j] - theta[i])
        dtheta[i] = (omegas[i] + (couplingConstant * coupling_sum))
    return dtheta
Esempio n. 28
0
def axisangle2quat(axis_angle):
    mag = axisanglemagnitude(axis_angle)

    x = axis_angle[0] / mag
    y = axis_angle[1] / mag
    z = axis_angle[2] / mag

    sn = sin(mag / 2.0)
    return quatnormalize([cos(mag / 2.0), sn * x, sn * y, sn * z])
Esempio n. 29
0
def _get_array():
    X, Y, Z = inp = array.array('d', [1, 2, 3])
    args = x, y, z = se.symbols('x y z')
    exprs = [x+y+z, se.sin(x)*se.log(y)*se.exp(z)]
    ref = [X+Y+Z, math.sin(X)*math.log(Y)*math.exp(Z)]

    def check(arr):
        assert all([abs(x1-x2) < 1e-13 for x1, x2 in zip(ref, arr)])
    return args, exprs, inp, check
Esempio n. 30
0
 def f():
     for i in range(N):
         coupling_sum = sum(
             y(3 * j) - y(3 * i) for j in range(N) if A[i, j])
         coupling_term = k * symengine.sin(t) * coupling_sum
         yield -ω[i] * y(3 * i + 1) - y(3 * i + 2) + coupling_term
         yield ω[i] * y(3 * i) + a * y(3 * i + 1)
         coupling_term_2 = k * (sum_z - N * y(3 * i + 2))
         yield b + y(3 * i + 2) * (y(3 * i) - c) + coupling_term_2
Esempio n. 31
0
def _get_array():
    X, Y, Z = inp = array.array('d', [1, 2, 3])
    args = x, y, z = se.symbols('x y z')
    exprs = [x+y+z, se.sin(x)*se.log(y)*se.exp(z)]
    ref = [X+Y+Z, math.sin(X)*math.log(Y)*math.exp(Z)]

    def check(arr):
        assert all([abs(x1-x2) < 1e-13 for x1, x2 in zip(ref, arr)])
    return args, exprs, inp, check
Esempio n. 32
0
def test_CCodePrinter():
    x = Symbol("x")
    y = Symbol("y")
    myprinter = CCodePrinter()

    assert myprinter.doprint(1+x, "bork") == "bork = 1 + x;"
    assert myprinter.doprint(1*x) == "x"
    assert myprinter.doprint(MutableDenseMatrix(1, 2, [x, y]), "larry") == "larry[0] = x;\nlarry[1] = y;"
    raises(TypeError, lambda: myprinter.doprint(sin(x), Integer))
    raises(RuntimeError, lambda: myprinter.doprint(MutableDenseMatrix(1, 2, [x, y])))
Esempio n. 33
0
def test_llvm_double():
    import numpy as np
    from symengine import Lambdify
    args = x, y, z = symbols('x y z')
    expr = sin(sinh(x + y) + z)
    l = Lambdify(args, expr, cse=True, backend='llvm')
    ss = pickle.dumps(l)
    ll = pickle.loads(ss)
    inp = [1, 2, 3]
    assert np.allclose(l(inp), ll(inp))
Esempio n. 34
0
def axisanglecompose(axis_angle, axis_angle2):
    a = axisanglemagnitude(axis_angle)
    ah = axisanglenormalize(axis_angle)

    b = axisanglemagnitude(axis_angle2)
    bh = axisanglenormalize(axis_angle2)

    sina = sin(a / 2)
    asina = [ah[0] * sina, ah[1] * sina, ah[2] * sina]

    sinb = sin(b / 2)
    bsinb = [bh[0] * sinb, bh[1] * sinb, bh[2] * sinb]

    c = 2 * acos(cos(a / 2)*cos(b / 2) - dot3d(asina, bsinb))
    d = axisanglenormalize(cos(a / 2) * sp.Matrix(bsinb) + cos(b / 2) * sp.Matrix(asina) + cross3d(asina, bsinb))
    return sp.Matrix([
            c * d[0],
            c * d[1],
            c * d[2]
        ])
Esempio n. 35
0
def test_ccode():
    x = Symbol("x")
    y = Symbol("y")
    assert ccode(x) == "x"
    assert ccode(x**3) == "pow(x, 3)"
    assert ccode(x**(y**3)) == "pow(x, pow(y, 3))"
    assert ccode(x**-1.0) == "pow(x, -1.0)"
    assert ccode(Max(x, x*x)) == "fmax(x, pow(x, 2))"
    assert ccode(sin(x)) == "sin(x)"
    assert ccode(Integer(67)) == "67"
    assert ccode(Integer(-1)) == "-1"
Esempio n. 36
0
def test_llvm_double():
    import numpy as np
    from symengine import Lambdify
    args = x, y, z = symbols('x y z')
    expr = sin(sinh(x + y) + z)
    l = Lambdify(args, expr, cse=True, backend='llvm')
    ss = pickle.dumps(l)
    ll = pickle.loads(ss)
    inp = [1, 2, 3]
    assert np.allclose(l(inp), ll(inp))
    # check that the LLVMDoubleVisitor is properly dumped/loaded
    assert np.allclose(l.unsafe_real(inp), ll.unsafe_real(inp))
Esempio n. 37
0
def rotation_matrix_from_rpy(roll, pitch, yaw):
    """
    Conversion of roll, pitch, yaw to 4x4 rotation matrix according to:
    https://github.com/orocos/orocos_kinematics_dynamics/blob/master/orocos_kdl/src/frames.cpp#L167
    :type roll: Union[float, Symbol]
    :type pitch: Union[float, Symbol]
    :type yaw: Union[float, Symbol]
    :return: 4x4 Matrix
    :rtype: Matrix
    """
    # TODO don't split this into 3 matrices

    rx = se.Matrix([[1, 0, 0, 0],
                    [0, se.cos(roll), -se.sin(roll), 0],
                    [0, se.sin(roll), se.cos(roll), 0],
                    [0, 0, 0, 1]])
    ry = se.Matrix([[se.cos(pitch), 0, se.sin(pitch), 0],
                    [0, 1, 0, 0],
                    [-se.sin(pitch), 0, se.cos(pitch), 0],
                    [0, 0, 0, 1]])
    rz = se.Matrix([[se.cos(yaw), -se.sin(yaw), 0, 0],
                    [se.sin(yaw), se.cos(yaw), 0, 0],
                    [0, 0, 1, 0],
                    [0, 0, 0, 1]])
    return (rz * ry * rx)
Esempio n. 38
0
def test_DictBasic():
    x, y, z = symbols("x y z")
    d = DictBasic({x: 2, y: z})

    assert str(d) == "{x: 2, y: z}" or str(d) == "{y: z, x: 2}"
    assert d[x] == 2

    raises(KeyError, lambda: d[2*z])
    if 2*z in d:
        assert False

    d[2*z] = x
    assert d[2*z] == x
    if 2*z not in d:
        assert False
    assert set(d.items()) == set([(2*z, x), (x, Integer(2)), (y, z)])

    del d[x]
    assert set(d.keys()) == set([2*z, y])
    assert set(d.values()) == set([x, z])

    e = y + sin(2*z)
    assert e.subs(d) == z + sin(x)
Esempio n. 39
0
def test_conv7b():
    x = sympy.Symbol("x")
    y = sympy.Symbol("y")
    assert sympify(sympy.sin(x/3)) == sin(Symbol("x") / 3)
    assert sympify(sympy.sin(x/3)) != cos(Symbol("x") / 3)
    assert sympify(sympy.cos(x/3)) == cos(Symbol("x") / 3)
    assert sympify(sympy.tan(x/3)) == tan(Symbol("x") / 3)
    assert sympify(sympy.cot(x/3)) == cot(Symbol("x") / 3)
    assert sympify(sympy.csc(x/3)) == csc(Symbol("x") / 3)
    assert sympify(sympy.sec(x/3)) == sec(Symbol("x") / 3)
    assert sympify(sympy.asin(x/3)) == asin(Symbol("x") / 3)
    assert sympify(sympy.acos(x/3)) == acos(Symbol("x") / 3)
    assert sympify(sympy.atan(x/3)) == atan(Symbol("x") / 3)
    assert sympify(sympy.acot(x/3)) == acot(Symbol("x") / 3)
    assert sympify(sympy.acsc(x/3)) == acsc(Symbol("x") / 3)
    assert sympify(sympy.asec(x/3)) == asec(Symbol("x") / 3)
Esempio n. 40
0
def spherical_harmonics(lmax):
    """Symbolic real spherical harmonics up to order lmax.

    .. code-block:: python

        sh = spherical_harmonics(6)  # Inclusive, so computes up to l = 6
        sh[3][-3]                    # symbolic f-phi angular function

    Args:
        lmax (int): highest order angular momentum quantum number
    """
    phase = {m: (-1) ** m for m in range(lmax + 1)}
    facts = {n: fac(n) for n in range(2 * lmax + 1)}
    sh = OrderedDict()
    for L in range(lmax + 1):
        sh[L] = OrderedDict()
        rac = ((2 * L + 1) / (4 * np.pi)) ** 0.5
        der = (_x ** 2 - 1) ** L
        den = 2 ** L * facts[L]
        for _ in range(L):
            der = der.diff(_x)
        for m in range(L + 1):
            pol = (1 - _x ** 2) ** (m/2)
            if m: der = der.diff(_x)
            leg = phase[m] / den * (pol * der).subs({_x: _z / _r})
            if not m:
                sh[L][m] = rac * leg
                continue
            N = 2 ** 0.5 * phase[m]
            facs = facts[L - m] / facts[L + m]
            norm = facs ** 0.5
            phi = (m * _x).subs({_x: 'arctan2(_y, _x)'})
            fun = cos(phi)
            sh[L][m] = N * rac * norm * leg * fun
            fun = sin(phi)
            sh[L][-m] = N * rac * norm * leg * fun
    return sh
Esempio n. 41
0
def test_sage_conversions():
    try:
        import sage.all as sage
    except ImportError:
        return

    x, y = sage.SR.var('x y')
    x1, y1 = symbols('x, y')

    # Symbol
    assert x1._sage_() == x
    assert x1 == sympify(x)

    # Integer
    assert Integer(12)._sage_() == sage.Integer(12)
    assert Integer(12) == sympify(sage.Integer(12))

    # Rational
    assert (Integer(1) / 2)._sage_() == sage.Integer(1) / 2
    assert Integer(1) / 2 == sympify(sage.Integer(1) / 2)

    # Operators
    assert x1 + y == x1 + y1
    assert x1 * y == x1 * y1
    assert x1 ** y == x1 ** y1
    assert x1 - y == x1 - y1
    assert x1 / y == x1 / y1

    assert x + y1 == x + y
    assert x * y1 == x * y
    # Doesn't work in Sage 6.1.1ubuntu2
    # assert x ** y1 == x ** y
    assert x - y1 == x - y
    assert x / y1 == x / y

    # Conversions
    assert (x1 + y1)._sage_() == x + y
    assert (x1 * y1)._sage_() == x * y
    assert (x1 ** y1)._sage_() == x ** y
    assert (x1 - y1)._sage_() == x - y
    assert (x1 / y1)._sage_() == x / y

    assert x1 + y1 == sympify(x + y)
    assert x1 * y1 == sympify(x * y)
    assert x1 ** y1 == sympify(x ** y)
    assert x1 - y1 == sympify(x - y)
    assert x1 / y1 == sympify(x / y)

    # Functions
    assert sin(x1) == sin(x)
    assert sin(x1)._sage_() == sage.sin(x)
    assert sin(x1) == sympify(sage.sin(x))

    assert cos(x1) == cos(x)
    assert cos(x1)._sage_() == sage.cos(x)
    assert cos(x1) == sympify(sage.cos(x))

    assert function_symbol('f', x1, y1)._sage_() == sage.function('f', x, y)
    assert function_symbol('f', 2 * x1, x1 + y1).diff(x1)._sage_() == sage.function('f', 2 * x, x + y).diff(x)

    # For the following test, sage needs to be modified
    # assert sage.sin(x) == sage.sin(x1)

    # Constants
    assert pi._sage_() == sage.pi
    assert E._sage_() == sage.e
    assert I._sage_() == sage.I

    assert pi == sympify(sage.pi)
    assert E == sympify(sage.e)

    # SympyConverter does not support converting the following
    # assert I == sympify(sage.I)

    # Matrix
    assert DenseMatrix(1, 2, [x1, y1])._sage_() == sage.matrix([[x, y]])

    # SympyConverter does not support converting the following
    # assert DenseMatrix(1, 2, [x1, y1]) == sympify(sage.matrix([[x, y]]))

    # Sage Number
    a = sage.Mod(2, 7)
    b = PyNumber(a, sage_module)

    a = a + 8
    b = b + 8
    assert isinstance(b, PyNumber)
    assert b._sage_() == a

    a = a + x
    b = b + x
    assert isinstance(b, Add)
    assert b._sage_() == a

    # Sage Function
    e = x1 + wrap_sage_function(sage.log_gamma(x))
    assert str(e) == "x + log_gamma(x)"
    assert isinstance(e, Add)
    assert e + wrap_sage_function(sage.log_gamma(x)) == x1 + 2*wrap_sage_function(sage.log_gamma(x))

    f = e.subs({x1 : 10})
    assert f == 10 + log(362880)

    f = e.subs({x1 : 2})
    assert f == 2

    f = e.subs({x1 : 100});
    v = f.n(53, real=True);
    assert abs(float(v) - 459.13420537) < 1e-7

    f = e.diff(x1)
Esempio n. 42
0
from jitcdde import t, y, jitcdde
from symengine import sin
import numpy as np

T = 200
A = 0.9/2/np.pi
τ_0 = 1.50
f = lambda z: 4*z*(1-z)
τ = τ_0 + A*sin(2*np.pi*t)

model = [ T*( -y(0) + f(y(0,t-τ)) ) ]

DDE = jitcdde(model,max_delay=τ_0+A)
DDE.past_from_function([0.4+0.2*sin(t)])
DDE.set_integration_parameters(max_step=0.01,first_step=0.01)
DDE.integrate_blindly(τ_0+A,0.01)

for time in DDE.t + 100 + np.arange(0,10,0.01):
	print(DDE.integrate(time)[0])
Esempio n. 43
0
def test_sage_conversions():
    try:
        import sage.all as sage
    except ImportError:
        return

    x, y = sage.SR.var('x y')
    x1, y1 = symbols('x, y')

    # Symbol
    assert x1._sage_() == x
    assert x1 == sympify(x)

    # Integer
    assert Integer(12)._sage_() == sage.Integer(12)
    assert Integer(12) == sympify(sage.Integer(12))

    # Rational
    assert (Integer(1) / 2)._sage_() == sage.Integer(1) / 2
    assert Integer(1) / 2 == sympify(sage.Integer(1) / 2)

    # Operators
    assert x1 + y == x1 + y1
    assert x1 * y == x1 * y1
    assert x1 ** y == x1 ** y1
    assert x1 - y == x1 - y1
    assert x1 / y == x1 / y1

    assert x + y1 == x + y
    assert x * y1 == x * y
    # Doesn't work in Sage 6.1.1ubuntu2
    # assert x ** y1 == x ** y
    assert x - y1 == x - y
    assert x / y1 == x / y

    # Conversions
    assert (x1 + y1)._sage_() == x + y
    assert (x1 * y1)._sage_() == x * y
    assert (x1 ** y1)._sage_() == x ** y
    assert (x1 - y1)._sage_() == x - y
    assert (x1 / y1)._sage_() == x / y

    assert x1 + y1 == sympify(x + y)
    assert x1 * y1 == sympify(x * y)
    assert x1 ** y1 == sympify(x ** y)
    assert x1 - y1 == sympify(x - y)
    assert x1 / y1 == sympify(x / y)

    # Functions
    assert sin(x1) == sin(x)
    assert sin(x1)._sage_() == sage.sin(x)
    assert sin(x1) == sympify(sage.sin(x))

    assert cos(x1) == cos(x)
    assert cos(x1)._sage_() == sage.cos(x)
    assert cos(x1) == sympify(sage.cos(x))

    assert function_symbol('f', x1, y1)._sage_() == sage.function('f', x, y)
    assert function_symbol('f', 2 * x1, x1 + y1).diff(x1)._sage_() == sage.function('f', 2 * x, x + y).diff(x)

    # For the following test, sage needs to be modified
    # assert sage.sin(x) == sage.sin(x1)

    # Constants
    assert pi._sage_() == sage.pi
    assert E._sage_() == sage.e
    assert I._sage_() == sage.I

    assert pi == sympify(sage.pi)
    assert E == sympify(sage.e)

    # SympyConverter does not support converting the following
    # assert I == sympify(sage.I)

    # Matrix
    assert DenseMatrix(1, 2, [x1, y1])._sage_() == sage.matrix([[x, y]])
Esempio n. 44
0
def test_eval_double2():
    x = Symbol("x")
    y = Symbol("y")
    e = sin(x)**2 + cos(x)**2
    raises(RuntimeError, lambda: (abs(eval_double(e) - 1) < 1e-9))
Esempio n. 45
0
def test_eval_double1():
    x = Symbol("x")
    y = Symbol("y")
    e = sin(x)**2 + cos(x)**2
    e = e.subs(x, 7)
    assert abs(eval_double(e) - 1) < 1e-9
Esempio n. 46
0
def test_conv7():
    x = Symbol("x")
    y = Symbol("y")
    assert sin(x/3)._sympy_() == sympy.sin(sympy.Symbol("x") / 3)
    assert sin(x/3)._sympy_() != sympy.cos(sympy.Symbol("x") / 3)
    assert cos(x/3)._sympy_() == sympy.cos(sympy.Symbol("x") / 3)
Esempio n. 47
0
def test_conv7b():
    x = sympy.Symbol("x")
    y = sympy.Symbol("y")
    assert sympify(sympy.sin(x/3)) == sin(Symbol("x") / 3)
    assert sympify(sympy.sin(x/3)) != cos(Symbol("x") / 3)
    assert sympify(sympy.cos(x/3)) == cos(Symbol("x") / 3)
Esempio n. 48
0
def test_xreplace():
    x = Symbol("x")
    y = Symbol("y")
    f = sin(cos(x))
    assert f.xreplace({x: y}) == sin(cos(y))