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')))")
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')
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')))")
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]
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
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 ')
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}")
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')))")
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'
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')))")
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)")
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¹ ² ³ ⁴')
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}")
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
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
def render(self, *args, **kwargs): ar = e.args # just to shorten things settings = printer._settings if printer else {} if printer: use_unicode = printer._use_unicode else: from sympy.printing.pretty.pretty_symbology import ( pretty_use_unicode) use_unicode = pretty_use_unicode() mpp = printer if printer else VectorPrettyPrinter(settings) if len(ar) == 0: return unicode(0) bar = u("\N{CIRCLED TIMES}") if use_unicode else "|" ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): # if the coef of the dyadic is 1, we skip the 1 if ar[i][0] == 1: ol.extend([u(" + "), mpp.doprint(ar[i][1]), bar, mpp.doprint(ar[i][2])]) # if the coef of the dyadic is -1, we skip the 1 elif ar[i][0] == -1: ol.extend([u(" - "), mpp.doprint(ar[i][1]), bar, mpp.doprint(ar[i][2])]) # If the coefficient of the dyadic is not 1 or -1, # we might wrap it in parentheses, for readability. elif ar[i][0] != 0: if isinstance(ar[i][0], Add): arg_str = mpp._print( ar[i][0]).parens()[0] else: arg_str = mpp.doprint(ar[i][0]) if arg_str.startswith(u("-")): arg_str = arg_str[1:] str_start = u(" - ") else: str_start = u(" + ") ol.extend([str_start, arg_str, u(" "), mpp.doprint(ar[i][1]), bar, mpp.doprint(ar[i][2])]) outstr = u("").join(ol) if outstr.startswith(u(" + ")): outstr = outstr[3:] elif outstr.startswith(" "): outstr = outstr[1:] return outstr
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[A^{2},B\right]" sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
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\{A^{2},B\right\}" sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def __new__(cls, name, index, system, pretty_str, latex_str): from sympy.vector.coordsysrect import CoordSysCartesian if isinstance(name, Symbol): name = name.name if isinstance(pretty_str, Symbol): pretty_str = pretty_str.name if isinstance(latex_str, Symbol): latex_str = latex_str.name index = _sympify(index) system = _sympify(system) obj = super(BaseScalar, cls).__new__(cls, Symbol(name), index, system, Symbol(pretty_str), Symbol(latex_str)) if not isinstance(system, CoordSysCartesian): raise TypeError("system should be a CoordSysCartesian") if index not in range(0, 3): raise ValueError("Invalid index specified.") # The _id is used for equating purposes, and for hashing obj._id = (index, system) obj._name = obj.name = name obj._pretty_form = u(pretty_str) obj._latex_form = latex_str obj._system = system return obj
def _pretty(self, printer, *args): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (Add, Mul)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(u('\u2a02') + u(' '))) else: pform = prettyForm(*pform.right('x' + ' ')) return pform
def test_qexpr(): q = QExpr('q') assert str(q) == 'q' assert pretty(q) == 'q' assert upretty(q) == u('q') assert latex(q) == r'q' sT(q, "QExpr(Symbol('q'))")
def __new__(cls, name, index, system, pretty_str, latex_str): name = str(name) pretty_str = str(pretty_str) latex_str = str(latex_str) #Verify arguments if not index in range(0, 3): raise ValueError("index must be 0, 1 or 2") if not isinstance(system, CoordSysCartesian): raise TypeError("system should be a CoordSysCartesian") #Initialize an object obj = super(BaseVector, cls).__new__(cls, Symbol(name), S(index), system, Symbol(pretty_str), Symbol(latex_str)) #Assign important attributes obj._base_instance = obj obj._components = {obj: S(1)} obj._measure_number = S(1) obj._name = name obj._pretty_form = u(pretty_str) obj._latex_form = latex_str obj._system = system assumptions = {} assumptions['commutative'] = True obj._assumptions = StdFactKB(assumptions) #This attr is used for re-expression to one of the systems #involved in the definition of the Vector. Applies to #VectorMul and VectorAdd too. obj._sys = system return obj
def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if self.is_annihilation: return pform else: return pform**prettyForm(u('\u2020'))
def _pretty(self, printer, *args): pform_exp = printer._print(self.exp, *args) if printer._use_unicode: pform_exp = prettyForm(*pform_exp.left(prettyForm(u('\N{N-ARY CIRCLED TIMES OPERATOR}')))) else: pform_exp = prettyForm(*pform_exp.left(prettyForm('x'))) pform_base = printer._print(self.base, *args) return pform_base**pform_exp
def _pretty(self, printer, *args): pform_exp = printer._print(self.exp, *args) if printer._use_unicode: pform_exp = prettyForm(*pform_exp.left(prettyForm(u('\u2a02')))) else: pform_exp = prettyForm(*pform_exp.left(prettyForm('x'))) pform_base = printer._print(self.base, *args) return pform_base**pform_exp
def _pretty(self, printer, *args): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(u(' ') + u('\N{CIRCLED PLUS}') + u(' '))) else: pform = prettyForm(*pform.right(' + ')) return pform
def test_tensorproduct(): tp = TensorProduct(JzKet(1, 1), JzKet(1, 0)) assert str(tp) == '|1,1>x|1,0>' assert pretty(tp) == '|1,1>x |1,0>' assert upretty(tp) == u('❘1,1⟩⨂ ❘1,0⟩') assert latex(tp) == \ r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}' sT(tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))")
def _pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if printer._use_unicode: pform = pform**prettyForm(u('\u2020')) else: pform = pform**prettyForm('+') return pform
def _test_rational_new(cls): """ Tests that are common between Integer and Rational. """ assert cls(0) is S.Zero assert cls(1) is S.One assert cls(-1) is S.NegativeOne # These look odd, but are similar to int(): assert cls('1') is S.One assert cls(u('-1')) is S.NegativeOne i = Integer(10) assert _strictly_equal(i, cls('10')) assert _strictly_equal(i, cls(u('10'))) assert _strictly_equal(i, cls(long(10))) assert _strictly_equal(i, cls(i)) raises(TypeError, lambda: cls(Symbol('x')))
def test_iterable_is_sequence(): ordered = [list(), tuple(), Tuple(), Matrix([[]])] unordered = [set()] not_sympy_iterable = [{}, '', u('')] assert all(is_sequence(i) for i in ordered) assert all(not is_sequence(i) for i in unordered) assert all(iterable(i) for i in ordered + unordered) assert all(not iterable(i) for i in not_sympy_iterable) assert all(iterable(i, exclude=None) for i in not_sympy_iterable)
def _pretty_brackets(self, height, use_unicode=True): # Return pretty printed brackets for the state # Ideally, this could be done by pform.parens but it does not support the angled < and > # Setup for unicode vs ascii if use_unicode: lbracket, rbracket = self.lbracket_ucode, self.rbracket_ucode slash, bslash, vert = u('\u2571'), u('\u2572'), u('\u2502') else: lbracket, rbracket = self.lbracket, self.rbracket slash, bslash, vert = '/', '\\', '|' # If height is 1, just return brackets if height == 1: return stringPict(lbracket), stringPict(rbracket) # Make height even height += (height % 2) brackets = [] for bracket in lbracket, rbracket: # Create left bracket if bracket in set([_lbracket, _lbracket_ucode]): bracket_args = [ ' ' * (height // 2 - i - 1) + slash for i in range(height // 2) ] bracket_args.extend( [' ' * i + bslash for i in range(height // 2)]) # Create right bracket elif bracket in set([_rbracket, _rbracket_ucode]): bracket_args = [' ' * i + bslash for i in range(height // 2)] bracket_args.extend([ ' ' * (height // 2 - i - 1) + slash for i in range(height // 2) ]) # Create straight bracket elif bracket in set([_straight_bracket, _straight_bracket_ucode]): bracket_args = [vert for i in range(height)] else: raise ValueError(bracket) brackets.append( stringPict('\n'.join(bracket_args), baseline=height // 2)) return brackets
def plot_gate(self, circ_plot, gate_idx): """ Plot the controlled gate. If *simplify_cgate* is true, simplify C-X and C-Z gates into their more familiar forms. """ min_wire = int(_min(chain(self.controls, self.targets))) max_wire = int(_max(chain(self.controls, self.targets))) circ_plot.control_line(gate_idx, min_wire, max_wire) for c in self.controls: circ_plot.control_point(gate_idx, int(c)) if self.simplify_cgate: if self.gate.gate_name == u('X'): self.gate.plot_gate_plus(circ_plot, gate_idx) elif self.gate.gate_name == u('Z'): circ_plot.control_point(gate_idx, self.targets[0]) else: self.gate.plot_gate(circ_plot, gate_idx) else: self.gate.plot_gate(circ_plot, gate_idx)
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 subscritp with unicode. # TODO : The pretty print division does not print correctly here: # w = alpha * N.x + sin(omega) * N.y + alpha / beta * N.z pp = VectorPrettyPrinter() expected = u(' 2\na n_x + b n_y + c\u22c5sin(\u03b1) n_z') assert expected == pp.doprint(v) assert expected == v._pretty().render() expected = u('\u03b1 n_x + sin(\u03c9) n_y + \u03b1\u22c5\u03b2 n_z') assert expected == pp.doprint(w) assert expected == w._pretty().render()
def _pretty(self, printer, *args): if (_combined_printing and (all([isinstance(arg, Ket) for arg in self.args]) or all([isinstance(arg, Bra) for arg in self.args]))): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print('', *args) length_i = len(self.args[i].args) for j in range(length_i): part_pform = printer._print(self.args[i].args[j], *args) next_pform = prettyForm(*next_pform.right(part_pform)) if j != length_i - 1: next_pform = prettyForm(*next_pform.right(', ')) if len(self.args[i].args) > 1: next_pform = prettyForm( *next_pform.parens(left='{', right='}')) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: pform = prettyForm(*pform.right(',' + ' ')) pform = prettyForm(*pform.left(self.args[0].lbracket)) pform = prettyForm(*pform.right(self.args[0].rbracket)) return pform length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (Add, Mul)): next_pform = prettyForm( *next_pform.parens(left='(', right=')')) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right( u('\N{N-ARY CIRCLED TIMES OPERATOR}') + u(' '))) else: pform = prettyForm(*pform.right('x' + ' ')) return pform
def test_dyadic_pretty_print(): expected = u(' 2\na \x1b[94m\x1b[1mn_x\x1b[0;0m\x1b[0;0m\u2297\x1b[94' 'm\x1b[1mn_y\x1b[0;0m\x1b[0;0m + b \x1b[94m\x1b[1mn_y\x1b' '[0;0m\x1b[0;0m\u2297\x1b[94m\x1b[1mn_y\x1b[0;0m\x1b[0;0m' ' + c\u22c5sin(\u03b1) \x1b[94m\x1b[1mn_z\x1b[0;0m\x1b[0;' '0m\u2297\x1b[94m\x1b[1mn_y\x1b[0;0m\x1b[0;0m') result = y._pretty().render() assert expected == result expected = u('\u03b1 \x1b[94m\x1b[1mn_x\x1b[0;0m\x1b[0;0m\u2297\x1b[94' 'm\x1b[1mn_x\x1b[0;0m\x1b[0;0m + sin(\u03c9) \x1b[94m\x1b' '[1mn_y\x1b[0;0m\x1b[0;0m\u2297\x1b[94m\x1b[1mn_z\x1b[0;0' 'm\x1b[0;0m + \u03b1\u22c5\u03b2 \x1b[94m\x1b[1mn_z\x1b[0' ';0m\x1b[0;0m\u2297\x1b[94m\x1b[1mn_x\x1b[0;0m\x1b[0;0m') result = x._pretty().render() assert expected == result
def test_tensorproduct(): tp = TensorProduct(JzKet(1, 1), JzKet(1, 0)) assert str(tp) == '|1,1>x|1,0>' assert pretty(tp) == '|1,1>x |1,0>' assert upretty(tp) == u('❘1,1⟩⨂ ❘1,0⟩') assert latex(tp) == \ r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}' sT( tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))" )
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 expected = """\ 2 a b + c c - n_x + ----- n_y + -- n_z b a b\ """ uexpected = u("""\ 2 a b + c c ─ n_x + ───── n_y + ── n_z b a b\ """) assert ascii_vpretty(o) == expected assert unicode_vpretty(o) == uexpected
class VectorZero(BasisDependentZero, Vector): """ Class to denote a zero vector """ _op_priority = 12.1 _pretty_form = u('0') _latex_form = '\mathbf{\hat{0}}' def __new__(cls): obj = BasisDependentZero.__new__(cls) return obj
class DyadicZero(BasisDependentZero, Dyadic): """ Class to denote a zero dyadic """ _op_priority = 13.1 _pretty_form = u('(0|0)') _latex_form = '(\mathbf{\hat{0}}|\mathbf{\hat{0}})' def __new__(cls): obj = BasisDependentZero.__new__(cls) return obj
def test_pretty_print_unicode(): assert upretty(v[0]) == u('0') assert upretty(v[1]) == u('N_i') assert upretty(v[5]) == u('(a) N_i + (-b) N_j') # Make sure the printing works in other objects assert upretty(v[5].args) == u('((a) N_i, (-b) N_j)') assert upretty(v[8]) == upretty_v_8 assert upretty(v[2]) == u('(-1) N_i') assert upretty(v[11]) == upretty_v_11 assert upretty(s) == upretty_s assert upretty(d[0]) == u('(0|0)') assert upretty(d[5]) == u('(a) (N_i|N_k) + (-b) (N_j|N_k)') assert upretty(d[7]) == upretty_d_7 assert upretty(d[10]) == u('(cos(a)) (C_i|N_k) + (-sin(a)) (C_j|N_k)')
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 pp = VectorPrettyPrinter() expected = u("""\ 2 a n_x + b n_y + c⋅sin(α) n_z\ """) assert expected == pp.doprint(v) assert expected == v._pretty().render() expected = u('α n_x + sin(ω) n_y + α⋅β n_z') assert expected == pp.doprint(w) assert expected == w._pretty().render()
def test_pretty_print_unicode(): assert upretty(v[0]) == u('0') assert upretty(v[1]) == u('N_i') assert upretty(v[5]) == u('(a) N_i + (-b) N_j') assert upretty(v[8]) == upretty_v_8 assert upretty(v[2]) == u('(-1) N_i') assert upretty(v[11]) == upretty_v_11 assert upretty(s) == upretty_s assert upretty(d[0]) == u('(0|0)') assert upretty(d[5]) == u('(a) (N_i|N_k) + (-b) (N_j|N_k)') assert upretty(d[7]) == upretty_d_7 assert upretty(d[10]) == u('(cos(a)) (C_i|N_k) + (-sin(a)) (C_j|N_k)')
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('\u250c\u2500\n\u251c\u2500\n\u2575')), 'G': (3, 0, 3, 1, u('\u256d\u2500\u256e\n\u2502\u2576\u2510\n\u2570\u2500\u256f')) } 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]
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 subscritp with unicode. # TODO : The pretty print division does not print correctly here: # w = alpha * N.x + sin(omega) * N.y + alpha / beta * N.z pp = VectorPrettyPrinter() expected = u(' 2\na \x1b[94m\x1b[1mn_x\x1b[0;0m\x1b[0;0m + b \x1b[94m' '\x1b[1mn_y\x1b[0;0m\x1b[0;0m + c\u22c5sin(\u03b1) \x1b[9' '4m\x1b[1mn_z\x1b[0;0m\x1b[0;0m') assert expected == pp.doprint(v) assert expected == v._pretty().render() expected = u('\u03b1 \x1b[94m\x1b[1mn_x\x1b[0;0m\x1b[0;0m + sin(\u03c9' ') \x1b[94m\x1b[1mn_y\x1b[0;0m\x1b[0;0m + \u03b1\u22c5' '\u03b2 \x1b[94m\x1b[1mn_z\x1b[0;0m\x1b[0;0m') assert expected == pp.doprint(w) assert expected == w._pretty().render()
class IdentityGate(OneQubitGate): """The single qubit identity gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('1') gate_name_latex = u('1') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('eye2', format) def _eval_commutator(self, other, **hints): return Integer(0) def _eval_anticommutator(self, other, **hints): return Integer(2) * other
class ZGate(HermitianOperator, OneQubitGate): """The single qubit Z gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('Z') gate_name_latex = u('Z') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Z', format) def _eval_commutator_XGate(self, other, **hints): return Integer(2) * I * YGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0)
class XGate(HermitianOperator, OneQubitGate): """The single qubit X, or NOT, gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('X') gate_name_latex = u('X') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('X', format) def plot_gate(self, circ_plot, gate_idx): OneQubitGate.plot_gate(self,circ_plot,gate_idx) def plot_gate_plus(self, circ_plot, gate_idx): circ_plot.not_point( gate_idx, int(self.label[0]) ) def _eval_commutator_YGate(self, other, **hints): return Integer(2)*I*ZGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0)
def __new__(cls, name, index, system, pretty_str, latex_str): from sympy.vector.coordsysrect import CoordSysCartesian obj = super(BaseScalar, cls).__new__(cls, name) if not isinstance(system, CoordSysCartesian): raise TypeError("system should be a CoordSysCartesian") if index not in range(0, 3): raise ValueError("Invalid index specified.") #The _id is used for equating purposes, and for hashing obj._id = (index, system) obj._name = name obj._pretty_form = u(pretty_str) obj._latex_form = latex_str obj._system = system return obj
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 ')
def test_dagger(): x = symbols("x") expr = Dagger(x) assert str(expr) == "Dagger(x)" ascii_str = """\ +\n\ x \ """ ucode_str = u("""\ †\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str assert latex(expr) == r"x^{\dagger}" sT(expr, "Dagger(Symbol('x'))")
def test_dagger(): x = symbols('x') expr = Dagger(x) assert str(expr) == 'Dagger(x)' ascii_str = \ """\ +\n\ x \ """ ucode_str = \ u("""\ †\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str assert latex(expr) == r'x^{\dag}' sT(expr, "Dagger(Symbol('x'))")
def __new__(cls, vector1, vector2): Vector = sympy.vector.Vector BaseVector = sympy.vector.BaseVector VectorZero = sympy.vector.VectorZero #Verify arguments if not isinstance(vector1, (BaseVector, VectorZero)) or \ not isinstance(vector2, (BaseVector, VectorZero)): raise TypeError("BaseDyadic cannot be composed of non-base "+ "vectors") #Handle special case of zero vector elif vector1 == Vector.zero or vector2 == Vector.zero: return Dyadic.zero #Initialize instance obj = super(BaseDyadic, cls).__new__(cls, vector1, vector2) obj._base_instance = obj obj._measure_number = 1 obj._components = {obj: S(1)} obj._sys = vector1._sys obj._pretty_form = u('(' + vector1._pretty_form + '|' + vector2._pretty_form + ')') obj._latex_form = ('(' + vector1._latex_form + "{|}" + vector2._latex_form + ')') return obj
def render(self, *args, **kwargs): ar = e.args # just to shorten things if len(ar) == 0: return unicode(0) settings = printer._settings if printer else {} vp = printer if printer else VectorPrettyPrinter(settings) 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. if isinstance(ar[i][0][j], Add): arg_str = vp._print( ar[i][0][j]).parens()[0] else: arg_str = (vp.doprint( ar[i][0][j])) 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
'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState', 'TimeDepBra', 'TimeDepKet', 'Wavefunction' ] #----------------------------------------------------------------------------- # States, bras and kets. #----------------------------------------------------------------------------- # ASCII brackets _lbracket = "<" _rbracket = ">" _straight_bracket = "|" # Unicode brackets # MATHEMATICAL ANGLE BRACKETS _lbracket_ucode = u("\u27E8") _rbracket_ucode = u("\u27E9") # LIGHT VERTICAL BAR _straight_bracket_ucode = u("\u2758") # Other options for unicode printing of <, > and | for Dirac notation. # LEFT-POINTING ANGLE BRACKET # _lbracket = u"\u2329" # _rbracket = u"\u232A" # LEFT ANGLE BRACKET # _lbracket = u"\u3008" # _rbracket = u"\u3009" # VERTICAL LINE
"""Simple tools for timing functions' execution, when IPython is not available. """ from __future__ import print_function, division import timeit import math from sympy.core.compatibility import u _scales = [1e0, 1e3, 1e6, 1e9] _units = [u('s'), u('ms'), u('\u03bcs'), u('ns')] def timed(func, setup="pass", limit=None): """Adaptively measure execution time of a function. """ timer = timeit.Timer(func, setup=setup) repeat, number = 3, 1 for i in range(1, 10): if timer.timeit(number) >= 0.2: break elif limit is not None and number >= limit: break else: number *= 10 time = min(timer.repeat(repeat, number)) / number if time > 0.0: order = min(-int(math.floor(math.log10(time)) // 3), 3) else:
def _pretty(self, printer, *args): # u = u('\u2108') # script ustr = u('\u0048') return prettyForm(ustr)
def _pretty(self, printer, *args): if printer._use_unicode: return prettyForm(u('\u210f')) return prettyForm('hbar')
class QExpr(Expr): """A base class for all quantum object like operators and states.""" # In sympy, slots are for instance attributes that are computed # dynamically by the __new__ method. They are not part of args, but they # derive from args. # The Hilbert space a quantum Object belongs to. __slots__ = ['hilbert_space'] is_commutative = False # The separator used in printing the label. _label_separator = u('') @property def free_symbols(self): return set([self]) def __new__(cls, *args, **old_assumptions): """Construct a new quantum object. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the quantum object. For a state, this will be its symbol or its set of quantum numbers. Examples ======== >>> from sympsi.qexpr import QExpr >>> q = QExpr(0) >>> q 0 >>> q.label (0,) >>> q.hilbert_space H >>> q.args (0,) >>> q.is_commutative False """ # First compute args and call Expr.__new__ to create the instance args = cls._eval_args(args) if len(args) == 0: args = cls._eval_args(tuple(cls.default_args())) inst = Expr.__new__(cls, *args, **old_assumptions) # Now set the slots on the instance inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _new_rawargs(cls, hilbert_space, *args, **old_assumptions): """Create new instance of this class with hilbert_space and args. This is used to bypass the more complex logic in the ``__new__`` method in cases where you already have the exact ``hilbert_space`` and ``args``. This should be used when you are positive these arguments are valid, in their final, proper form and want to optimize the creation of the object. """ obj = Expr.__new__(cls, *args, **old_assumptions) obj.hilbert_space = hilbert_space return obj #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def label(self): """The label is the unique set of identifiers for the object. Usually, this will include all of the information about the state *except* the time (in the case of time-dependent objects). This must be a tuple, rather than a Tuple. """ if len(self.args ) == 0: # If there is no label specified, return the default return self._eval_args(list(self.default_args())) else: return self.args @property def is_symbolic(self): return True @classmethod def default_args(self): """If no arguments are specified, then this will return a default set of arguments to be run through the constructor. NOTE: Any classes that override this MUST return a tuple of arguments. Should be overidden by subclasses to specify the default arguments for kets and operators """ raise NotImplementedError("No default arguments for this class!") #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_adjoint(self): obj = Expr._eval_adjoint(self) if obj is None: obj = Expr.__new__(Dagger, self) if isinstance(obj, QExpr): obj.hilbert_space = self.hilbert_space return obj @classmethod def _eval_args(cls, args): """Process the args passed to the __new__ method. This simply runs args through _qsympify_sequence. """ return _qsympify_sequence(args) @classmethod def _eval_hilbert_space(cls, args): """Compute the Hilbert space instance from the args. """ from sympsi.hilbert import HilbertSpace return HilbertSpace() #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- # Utilities for printing: these operate on raw sympy objects def _print_sequence(self, seq, sep, printer, *args): result = [] for item in seq: result.append(printer._print(item, *args)) return sep.join(result) def _print_sequence_pretty(self, seq, sep, printer, *args): pform = printer._print(seq[0], *args) for item in seq[1:]: pform = prettyForm(*pform.right((sep))) pform = prettyForm(*pform.right((printer._print(item, *args)))) return pform # Utilities for printing: these operate prettyForm objects def _print_subscript_pretty(self, a, b): top = prettyForm(*b.left(' ' * a.width())) bot = prettyForm(*a.right(' ' * b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_superscript_pretty(self, a, b): return a**b def _print_parens_pretty(self, pform, left='(', right=')'): return prettyForm(*pform.parens(left=left, right=right)) # Printing of labels (i.e. args) def _print_label(self, printer, *args): """Prints the label of the QExpr This method prints self.label, using self._label_separator to separate the elements. This method should not be overridden, instead, override _print_contents to change printing behavior. """ return self._print_sequence(self.label, self._label_separator, printer, *args) def _print_label_repr(self, printer, *args): return self._print_sequence(self.label, ',', printer, *args) def _print_label_pretty(self, printer, *args): return self._print_sequence_pretty(self.label, self._label_separator, printer, *args) def _print_label_latex(self, printer, *args): return self._print_sequence(self.label, self._label_separator, printer, *args) # Printing of contents (default to label) def _print_contents(self, printer, *args): """Printer for contents of QExpr Handles the printing of any unique identifying contents of a QExpr to print as its contents, such as any variables or quantum numbers. The default is to print the label, which is almost always the args. This should not include printing of any brackets or parenteses. """ return self._print_label(printer, *args) def _print_contents_pretty(self, printer, *args): return self._print_label_pretty(printer, *args) def _print_contents_latex(self, printer, *args): return self._print_label_latex(printer, *args) # Main printing methods def _sympystr(self, printer, *args): """Default printing behavior of QExpr objects Handles the default printing of a QExpr. To add other things to the printing of the object, such as an operator name to operators or brackets to states, the class should override the _print/_pretty/_latex functions directly and make calls to _print_contents where appropriate. This allows things like InnerProduct to easily control its printing the printing of contents. """ return self._print_contents(printer, *args) def _sympyrepr(self, printer, *args): classname = self.__class__.__name__ label = self._print_label_repr(printer, *args) return '%s(%s)' % (classname, label) def _pretty(self, printer, *args): pform = self._print_contents_pretty(printer, *args) return pform def _latex(self, printer, *args): return self._print_contents_latex(printer, *args) #------------------------------------------------------------------------- # Methods from Basic and Expr #------------------------------------------------------------------------- def doit(self, **kw_args): return self def _eval_rewrite(self, pattern, rule, **hints): if hints.get('deep', False): args = [a._eval_rewrite(pattern, rule, **hints) for a in self.args] else: args = self.args # TODO: Make Basic.rewrite use hints in evaluating # self.rule(*args, **hints), not having hints breaks spin state # (un)coupling on rewrite if pattern is None or isinstance(self, pattern): if hasattr(self, rule): rewritten = getattr(self, rule)(*args, **hints) if rewritten is not None: return rewritten return self #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): raise NotImplementedError('This object does not have a default basis') def _represent(self, **options): """Represent this object in a given basis. This method dispatches to the actual methods that perform the representation. Subclases of QExpr should define various methods to determine how the object will be represented in various bases. The format of these methods is:: def _represent_BasisName(self, basis, **options): Thus to define how a quantum object is represented in the basis of the operator Position, you would define:: def _represent_Position(self, basis, **options): Usually, basis object will be instances of Operator subclasses, but there is a chance we will relax this in the future to accomodate other types of basis sets that are not associated with an operator. If the ``format`` option is given it can be ("sympy", "numpy", "scipy.sparse"). This will ensure that any matrices that result from representing the object are returned in the appropriate matrix format. Parameters ========== basis : Operator The Operator whose basis functions will be used as the basis for representation. options : dict A dictionary of key/value pairs that give options and hints for the representation, such as the number of basis functions to be used. """ basis = options.pop('basis', None) if basis is None: result = self._represent_default_basis(**options) else: result = dispatch_method(self, '_represent', basis, **options) # If we get a matrix representation, convert it to the right format. format = options.get('format', 'sympy') result = self._format_represent(result, format) return result def _format_represent(self, result, format): if format == 'sympy' and not isinstance(result, Matrix): return to_sympy(result) elif format == 'numpy' and not isinstance(result, numpy_ndarray): return to_numpy(result) elif format == 'scipy.sparse' and \ not isinstance(result, scipy_sparse_matrix): return to_scipy_sparse(result) return result
def _print_GoldenRatio(self, e): """We use unicode #x3c6 for Greek letter phi as defined here http://www.w3.org/2003/entities/2007doc/isogrk1.html""" x = self.dom.createElement('cn') x.appendChild(self.dom.createTextNode(u("\u03c6"))) return x
C = N.orient_new_axis("C", a, N.k) # type: ignore v = [] d = [] v.append(Vector.zero) v.append(N.i) # type: ignore v.append(-N.i) # type: ignore v.append(N.i + N.j) # type: ignore v.append(a * N.i) # type: ignore v.append(a * N.i - b * N.j) # type: ignore v.append((a**2 + N.x) * N.i + N.k) # type: ignore v.append((a**2 + b) * N.i + 3 * (C.y - c) * N.k) # type: ignore f = Function("f") v.append(N.j - (Integral(f(b)) - C.x**2) * N.k) # type: ignore upretty_v_8 = u("""\ ⎛ 2 ⌠ ⎞ \n\ j_N + ⎜x_C - ⎮ f(b) db⎟ k_N\n\ ⎝ ⌡ ⎠ \ """) pretty_v_8 = u("""\ j_N + / / \\\n\ | 2 | |\n\ |x_C - | f(b) db|\n\ | | |\n\ \\ / / \ """) v.append(N.i + C.k) # type: ignore v.append(express(N.i, C)) # type: ignore v.append((a**2 + b) * N.i + (Integral(f(b))) * N.k) # type: ignore upretty_v_11 = u("""\ ⎛ 2 ⎞ ⎛⌠ ⎞ \n\