Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix typing in numpy function arguments #5657

Merged
merged 7 commits into from
Jul 6, 2022
Merged
Prev Previous commit
Next Next commit
Add parametrization check to PauliString operations
Also use assertions to tell mypy that PauliString.coefficient is complex
when not parameterized.
  • Loading branch information
pavoljuhas committed Jul 1, 2022
commit 79b3f418e59d68ac28c97c87d85d4c830ac91bf5
14 changes: 10 additions & 4 deletions cirq-core/cirq/ops/pauli_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import numpy as np
import sympy

import cirq
from cirq import value, protocols, linalg, qis
from cirq._doc import document
from cirq._import import LazyLoader
Expand Down Expand Up @@ -498,12 +499,16 @@ def matrix(self, qubits: Optional[Iterable[TKey]] = None) -> np.ndarray:
in which the matrix representation of the Pauli string is to
be computed. Qubits absent from `self.qubits` are acted on by
the identity. Defaults to `self.qubits`.

Raises:
NotImplementedError: If this PauliString is parameterized.
"""
qubits = self.qubits if qubits is None else qubits
factors = [self.get(q, default=identity.I) for q in qubits]
return linalg.kron(
cast(complex, self.coefficient), *[protocols.unitary(f) for f in factors]
)
if cirq.is_parameterized(self):
raise NotImplementedError('Cannot express as matrix when parameterized')
assert isinstance(self.coefficient, complex)
return linalg.kron(self.coefficient, *[protocols.unitary(f) for f in factors])

def _has_unitary_(self) -> bool:
if self._is_parameterized_():
Expand All @@ -518,8 +523,9 @@ def _unitary_(self) -> Optional[np.ndarray]:
def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs'):
if not self._has_unitary_():
return None
assert isinstance(self.coefficient, complex)
if self.coefficient != 1:
args.target_tensor *= cast(complex, self.coefficient)
args.target_tensor *= self.coefficient
return protocols.apply_unitaries([self[q].on(q) for q in self.qubits], self.qubits, args)

def expectation_from_state_vector(
Expand Down
2 changes: 2 additions & 0 deletions cirq-core/cirq/ops/pauli_string_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1985,6 +1985,8 @@ def test_parameterization():
pst.expectation_from_state_vector(np.array([]), {})
with pytest.raises(NotImplementedError, match='parameterized'):
pst.expectation_from_density_matrix(np.array([]), {})
with pytest.raises(NotImplementedError, match='as matrix when parameterized'):
pst.matrix()
assert pst**1 == pst
assert pst**-1 == pst.with_coefficient(1.0 / t)
assert (-pst) ** 1 == -pst
Expand Down