def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.Y.on(input_qubit[1])) # number=2 c.append(cirq.Y.on(input_qubit[1])) # number=4 c.append(cirq.Y.on(input_qubit[1])) # number=3 c.append(cirq.rx(2.0860175219836226).on(input_qubit[1])) # number=7 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=16 c.append(cirq.X.on(input_qubit[0])) # number=17 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=18 c.append(cirq.X.on(input_qubit[0])) # number=6 c.append(cirq.H.on(input_qubit[0])) # number=10 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=11 c.append(cirq.H.on(input_qubit[0])) # number=12 c.append(cirq.H.on(input_qubit[0])) # number=13 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=14 c.append(cirq.H.on(input_qubit[0])) # number=15 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c
def test_density_matrix_copy(): sim = cirq.DensityMatrixSimulator() q = cirq.LineQubit(0) circuit = cirq.Circuit(cirq.H(q), cirq.H(q)) matrices = [] for step in sim.simulate_moment_steps(circuit): matrices.append(step.density_matrix(copy=True)) assert all(np.isclose(np.trace(x), 1.0) for x in matrices) for x, y in itertools.combinations(matrices, 2): assert not np.shares_memory(x, y) # If the density matrix is not copied, then applying second Hadamard # causes old state to be modified. matrices = [] traces = [] for step in sim.simulate_moment_steps(circuit): matrices.append(step.density_matrix(copy=False)) traces.append(np.trace(step.density_matrix(copy=False))) assert any(not np.isclose(np.trace(x), 1.0) for x in matrices) assert all(np.isclose(x, 1.0) for x in traces) assert all(not np.shares_memory(x, y) for x, y in itertools.combinations(matrices, 2))
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=9 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.Y.on(input_qubit[3])) # number=12 c.append(cirq.H.on(input_qubit[0])) # number=5 c.append(cirq.H.on(input_qubit[1])) # number=6 c.append(cirq.H.on(input_qubit[2])) # number=7 c.append(cirq.H.on(input_qubit[3])) # number=8 c.append(cirq.H.on(input_qubit[3])) # number=30 c.append(cirq.CZ.on(input_qubit[0], input_qubit[3])) # number=31 c.append(cirq.H.on(input_qubit[3])) # number=32 c.append(cirq.X.on(input_qubit[3])) # number=28 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[3])) # number=29 c.append(cirq.Y.on(input_qubit[2])) # number=10 c.append(cirq.Y.on(input_qubit[2])) # number=11 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=13 c.append(cirq.H.on(input_qubit[0])) # number=15 c.append(cirq.CZ.on(input_qubit[1], input_qubit[0])) # number=16 c.append(cirq.H.on(input_qubit[1])) # number=20 c.append(cirq.H.on(input_qubit[2])) # number=19 c.append(cirq.CNOT.on(input_qubit[3], input_qubit[0])) # number=24 c.append(cirq.Z.on(input_qubit[3])) # number=25 c.append(cirq.CNOT.on(input_qubit[3], input_qubit[0])) # number=26 c.append(cirq.H.on(input_qubit[0])) # number=17 c.append(cirq.CNOT.on(input_qubit[2], input_qubit[0])) # number=21 c.append(cirq.X.on(input_qubit[1])) # number=23 c.append(cirq.CNOT.on(input_qubit[2], input_qubit[0])) # number=22 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c
def test_convert(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit.from_ops( cirq.X(q0), cirq.Y(q1) ** 0.5, cirq.Z(q0) ** -0.5, cirq.Z(q1) ** 0, cirq.H(q0), ) c_orig = cirq.Circuit(circuit) ConvertToSingleQubitCliffordGates().optimize_circuit(circuit) assert all(isinstance(op.gate, cirq.SingleQubitCliffordGate) for op in circuit.all_operations()) cirq.testing.assert_allclose_up_to_global_phase(circuit.unitary(), c_orig.unitary(), atol=1e-7) cirq.testing.assert_has_diagram(circuit, """ 0: ───X───────Z^-0.5───H─── 1: ───Y^0.5───I──────────── """)
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=7 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.CNOT.on(input_qubit[3], input_qubit[0])) # number=5 c.append(cirq.H.on(input_qubit[0])) # number=17 c.append(cirq.CZ.on(input_qubit[3], input_qubit[0])) # number=18 c.append(cirq.H.on(input_qubit[0])) # number=19 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=8 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=9 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=10 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=11 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=12 c.append(cirq.Z.on(input_qubit[3])) # number=16 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=13 c.append(cirq.SWAP.on(input_qubit[3], input_qubit[0])) # number=14 c.append(cirq.SWAP.on(input_qubit[3], input_qubit[0])) # number=15 # circuit end return c
def test_completes_weight_zero_billion_laughs(): circuit = cirq.quirk_url_to_circuit( 'https://algassert.com/quirk#circuit={' '"cols":[["~z"]],' '"gates":[' '{"id":"~a","circuit":{"cols":[' '["•"],["inputA2"],["setA"],["⊗","xpar"]]}},' '{"id":"~b","circuit":{"cols":[["~a"],["~a"],["~a"],["~a"]]}},' '{"id":"~c","circuit":{"cols":[["~b"],["~b"],["~b"],["~b"]]}},' '{"id":"~d","circuit":{"cols":[["~c"],["~c"],["~c"],["~c"]]}},' '{"id":"~e","circuit":{"cols":[["~d"],["~d"],["~d"],["~d"]]}},' '{"id":"~f","circuit":{"cols":[["~e"],["~e"],["~e"],["~e"]]}},' '{"id":"~g","circuit":{"cols":[["~f"],["~f"],["~f"],["~f"]]}},' '{"id":"~h","circuit":{"cols":[["~g"],["~g"],["~g"],["~g"]]}},' '{"id":"~i","circuit":{"cols":[["~h"],["~h"],["~h"],["~h"]]}},' '{"id":"~j","circuit":{"cols":[["~i"],["~i"],["~i"],["~i"]]}},' '{"id":"~k","circuit":{"cols":[["~j"],["~j"],["~j"],["~j"]]}},' '{"id":"~l","circuit":{"cols":[["~k"],["~k"],["~k"],["~k"]]}},' '{"id":"~m","circuit":{"cols":[["~l"],["~l"],["~l"],["~l"]]}},' '{"id":"~n","circuit":{"cols":[["~m"],["~m"],["~m"],["~m"]]}},' '{"id":"~o","circuit":{"cols":[["~n"],["~n"],["~n"],["~n"]]}},' '{"id":"~p","circuit":{"cols":[["~o"],["~o"],["~o"],["~o"]]}},' '{"id":"~q","circuit":{"cols":[["~p"],["~p"],["~p"],["~p"]]}},' '{"id":"~r","circuit":{"cols":[["~q"],["~q"],["~q"],["~q"]]}},' '{"id":"~s","circuit":{"cols":[["~r"],["~r"],["~r"],["~r"]]}},' '{"id":"~t","circuit":{"cols":[["~s"],["~s"],["~s"],["~s"]]}},' '{"id":"~u","circuit":{"cols":[["~t"],["~t"],["~t"],["~t"]]}},' '{"id":"~v","circuit":{"cols":[["~u"],["~u"],["~u"],["~u"]]}},' '{"id":"~w","circuit":{"cols":[["~v"],["~v"],["~v"],["~v"]]}},' '{"id":"~x","circuit":{"cols":[["~w"],["~w"],["~w"],["~w"]]}},' '{"id":"~y","circuit":{"cols":[["~x"],["~x"],["~x"],["~x"]]}},' '{"id":"~z","circuit":{"cols":[["~y"],["~y"],["~y"],["~y"]]}}' ']}', max_operation_count=0, ) assert circuit == cirq.Circuit()
def test_measure_grouped_settings(with_circuit_sweep): qubits = cirq.LineQubit.range(1) (q, ) = qubits tests = [ (cirq.KET_ZERO, cirq.Z, 1), (cirq.KET_ONE, cirq.Z, -1), (cirq.KET_PLUS, cirq.X, 1), (cirq.KET_MINUS, cirq.X, -1), (cirq.KET_IMAG, cirq.Y, 1), (cirq.KET_MINUS_IMAG, cirq.Y, -1), ] if with_circuit_sweep: ss = cirq.Linspace('a', 0, 1, 12) else: ss = None for init, obs, coef in tests: setting = cw.InitObsSetting( init_state=init(q), observable=obs(q), ) grouped_settings = {setting: [setting]} circuit = cirq.Circuit(cirq.I.on_each(*qubits)) results = cw.measure_grouped_settings( circuit=circuit, grouped_settings=grouped_settings, sampler=cirq.Simulator(), stopping_criteria=cw.RepetitionsStoppingCriteria(1_000), circuit_sweep=ss, ) if with_circuit_sweep: for result in results: assert result.means() == [coef] else: (result, ) = results # one group assert result.means() == [coef]
def test_prepare_gaussian_state(n_qubits, conserves_particle_number, occupied_orbitals, initial_state, atol=1e-5): qubits = LineQubit.range(n_qubits) if isinstance(initial_state, list): initial_state = sum(1 << (n_qubits - 1 - i) for i in initial_state) # Initialize a random quadratic Hamiltonian quad_ham = random_quadratic_hamiltonian(n_qubits, conserves_particle_number, real=False) quad_ham_sparse = get_sparse_operator(quad_ham) # Compute the energy of the desired state if occupied_orbitals is None: energy = quad_ham.ground_energy() else: orbital_energies, _, constant = ( quad_ham.diagonalizing_bogoliubov_transform()) energy = sum(orbital_energies[i] for i in occupied_orbitals) + constant # Get the state using a circuit simulation circuit = cirq.Circuit( prepare_gaussian_state(qubits, quad_ham, occupied_orbitals, initial_state=initial_state)) state = circuit.final_wavefunction(initial_state) # Check that the result is an eigenstate with the correct eigenvalue numpy.testing.assert_allclose(quad_ham_sparse.dot(state), energy * state, atol=atol)
def test_quadratic_fermionic_simulation_gate_unitary(weights, exponent): generator = np.zeros((4, 4), dtype=np.complex128) # w0 |10><01| + h.c. generator[2, 1] = weights[0] generator[1, 2] = weights[0].conjugate() # w1 |11><11| generator[3, 3] = weights[1] expected_unitary = la.expm(-1j * exponent * generator) gate = openfermion.QuadraticFermionicSimulationGate(weights, exponent=exponent) actual_unitary = cirq.unitary(gate) assert np.allclose(expected_unitary, actual_unitary) symbolic_gate = (openfermion.QuadraticFermionicSimulationGate( (sympy.Symbol('w0'), sympy.Symbol('w1')), exponent=sympy.Symbol('t'))) qubits = cirq.LineQubit.range(2) circuit = cirq.Circuit(symbolic_gate._decompose_(qubits)) resolver = {'w0': weights[0], 'w1': weights[1], 't': exponent} resolved_circuit = cirq.resolve_parameters(circuit, resolver) decomp_unitary = resolved_circuit.unitary(qubit_order=qubits) assert np.allclose(expected_unitary, decomp_unitary)
def single_gate_ops( target_qubits: List[cirq.GridQubit], matrix: np.ndarray) -> Tuple[cirq.OP_TREE, List[cirq.GridQubit]]: circs = [] circs2 = [] circs.append(([], [])) circs2.append(([], [])) first = True for i, circ in enumerate(circs): list, ancilla = circs2[i] unit = cirq.unitary(cirq.Circuit(list)) if first: #print(matrix) first = False if np.allclose(matrix, unit, atol=0.00001): return circ a = target_qubits[0] for gate in [cirq.X, cirq.Y, cirq.Z]: if np.allclose(matrix, (cirq.unitary(gate)), atol=0.00001): return [gate(a)], [] for gate in [cirq.H]: #,cirq.Y,cirq.Z]: if np.allclose(matrix, (cirq.unitary(gate)), atol=0.00001): return [cirq.Z(a), cirq.Y(a)**0.5], [] for gate in [cirq.S]: #,cirq.Y,cirq.Z]: if np.allclose(matrix, (cirq.unitary(gate)), atol=0.00001): return [cirq.Z(a)**0.5], [] for gate in [cirq.T]: #,cirq.Y,cirq.Z]: if np.allclose(matrix, (cirq.unitary(gate)), atol=0.00001): return [cirq.Z(a)**0.25], [] return NotImplemented, []
def test_sampler_sample_sweep(): a = cirq.LineQubit(0) t = sympy.Symbol('t') sampler = cirq.Simulator() circuit = cirq.Circuit(cirq.X(a) ** t, cirq.measure(a, key='out')) results = sampler.sample(circuit, repetitions=3, params=cirq.Linspace('t', 0, 2, 3)) pd.testing.assert_frame_equal( results, pd.DataFrame( columns=['t', 'out'], index=[0, 1, 2] * 3, data=[ [0.0, 0], [0.0, 0], [0.0, 0], [1.0, 1], [1.0, 1], [1.0, 1], [2.0, 0], [2.0, 0], [2.0, 0], ], ), )
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=7 c.append(cirq.rx(-1.6619025137490007).on(input_qubit[2])) # number=15 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.H.on(input_qubit[0])) # number=18 c.append(cirq.CZ.on(input_qubit[3], input_qubit[0])) # number=19 c.append(cirq.H.on(input_qubit[0])) # number=20 c.append(cirq.rx(-0.0785398163397449).on(input_qubit[2])) # number=16 c.append(cirq.H.on(input_qubit[0])) # number=12 c.append(cirq.CZ.on(input_qubit[3], input_qubit[0])) # number=13 c.append(cirq.H.on(input_qubit[0])) # number=14 c.append(cirq.X.on(input_qubit[3])) # number=17 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=8 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=9 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=10 c.append(cirq.SWAP.on(input_qubit[1], input_qubit[0])) # number=11 # circuit end return c
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")
def test_text_diagrams(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') circuit = cirq.Circuit(cirq.X(a), cirq.Y(a), cirq.Z(a), cirq.Z(a)**sympy.Symbol('x'), cirq.rx(sympy.Symbol('x')).on(a), cirq.CZ(a, b), cirq.CNOT(a, b), cirq.CNOT(b, a), cirq.H(a)**0.5, cirq.I(a), cirq.IdentityGate(2)(a, b)) cirq.testing.assert_has_diagram( circuit, """ a: ───X───Y───Z───Z^x───Rx(x)───@───@───X───H^0.5───I───I─── │ │ │ │ b: ─────────────────────────────@───X───@───────────────I─── """) cirq.testing.assert_has_diagram(circuit, """ a: ---X---Y---Z---Z^x---Rx(x)---@---@---X---H^0.5---I---I--- | | | | b: -----------------------------@---X---@---------------I--- """, use_unicode_characters=False)
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.rx(-0.09738937226128368).on(input_qubit[2])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=3 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=4 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=10 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[1])) # number=15 c.append(cirq.X.on(input_qubit[1])) # number=16 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[1])) # number=17 c.append(cirq.Z.on(input_qubit[1])) # number=11 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=12 c.append(cirq.Y.on(input_qubit[1])) # number=14 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=5 c.append(cirq.X.on(input_qubit[1])) # number=6 c.append(cirq.Z.on(input_qubit[1])) # number=8 c.append(cirq.X.on(input_qubit[1])) # number=7 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c
def test_cubic_fermionic_simulation_gate_text_diagram(): gate = openfermion.CubicFermionicSimulationGate((1, 1, 1)) qubits = cirq.LineQubit.range(5) circuit = cirq.Circuit([gate(*qubits[:3]), gate(*qubits[2:5])]) assert super(type(gate), gate).wire_symbol(False) == type(gate).__name__ assert (super(type(gate), gate)._diagram_exponent( cirq.CircuitDiagramInfoArgs.UNINFORMED_DEFAULT) == gate._exponent) expected_text_diagram = """ 0: ───↕↓↑(1, 1, 1)────────────────── │ 1: ───↕↓↑─────────────────────────── │ 2: ───↕↓↑────────────↕↓↑(1, 1, 1)─── │ 3: ──────────────────↕↓↑──────────── │ 4: ──────────────────↕↓↑──────────── """.strip() cirq.testing.assert_has_diagram(circuit, expected_text_diagram) expected_text_diagram = """ 0: ---na*a(1, 1, 1)------------------- | 1: ---na*a---------------------------- | 2: ---na*a------------na*a(1, 1, 1)--- | 3: -------------------na*a------------ | 4: -------------------na*a------------ """.strip() cirq.testing.assert_has_diagram(circuit, expected_text_diagram, use_unicode_characters=False)
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.rx(-0.09738937226128368).on(input_qubit[2])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=30 c.append(cirq.CZ.on(input_qubit[2], input_qubit[1])) # number=31 c.append(cirq.H.on(input_qubit[1])) # number=32 c.append(cirq.H.on(input_qubit[1])) # number=3 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=4 c.append(cirq.Y.on(input_qubit[1])) # number=15 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=10 c.append(cirq.H.on(input_qubit[1])) # number=19 c.append(cirq.CZ.on(input_qubit[0], input_qubit[1])) # number=20 c.append(cirq.rx(-0.6000441968356504).on(input_qubit[1])) # number=28 c.append(cirq.H.on(input_qubit[1])) # number=21 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[1])) # number=22 c.append(cirq.X.on(input_qubit[1])) # number=23 c.append(cirq.H.on(input_qubit[2])) # number=29 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[1])) # number=24 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[1])) # number=18 c.append(cirq.Z.on(input_qubit[1])) # number=11 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=12 c.append(cirq.CNOT.on(input_qubit[2], input_qubit[1])) # number=26 c.append(cirq.Y.on(input_qubit[1])) # number=14 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=5 c.append(cirq.X.on(input_qubit[1])) # number=6 c.append(cirq.Z.on(input_qubit[1])) # number=8 c.append(cirq.X.on(input_qubit[1])) # number=7 c.append(cirq.rx(-2.42845112122491).on(input_qubit[1])) # number=25 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=9 c.append(cirq.rx(-1.9069467407290044).on(input_qubit[2])) # number=20 c.append(cirq.H.on(input_qubit[3])) # number=21 c.append(cirq.H.on(input_qubit[3])) # number=27 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.Y.on(input_qubit[2])) # number=13 c.append(cirq.rx(0.13823007675795101).on(input_qubit[2])) # number=24 c.append(cirq.H.on(input_qubit[0])) # number=5 c.append(cirq.H.on(input_qubit[1])) # number=6 c.append(cirq.H.on(input_qubit[2])) # number=7 c.append(cirq.H.on(input_qubit[3])) # number=8 c.append(cirq.X.on(input_qubit[3])) # number=1 c.append(cirq.rx(-1.9352210746113125).on(input_qubit[3])) # number=14 c.append(cirq.H.on(input_qubit[2])) # number=28 c.append(cirq.CZ.on(input_qubit[1], input_qubit[2])) # number=29 c.append(cirq.H.on(input_qubit[2])) # number=30 c.append(cirq.Y.on(input_qubit[2])) # number=10 c.append(cirq.H.on(input_qubit[1])) # number=17 c.append(cirq.CZ.on(input_qubit[3], input_qubit[1])) # number=18 c.append(cirq.H.on(input_qubit[1])) # number=19 c.append(cirq.Y.on(input_qubit[2])) # number=11 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=15 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=16 c.append(cirq.Z.on(input_qubit[3])) # number=23 c.append(cirq.Y.on(input_qubit[1])) # number=25 c.append(cirq.Y.on(input_qubit[1])) # number=26 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c
def make_simon_circuit(first_qubits, second_qubits, oracle): circuit = cirq.Circuit() #Apply the first set of Hadamard gates for i in range(0, number_qubits): circuit.append(cirq.H.on(first_qubits[i])) #Apply the oracle circuit.append(oracle) #Apply the second set of Hadamard gates for i in range(0, number_qubits): circuit.append(cirq.H.on(first_qubits[i])) #Perform measurements upon the qubits circuit.append(cirq.measure(*second_qubits, key='x')) circuit.append(cirq.measure(*first_qubits, key='y')) return circuit
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("")
def test_symbol_values_type(self, symbol_type): """Tests all three ops for the different types. """ qubit = cirq.GridQubit(0, 0) circuits = util.convert_to_tensor([cirq.Circuit(cirq.H(qubit))]) symbol_names = ['symbol'] symbol_values = tf.convert_to_tensor([[1]], dtype=symbol_type) pauli_sums = util.random_pauli_sums([qubit], 3, 1) pauli_sums = util.convert_to_tensor([[x] for x in pauli_sums]) result = tfq_simulate_ops.tfq_simulate_state(circuits, symbol_names, symbol_values) self.assertDTypeEqual(result, np.complex64) result = tfq_simulate_ops.tfq_simulate_expectation( circuits, symbol_names, symbol_values, pauli_sums) self.assertDTypeEqual(result, np.float32) result = tfq_simulate_ops.tfq_simulate_samples(circuits, symbol_names, symbol_values, [100]) self.assertDTypeEqual(result, np.int8) result = tfq_simulate_ops.tfq_simulate_sampled_expectation( circuits, symbol_names, symbol_values, pauli_sums, [[100]]) self.assertDTypeEqual(result, np.float32)
def test_sampling_empty(self, op_and_sim, n_qubits, symbol_names): """Test empty circuits for sampling using cirq and tfq.""" op = op_and_sim[0] sim = op_and_sim[1] qubits = cirq.GridQubit.rect(1, n_qubits) n_samples = int((2**n_qubits) * 1000) circuit_batch = [cirq.Circuit() for _ in range(BATCH_SIZE)] resolver_batch = [cirq.ParamResolver({}) for _ in range(BATCH_SIZE)] symbol_values_array = np.array([[0.0 for _ in symbol_names] for _ in resolver_batch]) op_samples = np.array( op(util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, [n_samples]).to_list()) op_histograms = [ np.histogram( sample.dot(1 << np.arange(sample.shape[-1] - 1, -1, -1)), range=(0, 2**len(qubits)), bins=2**len(qubits))[0] for sample in op_samples ] cirq_samples = batch_util.batch_sample(circuit_batch, resolver_batch, n_samples, sim) cirq_histograms = [ np.histogram( sample.dot(1 << np.arange(sample.shape[-1] - 1, -1, -1)), range=(0, 2**len(qubits)), bins=2**len(qubits))[0] for sample in cirq_samples ] for a, b in zip(op_histograms, cirq_histograms): self.assertLess(stats.entropy(a + 1e-8, b + 1e-8), 0.005)
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.rx(1.6147786239451536).on(input_qubit[3])) # number=5 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.H.on(input_qubit[0])) # number=8 c.append(cirq.CZ.on(input_qubit[1], input_qubit[0])) # number=9 c.append(cirq.rx(0.666017642561036).on(input_qubit[2])) # number=14 c.append(cirq.H.on(input_qubit[0])) # number=10 c.append(cirq.H.on(input_qubit[0])) # number=16 c.append(cirq.CZ.on(input_qubit[1], input_qubit[0])) # number=17 c.append(cirq.H.on(input_qubit[0])) # number=18 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=11 c.append(cirq.CNOT.on(input_qubit[1], input_qubit[0])) # number=12 c.append(cirq.CNOT.on(input_qubit[2], input_qubit[1])) # number=13 c.append(cirq.CNOT.on(input_qubit[2], input_qubit[3])) # number=15 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c
def __init__( self, num_qubits: int, circuit: cirq.Circuit = cirq.Circuit(), simulate_ideal: bool = False, noise_dict: Optional[Dict] = None, ): """Initializes the AQT simulator. Args: num_qubits: Number of qubits. circuit: Optional, circuit to be simulated. Last moment needs to be a measurement over all qubits with key 'm' simulate_ideal: If True, an ideal, noiseless, circuit will be simulated. noise_dict: A map from gate to noise to be applied after that gate. If None, uses a default noise model. """ self.circuit = circuit self.num_qubits = num_qubits self.qubit_list = cirq.LineQubit.range(num_qubits) if noise_dict is None: noise_dict = get_default_noise_dict() self.noise_dict = noise_dict self.simulate_ideal = simulate_ideal
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.SWAP.on(input_qubit[2], input_qubit[0])) # number=5 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[1])) # number=16 c.append(cirq.X.on(input_qubit[1])) # number=17 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[1])) # number=18 c.append(cirq.SWAP.on(input_qubit[2], input_qubit[0])) # number=6 c.append(cirq.rx(-1.0053096491487337).on(input_qubit[2])) # number=10 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[3])) # number=13 c.append(cirq.X.on(input_qubit[3])) # number=14 c.append(cirq.CNOT.on(input_qubit[0], input_qubit[3])) # number=15 c.append(cirq.X.on(input_qubit[3])) # number=9 c.append(cirq.X.on(input_qubit[2])) # number=11 c.append(cirq.X.on(input_qubit[2])) # number=12 c.append(cirq.CNOT.on(input_qubit[3], input_qubit[0])) # number=19 c.append(cirq.CNOT.on(input_qubit[3], input_qubit[0])) # number=20 # circuit end return c
def generate_circuit(nr_of_qubits, layers): qubits = cirq.GridQubit.rect( 1, nr_of_qubits) # Define qubit grid. In this case nr_parameters = 3 * nr_of_qubits * layers # 3 params for each qubit and layer symb = sympy.symbols('theta0:' + str(nr_parameters)) symbols = np.array(symb) symbols = symbols.reshape(layers, nr_of_qubits, 3) circuit = cirq.Circuit() for l in range(layers): # Add a series of single qubit rotations. for i, qubit in enumerate(qubits): circuit += cirq.rz(symbols[l][i][0])(qubit) circuit += cirq.rx(symbols[l][i][1])(qubit) circuit += cirq.rz(symbols[l][i][2])(qubit) circuit += cirq.CZ(qubits[0], qubits[1]) circuit += cirq.CZ(qubits[2], qubits[3]) circuit += cirq.CZ(qubits[1], qubits[2]) op = 1 / 4 * (cirq.X(qubits[0]) + cirq.X(qubits[1]) + cirq.X(qubits[2]) + cirq.X(qubits[3])) return circuit, op, list(symb)
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=5 c.append(cirq.X.on(input_qubit[1])) # number=7 c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=6 c.append(cirq.rx(-1.0053096491487337).on(input_qubit[2])) # number=10 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=13 c.append(cirq.X.on(input_qubit[3])) # number=14 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=15 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=16 c.append(cirq.X.on(input_qubit[3])) # number=17 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=18 c.append(cirq.X.on(input_qubit[2])) # number=11 c.append(cirq.X.on(input_qubit[2])) # number=12 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c
def test_custom_measurement(): class XBasisMeasurement(cirq.Gate): def __init__(self, key: str): self.key = key def _num_qubits_(self) -> int: return 1 def _decompose_(self, qubits): q, = qubits return [cirq.H(q), cirq.measure(q, key=self.key), cirq.H(q)] s = stimcirq.StimSampler() a, b = cirq.LineQubit.range(2) out = s.sample( cirq.Circuit( cirq.H(a), cirq.X(b), cirq.H(b), XBasisMeasurement("a").on(a), XBasisMeasurement("b").on(b), )) np.testing.assert_array_equal(out["a"], [0]) np.testing.assert_array_equal(out["b"], [1])
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=7 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.H.on(input_qubit[0])) # number=12 c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=13 c.append(cirq.Y.on(input_qubit[2])) # number=15 c.append(cirq.H.on(input_qubit[0])) # number=14 c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11 c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=16 c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=17 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c
def test_controlled_pqc_operators_error(self): """Test that invalid operators error properly.""" symbol = sympy.Symbol('alpha') bit = cirq.GridQubit(0, 0) learnable_flip = cirq.Circuit(cirq.X(bit)**symbol) with self.assertRaisesRegex( TypeError, expected_regex="cirq.PauliSum or cirq.PauliString"): noisy_controlled_pqc.NoisyControlledPQC(learnable_flip, 'junk', repetitions=500, sample_based=False) with self.assertRaisesRegex(TypeError, expected_regex="Each element"): noisy_controlled_pqc.NoisyControlledPQC(learnable_flip, [[cirq.Z(bit)]], repetitions=500, sample_based=False) with self.assertRaisesRegex(TypeError, expected_regex="Each element"): noisy_controlled_pqc.NoisyControlledPQC(learnable_flip, [cirq.Z(bit), 'bad'], repetitions=500, sample_based=False)