def prepare_AOA_initial_state(self,circuit,D):
        '''
        Prepares the alternating Operator Ansatz
        initial state.

        |psi > = |10>^D \otimes ( (1/sqrt[2])*|00>+(1/sqrt[2])*|11>)^{N-D}

        Note that our convention is: |x^+ x^- > which is opposite to the paper
        '''

        # Prepare the |10> states, D-times
        for i in range(int(D)):
            sp_i, sm_i = self.portfolio_indices[i][1], self.portfolio_indices[i][2]
            circuit.append(cirq.X(self.qubits[sp_i]))

        # Prepare the Bell states ( (1/sqrt[2])*|00>+(1/sqrt[2])*|11>)^{N-D}
        for i in range(int(D), self.N_portfolio):
            sp_i, sm_i = self.portfolio_indices[i][1], self.portfolio_indices[i][2]
            circuit.append(cirq.H(self.qubits[sp_i]))
            circuit.append(cirq.CNOT(self.qubits[sp_i], self.qubits[sm_i]))

        return circuit
Exemplo n.º 2
0
def makeGroverCircuit(inputQubits, outputQubit, oracle):
    c = cirq.Circuit()

    c.append([
        cirq.X(outputQubit),
        cirq.H(outputQubit),
        cirq.H.on_each(*inputQubits),
    ])

    c.append(oracle)

    c.append(cirq.H.on_each(*inputQubits))
    c.append(cirq.X.on_each(*inputQubits))
    c.append(cirq.H.on(inputQubits[1]))
    c.append(cirq.CNOT(inputQubits[0], inputQubits[1]))
    c.append(cirq.H.on(inputQubits[1]))
    c.append(cirq.X.on_each(*inputQubits))
    c.append(cirq.H.on_each(*inputQubits))

    c.append(cirq.measure(*inputQubits, key='result'))

    return c
Exemplo n.º 3
0
def _decompose_two_qubit(operation: cirq.Operation) -> cirq.OP_TREE:
    """Decomposes a two qubit unitary operation into ZPOW, XPOW, and CNOT."""
    mat = cirq.unitary(operation)
    q0, q1 = operation.qubits
    naive = cirq.two_qubit_matrix_to_operations(q0,
                                                q1,
                                                mat,
                                                allow_partial_czs=False)
    temp = cirq.map_operations_and_unroll(
        cirq.Circuit(naive),
        lambda op, _:
        [cirq.H(op.qubits[1]),
         cirq.CNOT(*op.qubits),
         cirq.H(op.qubits[1])] if type(op.gate) == cirq.CZPowGate else op,
    )
    temp = cirq.merge_single_qubit_gates_to_phased_x_and_z(temp)
    # A final pass breaks up PhasedXPow into Rz, Rx.
    yield cirq.map_operations_and_unroll(
        temp,
        lambda op, _: cirq.decompose_once(op)
        if type(op.gate) == cirq.PhasedXPowGate else op,
    ).all_operations()
Exemplo n.º 4
0
def test_overlapping_measurements_at_end():
    a, b = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(
        cirq.H(a),
        cirq.CNOT(a, b),
        # These measurements are not on independent qubits but they commute.
        cirq.measure(a, key='a'),
        cirq.measure(a, key='not a', invert_mask=(True, )),
        cirq.measure(b, key='b'),
        cirq.measure(a, b, key='ab'),
    )

    samples = cirq.Simulator().sample(circuit, repetitions=100)
    np.testing.assert_array_equal(samples['a'].values,
                                  samples['not a'].values ^ 1)
    np.testing.assert_array_equal(
        samples['a'].values * 2 + samples['b'].values, samples['ab'].values)

    counts = samples['b'].value_counts()
    assert len(counts) == 2
    assert 10 <= counts[0] <= 90
    assert 10 <= counts[1] <= 90
Exemplo n.º 5
0
 def encode(self):
     yield cirq.ops.Moment([cirq.CNOT(self.physical_qubits[0], self.physical_qubits[3])])
     yield cirq.ops.Moment([cirq.CNOT(self.physical_qubits[0], self.physical_qubits[6])])
     yield cirq.ops.Moment(
         [
             cirq.H(self.physical_qubits[0]),
             cirq.H(self.physical_qubits[3]),
             cirq.H(self.physical_qubits[6]),
         ]
     )
     yield cirq.ops.Moment(
         [
             cirq.CNOT(self.physical_qubits[0], self.physical_qubits[1]),
             cirq.CNOT(self.physical_qubits[3], self.physical_qubits[4]),
             cirq.CNOT(self.physical_qubits[6], self.physical_qubits[7]),
         ]
     )
     yield cirq.ops.Moment(
         [
             cirq.CNOT(self.physical_qubits[0], self.physical_qubits[2]),
             cirq.CNOT(self.physical_qubits[3], self.physical_qubits[5]),
             cirq.CNOT(self.physical_qubits[6], self.physical_qubits[8]),
         ]
     )
Exemplo n.º 6
0
def test_convert_to_ion_gates():
    q0 = cirq.GridQubit(0, 0)
    q1 = cirq.GridQubit(0, 1)
    op = cirq.CNOT(q0, q1)
    circuit = cirq.Circuit()

    with pytest.raises(TypeError):
        cirq.ion.ConvertToIonGates().convert_one(circuit)

    with pytest.raises(TypeError):
        cirq.ion.ConvertToIonGates().convert_one(NoUnitary().on(q0))

    no_unitary_op = NoUnitary().on(q0)
    assert cirq.ion.ConvertToIonGates(
        ignore_failures=True).convert_one(no_unitary_op) == [no_unitary_op]

    rx = cirq.ion.ConvertToIonGates().convert_one(OtherX().on(q0))
    rop = cirq.ion.ConvertToIonGates().convert_one(op)
    rcnot = cirq.ion.ConvertToIonGates().convert_one(OtherCNOT().on(q0, q1))
    assert rx == [(cirq.X**1.0).on(cirq.GridQubit(0, 0))]
    assert rop == [
        cirq.Ry(np.pi / 2).on(op.qubits[0]),
        cirq.ion.MS(np.pi / 4).on(op.qubits[0], op.qubits[1]),
        cirq.ops.Rx(-1 * np.pi / 2).on(op.qubits[0]),
        cirq.ops.Rx(-1 * np.pi / 2).on(op.qubits[1]),
        cirq.ops.Ry(-1 * np.pi / 2).on(op.qubits[0])
    ]
    assert rcnot == [
        cirq.PhasedXPowGate(phase_exponent=-0.75,
                            exponent=0.5).on(cirq.GridQubit(0, 0)),
        (cirq.X**-0.25).on(cirq.GridQubit(0, 1)),
        cirq.T.on(cirq.GridQubit(0, 0)),
        cirq.MS(-0.5 * np.pi / 2).on(cirq.GridQubit(0,
                                                    0), cirq.GridQubit(0, 1)),
        (cirq.Y**0.5).on(cirq.GridQubit(0, 0)),
        (cirq.X**-0.25).on(cirq.GridQubit(0, 1)),
        (cirq.Z**-0.75).on(cirq.GridQubit(0, 0))
    ]
Exemplo n.º 7
0
def test_convert_to_ion_circuit():
    q0 = cirq.GridQubit(0, 0)
    q1 = cirq.GridQubit(0, 1)

    clifford_circuit_1 = cirq.Circuit()
    clifford_circuit_1.append(
        [cirq.X(q0), cirq.H(q1),
         cirq.MS(np.pi / 4).on(q0, q1)])
    ion_circuit_1 = cirq.ion.ConvertToIonGates().\
        convert_circuit(clifford_circuit_1)
    clifford_circuit_2 = cirq.Circuit()
    clifford_circuit_2.append(
        [cirq.X(q0),
         cirq.CNOT(q1, q0),
         cirq.MS(np.pi / 4).on(q0, q1)])
    ion_circuit_2 = cirq.ion.ConvertToIonGates().\
        convert_circuit(clifford_circuit_2)

    cirq.testing.assert_has_diagram(ion_circuit_1,
                                    """
(0, 0): ───X───────────────────MS(0.25π)───
                               │
(0, 1): ───Rx(π)───Ry(-0.5π)───MS(0.25π)───
    """,
                                    use_unicode_characters=True)

    cirq.testing.assert_has_diagram(ion_circuit_2,
                                    """
(0, 0): ───X──────────MS(0.25π)───Rx(-0.5π)───────────────MS(0.25π)───
                      │                                   │
(0, 1): ───Ry(0.5π)───MS(0.25π)───Rx(-0.5π)───Ry(-0.5π)───MS(0.25π)───
        """,
                                    use_unicode_characters=True)

    assert_ops_implement_unitary(q0, q1, ion_circuit_1,
                                 cirq.unitary(clifford_circuit_1))
    assert_ops_implement_unitary(q0, q1, ion_circuit_2,
                                 cirq.unitary(clifford_circuit_2))
Exemplo n.º 8
0
def test_assert_has_diagram():
    a, b = cirq.LineQubit.range(2)
    circuit = cirq.Circuit.from_ops(cirq.CNOT(a, b))
    cirq.testing.assert_has_diagram(circuit, """
0: ───@───
      │
1: ───X───
""")

    expected_error = """Circuit's text diagram differs from the desired diagram.

Diagram of actual circuit:
0: ───@───
      │
1: ───X───

Desired text diagram:
0: ───@───
      │
1: ───Z───

Highlighted differences:
0: ───@───
      │
1: ───█───

"""

    # Work around an issue when this test is run in python2, where using
    # match=expected_error causes an UnicodeEncodeError.
    with pytest.raises(AssertionError) as ex_info:
        cirq.testing.assert_has_diagram(
            circuit, u"""
0: ───@───
      │
1: ───Z───
""")
    assert expected_error in ex_info.value.args[0]
Exemplo n.º 9
0
def test_apply_tag_to_inverted_op_set():
    q = cirq.LineQubit.range(2)
    op = cirq.CNOT(*q)
    tag = "tag_to_flip"
    c_orig = cirq.Circuit(op, op.with_tags(tag),
                          cirq.CircuitOperation(cirq.FrozenCircuit(op)))
    # Toggle with deep = True.
    c_toggled = cirq.Circuit(
        op.with_tags(tag), op,
        cirq.CircuitOperation(cirq.FrozenCircuit(op.with_tags(tag))))
    cirq.testing.assert_same_circuits(
        cirq.toggle_tags(c_orig, [tag], deep=True), c_toggled)
    cirq.testing.assert_same_circuits(
        cirq.toggle_tags(c_toggled, [tag], deep=True), c_orig)

    # Toggle with deep = False
    c_toggled = cirq.Circuit(
        op.with_tags(tag), op,
        cirq.CircuitOperation(cirq.FrozenCircuit(op)).with_tags(tag))
    cirq.testing.assert_same_circuits(
        cirq.toggle_tags(c_orig, [tag], deep=False), c_toggled)
    cirq.testing.assert_same_circuits(
        cirq.toggle_tags(c_toggled, [tag], deep=False), c_orig)
Exemplo n.º 10
0
def test_classical_control():
    qasm = """OPENQASM 2.0;
        qreg q[2];
        creg m_a[1];
        measure q[0] -> m_a[0];
        if (m_a!=0) CX q[0], q[1];
    """
    parser = QasmParser()

    q_0 = cirq.NamedQubit('q_0')
    q_1 = cirq.NamedQubit('q_1')
    expected_circuit = cirq.Circuit(
        cirq.measure(q_0, key='m_a_0'),
        cirq.CNOT(q_0, q_1).with_classical_controls('m_a_0'),
    )

    parsed_qasm = parser.parse(qasm)

    assert parsed_qasm.supportedFormat
    assert not parsed_qasm.qelib1Include

    ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
    assert parsed_qasm.qregs == {'q': 2}
def make_grover_circuit(input_qubits, output_qubit, oracle):
    """Find the value recognized by the oracle in sqrt(N) attempts."""
    # For 2 input qubits, that means using Grover operator only once.
    c = cirq.Circuit()

    # Initialize qubits.
    c.append([cirq.X(output_qubit), cirq.H(output_qubit)])
    # Query oracle.
    make_oracle(input_qubits, output_qubit)

    # Construct Grover operator.
    c.append(cirq.H.on_each(*input_qubits))
    c.append(cirq.X.on_each(*input_qubits))
    c.append(cirq.H.on(input_qubits[1]))
    c.append(cirq.CNOT(input_qubits[0], input_qubits[1]))
    c.append(cirq.H.on(input_qubits[1]))
    c.append(cirq.X.on_each(*input_qubits))
    c.append(cirq.H.on_each(*input_qubits))

    # Measure the result.
    c.append(cirq.measure(*input_qubits, key='result'))

    return c
Exemplo n.º 12
0
 def _decompose_two_qubit_operation(self, op: cirq.Operation,
                                    _) -> cirq.OP_TREE:
     if not cirq.has_unitary(op):
         return NotImplemented
     mat = cirq.unitary(op)
     q0, q1 = op.qubits
     naive = cirq.two_qubit_matrix_to_cz_operations(q0,
                                                    q1,
                                                    mat,
                                                    allow_partial_czs=False)
     temp = cirq.map_operations_and_unroll(
         cirq.Circuit(naive),
         lambda op, _: [
             cirq.H(op.qubits[1]),
             cirq.CNOT(*op.qubits),
             cirq.H(op.qubits[1])
         ] if op.gate == cirq.CZ else op,
     )
     return cirq.merge_k_qubit_unitaries(
         temp,
         k=1,
         rewriter=lambda op: self._decompose_single_qubit_operation(
             op, -1)).all_operations()
Exemplo n.º 13
0
def test_unroll_circuit_op_and_variants():
    q = cirq.LineQubit.range(2)
    c = cirq.Circuit(cirq.X(q[0]), cirq.CNOT(q[0], q[1]), cirq.X(q[0]))
    cirq.testing.assert_has_diagram(
        c,
        '''
0: ───X───@───X───
          │
1: ───────X───────
''',
    )
    mapped_circuit = cirq.map_operations(
        c, lambda op, i: [cirq.Z(q[1])] * 2 if op.gate == cirq.CNOT else op)
    cirq.testing.assert_has_diagram(
        cirq.unroll_circuit_op(mapped_circuit),
        '''
0: ───X───────────X───

1: ───────Z───Z───────
''',
    )
    cirq.testing.assert_has_diagram(
        cirq.unroll_circuit_op_greedy_earliest(mapped_circuit),
        '''
0: ───X───────X───

1: ───Z───Z───────
''',
    )
    cirq.testing.assert_has_diagram(
        cirq.unroll_circuit_op_greedy_frontier(mapped_circuit),
        '''
0: ───X───────X───

1: ───────Z───Z───
''',
    )
Exemplo n.º 14
0
def toffoli(s0,s1,a):
	l=[cirq.H(a),
	cirq.CNOT(s0,a),
	(cirq.T**-1).on(a),
	cirq.CNOT(s1,a),
	cirq.T(a),
	cirq.CNOT(s0,a),
	(cirq.T**-1).on(a),
	cirq.CNOT(s1,a),
	cirq.T(a),
	(cirq.T**-1).on(s0),
	cirq.H(a),
	cirq.CNOT(s1,s0),
	(cirq.T**-1).on(s0),
	cirq.CNOT(s1,s0),
	cirq.S(s0),
	cirq.T(s1)]
	return l
Exemplo n.º 15
0
 def optimization_at(
     self, circuit: cirq.Circuit, index: int, op: cirq.Operation
 ) -> Optional[cirq.PointOptimizationSummary]:
     if len(op.qubits) > 3:
         raise DeviceMappingError(f"Four qubit ops not yet supported: {op}")
     new_ops = None
     if op.gate == cirq.SWAP or op.gate == cirq.CNOT:
         new_ops = cirq.google.optimized_for_sycamore(cirq.Circuit(op))
     if isinstance(op, cirq.ControlledOperation):
         if not all(v == 1 for values in op.control_values for v in values):
             raise DeviceMappingError(f"0-controlled ops not yet supported: {op}")
         qubits = op.sub_operation.qubits
         if op.gate.sub_gate == cirq.ISWAP:
             new_ops = controlled_iswap.controlled_iswap(*qubits, *op.controls)
         if op.gate.sub_gate == cirq.ISWAP ** -1:
             new_ops = controlled_iswap.controlled_iswap(
                 *qubits, *op.controls, inverse=True
             )
         if op.gate.sub_gate == cirq.ISWAP ** 0.5:
             new_ops = controlled_iswap.controlled_sqrt_iswap(*qubits, *op.controls)
         if op.gate.sub_gate == cirq.ISWAP ** -0.5:
             new_ops = controlled_iswap.controlled_inv_sqrt_iswap(
                 *qubits, *op.controls
             )
         if op.gate.sub_gate == cirq.X:
             if len(op.qubits) == 2:
                 new_ops = cirq.google.optimized_for_sycamore(
                     cirq.Circuit(cirq.CNOT(*op.controls, *qubits))
                 )
             if len(op.qubits) == 3:
                 new_ops = cirq.google.optimized_for_sycamore(
                     cirq.Circuit(cirq.TOFFOLI(*op.controls, *qubits))
                 )
     if new_ops:
         return cirq.PointOptimizationSummary(
             clear_span=1, clear_qubits=op.qubits, new_operations=new_ops
         )
Exemplo n.º 16
0
def test_simulate_moment_steps_sample():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(cirq.H(q0), cirq.CNOT(q0, q1))

    simulator = ccq.mps_simulator.MPSSimulator()

    for i, step in enumerate(simulator.simulate_moment_steps(circuit)):
        if i == 0:
            np.testing.assert_almost_equal(
                step._simulator_state().to_numpy(),
                np.asarray([1.0 / math.sqrt(2), 0.0, 1.0 / math.sqrt(2), 0.0]),
            )
            assert (str(step) == """TensorNetwork([
    Tensor(shape=(2,), inds=('i_0',), tags=set()),
    Tensor(shape=(2,), inds=('i_1',), tags=set()),
])""")
            samples = step.sample([q0, q1], repetitions=10)
            for sample in samples:
                assert np.array_equal(sample, [True, False]) or np.array_equal(
                    sample, [False, False])
            np.testing.assert_almost_equal(
                step._simulator_state().to_numpy(),
                np.asarray([1.0 / math.sqrt(2), 0.0, 1.0 / math.sqrt(2), 0.0]),
            )
        else:
            np.testing.assert_almost_equal(
                step._simulator_state().to_numpy(),
                np.asarray([1.0 / math.sqrt(2), 0.0, 0.0, 1.0 / math.sqrt(2)]),
            )
            assert (str(step) == """TensorNetwork([
    Tensor(shape=(2, 2), inds=('i_0', 'mu_0_1'), tags=set()),
    Tensor(shape=(2, 2), inds=('mu_0_1', 'i_1'), tags=set()),
])""")
            samples = step.sample([q0, q1], repetitions=10)
            for sample in samples:
                assert np.array_equal(sample, [True, True]) or np.array_equal(
                    sample, [False, False])
Exemplo n.º 17
0
def grovers_algorithm(num_qubits=2, copies=1000):
    # Define input and Target Qubit
    input_qubits = [cirq.LineQubit(i) for i in range(num_qubits)]
    target_qubit = cirq.LineQubit(num_qubits)
    # Define Quantum Circuit
    circuit = cirq.Circuit()
    # Create equal Superposition State
    circuit.append([cirq.H(input_qubits[i]) for i in range(num_qubits)])
    # Take target qubit to minus state |->
    circuit.append([cirq.X(target_qubit), cirq.H(target_qubit)])
    # Pass the qubit through the Oracle
    circuit = oracle(input_qubits, target_qubit, circuit)
    # Construct Grover operator.
    circuit.append(cirq.H.on_each(*input_qubits))
    circuit.append(cirq.X.on_each(*input_qubits))
    circuit.append(cirq.H.on(input_qubits[1]))
    circuit.append(cirq.CNOT(input_qubits[0], input_qubits[1]))
    circuit.append(cirq.H.on(input_qubits[1]))
    circuit.append(cirq.X.on_each(*input_qubits))
    circuit.append(cirq.H.on_each(*input_qubits))

    # Measure the result.
    circuit.append(cirq.measure(*input_qubits, key='Z'))
    print("Grover's algorithm follows")
    print(circuit)
    sim = cirq.Simulator()
    result = sim.run(circuit, repetitions=copies)
    out = result.histogram(key='Z')
    
    out_result = {}
    for k in out.keys():
        new_key = "{0:b}".format(k)
        if len(new_key) < num_qubits:
            new_key = (num_qubits - len(new_key)) * '0' + new_key
        # print(new_key,k)
        out_result[new_key] = out[k]
    print(out_result)
Exemplo n.º 18
0
def toffoli(a, b, c):
    return [
        cirq.H(c),
        cirq.CNOT(a, c),
        cirq.T(c)**3,
        cirq.CNOT(b, c),
        cirq.T(c),
        cirq.CNOT(a, c),
        cirq.T(c)**3,
        cirq.CNOT(b, c),
        cirq.T(c),
        cirq.H(c),
        cirq.T(a),
        cirq.CNOT(b, a),
        cirq.T(b),
        cirq.T(a)**3,
        cirq.CNOT(b, a)
    ]
Exemplo n.º 19
0
def test_example_9_iterations():
    Q = FIGURE_9A_PHYSICAL_QUBITS
    initial_mapping = dict(zip(q, Q))
    updater = SwapUpdater(FIGURE_9A_CIRCUIT, Q, initial_mapping,
                          lambda q1, q2: [cirq.SWAP(q1, q2)])

    # First iteration adds a swap between Q0 and Q1.
    assert list(updater.update_iteration()) == [cirq.SWAP(Q[0], Q[1])]
    # Next two iterations add the active gates as-is.
    assert list(updater.update_iteration()) == [cirq.CNOT(Q[1], Q[2])]
    assert list(updater.update_iteration()) == [cirq.CNOT(Q[5], Q[2])]
    # Next iteration adds a swap between Q1 and Q4.
    assert list(updater.update_iteration()) == [cirq.SWAP(Q[1], Q[4])]
    # Remaining gates are added as-is.
    assert list(updater.update_iteration()) == [cirq.CNOT(Q[4], Q[5])]
    assert list(updater.update_iteration()) == [cirq.CNOT(Q[1], Q[4])]
    assert list(updater.update_iteration()) == [cirq.CNOT(Q[4], Q[3])]
    # The final two gates are added in the same iteration, since they operate on
    # mutually exclusive qubits and are both simultaneously active.
    assert set(updater.update_iteration()) == {
        cirq.CNOT(Q[5], Q[4]), cirq.CNOT(Q[3], Q[0])
    }
Exemplo n.º 20
0
def test_final_wavefunction_different_program_types():
    a, b = cirq.LineQubit.range(2)

    np.testing.assert_allclose(cirq.final_wavefunction(cirq.X), [0, 1],
                               atol=1e-8)

    ops = [cirq.H(a), cirq.CNOT(a, b)]

    np.testing.assert_allclose(
        cirq.final_wavefunction(ops),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)

    np.testing.assert_allclose(
        cirq.final_wavefunction(cirq.Circuit.from_ops(ops)),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)

    np.testing.assert_allclose(
        cirq.final_wavefunction(
            cirq.moment_by_moment_schedule(cirq.UNCONSTRAINED_DEVICE,
                                           cirq.Circuit.from_ops(ops))),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)
Exemplo n.º 21
0
def test_superoperator():
    cnot = cirq.unitary(cirq.CNOT)

    a, b = cirq.LineQubit.range(2)

    m = cirq.Moment()
    assert m._has_superoperator_()
    s = m._superoperator_()
    assert np.allclose(s, np.array([[1.0]]))

    m = cirq.Moment(cirq.I(a))
    assert m._has_superoperator_()
    s = m._superoperator_()
    assert np.allclose(s, np.eye(4))

    m = cirq.Moment(cirq.IdentityGate(2).on(a, b))
    assert m._has_superoperator_()
    s = m._superoperator_()
    assert np.allclose(s, np.eye(16))

    m = cirq.Moment(cirq.S(a))
    assert m._has_superoperator_()
    s = m._superoperator_()
    assert np.allclose(s, np.diag([1, -1j, 1j, 1]))

    m = cirq.Moment(cirq.CNOT(a, b))
    assert m._has_superoperator_()
    s = m._superoperator_()
    assert np.allclose(s, np.kron(cnot, cnot))

    m = cirq.Moment(cirq.depolarize(0.75).on(a))
    assert m._has_superoperator_()
    s = m._superoperator_()
    assert np.allclose(
        s,
        np.array([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 1]]) / 2)
Exemplo n.º 22
0
    def test_step_by_step_circuit_inspection(self):
        """
        This function demonstrates how to use Cirq to print the state vector of every
        step (moment) in a circuit. It also shows how to get the state vector at each
        step, and how to print it in ket notation.
        """

        qubits = cirq.NamedQubit.range(3, prefix="qubit")
        circuit = cirq.Circuit()
        circuit.append(cirq.H.on_each(*qubits))
        circuit.append(cirq.X(qubits[2]))
        circuit.append(cirq.CNOT(qubits[2], qubits[0]))
        circuit.append(cirq.measure_each(*qubits))

        simulator = cirq.Simulator()
        steps = simulator.simulate_moment_steps(
            circuit)  # Step through each moment of the circuit
        for step in steps:
            print(
                step.state_vector()
            )  # Print the entire state vector for all of the qubits in the circuit
            print(cirq.dirac_notation(step.state_vector(
            )))  # Print the state vector in big-endian ket (Dirac) notation
            print("")
Exemplo n.º 23
0
def test_convert_to_ion_gates():
    q0 = cirq.GridQubit(0, 0)
    q1 = cirq.GridQubit(0, 1)
    op = cirq.CNOT(q0, q1)
    circuit = cirq.Circuit()

    with pytest.raises(TypeError):
        cirq.ion.ConvertToIonGates().convert_one(circuit)

    with pytest.raises(TypeError):
        cirq.ion.ConvertToIonGates().convert_one(NoUnitary().on(q0))

    no_unitary_op = NoUnitary().on(q0)
    assert cirq.ion.ConvertToIonGates(
        ignore_failures=True).convert_one(no_unitary_op) == [no_unitary_op]

    rx = cirq.ion.ConvertToIonGates().convert_one(OtherX().on(q0))
    rop = cirq.ion.ConvertToIonGates().convert_one(op)
    assert rx == [
        cirq.PhasedXPowGate(phase_exponent=1).on(cirq.GridQubit(0, 0))
    ]
    assert rop == [
        cirq.ry(np.pi / 2).on(op.qubits[0]),
        cirq.ms(np.pi / 4).on(op.qubits[0], op.qubits[1]),
        cirq.rx(-1 * np.pi / 2).on(op.qubits[0]),
        cirq.rx(-1 * np.pi / 2).on(op.qubits[1]),
        cirq.ry(-1 * np.pi / 2).on(op.qubits[0])
    ]

    rcnot = cirq.ion.ConvertToIonGates().convert_one(OtherCNOT().on(q0, q1))
    assert cirq.approx_eq([op for op in rcnot if len(op.qubits) > 1],
                          [cirq.ms(-0.5 * np.pi / 2).on(q0, q1)],
                          atol=1e-4)
    assert cirq.allclose_up_to_global_phase(
        cirq.unitary(cirq.Circuit(rcnot)), cirq.unitary(OtherCNOT().on(q0,
                                                                       q1)))
Exemplo n.º 24
0
def type_circuit(n):
    type_x = [[cirq.X(LineQubit(i)), 1,
               matrix_type(i, n, NOT)] for i in range(n)]
    type_h = [[cirq.H(LineQubit(i)), 1,
               matrix_type(i, n, H)] for i in range(n)]
    type_z = [[cirq.Z(LineQubit(i)), 1,
               matrix_type(i, n, Z)] for i in range(n)]
    type_s = [[cirq.S(LineQubit(i)), 1,
               matrix_type(i, n, S)] for i in range(n)]
    type_sdg = [[(cirq.S**-1)(LineQubit(i)), 1,
                 matrix_type(i, n, Sdg)] for i in range(n)]
    type_t = [[cirq.T(LineQubit(i)), 1,
               matrix_type(i, n, T)] for i in range(n)]
    type_tdg = [[(cirq.T**-1)(LineQubit(i)), 1,
                 matrix_type(i, n, Tdg)] for i in range(1, n)]
    type_cx = [[
        cirq.CNOT(LineQubit(i), LineQubit(j)), 3,
        matrix_type1(i, j, n, NOT)
    ] for i in range(n) for j in range(n) if i != j]
    type_all = type_x + type_h + type_z + type_s + type_t + type_sdg + type_tdg + type_cx
    # type_all = type_cx
    print('{}种情况\n'.format(len(type_all)))
    # print(type_all)
    return type_all
Exemplo n.º 25
0
    def decode_message(self, pair_a, pair_b):
        """
        Decodes two bits of information from an entangled pair of qubits.

        Parameters:
            pair_a (Qid): The "remote" qubit that was modified by the encoding
                process.
            pair_b (Qid): The "local" qubit that we received, which wasn't
                directly modified.

        Returns:
            a_measurement_key (str): The key of the measurement of the "remote" qubit.
            b_measurement_key (str): The key of the measurement of the "local" qubit.
        """

        a_measurement_key = "a_measurement"
        b_measurement_key = "b_measurement"

        self.circuit.append([cirq.CNOT(pair_a, pair_b), cirq.H(pair_a)])

        # Here's the decoding table based on the states after running
        # them through CNOT(A, B) and H(A):
        # |00> + |11>  =>  |00> + |10>  =>  |00>, so 00 means nothing happened
        # |01> + |10>  =>  |01> + |11>  =>  |01>, so 01 means X happened
        # |00> - |11>  =>  |00> - |10>  =>  |10>, so 10 means Z happened
        # |01> - |10>  =>  |01> - |11>  =>  |11>, so 11 means XZ happened
        # Notice how all 4 options align with the bit string used by the encoding
        # table, so measuring these qubits gives us the original bits where
        # pair_b corresponds to whether or not X was used, and pair_a corresponds
        # to Z.
        self.circuit.append([
            cirq.measure(pair_a, key=a_measurement_key),
            cirq.measure(pair_b, key=b_measurement_key),
        ])

        return (a_measurement_key, b_measurement_key)
Exemplo n.º 26
0
def get_pauli_representations(
    base_noise: float,
    qubits: Optional[List[cirq.Qid]] = None,
) -> List[OperationRepresentation]:

    if qubits is None:
        qreg = cirq.LineQubit.range(2)
    else:
        qreg = qubits

    # Generate all ideal single-qubit Pauli operations for both qubits
    pauli_gates = [cirq.X, cirq.Y, cirq.Z]
    ideal_operations = []

    for gate in pauli_gates:
        for qubit in qreg:
            ideal_operations.append(cirq.Circuit(gate(qubit)))

    # Generate all ideal 2-qubit Pauli operations
    for gate_a, gate_b in product(pauli_gates, repeat=2):
        ideal_operations.append(
            cirq.Circuit([gate_a(qreg[0]), gate_b(qreg[1])]))

    # Add CNOT too
    ideal_operations.append(cirq.Circuit(cirq.CNOT(*qreg)))

    # Generate all representations
    reps = []
    for op in ideal_operations:
        reps.append(
            represent_operation_with_local_depolarizing_noise(
                op,
                base_noise,
            ))

    return reps
Exemplo n.º 27
0
def get_pauli_and_cnot_representations(
    base_noise: float, qubits: Optional[List[cirq.Qid]] = None,
) -> List[OperationRepresentation]:

    if qubits is None:
        qreg = cirq.LineQubit.range(2)
    else:
        qreg = qubits

    # Generate all ideal single-qubit Pauli operations for both qubits
    pauli_gates = [cirq.X, cirq.Y, cirq.Z]
    ideal_operations = []

    for gate in pauli_gates:
        for qubit in qreg:
            ideal_operations.append(gate(qubit))

    # Add CNOT operation too
    ideal_operations.append(cirq.CNOT(*qreg))

    # Generate all representations
    return represent_operations_in_circuit_with_local_depolarizing_noise(
        ideal_circuit=cirq.Circuit(ideal_operations), noise_level=base_noise,
    )
def main():
    # The device to run the experiment.
    simulator = cirq.Simulator()

    # The two qubits to be characterized in this example.
    q_0 = cirq.GridQubit(0, 0)
    q_1 = cirq.GridQubit(0, 1)

    # Measure Rabi oscillation of q_0.
    rabi_results = cirq.experiments.rabi_oscillations(simulator, q_0,
                                                      4 * np.pi)
    rabi_results.plot()

    num_cfds = range(5, 20, 5)

    # Clifford-based randomized benchmarking of single-qubit gates on q_0.
    rb_result_1q = cirq.experiments.single_qubit_randomized_benchmarking(
        simulator, q_0, num_clifford_range=num_cfds, repetitions=100)
    rb_result_1q.plot()

    # Clifford-based randomized benchmarking of two-qubit gates on q_0 and q_1.
    rb_result_2q = cirq.experiments.two_qubit_randomized_benchmarking(
        simulator, q_0, q_1, num_clifford_range=num_cfds, repetitions=100)
    rb_result_2q.plot()

    # State-tomography of q_0 after application of an X/2 rotation.
    cir_1q = cirq.Circuit.from_ops(cirq.X(q_0)**0.5)
    tomography_1q = cirq.experiments.single_qubit_state_tomography(
        simulator, q_0, cir_1q)
    tomography_1q.plot()

    # State-tomography of a Bell state between q_0 and q_1.
    cir_2q = cirq.Circuit.from_ops(cirq.H(q_0), cirq.CNOT(q_0, q_1))
    tomography_2q = cirq.experiments.two_qubit_state_tomography(
        simulator, q_0, q_1, cir_2q)
    tomography_2q.plot()
Exemplo n.º 29
0
def test_simulate_moment_steps_sample():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(cirq.H(q0), cirq.CNOT(q0, q1))

    simulator = cirq.MPSSimulator()

    for i, step in enumerate(simulator.simulate_moment_steps(circuit)):
        if i == 0:
            np.testing.assert_almost_equal(
                step._simulator_state().to_numpy(),
                np.asarray([1.0 / math.sqrt(2), 0.0, 1.0 / math.sqrt(2), 0.0]),
            )
            assert str(
                step
            ) == "[array([[[0.70710678+0.j, 0.70710678+0.j]]]), array([[[1., 0.]]])]"
            samples = step.sample([q0, q1], repetitions=10)
            for sample in samples:
                assert np.array_equal(sample, [True, False]) or np.array_equal(
                    sample, [False, False])
            np.testing.assert_almost_equal(
                step._simulator_state().to_numpy(),
                np.asarray([1.0 / math.sqrt(2), 0.0, 1.0 / math.sqrt(2), 0.0]),
            )
        else:
            np.testing.assert_almost_equal(
                step._simulator_state().to_numpy(),
                np.asarray([1.0 / math.sqrt(2), 0.0, 0.0, 1.0 / math.sqrt(2)]),
            )
            assert (str(step) == """[array([[[0.84089642+0.j, 0.        +0.j],
        [0.        +0.j, 0.84089642+0.j]]]), array([[[0.84089642+0.j, 0.        +0.j]],

       [[0.        +0.j, 0.84089642+0.j]]])]""")
            samples = step.sample([q0, q1], repetitions=10)
            for sample in samples:
                assert np.array_equal(sample, [True, True]) or np.array_equal(
                    sample, [False, False])
 def generate_cirq(self):
     import cirq
     self.cirq_circuits_list=[]
     print("Creating Cirq circuit list...")
     self.logfile.write("Creating Cirq circuit list...")
     for circuit in self.circuits_list:
         c=cirq.Circuit()
         qubit_list=cirq.LineQubit.range(self.num_qubits)
         gate_list=[]
         for gate in circuit.gates:
             if gate.name in "H":
                 gate_list.append(cirq.H(qubit_list[gate.qubits[0]]))
             elif gate.name in "RZ":
                 gate_list.append(cirq.rz(gate.angles[0])(qubit_list[gate.qubits[0]]))
             elif gate.name in "RX":
                 gate_list.append(cirq.rx(gate.angles[0])(qubit_list[gate.qubits[0]]))
             elif gate.name in "CNOT":
                 gate_list.append(cirq.CNOT(qubit_list[gate.qubits[0]],qubit_list[gate.qubits[1]]))
         for i in range(self.num_qubits):
             gate_list.append(cirq.measure(qubit_list[i]))
         c.append(gate_list,strategy=cirq.InsertStrategy.EARLIEST)
         self.cirq_circuits_list.append(c)
     print("Successfully created Cirq circuit list")
     self.logfile.write("Successfully created Cirq circuit list")