How to use the cirq.value.value_equality function in cirq

To help you get started, we’ve selected a few cirq examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github quantumlib / Cirq / cirq / ops / linear_combinations.py View on Github external
return False
        for qid, pauli in k:
            if not isinstance(qid, raw_types.Qid):
                return False
            if not isinstance(pauli, pauli_gates.Pauli):
                return False

    return True


def _pauli_string_from_unit(unit: UnitPauliStringT,
                            coefficient: Union[int, float, complex] = 1):
    return PauliString(qubit_pauli_map=dict(unit), coefficient=coefficient)


@value.value_equality(approximate=True)
class PauliSum:
    """Represents operator defined by linear combination of PauliStrings.

    Since PauliStrings store their own coefficients, this class
    does not implement the LinearDict interface. Instead, you can
    add and subtract terms and then iterate over the resulting
    (simplified) expression.

    Under the hood, this class is backed by a LinearDict with coefficient-less
    PauliStrings as keys. PauliStrings are reconstructed on-the-fly during
    iteration.
    """

    def __init__(
            self,
            linear_dict: Optional[value.LinearDict[UnitPauliStringT]] = None):
github quantumlib / Cirq / cirq / ops / fsim_gate.py View on Github external
applies more generally to fermions, thus the name of the gate.
"""

import cmath
import math
from typing import Optional

import numpy as np

import cirq
from cirq import protocols, value
from cirq._compat import proper_repr
from cirq.ops import gate_features


@value.value_equality(approximate=True)
class FSimGate(gate_features.TwoQubitGate,
               gate_features.InterchangeableQubitsGate):
    """Fermionic simulation gate family.

    Contains all two qubit interactions that preserve excitations, up to
    single-qubit rotations and global phase.

    The unitary matrix of this gate is:

        [[1, 0, 0, 0],
         [0, a, b, 0],
         [0, b, a, 0],
         [0, 0, 0, c]]

    where:
github quantumlib / Cirq / cirq / contrib / quirk / cells / cell.py View on Github external
def persistent_modifiers(self) -> Dict[str, Callable[['Cell'], 'Cell']]:
        """Overridable modifications to apply to the rest of the circuit.

        Persistent modifiers apply to all cells in the same column and also to
        all cells in future columns (until a column overrides the modifier with
        another one using the same key).

        Returns:
            A dictionary of keyed modifications. Each modifier lasts until a
            later cell specifies a new modifier with the same key.
        """
        return {}


@value.value_equality
class ExplicitOperationsCell(Cell):
    """A quirk cell with known body operations and basis change operations."""

    def __init__(self,
                 operations: Iterable[ops.Operation],
                 basis_change: Iterable[ops.Operation] = ()):
        self._operations = tuple(operations)
        self._basis_change = tuple(basis_change)

    def _value_equality_values_(self):
        return self._operations, self._basis_change

    def basis_change(self) -> 'cirq.OP_TREE':
        return self._basis_change

    def operations(self) -> 'cirq.OP_TREE':
github quantumlib / Cirq / cirq / ops / gate_operation.py View on Github external
from typing import (Any, Dict, FrozenSet, List, Optional, Sequence, Tuple, Type,
                    TypeVar, Union, TYPE_CHECKING)

import numpy as np

from cirq import protocols, value
from cirq._compat import deprecated
from cirq.ops import raw_types, gate_features
from cirq.type_workarounds import NotImplementedType

if TYPE_CHECKING:
    import cirq


@value.value_equality(approximate=True)
class GateOperation(raw_types.Operation):
    """An application of a gate to a sequence of qubits."""

    def __init__(self, gate: 'cirq.Gate', qubits: Sequence['cirq.Qid']) -> None:
        """
        Args:
            gate: The gate to apply.
            qubits: The qubits to operate on.
        """
        gate.validate_args(qubits)
        self._gate = gate
        self._qubits = tuple(qubits)

    @property
    def gate(self) -> 'cirq.Gate':
        """The gate applied by the operation."""
github quantumlib / Cirq / cirq / sim / density_matrix_simulator.py View on Github external
def sample(self,
               qubits: List[ops.Qid],
               repetitions: int = 1,
               seed: Optional[Union[int, np.random.RandomState]] = None
              ) -> np.ndarray:
        indices = [self._qubit_map[q] for q in qubits]
        return density_matrix_utils.sample_density_matrix(
            self._simulator_state().density_matrix,
            indices,
            qid_shape=self._qid_shape,
            repetitions=repetitions,
            seed=seed)


@value.value_equality(unhashable=True)
class DensityMatrixSimulatorState():
    """The simulator state for DensityMatrixSimulator

    Args:
        density_matrix: The density matrix of the simulation.
        qubit_map: A map from qid to index used to define the
            ordering of the basis in density_matrix.
    """

    def __init__(self,
            density_matrix: np.ndarray,
            qubit_map: Dict[ops.Qid, int]):
        self.density_matrix = density_matrix
        self.qubit_map = qubit_map
        self._qid_shape = simulator._qubit_map_to_shape(qubit_map)
github quantumlib / Cirq / cirq / devices / noise_model.py View on Github external
implementation=_noisy_operation_impl_moments)
    @value.alternative(requires='noisy_moment',
                       implementation=_noisy_operation_impl_moment)
    def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE':
        """Adds noise to an individual operation.

        Args:
            operation: The operation to make noisy.

        Returns:
            An OP_TREE corresponding to the noisy operations implementing the
            noisy version of the given operation.
        """


@value.value_equality
class _NoNoiseModel(NoiseModel):
    """A default noise model that adds no noise."""

    def noisy_moments(self, moments: 'Iterable[cirq.Moment]',
                      system_qubits: Sequence['cirq.Qid']):
        return list(moments)

    def noisy_moment(self, moment: 'cirq.Moment',
                     system_qubits: Sequence['cirq.Qid']):
        return moment

    def noisy_operation(self, operation: 'cirq.Operation'):
        return operation

    def _value_equality_values_(self):
        return None
github quantumlib / Cirq / cirq / work / collector.py View on Github external
# limitations under the License.

from typing import Optional, Any, Iterable, Union, List, TYPE_CHECKING
import abc
import asyncio

import numpy as np

from cirq import circuits, study, value
from cirq.work import work_pool

if TYPE_CHECKING:
    import cirq


@value.value_equality(unhashable=True)
class CircuitSampleJob:
    """Describes a sampling task."""

    def __init__(self,
                 circuit: circuits.Circuit,
                 *,
                 repetitions: int,
                 tag: Any = None):
        """
        Args:
            circuit: The circuit to sample from.
            repetitions: How many times to sample the circuit.
            tag: An arbitrary value associated with the job. This value is used
                so that when a job completes and is handed back, it is possible
                to tell what the job was for. For example, the key could be a
                string like "main_run" or "calibration_run", or it could be set
github quantumlib / Cirq / cirq / ops / measurement_gate.py View on Github external
# 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.

from typing import Iterable, Optional, Tuple, TYPE_CHECKING

import numpy as np

from cirq import protocols, value
from cirq.ops import raw_types

if TYPE_CHECKING:
    import cirq


@value.value_equality
class MeasurementGate(raw_types.Gate):
    """A gate that measures qubits in the computational basis.

    The measurement gate contains a key that is used to identify results
    of measurements.
    """

    def __init__(self,
                 num_qubits: Optional[int] = None,
                 key: str = '',
                 invert_mask: Tuple[bool, ...] = (),
                 qid_shape: Tuple[int, ...] = None) -> None:
        """
        Args:
            num_qubits: The number of qubits to act upon.
            key: The string key of the measurement.
github quantumlib / Cirq / cirq / sim / simulator.py View on Github external
raise ValueError(
                    'Duplicate MeasurementGate with key {}'.format(key))
            bounds[key] = (current_index, current_index + len(op.qubits))
            all_qubits.extend(op.qubits)
            current_index += len(op.qubits)
        indexed_sample = self.sample(all_qubits, repetitions, seed=seed)

        results = {}
        for k, (s, e) in bounds.items():
            before_invert_mask = indexed_sample[:, s:e]
            results[k] = before_invert_mask ^ (np.logical_and(
                before_invert_mask < 2, meas_ops[k].full_invert_mask()))
        return results


@value.value_equality(unhashable=True)
class SimulationTrialResult:
    """Results of a simulation by a SimulatesFinalState.

    Unlike TrialResult these results contain the final simulator_state of the
    system. This simulator_state is dependent on the simulation implementation
    and may be, for example, the wave function of the system or the density
    matrix of the system.

    Attributes:
        params: A ParamResolver of settings used for this result.
        measurements: A dictionary from measurement gate key to measurement
            results. Measurement results are a numpy ndarray of actual boolean
            measurement results (ordered by the qubits acted on by the
            measurement gate.)
    """