def test_text_diagrams(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') circuit = cirq.Circuit.from_ops(cirq.SWAP(a, b), cirq.X(a), cirq.Y(a), cirq.Z(a), cirq.Z(a)**cirq.Symbol('x'), cirq.CZ(a, b), cirq.CNOT(a, b), cirq.CNOT(b, a), cirq.H(a), cirq.ISWAP(a, b), cirq.ISWAP(a, b)**-1) assert circuit.to_text_diagram().strip() == """ a: ───×───X───Y───Z───Z^x───@───@───X───H───iSwap───iSwap────── │ │ │ │ │ │ b: ───×─────────────────────@───X───@───────iSwap───iSwap^-1─── """.strip() assert circuit.to_text_diagram(use_unicode_characters=False).strip() == """ a: ---swap---X---Y---Z---Z^x---@---@---X---H---iSwap---iSwap------ | | | | | | b: ---swap---------------------@---X---@-------iSwap---iSwap^-1--- """.strip()
def test_swap_permutation_gate(): no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and op.gate == cirq.SWAP) a, b = cirq.NamedQubit('a'), cirq.NamedQubit('b') expander = cirq.ExpandComposite(no_decomp=no_decomp) gate = cca.SwapPermutationGate() assert gate.num_qubits() == 2 circuit = cirq.Circuit(gate(a, b)) expander(circuit) assert tuple(circuit.all_operations()) == (cirq.SWAP(a, b), ) no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and op.gate == cirq.CZ) expander = cirq.ExpandComposite(no_decomp=no_decomp) circuit = cirq.Circuit(cca.SwapPermutationGate(cirq.CZ)(a, b)) expander(circuit) assert tuple(circuit.all_operations()) == (cirq.CZ(a, b), ) assert cirq.commutes(gate, cirq.ZZ) with pytest.raises(TypeError): cirq.commutes(gate, cirq.CCZ)
def make_oracle(input_qubits, output_qubits, secret_string): """Gates implementing the function f(a) = f(b) iff a ⨁ b = s""" # Copy contents to output qubits: for control_qubit, target_qubit in zip(input_qubits, output_qubits): yield cirq.CNOT(control_qubit, target_qubit) # Create mapping: if sum(secret_string): # check if the secret string is non-zero # Find significant bit of secret string (first non-zero bit) significant = list(secret_string).index(1) # Add secret string to input according to the significant bit: for j in range(len(secret_string)): if secret_string[j] > 0: yield cirq.CNOT(input_qubits[significant], output_qubits[j]) # Apply a random permutation: pos = [ 0, len(secret_string) - 1, ] # Swap some qubits to define oracle. We choose first and last: yield cirq.SWAP(output_qubits[pos[0]], output_qubits[pos[1]])
def test_greedy_merging_reverse(): """Same as the above test, except that the aligning is done in reverse.""" q1, q2, q3, q4 = cirq.LineQubit.range(4) input_circuit = cirq.Circuit( cirq.Moment([cirq.SWAP(q1, q2), cirq.SWAP(q3, q4)]), cirq.Moment([cirq.X(q4)]), cirq.Moment([cirq.SWAP(q3, q4)]), cirq.Moment([cirq.X(q1)]), ) expected = cirq.Circuit( cirq.Moment([cirq.SWAP(q1, q2), cirq.SWAP(q3, q4)]), cirq.Moment([cirq.X(q1), cirq.X(q4)]), cirq.Moment([cirq.SWAP(q3, q4)]), ) cirq.testing.assert_same_circuits( cirq.stratified_circuit(input_circuit, categories=[cirq.X]), expected)
def basic_circuit(self, cd, qs): circuitDict = self.getCircuitDict() for col in cd: count = 0 paircnot = 0 swap = list() cont = list() gates = list() monent = list() for gate in col: if gate == 'Swap': swap.append(qs[count]) elif gate == '•': if paircnot == 0: paircnot += 1 cont.append(qs[count]) elif paircnot == 1: paircnot += 1 cont.append(qs[count]) elif gate != 1: gates.append((gate, qs[count])) count += 1 if len(swap) > 0: monent.append(cirq.SWAP(swap[0], swap[1])) if len(gates) > 0: for (gateType, gatePosition) in gates: monent.append(circuitDict[gateType](gatePosition)) if len(cont) > 0: if len(cont) == 1: if gates[0][0] == 'X': monent.append(cirq.CNOT(cont[0], gates[0][1])) if gates[0][0] == 'Z': monent.append(cirq.CZ(cont[0], gates[0][1])) if len(cont) == 2: monent.append(cirq.TOFFOLI(cont[0], cont[1], gates[0][1])) if len(cont) == 0 and len(swap) == 0: for (gateType, gatePosition) in gates: monent.append(circuitDict[gateType](gatePosition)) yield monent yield cirq.measure(*qs, key='result')
def test_various_known_gate_types(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') circuit = cirq.Circuit.from_ops( cirq.X(a), cirq.X(a)**0.25, cirq.X(a)**-0.5, cirq.Z(a), cirq.Z(a)**0.5, cirq.Y(a), cirq.Y(a)**-0.25, cirq.Y(a)**cirq.Symbol('t'), cirq.H(a), cirq.measure(a), cirq.measure(a, b, key='not-relevant'), cirq.SWAP(a, b), cirq.CNOT(a, b), cirq.CNOT(b, a), cirq.CZ(a, b), ) assert_links_to(circuit, """ http://algassert.com/quirk#circuit={"cols":[ ["X"], ["X^¼"], ["X^-½"], ["Z"], ["Z^½"], ["Y"], ["Y^-¼"], ["Y^t"], ["H"], ["Measure"], ["Measure","Measure"], ["Swap","Swap"], ["•","X"], ["X","•"], ["•","Z"]]} """, escape_url=False)
def anzatz(circuit, qubits, parameters): for i in range(5): pos_up = int(i * 2) pos_down = pos_up + 1 circuit.append([cirq.X(qubits[pos_down])]) circuit.append([cirq.ry(np.pi / 2).on(qubits[pos_up])]) circuit.append([cirq.rx(-np.pi / 2).on(qubits[pos_down])]) circuit.append([cirq.CNOT(qubits[pos_up], qubits[pos_down])]) circuit.append([cirq.rz(parameters[0]).on(qubits[pos_down])]) circuit.append([cirq.CNOT(qubits[pos_up], qubits[pos_down])]) circuit.append([cirq.ry(-np.pi / 2).on(qubits[pos_up])]) circuit.append([cirq.rx(np.pi / 2).on(qubits[pos_down])]) circuit.append([cirq.SWAP(qubits[0], qubits[1])]) circuit.append([cirq.CNOT(qubits[5], qubits[4])]) circuit.append([cirq.Z(qubits[6]), cirq.Z(qubits[7])]) circuit.append([cirq.S(qubits[6]), cirq.S(qubits[7])]) circuit.append([cirq.H(qubits[6]), cirq.H(qubits[7])]) circuit.append([cirq.CNOT(qubits[7], qubits[6])]) circuit.append([cirq.H(qubits[8]), cirq.H(qubits[9])]) circuit.append([cirq.CNOT(qubits[9], qubits[8])]) return circuit
def test_cirq2pyquil(self): ref_qprog = pyquil.quil.Program().inst(pyquil.gates.X(0), pyquil.gates.T(1), pyquil.gates.CNOT(0, 1), pyquil.gates.SWAP(0, 1), pyquil.gates.CZ(1, 0)) qubits = [cirq.GridQubit(i, 0) for i in ref_qprog.get_qubits()] gates = [ cirq.X(qubits[0]), cirq.T(qubits[1]), cirq.CNOT(qubits[0], qubits[1]), cirq.SWAP(qubits[0], qubits[1]), cirq.CZ(qubits[1], qubits[0]) ] circuit = cirq.Circuit() circuit.append(gates, strategy=cirq.circuits.InsertStrategy.EARLIEST) qprog = cirq2pyquil(circuit) self.assertEqual(qprog, ref_qprog)
def test_various_unknown_gate_types(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') circuit = cirq.Circuit( MysteryOperation(b), cirq.SWAP(a, b)**0.5, cirq.H(a)**0.5, cirq.SingleQubitCliffordGate.X_sqrt.merged_with( cirq.SingleQubitCliffordGate.Z_sqrt).on(a), cirq.X(a)**(1 / 5), cirq.Y(a)**(1 / 5), cirq.Z(a)**(1 / 5), cirq.CZ(a, b)**(1 / 5), cirq.PhasedXPowGate(phase_exponent=0.25)(a), cirq.PhasedXPowGate(exponent=1, phase_exponent=sympy.Symbol('r'))(a), cirq.PhasedXPowGate(exponent=0.001, phase_exponent=0.1)(a)) assert_links_to(circuit, """ http://algassert.com/quirk#circuit={"cols":[ [1,"UNKNOWN"], ["UNKNOWN", "UNKNOWN"], [{"id":"?","matrix":"{{0.853553+0.146447i,0.353553-0.353553i}, {0.353553-0.353553i,0.146447+0.853553i}}"}], [{"id":"?","matrix":"{{0.5+0.5i,0.5+0.5i},{0.5-0.5i,-0.5+0.5i}}"}], [{"arg":"0.2000","id":"X^ft"}], [{"arg":"0.2000","id":"Y^ft"}], [{"arg":"0.2000","id":"Z^ft"}], ["•",{"arg":"0.2000","id":"Z^ft"}], [{"id":"?", "matrix":"{{0, 0.707107+0.707107i}, {0.707107-0.707107i, 0}}"}], ["UNKNOWN"], [{"id":"?", "matrix":"{{0.999998+0.001571i,0.000488-0.001493i}, {-0.000483-0.001495i,0.999998+0.001571i}}"}] ]} """, escape_url=False, prefer_unknown_gate_to_failure=True)
def test_circuit_operation_conversion(optimizer_type, two_qubit_gate_type): q0, q1 = cirq.LineQubit.range(2) subcircuit = cirq.FrozenCircuit(cirq.X(q0), cirq.SWAP(q0, q1)) circuit = cirq.Circuit(cirq.CircuitOperation(subcircuit)) converted_circuit = cg.optimized_for_sycamore( circuit, optimizer_type=optimizer_type) # Verify that the CircuitOperation was preserved. ops = list(converted_circuit.all_operations()) assert isinstance(ops[0], cirq.CircuitOperation) # Verify that the contents of the CircuitOperation were optimized. converted_subcircuit = cg.optimized_for_sycamore( subcircuit.unfreeze(), optimizer_type=optimizer_type) assert len([ *converted_subcircuit.findall_operations_with_gate_type( two_qubit_gate_type) ]) == len([ *ops[0].circuit.findall_operations_with_gate_type(two_qubit_gate_type) ]) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( ops[0].circuit, converted_subcircuit, atol=1e-8) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( circuit, converted_circuit, atol=1e-8)
def test_greedy_merging(): """Tests a tricky situation where the algorithm of "Merge single-qubit gates, greedily align single-qubit then 2-qubit operations" doesn't work. Our algorithm succeeds because we also run it in reverse order.""" q1, q2, q3, q4 = cirq.LineQubit.range(4) input_circuit = cirq.Circuit( cirq.Moment([cirq.X(q1)]), cirq.Moment([cirq.SWAP(q1, q2), cirq.SWAP(q3, q4)]), cirq.Moment([cirq.X(q3)]), cirq.Moment([cirq.SWAP(q3, q4)]), ) expected = cirq.Circuit( cirq.Moment([cirq.SWAP(q3, q4)]), cirq.Moment([cirq.X(q1), cirq.X(q3)]), cirq.Moment([cirq.SWAP(q1, q2), cirq.SWAP(q3, q4)]), ) assert cirq.stratified_circuit(input_circuit, categories=[cirq.X]) == expected
def test_interchangeable_qubit_eq(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') c = cirq.NamedQubit('c') eq = cirq.testing.EqualsTester() eq.add_equality_group(cirq.SWAP(a, b), cirq.SWAP(b, a)) eq.add_equality_group(cirq.SWAP(a, c)) eq.add_equality_group(cirq.SWAP(a, b)**0.3, cirq.SWAP(b, a)**0.3) eq.add_equality_group(cirq.SWAP(a, c)**0.3) eq.add_equality_group(cirq.ISWAP(a, b), cirq.ISWAP(b, a)) eq.add_equality_group(cirq.ISWAP(a, c)) eq.add_equality_group(cirq.ISWAP(a, b)**0.3, cirq.ISWAP(b, a)**0.3) eq.add_equality_group(cirq.ISWAP(a, c)**0.3)
def test_text_diagrams(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') circuit = cirq.Circuit(cirq.SWAP(a, b), cirq.ISWAP(a, b)**-1) cirq.testing.assert_has_diagram( circuit, """ a: ───×───iSwap────── │ │ b: ───×───iSwap^-1─── """, ) cirq.testing.assert_has_diagram( circuit, """ a: ---Swap---iSwap------ | | b: ---Swap---iSwap^-1--- """, use_unicode_characters=False, )
def test_decompose_preserving_structure(): a, b = cirq.LineQubit.range(2) fc1 = cirq.FrozenCircuit(cirq.SWAP(a, b), cirq.FSimGate(0.1, 0.2).on(a, b)) cop1_1 = cirq.CircuitOperation(fc1).with_tags('test_tag') cop1_2 = cirq.CircuitOperation(fc1).with_qubit_mapping({a: b, b: a}) fc2 = cirq.FrozenCircuit(cirq.X(a), cop1_1, cop1_2) cop2 = cirq.CircuitOperation(fc2) circuit = cirq.Circuit(cop2, cirq.measure(a, b, key='m')) actual = cirq.Circuit(cirq.decompose(circuit, preserve_structure=True)) # This should keep the CircuitOperations but decompose their SWAPs. fc1_decomp = cirq.FrozenCircuit(cirq.decompose(fc1)) expected = cirq.Circuit( cirq.CircuitOperation( cirq.FrozenCircuit( cirq.X(a), cirq.CircuitOperation(fc1_decomp).with_tags('test_tag'), cirq.CircuitOperation(fc1_decomp).with_qubit_mapping({a: b, b: a}), ) ), cirq.measure(a, b, key='m'), ) assert actual == expected
def _swap_rzz(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> cirq.OP_TREE: """An implementation of SWAP * exp(-1j * theta * ZZ) using three sycamore gates. This builds off of the _rzz method. Args: theta: The rotation parameter of Rzz Ising coupling gate. q0: First qubit to operate on. q1: Second qubit to operate on. Yields: The `cirq.OP_TREE`` that implements ZZ followed by a swap. """ # Set interaction part. angle_offset = np.pi / 24 - np.pi / 4 circuit = cirq.Circuit(ops.SYC(q0, q1), _rzz(theta - angle_offset, q0, q1)) # Get the intended circuit. intended_circuit = cirq.Circuit( cirq.SWAP(q0, q1), cirq.ZZPowGate(exponent=2 * theta / np.pi, global_shift=-0.5).on(q0, q1) ) yield _create_corrected_circuit(cirq.unitary(intended_circuit), circuit, q0, q1)
def make_superdense_circuit(): circuit = cirq.Circuit() q0, q1, q2, q3, q4 = cirq.LineQubit.range(5) # Randomly sets q0 and q1 to either 0 or 1 circuit.append([cirq.H(q0), cirq.H(q1)]) circuit.append(cirq.measure(q0, q1, key="input ")) # Creates Bell State to be shared on q2 and q4 circuit.append([cirq.H(q2), cirq.CNOT(q2, q4)]) # Step 1 of encoding (controlled NOT gate on q1 / q2) circuit.append(cirq.CNOT(q1, q2)) # Step 2 of encoding (controlled Z gate on q0 / q2) circuit.append(cirq.CZ(q0, q2)) # Sends encoded information to receiver circuit.append(cirq.SWAP(q2, q3)) # Step 1 of decoding (controlled NOT gate on q3 and q4) circuit.append(cirq.CNOT(q3, q4)) # Step 2 of decoding (Hadamard gate on q3) circuit.append(cirq.H(q3)) # Measurement by receiver to decode bits circuit.append(cirq.measure(q3, q4, key="output")) return circuit
def test_cirq_qsim_all_supported_gates(self): q0 = cirq.GridQubit(1, 1) q1 = cirq.GridQubit(1, 0) q2 = cirq.GridQubit(0, 1) q3 = cirq.GridQubit(0, 0) circuit = cirq.Circuit( cirq.Moment([ cirq.H(q0), cirq.H(q1), cirq.H(q2), cirq.H(q3), ]), cirq.Moment([ cirq.T(q0), cirq.T(q1), cirq.T(q2), cirq.T(q3), ]), cirq.Moment([ cirq.CZPowGate(exponent=0.7, global_shift=0.2)(q0, q1), cirq.CXPowGate(exponent=1.2, global_shift=0.4)(q2, q3), ]), cirq.Moment([ cirq.XPowGate(exponent=0.3, global_shift=1.1)(q0), cirq.YPowGate(exponent=0.4, global_shift=1)(q1), cirq.ZPowGate(exponent=0.5, global_shift=0.9)(q2), cirq.HPowGate(exponent=0.6, global_shift=0.8)(q3), ]), cirq.Moment([ cirq.CX(q0, q2), cirq.CZ(q1, q3), ]), cirq.Moment([ cirq.X(q0), cirq.Y(q1), cirq.Z(q2), cirq.S(q3), ]), cirq.Moment([ cirq.XXPowGate(exponent=0.4, global_shift=0.7)(q0, q1), cirq.YYPowGate(exponent=0.8, global_shift=0.5)(q2, q3), ]), cirq.Moment([cirq.I(q0), cirq.I(q1), cirq.IdentityGate(2)(q2, q3)]), cirq.Moment([ cirq.rx(0.7)(q0), cirq.ry(0.2)(q1), cirq.rz(0.4)(q2), cirq.PhasedXPowGate(phase_exponent=0.8, exponent=0.6, global_shift=0.3)(q3), ]), cirq.Moment([ cirq.ZZPowGate(exponent=0.3, global_shift=1.3)(q0, q2), cirq.ISwapPowGate(exponent=0.6, global_shift=1.2)(q1, q3), ]), cirq.Moment([ cirq.XPowGate(exponent=0.1, global_shift=0.9)(q0), cirq.YPowGate(exponent=0.2, global_shift=1)(q1), cirq.ZPowGate(exponent=0.3, global_shift=1.1)(q2), cirq.HPowGate(exponent=0.4, global_shift=1.2)(q3), ]), cirq.Moment([ cirq.SwapPowGate(exponent=0.2, global_shift=0.9)(q0, q1), cirq.PhasedISwapPowGate(phase_exponent=0.8, exponent=0.6)(q2, q3), ]), cirq.Moment([ cirq.PhasedXZGate(x_exponent=0.2, z_exponent=0.3, axis_phase_exponent=1.4)(q0), cirq.T(q1), cirq.H(q2), cirq.S(q3), ]), cirq.Moment([ cirq.SWAP(q0, q2), cirq.XX(q1, q3), ]), cirq.Moment([ cirq.rx(0.8)(q0), cirq.ry(0.9)(q1), cirq.rz(1.2)(q2), cirq.T(q3), ]), cirq.Moment([ cirq.YY(q0, q1), cirq.ISWAP(q2, q3), ]), cirq.Moment([ cirq.T(q0), cirq.Z(q1), cirq.Y(q2), cirq.X(q3), ]), cirq.Moment([ cirq.FSimGate(0.3, 1.7)(q0, q2), cirq.ZZ(q1, q3), ]), cirq.Moment([ cirq.ry(1.3)(q0), cirq.rz(0.4)(q1), cirq.rx(0.7)(q2), cirq.S(q3), ]), cirq.Moment([ cirq.MatrixGate( np.array([[0, -0.5 - 0.5j, -0.5 - 0.5j, 0], [0.5 - 0.5j, 0, 0, -0.5 + 0.5j], [0.5 - 0.5j, 0, 0, 0.5 - 0.5j], [0, -0.5 - 0.5j, 0.5 + 0.5j, 0]]))(q0, q1), cirq.MatrixGate( np.array([[0.5 - 0.5j, 0, 0, -0.5 + 0.5j], [0, 0.5 - 0.5j, -0.5 + 0.5j, 0], [0, -0.5 + 0.5j, -0.5 + 0.5j, 0], [0.5 - 0.5j, 0, 0, 0.5 - 0.5j]]))(q2, q3), ]), cirq.Moment([ cirq.MatrixGate(np.array([[1, 0], [0, 1j]]))(q0), cirq.MatrixGate(np.array([[0, -1j], [1j, 0]]))(q1), cirq.MatrixGate(np.array([[0, 1], [1, 0]]))(q2), cirq.MatrixGate(np.array([[1, 0], [0, -1]]))(q3), ]), cirq.Moment([ cirq.riswap(0.7)(q0, q1), cirq.givens(1.2)(q2, q3), ]), cirq.Moment([ cirq.H(q0), cirq.H(q1), cirq.H(q2), cirq.H(q3), ]), ) simulator = cirq.Simulator() cirq_result = simulator.simulate(circuit) qsim_simulator = qsimcirq.QSimSimulator() qsim_result = qsim_simulator.simulate(circuit) assert cirq.linalg.allclose_up_to_global_phase( qsim_result.state_vector(), cirq_result.state_vector())
def test_moment_text_diagram(): a, b, c, d = cirq.GridQubit.rect(2, 2) m = cirq.Moment(cirq.CZ(a, b), cirq.CNOT(c, d)) assert (str(m).strip() == """ ╷ 0 1 ╶─┼───── 0 │ @─@ │ 1 │ @─X │ """.strip()) m = cirq.Moment(cirq.CZ(a, b), cirq.CNOT(c, d)) cirq.testing.assert_has_diagram( m, """ ╷ None 0 1 ╶──┼────────── aa │ │ 0 │ @─@ │ 1 │ @─X │ """, extra_qubits=[cirq.NamedQubit("aa")], ) m = cirq.Moment(cirq.S(c), cirq.ISWAP(a, d)) cirq.testing.assert_has_diagram( m, """ ╷ 0 1 ╶─┼───────────── 0 │ iSwap─┐ │ │ 1 │ S iSwap │ """, ) m = cirq.Moment(cirq.S(c)**0.1, cirq.ISWAP(a, d)**0.5) cirq.testing.assert_has_diagram( m, """ ╷ 0 1 ╶─┼───────────────── 0 │ iSwap^0.5─┐ │ │ 1 │ Z^0.05 iSwap │ """, ) a, b, c = cirq.LineQubit.range(3) m = cirq.Moment(cirq.X(a), cirq.SWAP(b, c)) cirq.testing.assert_has_diagram( m, """ ╷ a b c ╶─┼─────── 0 │ X │ 1 │ ×─┐ │ │ 2 │ × │ """, xy_breakdown_func=lambda q: ('abc'[q.x], q.x), ) class EmptyGate(cirq.Gate): def _num_qubits_(self) -> int: return 1 def __str__(self): return 'Empty' m = cirq.Moment(EmptyGate().on(a)) cirq.testing.assert_has_diagram( m, """ ╷ 0 ╶─┼─────── 0 │ Empty │ """, )
def _get_circuit_proto_pairs(): q0 = cirq.GridQubit(0, 0) q1 = cirq.GridQubit(0, 1) pairs = [ # HPOW and aliases. (cirq.Circuit(cirq.HPowGate(exponent=0.3)(q0)), _build_gate_proto("HP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0'])), (cirq.Circuit(cirq.HPowGate(exponent=sympy.Symbol('alpha'))(q0)), _build_gate_proto("HP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0'])), (cirq.Circuit(cirq.HPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0)), _build_gate_proto("HP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0'])), (cirq.Circuit(cirq.H(q0)), _build_gate_proto("HP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0'])), # XPOW and aliases. (cirq.Circuit(cirq.XPowGate(exponent=0.3)(q0)), _build_gate_proto("XP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0'])), (cirq.Circuit(cirq.XPowGate(exponent=sympy.Symbol('alpha'))(q0)), _build_gate_proto("XP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0'])), (cirq.Circuit(cirq.XPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0)), _build_gate_proto("XP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0'])), (cirq.Circuit(cirq.X(q0)), _build_gate_proto("XP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0'])), # YPOW and aliases (cirq.Circuit(cirq.YPowGate(exponent=0.3)(q0)), _build_gate_proto("YP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0'])), (cirq.Circuit(cirq.YPowGate(exponent=sympy.Symbol('alpha'))(q0)), _build_gate_proto("YP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0'])), (cirq.Circuit(cirq.YPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0)), _build_gate_proto("YP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0'])), (cirq.Circuit(cirq.Y(q0)), _build_gate_proto("YP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0'])), # ZPOW and aliases. (cirq.Circuit(cirq.ZPowGate(exponent=0.3)(q0)), _build_gate_proto("ZP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0'])), (cirq.Circuit(cirq.ZPowGate(exponent=sympy.Symbol('alpha'))(q0)), _build_gate_proto("ZP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0'])), (cirq.Circuit(cirq.ZPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0)), _build_gate_proto("ZP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0'])), (cirq.Circuit(cirq.Z(q0)), _build_gate_proto("ZP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0'])), # XXPow and aliases (cirq.Circuit(cirq.XXPowGate(exponent=0.3)(q0, q1)), _build_gate_proto("XXP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.XXPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("XXP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.XXPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("XXP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.XX(q0, q1)), _build_gate_proto("XXP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0', '0_1'])), # YYPow and aliases (cirq.Circuit(cirq.YYPowGate(exponent=0.3)(q0, q1)), _build_gate_proto("YYP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.YYPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("YYP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.YYPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("YYP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.YY(q0, q1)), _build_gate_proto("YYP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0', '0_1'])), # ZZPow and aliases (cirq.Circuit(cirq.ZZPowGate(exponent=0.3)(q0, q1)), _build_gate_proto("ZZP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.ZZPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("ZZP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.ZZPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("ZZP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.ZZ(q0, q1)), _build_gate_proto("ZZP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0', '0_1'])), # CZPow and aliases (cirq.Circuit(cirq.CZPowGate(exponent=0.3)(q0, q1)), _build_gate_proto("CZP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.CZPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("CZP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.CZPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("CZP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.CZ(q0, q1)), _build_gate_proto("CZP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0', '0_1'])), # CNOTPow and aliases (cirq.Circuit(cirq.CNotPowGate(exponent=0.3)(q0, q1)), _build_gate_proto("CNP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.CNotPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("CNP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.CNotPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("CNP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.CNOT(q0, q1)), _build_gate_proto("CNP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0', '0_1'])), # SWAPPow and aliases (cirq.Circuit(cirq.SwapPowGate(exponent=0.3)(q0, q1)), _build_gate_proto("SP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.SwapPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("SP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.SwapPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("SP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.SWAP(q0, q1)), _build_gate_proto("SP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0', '0_1'])), # ISWAPPow and aliases (cirq.Circuit(cirq.ISwapPowGate(exponent=0.3)(q0, q1)), _build_gate_proto("ISP", ['exponent', 'exponent_scalar', 'global_shift'], [0.3, 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.ISwapPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("ISP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 1.0, 0.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.ISwapPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)), _build_gate_proto("ISP", ['exponent', 'exponent_scalar', 'global_shift'], ['alpha', 3.1, 0.0], ['0_0', '0_1'])), (cirq.Circuit(cirq.ISWAP(q0, q1)), _build_gate_proto("ISP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, 0.0], ['0_0', '0_1'])), # PhasedXPow and aliases (cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=0.9, exponent=0.3, global_shift=0.2)(q0)), _build_gate_proto("PXP", [ 'phase_exponent', 'phase_exponent_scalar', 'exponent', 'exponent_scalar', 'global_shift' ], [0.9, 1.0, 0.3, 1.0, 0.2], ['0_0'])), (cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=sympy.Symbol('alpha'), exponent=0.3)(q0)), _build_gate_proto("PXP", [ 'phase_exponent', 'phase_exponent_scalar', 'exponent', 'exponent_scalar', 'global_shift' ], ['alpha', 1.0, 0.3, 1.0, 0.0], ['0_0'])), (cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=3.1 * sympy.Symbol('alpha'), exponent=0.3)(q0)), _build_gate_proto("PXP", [ 'phase_exponent', 'phase_exponent_scalar', 'exponent', 'exponent_scalar', 'global_shift' ], ['alpha', 3.1, 0.3, 1.0, 0.0], ['0_0'])), (cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=0.9, exponent=sympy.Symbol('beta'))(q0)), _build_gate_proto("PXP", [ 'phase_exponent', 'phase_exponent_scalar', 'exponent', 'exponent_scalar', 'global_shift' ], [0.9, 1.0, 'beta', 1.0, 0.0], ['0_0'])), (cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=0.9, exponent=5.1 * sympy.Symbol('beta'))(q0)), _build_gate_proto("PXP", [ 'phase_exponent', 'phase_exponent_scalar', 'exponent', 'exponent_scalar', 'global_shift' ], [0.9, 1.0, 'beta', 5.1, 0.0], ['0_0'])), (cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=3.1 * sympy.Symbol('alpha'), exponent=5.1 * sympy.Symbol('beta'))(q0)), _build_gate_proto("PXP", [ 'phase_exponent', 'phase_exponent_scalar', 'exponent', 'exponent_scalar', 'global_shift' ], ['alpha', 3.1, 'beta', 5.1, 0.0], ['0_0'])), # RX, RY, RZ with symbolization is tested in special cases as the # string comparison of the float converted sympy.pi does not happen # smoothly. See: test_serialize_deserialize_special_case_one_qubit (cirq.Circuit(cirq.rx(np.pi)(q0)), _build_gate_proto("XP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, -0.5], ['0_0'])), (cirq.Circuit(cirq.ry(np.pi)(q0)), _build_gate_proto("YP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, -0.5], ['0_0'])), (cirq.Circuit(cirq.rz(np.pi)(q0)), _build_gate_proto("ZP", ['exponent', 'exponent_scalar', 'global_shift'], [1.0, 1.0, -0.5], ['0_0'])), # Identity (cirq.Circuit(cirq.I(q0)), _build_gate_proto("I", ['unused'], [True], ['0_0'])), # FSimGate (cirq.Circuit(cirq.FSimGate(theta=0.1, phi=0.2)(q0, q1)), _build_gate_proto("FSIM", ['theta', 'theta_scalar', 'phi', 'phi_scalar'], [0.1, 1.0, 0.2, 1.0], ['0_0', '0_1'])), (cirq.Circuit( cirq.FSimGate(theta=2.1 * sympy.Symbol("alpha"), phi=1.3 * sympy.Symbol("beta"))(q0, q1)), _build_gate_proto("FSIM", ['theta', 'theta_scalar', 'phi', 'phi_scalar'], ['alpha', 2.1, 'beta', 1.3], ['0_0', '0_1'])), ] return pairs
def cz_and_swap(q0, q1, rot): """Yields a controlled-RZ gate and SWAP gate on the input qubits.""" yield cirq.CZ(q0, q1)**rot yield cirq.SWAP(q0, q1)
def _cz_and_swap(q0, q1, rot): yield cirq.CZ(q0, q1) ** rot yield cirq.SWAP(q0, q1)
def test_not_a_swap(exponent): a, b = cirq.LineQubit.range(2) assert not cirq.optimizers.eject_z._is_swaplike(cirq.SWAP(a, b)**exponent)
def _swap_and_zz(q_0: cirq.GridQubit, q_1: cirq.GridQubit, zz_coeff: float) -> List[cirq.Gate]: gate_seq = [cirq.SWAP(q_0, q_1)] if zz_coeff != 0: gate_seq.append(cirq.ZZ(q_0, q_1)**zz_coeff) return gate_seq
Q, Q2, Q3 = cirq.LineQubit.range(3) @pytest.mark.parametrize( "op,expected", [ (cirq.H(Q), True), (cirq.HPowGate(exponent=0.5)(Q), False), (cirq.PhasedXPowGate(exponent=0.25, phase_exponent=0.125)(Q), True), (cirq.XPowGate(exponent=0.5)(Q), True), (cirq.YPowGate(exponent=0.25)(Q), True), (cirq.ZPowGate(exponent=0.125)(Q), True), (cirq.CZPowGate(exponent=0.5)(Q, Q2), False), (cirq.CZ(Q, Q2), True), (cirq.CNOT(Q, Q2), True), (cirq.SWAP(Q, Q2), False), (cirq.ISWAP(Q, Q2), False), (cirq.CCNOT(Q, Q2, Q3), True), (cirq.CCZ(Q, Q2, Q3), True), (cirq.ParallelGate(cirq.X, num_copies=3)(Q, Q2, Q3), True), (cirq.ParallelGate(cirq.Y, num_copies=3)(Q, Q2, Q3), True), (cirq.ParallelGate(cirq.Z, num_copies=3)(Q, Q2, Q3), True), (cirq.X(Q).controlled_by(Q2, Q3), True), (cirq.Z(Q).controlled_by(Q2, Q3), True), (cirq.ZPowGate(exponent=0.5)(Q).controlled_by(Q2, Q3), False), ], ) def test_gateset(op: cirq.Operation, expected: bool): gs = cirq_pasqal.PasqalGateset() assert gs.validate(op) == expected assert gs.validate(cirq.Circuit(op)) == expected
import cirq circuit = cirq.Circuit() #首先创建一个电路来,可以通过添加电路来创建它 circuit.append(cirq.H(q) for q in cirq.LineQubit.range(3)) # 由于没有重叠,所有闸门都置于相同的时刻 print(circuit) # 我们页可以直接创建一个电路 print(cirq.Circuit((cirq.SWAP(q, q + 1) for q in cirq.LineQubit.range(3)))) #不希望cirq自动将操作一直移到最左边。要在不执行此操作的情况下构建电路,可以按瞬间创建电路,也可以使用其他方法 # 在单独的时刻创建每个门。 print(cirq.Circuit(cirq.Moment([cirq.H(q)]) for q in cirq.LineQubit.range(3)))
def bernstein(error_correct=False): API_TOKEN = '7cf33cd2f0d7044af8518c33321fa74d7380d3ba58d08b271404e8226aa1f5490818ba86e1635f89e6c3cfbf10aa091ff04c1f5ff61f0f391ed780b4484e0b18' # initialize qiskit IBMQ.save_account(API_TOKEN) provider = IBMQ.load_account() print(provider.backends()) backend = provider.backends.ibmq_16_melbourne # initialize qubits with architecture in mind qubits = [cirq.GridQubit(0, 5), cirq.GridQubit(1, 4),\ cirq.GridQubit(0, 6), cirq.GridQubit(2, 5),\ cirq.GridQubit(2, 3), cirq.GridQubit(1, 5),\ cirq.GridQubit(3, 4), cirq.GridQubit(2, 4)] if error_correct: error_qubits = [cirq.GridQubit(3, 4), cirq.GridQubit(3, 3),\ cirq.GridQubit(3, 2), cirq.GridQubit(4, 3)] # construct circuit circuit = cirq.Circuit() # error correction setup. error correct qubit (2,3) if error_correct: circuit.append([cirq.CNOT(qubits[2], error_qubits[1])]) circuit.append([cirq.SWAP(error_qubits[0], error_qubits[1])]) circuit.append([cirq.CNOT(qubits[2], error_qubits[1])]) circuit.append([cirq.SWAP(error_qubits[0], error_qubits[1])]) # hadamards circuit.append([cirq.H(q) for q in qubits]) # turn helper qubit to 1 circuit.append([cirq.Z(qubits[7])]) # oracle circuit.append([cirq.CNOT(qubits[1], qubits[7])]) circuit.append([cirq.CNOT(qubits[3], qubits[7])]) circuit.append([cirq.CNOT(qubits[4], qubits[7])]) circuit.append([cirq.CNOT(qubits[6], qubits[7])]) # hadamards circuit.append([cirq.H(q) for q in qubits[:-1]]) # error detection and correction if error_correct: circuit.append([cirq.SWAP(error_qubits[2], error_qubits[1])]) circuit.append([cirq.CNOT(qubits[2], error_qubits[1])]) circuit.append([cirq.SWAP(error_qubits[2], error_qubits[1])]) circuit.append([cirq.CNOT(error_qubits[1], error_qubits[2])]) circuit.append([cirq.SWAP(error_qubits[3], error_qubits[1])]) circuit.append([cirq.CNOT(qubits[2], error_qubits[1])]) circuit.append([cirq.CNOT(error_qubits[0], error_qubits[1])]) circuit.append([cirq.SWAP(error_qubits[1], error_qubits[3])]) circuit.append( [cirq.measure(error_qubits[2]), cirq.measure(error_qubits[3])]) circuit.append( [cirq.CCNOT(qubits[2], error_qubits[1], error_qubits[0])]) # measure circuit.append([cirq.measure(q) for q in qubits[:-1]]) # export to qasm qasm_str = circuit.to_qasm() # import qiskit from qasm qiskit_circuit = qiskitqc.from_qasm_str(qasm_str) # run qiskit transpiled = transpile(qiskit_circuit, backend) qobj = assemble(transpiled, backend, shots=100) job = backend.run(qobj) print(job.job_id()) result = job.result() counts = result.get_counts() delayed_result = backend.retrieve_job(job.job_id()).result() delayed_counts = delayed_result.get_counts() print(counts) print(delayed_counts) return requests.post(url, json=job_payload)
def generate_decomposed_swap( q1: cirq.Qid, q2: cirq.Qid) -> Generator[cirq.Operation, None, None]: """Generates a SWAP operation using sqrt-iswap gates.""" yield from cirq.google.optimized_for_sycamore( cirq.Circuit(cirq.SWAP(q1, q2))).all_operations()
pprint(oper_noU) print('U phase U TIMES (phase with opposite sign)') pprint(simplify(oper @ oper_noU.subs(t1, -t1).subs(t2, -t2).subs(t3, -t3).subs(t4, -t4))) # swap_T1C2 = kronecker_product(eye(2), SWAP(π/2), eye(2)) # oper = swap_T1C2 @ oper @ swap_T1C2 # print('Now with swapped such that the order is : C1 T1 C2 T2') # pprint(oper) # --- Again with Cirq --- print('CIRCUIT') qc2 = cirq.Circuit() _t1, _t2, _t3, _t4 = 1,2,3,4 qc2.append(cirq.SWAP(T1, T2).controlled_by(C1, C2)) qc2.append(cirq.SWAP(T1, T2).controlled_by(C1, C2, control_values=[0,0])) qc2.append(cirq.SWAP(C1, C2).controlled_by(T1, T2)) qc2.append(cirq.SWAP(C1, C2).controlled_by(T1, T2, control_values=[0,0])) qc2.append(cirq.ZPowGate().on(C1)**(_t1/np.pi)) qc2.append(cirq.ZPowGate().on(C2)**(_t2/np.pi)) qc2.append(cirq.ZPowGate().on(T1)**(_t3/np.pi)) qc2.append(cirq.ZPowGate().on(T2)**(_t4/np.pi)) qc2.append(cirq.SWAP(T1, T2).controlled_by(C1, C2)) qc2.append(cirq.SWAP(T1, T2).controlled_by(C1, C2, control_values=[0,0])) qc2.append(cirq.SWAP(C1, C2).controlled_by(T1, T2)) qc2.append(cirq.SWAP(C1, C2).controlled_by(T1, T2, control_values=[0,0])) criq_unitary = qc2.unitary(qubit_order=qubit_order) ndtotext_print(criq_unitary) print('The one from nympy with same values for t:')
undiagrammable_op = UndiagrammableGate()(qbits[1]) c_op = cirq.ControlledOperation(qbits[:1], undiagrammable_op) assert cirq.circuit_diagram_info(c_op, default=None) is None @pytest.mark.parametrize('gate', [ cirq.X(cirq.NamedQubit('q1')), cirq.X(cirq.NamedQubit('q1'))**0.5, cirq.rx(np.pi)(cirq.NamedQubit('q1')), cirq.rx(np.pi / 2)(cirq.NamedQubit('q1')), cirq.Z(cirq.NamedQubit('q1')), cirq.H(cirq.NamedQubit('q1')), cirq.CNOT(cirq.NamedQubit('q1'), cirq.NamedQubit('q2')), cirq.SWAP(cirq.NamedQubit('q1'), cirq.NamedQubit('q2')), cirq.CCZ(cirq.NamedQubit('q1'), cirq.NamedQubit('q2'), cirq.NamedQubit('q3')), cirq.ControlledGate(cirq.ControlledGate( cirq.CCZ))(*cirq.LineQubit.range(5)), GateUsingWorkspaceForApplyUnitary()(cirq.NamedQubit('q1')), GateAllocatingNewSpaceForResult()(cirq.NamedQubit('q1')), ]) def test_controlled_operation_is_consistent(gate: cirq.GateOperation): cb = cirq.NamedQubit('ctr') cgate = cirq.ControlledOperation([cb], gate) cirq.testing.assert_implements_consistent_protocols(cgate) cgate = cirq.ControlledOperation([cb], gate, control_values=[0]) cirq.testing.assert_implements_consistent_protocols(cgate)
def test_half_swap_does_merge(): args = create_container(qs2) args.apply_operation(cirq.SWAP(q0, q1)**0.5) assert len(set(args.values())) == 2 assert args[q0] is args[q1]