本文整理汇总了Python中sympy.external.import_module函数的典型用法代码示例。如果您正苦于以下问题:Python import_module函数的具体用法?Python import_module怎么用?Python import_module使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了import_module函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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()
示例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
示例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")
示例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)
示例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()
示例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
示例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")
示例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"
示例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]
示例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],
])
示例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
示例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
示例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
示例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)))