How to use the cirq.protocols.qid_shape 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 / circuits / circuit.py View on Github external
def qid_shape(self,
                  qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
                 ) -> Tuple[int, ...]:
        qids = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
            self.all_qubits())
        return protocols.qid_shape(qids)
github quantumlib / Cirq / cirq / circuits / circuit.py View on Github external
Args:
            operation: The operation to validate.

        Raises:
            ValueError: The operation had qids that don't match its qid shape.
        """
        # Cast from Iterable[Operation, Moment] because preserve_moments is
        # False.
        for op in cast(Iterable['cirq.Operation'],
                       ops.flatten_op_tree(op_tree)):
            if protocols.qid_shape(op) != protocols.qid_shape(op.qubits):
                raise ValueError(
                    'Invalid operation. '
                    'An operation has qid shape <{!r}> but is on qids with '
                    'shape <{!r}>. The operation is <{!r}>.'.format(
                        protocols.qid_shape(op), protocols.qid_shape(op.qubits),
                        op))
github quantumlib / Cirq / cirq / ops / raw_types.py View on Github external
def _validate_qid_shape(val: Any, qubits: Sequence['cirq.Qid']) -> None:
    """Helper function to validate qubits for gates and operations.

    Raises:
        ValueError: The operation had qids that don't match it's qid shape.
    """
    qid_shape = protocols.qid_shape(val)
    if len(qubits) != len(qid_shape):
        raise ValueError('Wrong number of qubits for <{!r}>. '
                         'Expected {} qubits but got <{!r}>.'.format(
                             val, len(qid_shape), qubits))
    if any(qid.dimension != dimension
           for qid, dimension in zip(qubits, qid_shape)):
        raise ValueError('Wrong shape of qids for <{!r}>. '
                         'Expected {} but got {} <{!r}>.'.format(
                             val, qid_shape,
                             tuple(qid.dimension for qid in qubits), qubits))
    if len(set(qubits)) != len(qubits):
        raise ValueError('Duplicate qids for <{!r}>. '
                         'Expected unique qids but got <{!r}>.'.format(
                             val, qubits))
github quantumlib / Cirq / cirq / sim / sparse_simulator.py View on Github external
def _base_iterator(
            self,
            circuit: circuits.Circuit,
            qubit_order: ops.QubitOrderOrList,
            initial_state: Union[int, np.ndarray],
            perform_measurements: bool=True,
    ) -> Iterator:
        qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
                circuit.all_qubits())
        num_qubits = len(qubits)
        qid_shape = protocols.qid_shape(qubits)
        qubit_map = {q: i for i, q in enumerate(qubits)}
        state = wave_function.to_valid_state_vector(initial_state,
                                                    num_qubits,
                                                    qid_shape=qid_shape,
                                                    dtype=self._dtype)
        if len(circuit) == 0:
            yield SparseSimulatorStep(state, {}, qubit_map, self._dtype)

        def on_stuck(bad_op: ops.Operation):
            return TypeError(
                "Can't simulate unknown operations that don't specify a "
                "_unitary_ method, a _decompose_ method, "
                "(_has_unitary_ + _apply_unitary_) methods,"
                "(_has_mixture_ + _mixture_) methods, or are measurements."
                ": {!r}".format(bad_op))
github quantumlib / Cirq / cirq / sim / sparse_simulator.py View on Github external
def _simulate_reset(self, op: ops.Operation, data: _StateAndBuffer,
                        indices: List[int]) -> None:
        """Simulate an op that is a reset to the |0> state."""
        if isinstance(op.gate, ops.ResetChannel):
            reset = op.gate
            # Do a silent measurement.
            bits, _ = wave_function.measure_state_vector(
                data.state, indices, out=data.state, qid_shape=data.state.shape)
            # Apply bit flip(s) to change the reset the bits to 0.
            for b, i, d in zip(bits, indices, protocols.qid_shape(reset)):
                if b == 0:
                    continue  # Already zero, no reset needed
                reset_unitary = _FlipGate(d, reset_value=b)(*op.qubits)
                self._simulate_unitary(reset_unitary, data, [i])
github quantumlib / Cirq / cirq / circuits / circuit.py View on Github external
def _validate_op_tree_qids(self, op_tree: 'cirq.OP_TREE') -> None:
        """Raises an exception if any operation in `op_tree` has qids that don't
        match its qid shape.

        Args:
            operation: The operation to validate.

        Raises:
            ValueError: The operation had qids that don't match its qid shape.
        """
        # Cast from Iterable[Operation, Moment] because preserve_moments is
        # False.
        for op in cast(Iterable['cirq.Operation'],
                       ops.flatten_op_tree(op_tree)):
            if protocols.qid_shape(op) != protocols.qid_shape(op.qubits):
                raise ValueError(
                    'Invalid operation. '
                    'An operation has qid shape <{!r}> but is on qids with '
                    'shape <{!r}>. The operation is <{!r}>.'.format(
                        protocols.qid_shape(op), protocols.qid_shape(op.qubits),
                        op))
github quantumlib / Cirq / cirq / sim / sparse_simulator.py View on Github external
def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer,
            indices: List[int]) -> None:
        """Simulate an op that is a mixtures of unitaries."""
        probs, unitaries = zip(*protocols.mixture(op))
        # We work around numpy barfing on choosing from a list of
        # numpy arrays (which is not `one-dimensional`) by selecting
        # the index of the unitary.
        prng = self.prng or np.random
        index = prng.choice(range(len(unitaries)), p=probs)
        shape = protocols.qid_shape(op) * 2
        unitary = unitaries[index].astype(self._dtype).reshape(shape)
        result = linalg.targeted_left_multiply(unitary, data.state, indices,
                                               out=data.buffer)
        data.buffer = data.state
        data.state = result