def swap(tk_circ, i, j): old = Qubit('q', i) tmp = Qubit('tmp', 0) new = Qubit('q', j) tk_circ.rename_units({old: tmp}) tk_circ.rename_units({new: old}) tk_circ.rename_units({tmp: new})
def test_conditions() -> None: box_c = Circuit(2, 2) box_c.Z(0) box_c.Y(1, condition_bits=[0, 1], condition_value=1) box_c.Measure(0, 0, condition_bits=[0, 1], condition_value=0) box = CircBox(box_c) u = np.asarray([[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]) ubox = Unitary2qBox(u) c = Circuit(2, 2, name="c") b = c.add_c_register("b", 1) c.add_circbox( box, [Qubit(0), Qubit(1), Bit(0), Bit(1)], condition_bits=[b[0]], condition_value=1, ) c.add_unitary2qbox(ubox, Qubit(0), Qubit(1), condition_bits=[b[0]], condition_value=0) c2 = c.copy() qc = tk_to_qiskit(c) c1 = qiskit_to_tk(qc) assert len(c1.get_commands()) == 2 DecomposeBoxes().apply(c) DecomposeBoxes().apply(c1) assert c == c1 c2.Z(1, condition=reg_eq(b, 1)) qc = tk_to_qiskit(c2) c1 = qiskit_to_tk(qc) assert len(c1.get_commands()) == 3
def test_blank_wires() -> None: backends: List[_CirqBaseBackend] = [ CirqDensityMatrixSimBackend(), CirqStateSimBackend(), ] for b in backends: assert b.get_result(b.process_circuit(Circuit(2).X(0))).q_bits == {Qubit(0): 0} assert b.get_result(b.process_circuit(Circuit(2).X(1))).q_bits == {Qubit(1): 0} for r in b.get_result(b.process_circuit_moments(Circuit(2).X(0).X(0).X(0))): # type: ignore assert r.q_bits == {Qubit(0): 0} for r in b.get_result(b.process_circuit_moments(Circuit(2).X(1).X(1).X(1))): # type: ignore assert r.q_bits == {Qubit(1): 0} for b in [CirqDensityMatrixSampleBackend(), CirqStateSampleBackend()]: assert b.get_result( b.process_circuit(Circuit(2, 2).X(0).Measure(0, 0), 100) ).c_bits == {Bit(0): 0} assert b.get_result( b.process_circuit(Circuit(2, 2).X(1).Measure(1, 1), 100) ).c_bits == {Bit(1): 0} assert b.get_result( b.process_circuit(Circuit(2, 2).X(1).Measure(1, 0), 100) ).c_bits == {Bit(0): 0} assert b.get_result( b.process_circuit(Circuit(2, 2).X(1).Measure(0, 1), 100) ).c_bits == {Bit(1): 0}
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_operator() -> None: c = circuit_gen() b = ProjectQBackend() zz = QubitPauliOperator( {QubitPauliString([Qubit(0), Qubit(1)], [Pauli.Z, Pauli.Z]): 1.0}) assert np.isclose(get_operator_expectation_value(c, zz, b), complex(1.0)) c.X(0) assert np.isclose(get_operator_expectation_value(c, zz, b), complex(-1.0))
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 prepare_qubit(tk_circ, left, box, right): if len(right) > 0: renaming = dict() for i in range(len(left), tk_circ.n_qubits): old = Qubit('q', i) new = Qubit('q', i + len(box.cod)) renaming.update({old: new}) tk_circ.rename_units(renaming) tk_circ.add_blank_wires(len(box.cod))
def test_operator_statevector(qvm: None, quilc: None) -> None: c = Circuit(2, 2) c.Rz(0.5, 0) b = ForestStateBackend() zi = QubitPauliString(Qubit(0), Pauli.Z) iz = QubitPauliString(Qubit(1), Pauli.Z) op = QubitPauliOperator({zi: 0.3, iz: -0.1}) assert get_operator_expectation_value(c, op, b) == pytest.approx(0.2) c.X(0) assert get_operator_expectation_value(c, op, b) == pytest.approx(-0.4)
def prepare_qubits(qubits, box, offset): renaming = dict() start = tk_circ.n_qubits if not qubits else 0\ if not offset else qubits[offset - 1] + 1 for i in range(start, tk_circ.n_qubits): old = Qubit('q', i) new = Qubit('q', i + len(box.cod)) renaming.update({old: new}) tk_circ.rename_units(renaming) tk_circ.add_blank_wires(len(box.cod)) return qubits[:offset] + list(range(start, start + len(box.cod)))\ + [i + len(box.cod) for i in qubits[offset:]]
def test_operator_sim(qvm: None, quilc: None) -> None: c = Circuit(2, 2) c.Rz(0.5, 0) b = ForestBackend("9q-square") zi = QubitPauliString(Qubit(0), Pauli.Z) iz = QubitPauliString(Qubit(1), Pauli.Z) op = QubitPauliOperator({zi: 0.3, iz: -0.1}) assert get_operator_expectation_value(c, op, b, 10) == pytest.approx(0.2, rel=0.001) c.X(0) assert get_operator_expectation_value(c, op, b, 10) == pytest.approx(-0.4, rel=0.001)
def test_expectation() -> None: b = BraketBackend(local=True) assert b.supports_expectation c = Circuit(2, 2) c.Rz(0.5, 0) zi = QubitPauliString(Qubit(0), Pauli.Z) iz = QubitPauliString(Qubit(1), Pauli.Z) op = QubitPauliOperator({zi: 0.3, iz: -0.1}) assert get_pauli_expectation_value(c, zi, b) == 1 assert get_operator_expectation_value(c, op, b) == pytest.approx(0.2) c.X(0) assert get_pauli_expectation_value(c, zi, b) == -1 assert get_operator_expectation_value(c, op, b) == pytest.approx(-0.4)
def test_simulator() -> None: b = BraketBackend( s3_bucket=S3_BUCKET, s3_folder=S3_FOLDER, device_type="quantum-simulator", provider="amazon", device="sv1", ) assert b.supports_shots c = Circuit(2).H(0).CX(0, 1) b.compile_circuit(c) n_shots = 100 h0, h1 = b.process_circuits([c, c], n_shots) res0 = b.get_result(h0) readouts = res0.get_shots() assert all(readouts[i][0] == readouts[i][1] for i in range(n_shots)) res1 = b.get_result(h1) counts = res1.get_counts() assert len(counts) <= 2 assert sum(counts.values()) == n_shots zi = QubitPauliString(Qubit(0), Pauli.Z) assert b.get_pauli_expectation_value( c, zi, poll_timeout_seconds=60, poll_interval_seconds=1 ) == pytest.approx(0) # Circuit with unused qubits c = Circuit(3).H(1).CX(1, 2) b.compile_circuit(c) h = b.process_circuit(c, 1) res = b.get_result(h) readout = res.get_shots()[0] assert readout[1] == readout[2]
def __init__(self, access_token: str, device_name: str = AQT_DEVICE_SIM, label: str = ""): """ Construct a new AQT backend. :param access_token: AQT access token :type access_token: string :param device_name: device name (suffix of URL, e.g. "sim/noise-model-1") :type device_name: string :param label: label to apply to submitted jobs :type label: string """ super().__init__() self._url = AQT_URL_PREFIX + device_name self._label = label self._header = { "Ocp-Apim-Subscription-Key": access_token, "SDK": "pytket" } if device_name in device_info: self._max_n_qubits: Optional[int] = device_info[device_name][ "max_n_qubits"] self._device = FullyConnected(self._max_n_qubits) self._qm = { Qubit(i): node for i, node in enumerate(self._device.nodes) } else: self._max_n_qubits = None self._device = None self._qm = {} self._MACHINE_DEBUG = False
def __init__( self, api_key: str, device_name: Optional[str] = "qpu", label: Optional[str] = "job", ): """ Construct a new IonQ backend. :param api_key: IonQ API key :type api_key: string :param device_name: device name, either "qpu" or "simulator". Default is "qpu". :type device_name: Optional[string] :param label: label to apply to submitted jobs. Default is "job". :type label: Optional[string] """ super().__init__() self._url = IONQ_JOBS_URL self._device_name = device_name self._label = label self._header = {"Authorization": f"apiKey {api_key}"} self._max_n_qubits = IONQ_N_QUBITS self._device = Device(FullyConnected(self._max_n_qubits)) self._qm = {Qubit(i): node for i, node in enumerate(self._device.nodes)} self._MACHINE_DEBUG = False
def test_pauli_statevector(qvm: None, quilc: None) -> None: c = Circuit(2, 2) c.Rz(0.5, 0) b = ForestStateBackend() zi = QubitPauliString(Qubit(0), Pauli.Z) assert get_pauli_expectation_value(c, zi, b) == 1 c.X(0) assert get_pauli_expectation_value(c, zi, b) == -1
def test_device() -> None: c = circuit_gen(False) b = IBMQBackend("ibmq_santiago", hub="ibm-q", group="open", project="main") assert b._max_per_job == 75 operator = QubitPauliOperator({ QubitPauliString(Qubit(0), Pauli.Z): 1.0, QubitPauliString(Qubit(0), Pauli.X): 0.5, }) val = get_operator_expectation_value(c, operator, b, 8000) print(val) c1 = circuit_gen(True) c2 = circuit_gen(True) b.compile_circuit(c1) b.compile_circuit(c2) print(b.get_shots(c1, n_shots=10)) print(b.get_shots(c2, n_shots=10))
def test_ilo(qvm: None, quilc: None) -> None: b = ForestBackend("9q-square") bs = ForestStateBackend() c = Circuit(2) c.CZ(0, 1) c.Rx(1.0, 1) assert np.allclose(bs.get_state(c), np.asarray([0, -1j, 0, 0])) assert np.allclose(bs.get_state(c, basis=BasisOrder.dlo), np.asarray([0, 0, -1j, 0])) c.rename_units({Qubit(0): Node(0), Qubit(1): Node(1)}) 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_pauli() -> None: c = Circuit(2) c.Rz(0.5, 0) b = ProjectQBackend() zi = QubitPauliString({Qubit(0): Pauli.Z}) assert np.isclose(get_pauli_expectation_value(c, zi, b), complex(1)) c.X(0) assert np.isclose(get_pauli_expectation_value(c, zi, b), complex(-1))
def qps_from_openfermion(paulis: QubitOperator) -> QubitPauliString: """ Utility function to translate from openfermion format to a QubitPauliString """ qlist = [] plist = [] for q, p in paulis: qlist.append(Qubit(q)) plist.append(pauli_sym[p]) return QubitPauliString(qlist, plist)
def test_pauli_statevector() -> None: c = Circuit(2) c.Rz(0.5, 0) Transform.OptimisePostRouting().apply(c) b = AerStateBackend() zi = QubitPauliString(Qubit(0), Pauli.Z) assert get_pauli_expectation_value(c, zi, b) == 1 c.X(0) assert get_pauli_expectation_value(c, zi, b) == -1
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_pauli_sim(qvm: None, quilc: None) -> None: c = Circuit(2, 2) c.Rz(0.5, 0) b = ForestBackend("9q-square") zi = QubitPauliString(Qubit(0), Pauli.Z) energy = get_pauli_expectation_value(c, zi, b, 10) assert abs(energy - 1) < 0.001 c.X(0) energy = get_pauli_expectation_value(c, zi, b, 10) assert abs(energy + 1) < 0.001
def test_multireg() -> None: b = HoneywellBackend(device_name="HQS-LT-1.0-APIVAL", label="test 3") c = Circuit() q1 = Qubit("q1", 0) q2 = Qubit("q2", 0) c1 = Bit("c1", 0) c2 = Bit("c2", 0) for q in (q1, q2): c.add_qubit(q) for cb in (c1, c2): c.add_bit(cb) c.H(q1) c.CX(q1, q2) c.Measure(q1, c1) c.Measure(q2, c2) b.compile_circuit(c) n_shots = 10 shots = b.get_shots(c, n_shots) assert np.array_equal(shots, np.zeros((10, 2)))
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_cnx() -> None: qr = QuantumRegister(5) qc = QuantumCircuit(qr, name="cnx_circuit") qc.mcx([0, 1, 2, 3], 4) c = qiskit_to_tk(qc) cmds = c.get_commands() assert len(cmds) == 1 cmd = cmds[0] assert cmd.op.type == OpType.CnX assert len(cmd.qubits) == 5 qregname = qc.qregs[0].name assert cmd.qubits[4] == Qubit(qregname, 4)
def test_conditional_measurement() -> None: c = MyCircuit([Qubit(0), Qubit(1)], [Bit(0), Bit(1), Bit(2), Bit(3)]) # Get a random number c.add_gate(QubitPauliString(Qubit(0), Pauli.X), np.pi / 2) c.add_measure(Qubit(0), Bit(0)) # If random number is 0 then flip to give |1> # Otherwise, randomly generate |+i> or |-i> c.add_gate(QubitPauliString(Qubit(0), Pauli.X), np.pi / 2) c.add_measure(Qubit(0), Bit(1), {Bit(0): 1}) c.add_gate(QubitPauliString(Qubit(0), Pauli.X), np.pi / 2) # Deterministic if Bit(0) == 0, random if Bit(0) == 1 c.add_measure(Qubit(0), Bit(2)) # Test end-of-circuit conditions by copying Bit(2) to Bit(3) c.add_gate(QubitPauliString(Qubit(1), Pauli.X), np.pi) c.add_measure(Qubit(1), Bit(3), {Bit(2): 1}) counts = get_counts(c, n_shots=10000, seed=11) assert counts[(1, 1, 0, 0)] == pytest.approx(5000, rel=0.02) assert counts[(0, 0, 0, 1)] == pytest.approx(1250, rel=0.02) assert counts[(1, 1, 0, 1)] == pytest.approx(1250, rel=0.02) assert counts[(0, 0, 1, 1)] == pytest.approx(1250, rel=0.02) assert counts[(1, 1, 1, 1)] == pytest.approx(1250, rel=0.02)
def test_variance() -> None: b = BraketBackend(local=True) assert b.supports_variance # - Prepare a state (1/sqrt(2), 1/sqrt(2)). # - Measure w.r.t. the operator Z which has evcs (1,0) (evl=+1) and (0,1) (evl=-1). # - Get +1 with prob. 1/2 and -1 with prob. 1/2. c = Circuit(1).H(0) z = QubitPauliString(Qubit(0), Pauli.Z) assert b.get_pauli_expectation_value(c, z) == pytest.approx(0) assert b.get_pauli_variance(c, z) == pytest.approx(1) op = QubitPauliOperator({z: 3}) assert b.get_operator_expectation_value(c, op) == pytest.approx(0) assert b.get_operator_variance(c, op) == pytest.approx(9)
def test_moments_with_shots() -> None: b = BraketBackend(local=True) c = Circuit(1).H(0) z = QubitPauliString(Qubit(0), Pauli.Z) e = b.get_pauli_expectation_value(c, z, n_shots=10) assert abs(e) <= 1 v = b.get_pauli_variance(c, z, n_shots=10) assert v <= 1 op = QubitPauliOperator({z: 3}) e = b.get_operator_expectation_value(c, op, n_shots=10) assert abs(e) <= 3 v = b.get_operator_variance(c, op, n_shots=10) assert v <= 9
def test_overwrite() -> None: # Test that classical data is overwritten by later measurements appropriately c = MyCircuit([Qubit(0)], [Bit(0), Bit(1)]) c.add_measure(Qubit(0), Bit(0)) c.add_gate(QubitPauliString(Qubit(0), Pauli.X), np.pi) c.add_measure(Qubit(0), Bit(0)) c.add_measure(Qubit(0), Bit(1)) c.add_gate(QubitPauliString(Qubit(0), Pauli.X), np.pi / 2) c.add_measure(Qubit(0), Bit(1)) counts = get_counts(c, n_shots=100, seed=11) assert counts == {(0, 1): 50, (1, 1): 50}
def test_convert_result() -> None: # testing fix to register order bug TKET-752 qr1 = QuantumRegister(1, name="q1") qr2 = QuantumRegister(2, name="q2") cr = ClassicalRegister(5, name="z") cr2 = ClassicalRegister(2, name="b") qc = QuantumCircuit(qr1, qr2, cr, cr2) qc.x(qr1[0]) qc.x(qr2[1]) # check statevector simulator = Aer.get_backend("statevector_simulator") qisk_result = execute(qc, simulator, shots=10).result() tk_res = next(qiskit_result_to_backendresult(qisk_result)) state = tk_res.get_state([Qubit("q2", 1), Qubit("q1", 0), Qubit("q2", 0)]) correct_state = np.zeros(1 << 3, dtype=complex) correct_state[6] = 1 + 0j assert compare_statevectors(state, correct_state) # check measured qc.measure(qr1[0], cr[0]) qc.measure(qr2[1], cr2[0]) simulator = Aer.get_backend("qasm_simulator") qisk_result = execute(qc, simulator, shots=10).result() tk_res = next(qiskit_result_to_backendresult(qisk_result)) one_bits = [Bit("z", 0), Bit("b", 0)] zero_bits = [Bit("z", i) for i in range(1, 5)] + [Bit("b", 1)] assert tk_res.get_counts(one_bits) == Counter({(1, 1): 10}) assert tk_res.get_counts(zero_bits) == Counter({(0, 0, 0, 0, 0): 10}) assert (qisk_result.results[0].data.to_dict() == backendresult_to_qiskit_resultdata(tk_res, qisk_result.results[0].header, None).to_dict())