def _with_parameterized_layers(circuit: 'cirq.AbstractCircuit',
                               qubits: Sequence['cirq.Qid'],
                               needs_init_layer: bool) -> 'cirq.Circuit':
    """Return a copy of the input circuit with parameterized single-qubit rotations.

    These rotations flank the circuit: the initial two layers of X and Y gates
    are given parameter names "{qubit}-Xi" and "{qubit}-Yi" and are used
    to set up the initial state. If `needs_init_layer` is False,
    these two layers of gates are omitted.

    The final two layers of X and Y gates are given parameter names
    "{qubit}-Xf" and "{qubit}-Yf" and are use to change the frame of the
    qubit before measurement, effectively measuring in bases other than Z.
    """
    x_beg_mom = circuits.Moment(
        [ops.X(q)**sympy.Symbol(f'{q}-Xi') for q in qubits])
    y_beg_mom = circuits.Moment(
        [ops.Y(q)**sympy.Symbol(f'{q}-Yi') for q in qubits])
    x_end_mom = circuits.Moment(
        [ops.X(q)**sympy.Symbol(f'{q}-Xf') for q in qubits])
    y_end_mom = circuits.Moment(
        [ops.Y(q)**sympy.Symbol(f'{q}-Yf') for q in qubits])
    meas_mom = circuits.Moment([ops.measure(*qubits, key='z')])
    if needs_init_layer:
        total_circuit = circuits.Circuit([x_beg_mom, y_beg_mom])
        total_circuit += circuit.unfreeze()
    else:
        total_circuit = circuit.unfreeze()
    total_circuit.append([x_end_mom, y_end_mom, meas_mom])
    return total_circuit
Esempio n. 2
0
def split_into_matching_protocol_then_general(
    circuit: 'cirq.AbstractCircuit', predicate: Callable[['cirq.Operation'],
                                                         bool]
) -> Tuple['cirq.AbstractCircuit', 'cirq.AbstractCircuit']:
    """Splits the circuit into a matching prefix and non-matching suffix.

    The splitting happens in a per-qubit fashion. A non-matching operation on
    qubit A will cause later operations on A to be part of the non-matching
    suffix, but later operations on other qubits will continue to be put into
    the matching part (as long as those qubits have had no non-matching operation
    up to that point).
    """
    blocked_qubits: Set[cirq.Qid] = set()
    matching_prefix = circuits.Circuit()
    general_suffix = circuits.Circuit()
    for moment in circuit:
        matching_part = []
        general_part = []
        for op in moment:
            qs = set(op.qubits)
            if not predicate(op) or not qs.isdisjoint(blocked_qubits):
                blocked_qubits |= qs

            if qs.isdisjoint(blocked_qubits):
                matching_part.append(op)
            else:
                general_part.append(op)
        if matching_part:
            matching_prefix.append(circuits.Moment(matching_part))
        if general_part:
            general_suffix.append(circuits.Moment(general_part))
    return matching_prefix, general_suffix
Esempio n. 3
0
def test_depolarizer_different_gate():
    q1 = ops.QubitId()
    q2 = ops.QubitId()
    cnot = Job(circuits.Circuit([
        circuits.Moment([ops.CNOT(q1, q2)]),
    ]))
    allerrors = DepolarizerChannel(
        probability=1.0,
        depolarizing_gates=[xmon_gates.ExpZGate(),
                            xmon_gates.ExpWGate()])
    p0 = Symbol(DepolarizerChannel._parameter_name + '0')
    p1 = Symbol(DepolarizerChannel._parameter_name + '1')
    p2 = Symbol(DepolarizerChannel._parameter_name + '2')
    p3 = Symbol(DepolarizerChannel._parameter_name + '3')

    error_sweep = (Points(p0.name, [1.0]) + Points(p1.name, [1.0]) +
                   Points(p2.name, [1.0]) + Points(p3.name, [1.0]))

    cnot_then_z = Job(
        circuits.Circuit([
            circuits.Moment([ops.CNOT(q1, q2)]),
            circuits.Moment([
                xmon_gates.ExpZGate(half_turns=p0).on(q1),
                xmon_gates.ExpZGate(half_turns=p1).on(q2)
            ]),
            circuits.Moment([
                xmon_gates.ExpWGate(half_turns=p2).on(q1),
                xmon_gates.ExpWGate(half_turns=p3).on(q2)
            ])
        ]), cnot.sweep * error_sweep)

    assert allerrors.transform_job(cnot) == cnot_then_z
Esempio n. 4
0
def test_leaves_singleton():
    m = MergeRotations(0.000001)
    q = ops.QubitId()
    c = circuits.Circuit([circuits.Moment([ops.X(q)])])

    m.optimization_at(c, 0, c.operation_at(q, 0))

    assert c == circuits.Circuit([circuits.Moment([ops.X(q)])])
Esempio n. 5
0
def test_clears_paired_cnot():
    q0 = ops.QubitId()
    q1 = ops.QubitId()
    assert_optimizes(
        before=circuits.Circuit([
            circuits.Moment([ops.CNOT(q0, q1)]),
            circuits.Moment([ops.CNOT(q0, q1)]),
        ]),
        after=circuits.Circuit())
Esempio n. 6
0
def test_removes_identity_sequence():
    q = ops.QubitId()
    assert_optimizes(before=circuits.Circuit([
        circuits.Moment([ops.Z(q)]),
        circuits.Moment([ops.H(q)]),
        circuits.Moment([ops.X(q)]),
        circuits.Moment([ops.H(q)]),
    ]),
                     after=circuits.Circuit())
Esempio n. 7
0
def test_ignores_2qubit_target():
    m = MergeRotations(0.000001)
    q = ops.QubitId()
    q2 = ops.QubitId()
    c = circuits.Circuit([
        circuits.Moment([ops.CZ(q, q2)]),
    ])

    m.optimization_at(c, 0, c.operation_at(q, 0))

    assert c == circuits.Circuit([circuits.Moment([ops.CZ(q, q2)])])
Esempio n. 8
0
 def noisy_moment(self, moment: 'cirq.Moment',
                  system_qubits: Sequence['cirq.Qid']):
     if validate_all_measurements(moment):
         return [
             circuits.Moment(
                 self.readout_noise_gate(q) for q in system_qubits), moment
         ]
     return [
         moment,
         circuits.Moment(self.qubit_noise_gate(q) for q in system_qubits)
     ]
Esempio n. 9
0
def _circuit_plus_pauli_string_measurements(
        circuit: 'cirq.Circuit',
        pauli_string: 'cirq.PauliString') -> 'cirq.Circuit':
    """A circuit measuring the given observable at the end of the given circuit."""
    assert pauli_string
    circuit = circuit.copy()
    circuit.append(circuits.Moment(pauli_string.to_z_basis_ops()))
    circuit.append(
        circuits.Moment([ops.measure(*sorted(pauli_string.keys()),
                                     key='out')]))
    return circuit
Esempio n. 10
0
def test_drop():
    q1 = ops.QubitId()
    q2 = ops.QubitId()
    assert_optimizes(before=circuits.Circuit([
        circuits.Moment(),
        circuits.Moment(),
        circuits.Moment([ops.CNOT(q1, q2)]),
        circuits.Moment(),
    ]),
                     after=circuits.Circuit([
                         circuits.Moment([ops.CNOT(q1, q2)]),
                     ]))
Esempio n. 11
0
def test_clears_small():
    m = circuits.DropNegligible(0.001)
    q = ops.QubitId()
    c = circuits.Circuit([circuits.Moment([ops.Z(q)**0.000001])])

    assert (m.optimization_at(c, 0, c.operation_at(q, 0)) ==
            circuits.PointOptimizationSummary(clear_span=1,
                                              clear_qubits=[q],
                                              new_operations=[]))

    m.optimize_circuit(c)
    assert c == circuits.Circuit([circuits.Moment()])
Esempio n. 12
0
def test_combines_sequence():
    m = MergeRotations(0.000001)
    q = ops.QubitId()
    c = circuits.Circuit([
        circuits.Moment([ops.X(q)**0.5]),
        circuits.Moment([ops.Z(q)**0.5]),
        circuits.Moment([ops.X(q)**-0.5]),
    ])

    assert (m.optimization_at(c, 0, c.operation_at(
        q,
        0)) == circuits.PointOptimizationSummary(clear_span=3,
                                                 clear_qubits=[q],
                                                 new_operations=ops.Y(q)**0.5))
Esempio n. 13
0
def align_left(
        circuit: 'cirq.AbstractCircuit',
        *,
        context: Optional['cirq.TransformerContext'] = None) -> 'cirq.Circuit':
    """Align gates to the left of the circuit.

    Note that tagged operations with tag in `context.tags_to_ignore` will continue to stay in their
    original position and will not be aligned.

    Args:
          circuit: Input circuit to transform.
          context: `cirq.TransformerContext` storing common configurable options for transformers.

    Returns:
          Copy of the transformed input circuit.
    """
    if context is None:
        context = transformer_api.TransformerContext()

    ret = circuits.Circuit()
    for i, moment in enumerate(circuit):
        for op in moment:
            if isinstance(op, ops.TaggedOperation) and set(
                    op.tags).intersection(context.tags_to_ignore):
                ret.append([circuits.Moment()] * (i + 1 - len(ret)))
                ret[i] = ret[i].with_operation(op)
            else:
                ret.append(op)
    return ret
Esempio n. 14
0
def _init_ops(data: Dict[str, Any]) -> 'cirq.OP_TREE':
    if 'init' not in data:
        return []
    init = data['init']
    if not isinstance(init, List):
        raise ValueError(f'Circuit JSON init must be a list but was {init!r}.')
    init_ops = []
    for i in range(len(init)):
        state = init[i]
        q = devices.LineQubit(i)
        if state == 0:
            pass
        elif state == 1:
            init_ops.append(ops.X(q))
        elif state == '+':
            init_ops.append(ops.ry(np.pi / 2).on(q))
        elif state == '-':
            init_ops.append(ops.ry(-np.pi / 2).on(q))
        elif state == 'i':
            init_ops.append(ops.rx(-np.pi / 2).on(q))
        elif state == '-i':
            init_ops.append(ops.rx(np.pi / 2).on(q))
        else:
            raise ValueError(f'Unrecognized init state: {state!r}')
    return circuits.Moment(init_ops)
Esempio n. 15
0
def rectify_acquaintance_strategy(circuit: circuits.Circuit,
                                  acquaint_first: bool = True) -> None:
    """Splits moments so that they contain either only acquaintance gates
    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 = collections.defaultdict(
            list)  # type: Dict[bool, List[ops.GateOperation]]
        for op in moment.operations:
            gate_type_to_ops[isinstance(
                op.gate, AcquaintanceOpportunityGate)].append(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(
                circuits.Moment(gate_type_to_ops[acquaint_first]))
    circuit._moments = rectified_moments
Esempio n. 16
0
def display_mapping(circuit: 'cirq.Circuit', initial_mapping: LogicalMapping) -> None:
    """Inserts display gates between moments to indicate the mapping throughout
    the circuit."""
    qubits = sorted(circuit.all_qubits())
    mapping = initial_mapping.copy()

    old_moments = circuit._moments
    gate = MappingDisplayGate(mapping.get(q) for q in qubits)
    new_moments = [circuits.Moment([gate(*qubits)])]
    for moment in old_moments:
        new_moments.append(moment)
        update_mapping(mapping, moment)
        gate = MappingDisplayGate(mapping.get(q) for q in qubits)
        new_moments.append(circuits.Moment([gate(*qubits)]))

    circuit._moments = new_moments
def get_grid_interaction_layer_circuit(
    device_graph: nx.Graph,
    pattern: Sequence[GridInteractionLayer] = HALF_GRID_STAGGERED_PATTERN,
    two_qubit_gate=ops.ISWAP**0.5,
) -> 'cirq.Circuit':
    """Create a circuit representation of a grid interaction pattern on a given device topology.

    The resulting circuit is deterministic, of depth len(pattern), and consists of `two_qubit_gate`
    applied to each pair in `pattern` restricted to available connections in `device_graph`.

    Args:
        device_graph: A graph whose nodes are qubits and whose edges represent the possibility of
            doing a two-qubit gate. This combined with the `pattern` argument determines which
            two qubit pairs are activated when.
        pattern: A sequence of `GridInteractionLayer`, each of which has a particular set of
            qubits that are activated simultaneously. These pairs of qubits are deduced by
            combining this argument with `device_graph`.
        two_qubit_gate: The two qubit gate to use in constructing the circuit layers.
    """
    moments = []
    for layer in pattern:
        pairs = sorted(_get_active_pairs(device_graph, layer))
        if len(pairs) == 0:
            continue
        moments += [
            circuits.Moment(two_qubit_gate.on(*pair) for pair in pairs)
        ]
    return circuits.Circuit(moments)
Esempio n. 18
0
def remove_redundant_acquaintance_opportunities(
        strategy: 'cirq.Circuit') -> int:
    """Removes redundant acquaintance opportunities."""

    qubits = sorted(strategy.all_qubits())
    mapping = {q: i for i, q in enumerate(qubits)}

    expose_acquaintance_gates(strategy)
    annotated_strategy = strategy.copy()
    LogicalAnnotator(mapping)(annotated_strategy)

    new_moments: List['cirq.Moment'] = []
    acquaintance_opps: Set[FrozenSet[int]] = set()
    n_removed = 0
    for moment in annotated_strategy:
        new_moment: List['cirq.Operation'] = []
        for op in moment:
            if isinstance(op, AcquaintanceOperation):
                opp = frozenset(cast(Sequence[int], op.logical_indices))
                if opp not in acquaintance_opps:
                    acquaintance_opps.add(opp)
                    new_moment.append(acquaint(*op.qubits))
                else:
                    n_removed += 1
            else:
                new_moment.append(op)
        new_moments.append(circuits.Moment(new_moment))
    strategy._moments = new_moments
    return n_removed
Esempio n. 19
0
def build_entangling_layers(qubits: Sequence[devices.GridQubit],
                            two_qubit_gate: ops.Gate) -> List[circuits.Moment]:
    """Builds a sequence of gates that entangle all pairs of qubits on a grid.

    The qubits are restricted to be physically on a square grid with distinct
    row and column indices (not every node of the grid needs to have a
    qubit). To entangle all pairs of qubits, a user-specified two-qubit gate
    is applied between each and every pair of qubit that are next to each
    other. In general, a total of four sets of parallel operations are needed to
    perform all possible two-qubit gates. We proceed as follows:

    The first layer applies two-qubit gates to qubits (i, j) and (i, j + 1)
    where i is any integer and j is an even integer. The second layer
    applies two-qubit gates to qubits (i, j) and (i + 1, j) where i is an even
    integer and j is any integer. The third layer applies two-qubit gates
    to qubits (i, j) and (i, j + 1) where i is any integer and j is an odd
    integer. The fourth layer applies two-qubit gates to qubits (i, j) and
    (i + 1, j) where i is an odd integer and j is any integer.

    After the layers are built as above, any empty layer is ejected.:

                 Cycle 1:                            Cycle 2:
        q00 ── q01    q02 ── q03            q00    q01    q02    q03
                                             |      |      |      |
        q10 ── q11    q12 ── q13            q10    q11    q12    q13

        q20 ── q21    q22 ── q23            q20    q21    q22    q23
                                             |      |      |      |
        q30 ── q31    q32 ── q33            q30    q31    q32    q33

                  Cycle 3:                           Cycle 4:
        q00    q01 ── q02    q03            q00    q01    q02    q03

        q10    q11 ── q12    q13            q10    q11    q12    q13
                                             |      |      |      |
        q20    q21 ── q22    q23            q20    q21    q22    q23

        q30    q31 ── q32    q33            q30    q31    q32    q33

    Args:
        qubits: The grid qubits included in the entangling operations.
        two_qubit_gate: The two-qubit gate to be applied between all
            neighboring pairs of qubits.

    Returns:
        A list of circuits.Moment, with a maximum length of 4. Each circuits.Moment
        includes two-qubit gates which can be performed at the same time.

    Raises:
        ValueError: two-qubit gate is not used.
    """
    if protocols.num_qubits(two_qubit_gate) != 2:
        raise ValueError('Input must be a two-qubit gate')
    interaction_sequence = _default_interaction_sequence(qubits)
    return [
        circuits.Moment([two_qubit_gate(q_a, q_b) for (q_a, q_b) in pairs])
        for pairs in interaction_sequence
    ]
Esempio n. 20
0
def map_operations(
        circuit: CIRCUIT_TYPE,
        map_func: Callable[[ops.Operation, int], ops.OP_TREE],
        *,
        deep: bool = False,
        raise_if_add_qubits=True,
        tags_to_ignore: Sequence[Hashable] = (),
) -> CIRCUIT_TYPE:
    """Applies local transformations on operations, by calling `map_func(op)` for each op.

    By default, the function assumes `issubset(qubit_set(map_func(op)), op.qubits)` is True.

    Args:
        circuit: Input circuit to apply the transformations on. The input circuit is not mutated.
        map_func: Mapping function from (cirq.Operation, moment_index) to a cirq.OP_TREE. If the
            resulting optree spans more than 1 moment, it's inserted in-place in the same moment as
            `cirq.CircuitOperation(cirq.FrozenCircuit(op_tree)).with_tags(MAPPED_CIRCUIT_OP_TAG)`
            to preserve moment structure. Utility methods like `cirq.unroll_circuit_op` can
            subsequently be used to unroll the mapped circuit operation.
        deep: If true, `map_func` will be recursively applied to circuits wrapped inside
            any circuit operations contained within `circuit`.
        raise_if_add_qubits: Set to True by default. If True, raises ValueError if `map_func(op)`
            adds operations on qubits outside of `op.qubits`.
        tags_to_ignore: Sequence of tags which should be ignored while applying `map_func` on
            tagged operations -- i.e. `map_func(op, idx)` will be called only for operations that
            satisfy `set(op.tags).isdisjoint(tags_to_ignore)`.

    Raises:
          ValueError if `issubset(qubit_set(map_func(op)), op.qubits) is False` and
            `raise_if_add_qubits is True`.

    Returns:
        Copy of input circuit with mapped operations (wrapped in a tagged CircuitOperation).
    """
    def apply_map(op: ops.Operation, idx: int) -> ops.OP_TREE:
        if not set(op.tags).isdisjoint(tags_to_ignore):
            return op
        c = circuits.FrozenCircuit(map_func(op, idx))
        if raise_if_add_qubits and not c.all_qubits().issubset(op.qubits):
            raise ValueError(
                f"Mapped operations {c.all_operations()} should act on a subset "
                f"of qubits of the original operation {op}")
        if len(c) <= 1:
            # Either empty circuit or all operations act in the same moment;
            # So, we don't need to wrap them in a circuit_op.
            return c[0].operations if c else []
        circuit_op = circuits.CircuitOperation(c).with_tags(
            MAPPED_CIRCUIT_OP_TAG)
        return circuit_op

    return map_moments(
        circuit,
        lambda m, i:
        [circuits.Moment(apply_map(op, i) for op in m.operations)],
        deep=deep,
        tags_to_ignore=tags_to_ignore,
    )
Esempio n. 21
0
def test_extension():
    class DummyGate(ops.Gate):
        pass

    optimizer = MergeRotations(extensions=Extensions({
        ops.KnownMatrixGate: {
            DummyGate:
            lambda _: ops.SingleQubitMatrixGate(np.array([[0, 1], [1, 0]]))
        }
    }))

    q = ops.QubitId()
    c = circuits.Circuit([
        circuits.Moment([DummyGate().on(q)]),
    ])
    assert_optimizes(before=c,
                     after=circuits.Circuit([circuits.Moment([ops.X(q)])]),
                     optimizer=optimizer)
Esempio n. 22
0
def test_depolarizer_no_errors():
    q1 = ops.QubitId()
    q2 = ops.QubitId()
    cnot = Job(circuits.Circuit([
        circuits.Moment([ops.CNOT(q1, q2)]),
    ]))
    noerrors = DepolarizerChannel(probability=0.0)

    assert noerrors.transform_job(cnot) == cnot
Esempio n. 23
0
def test_leaves_big():
    m = circuits.DropNegligible(0.001)
    q = ops.QubitId()
    c = circuits.Circuit([circuits.Moment([ops.Z(q)**0.1])])
    assert m.optimization_at(c, 0, c.operation_at(q, 0)) is None

    d = circuits.Circuit(c.moments)
    m.optimize_circuit(d)
    assert d == c
Esempio n. 24
0
 def merge_func(m1: 'cirq.Moment', m2: 'cirq.Moment') -> Optional['cirq.Moment']:
     if not (can_merge_moment(m1) and can_merge_moment(m2)):
         return None
     ret_ops = []
     for q in m1.qubits | m2.qubits:
         mat = protocols.unitary(circuits.Circuit(m.operation_at(q) or [] for m in [m1, m2]))
         gate = single_qubit_decompositions.single_qubit_matrix_to_phxz(mat, atol)
         if gate:
             ret_ops.append(gate(q))
     return circuits.Moment(ret_ops)
Esempio n. 25
0
def cubic_acquaintance_strategy(
    qubits: Iterable['cirq.Qid'], swap_gate: 'cirq.Gate' = ops.SWAP
) -> 'cirq.Circuit':
    """Acquaints every triple of qubits.

    Exploits the fact that in a simple linear swap network every pair of
    logical qubits that starts at distance two remains so (except temporarily
    near the edge), and that every third one `goes through` the pair at some
    point in the network. The strategy then iterates through a series of
    mappings in which qubits i and i + k are placed at distance two, for k = 1
    through n / 2. Linear swap networks are used in between to effect the
    permutation.
    """

    qubits = tuple(qubits)
    n_qubits = len(qubits)

    swap_gate = SwapPermutationGate(swap_gate)

    moments = []
    index_order = tuple(range(n_qubits))
    max_separation = max(((n_qubits - 1) // 2) + 1, 2)
    for separation in range(1, max_separation):
        stepped_indices_concatenated = tuple(
            itertools.chain(*(range(offset, n_qubits, separation) for offset in range(separation)))
        )
        new_index_order = skip_and_wrap_around(stepped_indices_concatenated)
        permutation = {i: new_index_order.index(j) for i, j in enumerate(index_order)}
        permutation_gate = LinearPermutationGate(n_qubits, permutation, swap_gate)
        moments.append(circuits.Moment([permutation_gate(*qubits)]))
        for i in range(n_qubits + 1):
            for offset in range(3):
                moment = circuits.Moment(
                    acquaint(*qubits[j : j + 3]) for j in range(offset, n_qubits - 2, 3)
                )
                moments.append(moment)
            if i < n_qubits:
                moment = circuits.Moment(
                    swap_gate(*qubits[j : j + 2]) for j in range(i % 2, n_qubits - 1, 2)
                )
                moments.append(moment)
        index_order = new_index_order[::-1]
    return circuits.Circuit(moments)
Esempio n. 26
0
    def new_layer(self, previous_single_qubit_layer: 'cirq.Moment') -> 'cirq.Moment':
        def random_gate(qubit: 'cirq.Qid') -> 'cirq.Gate':
            excluded_op = previous_single_qubit_layer.operation_at(qubit)
            excluded_gate = excluded_op.gate if excluded_op is not None else None
            g = self.single_qubit_gates[self.prng.randint(0, len(self.single_qubit_gates))]
            while g is excluded_gate:
                g = self.single_qubit_gates[self.prng.randint(0, len(self.single_qubit_gates))]
            return g

        return circuits.Moment(random_gate(q).on(q) for q in self.qubits)
Esempio n. 27
0
 def map_func(m: 'cirq.Moment', _) -> Sequence['cirq.Moment']:
     stratified_ops: List[List['cirq.Operation']] = [[] for _ in range(num_categories)]
     for op in m:
         if set(op.tags) & set(context.tags_to_ignore):
             stratified_ops[0].append(op)
             continue
         for i, classifier in enumerate(classifiers):
             if classifier(op):
                 stratified_ops[i + 1].append(op)
                 break
     return [circuits.Moment(op_list) for op_list in stratified_ops]
Esempio n. 28
0
def parameterize_circuit(
        circuit: 'cirq.Circuit',
        options: XEBCharacterizationOptions) -> 'cirq.Circuit':
    """Parameterize PhasedFSim-like gates in a given circuit according to
    `phased_fsim_options`.
    """
    gate = options.get_parameterized_gate()
    return circuits.Circuit(
        circuits.Moment(
            gate.on(*op.qubits) if options.should_parameterize(op) else op
            for op in moment.operations) for moment in circuit.moments)
Esempio n. 29
0
def test_clears_known_empties_even_at_zero_tolerance():
    m = circuits.DropNegligible(0.001)
    q = ops.QubitId()
    q2 = ops.QubitId()
    c = circuits.Circuit.from_ops(
        ops.Z(q)**0,
        ops.Y(q)**0.0000001,
        ops.X(q)**-0.0000001,
        ops.CZ(q, q2)**0)

    m.optimize_circuit(c)
    assert c == circuits.Circuit([circuits.Moment()] * 4)
Esempio n. 30
0
 def noisy_moment(self, moment: 'cirq.Moment',
                  system_qubits: Sequence['cirq.Qid']):
     if self.is_virtual_moment(moment):
         return moment
     if validate_all_measurements(moment):
         return [
             circuits.Moment(
                 self.readout_noise_gate(q).with_tags(ops.VirtualTag())
                 for q in system_qubits),
             moment,
         ]
     return moment