Esempio n. 1
0
def test_dim_simplify_dimless():
    assert dim_simplify(Mul(Pow(sin(Mul(L, Pow(L, -1))), 2), L)) == L
    assert dim_simplify(sin(L * L**(-1))**2 * L) == L
Esempio n. 2
0
def test_pretty_basic():
    assert pretty(-Rational(1) / 2) == '-1/2'
    assert pretty( -Rational(13)/22 ) == \
"""\
  13\n\
- --\n\
  22\
"""
    expr = oo
    ascii_str = \
"""\
oo\
"""
    ucode_str = \
u"""\
∞\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (x**2)
    ascii_str = \
"""\
 2\n\
x \
"""
    ucode_str = \
u"""\
 2\n\
x \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = 1 / x
    ascii_str = \
"""\
1\n\
-\n\
x\
"""
    ucode_str = \
u"""\
1\n\
─\n\
x\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = y * x**-2
    ascii_str = \
"""\
y \n\
--\n\
 2\n\
x \
"""
    ucode_str = \
u"""\
y \n\
──\n\
 2\n\
x \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = x**Rational(-5, 2)
    ascii_str = \
"""\
 1  \n\
----\n\
 5/2\n\
x   \
"""
    ucode_str = \
u"""\
 1  \n\
────\n\
 5/2\n\
x   \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (-2)**x
    ascii_str = \
"""\
    x\n\
(-2) \
"""
    ucode_str = \
u"""\
    x\n\
(-2) \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    # See issue 1824
    expr = Pow(3, 1, evaluate=False)
    ascii_str = \
"""\
 1\n\
3 \
"""
    ucode_str = \
u"""\
 1\n\
3 \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (x**2 + x + 1)
    ascii_str_1 = \
"""\
         2\n\
1 + x + x \
"""
    ascii_str_2 = \
"""\
 2        \n\
x  + x + 1\
"""
    ascii_str_3 = \
"""\
 2        \n\
x  + 1 + x\
"""
    ucode_str_1 = \
u"""\
         2\n\
1 + x + x \
"""
    ucode_str_2 = \
u"""\
 2        \n\
x  + x + 1\
"""
    ucode_str_3 = \
u"""\
 2        \n\
x  + 1 + x\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]

    expr = 1 - x
    ascii_str_1 = \
"""\
1 - x\
"""
    ascii_str_2 = \
"""\
-x + 1\
"""
    ucode_str_1 = \
u"""\
1 - x\
"""
    ucode_str_2 = \
u"""\
-x + 1\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]

    expr = 1 - 2 * x
    ascii_str_1 = \
"""\
1 - 2*x\
"""
    ascii_str_2 = \
"""\
-2*x + 1\
"""
    ucode_str_1 = \
u"""\
1 - 2⋅x\
"""
    ucode_str_2 = \
u"""\
-2⋅x + 1\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]

    expr = x / y
    ascii_str = \
"""\
x\n\
-\n\
y\
"""
    ucode_str = \
u"""\
x\n\
─\n\
y\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = -x / y
    ascii_str = \
"""\
-x\n\
--\n\
y \
"""
    ucode_str = \
u"""\
-x\n\
──\n\
y \
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = (x + 2) / y
    ascii_str_1 = \
"""\
2 + x\n\
-----\n\
  y  \
"""
    ascii_str_2 = \
"""\
x + 2\n\
-----\n\
  y  \
"""
    ucode_str_1 = \
u"""\
2 + x\n\
─────\n\
  y  \
"""
    ucode_str_2 = \
u"""\
x + 2\n\
─────\n\
  y  \
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]

    expr = (1 + x) * y
    ascii_str_1 = \
"""\
y*(1 + x)\
"""
    ascii_str_2 = \
"""\
(1 + x)*y\
"""
    ascii_str_3 = \
"""\
y*(x + 1)\
"""
    ucode_str_1 = \
u"""\
y⋅(1 + x)\
"""
    ucode_str_2 = \
u"""\
(1 + x)⋅y\
"""
    ucode_str_3 = \
u"""\
y⋅(x + 1)\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]

    # Test for correct placement of the negative sign
    expr = -5 * x / (x + 10)
    ascii_str_1 = \
"""\
 -5*x \n\
------\n\
10 + x\
"""
    ascii_str_2 = \
"""\
 -5*x \n\
------\n\
x + 10\
"""
    ucode_str_1 = \
u"""\
 -5⋅x \n\
──────\n\
10 + x\
"""
    ucode_str_2 = \
u"""\
 -5⋅x \n\
──────\n\
x + 10\
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]

    expr = -S(1) / 2 - 3 * x
    ascii_str = \
"""\
-3*x - 1/2\
"""
    ucode_str = \
u"""\
-3⋅x - 1/2\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = S(1) / 2 - 3 * x
    ascii_str = \
"""\
-3*x + 1/2\
"""
    ucode_str = \
u"""\
-3⋅x + 1/2\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = -S(1) / 2 - 3 * x / 2
    ascii_str = \
"""\
  3*x   1\n\
- --- - -\n\
   2    2\
"""
    ucode_str = \
u"""\
  3⋅x   1\n\
- ─── - ─\n\
   2    2\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = S(1) / 2 - 3 * x / 2
    ascii_str = \
"""\
  3*x   1\n\
- --- + -\n\
   2    2\
"""
    ucode_str = \
u"""\
  3⋅x   1\n\
- ─── + ─\n\
   2    2\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str
Esempio n. 3
0
def test_dim_simplify_pow():
    assert dim_simplify(Pow(L, 2)) == L.pow(2)
Esempio n. 4
0
def mason(graph: Graph, start: Node, end: Node) -> MasonResult:
    # mason = (sum(path[i] * delta[i])) / (delta)
    # delta = 1 - sum of all loops
    #         + sum of products of two loops
    #         - sum of products of three loops
    #         + sum of products of four loops
    #         ....
    # delta: determinante
    # paths[i]: forward path i
    # delta_per_path[i]: delta without loops that touch the forward path i

    result = MasonResult()

    delta = Integer(1)  # Initialize determinante with 1

    # Loops with their corresponding symbol
    loops: List[List[Branch]] = list()
    loop_symbols: List[Symbol] = list()

    # Create a sorted list of simple cycles
    simple_cycle_list = sorted(simple_cycles(graph),
                               key=lambda L: '%s' % (loop_to_expression(L), ))
    # Find loops and replace the branch copies with the original branch
    for loop_index, loop in enumerate(simple_cycle_list, start=0):
        new_loop = list()
        for loop_branch in loop:
            branch_iter = iter(graph.branches)
            existing_branch = next(branch_iter)
            while not existing_branch.id == loop_branch.id:
                existing_branch = next(branch_iter)

            new_loop.append(existing_branch)

        loops.append(new_loop)
        loop_symbols.append(Symbol("L" + str(loop_index + 1)))

    for i, loop in enumerate(loops):
        # Add to delta
        delta = Add(delta, Mul(Integer(-1), loop_symbols[i]))
        # Append to loops in result
        result.loops.append((loop_symbols[i], loop_to_expression(loops[i])))

    # Add or substract sum of product of two, three, ... loops
    loop_groups = sorted(find_loop_groups(loops), key=attrgetter('loop_count'))

    for loop_group in loop_groups:
        if loop_group.loop_count > 1:  # Skip loop groups with one member
            expr = Integer(1)

            i = 0
            while i < len(loop_group.loops):
                loop_index = loops.index(loop_group.loops[i])
                expr = Mul(expr, loop_symbols[loop_index])
                i += 1

            # Insert negative sign if necessary
            if loop_group.loop_count % 2 == 1:
                expr = Mul(Integer(-1), expr)

            delta = Add(delta, expr)

    # Summation of products of paths and its determinantes
    paths = find_paths(start, end)

    numerator: Expr = Integer(0)

    # Create a sorted list of paths
    path_list = sorted(paths, key=lambda L: '%s' % (loop_to_expression(L), ))
    for i, path in enumerate(path_list, start=1):
        # Create symbol and append to paths in result
        path_symbol = Symbol("P" + str(i))
        result.paths.append((path_symbol, loop_to_expression(path)))

        dpp_symbol = Symbol("D" + str(i))
        dpp = __get_delta_per_path(loops, loop_symbols, loop_groups, path)
        # Append to paths in result
        result.paths.append((dpp_symbol, dpp))
        # Add delta_per_path to sum
        numerator = Add(numerator, Mul(path_symbol, dpp_symbol))

    delta_symbol = Symbol("Delta")
    result.determinant = [(delta_symbol, delta)]

    numerator_symbol = Symbol("T_num")
    result.numerator = [(numerator_symbol, numerator)]

    denominator_symbol = Symbol("T_den")
    result.denominator = [(denominator_symbol, delta_symbol)]

    transfer_function_symbol = Symbol("T")
    transfer_function = Mul(numerator_symbol,
                            Pow(denominator_symbol, Integer(-1)))  # Division
    result.transfer_function = [(transfer_function_symbol, transfer_function)]

    return result
Esempio n. 5
0
def test_nested_substitution():
    # Substitution within a substitution.
    e = Add(Pow(w * x + y, 2), sqrt(w * x + y))
    substs, reduced = cse([e])
    assert substs == [(x0, w * x + y)]
    assert reduced == [sqrt(x0) + x0**2]
Esempio n. 6
0
def inv(a):
    return Pow(a, -1)
Esempio n. 7
0
def test_issue_3512a():
    assert Mul.flatten([3**Rational(1, 3),
        Pow(-Rational(1, 9), Rational(2, 3), evaluate=False)]) == \
        ([Rational(1, 3), (-1)**Rational(2, 3)], [], None)
Esempio n. 8
0
def test_variable_percentage():
    assert_equal(
        "\\variable{x}\\%",
        Mul(Symbol('x' + hashlib.md5('x'.encode()).hexdigest(), real=True),
            Pow(100, -1, evaluate=False),
            evaluate=False))
Esempio n. 9
0
 def __rdiv__(self, other):
     return MatSymbolicMul(other, Pow(self, S.NegativeOne))
Esempio n. 10
0
    def redlich_kister_sum(self, phase, param_search, param_query):
        """
        Construct parameter in Redlich-Kister polynomial basis, using
        the Muggianu ternary parameter extension.
        """
        rk_terms = []

        # search for desired parameters
        params = param_search(param_query)
        for param in params:
            # iterate over every sublattice
            mixing_term = S.One
            for subl_index, comps in enumerate(param['constituent_array']):
                comp_symbols = None
                # convert strings to symbols
                if comps[0] == '*':
                    # Handle wildcards in constituent array
                    comp_symbols = \
                        [
                            v.SiteFraction(phase.name, subl_index, comp)
                            for comp in set(phase.constituents[subl_index])\
                                .intersection(self.components)
                        ]
                    mixing_term *= Add(*comp_symbols)
                else:
                    comp_symbols = \
                        [
                            v.SiteFraction(phase.name, subl_index, comp)
                            for comp in comps
                        ]
                    mixing_term *= Mul(*comp_symbols)
                # is this a higher-order interaction parameter?
                if len(comps) == 2 and param['parameter_order'] > 0:
                    # interacting sublattice, add the interaction polynomial
                    mixing_term *= Pow(comp_symbols[0] - \
                        comp_symbols[1], param['parameter_order'])
                if len(comps) == 3:
                    # 'parameter_order' is an index to a variable when
                    # we are in the ternary interaction parameter case

                    # NOTE: The commercial software packages seem to have
                    # a "feature" where, if only the zeroth
                    # parameter_order term of a ternary parameter is specified,
                    # the other two terms are automatically generated in order
                    # to make the parameter symmetric.
                    # In other words, specifying only this parameter:
                    # PARAMETER G(FCC_A1,AL,CR,NI;0) 298.15  +30300; 6000 N !
                    # Actually implies:
                    # PARAMETER G(FCC_A1,AL,CR,NI;0) 298.15  +30300; 6000 N !
                    # PARAMETER G(FCC_A1,AL,CR,NI;1) 298.15  +30300; 6000 N !
                    # PARAMETER G(FCC_A1,AL,CR,NI;2) 298.15  +30300; 6000 N !
                    #
                    # If either 1 or 2 is specified, no implicit parameters are
                    # generated.
                    # We need to handle this case.
                    if param['parameter_order'] == 0:
                        # are _any_ of the other parameter_orders specified?
                        ternary_param_query = (
                            (where('phase_name') == param['phase_name']) & \
                            (where('parameter_type') == \
                                param['parameter_type']) & \
                            (where('constituent_array') == \
                                param['constituent_array'])
                        )
                        other_tern_params = param_search(ternary_param_query)
                        if len(other_tern_params) == 1 and \
                            other_tern_params[0] == param:
                            # only the current parameter is specified
                            # We need to generate the other two parameters.
                            order_one = copy.deepcopy(param)
                            order_one['parameter_order'] = 1
                            order_two = copy.deepcopy(param)
                            order_two['parameter_order'] = 2
                            # Add these parameters to our iteration.
                            params.extend((order_one, order_two))
                    # Include variable indicated by parameter order index
                    # Perform Muggianu adjustment to site fractions
                    mixing_term *= comp_symbols[param['parameter_order']].subs(
                        self._Muggianu_correction_dict(comp_symbols),
                        simultaneous=True)
            rk_terms.append(mixing_term * param['parameter'])
        return Add(*rk_terms)
Esempio n. 11
0
def my_division(a, b):
    return Mul(x, Pow(y, -1))
Esempio n. 12
0
def test_dim_simplify_pow():
    assert Pow(L, 2) == L**2
Esempio n. 13
0
    'CNOT',
    'SWAP',
    'H',
    'X',
    'Y',
    'Z',
    'T',
    'S',
    'Phase',
    'normalized',
    'gate_sort',
    'gate_simp',
    'random_circuit',
]

sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False)

#-----------------------------------------------------------------------------
# Gate Super-Classes
#-----------------------------------------------------------------------------

_normalized = True


def normalized(normalize):
    """Should Hadamard gates be normalized by a 1/sqrt(2).

    This is a global setting that can be used to simplify the look of various
    expressions, by leaving of the leading 1/sqrt(2) of the Hadamard gate.

    Parameters
Esempio n. 14
0
def test_qsimplify_pow():
    assert qsimplify(Pow(q1, 2)) == q1.pow(2)
Esempio n. 15
0
def _Pow(a, b):
    return Pow(a, b, evaluate=False)
Esempio n. 16
0
def test_ops():
    k0 = Ket(0)
    k1 = Ket(1)
    k = 2 * I * k0 - (x / sqrt(2)) * k1
    assert k == Add(Mul(2, I, k0),
                    Mul(Rational(-1, 2), x, Pow(2, Rational(1, 2)), k1))
Esempio n. 17
0
def div(a, b):
    return Mul(a, Pow(b, -1))
Esempio n. 18
0
def GeneralizedMultivariateLogGammaOmega(syms, omega, v, lamda, mu):
    """
    Extends GeneralizedMultivariateLogGamma.

    Parameters
    ==========

    syms: list/tuple/set of symbols for identifying each component
    omega: A square matrix
           Every element of square matrix must be absolute value of
           sqaure root of correlation coefficient
    v: positive real
    lamda: a list of positive reals
    mu: a list of positive reals

    Returns
    =======

    A Random Symbol

    Examples
    ========

    >>> from sympy.stats import density
    >>> from sympy.stats.joint_rv import marginal_distribution
    >>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega
    >>> from sympy import Matrix, symbols, S
    >>> omega = Matrix([[1, S.Half, S.Half], [S.Half, 1, S.Half], [S.Half, S.Half, 1]])
    >>> v = 1
    >>> l, mu = [1, 1, 1], [1, 1, 1]
    >>> G = GeneralizedMultivariateLogGammaOmega('G', omega, v, l, mu)
    >>> y = symbols('y_1:4', positive=True)
    >>> density(G)(y[0], y[1], y[2])
    sqrt(2)*Sum((1 - sqrt(2)/2)**n*exp((n + 1)*(y_1 + y_2 + y_3) - exp(y_1) -
    exp(y_2) - exp(y_3))/gamma(n + 1)**3, (n, 0, oo))/2

    References
    ==========

    See references of GeneralizedMultivariateLogGamma.

    Notes
    =====

    If the GeneralizedMultivariateLogGammaOmega is too long to type use,
    `from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega as GMVLGO`
    """
    _value_check((omega.is_square, isinstance(omega, Matrix)),
                 "omega must be a"
                 " square matrix")
    for val in omega.values():
        _value_check(
            (val >= 0, val <= 1),
            "all values in matrix must be between 0 and 1(both inclusive).")
    _value_check(omega.diagonal().equals(ones(1, omega.shape[0])),
                 "all the elements of diagonal should be 1.")
    _value_check((omega.shape[0] == len(lamda), len(lamda) == len(mu)),
                 "lamda, mu should be of same length and omega should "
                 " be of shape (length of lamda, length of mu)")
    _value_check(
        len(lamda) > 1, "the distribution should have at least"
        " two random variables.")
    delta = Pow(Rational(omega.det()), Rational(1, len(lamda) - 1))
    return GeneralizedMultivariateLogGamma(syms, delta, v, lamda, mu)
Esempio n. 19
0
def test_issue_2941():
    a, b = Pow(1, 2, evaluate=False), S.One
    assert a != b
    assert b != a
    assert not (a == b)
    assert not (b == a)
Esempio n. 20
0
def test_evaluate_false():
    for no in [0, False]:
        assert Add(3, 2, evaluate=no).is_Add
        assert Mul(3, 2, evaluate=no).is_Mul
        assert Pow(3, 2, evaluate=no).is_Pow
    assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0
Esempio n. 21
0
def test_powers_Integer():
    """Test Integer._eval_power"""
    # check infinity
    assert S(1)**S.Infinity == 1
    assert S(-1)**S.Infinity == S.NaN
    assert S(2)**S.Infinity == S.Infinity
    assert S(-2)**S.Infinity == S.Infinity + S.Infinity * S.ImaginaryUnit
    assert S(0)**S.Infinity == 0

    # check Nan
    assert S(1)**S.NaN == S.One
    assert S(-1)**S.NaN == S.NaN

    # check for exact roots
    assert S(-1)**Rational(6, 5) == -(-1)**(S(1) / 5)
    assert sqrt(S(4)) == 2
    assert sqrt(S(-4)) == I * 2
    assert S(16)**Rational(1, 4) == 2
    assert S(-16)**Rational(1, 4) == 2 * (-1)**Rational(1, 4)
    assert S(9)**Rational(3, 2) == 27
    assert S(-9)**Rational(3, 2) == -27 * I
    assert S(27)**Rational(2, 3) == 9
    assert S(-27)**Rational(2, 3) == 9 * (S(-1)**Rational(2, 3))
    assert (-2)**Rational(-2, 1) == Rational(1, 4)

    # not exact roots
    assert sqrt(-3) == I * sqrt(3)
    assert (3)**(S(3) / 2) == 3 * sqrt(3)
    assert (-3)**(S(3) / 2) == -3 * sqrt(-3)
    assert (-3)**(S(5) / 2) == 9 * I * sqrt(3)
    assert (-3)**(S(7) / 2) == -I * 27 * sqrt(3)
    assert (2)**(S(3) / 2) == 2 * sqrt(2)
    assert (2)**(S(-3) / 2) == sqrt(2) / 4
    assert (81)**(S(2) / 3) == 9 * (S(3)**(S(2) / 3))
    assert (-81)**(S(2) / 3) == 9 * (S(-3)**(S(2) / 3))
    assert (-3)**Rational(-7,
                          3) == -(-1)**Rational(2, 3) * 3**Rational(2, 3) / 27
    assert (-3)**Rational(-2,
                          3) == -(-1)**Rational(1, 3) * 3**Rational(1, 3) / 3

    # join roots
    assert sqrt(6) + sqrt(24) == 3 * sqrt(6)
    assert sqrt(2) * sqrt(3) == sqrt(6)

    # separate symbols & constansts
    x = Symbol("x")
    assert sqrt(49 * x) == 7 * sqrt(x)
    assert sqrt((3 - sqrt(pi))**2) == 3 - sqrt(pi)

    # check that it is fast for big numbers
    assert (2**64 + 1)**Rational(4, 3)
    assert (2**64 + 1)**Rational(17, 25)

    # negative rational power and negative base
    assert (-3)**Rational(-7,
                          3) == -(-1)**Rational(2, 3) * 3**Rational(2, 3) / 27
    assert (-3)**Rational(-2,
                          3) == -(-1)**Rational(1, 3) * 3**Rational(1, 3) / 3

    assert S(1234).factors() == {617: 1, 2: 1}
    assert Rational(2 * 3, 3 * 5 * 7).factors() == {2: 1, 5: -1, 7: -1}

    # test that eval_power factors numbers bigger than limit (2**15)
    from sympy import nextprime
    n = nextprime(
        2**15)  # bigger than the current limit in factor_trial_division
    assert sqrt(n**2) == n
    assert sqrt(n**3) == n * sqrt(n)
    assert sqrt(4 * n) == 2 * sqrt(n)

    # check that factors of base with powers sharing gcd with power are removed
    assert (2**4 * 3)**Rational(1, 6) == 2**Rational(2, 3) * 3**Rational(1, 6)
    assert (2**4 * 3)**Rational(
        5, 6) == 8 * 2**Rational(1, 3) * 3**Rational(5, 6)

    # check that bases sharing a gcd are exptracted
    assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \
           2**Rational(8, 15)*3**Rational(9, 20)
    assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \
           4*2**Rational(7, 10)*3**Rational(8, 15)
    assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \
           4*(-3)**Rational(8, 15)*2**Rational(7, 10)
    assert 2**Rational(1, 3) * 2**Rational(8, 9) == 2 * 2**Rational(2, 9)
    assert 2**Rational(2, 3) * 6**Rational(1, 3) == 2 * 3**Rational(1, 3)
    assert 2**Rational(2, 3) * 6**Rational(8, 9) == 2 * 2**Rational(
        5, 9) * 3**Rational(8, 9)
    assert (-2)**Rational(2, S(3)) * (-4)**Rational(
        1, S(3)) == -2 * 2**Rational(1, 3)
    assert 3 * Pow(3, 2, evaluate=False) == 3**3
    assert 3 * Pow(3, -1 / S(3), evaluate=False) == 3**(2 / S(3))
    assert (-2)**(1/S(3))*(-3)**(1/S(4))*(-5)**(5/S(6)) == \
           -(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4)*5**Rational(5, 6)

    assert Integer(-2)**Symbol('', even=True) == Integer(2)**Symbol('',
                                                                    even=True)
    assert (-1)**Float(.5) == 1.0 * I
Esempio n. 22
0
def test_chop_value():
    for i in range(-27, 28):
        assert (Pow(10, i) *
                2).n(chop=10**i) and not (Pow(10, i)).n(chop=10**i)
Esempio n. 23
0
def test_cse_single():
    # Simple substitution.
    e = Add(Pow(x + y, 2), sqrt(x + y))
    substs, reduced = cse([e])
    assert substs == [(x0, x + y)]
    assert reduced == [sqrt(x0) + x0**2]
Esempio n. 24
0
def test_cse_single2():
    # Simple substitution, test for being able to pass the expression directly
    e = Add(Pow(x + y, 2), sqrt(x + y))
    substs, reduced = cse(e, optimizations=[])
    assert substs == [(x0, x + y)]
    assert reduced == [sqrt(x0) + x0**2]
Esempio n. 25
0
class TestAllGood(object):
    # These latex strings should parse to the corresponding SymPy expression
    GOOD_PAIRS = [
        ("0", 0),
        ("1", 1),
        ("-3.14", -3.14),
        ("5-3", _Add(5, -3)),
        ("(-7.13)(1.5)", _Mul(Rational('-7.13'), Rational('1.5'))),
        ("\\left(-7.13\\right)\\left(1.5\\right)", _Mul(Rational('-7.13'), Rational('1.5'))),
        ("x", x),
        ("2x", 2 * x),
        ("x^2", x**2),
        ("x^{3 + 1}", x**_Add(3, 1)),
        ("x^{\\left\\{3 + 1\\right\\}}", x**_Add(3, 1)),
        ("-3y + 2x", _Add(_Mul(2, x), Mul(-1, 3, y, evaluate=False))),
        ("-c", -c),
        ("a \\cdot b", a * b),
        ("a / b", a / b),
        ("a \\div b", a / b),
        ("a + b", a + b),
        ("a + b - a", Add(a, b, _Mul(-1, a), evaluate=False)),
        ("a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)),
        ("a^2 + b^2 != 2c^2", Ne(a**2 + b**2, 2 * c**2)),
        ("a\\mod b", Mod(a, b)),
        ("\\sin \\theta", sin(theta)),
        ("\\sin(\\theta)", sin(theta)),
        ("\\sin\\left(\\theta\\right)", sin(theta)),
        ("\\sin^{-1} a", asin(a)),
        ("\\sin a \\cos b", _Mul(sin(a), cos(b))),
        ("\\sin \\cos \\theta", sin(cos(theta))),
        ("\\sin(\\cos \\theta)", sin(cos(theta))),
        ("\\arcsin(a)", asin(a)),
        ("\\arccos(a)", acos(a)),
        ("\\arctan(a)", atan(a)),
        ("\\sinh(a)", sinh(a)),
        ("\\cosh(a)", cosh(a)),
        ("\\tanh(a)", tanh(a)),
        ("\\sinh^{-1}(a)", asinh(a)),
        ("\\cosh^{-1}(a)", acosh(a)),
        ("\\tanh^{-1}(a)", atanh(a)),
        ("\\arcsinh(a)", asinh(a)),
        ("\\arccosh(a)", acosh(a)),
        ("\\arctanh(a)", atanh(a)),
        ("\\arsinh(a)", asinh(a)),
        ("\\arcosh(a)", acosh(a)),
        ("\\artanh(a)", atanh(a)),
        ("\\operatorname{arcsinh}(a)", asinh(a)),
        ("\\operatorname{arccosh}(a)", acosh(a)),
        ("\\operatorname{arctanh}(a)", atanh(a)),
        ("\\operatorname{arsinh}(a)", asinh(a)),
        ("\\operatorname{arcosh}(a)", acosh(a)),
        ("\\operatorname{artanh}(a)", atanh(a)),
        ("\\cos^2(x)", cos(x)**2),
        ("\\cos(x)^2", cos(x)**2),
        ("\\frac{a}{b}", a / b),
        ("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
        ("\\frac{7}{3}", _Mul(7, _Pow(3, -1))),
        ("(\\csc x)(\\sec y)", csc(x) * sec(y)),
        ("\\lim_{x \\to 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')),
        ("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')),
        ("\\infty", oo),
        ("\\infty\\%", oo),
        ("\\$\\infty", oo),
        ("-\\infty", -oo),
        ("-\\infty\\%", -oo),
        ("-\\$\\infty", -oo),
        ("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Mul(1, _Pow(x, -1)), x, oo)),
        ("\\frac{d}{dx} x", Derivative(x, x)),
        ("\\frac{d}{dt} x", Derivative(x, t)),
        # ("f(x)", f(x)),
        # ("f(x, y)", f(x, y)),
        # ("f(x, y, z)", f(x, y, z)),
        # ("\\frac{d f(x)}{dx}", Derivative(f(x), x)),
        # ("\\frac{d\\theta(x)}{dx}", Derivative(theta(x), x)),
        ("|x|", _Abs(x)),
        ("\\left|x\\right|", _Abs(x)),
        ("||x||", _Abs(Abs(x))),
        ("|x||y|", _Abs(x) * _Abs(y)),
        ("||x||y||", _Abs(_Abs(x) * _Abs(y))),
        ("\\pi^{|xy|}", pi**_Abs(x * y)),
        ("\\frac{\\pi}{3}", _Mul(pi, _Pow(3, -1))),
        ("\\sin{\\frac{\\pi}{2}}", sin(_Mul(pi, _Pow(2, -1)), evaluate=False)),
        ("a+bI", a + I * b),
        ("e^{I\\pi}", -1),
        ("\\int x dx", Integral(x, x)),
        ("\\int x d\\theta", Integral(x, theta)),
        ("\\int (x^2 - y)dx", Integral(x**2 - y, x)),
        ("\\int x + a dx", Integral(_Add(x, a), x)),
        ("\\int da", Integral(1, a)),
        ("\\int_0^7 dx", Integral(1, (x, 0, 7))),
        ("\\int_a^b x dx", Integral(x, (x, a, b))),
        ("\\int^b_a x dx", Integral(x, (x, a, b))),
        ("\\int_{a}^b x dx", Integral(x, (x, a, b))),
        ("\\int^{b}_a x dx", Integral(x, (x, a, b))),
        ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))),
        ("\\int_{  }^{}x dx", Integral(x, x)),
        ("\\int^{  }_{ }x dx", Integral(x, x)),
        ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))),
        # ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
        ("\\int (x+a)", Integral(_Add(x, a), x)),
        ("\\int a + b + c dx", Integral(Add(a, b, c, evaluate=False), x)),
        ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)),
        ("\\int \\frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)),
        ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)),
        ("\\int \\frac{1}{a} + \\frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
        ("\\int \\frac{3 \\cdot d\\theta}{\\theta}", Integral(3 * _Pow(theta, -1), theta)),
        ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
        ("x_0", Symbol('x_{0}', real=True)),
        ("x_{1}", Symbol('x_{1}', real=True)),
        ("x_a", Symbol('x_{a}', real=True)),
        ("x_{b}", Symbol('x_{b}', real=True)),
        ("h_\\theta", Symbol('h_{theta}', real=True)),
        ("h_{\\theta}", Symbol('h_{theta}', real=True)),
        # ("h_{\\theta}(x_0, x_1)", Symbol('h_{theta}', real=True)(Symbol('x_{0}', real=True), Symbol('x_{1}', real=True))),
        ("x!", _factorial(x)),
        ("100!", _factorial(100)),
        ("\\theta!", _factorial(theta)),
        ("(x + 1)!", _factorial(_Add(x, 1))),
        ("\\left(x + 1\\right)!", _factorial(_Add(x, 1))),
        ("(x!)!", _factorial(_factorial(x))),
        ("x!!!", _factorial(_factorial(_factorial(x)))),
        ("5!7!", _Mul(_factorial(5), _factorial(7))),
        ("\\sqrt{x}", sqrt(x)),
        ("\\sqrt{x + b}", sqrt(_Add(x, b))),
        ("\\sqrt[3]{\\sin x}", root(sin(x), 3)),
        ("\\sqrt[y]{\\sin x}", root(sin(x), y)),
        ("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)),
        ("x < y", StrictLessThan(x, y)),
        ("x \\leq y", LessThan(x, y)),
        ("x > y", StrictGreaterThan(x, y)),
        ("x \\geq y", GreaterThan(x, y)),
        ("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
        ("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
        ("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
        ("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
        ("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
        ("\\sum_{n = 0}^{\\infty} \\frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))),
        ("\\prod_{a = b}^{c} x", Product(x, (a, b, c))),
        ("\\prod_{a = b}^c x", Product(x, (a, b, c))),
        ("\\prod^{c}_{a = b} x", Product(x, (a, b, c))),
        ("\\prod^c_{a = b} x", Product(x, (a, b, c))),
        ("\\ln x", _log(x, E)),
        ("\\ln xy", _log(x * y, E)),
        ("\\log x", _log(x, 10)),
        ("\\log xy", _log(x * y, 10)),
        # ("\\log_2 x", _log(x, 2)),
        ("\\log_{2} x", _log(x, 2)),
        # ("\\log_a x", _log(x, a)),
        ("\\log_{a} x", _log(x, a)),
        ("\\log_{11} x", _log(x, 11)),
        ("\\log_{a^2} x", _log(x, _Pow(a, 2))),
        ("[x]", x),
        ("[a + b]", _Add(a, b)),
        ("\\frac{d}{dx} [ \\tan x ]", Derivative(tan(x), x)),
        ("2\\overline{x}", 2 * Symbol('xbar', real=True)),
        ("2\\overline{x}_n", 2 * Symbol('xbar_{n}', real=True)),
        ("\\frac{x}{\\overline{x}_n}", x / Symbol('xbar_{n}', real=True)),
        ("\\frac{\\sin(x)}{\\overline{x}_n}", sin(Symbol('x', real=True)) / Symbol('xbar_{n}', real=True)),
        ("2\\bar{x}", 2 * Symbol('xbar', real=True)),
        ("2\\bar{x}_n", 2 * Symbol('xbar_{n}', real=True)),
        ("\\sin\\left(\\theta\\right) \\cdot4", sin(theta) * 4),
        ("\\ln\\left(\\theta\\right)", _log(theta, E)),
        ("\\ln\\left(x-\\theta\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left(x-\\theta\\right)\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left[x-\\theta\\right]\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left\\{x-\\theta\\right\\}\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left|x-\\theta\\right|\\right)", _log(_Abs(x - theta), E)),
        ("\\frac{1}{2}xy(x+y)", Mul(_Pow(2, -1), x, y, (x + y), evaluate=False)),
        ("\\frac{1}{2}\\theta(x+y)", Mul(_Pow(2, -1), theta, (x + y), evaluate=False)),
        ("1-f(x)", 1 - f * x),

        ("\\begin{matrix}1&2\\\\3&4\\end{matrix}", Matrix([[1, 2], [3, 4]])),
        ("\\begin{matrix}x&x^2\\\\\\sqrt{x}&x\\end{matrix}", Matrix([[x, x**2], [_Pow(x, S.Half), x]])),
        ("\\begin{matrix}\\sqrt{x}\\\\\\sin(\\theta)\\end{matrix}", Matrix([_Pow(x, S.Half), sin(theta)])),
        ("\\begin{pmatrix}1&2\\\\3&4\\end{pmatrix}", Matrix([[1, 2], [3, 4]])),
        ("\\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}", Matrix([[1, 2], [3, 4]])),

        # scientific notation
        ("2.5\\times 10^2", 250),
        ("1,500\\times 10^{-1}", 150),

        # e notation
        ("2.5E2", 250),
        ("1,500E-1", 150),

        # multiplication without cmd
        ("2x2y", Mul(2, x, 2, y, evaluate=False)),
        ("2x2", Mul(2, x, 2, evaluate=False)),
        ("x2", x * 2),

        # lin alg processing
        ("\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(theta, Matrix([[1, 2], [3, 4]]), evaluate=False)),
        ("\\theta\\begin{matrix}1\\\\3\\end{matrix} - \\begin{matrix}-1\\\\2\\end{matrix}", MatAdd(MatMul(theta, Matrix([[1], [3]]), evaluate=False), MatMul(-1, Matrix([[-1], [2]]), evaluate=False), evaluate=False)),
        ("\\theta\\begin{matrix}1&0\\\\0&1\\end{matrix}*\\begin{matrix}3\\\\-2\\end{matrix}", MatMul(theta, Matrix([[1, 0], [0, 1]]), Matrix([3, -2]), evaluate=False)),
        ("\\frac{1}{9}\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(Pow(9, -1, evaluate=False), theta, Matrix([[1, 2], [3, 4]]), evaluate=False)),
        ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix};\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix},\\begin{pmatrix}1\\\\1\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1]), Matrix([1, 1, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right\\}", Matrix([1, 2, 3])),
        ("\\left{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right}", Matrix([1, 2, 3])),
        ("{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}}", Matrix([1, 2, 3])),

        # us dollars
        ("\\$1,000.00", 1000),
        ("\\$543.21", 543.21),
        ("\\$0.009", 0.009),

        # percentages
        ("100\\%", 1),
        ("1.5\\%", 0.015),
        ("0.05\\%", 0.0005),

        # empty set
        ("\\emptyset", S.EmptySet)
    ]

    def test_good_pair(self, s, eq):
        assert_equal(s, eq)
	# q is between a and b: cr(a,q,b,c) = cr(A,Q,B,C) = (AB/QB)/(AC/QC)
	if q_left:
		ab = np.linalg.linalg.norm(a-b)
		qb = np.linalg.linalg.norm(q-b)
		ac = np.linalg.linalg.norm(a-c) 
		qc = np.linalg.linalg.norm(q-c)
		cross_ratio = ((ab)/(qb))/((ac)/(qc))
		AB = np.linalg.norm(A-B)
		AC = np.linalg.norm(A-C)
		BC = AC-AB
		# use cross ratio + geometry
		QB = sym.symbols('QB',real=True)
		QB = sym.solve((AB/QB)/(AC/(BC+QB))-cross_ratio, QB)[0] # cross
		QC = BC + QB # geometric relationship: BC + QB = QC 
		Qx, Qy = sym.symbols('Qx, Qy')
		sol = sym.solve((sqrt(Pow(Qx - B[0],2) + Pow(Qy - B[1],2))-QB,sqrt(Pow(Qx - C[0],2) + Pow(Qy - C[1],2))-QC),(Qx,Qy))
	else: # cr(a,b,q,c) = cr(A,B,Q,C) = (AQ/BQ)*(AC/BC)
		# q is between b and c... flip the problem (swap a and c from above condition)
		aq = np.linalg.linalg.norm(q-a)
		qb = np.linalg.linalg.norm(q-b)
		ac = np.linalg.linalg.norm(a-c) 
		bc = np.linalg.linalg.norm(b-c) 

		cross_ratio = ((aq)/(qb))/((ac)/(bc))
		AC = np.linalg.norm(A-C)
		CB = np.linalg.norm(C-B)
		AB = AC-CB
		# use cross ratio + geometry
		QB = sym.symbols('QB',real=True)
		QB = sym.solve(((AB+QB)/QB)/(AC/CB)-cross_ratio, QB)[0] # cross
		QA = AB + QB # geometric relationship: BC + QB = QC 
Esempio n. 27
0
def test_big_expr():
    f = Function('f')
    x = symbols('x')
    e1 = Dagger(AntiCommutator(Operator('A') + Operator('B'), Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3))*TensorProduct(Jz**2, Operator('A') + Operator('B')))*(JzBra(1, 0) + JzBra(1, 1))*(JzKet(0, 0) + JzKet(1, -1))
    e2 = Commutator(Jz**2, Operator('A') + Operator('B'))*AntiCommutator(Dagger(Operator('C')*Operator('D')), Operator('E').inv()**2)*Dagger(Commutator(Jz, J2))
    e3 = Wigner3j(1, 2, 3, 4, 5, 6)*TensorProduct(Commutator(Operator('A') + Dagger(Operator('B')), Operator('C') + Operator('D')), Jz - J2)*Dagger(OuterProduct(Dagger(JzBra(1, 1)), JzBra(1, 0)))*TensorProduct(JzKetCoupled(1, 1, (1, 1)) + JzKetCoupled(1, 0, (1, 1)), JzKetCoupled(1, -1, (1, 1)))
    e4 = (ComplexSpace(1)*ComplexSpace(2) + FockSpace()**2)*(L2(Interval(
        0, oo)) + HilbertSpace())
    assert str(e1) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)'
    ascii_str = \
"""\
                 /                                      3        \\                                 \n\
                 |/                                   +\\         |                                 \n\
    2  / +    +\\ <|                    /d            \\ |   +    +>                                 \n\
/J \\ x \\A  + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A  + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\
\\ z/             \\\\                    \dx           / /         /                                 \
"""
    ucode_str = \
u"""\
                 ⎧                                      3        ⎫                                 \n\
                 ⎪⎛                                   †⎞         ⎪                                 \n\
    2  ⎛ †    †⎞ ⎨⎜                    ⎛d            ⎞ ⎟   †    †⎬                                 \n\
⎛J ⎞ ⨂ ⎝A  + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A  + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\
⎝ z⎠             ⎩⎝                    ⎝dx           ⎠ ⎠         ⎭                                 \
"""
    assert pretty(e1) == ascii_str
    assert upretty(e1) == ucode_str
    assert latex(e1) == \
        r'{\left(J_z\right)^{2}}\otimes \left({A^{\dag} + B^{\dag}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left (x \right )},f{\left (x \right )}\right)^{\dag}\right)^{3},A^{\dag} + B^{\dag}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)'
    sT(e1, "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Symbol('x')),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))")
    assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]'
    ascii_str = \
"""\
[    2      ] / -2  +  +\\ [ 2   ]\n\
[/J \\ ,A + B]*<E  ,D *C >*[J ,J ]\n\
[\\ z/       ] \\         / [    z]\
"""
    ucode_str = \
u"""\
⎡    2      ⎤ ⎧ -2  †  †⎫ ⎡ 2   ⎤\n\
⎢⎛J ⎞ ,A + B⎥⋅⎨E  ,D ⋅C ⎬⋅⎢J ,J ⎥\n\
⎣⎝ z⎠       ⎦ ⎩         ⎭ ⎣    z⎦\
"""
    assert pretty(e2) == ascii_str
    assert upretty(e2) == ucode_str
    assert latex(e2) == \
        r'\left[\left(J_z\right)^{2},A + B\right] \left\{\left(E\right)^{-2},D^{\dag} C^{\dag}\right\} \left[J^2,J_z\right]'
    sT(e2, "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))")
    assert str(e3) == \
        "Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>"
    ascii_str = \
"""\
          [ +          ]  /   2     \\                                                                 \n\
/1  3  5\\*[B  + A,C + D]x |- J  + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\
|       |                 \\        z/                                                                 \n\
\\2  4  6/                                                                                             \
"""
    ucode_str = \
u"""\
          ⎡ †          ⎤  ⎛   2     ⎞                                                                 \n\
⎛1  3  5⎞⋅⎣B  + A,C + D⎦⨂ ⎜- J  + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\
⎜       ⎟                 ⎝        z⎠                                                                 \n\
⎝2  4  6⎠                                                                                             \
"""
    assert pretty(e3) == ascii_str
    assert upretty(e3) == ucode_str
    assert latex(e3) == \
        r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dag} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}'
    sT(e3, "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))")
    assert str(e4) == '(C(1)*C(2)+F**2)*(L2([0, oo))+H)'
    ascii_str = \
"""\
// 1    2\\    x2\\   / 2    \\\n\
\\\\C  x C / + F  / x \L  + H/\
"""
    ucode_str = \
u"""\
⎛⎛ 1    2⎞    ⨂2⎞   ⎛ 2    ⎞\n\
⎝⎝C  ⨂ C ⎠ ⊕ F  ⎠ ⨂ ⎝L  ⊕ H⎠\
"""
    assert pretty(e4) == ascii_str
    assert upretty(e4) == ucode_str
    assert latex(e4) == \
        r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)'
    sT(e4, "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, False, True)),HilbertSpace())))")
Esempio n. 28
0
 ("\\int x dx", Integral(x, x)),
 ("\\int x d\\theta", Integral(x, theta)),
 ("\\int (x^2 - y)dx", Integral(x**2 - y, x)),
 ("\\int x + a dx", Integral(_Add(x, a), x)),
 ("\\int da", Integral(1, a)),
 ("\\int_0^7 dx", Integral(1, (x, 0, 7))),
 ("\\int_a^b x dx", Integral(x, (x, a, b))),
 ("\\int^b_a x dx", Integral(x, (x, a, b))),
 ("\\int_{a}^b x dx", Integral(x, (x, a, b))),
 ("\\int^{b}_a x dx", Integral(x, (x, a, b))),
 ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))),
 ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))),
 ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
 ("\\int (x+a)", Integral(_Add(x, a), x)),
 ("\\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)),
 ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)),
 ("\\int \\frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)),
 ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)),
 ("\\int \\frac{1}{a} + \\frac{1}{b} dx",
  Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
 ("\\int \\frac{3 \\cdot d\\theta}{\\theta}",
  Integral(3 * _Pow(theta, -1), theta)),
 ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
 ("x_0", Symbol('x_{0}')),
 ("x_{1}", Symbol('x_{1}')),
 ("x_a", Symbol('x_{a}')),
 ("x_{b}", Symbol('x_{b}')),
 ("h_\\theta", Symbol('h_{theta}')),
 ("h_{\\theta}", Symbol('h_{theta}')),
 ("h_{\\theta}(x_0, x_1)", Function('h_{theta}')(Symbol('x_{0}'),
                                                 Symbol('x_{1}'))),
Esempio n. 29
0
def test_dim_simplify_dimless():
    assert dim_simplify(Mul(Pow(sin(Mul(L, Pow(L, -1))), 2), L)) == L
Esempio n. 30
0
def test_complex():
    a = Symbol("a", real=True)
    b = Symbol("b", real=True)
    e = (a + I * b) * (a - I * b)
    assert e.expand() == a**2 + b**2
    assert sqrt(I) == Pow(I, S.Half)