def test_aer_expanded_gates() -> None: c = Circuit(3).CX(0, 1) c.add_gate(OpType.ZZPhase, 0.1, [0, 1]) c.add_gate(OpType.CY, [0, 1]) c.add_gate(OpType.CCX, [0, 1, 2]) backend = AerBackend() assert backend.valid_circuit(c)
def test_process_characterisation_no_noise_model() -> None: my_noise_model = NoiseModel() back = AerBackend(my_noise_model) assert back.characterisation is None c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0) back.compile_circuit(c) assert back.valid_circuit(c)
def test_samples() -> None: qc = circuit_gen(True) b = AerBackend() for comp in (None, b.default_compilation_pass()): tb = TketBackend(b, comp) job = execute(qc, tb, shots=100, memory=True) shots = job.result().get_memory() assert all(((r[0] == "1" and r[1] == r[2]) for r in shots)) counts = job.result().get_counts() assert all(((r[0] == "1" and r[1] == r[2]) for r in counts.keys()))
def test_aer_placed_expectation() -> None: # bug TKET-695 n_qbs = 3 c = Circuit(n_qbs, n_qbs) c.X(0) c.CX(0, 2) c.CX(1, 2) c.H(1) # c.measure_all() b = AerBackend() operator = QubitPauliOperator({ QubitPauliString(Qubit(0), Pauli.Z): 1.0, QubitPauliString(Qubit(1), Pauli.X): 0.5, }) assert b.get_operator_expectation_value(c, operator) == (-0.5 + 0j) with open(os.path.join(sys.path[0], "ibmqx2_properties.pickle"), "rb") as f: properties = pickle.load(f) noise_model = NoiseModel.from_backend(properties) noise_b = AerBackend(noise_model) with pytest.raises(RuntimeError) as errorinfo: noise_b.get_operator_expectation_value(c, operator) assert "not supported with noise model" in str(errorinfo.value) c.rename_units({Qubit(1): Qubit("node", 1)}) with pytest.raises(ValueError) as errorinfoCirc: b.get_operator_expectation_value(c, operator) assert "default register Qubits" in str(errorinfoCirc.value)
def test_routing_measurements() -> None: qc = get_test_circuit(True) circ = qiskit_to_tk(qc) sim = AerBackend() original_results = sim.get_shots(circ, 10, seed=4) coupling = [[1, 0], [2, 0], [2, 1], [3, 2], [3, 4], [4, 2]] arc = Architecture(coupling) physical_c = route(circ, arc) Transform.DecomposeSWAPtoCX().apply(physical_c) Transform.DecomposeCXDirected(arc).apply(physical_c) Transform.OptimisePostRouting().apply(physical_c) assert (sim.get_shots(physical_c, 10) == original_results).all()
def test_mixed_circuit() -> None: c = Circuit() qr = c.add_q_register("q", 2) ar = c.add_c_register("a", 1) br = c.add_c_register("b", 1) c.H(qr[0]) c.Measure(qr[0], ar[0]) c.X(qr[1], condition=reg_eq(ar, 0)) c.Measure(qr[1], br[0]) backend = AerBackend() backend.compile_circuit(c) counts = backend.get_counts(c, 1024) for key in counts.keys(): assert key in {(0, 1), (1, 0)}
def test_cancellation_aer() -> None: b = AerBackend() c = circuit_gen(True) b.compile_circuit(c) h = b.process_circuit(c, 10) b.cancel(h) print(b.circuit_status(h))
def test_cancel() -> None: b = AerBackend() tb = TketBackend(b) qc = circuit_gen() job = execute(qc, tb) job.cancel() assert job.status() == JobStatus.CANCELLED
def test_operator() -> None: for b in [AerBackend(), AerStateBackend()]: c = circuit_gen() zz = QubitPauliOperator( {QubitPauliString([Qubit(0), Qubit(1)], [Pauli.Z, Pauli.Z]): 1.0}) assert cmath.isclose(get_operator_expectation_value(c, zz, b), 1.0) c.X(0) assert cmath.isclose(get_operator_expectation_value(c, zz, b), -1.0)
def test_ibmq_emulator() -> None: b_emu = IBMQEmulatorBackend("ibmq_santiago", hub="ibm-q", group="open", project="main") assert b_emu._noise_model is not None b_ibm = b_emu._ibmq b_aer = AerBackend() for ol in range(3): comp_pass = b_emu.default_compilation_pass(ol) c = Circuit(3, 3) c.H(0) c.CX(0, 1) c.CSWAP(1, 0, 2) c.ZZPhase(0.84, 2, 0) c_cop = c.copy() comp_pass.apply(c_cop) c.measure_all() for bac in (b_emu, b_ibm): assert all(pred.verify(c_cop) for pred in bac.required_predicates) c_cop_2 = c.copy() b_aer.compile_circuit(c_cop_2, ol) if ol == 0: assert not all( pred.verify(c_cop_2) for pred in b_emu.required_predicates) circ = Circuit(2, 2).H(0).CX(0, 1).measure_all() b_emu.compile_circuit(circ) b_noi = AerBackend(noise_model=b_emu._noise_model) emu_shots = b_emu.get_shots(circ, 10, seed=10) aer_shots = b_noi.get_shots(circ, 10, seed=10) assert np.array_equal(emu_shots, aer_shots)
def test_measures() -> None: n_qbs = 12 c = Circuit(n_qbs, n_qbs) x_qbs = [2, 5, 7, 11] for i in x_qbs: c.X(i) c.measure_all() b = AerBackend() shots = b.get_shots(c, 10) all_ones = True all_zeros = True for i in x_qbs: all_ones = all_ones and bool(np.all(shots[:, i])) for i in range(n_qbs): if i not in x_qbs: all_zeros = all_zeros and (not np.any(shots[:, i])) assert all_ones assert all_zeros
def test_pauli() -> None: for b in [AerBackend(), AerStateBackend()]: c = Circuit(2) c.Rz(0.5, 0) b.compile_circuit(c) zi = QubitPauliString(Qubit(0), Pauli.Z) assert cmath.isclose(get_pauli_expectation_value(c, zi, b), 1) c.X(0) assert cmath.isclose(get_pauli_expectation_value(c, zi, b), -1)
def test_nomeasure_warning() -> None: warnings.simplefilter("error") circuit = Circuit(2) warn_msg = "Circuit with index 0 in submitted does not contain a measure " "operation." with pytest.raises(UserWarning) as warninfo: AerBackend().get_shots(circuit, 4) assert warn_msg in str(warninfo.value) assert warninfo == UserWarning
def test_pauli_sim() -> None: c = Circuit(2, 2) c.Rz(0.5, 0) Transform.OptimisePostRouting().apply(c) b = AerBackend() zi = QubitPauliString(Qubit(0), Pauli.Z) energy = get_pauli_expectation_value(c, zi, b, 8000) assert abs(energy - 1) < 0.001 c.X(0) energy = get_pauli_expectation_value(c, zi, b, 8000) assert abs(energy + 1) < 0.001
def test_aer_default_pass() -> None: with open(os.path.join(sys.path[0], "ibmqx2_properties.pickle"), "rb") as f: properties = pickle.load(f) noise_model = NoiseModel.from_backend(properties) for nm in [None, noise_model]: b = AerBackend(nm) for ol in range(3): comp_pass = b.default_compilation_pass(ol) c = Circuit(3, 3) c.H(0) c.CX(0, 1) c.CSWAP(1, 0, 2) c.ZZPhase(0.84, 2, 0) c.add_gate(OpType.TK1, [0.2, 0.3, 0.4], [0]) comp_pass.apply(c) c.measure_all() for pred in b.required_predicates: assert pred.verify(c)
def test_aer_result_handle() -> None: c = Circuit(2, 2).H(0).CX(0, 1).measure_all() b = AerBackend() handles = b.process_circuits([c, c.copy()], n_shots=2) ids, indices = zip(*(han for han in handles)) assert all(isinstance(idval, str) for idval in ids) assert indices == (0, 1) assert len(b.get_result(handles[0]).get_shots()) == 2 with pytest.raises(TypeError) as errorinfo: _ = b.get_result(ResultHandle("43")) assert "ResultHandle('43',) does not match expected identifier types" in str( errorinfo.value) wronghandle = ResultHandle("asdf", 3) with pytest.raises(CircuitNotRunError) as errorinfoCirc: _ = b.get_result(wronghandle) assert "Circuit corresponding to {0!r} ".format( wronghandle) + "has not been run by this backend instance." in str( errorinfoCirc.value)
def test_ilo() -> None: b = AerBackend() bs = AerStateBackend() bu = AerUnitaryBackend() c = Circuit(2) c.X(1) assert (bs.get_state(c) == np.asarray([0, 1, 0, 0])).all() assert (bs.get_state(c, basis=BasisOrder.dlo) == np.asarray([0, 0, 1, 0])).all() assert (bu.get_unitary(c) == np.asarray([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])).all() assert (bu.get_unitary(c, basis=BasisOrder.dlo) == np.asarray([[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])).all() c.measure_all() assert (b.get_shots(c, 2) == np.asarray([[0, 1], [0, 1]])).all() assert (b.get_shots(c, 2, basis=BasisOrder.dlo) == np.asarray([[1, 0], [1, 0]])).all() assert b.get_counts(c, 2) == {(0, 1): 2} assert b.get_counts(c, 2, basis=BasisOrder.dlo) == {(1, 0): 2}
def test_process_characterisation_incomplete_noise_model() -> None: my_noise_model = NoiseModel() my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 1]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [1]) my_noise_model.add_quantum_error(depolarizing_error(0.1, 1), ["u3"], [3]) my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Z", 0.65)]), ["u2"], [0]) my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Y", 0.65)]), ["u1"], [2]) back = AerBackend(my_noise_model) char = cast(Dict[str, Any], back.characterisation) c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0).measure_all() back.compile_circuit(c) assert back.valid_circuit(c) dev = Device( char.get("NodeErrors", {}), char.get("EdgeErrors", {}), char.get("Architecture", Architecture([])), ) nodes = dev.nodes assert set(dev.architecture.coupling) == set([ (nodes[0], nodes[1]), (nodes[0], nodes[2]), (nodes[0], nodes[3]), (nodes[1], nodes[2]), (nodes[1], nodes[3]), (nodes[2], nodes[0]), (nodes[2], nodes[1]), (nodes[2], nodes[3]), (nodes[3], nodes[0]), (nodes[3], nodes[1]), (nodes[3], nodes[2]), ])
def iterated_noisy_experiment(dep_err_rate, ro_err_rate, max_iter): # Set up the noisy simulator with the given error rates test_model = make_noise_model(dep_err_rate, ro_err_rate, range(4)) backend = AerBackend(noise_model=test_model) # Estimate the fidelity after n iterations, from 0 to max_iter (inclusive) fid_list = [] for i in range(max_iter + 1): it_es, qubits = iterated_entanglement_swap(i) probs_list = run_tomography_circuits(it_es, qubits, [data[0], data[1]], backend) dm = fit_tomography_outcomes(probs_list, 2) fid = fidelity(dm, bell_state) fid_list.append(fid) return fid_list
def test_process_characterisation_complete_noise_model() -> None: my_noise_model = NoiseModel() readout_error_0 = 0.2 readout_error_1 = 0.3 my_noise_model.add_readout_error( [ [1 - readout_error_0, readout_error_0], [readout_error_0, 1 - readout_error_0], ], [0], ) my_noise_model.add_readout_error( [ [1 - readout_error_1, readout_error_1], [readout_error_1, 1 - readout_error_1], ], [1], ) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 1]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [0]) my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Z", 0.65)]), ["u2"], [0]) my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Y", 0.65)]), ["u1"], [0]) back = AerBackend(my_noise_model) char = cast(Dict[str, Any], back.characterisation) dev = Device( char.get("NodeErrors", {}), char.get("EdgeErrors", {}), char.get("Architecture", Architecture([])), ) assert char["GenericTwoQubitQErrors"][(0, 1)][0][1][0] == 0.0375 assert char["GenericTwoQubitQErrors"][(0, 1)][0][1][15] == 0.4375 assert char["GenericOneQubitQErrors"][0][0][1][0] == 0.125 assert char["GenericOneQubitQErrors"][0][0][1][3] == 0.625 assert char["GenericOneQubitQErrors"][0][1][1][0] == 0.35 assert char["GenericOneQubitQErrors"][0][1][1][1] == 0.65 assert char["GenericOneQubitQErrors"][0][2][1][0] == 0.35 assert char["GenericOneQubitQErrors"][0][2][1][1] == 0.65 assert dev.get_error(OpType.U3, dev.nodes[0]) == 0.375 assert dev.get_error(OpType.CX, (dev.nodes[0], dev.nodes[1])) == 0.5625 assert dev.get_error(OpType.CX, (dev.nodes[1], dev.nodes[0])) == 0.80859375 assert char["ReadoutErrors"][0] == [[0.8, 0.2], [0.2, 0.8]] assert char["ReadoutErrors"][1] == [[0.7, 0.3], [0.3, 0.7]]
def test_circuit_compilation_complete_noise_model() -> None: my_noise_model = NoiseModel() my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 1]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 2]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 3]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [1, 2]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [1, 3]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [2, 3]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [0]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [1]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [2]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [3]) back = AerBackend(my_noise_model) c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0).measure_all() back.compile_circuit(c) assert back.valid_circuit(c)
def test_aqua_algorithm() -> None: backends: List[Backend] = [AerBackend(), AerStateBackend()] if use_qulacs: backends.append(QulacsBackend()) for b in backends: for comp in (None, b.default_compilation_pass()): if use_qulacs and type(b) == QulacsBackend and comp is None: continue tb = TketBackend(b, comp) ora = TruthTableOracle(bitmaps="01100110") alg = BernsteinVazirani(oracle=ora, quantum_instance=tb) result = alg.run() assert result["result"] == "011" alg = DeutschJozsa(oracle=ora, quantum_instance=tb) result = alg.run() assert result["result"] == "balanced" ora = TruthTableOracle(bitmaps="11111111") alg = DeutschJozsa(oracle=ora, quantum_instance=tb) result = alg.run() assert result["result"] == "constant"
def test_noise() -> None: with open(os.path.join(sys.path[0], "ibmqx2_properties.pickle"), "rb") as f: properties = pickle.load(f) noise_model = NoiseModel.from_backend(properties) n_qbs = 5 c = Circuit(n_qbs, n_qbs) x_qbs = [2, 0, 4] for i in x_qbs: c.X(i) c.measure_all() b = AerBackend(noise_model) n_shots = 50 b.compile_circuit(c) shots = b.get_shots(c, n_shots, seed=4) zer_exp = [] one_exp = [] for i in range(n_qbs): expectation = np.sum(shots[:, i]) / n_shots if i in x_qbs: one_exp.append(expectation) else: zer_exp.append(expectation) assert min(one_exp) > max(zer_exp) c2 = (Circuit(4, 4).H(0).CX(0, 2).CX(3, 1).T(2).CX(0, 1).CX(0, 3).CX(2, 1).measure_all()) b.compile_circuit(c2) shots = b.get_shots(c2, 10, seed=5) assert shots.shape == (10, 4)
def test_shots_bits_edgecases(n_shots: int, n_bits: int) -> None: c = Circuit(n_bits, n_bits) aer_backend = AerBackend() # TODO TKET-813 add more shot based backends and move to integration tests h = aer_backend.process_circuit(c, n_shots) res = aer_backend.get_result(h) correct_shots = np.zeros((n_shots, n_bits), dtype=int) correct_shape = (n_shots, n_bits) correct_counts = Counter({(0, ) * n_bits: n_shots}) # BackendResult assert np.array_equal(res.get_shots(), correct_shots) assert res.get_shots().shape == correct_shape assert res.get_counts() == correct_counts # Direct assert np.array_equal(aer_backend.get_shots(c, n_shots), correct_shots) assert aer_backend.get_shots(c, n_shots).shape == correct_shape assert aer_backend.get_counts(c, n_shots) == correct_counts
def test_simulation_method() -> None: state_backends = [ AerBackend(), AerBackend(simulation_method="statevector") ] stabilizer_backend = AerBackend(simulation_method="stabilizer") clifford_circ = Circuit(2).H(0).CX(0, 1).measure_all() clifford_T_circ = Circuit(2).H(0).T(1).CX(0, 1).measure_all() for b in state_backends + [stabilizer_backend]: counts = b.get_counts(clifford_circ, 4) assert sum(val for _, val in counts.items()) == 4 for b in state_backends: counts = b.get_counts(clifford_T_circ, 4) assert sum(val for _, val in counts.items()) == 4 with pytest.raises(AttributeError) as warninfo: # check for the error thrown when non-clifford circuit used with # stabilizer backend stabilizer_backend.get_counts(clifford_T_circ, 4) assert "Attribute header is not defined" in str(warninfo.value)
return expectation_value( ansatz_at_params, all_measures, hamiltonian, backend ).real return objective_function # Number operator for exercise 5 number_operator = ( FermionOperator("0^ 0") + FermionOperator("1^ 1") + FermionOperator("2^ 2") + FermionOperator("3^ 3") ) # Hamiltonian for H2 (Jordan-Wigner, sto-3g) hamiltonian = QubitOperator( "-0.10973055606700793 [] + -0.04544288414432624 [X0 X1 Y2 Y3] + 0.04544288414432624 [X0 Y1 Y2 X3] + 0.04544288414432624 [Y0 X1 X2 Y3] + -0.04544288414432624 [Y0 Y1 X2 X3] + 0.16988452027940334 [Z0] + 0.16821198673715726 [Z0 Z1] + 0.1200514307254604 [Z0 Z2] + 0.16549431486978664 [Z0 Z3] + 0.1698845202794033 [Z1] + 0.16549431486978664 [Z1 Z2] + 0.1200514307254604 [Z1 Z3] + -0.21886306781219583 [Z2] + 0.17395378776494158 [Z2 Z3] + -0.21886306781219583 [Z3]" ) # Set up and run a VQE experiment ansatz, symbols = h2_JW_sto3g_ansatz() backend = AerBackend() obj = gen_objective_function(ansatz, symbols, hamiltonian, backend) initial_params = [1e-6, 1e-6, 1e-1] result = minimize(obj, initial_params, method="Nelder-Mead") print("Final parameter values", result.x) print("Final energy value", result.fun)
# There are several strategies for measurement reduction throughout the literature. Examples include https://arxiv.org/abs/1908.06942, https://arxiv.org/abs/1908.08067 and https://arxiv.org/abs/1907.07859. # In `pytket`, we provide tools to perform measurement reduction. The most accessible way is to use the utils method, `get_operator_expectation_value`. This method wraps up some under-the-hood processes to allow users to calculate expectation values, agnostic to the backend, operator, or circuit. In this tutorial we will use the Qiskit Aer simulators via the `AerBackend`, for shots, and the `AerStateBackend`, for statevector simulation. # # We use the `QubitPauliOperator` class to represent the operator $H$. from pytket.circuit import Circuit, Qubit from pytket.pauli import Pauli, QubitPauliString from pytket.utils import QubitPauliOperator from pytket.utils.expectations import get_operator_expectation_value from pytket.extensions.qiskit import AerBackend, AerStateBackend # First, let's get some results on a toy circuit without using any measurement reduction: shots_backend = AerBackend() n_shots = 10000 c = Circuit(5) c.H(4) c.V(2) shots_backend.compile_circuit(c) op = QubitPauliOperator({ QubitPauliString([Qubit(0)], [Pauli.Z]): 0.1, QubitPauliString( [Qubit(0), Qubit(1), Qubit(2), Qubit(3), Qubit(4)], [Pauli.Y, Pauli.Z, Pauli.X, Pauli.X, Pauli.Y], ):
def test_sim() -> None: c = circuit_gen(True) b = AerBackend() shots = b.get_shots(c, 1024) print(shots)
def test_counts() -> None: qc = get_test_circuit(True) circ = qiskit_to_tk(qc) sim = AerBackend() counts = sim.get_counts(circ, 10, seed=4) assert counts == {(1, 0, 1, 1, 0): 10}
def test_cache() -> None: b = AerBackend() c = circuit_gen() b.compile_circuit(c) h = b.process_circuits([c], 2)[0] b.get_result(h).get_shots() assert h in b._cache b.pop_result(h) assert h not in b._cache assert not b._cache b.get_counts(c, n_shots=2) b.get_counts(c.copy(), n_shots=2) b.empty_cache() assert not b._cache