Esempio n. 1
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     if protocols.is_parameterized(self):
         return NotImplemented
     global_phase = 1j**(2 * self._exponent * self._global_shift)
     cnot_phase = 1j**self._exponent
     c = -1j * cnot_phase * np.sin(np.pi * self._exponent / 2) / 2
     return value.LinearDict({
         'II': global_phase * (1 - c),
         'IX': global_phase * c,
         'ZI': global_phase * c,
         'ZX': global_phase * -c,
     })
Esempio n. 2
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     if protocols.is_parameterized(self):
         return NotImplemented
     global_phase = 1j**(2 * self._exponent * self._global_shift)
     angle = np.pi * self._exponent / 4
     c, s = np.cos(angle), np.sin(angle)
     return value.LinearDict({
         'II': global_phase * c * c,
         'XX': global_phase * c * s * 1j,
         'YY': global_phase * s * c * 1j,
         'ZZ': global_phase * s * s,
     })
Esempio n. 3
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     return value.LinearDict(
         {
             'III': 3 / 4,
             'IXX': 1 / 4,
             'IYY': 1 / 4,
             'IZZ': 1 / 4,
             'ZII': 1 / 4,
             'ZXX': -1 / 4,
             'ZYY': -1 / 4,
             'ZZZ': -1 / 4,
         }
     )
Esempio n. 4
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     if self._is_parameterized_():
         return NotImplemented
     phase_angle = np.pi * self._phase_exponent / 2
     angle = np.pi * self._exponent / 2
     phase = 1j ** (2 * self._exponent * (self._global_shift + 0.5))
     return value.LinearDict(
         {
             'I': phase * np.cos(angle),
             'X': -1j * phase * np.sin(angle) * np.cos(2 * phase_angle),
             'Y': -1j * phase * np.sin(angle) * np.sin(2 * phase_angle),
         }
     )
Esempio n. 5
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     if protocols.is_parameterized(self):
         return NotImplemented
     x = [np.exp(1j * angle) for angle in self._diag_angles_radians]
     return value.LinearDict({
         'III': (x[0] + x[1] + x[2] + x[3] + x[4] + x[5] + x[6] + x[7]) / 8,
         'IIZ': (x[0] - x[1] + x[2] - x[3] + x[4] - x[5] + x[6] - x[7]) / 8,
         'IZI': (x[0] + x[1] - x[2] - x[3] + x[4] + x[5] - x[6] - x[7]) / 8,
         'IZZ': (x[0] - x[1] - x[2] + x[3] + x[4] - x[5] - x[6] + x[7]) / 8,
         'ZII': (x[0] + x[1] + x[2] + x[3] - x[4] - x[5] - x[6] - x[7]) / 8,
         'ZIZ': (x[0] - x[1] + x[2] - x[3] - x[4] + x[5] - x[6] + x[7]) / 8,
         'ZZI': (x[0] + x[1] - x[2] - x[3] - x[4] - x[5] + x[6] + x[7]) / 8,
         'ZZZ': (x[0] - x[1] - x[2] + x[3] - x[4] + x[5] + x[6] - x[7]) / 8,
     })
Esempio n. 6
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     if protocols.is_parameterized(self):
         return NotImplemented
     a = math.cos(self.theta)
     b = -1j * math.sin(self.theta)
     c = cmath.exp(-1j * self.phi)
     return value.LinearDict({
         'II': (1 + c) / 4 + a / 2,
         'IZ': (1 - c) / 4,
         'ZI': (1 - c) / 4,
         'ZZ': (1 + c) / 4 - a / 2,
         'XX': b / 2,
         'YY': b / 2,
     })
Esempio n. 7
0
    def __init__(
        self,
        linear_dict: Optional[value.LinearDict[FrozenSet[Tuple[raw_types.Qid,
                                                               int]]]] = None):
        """Constructor for ProjectorSum

        Args:
            linear_dict: A linear dictionary from a set of tuples of (Qubit, integer) to a complex
                number. The tuple is a projector onto the qubit and the complex number is the
                weight of these projections.
        """
        self._linear_dict: value.LinearDict[FrozenSet[Tuple[
            raw_types.Qid, int]]] = (linear_dict if linear_dict is not None
                                     else value.LinearDict({}))
def expand_matrix_in_orthogonal_basis(
    m: np.ndarray,
    basis: Dict[str, np.ndarray],
) -> value.LinearDict[str]:
    """Computes coefficients of expansion of m in basis.

    We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner
    product. We do not require that basis be orthonormal. Note that Pauli
    basis (I, X, Y, Z) is orthogonal, but not orthonormal.
    """
    return value.LinearDict({
        name: (hilbert_schmidt_inner_product(b, m) /
               hilbert_schmidt_inner_product(b, b))
        for name, b in basis.items()
    })
Esempio n. 9
0
    def _pauli_expansion_(self) -> 'cirq.LinearDict[str]':
        if protocols.is_parameterized(self):
            return NotImplemented
        x_angle = np.pi * self._x_exponent / 2
        z_angle = np.pi * self._z_exponent / 2
        axis_angle = np.pi * self._axis_phase_exponent
        phase = np.exp(1j * (x_angle + z_angle))

        cx = np.cos(x_angle)
        sx = np.sin(x_angle)
        return value.LinearDict({
            'I': phase * cx * np.cos(z_angle),
            'X': -1j * phase * sx * np.cos(z_angle + axis_angle),
            'Y': -1j * phase * sx * np.sin(z_angle + axis_angle),
            'Z': -1j * phase * cx * np.sin(z_angle),
        })  # yapf: disable
Esempio n. 10
0
    def _pauli_expansion_(self) -> value.LinearDict[str]:
        if self._is_parameterized_():
            return NotImplemented
        expansion = protocols.pauli_expansion(self._iswap)
        assert set(expansion.keys()).issubset({'II', 'XX', 'YY', 'ZZ'})
        assert np.isclose(expansion['XX'], expansion['YY'])

        v = (expansion['XX'] + expansion['YY']) / 2
        phase_angle = np.pi * self.phase_exponent
        c, s = np.cos(2 * phase_angle), np.sin(2 * phase_angle)

        return value.LinearDict({
            'II': expansion['II'],
            'XX': c * v,
            'YY': c * v,
            'XY': s * v,
            'YX': -s * v,
            'ZZ': expansion['ZZ'],
        })
Esempio n. 11
0
    def from_projector_strings(
        cls, terms: Union[ProjectorString,
                          List[ProjectorString]]) -> 'ProjectorSum':
        """Builds a ProjectorSum from one or more ProjectorString(s).

        Args:
            terms: Either a single ProjectorString or a list of ProjectorStrings.

        Returns:
            A ProjectorSum.
        """
        if isinstance(terms, ProjectorString):
            terms = [terms]
        termdict: DefaultDict[FrozenSet[Tuple[raw_types.Qid, int]],
                              value.Scalar] = defaultdict(lambda: 0.0)
        for pstring in terms:
            key = frozenset(pstring.projector_dict.items())
            termdict[key] += pstring.coefficient
        return cls(linear_dict=value.LinearDict(termdict))
Esempio n. 12
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     return value.LinearDict({'I' * self.num_qubits(): 1.0})
Esempio n. 13
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     if not all(d == 2 for d in self._qid_shape):
         return NotImplemented
     return value.LinearDict({'I' * self.num_qubits(): 1.0})
Esempio n. 14
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     result = value.LinearDict({})  # type: value.LinearDict[str]
     for gate, coefficient in self.items():
         result += protocols.pauli_expansion(gate) * coefficient
     return result
Esempio n. 15
0
 def _from_json_dict_(cls, items, **kwargs):
     mapping = {
         frozenset(tuple(qid_pauli) for qid_pauli in unit_pauli_string): val
         for unit_pauli_string, val in items
     }
     return cls(linear_dict=value.LinearDict(mapping))
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Protocol for obtaining expansion of linear operators in Pauli basis."""

from typing import Any, TypeVar, Union
from typing_extensions import Protocol

from cirq import value
from cirq._doc import doc_private
from cirq.linalg import operator_spaces
from cirq.protocols import qid_shape_protocol, unitary_protocol

TDefault = TypeVar('TDefault')

RaiseTypeErrorIfNotProvided: value.LinearDict[str] = value.LinearDict({})


class SupportsPauliExpansion(Protocol):
    """An object that knows its expansion in the Pauli basis."""
    @doc_private
    def _pauli_expansion_(self) -> value.LinearDict[str]:
        """Efficiently obtains expansion of self in the Pauli basis.

        Returns:
            Linear dict keyed by name of Pauli basis element. The names
            consist of n captal letters from the set 'I', 'X', 'Y', 'Z'
            where n is the number of qubits. For example, 'II', 'IX' and
            'XY' are valid Pauli names in the two-qubit case.
        """
Esempio n. 17
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Protocol for obtaining expansion of linear operators in Pauli basis."""

from typing import Any, TypeVar, Union
from typing_extensions import Protocol

from cirq import value
from cirq.linalg import operator_spaces
from cirq.protocols import qid_shape_protocol, unitary_protocol

TDefault = TypeVar('TDefault')

RaiseTypeErrorIfNotProvided = (value.LinearDict({})
                              )  # type: value.LinearDict[str]


class SupportsPauliExpansion(Protocol):
    """An object that knows its expansion in the Pauli basis."""

    def _pauli_expansion_(self) -> value.LinearDict[str]:
        """Efficiently obtains expansion of self in the Pauli basis.

        Returns:
            Linear dict keyed by name of Pauli basis element. The names
            consist of n captal letters from the set 'I', 'X', 'Y', 'Z'
            where n is the number of qubits. For example, 'II', 'IX' and
            'XY' are valid Pauli names in the two-qubit case.
        """
Esempio n. 18
0
 def _pauli_expansion_(self) -> value.LinearDict[str]:
     return value.LinearDict({'I' * len(self._qubits): 1.0})