Exemple #1
0
def test_per_qubit_readout_error_from_data():
    # Generate the readout error noise model from calibration data.
    calibration = cirq.google.Calibration(_CALIBRATION_DATA)
    noise_model = simple_noise_from_calibration_metrics(
        calibration=calibration, readout_error_noise=True)

    # Create the circuit and apply the noise model.
    qubits = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(1, 0)]
    program = cirq.Circuit(
        cirq.Moment([cirq.H(qubits[0])]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[1])]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[2])]),
        cirq.Moment([
            cirq.measure(qubits[0], key='q0'),
            cirq.measure(qubits[1], key='q1'),
            cirq.measure(qubits[2], key='q2')
        ]))
    noisy_circuit = cirq.Circuit(noise_model.noisy_moments(program, qubits))

    # Insert channels explicitly to construct expected output.
    expected_program = cirq.Circuit(
        cirq.Moment([cirq.H(qubits[0])]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[1])]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[2])]),
        cirq.Moment([
            cirq.BitFlipChannel(0.004).on(qubits[0]),
            cirq.BitFlipChannel(0.005).on(qubits[1]),
            cirq.BitFlipChannel(0.006).on(qubits[2])
        ]),
        cirq.Moment([
            cirq.measure(qubits[0], key='q0'),
            cirq.measure(qubits[1], key='q1'),
            cirq.measure(qubits[2], key='q2')
        ]))
    _assert_equivalent_op_tree(expected_program, noisy_circuit)
def test_per_qubit_combined_noise_from_data():
    # Generate the combined noise model from calibration data.
    calibration = cirq_google.Calibration(_CALIBRATION_DATA)
    noise_model = simple_noise_from_calibration_metrics(
        calibration=calibration,
        depol_noise=True,
        readout_error_noise=True,
        readout_decay_noise=True,
    )

    # Create the circuit and apply the noise model.
    qubits = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(1, 0)]
    program = cirq.Circuit(
        cirq.Moment([cirq.H(qubits[0])]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[1])]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[2])]),
        cirq.Moment([
            cirq.measure(qubits[0], key='q0'),
            cirq.measure(qubits[1], key='q1'),
            cirq.measure(qubits[2], key='q2'),
        ]),
    )
    noisy_circuit = cirq.Circuit(noise_model.noisy_moments(program, qubits))

    # Insert channels explicitly to construct expected output.
    decay_prob = [
        1 - exp(-1 / 0.007), 1 - exp(-1 / 0.008), 1 - exp(-1 / 0.009)
    ]
    expected_program = cirq.Circuit(
        cirq.Moment([cirq.H(qubits[0])]),
        cirq.Moment([cirq.DepolarizingChannel(DEPOL_001).on(qubits[0])]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[1])]),
        cirq.Moment([
            cirq.DepolarizingChannel(DEPOL_001).on(qubits[0]),
            cirq.DepolarizingChannel(DEPOL_002).on(qubits[1]),
        ]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[2])]),
        cirq.Moment([
            cirq.DepolarizingChannel(DEPOL_001).on(qubits[0]),
            cirq.DepolarizingChannel(DEPOL_003).on(qubits[2]),
        ]),
        cirq.Moment([
            cirq.AmplitudeDampingChannel(decay_prob[i]).on(qubits[i])
            for i in range(3)
        ]),
        cirq.Moment([
            cirq.BitFlipChannel(0.004).on(qubits[0]),
            cirq.BitFlipChannel(0.005).on(qubits[1]),
            cirq.BitFlipChannel(0.006).on(qubits[2]),
        ]),
        cirq.Moment([
            cirq.measure(qubits[0], key='q0'),
            cirq.measure(qubits[1], key='q1'),
            cirq.measure(qubits[2], key='q2'),
        ]),
    )
    assert_equivalent_op_tree(expected_program, noisy_circuit)
Exemple #3
0
def test_readout_noise_after_moment():
    program = cirq.Circuit()
    qubits = cirq.LineQubit.range(3)
    program.append([
        cirq.H(qubits[0]),
        cirq.CNOT(qubits[0], qubits[1]),
        cirq.CNOT(qubits[1], qubits[2])
    ])
    program.append(
        [
            cirq.measure(qubits[0], key='q0'),
            cirq.measure(qubits[1], key='q1'),
            cirq.measure(qubits[2], key='q2'),
        ],
        strategy=cirq.InsertStrategy.NEW_THEN_INLINE,
    )

    # Use noise model to generate circuit
    depol_noise = ccn.DepolarizingNoiseModel(depol_prob=0.01)
    readout_noise = ccn.ReadoutNoiseModel(bitflip_prob=0.05)
    noisy_circuit = cirq.Circuit(depol_noise.noisy_moments(program, qubits))
    noisy_circuit = cirq.Circuit(
        readout_noise.noisy_moments(noisy_circuit, qubits))

    # Insert channels explicitly
    true_noisy_program = cirq.Circuit()
    true_noisy_program.append([cirq.H(qubits[0])])
    true_noisy_program.append(
        [
            cirq.DepolarizingChannel(0.01).on(q).with_tags(ops.VirtualTag())
            for q in qubits
        ],
        strategy=cirq.InsertStrategy.NEW_THEN_INLINE,
    )
    true_noisy_program.append([cirq.CNOT(qubits[0], qubits[1])])
    true_noisy_program.append(
        [
            cirq.DepolarizingChannel(0.01).on(q).with_tags(ops.VirtualTag())
            for q in qubits
        ],
        strategy=cirq.InsertStrategy.NEW_THEN_INLINE,
    )
    true_noisy_program.append([cirq.CNOT(qubits[1], qubits[2])])
    true_noisy_program.append(
        [
            cirq.DepolarizingChannel(0.01).on(q).with_tags(ops.VirtualTag())
            for q in qubits
        ],
        strategy=cirq.InsertStrategy.NEW_THEN_INLINE,
    )
    true_noisy_program.append([
        cirq.BitFlipChannel(0.05).on(q).with_tags(ops.VirtualTag())
        for q in qubits
    ])
    true_noisy_program.append([
        cirq.measure(qubits[0], key='q0'),
        cirq.measure(qubits[1], key='q1'),
        cirq.measure(qubits[2], key='q2'),
    ])
    assert_equivalent_op_tree(true_noisy_program, noisy_circuit)
Exemple #4
0
 def noisy_moment(self, moment: cirq.Moment,
                  system_qubits: Sequence[cirq.Qid]) -> cirq.OP_TREE:
     if self.is_virtual_moment(moment):
         return moment
     moments = []
     if validate_all_measurements(moment):
         if self.decay_probs:
             moments.append(
                 cirq.Moment(
                     cirq.AmplitudeDampingChannel(self.decay_probs[q])(q)
                     for q in system_qubits))
         if self.bitflip_probs:
             moments.append(
                 cirq.Moment(
                     cirq.BitFlipChannel(self.bitflip_probs[q])(q)
                     for q in system_qubits))
         moments.append(moment)
         return moments
     else:
         moments.append(moment)
         if self.depol_probs:
             gated_qubits = [
                 q for q in system_qubits
                 if moment.operates_on_single_qubit(q)
             ]
             if gated_qubits:
                 moments.append(
                     cirq.Moment(
                         cirq.DepolarizingChannel(self.depol_probs[q])(q)
                         for q in gated_qubits))
         return moments
def test_apply_mixture():
    q0 = cirq.LineQubit(0)
    state = Mock()
    args = cirq.StabilizerSimulationState(state=state, qubits=[q0])

    for _ in range(100):
        assert args._strat_apply_mixture(cirq.BitFlipChannel(0.5),
                                         [q0]) is True
    state.apply_x.assert_called_with(0, 1.0, 0.0)
    assert 10 < state.apply_x.call_count < 90
Exemple #6
0
def test_aggregate_decay_noise_after_moment():
    program = cirq.Circuit()
    qubits = cirq.LineQubit.range(3)
    program.append([
        cirq.H(qubits[0]),
        cirq.CNOT(qubits[0], qubits[1]),
        cirq.CNOT(qubits[1], qubits[2])
    ])
    program.append(
        [
            cirq.measure(qubits[0], key='q0'),
            cirq.measure(qubits[1], key='q1'),
            cirq.measure(qubits[2], key='q2'),
        ],
        strategy=cirq.InsertStrategy.NEW_THEN_INLINE,
    )

    # Use noise model to generate circuit
    noise_model = ccn.DepolarizingWithDampedReadoutNoiseModel(
        depol_prob=0.01, decay_prob=0.02, bitflip_prob=0.05)
    noisy_circuit = cirq.Circuit(noise_model.noisy_moments(program, qubits))

    # Insert channels explicitly
    true_noisy_program = cirq.Circuit()
    true_noisy_program.append([cirq.H(qubits[0])])
    true_noisy_program.append(
        [cirq.DepolarizingChannel(0.01).on(q) for q in qubits],
        strategy=cirq.InsertStrategy.NEW_THEN_INLINE,
    )
    true_noisy_program.append([cirq.CNOT(qubits[0], qubits[1])])
    true_noisy_program.append(
        [cirq.DepolarizingChannel(0.01).on(q) for q in qubits],
        strategy=cirq.InsertStrategy.NEW_THEN_INLINE,
    )
    true_noisy_program.append([cirq.CNOT(qubits[1], qubits[2])])
    true_noisy_program.append(
        [cirq.DepolarizingChannel(0.01).on(q) for q in qubits],
        strategy=cirq.InsertStrategy.NEW_THEN_INLINE,
    )
    true_noisy_program.append(
        [cirq.AmplitudeDampingChannel(0.02).on(q) for q in qubits])
    true_noisy_program.append(
        [cirq.BitFlipChannel(0.05).on(q) for q in qubits])
    true_noisy_program.append([
        cirq.measure(qubits[0], key='q0'),
        cirq.measure(qubits[1], key='q1'),
        cirq.measure(qubits[2], key='q2'),
    ])
    assert_equivalent_op_tree(true_noisy_program, noisy_circuit)
Exemple #7
0
def get_supported_channels():
    """A helper to get the channels that are supported in TFQ.

    Returns a dictionary mapping from supported channel types
    to number of qubits.
    """
    # Add new channels here whenever additional support is needed.
    channel_mapping = dict()
    channel_mapping[cirq.DepolarizingChannel(0.01)] = 1
    channel_mapping[cirq.AsymmetricDepolarizingChannel(0.01, 0.02, 0.03)] = 1
    channel_mapping[cirq.GeneralizedAmplitudeDampingChannel(0.01, 0.02)] = 1
    channel_mapping[cirq.AmplitudeDampingChannel(0.01)] = 1
    channel_mapping[cirq.ResetChannel()] = 1
    channel_mapping[cirq.PhaseDampingChannel(0.01)] = 1
    channel_mapping[cirq.PhaseFlipChannel(0.01)] = 1
    channel_mapping[cirq.BitFlipChannel(0.01)] = 1

    return channel_mapping
Exemple #8
0
def test_bit_flip_channel_repr():
    cirq.testing.assert_equivalent_repr(cirq.BitFlipChannel(0.3))
Exemple #9
0
    with pytest.raises(ValueError) as e:
        cirq.read_json(buffer)
    assert e.match("Could not resolve type 'MyCustomClass' "
                   "during deserialization")


QUBITS = cirq.LineQubit.range(5)
Q0, Q1, Q2, Q3, Q4 = QUBITS

TEST_OBJECTS = {
    'AmplitudeDampingChannel':
    cirq.AmplitudeDampingChannel(0.5),
    'AsymmetricDepolarizingChannel':
    cirq.AsymmetricDepolarizingChannel(0.1, 0.2, 0.3),
    'BitFlipChannel':
    cirq.BitFlipChannel(0.5),
    'Bristlecone':
    cirq.google.Bristlecone,
    'CCNOT':
    cirq.CCNOT,
    'CCX':
    cirq.CCX,
    'CCXPowGate':
    cirq.CCXPowGate(exponent=0.123, global_shift=0.456),
    'CCZ':
    cirq.CCZ,
    'CCZPowGate':
    cirq.CCZPowGate(exponent=0.123, global_shift=0.456),
    'CNOT':
    cirq.CNOT,
    'CNotPowGate':
Exemple #10
0
 def __init__(self, depol_prob: float, bitflip_prob: float,
              decay_prob: float):
     self.qubit_noise_gate = cirq.DepolarizingChannel(depol_prob)
     self.readout_noise_gate = cirq.BitFlipChannel(bitflip_prob)
     self.readout_decay_gate = cirq.AmplitudeDampingChannel(decay_prob)
Exemple #11
0
    a, b = cirq.LineQubit.range(2)
    c, _ = cirq_circuit_to_stim_data(
        cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b),
                     cirq.reset(a)))
    assert (str(c).strip() == """
H 0
CX 0 1
M 0 1
R 0
    """.strip())


@pytest.mark.parametrize(
    "gate",
    [
        cirq.BitFlipChannel(0.1),
        cirq.BitFlipChannel(0.2),
        cirq.PhaseFlipChannel(0.1),
        cirq.PhaseFlipChannel(0.2),
        cirq.PhaseDampingChannel(0.1),
        cirq.PhaseDampingChannel(0.2),
        cirq.X.with_probability(0.1),
        cirq.X.with_probability(0.2),
        cirq.Y.with_probability(0.1),
        cirq.Y.with_probability(0.2),
        cirq.Z.with_probability(0.1),
        cirq.Z.with_probability(0.2),
        cirq.DepolarizingChannel(0.1),
        cirq.DepolarizingChannel(0.2),
        cirq.DepolarizingChannel(0.1, n_qubits=2),
        cirq.DepolarizingChannel(0.2, n_qubits=2),
Exemple #12
0
    def __init__(self, n, J, J_max, L, T):
        """Generate a circuit for compressed quantum simulation of the Ising
        model in the 1D case using a 1D non-circular arrangement of qubits,
        which will allow the hamiltonian to be compressed via matchgates.

        Args:
            n: The num of qubits to be evolved to a state J
            J: State of the magnetization, ratio of interaction strength and
               external field strength
            J_max: The maximium J value for evolution
            L: The number of steps
            T: The time of evolution

        Returns: circuit for compressed Ising simulation

        For L = 2000 and T = 100, the circuit should produce very accurate
        values.  However, it makes for very slow runtimes, so we've been using
        L = 200 and T = 10 which Kraus claimed to produce decent enough
        results.
        """
        self.dt = T / (L + 1)
        self.m = int(np.log2(n)) + 1
        self.qubits = cirq.LineQubit.range(self.m)
        self.circuit = cirq.Circuit()

        # Initial states - H and S gates are for |+>(Y) state, bit flip is for
        # mixed state
        self.circuit.append([cirq.H(self.qubits[self.m - 1])])
        self.circuit.append([cirq.S(self.qubits[self.m - 1])])

        bit_flip = cirq.BitFlipChannel(0.5)
        for i in range(0, self.m - 1):
            self.circuit.append([bit_flip.on(self.qubits[i])])

        # LJ determines the number of adiabatic steps to take
        self.LJ = int(J * L / J_max)
        for l in range(0, self.LJ):
            Jl = J_max * l / L

            # Rotate qubit m
            R0l = R0(-4 * self.dt)
            self.circuit.append([R0l.on(self.qubits[self.m - 1])])

            # shift qubit states up so the rotation matrix Rl acts on the
            # states correctly
            shiftu = SHIFTU(self.m)
            self.circuit.append(shiftu(*self.qubits))

            # application of Rl, a rotation matrix on the whole state
            # phi_l is the angle
            # We apply the rotation gate (r) to the pair of states we care
            # about (they are on qubit m after shifting)
            phi_l = 2 * Jl * self.dt
            r = cirq.SingleQubitMatrixGate(
                np.array([[np.cos(phi_l), -np.sin(phi_l)],
                          [np.sin(phi_l), np.cos(phi_l)]]))
            self.circuit.append([r.on(self.qubits[self.m - 1])])
            # We then apply a controlled inverse of (r), with all the other
            # qubits as controls This effectively gives us our desired Rl on
            # the wavefunction
            controls = self.qubits[0:self.m - 1]
            Cr = cirq.ControlledGate(sub_gate=(r**-1), control_qubits=controls)
            self.circuit.append(Cr.on(self.qubits[self.m - 1]))

            # Shift back down for R0 to work correctly
            shiftd = SHIFTD(self.m)
            self.circuit.append(shiftd(*self.qubits))

        # these are applied for measurement of Y on qubit self.m
        self.circuit.append([cirq.S(self.qubits[self.m - 1])**-1])
        self.circuit.append([cirq.H(self.qubits[self.m - 1])])
def test_apply_gate():
    q0, q1 = cirq.LineQubit.range(2)
    state = Mock()
    args = cirq.StabilizerSimulationState(state=state, qubits=[q0, q1])

    assert args._strat_apply_gate(cirq.X, [q0]) is True
    state.apply_x.assert_called_with(0, 1.0, 0.0)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.X**2, [q0]) is True
    state.apply_x.assert_called_with(0, 2.0, 0.0)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.X**sympy.Symbol('t'),
                                  [q0]) is NotImplemented
    state.apply_x.assert_not_called()

    state.reset_mock()
    assert args._strat_apply_gate(cirq.XPowGate(exponent=2, global_shift=1.3),
                                  [q1]) is True
    state.apply_x.assert_called_with(1, 2.0, 1.3)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.X**1.4, [q0]) == NotImplemented
    state.apply_x.assert_not_called()

    state.reset_mock()
    assert args._strat_apply_gate(cirq.Y, [q0]) is True
    state.apply_y.assert_called_with(0, 1.0, 0.0)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.Z, [q0]) is True
    state.apply_z.assert_called_with(0, 1.0, 0.0)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.H, [q0]) is True
    state.apply_h.assert_called_with(0, 1.0, 0.0)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.CX, [q0, q1]) is True
    state.apply_cx.assert_called_with(0, 1, 1.0, 0.0)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.CX, [q1, q0]) is True
    state.apply_cx.assert_called_with(1, 0, 1.0, 0.0)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.CZ, [q0, q1]) is True
    state.apply_cz.assert_called_with(0, 1, 1.0, 0.0)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.GlobalPhaseGate(1j), []) is True
    state.apply_global_phase.assert_called_with(1j)

    state.reset_mock()
    assert args._strat_apply_gate(cirq.GlobalPhaseGate(sympy.Symbol('t')),
                                  []) is NotImplemented
    state.apply_global_phase.assert_not_called()

    state.reset_mock()
    assert args._strat_apply_gate(cirq.SWAP, [q0, q1]) is True
    state.apply_cx.assert_has_calls(
        [call(0, 1), call(1, 0, 1.0, 0.0),
         call(0, 1)])

    state.reset_mock()
    assert args._strat_apply_gate(
        cirq.SwapPowGate(exponent=2, global_shift=1.3), [q0, q1]) is True
    state.apply_cx.assert_has_calls(
        [call(0, 1), call(1, 0, 2.0, 1.3),
         call(0, 1)])

    state.reset_mock()
    assert args._strat_apply_gate(cirq.BitFlipChannel(0.5),
                                  [q0]) == NotImplemented
    state.apply_x.assert_not_called()