Beispiel #1
0
def test_reset():
    a, b = cirq.LineQubit.range(2)
    c = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.reset(a), cirq.reset(b))
    output = cirq.QasmOutput(
        c.all_operations(),
        tuple(sorted(c.all_qubits())),
        header='Generated from Cirq!',
        precision=5,
    )
    assert (str(output).strip() == """
// Generated from Cirq!

OPENQASM 2.0;
include "qelib1.inc";


// Qubits: [0, 1]
qreg q[2];


h q[0];
cx q[0],q[1];
reset q[0];
reset q[1];
    """.strip())
Beispiel #2
0
def test_reset():
    q = cirq.LineQubit(0)
    c = cirq.Circuit(cirq.X(q), cirq.reset(q), cirq.measure(q, key="out"))
    assert cirq.CliffordSimulator().sample(c)["out"][0] == 0
    c = cirq.Circuit(cirq.H(q), cirq.reset(q), cirq.measure(q, key="out"))
    assert cirq.CliffordSimulator().sample(c)["out"][0] == 0
    c = cirq.Circuit(cirq.reset(q), cirq.measure(q, key="out"))
    assert cirq.CliffordSimulator().sample(c)["out"][0] == 0
def test_reset():
    q = cirq.LineQubit(0)
    simulator = ccq.mps_simulator.MPSSimulator()
    c = cirq.Circuit(cirq.X(q), cirq.reset(q), cirq.measure(q))
    assert simulator.sample(c)['q(0)'][0] == 0
    c = cirq.Circuit(cirq.H(q), cirq.reset(q), cirq.measure(q))
    assert simulator.sample(c)['q(0)'][0] == 0
    c = cirq.Circuit(cirq.reset(q), cirq.measure(q))
    assert simulator.sample(c)['q(0)'][0] == 0
def test_reset(split):
    q = cirq.LineQubit(0)
    c = cirq.Circuit(cirq.X(q), cirq.reset(q), cirq.measure(q, key="out"))
    sim = cirq.CliffordSimulator(split_untangled_states=split)
    assert sim.sample(c)["out"][0] == 0
    c = cirq.Circuit(cirq.H(q), cirq.reset(q), cirq.measure(q, key="out"))
    assert sim.sample(c)["out"][0] == 0
    c = cirq.Circuit(cirq.reset(q), cirq.measure(q, key="out"))
    assert sim.sample(c)["out"][0] == 0
def test_reset():
    q = cirq.LineQubit(0)
    sampler = cirq.StabilizerSampler()
    c = cirq.Circuit(cirq.X(q), cirq.reset(q), cirq.measure(q))
    assert sampler.sample(c)['q(0)'][0] == 0
    c = cirq.Circuit(cirq.H(q), cirq.reset(q), cirq.measure(q))
    assert sampler.sample(c)['q(0)'][0] == 0
    c = cirq.Circuit(cirq.reset(q), cirq.measure(q))
    assert sampler.sample(c)['q(0)'][0] == 0
Beispiel #6
0
def _represent_operation_with_amplitude_damping_noise(
    ideal_operation: Circuit,
    noise_level: float,
) -> OperationRepresentation:
    r"""Returns the quasi-probability representation of the input
    single-qubit ``ideal_operation`` with respect to a basis of noisy
    operations.

    Any ideal single-qubit unitary followed by local amplitude-damping noise
    of equal ``noise_level`` is assumed to be in the basis of implementable
    operations.

    The representation is based on the analytical result presented
    in :cite:`Takagi2020`.

    Args:
        ideal_operation: The ideal operation (as a QPROGRAM) to represent.
        noise_level: The noise level of each amplitude damping channel.

    Returns:
        The quasi-probability representation of the ``ideal_operation``.

    .. note::
        The input ``ideal_operation`` is typically a QPROGRAM with a single
        gate but could also correspond to a sequence of more gates.
        This is possible as long as the unitary associated to the input
        QPROGRAM, followed by a single final amplitude damping channel, is
        physically implementable.

    .. note::
        The input ``ideal_operation`` must be a ``cirq.Circuit``.
    """

    if not isinstance(ideal_operation, Circuit):
        raise NotImplementedError(
            "The input ideal_operation must be a cirq.Circuit.", )

    qubits = ideal_operation.all_qubits()

    if len(qubits) == 1:
        q = tuple(qubits)[0]

        eta_0 = (1 + np.sqrt(1 - noise_level)) / (2 * (1 - noise_level))
        eta_1 = (1 - np.sqrt(1 - noise_level)) / (2 * (1 - noise_level))
        eta_2 = -noise_level / (1 - noise_level)
        etas = [eta_0, eta_1, eta_2]
        post_ops = [[], Z(q), reset(q)]

    else:
        raise ValueError(  # pragma: no cover
            "Only single-qubit operations are supported."  # pragma: no cover
        )  # pragma: no cover

    # Basis of implementable operations as circuits
    imp_op_circuits = [ideal_operation + Circuit(op) for op in post_ops]

    # Build basis_expantion
    expansion = {NoisyOperation(c): a for c, a in zip(imp_op_circuits, etas)}

    return OperationRepresentation(ideal_operation, expansion)
Beispiel #7
0
def build_circuit(qubits, params):
    """
    Constructs a circuit representing a single timestep of quantum stuff.
    params is a list of 6 lists, each containing nqubits floats in [0, 1).
    These parameterize the circuit, such that each operation is performed
    only if its relevant parameter is >= 0.5.

    In order, we check the parameters, and if they are big enough we:
    -Set each qubit to zero.
    -Apply a CNOT gate between this qubit and its right neighbour.
    -Apply H, then S, then T gates.
    -Measure in the Z basis.

    Returns the constructed circuit.
    """
    circuit = cirq.Circuit()

    circuit.append(
        cirq.reset(q) for q, p in zip(qubits, params[0]) if p >= 0.5)

    for qi, q in enumerate(qubits[:-1]):
        if params[1][qi] >= 0.5:
            circuit.append(cirq.CNOT(q, qubits[qi + 1]))

    circuit.append(cirq.H(q) for q, p in zip(qubits, params[2]) if p >= 0.5)
    circuit.append(cirq.S(q) for q, p in zip(qubits, params[3]) if p >= 0.5)
    circuit.append(cirq.T(q) for q, p in zip(qubits, params[4]) if p >= 0.5)
    circuit.append(
        cirq.measure(q) for q, p in zip(qubits, params[5]) if p >= 0.5)

    return circuit
Beispiel #8
0
def test_run_reset(dtype):
    q0, q1 = cirq.LineQid.for_qid_shape((2, 3))
    simulator = cirq.Simulator(dtype=dtype)
    circuit = cirq.Circuit(
        cirq.H(q0),
        PlusGate(3, 2)(q1),
        cirq.reset(q0),
        cirq.measure(q0, key='m0'),
        cirq.measure(q1, key='m1a'),
        cirq.reset(q1),
        cirq.measure(q1, key='m1b'),
    )
    meas = simulator.run(circuit, repetitions=100).measurements
    assert np.array_equal(meas['m0'], np.zeros((100, 1)))
    assert np.array_equal(meas['m1a'], np.full((100, 1), 2))
    assert np.array_equal(meas['m1b'], np.zeros((100, 1)))
Beispiel #9
0
def test_sim_state_instance_unchanged_during_normal_sim(split: bool):
    sim = SplittableCountingSimulator(split_untangled_states=split)
    state = sim._create_simulation_state(0, (q0, q1))
    circuit = cirq.Circuit(cirq.H(q0), cirq.CNOT(q0, q1), cirq.reset(q1))
    for step in sim.simulate_moment_steps(circuit, initial_state=state):
        assert step._sim_state is state
        assert (step._merged_sim_state is not state) == split
Beispiel #10
0
def test_reset_causes_split():
    args = create_container(qs2)
    args.apply_operation(cirq.CNOT(q0, q1))
    assert len(set(args.values())) == 2
    args.apply_operation(cirq.reset(q0))
    assert len(set(args.values())) == 3
    assert args[q0] is not args[q1]
    assert args[q0] is not args[None]
Beispiel #11
0
def test_reset_does_not_split_if_disabled():
    args = create_container(qs2, False)
    args.apply_operation(cirq.CNOT(q0, q1))
    assert len(set(args.values())) == 1
    args.apply_operation(cirq.reset(q0))
    assert len(set(args.values())) == 1
    assert args[q1] is args[q0]
    assert args[None] is args[q0]
def test_reset_channel():
    r = cirq.reset(cirq.LineQubit(0))
    np.testing.assert_almost_equal(
        cirq.channel(r),
        (np.array([[1., 0.], [0., 0]]), np.array([[0., 1.], [0., 0.]])))
    assert cirq.has_channel(r)
    assert not cirq.has_mixture(r)
    assert cirq.qid_shape(r) == (2, )

    r = cirq.reset(cirq.LineQid(0, dimension=3))
    np.testing.assert_almost_equal(
        cirq.channel(r),
        (np.array([[1, 0, 0], [0, 0, 0], [0, 0, 0]]),
         np.array([[0, 1, 0], [0, 0, 0], [0, 0, 0]]),
         np.array([[0, 0, 1], [0, 0, 0], [0, 0, 0]])))  # yapf: disable
    assert cirq.has_channel(r)
    assert not cirq.has_mixture(r)
    assert cirq.qid_shape(r) == (3, )
Beispiel #13
0
def test_sim_state_instance_gets_changes_from_step_result(split: bool):
    sim = SplittableCountingSimulator(split_untangled_states=split)
    args = sim._create_act_on_args(0, (q0, q1))
    circuit = cirq.Circuit(cirq.H(q0), cirq.CNOT(q0, q1), cirq.reset(q1))
    for step in sim.simulate_moment_steps(circuit, initial_state=args):
        assert step._sim_state is args
        args = sim._create_act_on_args(0, (q0, q1))
        step._sim_state = args
        assert (step._merged_sim_state is not args) == split
Beispiel #14
0
def qdc_step(HS_step_f: Callable[[float], cirq.Circuit],
             coupl_step_f: Callable[[float, float], cirq.Circuit],
             epsilon: float,
             gamma: float,
             t: float,
             qdc_trotter_number: int,
             HS_trotter_factor: int = 1) -> cirq.Circuit:
    '''
    Circuit implementing a generic 2nd-order trotterized QDC step.
    Typical parameters of QDC steps are indicated below.

    Args:
        HS_step_f (`function(dt)`): function returning cirq.Circuit for a
        2nd order trotter step of the system evolution.
        coupl_step_f (`function(gamma, dt)`): function returning the
            cirq.Circuit for a 1st oder trotter step of evolution genetated by
            the system-fridge coupling.
        epsilon: fridge energy
        gamma: coupling strength
        t: coupling time
        qdc_trotter_number: steps for coupling+hamiltonian 2nd order Trotter
            simulation
        HS_trotter_factor: multiplicative factor for number of Trotter steps
            employed for the system evolution Hamiltonian simulation.

    Returns:
        Circuit of the cooling step. Includes final fridge reset.

    ---

    Typical parameters:
        weak coupling:
            epsilon = E_transition
            t >> E_transition
            gamma = pi / t
            trotter_steps >= 2 sqrt(1 + (E_transition + E_max)^2 /
                                        (2 * gamma)^2 ) 
        bang-bang (Ramsey) strong coupling:
            epsilon = e_transition
            t = pi / (2 * E_transition)
            gamma = 2 e_transition
            trotter_steps = 1
    '''
    dt = t / qdc_trotter_number
    coupl_halfstep = coupl_step_f(gamma, dt / 2)
    c = cirq.Circuit([
        coupl_halfstep,
        [HS_step_f(dt / HS_trotter_factor)] * HS_trotter_factor,
        cirq.ZPowGate(exponent=(-dt * epsilon / np.pi))(FRIDGE),
        coupl_halfstep,
    ]) * qdc_trotter_number
    c.append(cirq.reset(FRIDGE))
    return c
def test_reset_channel():
    r = cirq.reset(cirq.LineQubit(0))
    np.testing.assert_almost_equal(
        cirq.kraus(r),
        (np.array([[1.0, 0.0], [0.0, 0]]), np.array([[0.0, 1.0], [0.0, 0.0]])))
    cirq.testing.assert_consistent_channel(r)
    assert not cirq.has_mixture(r)

    assert cirq.num_qubits(r) == 1
    assert cirq.qid_shape(r) == (2, )

    r = cirq.reset(cirq.LineQid(0, dimension=3))
    np.testing.assert_almost_equal(
        cirq.kraus(r),
        (
            np.array([[1, 0, 0], [0, 0, 0], [0, 0, 0]]),
            np.array([[0, 1, 0], [0, 0, 0], [0, 0, 0]]),
            np.array([[0, 0, 1], [0, 0, 0], [0, 0, 0]]),
        ),
    )  # yapf: disable
    cirq.testing.assert_consistent_channel(r)
    assert not cirq.has_mixture(r)
    assert cirq.qid_shape(r) == (3, )
Beispiel #16
0
def test_more_unitary_gate_conversions():
    for p in [1, 1j, -1, -1j]:
        assert_unitary_gate_converts_correctly(p *
                                               cirq.DensePauliString("IXYZ"))
        assert_unitary_gate_converts_correctly(
            (p * cirq.DensePauliString("IXYZ")).controlled(1))

    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())
Beispiel #17
0
def test_simulate_moment_steps_qudits(dtype):
    q0, q1 = cirq.LineQid.for_qid_shape((2, 3))
    circuit = cirq.Circuit(
        PlusGate(2, 1)(q0),
        PlusGate(3, 1)(q1),
        cirq.reset(q1),
        PlusGate(3, 1)(q1),
    )
    simulator = cirq.DensityMatrixSimulator(dtype=dtype)
    for i, step in enumerate(simulator.simulate_moment_steps(circuit)):
        assert cirq.qid_shape(step) == (2, 3)
        if i == 0:
            np.testing.assert_almost_equal(step.density_matrix(), np.diag([0, 0, 0, 0, 1, 0]))
        elif i == 1:
            np.testing.assert_almost_equal(step.density_matrix(), np.diag([0, 0, 0, 1, 0, 0]))
        else:
            np.testing.assert_almost_equal(step.density_matrix(), np.diag([0, 0, 0, 0, 1, 0]))
Beispiel #18
0
def _get_noise_proto_pairs():
    q0 = cirq.GridQubit(0, 0)

    pairs = [
        # Depolarization.
        (cirq.Circuit(cirq.depolarize(p=0.3)(q0)),
         _build_op_proto("DP", ['p'], [0.3], ['0_0'])),

        # Asymmetric depolarization.
        (cirq.Circuit(
            cirq.asymmetric_depolarize(p_x=0.1, p_y=0.2, p_z=0.3)(q0)),
         _build_op_proto("ADP", ['p_x', 'p_y', 'p_z'], [0.1, 0.2, 0.3],
                         ['0_0'])),

        # Generalized Amplitude damp.
        (cirq.Circuit(cirq.generalized_amplitude_damp(p=0.1, gamma=0.2)(q0)),
         _build_op_proto("GAD", ['p', 'gamma'], [0.1, 0.2], ['0_0'])),

        # Amplitude damp.
        (cirq.Circuit(cirq.amplitude_damp(gamma=0.1)(q0)),
         _build_op_proto("AD", ['gamma'], [0.1], ['0_0'])),

        # Reset.
        (cirq.Circuit(cirq.reset(q0)), _build_op_proto("RST", [], [],
                                                       ['0_0'])),

        # Phase damp.
        (cirq.Circuit(cirq.phase_damp(gamma=0.1)(q0)),
         _build_op_proto("PD", ['gamma'], [0.1], ['0_0'])),

        # Phase flip.
        (cirq.Circuit(cirq.phase_flip(p=0.1)(q0)),
         _build_op_proto("PF", ['p'], [0.1], ['0_0'])),

        # Bit flip.
        (cirq.Circuit(cirq.bit_flip(p=0.1)(q0)),
         _build_op_proto("BF", ['p'], [0.1], ['0_0']))
    ]
    return pairs
Beispiel #19
0
def _get_noise_proto_pairs():
    q0 = cirq.GridQubit(0, 0)

    pairs = [
        # Depolarization.
        (cirq.Circuit(cirq.depolarize(p=0.3)(q0)),
         _build_op_proto("DP", ['p'], [0.3], ['0_0'])),

        # Asymmetric depolarization.
        (cirq.Circuit(
            cirq.asymmetric_depolarize(p_x=0.1, p_y=0.2, p_z=0.3)(q0)),
         _build_op_proto("ADP", ['p_x', 'p_y', 'p_z'], [0.1, 0.2, 0.3],
                         ['0_0'])),

        # Amplitude damp.
        (cirq.Circuit(cirq.amplitude_damp(gamma=0.1)(q0)),
         _build_op_proto("AD", ['gamma'], [0.1], ['0_0'])),

        # Reset.
        (cirq.Circuit(cirq.reset(q0)), _build_op_proto("RST", [], [], ['0_0']))
    ]
    return pairs
Beispiel #20
0
import cirq

qubits = cirq.LineQubit.range(3)

for i in range(200):

    def CEntang():
        global qubits
        yield cirq.H(qubits[1]), cirq.X(qubits[0])
        yield cirq.CX(qubits[1], qubits[2])
        yield cirq.CX(qubits[0], qubits[1])
        yield cirq.CX(qubits[1], qubits[2])
        yield cirq.Moment(cirq.measure(qubits[0], key="q1"),
                          cirq.measure(qubits[2], key="q2"))

    circuit = cirq.Circuit()
    circuit.append(CEntang())
    print(circuit)
    simulate = cirq.Simulator()
    result = simulate.run(circuit, repetitions=1000)
    print(result.multi_measurement_histogram(keys=["q1", "q2"]))

    cirq.reset(qubits[0])
    cirq.reset(qubits[1])
    print(result)

    #cirq.plot_state_histogram(result)
Beispiel #21
0
 def _decompose_(self, qubits):
     yield cirq.measure(qubits[0], key='inner1')
     yield cirq.measure(qubits[1], key='inner2')
     yield cirq.reset(qubits[0])
Beispiel #22
0
def test_reset_channel_equality():
    assert cirq.reset(cirq.LineQubit(0)).gate == cirq.ResetChannel()
    assert cirq.reset(cirq.LineQid(0, 3)).gate == cirq.ResetChannel(3)
Beispiel #23
0
def test_reset_stabilizer():
    assert cirq.has_stabilizer_effect(cirq.reset(cirq.LineQubit(0)))