How to use the cirq.ops 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 / testing / consistent_qasm.py View on Github external
import qiskit
    except ImportError:
        # coverage: ignore
        warnings.warn("Skipped assert_qasm_is_consistent_with_unitary because "
                      "qiskit isn't installed to verify against.")
        return

    unitary = protocols.unitary(val, None)
    if unitary is None:
        # Vacuous consistency.
        return

    if isinstance(val, ops.Operation):
        qubits: Sequence[ops.Qid] = val.qubits
        op = val
    elif isinstance(val, ops.Gate):
        qid_shape = protocols.qid_shape(val)
        remaining_shape = list(qid_shape)
        controls = getattr(val, 'control_qubits', None)
        if controls is not None:
            for i, q in zip(reversed(range(len(controls))), reversed(controls)):
                if q is not None:
                    remaining_shape.pop(i)
        qubits = devices.LineQid.for_qid_shape(remaining_shape)
        op = val.on(*qubits)
    else:
        raise NotImplementedError("Don't know how to test {!r}".format(val))

    args = protocols.QasmArgs(
        qubit_id_map={q: 'q[{}]'.format(i) for i, q in enumerate(qubits)})
    qasm = protocols.qasm(op, args=args, default=None)
    if qasm is None:
github quantumlib / Cirq / cirq / contrib / qasm_import / _parser.py View on Github external
def on(self, params: List[float], args: List[List[ops.Qid]],
           lineno: int) -> Iterable[ops.Operation]:
        self._validate_args(args, lineno)
        self._validate_params(params, lineno)

        reg_sizes = np.unique([len(reg) for reg in args])
        if len(reg_sizes) > 2 or (len(reg_sizes) > 1 and reg_sizes[0] != 1):
            raise QasmException("Non matching quantum registers of length {} "
                                "at line {}".format(reg_sizes, lineno))

        # the actual gate we'll apply the arguments to might be a parameterized
        # or non-parametrized gate
        final_gate: ops.Gate = (self.cirq_gate if isinstance(
            self.cirq_gate, ops.Gate) else self.cirq_gate(params))
        # OpenQASM gates can be applied on single qubits and qubit registers.
        # We represent single qubits as registers of size 1.
        # Based on the OpenQASM spec (https://arxiv.org/abs/1707.03429),
        # single qubit arguments can be mixed with qubit registers.
        # Given quantum registers of length reg_size and single qubits are both
        # used as arguments, we generate reg_size GateOperations via iterating
        # through each qubit of the registers 0 to n-1 and use the same one
        # qubit from the "single-qubit registers" for each operation.
        op_qubits = cast(Sequence[Sequence[ops.Qid]],
                         functools.reduce(np.broadcast, args))
        for qubits in op_qubits:
            if isinstance(qubits, ops.Qid):
                yield final_gate.on(qubits)
            elif len(np.unique(qubits)) < len(qubits):
                raise QasmException("Overlapping qubits in arguments"
github quantumlib / Cirq / cirq / google / devices / xmon_device.py View on Github external
def validate_moment(self, moment: 'cirq.Moment'):
        super().validate_moment(moment)
        for op in moment.operations:
            if isinstance(op.gate, ops.CZPowGate):
                for other in moment.operations:
                    if (other is not op and
                            self._check_if_exp11_operation_interacts(
                                cast(ops.GateOperation, op),
                                cast(ops.GateOperation, other))):
                        raise ValueError(
                            'Adjacent Exp11 operations: {}.'.format(moment))
github quantumlib / Cirq / cirq / contrib / acquaintance / mutation_utils.py View on Github external
or only permutation gates. Orders resulting moments so that the first one
    is of the same type as the previous one.

    Args:
        circuit: The acquaintance strategy to rectify.
        acquaint_first: Whether to make acquaintance moment first in when
        splitting the first mixed moment.
    """

    if not is_acquaintance_strategy(circuit):
        raise TypeError('not is_acquaintance_strategy(circuit)')

    rectified_moments = []
    for moment in circuit:
        gate_type_to_ops: Dict[bool, List[
            ops.GateOperation]] = collections.defaultdict(list)
        for op in moment.operations:
            gate_op = cast(ops.GateOperation, op)
            is_acquaintance = isinstance(gate_op.gate,
                                         AcquaintanceOpportunityGate)
            gate_type_to_ops[is_acquaintance].append(gate_op)
        if len(gate_type_to_ops) == 1:
            rectified_moments.append(moment)
            continue
        for acquaint_first in sorted(gate_type_to_ops.keys(),
                                     reverse=acquaint_first):
            rectified_moments.append(
                    ops.Moment(gate_type_to_ops[acquaint_first]))
    circuit._moments = rectified_moments
github quantumlib / Cirq / cirq / optimizers / two_qubit_decompositions.py View on Github external
def _kak_decomposition_to_operations(q0: ops.Qid,
                                     q1: ops.Qid,
                                     kak: linalg.KakDecomposition,
                                     allow_partial_czs: bool,
                                     atol: float = 1e-8
                                     ) -> List[ops.Operation]:
    """Assumes that the decomposition is canonical."""
    b0, b1 = kak.single_qubit_operations_before
    pre = [_do_single_on(b0, q0, atol=atol), _do_single_on(b1, q1, atol=atol)]
    a0, a1 = kak.single_qubit_operations_after
    post = [_do_single_on(a0, q0, atol=atol), _do_single_on(a1, q1, atol=atol)]

    return list(cast(Iterable[ops.Operation], ops.flatten_op_tree([
        pre,
        _non_local_part(q0,
                        q1,
                        kak.interaction_coefficients,
                        allow_partial_czs,
                        atol=atol),
        post,
    ])))
github quantumlib / Cirq / cirq / experiments / qubit_characterizations.py View on Github external
c1_in_xz.append([ops.Z ** phi_0, ops.X ** phi_1])

    c1_in_xy.append([ops.X ** 0.0])
    c1_in_xy.append([ops.Y, ops.X])

    phi_xy = [[-0.5, 0.5, 0.5], [-0.5, -0.5, 0.5], [0.5, 0.5, 0.5],
              [-0.5, 0.5, -0.5]]
    for phi in phi_xy:
        c1_in_xy.append([ops.X ** phi[0], ops.Y ** phi[1], ops.X ** phi[2]])

    phi_xz = [[0.5, 0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, -0.5, -0.5],
              [-0.5, 0.5, -0.5]]
    for phi in phi_xz:
        c1_in_xz.append([ops.X ** phi[0], ops.Z ** phi[1], ops.X ** phi[2]])

    s1 = [[ops.X ** 0.0], [ops.Y ** 0.5, ops.X ** 0.5],
          [ops.X ** -0.5, ops.Y ** -0.5]]  # type: List[List[ops.Gate]]
    s1_x = [[ops.X ** 0.5], [ops.X ** 0.5, ops.Y ** 0.5, ops.X ** 0.5],
            [ops.Y ** -0.5]]  # type: List[List[ops.Gate]]
    s1_y = [[ops.Y ** 0.5], [ops.X ** -0.5, ops.Y ** -0.5, ops.X ** 0.5],
            [ops.Y, ops.X ** 0.5]]  # type: List[List[ops.Gate]]

    return Cliffords(c1_in_xy, c1_in_xz, s1, s1_x, s1_y)
github quantumlib / Cirq / cirq / sim / simulator.py View on Github external
numpy array, the first dimension corresponding to the repetition
            and the second to the actual boolean measurement results (ordered
            by the qubits being measured.)

        Raises:
            ValueError: If the operation's gates are not `MeasurementGate`
                instances or a qubit is acted upon multiple times by different
                operations from `measurement_ops`.
        """
        bounds = {}  # type: Dict[str, Tuple]
        all_qubits = []  # type: List[ops.Qid]
        meas_ops = {}
        current_index = 0
        for op in measurement_ops:
            gate = op.gate
            if not isinstance(gate, ops.MeasurementGate):
                raise ValueError('{} was not a MeasurementGate'.format(gate))
            key = protocols.measurement_key(gate)
            meas_ops[key] = gate
            if key in bounds:
                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()))
github quantumlib / Cirq / cirq / optimizers / eject_z.py View on Github external
a, b = op.qubits
                    qubit_phase[a], qubit_phase[b] = qubit_phase[
                        b], qubit_phase[a]
                    continue


                # Try to move the tracked phasing over the operation.
                phased_op = op
                for i, p in enumerate(phases):
                    if not decompositions.is_negligible_turn(p, self.tolerance):
                        phased_op = protocols.phase_by(phased_op, -p, i,
                                                       default=None)
                if phased_op is not None:
                    deletions.append((moment_index, op))
                    inline_intos.append((moment_index,
                                     cast(ops.Operation, phased_op)))
                else:
                    dump_tracked_phase(op.qubits, moment_index)

        dump_tracked_phase(qubit_phase.keys(), len(circuit))
        circuit.batch_remove(deletions)
        circuit.batch_insert_into(inline_intos)
        circuit.batch_insert(insertions)
github quantumlib / Cirq / cirq / optimizers / two_qubit_decompositions.py View on Github external
def _xx_interaction_via_full_czs(q0: ops.Qid,
                                 q1: ops.Qid,
                                 x: float):
    a = x * -2 / np.pi
    yield ops.H(q1)
    yield ops.CZ(q0, q1)
    yield ops.X(q0)**a
    yield ops.CZ(q0, q1)
    yield ops.H(q1)
github quantumlib / Cirq / cirq / circuits / circuit.py View on Github external
def _to_qasm_output(
            self,
            header: Optional[str] = None,
            precision: int = 10,
            qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
    ) -> QasmOutput:
        """Returns a QASM object equivalent to the circuit.

        Args:
            header: A multi-line string that is placed in a comment at the top
                of the QASM. Defaults to a cirq version specifier.
            precision: Number of digits to use when representing numbers.
            qubit_order: Determines how qubits are ordered in the QASM
                register.
        """
        if header is None:
            header = 'Generated from Cirq v{}'.format(
                cirq._version.__version__)
        qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
            self.all_qubits())
        return QasmOutput(operations=self.all_operations(),