本文整理汇总了Python中sympy.core.compatibility.u函数的典型用法代码示例。如果您正苦于以下问题:Python u函数的具体用法?Python u怎么用?Python u使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了u函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_commutator
def test_commutator():
A = Operator('A')
B = Operator('B')
c = Commutator(A, B)
c_tall = Commutator(A**2, B)
assert str(c) == '[A,B]'
assert pretty(c) == '[A,B]'
assert upretty(c) == u('[A,B]')
assert latex(c) == r'\left[A,B\right]'
sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))")
assert str(c_tall) == '[A**2,B]'
ascii_str = \
"""\
[ 2 ]\n\
[A ,B]\
"""
ucode_str = \
u("""\
⎡ 2 ⎤\n\
⎣A ,B⎦\
""")
assert pretty(c_tall) == ascii_str
assert upretty(c_tall) == ucode_str
assert latex(c_tall) == r'\left[\left(A\right)^{2},B\right]'
sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
示例2: test_dyadic_pretty_print
def test_dyadic_pretty_print():
expected = """\
2
a n_x|n_y + b n_y|n_y + c*sin(alpha) n_z|n_y\
"""
uexpected = u("""\
2
a n_x⊗n_y + b n_y⊗n_y + c⋅sin(α) n_z⊗n_y\
""")
assert ascii_vpretty(y) == expected
assert unicode_vpretty(y) == uexpected
expected = u('alpha n_x|n_x + sin(omega) n_y|n_z + alpha*beta n_z|n_x')
uexpected = u('α n_x⊗n_x + sin(ω) n_y⊗n_z + α⋅β n_z⊗n_x')
assert ascii_vpretty(x) == expected
assert unicode_vpretty(x) == uexpected
assert ascii_vpretty(Dyadic([])) == '0'
assert unicode_vpretty(Dyadic([])) == '0'
assert ascii_vpretty(xx) == '- n_x|n_y - n_x|n_z'
assert unicode_vpretty(xx) == u('- n_x⊗n_y - n_x⊗n_z')
assert ascii_vpretty(xx2) == 'n_x|n_y + n_x|n_z'
assert unicode_vpretty(xx2) == u('n_x⊗n_y + n_x⊗n_z')
示例3: test_vector_pretty_print
def test_vector_pretty_print():
# TODO : The unit vectors should print with subscripts but they just
# print as `n_x` instead of making `x` a subscript with unicode.
# TODO : The pretty print division does not print correctly here:
# w = alpha * N.x + sin(omega) * N.y + alpha / beta * N.z
expected = """\
2
a n_x + b n_y + c*sin(alpha) n_z\
"""
uexpected = u("""\
2
a n_x + b n_y + c⋅sin(α) n_z\
""")
assert ascii_vpretty(v) == expected
assert unicode_vpretty(v) == uexpected
expected = u('alpha n_x + sin(omega) n_y + alpha*beta n_z')
uexpected = u('α n_x + sin(ω) n_y + α⋅β n_z')
assert ascii_vpretty(w) == expected
assert unicode_vpretty(w) == uexpected
示例4: annotated
def annotated(letter):
"""
Return a stylised drawing of the letter ``letter``, together with
information on how to put annotations (super- and subscripts to the
left and to the right) on it.
See pretty.py functions _print_meijerg, _print_hyper on how to use this
information.
"""
ucode_pics = {
'F': (2, 0, 2, 0, u('\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
'\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
'\N{BOX DRAWINGS LIGHT UP}')),
'G': (3, 0, 3, 1,
u('\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}\n'
'\N{BOX DRAWINGS LIGHT VERTICAL}\N{BOX DRAWINGS LIGHT RIGHT}\N{BOX DRAWINGS LIGHT DOWN AND LEFT}\n'
'\N{BOX DRAWINGS LIGHT ARC UP AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC UP AND LEFT}'))
}
ascii_pics = {
'F': (3, 0, 3, 0, ' _\n|_\n|\n'),
'G': (3, 0, 3, 1, ' __\n/__\n\_|')
}
if _use_unicode:
return ucode_pics[letter]
else:
return ascii_pics[letter]
示例5: test_ipythonprinting
def test_ipythonprinting():
# Initialize and setup IPython session
app = init_ipython_session()
app.run_cell("ip = get_ipython()")
app.run_cell("inst = ip.instance()")
app.run_cell("format = inst.display_formatter.format")
app.run_cell("from sympy import Symbol")
# Printing without printing extension
app.run_cell("a = format(Symbol('pi'))")
app.run_cell("a2 = format(Symbol('pi')**2)")
# Deal with API change starting at IPython 1.0
if int(ipython.__version__.split(".")[0]) < 1:
assert app.user_ns['a']['text/plain'] == "pi"
assert app.user_ns['a2']['text/plain'] == "pi**2"
else:
assert app.user_ns['a'][0]['text/plain'] == "pi"
assert app.user_ns['a2'][0]['text/plain'] == "pi**2"
# Load printing extension
app.run_cell("from sympy import init_printing")
app.run_cell("init_printing()")
# Printing with printing extension
app.run_cell("a = format(Symbol('pi'))")
app.run_cell("a2 = format(Symbol('pi')**2)")
# Deal with API change starting at IPython 1.0
if int(ipython.__version__.split(".")[0]) < 1:
assert app.user_ns['a']['text/plain'] in (u('\N{GREEK SMALL LETTER PI}'), 'pi')
assert app.user_ns['a2']['text/plain'] in (u(' 2\n\N{GREEK SMALL LETTER PI} '), ' 2\npi ')
else:
assert app.user_ns['a'][0]['text/plain'] in (u('\N{GREEK SMALL LETTER PI}'), 'pi')
assert app.user_ns['a2'][0]['text/plain'] in (u(' 2\n\N{GREEK SMALL LETTER PI} '), ' 2\npi ')
示例6: test_print_builtin_option
def test_print_builtin_option():
# Initialize and setup IPython session
app = init_ipython_session()
app.run_cell("ip = get_ipython()")
app.run_cell("inst = ip.instance()")
app.run_cell("format = inst.display_formatter.format")
app.run_cell("from sympy import Symbol")
app.run_cell("from sympy import init_printing")
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
# Deal with API change starting at IPython 1.0
if int(ipython.__version__.split(".")[0]) < 1:
text = app.user_ns['a']['text/plain']
raises(KeyError, lambda: app.user_ns['a']['text/latex'])
else:
text = app.user_ns['a'][0]['text/plain']
raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
# Note : Unicode of Python2 is equivalent to str in Python3. In Python 3 we have one
# text type: str which holds Unicode data and two byte types bytes and bytearray.
# XXX: How can we make this ignore the terminal width? This test fails if
# the terminal is too narrow.
assert text in ("{pi: 3.14, n_i: 3}",
u('{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}'),
"{n_i: 3, pi: 3.14}",
u('{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}'))
# If we enable the default printing, then the dictionary's should render
# as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
app.run_cell("init_printing(use_latex=True)")
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
# Deal with API change starting at IPython 1.0
if int(ipython.__version__.split(".")[0]) < 1:
text = app.user_ns['a']['text/plain']
latex = app.user_ns['a']['text/latex']
else:
text = app.user_ns['a'][0]['text/plain']
latex = app.user_ns['a'][0]['text/latex']
assert text in ("{pi: 3.14, n_i: 3}",
u('{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}'),
"{n_i: 3, pi: 3.14}",
u('{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}'))
assert latex == r'$$\left \{ n_{i} : 3, \quad \pi : 3.14\right \}$$'
app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
app.run_cell("init_printing(use_latex=True, print_builtin=False)")
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
# Deal with API change starting at IPython 1.0
if int(ipython.__version__.split(".")[0]) < 1:
text = app.user_ns['a']['text/plain']
raises(KeyError, lambda: app.user_ns['a']['text/latex'])
else:
text = app.user_ns['a'][0]['text/plain']
raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
# Note : Unicode of Python2 is equivalent to str in Python3. In Python 3 we have one
# text type: str which holds Unicode data and two byte types bytes and bytearray.
# Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
# Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
# Python 2.7.5 + IPython 1.1.0 gives: '{pi: 3.14, n_i: 3}'
assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
示例7: test_anticommutator
def test_anticommutator():
A = Operator('A')
B = Operator('B')
ac = AntiCommutator(A, B)
ac_tall = AntiCommutator(A**2, B)
assert str(ac) == '{A,B}'
assert pretty(ac) == '{A,B}'
assert upretty(ac) == u('{A,B}')
assert latex(ac) == r'\left\{A,B\right\}'
sT(ac, "AntiCommutator(Operator(Symbol('A')),Operator(Symbol('B')))")
assert str(ac_tall) == '{A**2,B}'
ascii_str = \
"""\
/ 2 \\\n\
<A ,B>\n\
\\ /\
"""
ucode_str = \
u("""\
⎧ 2 ⎫\n\
⎨A ,B⎬\n\
⎩ ⎭\
""")
assert pretty(ac_tall) == ascii_str
assert upretty(ac_tall) == ucode_str
assert latex(ac_tall) == r'\left\{\left(A\right)^{2},B\right\}'
sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
示例8: test_operator
def test_operator():
a = Operator('A')
b = Operator('B', Symbol('t'), S(1)/2)
inv = a.inv()
f = Function('f')
x = symbols('x')
d = DifferentialOperator(Derivative(f(x), x), f(x))
op = OuterProduct(Ket(), Bra())
assert str(a) == 'A'
assert pretty(a) == 'A'
assert upretty(a) == u('A')
assert latex(a) == 'A'
sT(a, "Operator(Symbol('A'))")
assert str(inv) == 'A**(-1)'
ascii_str = \
"""\
-1\n\
A \
"""
ucode_str = \
u("""\
-1\n\
A \
""")
assert pretty(inv) == ascii_str
assert upretty(inv) == ucode_str
assert latex(inv) == r'\left(A\right)^{-1}'
sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))")
assert str(d) == 'DifferentialOperator(Derivative(f(x), x),f(x))'
ascii_str = \
"""\
/d \\\n\
DifferentialOperator|--(f(x)),f(x)|\n\
\dx /\
"""
ucode_str = \
u("""\
⎛d ⎞\n\
DifferentialOperator⎜──(f(x)),f(x)⎟\n\
⎝dx ⎠\
""")
assert pretty(d) == ascii_str
assert upretty(d) == ucode_str
assert latex(d) == \
r'DifferentialOperator\left(\frac{d}{d x} f{\left (x \right )},f{\left (x \right )}\right)'
sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Symbol('x')),Function('f')(Symbol('x')))")
assert str(b) == 'Operator(B,t,1/2)'
assert pretty(b) == 'Operator(B,t,1/2)'
assert upretty(b) == u('Operator(B,t,1/2)')
assert latex(b) == r'Operator\left(B,t,\frac{1}{2}\right)'
sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))")
assert str(op) == '|psi><psi|'
assert pretty(op) == '|psi><psi|'
assert upretty(op) == u('❘ψ⟩⟨ψ❘')
assert latex(op) == r'{\left|\psi\right\rangle }{\left\langle \psi\right|}'
sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))")
示例9: test_vector_derivative_printing
def test_vector_derivative_printing():
# First order
v = omega.diff() * N.x
assert unicode_vpretty(v) == u('ω̇ n_x')
assert ascii_vpretty(v) == u("omega'(t) n_x")
# Second order
v = omega.diff().diff() * N.x
assert v._latex() == r'\ddot{\omega}\mathbf{\hat{n}_x}'
assert unicode_vpretty(v) == u('ω̈ n_x')
assert ascii_vpretty(v) == u("omega''(t) n_x")
# Third order
v = omega.diff().diff().diff() * N.x
assert v._latex() == r'\dddot{\omega}\mathbf{\hat{n}_x}'
assert unicode_vpretty(v) == u('ω⃛ n_x')
assert ascii_vpretty(v) == u("omega'''(t) n_x")
# Fourth order
v = omega.diff().diff().diff().diff() * N.x
assert v._latex() == r'\ddddot{\omega}\mathbf{\hat{n}_x}'
assert unicode_vpretty(v) == u('ω⃜ n_x')
assert ascii_vpretty(v) == u("omega''''(t) n_x")
# Fifth order
v = omega.diff().diff().diff().diff().diff() * N.x
assert v._latex() == r'\frac{d^{5}}{d t^{5}} \omega{\left(t \right)}\mathbf{\hat{n}_x}'
assert unicode_vpretty(v) == u(' 5\n d\n───(ω) n_x\n 5\ndt')
assert ascii_vpretty(v) == ' 5\n d\n---(omega) n_x\n 5\ndt'
示例10: test_operator
def test_operator():
a = Operator("A")
b = Operator("B", Symbol("t"), S(1) / 2)
inv = a.inv()
f = Function("f")
x = symbols("x")
d = DifferentialOperator(Derivative(f(x), x), f(x))
op = OuterProduct(Ket(), Bra())
assert str(a) == "A"
assert pretty(a) == "A"
assert upretty(a) == u"A"
assert latex(a) == "A"
sT(a, "Operator(Symbol('A'))")
assert str(inv) == "A**(-1)"
ascii_str = """\
-1\n\
A \
"""
ucode_str = u(
"""\
-1\n\
A \
"""
)
assert pretty(inv) == ascii_str
assert upretty(inv) == ucode_str
assert latex(inv) == r"A^{-1}"
sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))")
assert str(d) == "DifferentialOperator(Derivative(f(x), x),f(x))"
ascii_str = """\
/d \\\n\
DifferentialOperator|--(f(x)),f(x)|\n\
\dx /\
"""
ucode_str = u(
"""\
⎛d ⎞\n\
DifferentialOperator⎜──(f(x)),f(x)⎟\n\
⎝dx ⎠\
"""
)
assert pretty(d) == ascii_str
assert upretty(d) == ucode_str
assert latex(d) == r"DifferentialOperator\left(\frac{d}{d x} f{\left (x \right )},f{\left (x \right )}\right)"
sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Symbol('x')),Function('f')(Symbol('x')))")
assert str(b) == "Operator(B,t,1/2)"
assert pretty(b) == "Operator(B,t,1/2)"
assert upretty(b) == u"Operator(B,t,1/2)"
assert latex(b) == r"Operator\left(B,t,\frac{1}{2}\right)"
sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))")
assert str(op) == "|psi><psi|"
assert pretty(op) == "|psi><psi|"
assert upretty(op) == u"❘ψ⟩⟨ψ❘"
assert latex(op) == r"{\left|\psi\right\rangle }{\left\langle \psi\right|}"
sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))")
示例11: test_qubit
def test_qubit():
q1 = Qubit('0101')
q2 = IntQubit(8)
assert str(q1) == '|0101>'
assert pretty(q1) == '|0101>'
assert upretty(q1) == u('❘0101⟩')
assert latex(q1) == r'{\left|0101\right\rangle }'
sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))")
assert str(q2) == '|8>'
assert pretty(q2) == '|8>'
assert upretty(q2) == u('❘8⟩')
assert latex(q2) == r'{\left|8\right\rangle }'
sT(q2, "IntQubit(8)")
示例12: test_upretty_sub_super
def test_upretty_sub_super():
assert upretty( Symbol('beta_1_2') ) == u('β₁ ₂')
assert upretty( Symbol('beta^1^2') ) == u('β¹ ²')
assert upretty( Symbol('beta_1^2') ) == u('β²₁')
assert upretty( Symbol('beta_10_20') ) == u('β₁₀ ₂₀')
assert upretty( Symbol('beta_ax_gamma^i') ) == u('βⁱₐₓ ᵧ')
assert upretty( Symbol("F^1^2_3_4") ) == u('F¹ ²₃ ₄')
assert upretty( Symbol("F_1_2^3^4") ) == u('F³ ⁴₁ ₂')
assert upretty( Symbol("F_1_2_3_4") ) == u('F₁ ₂ ₃ ₄')
assert upretty( Symbol("F^1^2^3^4") ) == u('F¹ ² ³ ⁴')
示例13: test_dyadic_pretty_print
def test_dyadic_pretty_print():
expected = u("""\
2
a n_x⊗n_y + b n_y⊗n_y + c⋅sin(α) n_z⊗n_y\
""")
result = y._pretty().render()
assert expected == result
expected = u('α n_x⊗n_x + sin(ω) n_y⊗n_z + α⋅β n_z⊗n_x')
result = x._pretty().render()
assert expected == result
示例14: test_print_builtin_option
def test_print_builtin_option():
# Initialize and setup IPython session
app = init_ipython_session()
app.run_cell("ip = get_ipython()")
app.run_cell("inst = ip.instance()")
app.run_cell("format = inst.display_formatter.format")
app.run_cell("from sympy import Symbol")
app.run_cell("from sympy import init_printing")
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
# Deal with API change starting at IPython 1.0
if int(ipython.__version__.split(".")[0]) < 1:
text = app.user_ns['a']['text/plain']
raises(KeyError, lambda: app.user_ns['a']['text/latex'])
else:
text = app.user_ns['a'][0]['text/plain']
raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
# Note : In Python 3 the text is unicode, but in 2 it is a string.
assert text in ("{pi: 3.14, n_i: 3}", u('{n\u1d62: 3, \u03c0: 3.14}'))
# If we enable the default printing, then the dictionary's should render
# as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
app.run_cell("init_printing(use_latex=True)")
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
# Deal with API change starting at IPython 1.0
if int(ipython.__version__.split(".")[0]) < 1:
text = app.user_ns['a']['text/plain']
latex = app.user_ns['a']['text/latex']
else:
text = app.user_ns['a'][0]['text/plain']
latex = app.user_ns['a'][0]['text/latex']
assert text == u('{n\u1d62: 3, \u03c0: 3.14}')
assert latex == '$$\\begin{Bmatrix}n_{i} : 3, & \\pi : 3.14\\end{Bmatrix}$$'
app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
app.run_cell("init_printing(use_latex=True, print_builtin=False)")
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
# Deal with API change starting at IPython 1.0
if int(ipython.__version__.split(".")[0]) < 1:
text = app.user_ns['a']['text/plain']
raises(KeyError, lambda: app.user_ns['a']['text/latex'])
else:
text = app.user_ns['a'][0]['text/plain']
raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
# Note : In Python 3 the text is unicode, but in 2 it is a string.
# Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
# Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
# Python 2.7.5 + IPython 1.1.0 gives: '{pi: 3.14, n_i: 3}'
assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
示例15: render
def render(self, *args, **kwargs):
self = e
ar = self.args # just to shorten things
if len(ar) == 0:
return unicode(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
ol.append(u(" + ") + ar[i][1].pretty_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
ol.append(u(" - ") + ar[i][1].pretty_vecs[j])
elif ar[i][0][j] != 0:
# If the basis vector coeff is not 1 or -1,
# we might wrap it in parentheses, for readability.
arg_str = (VectorPrettyPrinter().doprint(
ar[i][0][j]))
if isinstance(ar[i][0][j], Add):
arg_str = u("(%s)") % arg_str
if arg_str[0] == u("-"):
arg_str = arg_str[1:]
str_start = u(" - ")
else:
str_start = u(" + ")
ol.append(str_start + arg_str + '*' +
ar[i][1].pretty_vecs[j])
outstr = u("").join(ol)
if outstr.startswith(u(" + ")):
outstr = outstr[3:]
elif outstr.startswith(" "):
outstr = outstr[1:]
return outstr