• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python external.import_module函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sympy.external.import_module函数的典型用法代码示例。如果您正苦于以下问题:Python import_module函数的具体用法?Python import_module怎么用?Python import_module使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了import_module函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_entropy

def test_entropy():
    up = JzKet(S(1)/2, S(1)/2)
    down = JzKet(S(1)/2, -S(1)/2)
    d = Density((up, 0.5), (down, 0.5))

    # test for density object
    ent = entropy(d)
    assert entropy(d) == 0.5*log(2)
    assert d.entropy() == 0.5*log(2)

    np = import_module('numpy', min_module_version='1.4.0')
    if np:
        #do this test only if 'numpy' is available on test machine
        np_mat = represent(d, format='numpy')
        ent = entropy(np_mat)
        assert isinstance(np_mat, np.matrixlib.defmatrix.matrix)
        assert ent.real == 0.69314718055994529
        assert ent.imag == 0

    scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']})
    if scipy and np:
        #do this test only if numpy and scipy are available
        mat = represent(d, format="scipy.sparse")
        assert isinstance(mat, scipy_sparse_matrix)
        assert ent.real == 0.69314718055994529
        assert ent.imag == 0
开发者ID:AALEKH,项目名称:sympy,代码行数:26,代码来源:test_density.py


示例2: mplot3d

def mplot3d(f, var1, var2, show=True):
    """
    Plot a 3d function using matplotlib/Tk.
    """

    import warnings
    warnings.filterwarnings("ignore", "Could not match \S")

    p = import_module('pylab')
    # Try newer version first
    p3 = import_module('mpl_toolkits.mplot3d',
        __import__kwargs={'fromlist':['something']}) or import_module('matplotlib.axes3d')
    if not p or not p3:
        sys.exit("Matplotlib is required to use mplot3d.")

    x, y, z = sample(f, var1, var2)

    fig = p.figure()
    ax = p3.Axes3D(fig)

    #ax.plot_surface(x,y,z) #seems to be a bug in matplotlib
    ax.plot_wireframe(x,y,z)

    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

    if show:
        p.show()
开发者ID:101man,项目名称:sympy,代码行数:29,代码来源:mplot3d.py


示例3: test_is_scalar_sparse_matrix

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
开发者ID:AALEKH,项目名称:sympy,代码行数:48,代码来源:test_identitysearch.py


示例4: test_matplotlib

def test_matplotlib():
    matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
    if matplotlib:
        plot_implicit_tests('test')
        test_line_color()
    else:
        skip("Matplotlib not the default backend")
开发者ID:A-turing-machine,项目名称:sympy,代码行数:7,代码来源:test_plot_implicit.py


示例5: parse_latex

def parse_latex(s):
    r"""Converts the string ``s`` to a SymPy ``Expr``

    Parameters
    ==========

    s : str
        The LaTeX string to parse. In Python source containing LaTeX,
        *raw strings* (denoted with ``r"``, like this one) are preferred,
        as LaTeX makes liberal use of the ``\`` character, which would
        trigger escaping in normal Python strings.

    Examples
    ========

    >>> from sympy.parsing.latex import parse_latex  # doctest: +SKIP
    >>> expr = parse_latex(r"\frac {1 + \sqrt {\a}} {\b}")  # doctest: +SKIP
    >>> expr  # doctest: +SKIP
    (sqrt(a) + 1)/b
    >>> expr.evalf(4, subs=dict(a=5, b=2))  # doctest: +SKIP
    1.618
    """

    _latex = import_module(
        'sympy.parsing.latex._parse_latex_antlr',
        __import__kwargs={'fromlist': ['X']})

    if _latex is not None:
        return _latex.parse_latex(s)
开发者ID:asmeurer,项目名称:sympy,代码行数:29,代码来源:__init__.py


示例6: mplot2d

def mplot2d(f, var, show=True):
    """
    Plot a 2d function using matplotlib/Tk.
    """

    import warnings
    warnings.filterwarnings("ignore", "Could not match \S")
    
    p = import_module('pylab')
    if not p:
        sys.exit("Matplotlib is required to use mplot2d.")

    if not is_sequence(f):
        f = [f,]
    
    for f_i in f:
        x, y = sample2d(f_i, var)
        p.plot(x, y,'black')

    p.draw()
    
    p.ylabel("Transverse beam cordinate")
    p.xlabel("Propagation coordinate")
    p.grid(True)
    
    if show:
        p.show()
开发者ID:Enchanter12,项目名称:sympy,代码行数:27,代码来源:gaussopt.py


示例7: parse_latex

def parse_latex(sympy):
    antlr4 = import_module('antlr4', warn_not_installed=True)

    if None in [antlr4, MathErrorListener]:
        raise ImportError("LaTeX parsing requires the antlr4 python package,"
                          " provided by pip (antlr4-python2-runtime or"
                          " antlr4-python3-runtime) or"
                          " conda (antlr-python-runtime)")

    matherror = MathErrorListener(sympy)

    stream = antlr4.InputStream(sympy)
    lex = LaTeXLexer(stream)
    lex.removeErrorListeners()
    lex.addErrorListener(matherror)

    tokens = antlr4.CommonTokenStream(lex)
    parser = LaTeXParser(tokens)

    # remove default console error listener
    parser.removeErrorListeners()
    parser.addErrorListener(matherror)

    relation = parser.math().relation()
    expr = convert_relation(relation)

    return expr
开发者ID:KonstantinTogoi,项目名称:sympy,代码行数:27,代码来源:_parse_latex_antlr.py


示例8: test_evalonarray_numpy

def test_evalonarray_numpy():
    numpy = import_module('numpy')
    a = numpy.arange(10, dtype=float)
    evalonarray('lambda x: x + 1', a)
    for i, j in enumerate(a):
        if float(i + 1) != j:
            raise ValueError("Values should be equal")
开发者ID:vprusso,项目名称:sympy,代码行数:7,代码来源:compilef.py


示例9: _get_meshes_grid

    def _get_meshes_grid(self):
        """Generates the mesh for generating a contour.

        In the case of equality, ``contour`` function of matplotlib can
        be used. In other cases, matplotlib's ``contourf`` is used.
        """
        equal = False
        if isinstance(self.expr, Equality):
            expr = self.expr.lhs - self.expr.rhs
            equal = True

        elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)):
            expr = self.expr.lhs - self.expr.rhs

        elif isinstance(self.expr, (LessThan, StrictLessThan)):
            expr = self.expr.rhs - self.expr.lhs
        else:
            raise NotImplementedError("The expression is not supported for " "plotting in uniform meshed plot.")
        np = import_module("numpy")
        xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points)
        yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points)
        x_grid, y_grid = np.meshgrid(xarray, yarray)

        func = vectorized_lambdify((self.var_x, self.var_y), expr)
        z_grid = func(x_grid, y_grid)
        z_grid[np.ma.where(z_grid < 0)] = -1
        z_grid[np.ma.where(z_grid > 0)] = 1
        if equal:
            return xarray, yarray, z_grid, "contour"
        else:
            return xarray, yarray, z_grid, "contourf"
开发者ID:alphaitis,项目名称:sympy,代码行数:31,代码来源:plot_implicit.py


示例10: test_valued_non_diagonal_metric

def test_valued_non_diagonal_metric():
    numpy = import_module("numpy")
    if numpy is None:
        skip("numpy not installed.")

    mmatrix = Matrix(ndm_matrix)
    assert NA(n0)*NA(-n0) == (NA(n0).get_matrix().T * mmatrix * NA(n0).get_matrix())[0, 0]
开发者ID:MarcdeFalco,项目名称:sympy,代码行数:7,代码来源:test_tensor.py


示例11: test_valued_tensor_applyfunc

def test_valued_tensor_applyfunc():
    numpy = import_module("numpy")
    if numpy is None:
        skip("numpy not installed.")

    aA = A(i0).applyfunc(lambda x: x**2)
    aB = B(i0).applyfunc(lambda x: x**3)
    aB2 = B(-i0).applyfunc(lambda x: x**3)

    for i in range(4):
        assert aA[i] == A(i0)[i]**2
        assert aB[i] == B(i1)[i]**3
    assert aB*aB2 == -794

    tA = A.applyfunc(lambda x: x + 33)
    tB = B.applyfunc(lambda x: x + 33)
    tAB = AB.applyfunc(lambda x: x + 33)

    assert (tA(i0)*tA(-i0)).expand() == ((E + 33)**2 - (px + 33)**2 - (py + 33)**2 - (pz + 33)**2).expand()
    assert tB(i0).get_matrix() == Matrix([33, 34, 35, 36])
    assert tAB(i0, i1).get_matrix() == Matrix([
        [34, 33, 33, 33],
        [33, 32, 33, 33],
        [33, 33, 32, 33],
        [33, 33, 33, 32],
    ])
开发者ID:MarcdeFalco,项目名称:sympy,代码行数:26,代码来源:test_tensor.py


示例12: test_valued_tensor_self_contraction

def test_valued_tensor_self_contraction():
    numpy = import_module("numpy")
    if numpy is None:
        skip("numpy not installed.")

    assert AB(i0, -i0) == 4
    assert BA(i0, -i0) == 2
开发者ID:MarcdeFalco,项目名称:sympy,代码行数:7,代码来源:test_tensor.py


示例13: cos

def cos(x):
    """Evaluates the cos of an interval"""
    np = import_module('numpy')
    if isinstance(x, (int, float)):
        return interval(np.sin(x))
    elif isinstance(x, interval):
        if not (np.isfinite(x.start) and np.isfinite(x.end)):
            return interval(-1, 1, is_valid=x.is_valid)
        na, __ = divmod(x.start, np.pi / 2.0)
        nb, __ = divmod(x.end, np.pi / 2.0)
        start = min(np.cos(x.start), np.cos(x.end))
        end = max(np.cos(x.start), np.cos(x.end))
        if nb - na > 4:
            #differ more than 2*pi
            return interval(-1, 1, is_valid=x.is_valid)
        elif na == nb:
            #in the same quadarant
            return interval(start, end, is_valid=x.is_valid)
        else:
            if (na) // 4 != (nb) // 4:
                #cos has max
                end = 1
            if (na - 2) // 4 != (nb - 2) // 4:
                #cos has min
                start = -1
            return interval(start, end, is_valid=x.is_valid)
    else:
        raise NotImplementedError
开发者ID:abhishekkumawat23,项目名称:sympy,代码行数:28,代码来源:lib_interval.py


示例14: sin

def sin(x):
    """evaluates the sine of an interval"""
    np = import_module('numpy')
    if isinstance(x, (int, float)):
        return interval(np.sin(x))
    elif isinstance(x, interval):
        if not x.is_valid:
            return interval(-1, 1, is_valid=x.is_valid)
        na, __ = divmod(x.start, np.pi / 2.0)
        nb, __ = divmod(x.end, np.pi / 2.0)
        start = min(np.sin(x.start), np.sin(x.end))
        end = max(np.sin(x.start), np.sin(x.end))
        if nb - na > 4:
            return interval(-1, 1, is_valid=x.is_valid)
        elif na == nb:
            return interval(start, end, is_valid=x.is_valid)
        else:
            if (na - 1) // 4 != (nb - 1) // 4:
                #sin has max
                end = 1
            if (na - 3) // 4 != (nb - 3) // 4:
                #sin has min
                start = -1
            return interval(start, end)
    else:
        raise NotImplementedError
开发者ID:abhishekkumawat23,项目名称:sympy,代码行数:26,代码来源:lib_interval.py


示例15: fbenchmark

 def fbenchmark(f, var=[Symbol('x')]):
     """
     Do some benchmarks with f using clambdify, lambdify and psyco.
     """
     global cf, pf, psyf
     start = time()
     cf = clambdify(var, f)
     print('compile time (including sympy overhead): %f s' % (
         time() - start))
     pf = lambdify(var, f, 'math')
     psyf = None
     psyco = import_module('psyco')
     if psyco:
         psyf = lambdify(var, f, 'math')
         psyco.bind(psyf)
     code = '''for x in (i/1000. for i in range(1000)):
     f(%s)''' % ('x,'*len(var)).rstrip(',')
     t1 = Timer(code, 'from __main__ import cf as f')
     t2 = Timer(code, 'from __main__ import pf as f')
     if psyf:
         t3 = Timer(code, 'from __main__ import psyf as f')
     else:
         t3 = None
     print('for x = (0, 1, 2, ..., 999)/1000')
     print('20 times in 3 runs')
     print('compiled:      %.4f %.4f %.4f' % tuple(t1.repeat(3, 20)))
     print('Python lambda: %.4f %.4f %.4f' % tuple(t2.repeat(3, 20)))
     if t3:
         print('Psyco lambda:  %.4f %.4f %.4f' % tuple(t3.repeat(3, 20)))
开发者ID:vprusso,项目名称:sympy,代码行数:29,代码来源:compilef.py


示例16: init_ipython_session

def init_ipython_session(argv=[], auto_symbols=False, auto_int_to_Integer=False):
    """Construct new IPython session. """
    import IPython

    if IPython.__version__ >= '0.11':
        # use an app to parse the command line, and init config
        # IPython 1.0 deprecates the frontend module, so we import directly
        # from the terminal module to prevent a deprecation message from being
        # shown.
        if IPython.__version__ >= '1.0':
            from IPython.terminal import ipapp
        else:
            from IPython.frontend.terminal import ipapp
        app = ipapp.TerminalIPythonApp()

        # don't draw IPython banner during initialization:
        app.display_banner = False
        app.initialize(argv)

        if auto_symbols:
            readline = import_module("readline")
            if readline:
                enable_automatic_symbols(app)
        if auto_int_to_Integer:
            enable_automatic_int_sympification(app)

        return app.shell
    else:
        from IPython.Shell import make_IPython
        return make_IPython(argv)
开发者ID:B-Rich,项目名称:sympy,代码行数:30,代码来源:session.py


示例17: test_issue_15265

def test_issue_15265():
    from sympy.core.sympify import sympify
    from sympy.core.singleton import S

    matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
    if not matplotlib:
        skip("Matplotlib not the default backend")

    x = Symbol('x')
    eqn = sin(x)

    p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1))
    p._backend.close()

    p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi))
    p._backend.close()

    p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14')))
    p._backend.close()

    p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1))
    p._backend.close()

    raises(ValueError,
        lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-S.Infinity, 1), ylim=(-1, 1)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity)))
开发者ID:Lenqth,项目名称:sympy,代码行数:34,代码来源:test_plot.py


示例18: test_no_stdlib_collections3

def test_no_stdlib_collections3():
    '''make sure we get the right collections with no catch'''
    import collections
    matplotlib = import_module('matplotlib',
        __import__kwargs={'fromlist': ['cm', 'collections']},
        min_module_version='1.1.0')
    if matplotlib:
        assert collections != matplotlib.collections
开发者ID:A-turing-machine,项目名称:sympy,代码行数:8,代码来源:test_importtools.py


示例19: __call__

    def __call__(self, *args):
        np = import_module('numpy')
        np_old_err = np.seterr(invalid='raise')
        try:
            temp_args = (np.array(a, dtype=np.complex) for a in args)
            results = self.vector_func(*temp_args)
            results = np.ma.masked_where(
                                np.abs(results.imag) > 1e-7 * np.abs(results),
                                results.real, copy=False)
        except Exception as e:
            #DEBUG: print 'Error', type(e), e
            if ((isinstance(e, TypeError)
                 and 'unhashable type: \'numpy.ndarray\'' in str(e))
                or
                (isinstance(e, ValueError)
                 and ('Invalid limits given:' in str(e)
                      or 'negative dimensions are not allowed' in str(e)  # XXX
                      or 'sequence too large; must be smaller than 32' in str(e)))):  # XXX
                # Almost all functions were translated to numpy, but some were
                # left as sympy functions. They received an ndarray as an
                # argument and failed.
                #   sin(ndarray(...)) raises "unhashable type"
                #   Integral(x, (x, 0, ndarray(...))) raises "Invalid limits"
                #   other ugly exceptions that are not well understood (marked with XXX)
                # TODO: Cleanup the ugly special cases marked with xxx above.
                # Solution: use cmath and vectorize the final lambda.
                self.lambda_func = experimental_lambdify(
                    self.args, self.expr, use_python_cmath=True)
                self.vector_func = np.vectorize(
                    self.lambda_func, otypes=[np.complex])
                results = self.vector_func(*args)
                results = np.ma.masked_where(
                                np.abs(results.imag) > 1e-7 * np.abs(results),
                                results.real, copy=False)
            else:
                # Complete failure. One last try with no translations, only
                # wrapping in complex((...).evalf()) and returning the real
                # part.
                if self.failure:
                    raise e
                else:
                    self.failure = True
                    self.lambda_func = experimental_lambdify(
                        self.args, self.expr, use_evalf=True,
                        complex_wrap_evalf=True)
                    self.vector_func = np.vectorize(
                        self.lambda_func, otypes=[np.complex])
                    results = self.vector_func(*args)
                    results = np.ma.masked_where(
                            np.abs(results.imag) > 1e-7 * np.abs(results),
                            results.real, copy=False)
                    warnings.warn('The evaluation of the expression is'
                            ' problematic. We are trying a failback method'
                            ' that may still work. Please report this as a bug.')
        finally:
            np.seterr(**np_old_err)

        return results
开发者ID:KonstantinTogoi,项目名称:sympy,代码行数:58,代码来源:experimental_lambdify.py


示例20: test_valued_tensor_pow

def test_valued_tensor_pow():
    numpy = import_module("numpy")
    if numpy is None:
        skip("numpy not installed.")

    assert C**2 == -E**2 + px**2 + py**2 + pz**2
    assert C**1 == sqrt(-E**2 + px**2 + py**2 + pz**2)
    assert C(mu0)**2 == C**2
    assert C(mu0)**1 == C**1
开发者ID:MarcdeFalco,项目名称:sympy,代码行数:9,代码来源:test_tensor.py



注:本文中的sympy.external.import_module函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python functions.acosh函数代码示例发布时间:2022-05-27
下一篇:
Python sympify.sympify函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap