Python sympy.Pow() Examples

The following are 30 code examples of sympy.Pow(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sympy , or try the search function .
Example #1
Source File: process_latex.py    From latex2sympy with MIT License 6 votes vote down vote up
def convert_exp(exp):
    if hasattr(exp, 'exp'):
        exp_nested = exp.exp()
    else:
        exp_nested = exp.exp_nofunc()

    if exp_nested:
        base = convert_exp(exp_nested)
        if isinstance(base, list):
            raise Exception("Cannot raise derivative to power")
        if exp.atom():
            exponent = convert_atom(exp.atom())
        elif exp.expr():
            exponent = convert_expr(exp.expr())
        return sympy.Pow(base, exponent, evaluate=False)
    else:
        if hasattr(exp, 'comp'):
            return convert_comp(exp.comp())
        else:
            return convert_comp(exp.comp_nofunc()) 
Example #2
Source File: process_latex.py    From latex2sympy with MIT License 6 votes vote down vote up
def convert_mp(mp):
    if hasattr(mp, 'mp'):
        mp_left = mp.mp(0)
        mp_right = mp.mp(1)
    else:
        mp_left = mp.mp_nofunc(0)
        mp_right = mp.mp_nofunc(1)

    if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
        lh = convert_mp(mp_left)
        rh = convert_mp(mp_right)
        return sympy.Mul(lh, rh, evaluate=False)
    elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
        lh = convert_mp(mp_left)
        rh = convert_mp(mp_right)
        return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
    else:
        if hasattr(mp, 'unary'):
            return convert_unary(mp.unary())
        else:
            return convert_unary(mp.unary_nofunc()) 
Example #3
Source File: test_differentiable.py    From devito with MIT License 6 votes vote down vote up
def test_differentiable():
    a = Function(name="a", grid=Grid((10, 10)))
    e = Function(name="e", grid=Grid((10, 10)))

    assert isinstance(1.2 * a.dx, Mul)
    assert isinstance(e + a, Add)
    assert isinstance(e * a, Mul)
    assert isinstance(a * a, Pow)
    assert isinstance(1 / (a * a), Pow)

    addition = a + 1.2 * a.dx
    assert isinstance(addition, Add)
    assert all(isinstance(a, Differentiable) for a in addition.args)

    addition2 = a + e * a.dx
    assert isinstance(addition2, Add)
    assert all(isinstance(a, Differentiable) for a in addition2.args) 
Example #4
Source File: test_printing.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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')))") 
Example #5
Source File: operatorordering.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _expand_powers(factors):
    """
    Helper function for normal_ordered_form and normal_order: Expand a
    power expression to a multiplication expression so that that the
    expression can be handled by the normal ordering functions.
    """

    new_factors = []
    for factor in factors.args:
        if (isinstance(factor, Pow)
                and isinstance(factor.args[1], Integer)
                and factor.args[1] > 0):
            for n in range(factor.args[1]):
                new_factors.append(factor.args[0])
        else:
            new_factors.append(factor)

    return new_factors 
Example #6
Source File: test_differentiable.py    From devito with MIT License 6 votes vote down vote up
def test_diffify():
    a = Function(name="a", grid=Grid((10, 10)))
    e = Function(name="e", grid=Grid((10, 10)))

    assert isinstance(diffify(sympy.Mul(*[1.2, a.dx])), Mul)
    assert isinstance(diffify(sympy.Add(*[a, e])), Add)
    assert isinstance(diffify(sympy.Mul(*[e, a])), Mul)
    assert isinstance(diffify(sympy.Mul(*[a, a])), Pow)
    assert isinstance(diffify(sympy.Pow(*[a*a, -1])), Pow)

    addition = diffify(sympy.Add(*[a, sympy.Mul(*[1.2, a.dx])]))
    assert isinstance(addition, Add)
    assert all(isinstance(a, Differentiable) for a in addition.args)

    addition2 = diffify(sympy.Add(*[a, sympy.Mul(*[e, a.dx])]))
    assert isinstance(addition2, Add)
    assert all(isinstance(a, Differentiable) for a in addition2.args) 
Example #7
Source File: operator.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _replace_op_func(e, variable):

    if isinstance(e, Operator):
        return OperatorFunction(e, variable)
    
    if e.is_Number:
        return e
    
    if isinstance(e, Pow):
        return Pow(_replace_op_func(e.base, variable), e.exp)
    
    new_args = [_replace_op_func(arg, variable) for arg in e.args]
    
    if isinstance(e, Add):
        return Add(*new_args)
    
    elif isinstance(e, Mul):
        return Mul(*new_args)
    
    else:
        return e 
Example #8
Source File: manipulation.py    From devito with MIT License 6 votes vote down vote up
def pow_to_mul(expr):
    if expr.is_Atom or expr.is_Indexed:
        return expr
    elif expr.is_Pow:
        base, exp = expr.as_base_exp()
        if exp > 10 or exp < -10 or int(exp) != exp or exp == 0:
            # Large and non-integer powers remain untouched
            return expr
        elif exp == -1:
            # Reciprocals also remain untouched, but we traverse the base
            # looking for other Pows
            return expr.func(pow_to_mul(base), exp, evaluate=False)
        elif exp > 0:
            return sympy.Mul(*[base]*int(exp), evaluate=False)
        else:
            # SymPy represents 1/x as Pow(x,-1). Also, it represents
            # 2/x as Mul(2, Pow(x, -1)). So we shouldn't end up here,
            # but just in case SymPy changes its internal conventions...
            posexpr = sympy.Mul(*[base]*(-int(exp)), evaluate=False)
            return sympy.Pow(posexpr, -1, evaluate=False)
    else:
        return expr.func(*[pow_to_mul(i) for i in expr.args], evaluate=False) 
Example #9
Source File: builtins.py    From devito with MIT License 5 votes vote down vote up
def norm(f, order=2):
    """
    Compute the norm of a Function.

    Parameters
    ----------
    f : Function
        Input Function.
    order : int, optional
        The order of the norm. Defaults to 2.
    """
    kwargs = {}
    if f.is_TimeFunction and f._time_buffering:
        kwargs[f.time_dim.max_name] = f._time_size - 1

    # Protect SparseFunctions from accessing duplicated (out-of-domain) data,
    # otherwise we would eventually be summing more than expected
    p, eqns = f.guard() if f.is_SparseFunction else (f, [])

    s = dv.types.Scalar(name='sum', dtype=f.dtype)

    with MPIReduction(f) as mr:
        op = dv.Operator([dv.Eq(s, 0.0)] +
                         eqns +
                         [dv.Inc(s, Abs(Pow(p, order))), dv.Eq(mr.n[0], s)],
                         name='norm%d' % order)
        op.apply(**kwargs)

    v = Pow(mr.v, 1/order)

    return f.dtype(v) 
Example #10
Source File: _optimizer.py    From hope with GNU General Public License v3.0 5 votes vote down vote up
def visit_Mul(self, expr):
        sign, numerators, denominator = 1, [], []
        for term in expr.as_ordered_factors():
            if term.is_Pow and term.exp.is_Rational and term.exp.is_negative:
                denominator.append(sp.Pow(term.base, -term.exp, evaluate=term.exp==-1))
            elif term.is_Rational:
                if term.p == -1:
                    sign *= -1
                elif term.p != 1:
                    numerators.append(sp.Rational(term.p))
                if term.q == -1:
                    sign *= -1
                elif term.q != 1:
                    denominator.append(sp.Rational(term.q))
            else:
                numerators.append(term)
        if len(numerators) == 0:
            ret = Number(1)
        else:
            ret = self.visit(numerators[0])
            for arg in numerators[1:]:
                ret = BinOp("Mult", ret, self.visit(arg))
        if len(denominator) > 0:
            ret = BinOp("Div", ret, self.binOp_visit("Mult", denominator))
        if sign < 0:
            ret = UnaryOp("USub", ret)
        return ret 
Example #11
Source File: _optimizer.py    From hope with GNU General Public License v3.0 5 votes vote down vote up
def visit_Pow(self, expr):
        from sympy.core.singleton import S
        if expr.exp.is_real and float(int(expr.exp)) == expr.exp:
            print("Integer exponent as flaot: {0!s}".format(expr))
        if expr.exp is S.Half or (expr.exp.is_real and expr.exp == 0.5):
            return Call(NumpyAttr("sqrt"), True, [self.visit(expr.base)])
        elif -expr.exp is S.Half or (expr.exp.is_real and -expr.exp == 0.5):
            return BinOp("Div", Number(1.), Call(NumpyAttr("sqrt"), True, [self.visit(expr.base)], {}))
        elif expr.exp == -1:
            return BinOp("Div", Number(1.), self.visit(expr.base))
        else:
            return self.binOp_visit("Pow", expr.args) 
Example #12
Source File: _ode_composition.py    From pygom with GNU General Public License v2.0 5 votes vote down vote up
def _getExpression(expr, input_dict):
    """
    all the operations is dependent on the conditions 
    whether all the elements are leafs or only some of them.
    Only return expressions and not the individual elements
    """
    t = expr.args if len(expr.atoms()) > 1 else [expr]
    # print t

    # find out the length of the components within this node
    t_lengths = np.array(list(map(_expressionLength, t)))
    # print(tLengths)
    if np.all(t_lengths == 0):
        # if all components are leafs, then the node is an expression
        input_dict.setdefault(expr, 0)
        input_dict[expr] += 1
    else:
        for i, ti in enumerate(t):
            # if the leaf is a singleton, then it is an expression
            # else, go further along the tree
            if t_lengths[i] == 0:
                input_dict.setdefault(ti, 0)
                input_dict[ti] += 1
            else:
                if isinstance(ti, sympy.Mul):
                    _getExpression(ti, input_dict)
                elif isinstance(ti, sympy.Pow):
                    input_dict.setdefault(ti, 0)
                    input_dict[ti] += 1 
Example #13
Source File: differentiable.py    From devito with MIT License 5 votes vote down vote up
def __pow__(self, other):
        return Pow(self, other) 
Example #14
Source File: differentiable.py    From devito with MIT License 5 votes vote down vote up
def __div__(self, other):
        return Mul(self, Pow(other, sympy.S.NegativeOne)) 
Example #15
Source File: differentiable.py    From devito with MIT License 5 votes vote down vote up
def __rdiv__(self, other):
        return Mul(other, Pow(self, sympy.S.NegativeOne)) 
Example #16
Source File: process_latex.py    From latex2sympy with MIT License 5 votes vote down vote up
def convert_frac(frac):
    diff_op = False
    partial_op = False
    lower_itv = frac.lower.getSourceInterval()
    lower_itv_len = lower_itv[1] - lower_itv[0] + 1
    if (frac.lower.start == frac.lower.stop and
        frac.lower.start.type == PSLexer.DIFFERENTIAL):
        wrt = get_differential_var_str(frac.lower.start.text)
        diff_op = True
    elif (lower_itv_len == 2 and
        frac.lower.start.type == PSLexer.SYMBOL and
        frac.lower.start.text == '\\partial' and
        (frac.lower.stop.type == PSLexer.LETTER or frac.lower.stop.type == PSLexer.SYMBOL)):
        partial_op = True
        wrt = frac.lower.stop.text
        if frac.lower.stop.type == PSLexer.SYMBOL:
            wrt = wrt[1:]

    if diff_op or partial_op:
        wrt = sympy.Symbol(wrt)
        if (diff_op and frac.upper.start == frac.upper.stop and
            frac.upper.start.type == PSLexer.LETTER and
            frac.upper.start.text == 'd'):
            return [wrt]
        elif (partial_op and frac.upper.start == frac.upper.stop and
            frac.upper.start.type == PSLexer.SYMBOL and
            frac.upper.start.text == '\\partial'):
            return [wrt]
        upper_text = rule2text(frac.upper)

        expr_top = None
        if diff_op and upper_text.startswith('d'):
            expr_top = process_sympy(upper_text[1:])
        elif partial_op and frac.upper.start.text == '\\partial':
            expr_top = process_sympy(upper_text[len('\\partial'):])
        if expr_top:
            return sympy.Derivative(expr_top, wrt)

    expr_top = convert_expr(frac.upper)
    expr_bot = convert_expr(frac.lower)
    return sympy.Mul(expr_top, sympy.Pow(expr_bot, -1, evaluate=False), evaluate=False) 
Example #17
Source File: cacheprediction.py    From kerncraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def dimension_from_factor(dimension_factor):
    """
    Extract dimension from sympy factor

    >>> M = sympy.Symbol(name='M', positive=True, integer=True)
    >>> N = sympy.Symbol(name='N', positive=True, integer=True)
    >>> dimension_from_factor(M*N)
    2
    >>> dimension_from_factor(N**2)
    2
    >>> dimension_from_factor(23)
    0
    >>> dimension_from_factor(N)
    1

    :param dimension_factor: sympy expression, integer or symbol
    :return: dimension integer
    """
    if isinstance(dimension_factor, (sympy.Number, int)):
        return 0
    if isinstance(dimension_factor, sympy.Symbol):
        return 1
    # Replace all free symbols with one:
    if not dimension_factor.free_symbols:
        raise ValueError("dimension_factor is neither a number, a symbol nor an expression based "
                         "on symbols.")
    free_symbols = list(dimension_factor.free_symbols)
    for s in free_symbols[1:]:
        dimension_factor = dimension_factor.subs(s, free_symbols[0])
    if isinstance(dimension_factor, sympy.Pow):
        return dimension_factor.as_base_exp()[1]


# TODO support this delinearization in KernelCode? 
Example #18
Source File: _expr.py    From chempy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _implicit_conversion(obj):
    if isinstance(obj, (int, float)):
        return Constant(obj)
    elif isinstance(obj, Expr):
        return obj
    elif isinstance(obj, str):
        return Symbol(unique_keys=(obj,))

    if sympy is not None:
        if isinstance(obj, sympy.Mul):
            if len(obj.args) != 2:
                raise NotImplementedError("Did you use evaluate=False?")
            return _MulExpr([_implicit_conversion(obj.args[0]), _implicit_conversion(obj.args[1])])
        elif isinstance(obj, sympy.Add):
            if len(obj.args) != 2:
                raise NotImplementedError("Did you use evaluate=False?")
            return _AddExpr([_implicit_conversion(obj.args[0]), _implicit_conversion(obj.args[1])])
        elif isinstance(obj, sympy.Pow):
            return _PowExpr(_implicit_conversion(obj.base), _implicit_conversion(obj.exp))
        elif isinstance(obj, sympy.Float):
            return Constant(float(obj))
        elif isinstance(obj, sympy.Symbol):
            return Symbol(unique_keys=(obj.name,))

    raise NotImplementedError(
        "Don't know how to convert %s (of type %s)" % (obj, type(obj))) 
Example #19
Source File: _ode_composition.py    From pygom with GNU General Public License v2.0 5 votes vote down vote up
def _expressionLength(expr):
    """
    Returns the length of the expression i.e. number of terms.
    If the expression is a power term, i.e. x^2 then we assume
    that it is one term and return 0.
    """
    # print type(expr)
    if isinstance(expr, sympy.Mul):
        return len(expr.args)
    elif isinstance(expr, sympy.Pow):
        return 0
    else:
        return 0 
Example #20
Source File: arithmetic.py    From mathematics_dataset with Apache License 2.0 5 votes vote down vote up
def _surd_coefficients(sympy_exp):
  """Extracts coefficients a, b, where sympy_exp = a + b * sqrt(base)."""
  sympy_exp = sympy.simplify(sympy.expand(sympy_exp))

  def extract_b(b_sqrt_base):
    """Returns b from expression of form b * sqrt(base)."""
    if isinstance(b_sqrt_base, sympy.Pow):
      # Just form sqrt(base)
      return 1
    else:
      assert isinstance(b_sqrt_base, sympy.Mul)
      assert len(b_sqrt_base.args) == 2
      assert b_sqrt_base.args[0].is_rational
      assert isinstance(b_sqrt_base.args[1], sympy.Pow)  # should be sqrt.
      return b_sqrt_base.args[0]

  if sympy_exp.is_rational:
    # Form: a.
    return sympy_exp, 0
  elif isinstance(sympy_exp, sympy.Add):
    # Form: a + b * sqrt(base)
    assert len(sympy_exp.args) == 2
    assert sympy_exp.args[0].is_rational
    a = sympy_exp.args[0]
    b = extract_b(sympy_exp.args[1])
    return a, b
  else:
    # Form: b * sqrt(base).
    return 0, extract_b(sympy_exp) 
Example #21
Source File: tensorproduct.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _sympystr(self, printer, *args):
        from sympy.printing.str import sstr
        length = len(self.args)
        s = ''
        for i in range(length):
            if isinstance(self.args[i], (Add, Pow, Mul)):
                s = s + '('
            s = s + sstr(self.args[i])
            if isinstance(self.args[i], (Add, Pow, Mul)):
                s = s + ')'
            if i != length - 1:
                s = s + 'x'
        return s 
Example #22
Source File: pretty.py    From Computable with MIT License 5 votes vote down vote up
def _print_ProductSet(self, p):
        if len(p.sets) > 1 and not has_variety(p.sets):
            from sympy import Pow
            return self._print(Pow(p.sets[0], len(p.sets), evaluate=False))
        else:
            prod_char = u('\xd7')
            return self._print_seq(p.sets, None, None, ' %s ' % prod_char,
                parenthesize=lambda set: set.is_Union or set.is_Intersection) 
Example #23
Source File: pretty.py    From Computable with MIT License 5 votes vote down vote up
def _print_Pow(self, power):
        from sympy.simplify.simplify import fraction
        b, e = power.as_base_exp()
        if power.is_commutative:
            if e is S.NegativeOne:
                return prettyForm("1")/self._print(b)
            n, d = fraction(e)
            if n is S.One and d.is_Atom and not e.is_Integer:
                return self._print_nth_root(b, e)
            if e.is_Rational and e < 0:
                return prettyForm("1")/self._print(C.Pow(b, -e, evaluate=False))

        return self._print(b)**self._print(e) 
Example #24
Source File: ops.py    From mathematics_dataset with Apache License 2.0 5 votes vote down vote up
def sympy(self):
    return sympy.Pow(
        sympy.sympify(self.children['a']), sympy.sympify(self.children['b'])) 
Example #25
Source File: ops.py    From mathematics_dataset with Apache License 2.0 5 votes vote down vote up
def __init__(self, a, b):
    super(Pow, self).__init__({'a': a, 'b': b}) 
Example #26
Source File: ops.py    From mathematics_dataset with Apache License 2.0 5 votes vote down vote up
def sympy(self):
    return sympy.Mul(
        self.children['numer'], sympy.Pow(self.children['denom'], -1)) 
Example #27
Source File: test_printing.py    From sympsi with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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')))") 
Example #28
Source File: tensorproduct.py    From sympsi with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def tensor_product_simp(e, **hints):
    """Try to simplify and combine TensorProducts.

    In general this will try to pull expressions inside of ``TensorProducts``.
    It currently only works for relatively simple cases where the products have
    only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators``
    of ``TensorProducts``. It is best to see what it does by showing examples.

    Examples
    ========

    >>> from sympsi import tensor_product_simp
    >>> from sympsi import TensorProduct
    >>> from sympy import Symbol
    >>> A = Symbol('A',commutative=False)
    >>> B = Symbol('B',commutative=False)
    >>> C = Symbol('C',commutative=False)
    >>> D = Symbol('D',commutative=False)

    First see what happens to products of tensor products:

    >>> e = TensorProduct(A,B)*TensorProduct(C,D)
    >>> e
    AxB*CxD
    >>> tensor_product_simp(e)
    (A*C)x(B*D)

    This is the core logic of this function, and it works inside, powers, sums,
    commutators and anticommutators as well:

    >>> tensor_product_simp(e**2)
    (A*C)x(B*D)**2

    """
    if isinstance(e, Add):
        return Add(*[tensor_product_simp(arg) for arg in e.args])
    elif isinstance(e, Pow):
        return tensor_product_simp(e.base) ** e.exp
    elif isinstance(e, Mul):
        return tensor_product_simp_Mul(e)
    elif isinstance(e, Commutator):
        return Commutator(*[tensor_product_simp(arg) for arg in e.args])
    elif isinstance(e, AntiCommutator):
        return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args])
    else:
        return e 
Example #29
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def qsimplify_pauli(e):
    """
    Simplify an expression that includes products of pauli operators.

    Parameters
    ==========

    e : expression
        An expression that contains products of Pauli operators that is
        to be simplified.

    Examples
    ========

    >>> from sympy.physics.quantum.pauli import SigmaX, SigmaY
    >>> from sympy.physics.quantum.pauli import qsimplify_pauli
    >>> sx, sy = SigmaX(), SigmaY()
    >>> sx * sy
    SigmaX()*SigmaY()
    >>> qsimplify_pauli(sx * sy)
    I*SigmaZ()
    """
    if isinstance(e, Operator):
        return e

    if isinstance(e, (Add, Pow, exp)):
        t = type(e)
        return t(*(qsimplify_pauli(arg) for arg in e.args))

    if isinstance(e, Mul):

        c, nc = e.args_cnc()

        nc_s = []
        while nc:
            curr = nc.pop(0)

            while (len(nc) and
                   isinstance(curr, SigmaOpBase) and
                   isinstance(nc[0], SigmaOpBase) and
                   curr.name == nc[0].name):

                x = nc.pop(0)
                y = _qsimplify_pauli_product(curr, x)
                c1, nc1 = y.args_cnc()
                curr = Mul(*nc1)
                c = c + c1

            nc_s.append(curr)

        return Mul(*c) * Mul(*nc_s)

    return e 
Example #30
Source File: printer.py    From galgebra with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _print_Pow(self, expr):
        base = self._print(expr.base)
        if ('_' in base or '^' in base) and 'cdot' not in base:
            mode = True
        else:
            mode = False

        # Treat x**Rational(1, n) as special case
        if expr.exp.is_Rational and abs(expr.exp.p) == 1 and expr.exp.q != 1:
            #base = self._print(expr.base)
            expq = expr.exp.q

            if expq == 2:
                tex = r"\sqrt{%s}" % base
            elif self._settings['itex']:
                tex = r"\root{%d}{%s}" % (expq, base)
            else:
                tex = r"\sqrt[%d]{%s}" % (expq, base)

            if expr.exp.is_negative:
                return r"\frac{1}{%s}" % tex
            else:
                return tex
        elif self._settings['fold_frac_powers'] \
            and expr.exp.is_Rational \
                and expr.exp.q != 1:
            base, p, q = self._print(expr.base), expr.exp.p, expr.exp.q
            if mode:
                return r"{\left ( %s \right )}^{%s/%s}" % (base, p, q)
            else:
                return r"%s^{%s/%s}" % (base, p, q)

        elif expr.exp.is_Rational and expr.exp.is_negative and expr.base.is_Function:
            # Things like 1/x
            return r"\frac{%s}{%s}" % \
                (1, self._print(Pow(expr.base, -expr.exp)))
        else:
            if expr.base.is_Function:
                return r"{%s}^{%s}" % (self._print(expr.base), self._print(expr.exp))
            else:
                if expr.is_commutative and expr.exp == -1:
                    #solves issue 1030
                    #As Mul always simplify 1/x to x**-1
                    #The objective is achieved with this hack
                    #first we get the latex for -1 * expr,
                    #which is a Mul expression
                    tex = self._print(S.NegativeOne * expr).strip()
                    #the result comes with a minus and a space, so we remove
                    if tex[:1] == "-":
                        return tex[1:].strip()
                if self._needs_brackets(expr.base):
                    tex = r"\left(%s\right)^{%s}"
                else:
                    if mode:
                        tex = r"{\left ( %s \right )}^{%s}"
                    else:
                        tex = r"%s^{%s}"

                return tex % (self._print(expr.base),
                              self._print(expr.exp))