def test_local_simulator() -> None: b = BraketBackend(local=True) assert b.supports_shots assert b.supports_counts c = Circuit(2).H(0).CX(0, 1) b.compile_circuit(c) n_shots = 100 h = b.process_circuit(c, n_shots) res = b.get_result(h) readouts = res.get_shots() assert all(readouts[i][0] == readouts[i][1] for i in range(n_shots)) counts = res.get_counts() assert len(counts) <= 2 assert sum(counts.values()) == n_shots
def s0_circ(n_orbitals: int, n_electrons: int): """ Args: n_orbitals (int) = number of qubits/spin orbitals from MolecularData n_electrons (int) = number of electrons from MolecularData Returns: circ (pytket.circuit.Circuit object) = in Hartree-Fock ground state """ circ = Circuit(n_orbitals) for i in range(n_electrons): circ.X(i) #rotates from |0> to |1> return circ
def test_shots_counts_cirq_dm_sample_simulator() -> None: b = CirqDensityMatrixSampleBackend() assert b.supports_shots c = Circuit(2).H(0).CX(0, 1).measure_all() 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(readout[0] == readout[1] for readout in readouts) res1 = b.get_result(h1) counts = res1.get_counts() assert len(counts) <= 2 assert sum(counts.values()) == n_shots # Circuit with unused qubits c = Circuit(3, 2).H(1).CX(1, 2).measure_all() 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 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 toffoli_from_tk1(a: float, b: float, c: float) -> Circuit: """ Only accept operations equivalent to I or X. """ circ = Circuit(1) if is_approx_0_mod_2(b) and is_approx_0_mod_2(a + c): # identity pass elif is_approx_0_mod_2(b + 1) and is_approx_0_mod_2(a - c): # X circ.X() else: raise RuntimeError( "Cannot compile to Toffoli gate set: TK1({}, {}, {}) ∉ {{I, X}}". format(a, b, c)) return circ
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)
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_rigetti() -> None: b = BraketBackend( s3_bucket=S3_BUCKET, s3_folder=S3_FOLDER, device_type="qpu", provider="rigetti", device="Aspen-9", ) assert b.persistent_handles assert b.supports_shots assert not b.supports_state chars = b.characterisation assert chars is not None specs = chars["specs"] assert "1Q" in specs assert "2Q" in specs c = ( Circuit(3) .add_gate(OpType.CCX, [0, 1, 2]) .add_gate(OpType.U1, 0.5, [1]) .add_gate(OpType.ISWAP, 0.5, [0, 2]) .add_gate(OpType.XXPhase, 0.5, [1, 2]) ) assert not b.valid_circuit(c) b.compile_circuit(c) assert b.valid_circuit(c) h = b.process_circuit(c, 10) # min shots = 10 for Rigetti _ = b.circuit_status(h) b.cancel(h) # Circuit with unused qubits c = Circuit(11).H(9).CX(9, 10) b.compile_circuit(c) h = b.process_circuit(c, 10) b.cancel(h)
def t1_circ(n_orbitals: int, n_electrons: int): """ Args: n_orbitals (int) = number of qubits/spin orbitals from MolecularData n_electrons (int) = number of electrons from MolecularData Returns: circ (pytket.circuit.Circuit object) = in T1 configuration from H**O->LUMO """ circ = Circuit(n_orbitals) for i in range(n_electrons-1): # for all but one electrons circ.X(i) # rotates from |0> to |1> circ.X(n_electrons) # rotate from |0> to |1> for the triplet spin orbital return circ
def test_default_pass() -> None: b = QsharpToffoliSimulatorBackend() for ol in range(3): comp_pass = b.default_compilation_pass(ol) c = Circuit(4, 4) c.CX(0, 1) c.CCX(0, 1, 2) c.add_gate(OpType.CnX, [0, 1, 2, 3]) c.add_gate(OpType.noop, [2]) c.X(3) c.SWAP(1, 2) c.measure_all() comp_pass.apply(c) for pred in b.required_predicates: assert pred.verify(c)
def test_rebase_large() -> None: circ = Circuit(3) # some arbitrary unitary circ.Rx(0.21, 0).Rz(0.12, 1).Rz(8.2, 2).X(2).CX(0, 1).CX(1, 2).Rz(0.44, 1).Rx( 0.43, 0 ) orig_circ = circ.copy() _aqt_rebase().apply(circ) # TODO use tketsim for this test once available u1 = AerUnitaryBackend().get_unitary(orig_circ) u2 = AerUnitaryBackend().get_unitary(circ) assert np.allclose(u1, u2)
def test_convert() -> None: circ = Circuit(4, 4) circ.H(0).CX(0, 1) circ.add_gate(OpType.noop, [1]) circ.CRz(0.5, 1, 2) circ.add_barrier([2]) circ.ZZPhase(0.3, 2, 3).CX(3, 0).Tdg(1) circ.Measure(0, 0) circ.Measure(1, 2) circ.Measure(2, 3) circ.Measure(3, 1) circ_aqt = tk_to_aqt(circ) assert json.loads(circ_aqt[1]) == [0, 3, 1, 2] assert all(gate[0] in ["X", "Y", "MS"] for gate in circ_aqt[0])
def _tk1_to_x_v_rz(a: float, b: float, c: float) -> Circuit: circ = Circuit(1) if _approx_0_mod_2(b): circ.Rz(a + c, 0) elif _approx_0_mod_2(b + 1): if _approx_0_mod_2(a - 0.5) and _approx_0_mod_2(c - 0.5): circ.X(0) else: circ.Rz(c, 0).X(0).Rz(a, 0) else: if _approx_0_mod_2(a - 0.5) and _approx_0_mod_2(c - 0.5): circ.V(0).Rz(1 - b, 0).V(0) else: circ.Rz(c + 0.5, 0).V(0).Rz(b - 1, 0).V(0).Rz(a + 0.5, 0) return circ
def test_cancel() -> None: b = HoneywellBackend(device_name="HQS-LT-1.0-APIVAL", label="test cancel") c = Circuit(2, 2).H(0).CX(0, 1).measure_all() b.compile_circuit(c) handle = b.process_circuit(c, 10) try: # will raise HTTP error if job is already completed b.cancel(handle) except HQSAPIError as err: check_completed = "job has completed already" in str(err) assert check_completed if not check_completed: raise err print(b.circuit_status(handle))
def test_bell() -> None: """ Simulate a circuit that generates a Bell state, and check that the results are all (0,0) or (1,1). """ b = QsharpSimulatorBackend() c = Circuit(2) c.H(0) c.CX(0, 1) c.measure_all() b.compile_circuit(c) n_shots = 10 counts = b.get_counts(c, n_shots) assert all(m[0] == m[1] for m in counts.keys()) assert sum(counts.values()) == n_shots
def pyquil_to_tk(prog: Program) -> Circuit: """ Convert a :py:class:`pyquil.Program` to a tket :py:class:`Circuit` . Note that not all pyQuil operations are currently supported by pytket. :param prog: A circuit to be converted :return: The converted circuit """ tkc = Circuit() qmap = {} for q in prog.get_qubits(): uid = Qubit("q", q) tkc.add_qubit(uid) qmap.update({q: uid}) cregmap: Dict = {} for i in prog.instructions: if isinstance(i, Gate): try: optype = _known_quil_gate[i.name] except KeyError as error: raise NotImplementedError("Operation not supported by tket: " + str(i)) from error qubits = [qmap[q.index] for q in i.qubits] params = [param_from_pyquil(p) for p in i.params] # type: ignore tkc.add_gate(optype, params, qubits) elif isinstance(i, Measurement): qubit = qmap[i.qubit.index] reg = cregmap[i.classical_reg.name] # type: ignore bit = reg[i.classical_reg.offset] # type: ignore tkc.Measure(qubit, bit) elif isinstance(i, Declare): if i.memory_type == "BIT": new_reg = tkc.add_c_register(i.name, i.memory_size) cregmap.update({i.name: new_reg}) elif i.memory_type == "REAL": continue else: raise NotImplementedError("Cannot handle memory of type " + i.memory_type) elif isinstance(i, Pragma): continue elif isinstance(i, Halt): return tkc else: raise NotImplementedError("PyQuil instruction is not a gate: " + str(i)) return tkc
def test_compile() -> None: """ Compile a circuit containing SWAPs and noops down to CnX's """ b = QsharpToffoliSimulatorBackend() c = Circuit(4) c.CX(0, 1) c.CCX(0, 1, 2) c.add_gate(OpType.CnX, [0, 1, 2, 3]) c.add_gate(OpType.noop, [2]) c.X(3) c.SWAP(1, 2) c.measure_all() b.compile_circuit(c) shots = b.get_shots(c, 2) assert all(shots[0] == shots[1])
def test_probabilities_with_shots() -> None: b = BraketBackend(local=True) c = Circuit(2).V(1).CX(1, 0).S(1) probs_all = b.get_probabilities(c, n_shots=10) assert len(probs_all) == 4 assert sum(probs_all) == pytest.approx(1) assert probs_all[1] == 0 assert probs_all[2] == 0 probs1 = b.get_probabilities(c, n_shots=10, qubits=[1]) assert len(probs1) == 2 assert sum(probs1) == pytest.approx(1) h = b.process_circuit(c, n_shots=10) res = b.get_result(h) dist = res.get_distribution() assert (1, 0) not in dist assert (0, 1) not in dist
def measurement_circuits(hamiltonian, n_qubits): all_circs = [] for pauli, _ in hamiltonian.terms.items(): if not pauli: continue # Ignore the constant term measure_circ = Circuit(n_qubits, n_qubits) for qb, p in pauli: if p == "I": continue # Discard I qubits elif p == "X": measure_circ.H(qb) elif p == "Y": measure_circ.Rx(0.5, qb) measure_circ.Measure(qb, qb) all_circs.append(measure_circ) return all_circs
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_ibmq_mid_measure() -> None: c = Circuit(3, 3).H(1).CX(1, 2).Measure(0, 0).Measure(1, 1) c.add_barrier([0, 1, 2]) c.CX(1, 0).H(0).Measure(2, 2) # test open backend does not support mid-measure # cannot test premium backends that do b = IBMQEmulatorBackend("ibmq_athens") with pytest.raises(RuntimeError) as warninfo: b.compile_circuit(c) assert "Not a valid operation" in str(warninfo.value) with pytest.raises(CircuitNotValidError) as warninfo2: b.get_counts(c, 10) assert "NoMidMeasurePredicate" in str(warninfo2.value)
def test_nondefault_registers() -> None: c = Circuit() qreg = c.add_q_register("g", 3) creg1 = c.add_c_register("a", 3) creg2 = c.add_c_register("b", 3) c.X(qreg[1]) c.X(qreg[0]) c.Measure(qreg[1], creg1[1]) c.Measure(qreg[0], creg2[0]) b = QsharpSimulatorBackend() b.compile_circuit(c) counts = b.get_result(b.process_circuit(c, 10)).get_counts() assert counts == {(0, 1, 0, 1, 0, 0): 10}
def test_bellpair() -> None: circ = Circuit(2) circ.H(0) circ.CX(0, 1) eng = MainEngine() qureg = eng.allocate_qureg(circ.n_qubits) tk_to_projectq(eng, qureg, circ) eng.flush() p1 = eng.backend.get_probability([0, 0], qureg) p2 = eng.backend.get_probability([0, 1], qureg) p3 = eng.backend.get_probability([1, 0], qureg) p4 = eng.backend.get_probability([1, 1], qureg) assert p2 == 0 assert p3 == 0 assert isclose(p1, 0.5, abs_tol=eps) assert isclose(p4, 0.5, abs_tol=eps) All(Measure) | qureg # pylint: disable=expression-not-assigned
def receive(self, command_list: list) -> None: """ Receives a list of commands and appends to local Circuit. If a flush gate is received, optimises the Circuit using a default Transform pass and then sends the commands from this optimised Circuit into the next engine. """ for cmd in command_list: if cmd.gate == pqo.FlushGate( ): # flush gate --> optimize and then flush cmd_list = self._optimise() cmd_list.append(cmd) self._circuit = Circuit() self._qubit_dictionary = dict() self.send(cmd_list) continue _handle_gate(cmd, self)
def test_handles() -> None: token = cast(str, os.getenv("AQT_AUTH")) b = AQTBackend(token, device_name="sim/noise-model-1", label="test 5") c = Circuit(2, 2) c.H(0) c.CX(0, 1) c.measure_all() b.compile_circuit(c) n_shots = 5 shots = b.get_shots(c, n_shots=n_shots, timeout=30) assert len(shots) == n_shots counts = b.get_counts(c, n_shots=n_shots) assert sum(counts.values()) == n_shots handles = b.process_circuits([c, c], n_shots=n_shots) assert len(handles) == 2 for handle in handles: assert b.circuit_status(handle).status is StatusEnum.COMPLETED
def test_swaps_basisorder() -> None: # Check that implicit swaps can be corrected irrespective of BasisOrder b = ProjectQBackend() c = Circuit(4) c.X(0) c.CX(0, 1) c.CX(1, 0) CliffordSimp(True).apply(c) assert c.n_gates_of_type(OpType.CX) == 1 b.compile_circuit(c) s_ilo = b.get_state(c, basis=BasisOrder.ilo) s_dlo = b.get_state(c, basis=BasisOrder.dlo) correct_ilo = np.zeros((16, )) correct_ilo[4] = 1.0 assert np.allclose(s_ilo, correct_ilo) correct_dlo = np.zeros((16, )) correct_dlo[2] = 1.0 assert np.allclose(s_dlo, correct_dlo)
def qs_compilation_pass() -> BasePass: return RebaseCustom( {OpType.CX, OpType.CCX, OpType.PauliExpBox, OpType.SWAP, OpType.CnX }, # multiqs Circuit(), # cx_replacement (irrelevant) { OpType.H, OpType.Rx, OpType.Ry, OpType.Rz, OpType.S, OpType.T, OpType.X, OpType.Y, OpType.Z, }, # singleqs _from_tk1, ) # tk1_replacement
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_symbolic(qvm) -> None: pi2 = Symbol("pi2") pi3 = Symbol("pi3") tkc = Circuit(2).Rx(pi2, 1).Rx(-pi3, 1).CX(1, 0) RemoveRedundancies().apply(tkc) prog = tk_to_pyquil(tkc) tkc2 = pyquil_to_tk(prog) assert tkc2.free_symbols() == {pi2, pi3} tkc2.symbol_substitution({pi2: pi / 2, pi3: -pi / 3}) backend = ForestStateBackend() state1 = backend.get_state(tkc2) state0 = np.array( [-0.56468689 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.82530523j]) assert np.allclose(state0, state1)
def _tk1_to_x_sx_rz(a: float, b: float, c: float) -> Circuit: circ = Circuit(1) if _approx_0_mod_2(b): circ.Rz(a + c, 0) elif _approx_0_mod_2(b + 1): if _approx_0_mod_2(a - 0.5) and _approx_0_mod_2(c - 0.5): circ.X(0) else: circ.Rz(c, 0).X(0).Rz(a, 0) else: # use SX; SX = e^{i\pi/4}V; V = RX(1/2) if _approx_0_mod_2(a - 0.5) and _approx_0_mod_2(c - 0.5): circ.SX(0).Rz(1 - b, 0).SX(0) circ.add_phase(-0.5) else: circ.Rz(c + 0.5, 0).SX(0).Rz(b - 1, 0).SX(0).Rz(a + 0.5, 0) circ.add_phase(-0.5) return circ