Пример #1
0
def test_is_scalar_sparse_matrix():
    np = import_module('numpy')
    if not np:
        skip("numpy not installed.")

    scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
    if not scipy:
        skip("scipy not installed.")

    numqubits = 2
    id_only = False

    id_gate = (IdentityGate(1),)
    assert is_scalar_sparse_matrix(id_gate, numqubits, id_only) is True

    x0 = X(0)
    xx_circuit = (x0, x0)
    assert is_scalar_sparse_matrix(xx_circuit, numqubits, id_only) is True

    x1 = X(1)
    y1 = Y(1)
    xy_circuit = (x1, y1)
    assert is_scalar_sparse_matrix(xy_circuit, numqubits, id_only) is False

    z1 = Z(1)
    xyz_circuit = (x1, y1, z1)
    assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is True

    cnot = CNOT(1, 0)
    cnot_circuit = (cnot, cnot)
    assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True

    h = H(0)
    hh_circuit = (h, h)
    assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True

    # NOTE:
    # The elements of the sparse matrix for the following circuit
    # is actually 1.0000000000000002+0.0j.
    h1 = H(1)
    xhzh_circuit = (x1, h1, z1, h1)
    assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True

    id_only = True
    assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True
    assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is False
    assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True
    assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True
Пример #2
0
def has_module(module):
    """
    Return True if module exists, otherwise run skip().

    module should be a string.
    """
    # To give a string of the module name to skip(), this function takes a
    # string.  So we don't waste time running import_module() more than once,
    # just map the three modules tested here in this dict.
    modnames = {'numpy': numpy, 'Cython': Cython, 'f2py': f2py}

    if modnames[module]:
        if module == 'f2py' and not f2pyworks:
            skip("Couldn't run f2py.")
        return True
    skip("Couldn't import %s." % module)
Пример #3
0
def test_issue_18770():
    numpy = import_module('numpy')
    if not numpy:
        skip("numpy not installed.")

    from sympy import lambdify, Min, Max

    expr1 = Min(0.1 * x + 3, x + 1, 0.5 * x + 1)
    func = lambdify(x, expr1, "numpy")
    assert (func(numpy.linspace(0, 3, 3)) == [1.0, 1.75, 2.5]).all()
    assert func(4) == 3

    expr1 = Max(x**2, x**3)
    func = lambdify(x, expr1, "numpy")
    assert (func(numpy.linspace(-1, 2, 4)) == [1, 0, 1, 8]).all()
    assert func(4) == 64
Пример #4
0
def test_numpy_logical_ops():
    if not numpy:
        skip("numpy not installed.")
    and_func = lambdify((x, y), And(x, y), modules="numpy")
    and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy")
    or_func = lambdify((x, y), Or(x, y), modules="numpy")
    or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy")
    not_func = lambdify((x), Not(x), modules="numpy")
    arr1 = numpy.array([True, True])
    arr2 = numpy.array([False, True])
    arr3 = numpy.array([True, False])
    numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True]))
    numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False]))
    numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True]))
    numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True]))
    numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False]))
Пример #5
0
def test_sample_numpy():
    distribs_numpy = [
        Binomial("B", 5, 0.4),
    ]
    size = 3
    numpy = import_module('numpy')
    if not numpy:
        skip('Numpy is not installed. Abort tests for _sample_numpy.')
    else:
        for X in distribs_numpy:
            samps = sample(X, size=size, library='numpy')
            for sam in samps:
                assert sam in X.pspace.domain.set
        raises(NotImplementedError, lambda: sample(Die("D"), library='numpy'))
    raises(NotImplementedError,
           lambda: Die("D").pspace.sample(library='tensorflow'))
Пример #6
0
def test_prudnikov_3():
    if ON_TRAVIS:
        # See https://github.com/sympy/sympy/pull/12795
        skip("Too slow for travis.")

    h = S.Half
    assert can_do([Rational(1, 4), Rational(3, 4)], [h])
    assert can_do([Rational(1, 4), Rational(3, 4)], [3 * h])
    assert can_do([Rational(1, 3), Rational(2, 3)], [3 * h])
    assert can_do([Rational(3, 4), Rational(5, 4)], [h])
    assert can_do([Rational(3, 4), Rational(5, 4)], [3 * h])

    for p in [1, 2, 3, 4]:
        for n in [-h, h, 1, 3 * h, 2, 5 * h, 3, 7 * h, 4, 9 * h]:
            for m in [1, 3 * h, 2, 5 * h, 3, 7 * h, 4]:
                assert can_do([p, m], [n])
Пример #7
0
def test_sample_pymc3():
    distribs_pymc3 = [Bernoulli('B', 0.2), Binomial('N', 5, 0.4)]
    size = 3
    pymc3 = import_module('pymc3')
    if not pymc3:
        skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
    else:
        with ignore_warnings(
                UserWarning
        ):  ### TODO: Restore tests once warnings are removed
            for X in distribs_pymc3:
                samps = next(sample(X, size=size, library='pymc3'))
                for sam in samps:
                    assert sam in X.pspace.domain.set
            raises(NotImplementedError,
                   lambda: next(sample(Die("D"), library='pymc3')))
Пример #8
0
def test_issue_17006():
    if not np:
        skip("NumPy not installed")

    M = MatrixSymbol("M", 2, 2)

    f = lambdify(M, M + Identity(2))
    ma = np.array([[1, 2], [3, 4]])
    mr = np.array([[2, 2], [3, 5]])

    assert (f(ma) == mr).all()

    from sympy import symbols
    n = symbols('n', integer=True)
    N = MatrixSymbol("M", n, n)
    raises(NotImplementedError, lambda: lambdify(N, N + Identity(n)))
Пример #9
0
def test_issue_15827():
    if not numpy:
        skip("numpy not installed")
    A = MatrixSymbol("A", 3, 3)
    B = MatrixSymbol("B", 2, 3)
    C = MatrixSymbol("C", 3, 4)
    D = MatrixSymbol("D", 4, 5)
    k = symbols("k")
    f = lambdify(A, (2 * k) * A)
    g = lambdify(A, (2 + k) * A)
    h = lambdify(A, 2 * A)
    i = lambdify((B, C, D), 2 * B * C * D)
    assert numpy.array_equal(
        f(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])),
        numpy.array(
            [[2 * k, 4 * k, 6 * k], [2 * k, 4 * k, 6 * k],
             [2 * k, 4 * k, 6 * k]],
            dtype=object,
        ),
    )

    assert numpy.array_equal(
        g(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])),
        numpy.array(
            [
                [k + 2, 2 * k + 4, 3 * k + 6],
                [k + 2, 2 * k + 4, 3 * k + 6],
                [k + 2, 2 * k + 4, 3 * k + 6],
            ],
            dtype=object,
        ),
    )

    assert numpy.array_equal(
        h(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])),
        numpy.array([[2, 4, 6], [2, 4, 6], [2, 4, 6]]),
    )

    assert numpy.array_equal(
        i(
            numpy.array([[1, 2, 3], [1, 2, 3]]),
            numpy.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]),
            numpy.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5],
                         [1, 2, 3, 4, 5]]),
        ),
        numpy.array([[120, 240, 360, 480, 600], [120, 240, 360, 480, 600]]),
    )
Пример #10
0
def test_sample_numpy():
    distribs_numpy = [Geometric('G', 0.5), Poisson('P', 1), Zeta('Z', 2)]
    size = 3
    numpy = import_module('numpy')
    if not numpy:
        skip('Numpy is not installed. Abort tests for _sample_numpy.')
    else:
        with ignore_warnings(UserWarning):
            for X in distribs_numpy:
                samps = next(sample(X, size=size, library='numpy'))
                for sam in samps:
                    assert sam in X.pspace.domain.set
            raises(NotImplementedError,
                   lambda: next(sample(Skellam('S', 1, 1), library='numpy')))
    raises(
        NotImplementedError, lambda: Skellam('S', 1, 1).pspace.distribution.
        sample(library='tensorflow'))
Пример #11
0
def test_scipy_fns():
    if not scipy:
        skip("scipy not installed")

    single_arg_sympy_fns = [erf, erfc, factorial, gamma, loggamma, digamma]
    single_arg_scipy_fns = [scipy.special.erf, scipy.special.erfc,
        scipy.special.factorial, scipy.special.gamma, scipy.special.gammaln,
        scipy.special.psi]
    numpy.random.seed(0)
    for (sympy_fn, scipy_fn) in zip(single_arg_sympy_fns, single_arg_scipy_fns):
        f = lambdify(x, sympy_fn(x), modules="scipy")
        for i in range(20):
            tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
            # SciPy thinks that factorial(z) is 0 when re(z) < 0 and
            # does not support complex numbers.
            # SymPy does not think so.
            if sympy_fn == factorial:
                tv = numpy.abs(tv)
            # SciPy supports gammaln for real arguments only,
            # and there is also a branch cut along the negative real axis
            if sympy_fn == loggamma:
                tv = numpy.abs(tv)
            # SymPy's digamma evaluates as polygamma(0, z)
            # which SciPy supports for real arguments only
            if sympy_fn == digamma:
                tv = numpy.real(tv)
            sympy_result = sympy_fn(tv).evalf()
            assert abs(f(tv) - sympy_result) < 1e-13*(1 + abs(sympy_result))
            assert abs(f(tv) - scipy_fn(tv)) < 1e-13*(1 + abs(sympy_result))

    double_arg_sympy_fns = [RisingFactorial, besselj, bessely, besseli,
        besselk]
    double_arg_scipy_fns = [scipy.special.poch, scipy.special.jv,
        scipy.special.yv, scipy.special.iv, scipy.special.kv]
    for (sympy_fn, scipy_fn) in zip(double_arg_sympy_fns, double_arg_scipy_fns):
        f = lambdify((x, y), sympy_fn(x, y), modules="scipy")
        for i in range(20):
            # SciPy supports only real orders of Bessel functions
            tv1 = numpy.random.uniform(-10, 10)
            tv2 = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
            # SciPy supports poch for real arguments only
            if sympy_fn == RisingFactorial:
                tv2 = numpy.real(tv2)
            sympy_result = sympy_fn(tv1, tv2).evalf()
            assert abs(f(tv1, tv2) - sympy_result) < 1e-13*(1 + abs(sympy_result))
            assert abs(f(tv1, tv2) - scipy_fn(tv1, tv2)) < 1e-13*(1 + abs(sympy_result))
Пример #12
0
def test_issue_18770():
    numpy = import_module('numpy')
    if not numpy:
        skip("numpy not installed.")

    from sympy.functions.elementary.miscellaneous import (Max, Min)
    from sympy.utilities.lambdify import lambdify

    expr1 = Min(0.1 * x + 3, x + 1, 0.5 * x + 1)
    func = lambdify(x, expr1, "numpy")
    assert (func(numpy.linspace(0, 3, 3)) == [1.0, 1.75, 2.5]).all()
    assert func(4) == 3

    expr1 = Max(x**2, x**3)
    func = lambdify(x, expr1, "numpy")
    assert (func(numpy.linspace(-1, 2, 4)) == [1, 0, 1, 8]).all()
    assert func(4) == 64
Пример #13
0
def test_step_response():
    if not matplotlib:
        skip("Matplotlib not the default backend")

    def step_res_tester(sys, expected_value):
        x, y = _to_tuple(*step_response_numerical_data(sys,
            adaptive=False, nb_of_points=10))
        x_check = check_point_accuracy(x, expected_value[0])
        y_check = check_point_accuracy(y, expected_value[1])
        return x_check and y_check

    exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
        5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
        (-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717,
        0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071,
        0.4486997874319281, 0.4839358435839171))
    exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
        5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
        (0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073,
        0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221,
        -0.003636420058445484))
    exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
        5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
        (0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376,
        86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917))
    exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
        5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
        (0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532,
        493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667))
    exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
        5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
        (-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518,
        0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325,
        0.49997448824584123, 0.5000039745919259))
    exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
        5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
        (-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517,
        9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757,
        2447.387582370878))

    assert step_res_tester(tf1, exp1)
    assert step_res_tester(tf2, exp2)
    assert step_res_tester(tf3, exp3)
    assert step_res_tester(tf4, exp4)
    assert step_res_tester(tf5, exp5)
    assert step_res_tester(ser2, exp6)
Пример #14
0
def test_sample_pymc3():
    distribs_pymc3 = [
        Geometric('G', 0.5),
        Poisson('P', 1),
        NegativeBinomial('N', 5, 0.4)
    ]
    size = 3
    pymc3 = import_module('pymc3')
    if not pymc3:
        skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
    else:
        for X in distribs_pymc3:
            samps = sample(X, size=size, library='pymc3')
            for sam in samps:
                assert sam in X.pspace.domain.set
        raises(NotImplementedError,
               lambda: sample(Skellam('S', 1, 1), library='pymc3'))
def test_sample_pymc3():
    distribs_pymc3 = [
        MatrixNormal('M', [[5, 6], [3, 4]], [[1, 0], [0, 1]], [[2, 1], [1, 2]]),
        Wishart('W', 7, [[2, 1], [1, 2]])
    ]
    size = 3
    pymc3 = import_module('pymc3')
    if not pymc3:
        skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
    else:
        with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
            for X in distribs_pymc3:
                samps = next(sample(X, size=size, library='pymc3'))
                for sam in samps:
                    assert Matrix(sam) in X.pspace.distribution.set
            M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]])
            raises(NotImplementedError, lambda: next(sample(M, size=3)))
Пример #16
0
def test_sum():
    if not np:
        skip("NumPy not installed")

    s = Sum(x**i, (i, a, b))
    f = lambdify((a, b, x), s, 'numpy')

    a_, b_ = 0, 10
    x_ = np.linspace(-1, +1, 10)
    assert np.allclose(f(a_, b_, x_), sum(x_**i_ for i_ in range(a_, b_ + 1)))

    s = Sum(i * x, (i, a, b))
    f = lambdify((a, b, x), s, 'numpy')

    a_, b_ = 0, 10
    x_ = np.linspace(-1, +1, 10)
    assert np.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
Пример #17
0
def test_lognormal_sampling():
    # Right now, only density function and sampling works
    scipy = import_module('scipy')
    if not scipy:
        skip('Scipy is not installed. Abort tests')
    with ignore_warnings(
            UserWarning):  ### TODO: Restore tests once warnings are removed
        for i in range(3):
            X = LogNormal('x', i, 1)
            assert next(sample(X)) in X.pspace.domain.set

    size = 5
    with ignore_warnings(
            UserWarning):  ### TODO: Restore tests once warnings are removed
        samps = next(sample(X, size=size))
        for samp in samps:
            assert samp in X.pspace.domain.set
Пример #18
0
def test_sample_scipy():
    distribs_scipy = [
        MatrixNormal('M', [[5, 6]], [4], [[2, 1], [1, 2]]),
        Wishart('W', 5, [[1, 0], [0, 1]])
    ]

    size = 5
    scipy = import_module('scipy')
    if not scipy:
        skip('Scipy not installed. Abort tests for _sample_scipy.')
    else:
        for X in distribs_scipy:
            samps = sample(X, size=size)
            for sam in samps:
                assert Matrix(sam) in X.pspace.distribution.set
        M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]])
        raises(NotImplementedError, lambda: sample(M, size=3))
Пример #19
0
def test_sample_pymc3():
    distribs_pymc3 = [
        MatrixNormal('M', [[5, 6], [3, 4]], [[1, 0], [0, 1]],
                     [[2, 1], [1, 2]]),
        Wishart('W', 7, [[2, 1], [1, 2]])
    ]
    size = 3
    pymc3 = import_module('pymc3')
    if not pymc3:
        skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
    else:
        for X in distribs_pymc3:
            samps = sample(X, size=size, library='pymc3')
            for sam in samps:
                assert Matrix(sam) in X.pspace.distribution.set
        M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]])
        raises(NotImplementedError, lambda: sample(M, size=3))
Пример #20
0
def test_sample_numpy():
    distribs_numpy = [
        MultivariateNormal("M", [3, 4], [[2, 1], [1, 2]]),
        MultivariateBeta("B", [0.4, 5, 15, 50, 203]),
        Multinomial("N", 50, [0.3, 0.2, 0.1, 0.25, 0.15])
    ]
    size = 3
    numpy = import_module('numpy')
    if not numpy:
        skip('Numpy is not installed. Abort tests for _sample_numpy.')
    else:
        for X in distribs_numpy:
            samps = sample(X, size=size, library='numpy')
            for sam in samps:
                assert tuple(sam) in X.pspace.distribution.set
        N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1)
        raises(NotImplementedError, lambda: sample(N_c, library='numpy'))
Пример #21
0
def test_sample_pymc3():
    distribs_pymc3 = [
        MultivariateNormal("M", [5, 2], [[1, 0], [0, 1]]),
        MultivariateBeta("B", [0.4, 5, 15]),
        Multinomial("N", 4, [0.3, 0.2, 0.1, 0.4])
    ]
    size = 3
    pymc3 = import_module('pymc3')
    if not pymc3:
        skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
    else:
        for X in distribs_pymc3:
            samps = sample(X, size=size, library='pymc3')
            for sam in samps:
                assert tuple(sam.flatten()) in X.pspace.distribution.set
        N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1)
        raises(NotImplementedError, lambda: sample(N_c, library='pymc3'))
Пример #22
0
def test_issue_9871():
    if not numexpr:
        skip("numexpr not installed.")
    if not numpy:
        skip("numpy not installed.")

    r = sqrt(x**2 + y**2)
    expr = diff(1 / r, x)

    xn = yn = numpy.linspace(1, 10, 16)
    # expr(xn, xn) = -xn/(sqrt(2)*xn)^3
    fv_exact = -numpy.sqrt(2.)**-3 * xn**-2

    fv_numpy = lambdify((x, y), expr, modules='numpy')(xn, yn)
    fv_numexpr = lambdify((x, y), expr, modules='numexpr')(xn, yn)
    numpy.testing.assert_allclose(fv_numpy, fv_exact, rtol=1e-10)
    numpy.testing.assert_allclose(fv_numexpr, fv_exact, rtol=1e-10)
Пример #23
0
def test_pmint_bessel_products():
    # Note: Derivatives of Bessel functions have many forms.
    # Recurrence relations are needed for comparisons.
    if ON_TRAVIS:
        skip("Too slow for travis.")

    f = x * besselj(nu, x) * bessely(nu, 2 * x)
    g = -2 * x * besselj(nu, x) * bessely(nu - 1, 2 * x) / 3 + x * besselj(
        nu - 1, x) * bessely(nu, 2 * x) / 3

    assert heurisch(f, x) == g

    f = x * besselj(nu, x) * besselk(nu, 2 * x)
    g = -2 * x * besselj(nu, x) * besselk(nu - 1, 2 * x) / 5 - x * besselj(
        nu - 1, x) * besselk(nu, 2 * x) / 5

    assert heurisch(f, x) == g
Пример #24
0
def test_sympify_numpy():
    if not numpy:
        skip('numpy not installed. Abort numpy tests.')
    np = numpy

    def equal(x, y):
        return x == y and type(x) == type(y)

    assert sympify(np.bool_(1)) is S(True)
    try:
        assert equal(sympify(np.int_(1234567891234567891)),
                     S(1234567891234567891))
        assert equal(sympify(np.intp(1234567891234567891)),
                     S(1234567891234567891))
    except OverflowError:
        # May fail on 32-bit systems: Python int too large to convert to C long
        pass
    assert equal(sympify(np.intc(1234567891)), S(1234567891))
    assert equal(sympify(np.int8(-123)), S(-123))
    assert equal(sympify(np.int16(-12345)), S(-12345))
    assert equal(sympify(np.int32(-1234567891)), S(-1234567891))
    assert equal(sympify(np.int64(-1234567891234567891)),
                 S(-1234567891234567891))
    assert equal(sympify(np.uint8(123)), S(123))
    assert equal(sympify(np.uint16(12345)), S(12345))
    assert equal(sympify(np.uint32(1234567891)), S(1234567891))
    assert equal(sympify(np.uint64(1234567891234567891)),
                 S(1234567891234567891))
    assert equal(sympify(np.float32(1.123456)), Float(1.123456, precision=24))
    assert equal(sympify(np.float64(1.1234567891234)),
                 Float(1.1234567891234, precision=53))
    assert equal(sympify(np.longdouble(1.123456789)),
                 Float(1.123456789, precision=80))
    assert equal(sympify(np.complex64(1 + 2j)), S(1.0 + 2.0 * I))
    assert equal(sympify(np.complex128(1 + 2j)), S(1.0 + 2.0 * I))
    assert equal(sympify(np.longcomplex(1 + 2j)), S(1.0 + 2.0 * I))

    #float96 does not exist on all platforms
    if hasattr(np, 'float96'):
        assert equal(sympify(np.float96(1.123456789)),
                     Float(1.123456789, precision=80))
    #float128 does not exist on all platforms
    if hasattr(np, 'float128'):
        assert equal(sympify(np.float128(1.123456789123)),
                     Float(1.123456789123, precision=80))
Пример #25
0
def test_region_and():
    matplotlib = import_module("matplotlib",
                               min_module_version="1.1.0",
                               catch=(RuntimeError, ))
    if not matplotlib:
        skip("Matplotlib not the default backend")

    from matplotlib.testing.compare import compare_images

    test_directory = os.path.dirname(os.path.abspath(__file__))

    try:
        temp_dir = mkdtemp()
        TmpFileManager.tmp_folder(temp_dir)

        x, y = symbols("x y")

        r1 = (x - 1)**2 + y**2 < 2
        r2 = (x + 1)**2 + y**2 < 2

        test_filename = tmp_file(dir=temp_dir, name="test_region_and")
        cmp_filename = os.path.join(test_directory, "test_region_and.png")
        p = plot_implicit(r1 & r2, x, y)
        p.save(test_filename)
        compare_images(cmp_filename, test_filename, 0.005)

        test_filename = tmp_file(dir=temp_dir, name="test_region_or")
        cmp_filename = os.path.join(test_directory, "test_region_or.png")
        p = plot_implicit(r1 | r2, x, y)
        p.save(test_filename)
        compare_images(cmp_filename, test_filename, 0.005)

        test_filename = tmp_file(dir=temp_dir, name="test_region_not")
        cmp_filename = os.path.join(test_directory, "test_region_not.png")
        p = plot_implicit(~r1, x, y)
        p.save(test_filename)
        compare_images(cmp_filename, test_filename, 0.005)

        test_filename = tmp_file(dir=temp_dir, name="test_region_xor")
        cmp_filename = os.path.join(test_directory, "test_region_xor.png")
        p = plot_implicit(r1 ^ r2, x, y)
        p.save(test_filename)
        compare_images(cmp_filename, test_filename, 0.005)
    finally:
        TmpFileManager.cleanup()
Пример #26
0
def test_Subroutine():
    # Code to generate the subroutine in the example from
    # http://www.fortran90.org/src/best-practices.html#arrays
    r = Symbol("r", real=True)
    i = Symbol("i", integer=True)
    v_r = Variable.deduced(r, attrs=(dimension(assumed_extent), intent_out))
    v_i = Variable.deduced(i)
    v_n = Variable("n", integer)
    do_loop = Do([Assignment(Element(r, [i]),
                             literal_dp(1) / i**2)], i, 1, v_n)
    sub = Subroutine(
        "f",
        [v_r],
        [
            Declaration(v_n),
            Declaration(v_i),
            Assignment(v_n, size(r)), do_loop
        ],
    )
    x = Symbol("x", real=True)
    v_x3 = Variable.deduced(x, attrs=[dimension(3)])
    mod = Module("mymod", definitions=[sub])
    prog = Program(
        "foo",
        [
            use(mod, only=[sub]),
            Declaration(v_x3),
            SubroutineCall(sub, [v_x3]),
            Print([sum_(v_x3), v_x3]),
        ],
    )

    if not has_fortran():
        skip("No fortran compiler found.")

    (stdout, stderr), info = compile_run_strings(
        [("a.f90", fcode(mod, standard=90)),
         ("b.f90", fcode(prog, standard=90))],
        clean=True,
    )
    ref = [1.0 / i**2 for i in range(1, 4)]
    assert str(sum(ref))[:-3] in stdout
    for _ in ref:
        assert str(_)[:-3] in stdout
    assert stderr == ""
Пример #27
0
def test_plot_size():
    if not matplotlib:
        skip("Matplotlib not the default backend")

    x = Symbol('x')

    p1 = plot(sin(x), backend="matplotlib", size=(8, 4))
    s1 = p1._backend.fig.get_size_inches()
    assert (s1[0] == 8) and (s1[1] == 4)
    p2 = plot(sin(x), backend="matplotlib", size=(5, 10))
    s2 = p2._backend.fig.get_size_inches()
    assert (s2[0] == 5) and (s2[1] == 10)
    p3 = PlotGrid(2, 1, p1, p2, size=(6, 2))
    s3 = p3._backend.fig.get_size_inches()
    assert (s3[0] == 6) and (s3[1] == 2)

    with raises(ValueError):
        plot(sin(x), backend="matplotlib", size=(-1, 3))
Пример #28
0
def test_append_issue_7140():
    if not matplotlib:
        skip("Matplotlib not the default backend")

    x = Symbol('x')
    p1 = plot(x)
    p2 = plot(x**2)
    plot(x + 2)

    # append a series
    p2.append(p1[0])
    assert len(p2._series) == 2

    with raises(TypeError):
        p1.append(p2)

    with raises(TypeError):
        p1.append(p2._series)
Пример #29
0
def test_cnot():
    """Test a simple cnot circuit. Right now this only makes sure the code doesn't
    raise an exception, and some simple properties
    """
    if not mpl:
        skip("matplotlib not installed")
    else:
        from sympy.physics.quantum.circuitplot import CircuitPlot

    c = CircuitPlot(CNOT(1, 0), 2, labels=labeller(2))
    assert c.ngates == 2
    assert c.nqubits == 2
    assert c.labels == ['q_1', 'q_0']

    c = CircuitPlot(CNOT(1, 0), 2)
    assert c.ngates == 2
    assert c.nqubits == 2
    assert c.labels == []
Пример #30
0
def test_mod():
    if not np:
        skip("NumPy not installed")

    e = Mod(a, b)
    f = lambdify((a, b), e)

    a_ = np.array([0, 1, 2, 3])
    b_ = 2
    assert np.array_equal(f(a_, b_), [0, 1, 0, 1])

    a_ = np.array([0, 1, 2, 3])
    b_ = np.array([2, 2, 2, 2])
    assert np.array_equal(f(a_, b_), [0, 1, 0, 1])

    a_ = np.array([2, 3, 4, 5])
    b_ = np.array([2, 3, 4, 5])
    assert np.array_equal(f(a_, b_), [0, 0, 0, 0])