Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __sub__(self, other):
if isinstance(other, Number):
other = Expr.from_number(other)
elif isinstance(other, Term):
other = Expr.from_term(other)
if isinstance(other, Expr):
terms = self.terms_to_dict()
for op, coeff in other.terms:
if op in terms:
terms[op] -= coeff
if terms[op] == 0:
del terms[op]
else:
terms[op] = -coeff
return Expr.from_terms_dict(terms)
return NotImplemented
def from_paulipair(pauli1, pauli2):
"""Make new Term from two Pauli operator."""
return Term(Term.join_ops((pauli1,), (pauli2,)), 1.0)
def __rmul__(self, other):
if isinstance(other, Number):
if other == 0:
return Expr.from_number(0.0)
return Expr.from_terms_iter(Term(op, coeff * other) for op, coeff in self.terms)
if isinstance(other, _PauliImpl):
other = other.to_term()
if isinstance(other, Term):
return Expr(tuple(other * term for term in self.terms))
return NotImplemented
def from_number(num):
"""Make new Expr from a number"""
if num:
return Expr.from_term(Term((), num))
else:
return Expr.zero()
def __mul__(self, other):
if isinstance(other, Number):
return Term(self.ops, self.coeff * other)
if isinstance(other, Term):
ops = Term.join_ops(self.ops, other.ops)
coeff = self.coeff * other.coeff
return Term(ops, coeff)
if isinstance(other, _PauliImpl):
if other.is_identity:
return self
return Term(Term.join_ops(self.ops, (other,)), self.coeff)
return NotImplemented
def from_ops_iter(ops, coeff):
"""For internal use."""
return Term(tuple(ops), coeff)
new_ops = []
for n in sorted(before.keys()):
ops = before[n]
assert ops
k = 1.0
op = ops[0]
for _op in ops[1:]:
_k, op = mul(op, _op)
k *= _k
new_coeff *= k
if new_coeff.imag == 0:
# cast to float
new_coeff = new_coeff.real
if op != "I":
new_ops.append(pauli_from_char(op, n))
return Term(tuple(new_ops), new_coeff)