本文整理汇总了Python中sympy.latex方法的典型用法代码示例。如果您正苦于以下问题:Python sympy.latex方法的具体用法?Python sympy.latex怎么用?Python sympy.latex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sympy
的用法示例。
在下文中一共展示了sympy.latex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: print_ode
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def print_ode(self, latex_output=False):
'''
Prints the ode in symbolic form onto the screen/console in actual
symbols rather than the word of the symbol.
Parameters
----------
latex_output: bool, optional
Defaults to false which prints the equation in terms of symbols,
if set to yes then the formula in terms of latex equations will
be printed onto the screen.
'''
A = self.get_ode_eqn()
B = sympy.zeros(A.rows,2)
for i in range(A.shape[0]):
B[i,0] = sympy.symbols('d' + str(self._stateList[i]) + '/dt=')
B[i,1] = A[i]
if latex_output:
print(sympy.latex(B, mat_str="array", mat_delim=None,
inv_trig_style='full'))
else:
sympy.pretty_print(B)
示例2: symbolize
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def symbolize(flt: float) -> sympy.Symbol:
"""Attempt to convert a real number into a simpler symbolic
representation.
Returns:
A sympy Symbol. (Convert to string with str(sym) or to latex with
sympy.latex(sym)
Raises:
ValueError: If cannot simplify float
"""
try:
ratio = rationalize(flt)
res = sympy.simplify(ratio)
except ValueError:
ratio = rationalize(flt/np.pi)
res = sympy.simplify(ratio) * sympy.pi
return res
# fin
示例3: circuit_to_image
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def circuit_to_image(circ: Circuit,
qubits: Qubits = None) -> PIL.Image: # pragma: no cover
"""Create an image of a quantum circuit.
A convenience function that calls circuit_to_latex() and render_latex().
Args:
circ: A quantum Circuit
qubits: Optional qubit list to specify qubit order
Returns:
Returns: A PIL Image (Use img.show() to display)
Raises:
NotImplementedError: For unsupported gates.
OSError: If an external dependency is not installed.
"""
latex = circuit_to_latex(circ, qubits)
img = render_latex(latex)
return img
# ==== UTILITIES ====
示例4: test_Expr__latex
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def test_Expr__latex():
Poly = Expr.from_callback(_poly, parameter_keys=('x',), argument_names=('x0', Ellipsis))
p = Poly([1, 2, 3, 4])
import sympy
t = sympy.Symbol('t')
ref = sympy.latex((2 + 3*(t-1) + 4*(t-1)**2).simplify())
assert p.latex({'x': 't'}) == ref
TE = Poly([3, 7, 5])
cv_Al = _get_cv()['Al']
T, E, R, m = sympy.symbols('T E R m')
_TE = 7 + 5*(E-3)
ref = sympy.latex(((3*R*(_TE/(2*T))**2 * sympy.sinh(_TE/(2*T))**-2)/m).simplify())
cv_Al.unique_keys = ('TE_Al', 'm_Al')
res = cv_Al.latex({'TE_Al': TE, 'temperature': 'T', 'x': 'E', 'molar_gas_constant': 'R', 'm_Al': 'm'})
assert res == ref
X = sympy.symbols('X')
_TE2 = 7 + 5*(X-3)
ref2 = sympy.latex(((3*R*(_TE2/(2*T))**2 * sympy.sinh(_TE2/(2*T))**-2)/m).simplify())
res2 = cv_Al.latex({'TE_Al': TE, 'temperature': 'T', 'molar_gas_constant': 'R', 'm_Al': 'm'},
default=lambda k: k.upper())
assert res2 == ref2
示例5: print_latex
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def print_latex(obj):
"""Print formulas in latex format.
Parameters
----------
obj : pixyz.distributions.distributions.Distribution, pixyz.losses.losses.Loss or pixyz.models.model.Model.
"""
if isinstance(obj, pixyz.distributions.distributions.Distribution):
latex_text = obj.prob_joint_factorized_and_text
elif isinstance(obj, pixyz.losses.losses.Loss):
latex_text = obj.loss_text
elif isinstance(obj, pixyz.models.model.Model):
latex_text = obj.loss_cls.loss_text
return Math(latex_text)
示例6: convert_to_function
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def convert_to_function(string: str, scale_by_k=False):
"""Using the sympy module, parse string input
into a mathematical expression.
Returns the original string, the latexified string,
the mathematical expression in terms of sympy symbols,
and a lambdified function
"""
string = string.replace("^", "**")
symbolic_function = parse_expr(string)
if scale_by_k:
latexstring = latex(symbolic_function*abc.k)
else:
latexstring = latex(symbolic_function)
lambda_function = lambdify(abc.x, symbolic_function,
modules=module_list)
string = string.replace('*', '')
latexstring = "$" + latexstring + "$"
return string, latexstring, \
symbolic_function, lambda_function
示例7: print_png
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def print_png(o):
"""
A function to display sympy expression using inline style LaTeX in PNG.
"""
s = latex(o, mode='inline')
# mathtext does not understand certain latex flags, so we try to replace
# them with suitable subs.
s = s.replace('\\operatorname','')
s = s.replace('\\overline', '\\bar')
png = latex_to_png(s)
return png
示例8: print_display_png
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def print_display_png(o):
"""
A function to display sympy expression using display style LaTeX in PNG.
"""
s = latex(o, mode='plain')
s = s.strip('$')
# As matplotlib does not support display style, dvipng backend is
# used here.
png = latex_to_png(s, backend='dvipng', wrap=True)
return png
示例9: print_latex
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def print_latex(o):
"""A function to generate the latex representation of sympy
expressions."""
if can_print_latex(o):
s = latex(o, mode='plain')
s = s.replace('\\dag','\\dagger')
s = s.strip('$')
return '$$%s$$' % s
# Fallback to the string printer
return None
示例10: _plot_gate
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def _plot_gate(self, gate):
"""
Parameters
----------
gate : quantumsim.circuits.Gate
Returns
-------
"""
metadata = deepcopy(gate.plot_metadata)
# By default we will plot a box
style = metadata.pop('style', 'box')
if style == 'box':
# TODO: formatting with params (it is tricky)
# params = gate.params_set()
label = metadata.pop('label', r'$\mathcal{G}$') # .format(**params)
params = {key: latex(val) for key, val in gate.params.items()}
label = label.format(**params)
return self._plot_box_with_label(
gate.time_start, gate.time_end, *self._qubit_range(gate.qubits),
label, **self._get_box_kwargs(metadata))
elif style == 'line':
time = gate.time_start + 0.5 * gate.duration
markers = metadata.pop('markers')
self._plot_vline(time, *self._qubit_range(gate.qubits), metadata)
if markers is not None:
for qubit, marker in zip(gate.qubits, markers):
self._plot_single_qubit_marker(
qubit, gate.time_start, gate.duration, marker)
elif style == 'marker':
for qubit in gate.qubits:
self._plot_single_qubit_marker(
qubit, gate.time_start, gate.duration, metadata)
else:
raise RuntimeError("Unknown gate plotting style: {}".format(style))
示例11: _print_contents_latex
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def _print_contents_latex(self, printer, *args):
return r'{{%s}(%s)}' % (latex(self.operator), latex(self.variable))
示例12: _latex_format
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def _latex_format(obj: Any) -> str:
"""Format an object as a latex string."""
if isinstance(obj, float):
try:
return sympy.latex(symbolize(obj))
except ValueError:
return "{0:.4g}".format(obj)
return str(obj)
# fin
示例13: _get_properties
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def _get_properties(self):
properties = super(LaTeX, self)._get_properties()
obj = self.object
if obj is None:
obj = ''
elif hasattr(obj, '_repr_latex_'):
obj = obj._repr_latex_()
elif is_sympy_expr(obj):
import sympy
obj = r'$'+sympy.latex(obj)+'$'
return dict(properties, text=obj)
示例14: _sympy_formatter
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def _sympy_formatter(self):
def formatter(x):
if (isinstance(x, sympy.Basic)):
return '${}$'.format(sympy.latex(x))
else:
return x
new = self.copy()
for col in self.columns.drop('atom'):
if self[col].dtype == np.dtype('O'):
new._frame.loc[:, col] = self[col].apply(formatter)
return new
示例15: convert_latex_name
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import latex [as 别名]
def convert_latex_name(name):
return sympy.latex(sympy.Symbol(name))