repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Testing InverseCancellation """ import unittest import numpy as np from qiskit import QuantumCircuit from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import InverseCancellation from qiskit.transpiler import PassManager from qiskit.test import QiskitTestCase from qiskit.circuit.library import RXGate, HGate, CXGate, PhaseGate, XGate, TGate, TdgGate class TestInverseCancellation(QiskitTestCase): """Test the InverseCancellation transpiler pass.""" def test_basic_self_inverse(self): """Test that a single self-inverse gate as input can be cancelled.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) pass_ = InverseCancellation([HGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("h", gates_after) def test_odd_number_self_inverse(self): """Test that an odd number of self-inverse gates leaves one gate remaining.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) qc.h(0) pass_ = InverseCancellation([HGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("h", gates_after) self.assertEqual(gates_after["h"], 1) def test_basic_cx_self_inverse(self): """Test that a single self-inverse cx gate as input can be cancelled.""" qc = QuantumCircuit(2, 2) qc.cx(0, 1) qc.cx(0, 1) pass_ = InverseCancellation([CXGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("cx", gates_after) def test_basic_gate_inverse(self): """Test that a basic pair of gate inverse can be cancelled.""" qc = QuantumCircuit(2, 2) qc.rx(np.pi / 4, 0) qc.rx(-np.pi / 4, 0) pass_ = InverseCancellation([(RXGate(np.pi / 4), RXGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("rx", gates_after) def test_non_inverse_do_not_cancel(self): """Test that non-inverse gate pairs do not cancel.""" qc = QuantumCircuit(2, 2) qc.rx(np.pi / 4, 0) qc.rx(np.pi / 4, 0) pass_ = InverseCancellation([(RXGate(np.pi / 4), RXGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("rx", gates_after) self.assertEqual(gates_after["rx"], 2) def test_non_consecutive_gates(self): """Test that only consecutive gates cancel.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) qc.h(0) qc.cx(0, 1) qc.cx(0, 1) qc.h(0) pass_ = InverseCancellation([HGate(), CXGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("cx", gates_after) self.assertEqual(gates_after["h"], 2) def test_gate_inverse_phase_gate(self): """Test that an inverse pair of a PhaseGate can be cancelled.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("p", gates_after) def test_self_inverse_on_different_qubits(self): """Test that self_inverse gates cancel on the correct qubits.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(1) qc.h(0) qc.h(1) pass_ = InverseCancellation([HGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("h", gates_after) def test_non_inverse_raise_error(self): """Test that non-inverse gate inputs raise an error.""" qc = QuantumCircuit(2, 2) qc.rx(np.pi / 2, 0) qc.rx(np.pi / 4, 0) with self.assertRaises(TranspilerError): InverseCancellation([RXGate(0.5)]) def test_non_gate_inverse_raise_error(self): """Test that non-inverse gate inputs raise an error.""" qc = QuantumCircuit(2, 2) qc.rx(np.pi / 4, 0) qc.rx(np.pi / 4, 0) with self.assertRaises(TranspilerError): InverseCancellation([(RXGate(np.pi / 4))]) def test_string_gate_error(self): """Test that when gate is passed as a string an error is raised.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) with self.assertRaises(TranspilerError): InverseCancellation(["h"]) def test_consecutive_self_inverse_h_x_gate(self): """Test that only consecutive self-inverse gates cancel.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) qc.h(0) qc.x(0) qc.x(0) qc.h(0) pass_ = InverseCancellation([HGate(), XGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("x", gates_after) self.assertEqual(gates_after["h"], 2) def test_inverse_with_different_names(self): """Test that inverse gates that have different names.""" qc = QuantumCircuit(2, 2) qc.t(0) qc.tdg(0) pass_ = InverseCancellation([(TGate(), TdgGate())]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("t", gates_after) self.assertNotIn("tdg", gates_after) def test_three_alternating_inverse_gates(self): """Test that inverse cancellation works correctly for alternating sequences of inverse gates of odd-length.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("p", gates_after) self.assertEqual(gates_after["p"], 1) def test_four_alternating_inverse_gates(self): """Test that inverse cancellation works correctly for alternating sequences of inverse gates of even-length.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("p", gates_after) def test_five_alternating_inverse_gates(self): """Test that inverse cancellation works correctly for alternating sequences of inverse gates of odd-length.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("p", gates_after) self.assertEqual(gates_after["p"], 1) def test_sequence_of_inverse_gates_1(self): """Test that inverse cancellation works correctly for more general sequences of inverse gates. In this test two pairs of inverse gates are supposed to cancel out.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("p", gates_after) self.assertEqual(gates_after["p"], 1) def test_sequence_of_inverse_gates_2(self): """Test that inverse cancellation works correctly for more general sequences of inverse gates. In this test, in theory three pairs of inverse gates can cancel out, but in practice only two pairs are back-to-back.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("p", gates_after) self.assertEqual(gates_after["p"] % 2, 1) def test_cx_do_not_wrongly_cancel(self): """Test that CX(0,1) and CX(1, 0) do not cancel out, when (CX, CX) is passed as an inverse pair.""" qc = QuantumCircuit(2, 0) qc.cx(0, 1) qc.cx(1, 0) pass_ = InverseCancellation([(CXGate(), CXGate())]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("cx", gates_after) self.assertEqual(gates_after["cx"], 2) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXDebugging())
https://github.com/abbarreto/qiskit4
abbarreto
#In case you don't have qiskit, install it now %pip install qiskit --quiet #Installing/upgrading pylatexenc seems to have fixed my mpl issue #If you try this and it doesn't work, try also restarting the runtime/kernel %pip install pylatexenc --quiet !pip install -Uqq ipdb !pip install qiskit_optimization import networkx as nx import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer from qiskit.compiler import transpile from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import process_fidelity from qiskit.extensions.hamiltonian_gate import HamiltonianGate from qiskit.extensions import RXGate, XGate, CXGate from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute import numpy as np from qiskit.visualization import plot_histogram import ipdb from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * #quadratic optimization from qiskit_optimization import QuadraticProgram from qiskit_optimization.converters import QuadraticProgramToQubo %pdb on # def ApplyCost(qc, gamma): # Ix = np.array([[1,0],[0,1]]) # Zx= np.array([[1,0],[0,-1]]) # Xx = np.array([[0,1],[1,0]]) # Temp = (Ix-Zx)/2 # T = Operator(Temp) # I = Operator(Ix) # Z = Operator(Zx) # X = Operator(Xx) # FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T) # ham = HamiltonianGate(FinalOp,gamma) # qc.append(ham,[0,1,2]) task = QuadraticProgram(name = 'QUBO on QC') task.binary_var(name = 'x') task.binary_var(name = 'y') task.binary_var(name = 'z') task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1}) qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO operator, offset = qubo.to_ising() print(operator) # ham = HamiltonianGate(operator,0) # print(ham) Ix = np.array([[1,0],[0,1]]) Zx= np.array([[1,0],[0,-1]]) Xx = np.array([[0,1],[1,0]]) Temp = (Ix-Zx)/2 T = Operator(Temp) I = Operator(Ix) Z = Operator(Zx) X = Operator(Xx) FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T) ham = HamiltonianGate(FinalOp,0) print(ham) #define PYBIND11_DETAILED_ERROR_MESSAGES def compute_expectation(counts): """ Computes expectation value based on measurement results Args: counts: dict key as bitstring, val as count G: networkx graph Returns: avg: float expectation value """ avg = 0 sum_count = 0 for bitstring, count in counts.items(): x = int(bitstring[2]) y = int(bitstring[1]) z = int(bitstring[0]) obj = -2*x*z-y*z-x+2*y-3*z avg += obj * count sum_count += count return avg/sum_count # We will also bring the different circuit components that # build the qaoa circuit under a single function def create_qaoa_circ(theta): """ Creates a parametrized qaoa circuit Args: G: networkx graph theta: list unitary parameters Returns: qc: qiskit circuit """ nqubits = 3 n,m=3,3 p = len(theta)//2 # number of alternating unitaries qc = QuantumCircuit(nqubits,nqubits) Ix = np.array([[1,0],[0,1]]) Zx= np.array([[1,0],[0,-1]]) Xx = np.array([[0,1],[1,0]]) Temp = (Ix-Zx)/2 T = Operator(Temp) I = Operator(Ix) Z = Operator(Zx) X = Operator(Xx) FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z) beta = theta[:p] gamma = theta[p:] # initial_state for i in range(0, nqubits): qc.h(i) for irep in range(0, p): #ipdb.set_trace(context=6) # problem unitary # for pair in list(G.edges()): # qc.rzz(2 * gamma[irep], pair[0], pair[1]) #ApplyCost(qc,2*0) ham = HamiltonianGate(operator,2 * gamma[irep]) qc.append(ham,[0,1,2]) # mixer unitary for i in range(0, nqubits): qc.rx(2 * beta[irep], i) qc.measure(qc.qubits[:n],qc.clbits[:m]) return qc # Finally we write a function that executes the circuit on the chosen backend def get_expectation(shots=512): """ Runs parametrized circuit Args: G: networkx graph p: int, Number of repetitions of unitaries """ backend = Aer.get_backend('qasm_simulator') backend.shots = shots def execute_circ(theta): qc = create_qaoa_circ(theta) # ipdb.set_trace(context=6) counts = {} job = execute(qc, backend, shots=1024) result = job.result() counts=result.get_counts(qc) return compute_expectation(counts) return execute_circ from scipy.optimize import minimize expectation = get_expectation() res = minimize(expectation, [1, 1], method='COBYLA') expectation = get_expectation() res = minimize(expectation, res.x, method='COBYLA') res from qiskit.visualization import plot_histogram backend = Aer.get_backend('aer_simulator') backend.shots = 512 qc_res = create_qaoa_circ(res.x) backend = Aer.get_backend('qasm_simulator') job = execute(qc_res, backend, shots=1024) result = job.result() counts=result.get_counts(qc_res) plot_histogram(counts)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
!pip install qiskit # or #%pip install qiskit !pip install qiskit[visualization] !pip install qiskit[machine-learning] !pip install qiskit[nature] %pip install matplotlib import qiskit qiskit.version.get_version_info() !pip install pylatexenc
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle/360 return [cos(angle_radian),sin(angle_radian)] # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() for i in range(6): [x,y]=random_quantum_state2() draw_quantum_state(x,y,"|v"+str(i)+">") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() for i in range(100): [x,y]=random_quantum_state2() draw_quantum_state(x,y,"")
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from sympy import * init_printing(use_unicode=True) r1,r2,r3,s1,s2,s3 = symbols('r_1 r_2 r_3 s_1 s_2 s_3') I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]) rho = (1/2)*(I+r1*X+r2*Y+r3*Z); sigma = (1/2)*(I+s1*X+s2*Y+s3*Z) #rho, sigma def frho(r1,r2,r3): return (1/2)*(I+r1*X+r2*Y+r3*Z) def fsigma(s1,s2,s3): return (1/2)*(I+s1*X+s2*Y+s3*Z) A = frho(r1,0,r2)*fsigma(0,s2,0) simplify(A.eigenvals()) A = frho(0,0,r3); B = fsigma(s1,s2,0) simplify(A*(B**2)*A - B*(A**2)*B) M = A*B; simplify(M) simplify(M.eigenvals()) # parecem ser positivos o que esta na raiz e o autovalores
https://github.com/IvanIsCoding/Quantum
IvanIsCoding
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(1) # print the statevector print(f"Initial Statevector: {Statevector.from_instruction(circuit).data}\n\n") # Add an X gate followed by a H gate to put the qubit in |-> state circuit.x(0) circuit.h(0) print("After putting the qubit in |-> state\n\n") # print the statevector print("Final Statevector: ", Statevector.from_instruction(circuit).data) import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import Statevector # Create a Quantum Register with 3 qubits q = QuantumRegister(3) # Create a Quantum Circuit acting on the q register to demonstrate the GHZ state circuit = QuantumCircuit(q) # Add a H gate on qubit 0, putting this qubit in superposition. circuit.h(q[0]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(q[0], q[1]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2 circuit.cx(q[0], q[2]) from qiskit.quantum_info import Statevector # Set the intial state of the simulator to the ground state using from_int state = Statevector.from_int(0, 2**3) # Evolve the state by the quantum circuit state = state.evolve(circuit) #draw using latex state.draw('latex') from qiskit.visualization import array_to_latex #Alternative way of representing in latex array_to_latex(state) state.draw('qsphere')
https://github.com/riddheshMarkandeya/shors-algorithm-quantum
riddheshMarkandeya
import math import numpy as np from qiskit import QuantumCircuit, Aer, transpile, execute from qiskit.visualization import plot_histogram, circuit_drawer from qiskit.quantum_info.operators import Operator from qiskit.circuit.library import CU1Gate, QFT from math import gcd from fractions import Fraction #helper functions def make_permutation_matrix(n, permutation): r = np.zeros((n,n), dtype=int) for i in range(n): r[permutation(i), i] = 1 return r def mult_mat(x,k,N): n = math.ceil(math.log(N, 2)) return make_permutation_matrix( 2**n, permutation=lambda y: y*pow(x,k) % N if y<N else y) def c_mult_mat(x,k,N): n = math.ceil(math.log(N, 2)) permutation = lambda y: y if y%2==0 or (y-1)/2 >= N else 2*(int((y-1)/2)*pow(x,k) % N) + 1 return make_permutation_matrix(2*(2**n), permutation ) def mult_op(x,k,N): return Operator(mult_mat(x,k,N)) #controlled-U oracle def c_mult_op(x,k,N): return Operator(c_mult_mat(x,k,N)) # QFT and IQFT def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): circ.h(q[j]) for k in range(j+1,n): circ.cu1(math.pi/float(2**(k-j)), q[k], q[j]) for i in range(n//2): circ.swap(q[i], q[n-i-1]) def iqft(circ,q,n): for j in range(n): circ.h(q[j]) for k in range(j+1,n): #circ.cu1(-math.pi/float(2**(k-j)), q[k], q[j]) gate = CU1Gate(-np.pi/float(2**(k-j)) ) circ.append(gate, [q[k],q[j]]) for i in range(n//2): circ.swap(q[i], q[n-i-1]) # Constants N = 119 # N = 133 x = 9 n_count = 2 * math.ceil(math.log2(N)) # number of counting qubits o_qbits = math.ceil(math.log2(N)) # oracle qubits # Quantum Phase Estimation Circuit qc = QuantumCircuit(n_count + o_qbits, n_count) qc.x(n_count) # converting to |1> eigenstate for q in range(n_count): qc.h(q) for q in range(n_count): qc.unitary(c_mult_op(x,2**q,N), [q] + [i + n_count for i in range(o_qbits)]) # Adding Unitary operation qft_circuit = QFT(n_count) iqft_circuit = qft_circuit.inverse() # Used inbuilt IQFT, provided IQFT wasn't working correctly for some reason qc.append(iqft_circuit, range(n_count)) qc.measure(range(n_count), range(n_count)) # Visualize the Circuit circuit_drawer(qc, output='mpl', scale=0.7, fold=-1) # Simulate the Circuit simulator = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, simulator) result = simulator.run(transpiled_qc, shots=2*1024).result() counts = result.get_counts(qc) # Plot histogram plot_histogram(counts) # Determine the order r def determine_order(counts): measured_str = max(counts, key=counts.get) measured = int(measured_str, 2) # converting binary to decimal phase = measured / (2**n_count) frac = Fraction(phase).limit_denominator(N) # compute s/r for phase return frac.denominator r = determine_order(counts) print(f"Order r: {r}") # Classical post-processing to factorize N factor_found = False if r % 2 == 0: plus = gcd(pow(x, r//2) + 1, N) minus = gcd(pow(x, r//2) - 1, N) if plus not in [1, N]: print(f"One factor of {N} is {plus}") factor_found = True if minus not in [1, N]: print(f"One factor of {N} is {minus}") factor_found = True if not factor_found: print("No factors found. Try a different random x or run from circuit cell again.")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Gate cancellation pass testing""" import unittest import numpy as np from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import U1Gate, RZGate, PhaseGate, CXGate, SXGate from qiskit.circuit.parameter import Parameter from qiskit.transpiler.target import Target from qiskit.transpiler import PassManager, PropertySet from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation, FixedPoint, Size from qiskit.quantum_info import Operator class TestCommutativeCancellation(QiskitTestCase): """Test the CommutativeCancellation pass.""" def setUp(self): super().setUp() self.com_pass_ = CommutationAnalysis() self.pass_ = CommutativeCancellation() self.pset = self.pass_.property_set = PropertySet() def test_all_gates(self): """Test all gates on 1 and 2 qubits q0:-[H]-[H]--[x]-[x]--[y]-[y]--[rz]-[rz]--[u1]-[u1]-[rx]-[rx]---.--.--.--.--.--.- | | | | | | q1:-------------------------------------------------------------X--X--Y--Y--.--.- = qr0:---[u1]--- qr1:---------- """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.x(qr[0]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.y(qr[0]) circuit.rz(0.5, qr[0]) circuit.rz(0.5, qr[0]) circuit.append(U1Gate(0.5), [qr[0]]) # TODO this should work with Phase gates too circuit.append(U1Gate(0.5), [qr[0]]) circuit.rx(0.5, qr[0]) circuit.rx(0.5, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(2.0), [qr[0]]) expected.rx(1.0, qr[0]) self.assertEqual(expected, new_circuit) def test_commutative_circuit1(self): """A simple circuit where three CNOTs commute, the first and the last cancel. qr0:----.---------------.-- qr0:------------ | | qr1:---(+)-----(+)-----(+)- = qr1:-------(+)-- | | qr2:---[H]------.---------- qr2:---[H]--.--- """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[0], qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.h(qr[2]) expected.cx(qr[2], qr[1]) self.assertEqual(expected, new_circuit) def test_consecutive_cnots(self): """A simple circuit equals identity qr0:----.- ----.-- qr0:------------ | | qr1:---(+)----(+)- = qr1:------------ """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_consecutive_cnots2(self): """ Two CNOTs that equals identity, with rotation gates inserted. """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.rx(np.pi, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.rx(np.pi, qr[0]) passmanager = PassManager() passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_2_alternating_cnots(self): """A simple circuit where nothing should be cancelled. qr0:----.- ---(+)- qr0:----.----(+)- | | | | qr1:---(+)-----.-- = qr1:---(+)----.-- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.cx(qr[1], qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot(self): """A simple circuit where nothing should be cancelled. qr0:----.------[X]------.-- qr0:----.------[X]------.-- | | | | qr1:---(+)-------------(+)- = qr1:---(+)-------------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.x(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.x(qr[0]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot1(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[Z]------.-- qr0:---[Z]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.z(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.z(qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot2(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[T]------.-- qr0:---[T]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.t(qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot3(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[Rz]------.-- qr0:---[Rz]--- | | qr1:---(+)-------- -----(+)- = qr1:---------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.rz(np.pi / 3, qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot4(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[T]------.-- qr0:---[T]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.t(qr[0]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[Z]-----(+)- = qr1:---(+)----[Z]------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.z(qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.z(qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot1(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[T]-----(+)- = qr1:---(+)----[T]------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.t(qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot2(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[Rz]----(+)- = qr1:---(+)----[Rz]-----(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.rz(np.pi / 3, qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_commutative_circuit2(self): """ A simple circuit where three CNOTs commute, the first and the last cancel, also two X gates cancel and two Rz gates combine. qr0:----.---------------.-------- qr0:------------- | | qr1:---(+)---(+)--[X]--(+)--[X]-- = qr1:--------(+)-- | | qr2:---[Rz]---.---[Rz]-[T]--[S]-- qr2:--[U1]---.--- """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.cx(qr[2], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.t(qr[2]) circuit.s(qr[2]) circuit.x(qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(np.pi * 17 / 12), [qr[2]]) expected.cx(qr[2], qr[1]) expected.global_phase = (np.pi * 17 / 12 - (2 * np.pi / 3)) / 2 self.assertEqual(expected, new_circuit) def test_commutative_circuit3(self): """ A simple circuit where three CNOTs commute, the first and the last cancel, also two X gates cancel and two Rz gates combine. qr0:-------.------------------.------------- qr0:------------- | | qr1:------(+)------(+)--[X]--(+)-------[X]-- = qr1:--------(+)-- | | qr2:------[Rz]--.---.----.---[Rz]-[T]--[S]-- qr2:--[U1]---.--- | | qr3:-[Rz]--[X]-(+)------(+)--[X]-[Rz]------- qr3:--[Rz]------- """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.rz(np.pi / 3, qr[3]) circuit.x(qr[3]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[2], qr[3]) circuit.rz(np.pi / 3, qr[2]) circuit.t(qr[2]) circuit.x(qr[3]) circuit.rz(np.pi / 3, qr[3]) circuit.s(qr[2]) circuit.x(qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) passmanager = PassManager() passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(np.pi * 17 / 12), [qr[2]]) expected.append(RZGate(np.pi * 2 / 3), [qr[3]]) expected.cx(qr[2], qr[1]) self.assertEqual( expected, new_circuit, msg=f"expected:\n{expected}\nnew_circuit:\n{new_circuit}" ) def test_cnot_cascade(self): """ A cascade of CNOTs that equals identity. """ qr = QuantumRegister(10, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) passmanager = PassManager() # passmanager.append(CommutativeCancellation()) passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_cnot_cascade1(self): """ A cascade of CNOTs that equals identity, with rotation gates inserted. """ qr = QuantumRegister(10, "qr") circuit = QuantumCircuit(qr) circuit.rx(np.pi, qr[0]) circuit.rx(np.pi, qr[1]) circuit.rx(np.pi, qr[2]) circuit.rx(np.pi, qr[3]) circuit.rx(np.pi, qr[4]) circuit.rx(np.pi, qr[5]) circuit.rx(np.pi, qr[6]) circuit.rx(np.pi, qr[7]) circuit.rx(np.pi, qr[8]) circuit.rx(np.pi, qr[9]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) circuit.rx(np.pi, qr[0]) circuit.rx(np.pi, qr[1]) circuit.rx(np.pi, qr[2]) circuit.rx(np.pi, qr[3]) circuit.rx(np.pi, qr[4]) circuit.rx(np.pi, qr[5]) circuit.rx(np.pi, qr[6]) circuit.rx(np.pi, qr[7]) circuit.rx(np.pi, qr[8]) circuit.rx(np.pi, qr[9]) passmanager = PassManager() # passmanager.append(CommutativeCancellation()) passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_conditional_gates_dont_commute(self): """Conditional gates do not commute and do not cancel""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────── # └───┘└╥┘ ┌─┐ # q_1: ──■───╫────■───┤M├─── # ┌─┴─┐ ║ ┌─┴─┐ └╥┘┌─┐ # q_2: ┤ X ├─╫──┤ X ├──╫─┤M├ # └───┘ ║ └─╥─┘ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ # c: 2/══════╩═╡ 0x0 ╞═╩══╩═ # 0 └─────┘ 0 1 circuit = QuantumCircuit(3, 2) circuit.h(0) circuit.measure(0, 0) circuit.cx(1, 2) circuit.cx(1, 2).c_if(circuit.cregs[0], 0) circuit.measure([1, 2], [0, 1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) self.assertEqual(circuit, new_circuit) def test_basis_01(self): """Test basis priority change, phase gate""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) circuit.rz(np.pi, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation(basis_gates=["cx", "p", "sx"])) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(11 * np.pi / 4, 0) expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2 self.assertEqual(new_circuit, expected) def test_target_basis_01(self): """Test basis priority change, phase gate, with target.""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) circuit.rz(np.pi, 0) theta = Parameter("theta") target = Target(num_qubits=2) target.add_instruction(CXGate()) target.add_instruction(PhaseGate(theta)) target.add_instruction(SXGate()) passmanager = PassManager() passmanager.append(CommutativeCancellation(target=target)) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(11 * np.pi / 4, 0) expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2 self.assertEqual(new_circuit, expected) def test_basis_02(self): """Test basis priority change, Rz gate""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) passmanager = PassManager() passmanager.append(CommutativeCancellation(basis_gates=["cx", "rz", "sx"])) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(7 * np.pi / 4, 0) expected.global_phase = 7 * np.pi / 4 / 2 self.assertEqual(new_circuit, expected) def test_basis_03(self): """Test no specified basis""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.s(0) expected.z(0) expected.t(0) self.assertEqual(new_circuit, expected) def test_basis_global_phase_01(self): """Test no specified basis, rz""" circ = QuantumCircuit(1) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) circ.p(np.pi / 2, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basis_global_phase_02(self): """Test no specified basis, p""" circ = QuantumCircuit(1) circ.p(np.pi / 2, 0) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basis_global_phase_03(self): """Test global phase preservation if cummulative z-rotation is 0""" circ = QuantumCircuit(1) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) circ.z(0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basic_classical_wires(self): """Test that transpile runs without internal errors when dealing with commutable operations with classical controls. Regression test for gh-8553.""" original = QuantumCircuit(2, 1) original.x(0).c_if(original.cregs[0], 0) original.x(1).c_if(original.cregs[0], 0) # This transpilation shouldn't change anything, but it should succeed. At one point it was # triggering an internal logic error and crashing. transpiled = PassManager([CommutativeCancellation()]).run(original) self.assertEqual(original, transpiled) def test_simple_if_else(self): """Test that the pass is not confused by if-else.""" base_test1 = QuantumCircuit(3, 3) base_test1.x(1) base_test1.cx(0, 1) base_test1.x(1) base_test2 = QuantumCircuit(3, 3) base_test2.rz(0.1, 1) base_test2.rz(0.1, 1) test = QuantumCircuit(3, 3) test.h(0) test.x(0) test.rx(0.2, 0) test.measure(0, 0) test.x(0) test.if_else( (test.clbits[0], True), base_test1.copy(), base_test2.copy(), test.qubits, test.clbits ) expected = QuantumCircuit(3, 3) expected.h(0) expected.rx(np.pi + 0.2, 0) expected.measure(0, 0) expected.x(0) expected_test1 = QuantumCircuit(3, 3) expected_test1.cx(0, 1) expected_test2 = QuantumCircuit(3, 3) expected_test2.rz(0.2, 1) expected.if_else( (expected.clbits[0], True), expected_test1.copy(), expected_test2.copy(), expected.qubits, expected.clbits, ) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test) self.assertEqual(new_circuit, expected) def test_nested_control_flow(self): """Test that the pass does not add barrier into nested control flow.""" level2_test = QuantumCircuit(2, 1) level2_test.cz(0, 1) level2_test.cz(0, 1) level2_test.cz(0, 1) level2_test.measure(0, 0) level1_test = QuantumCircuit(2, 1) level1_test.for_loop((0,), None, level2_test.copy(), level1_test.qubits, level1_test.clbits) level1_test.h(0) level1_test.h(0) level1_test.measure(0, 0) test = QuantumCircuit(2, 1) test.while_loop((test.clbits[0], True), level1_test.copy(), test.qubits, test.clbits) test.measure(0, 0) level2_expected = QuantumCircuit(2, 1) level2_expected.cz(0, 1) level2_expected.measure(0, 0) level1_expected = QuantumCircuit(2, 1) level1_expected.for_loop( (0,), None, level2_expected.copy(), level1_expected.qubits, level1_expected.clbits ) level1_expected.measure(0, 0) expected = QuantumCircuit(2, 1) expected.while_loop( (expected.clbits[0], True), level1_expected.copy(), expected.qubits, expected.clbits ) expected.measure(0, 0) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test) self.assertEqual(new_circuit, expected) def test_cancellation_not_crossing_block_boundary(self): """Test that the pass does cancel gates across control flow op block boundaries.""" test1 = QuantumCircuit(2, 2) test1.x(1) with test1.if_test((0, False)): test1.cx(0, 1) test1.x(1) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test1) self.assertEqual(new_circuit, test1) def test_cancellation_not_crossing_between_blocks(self): """Test that the pass does cancel gates in different control flow ops.""" test2 = QuantumCircuit(2, 2) with test2.if_test((0, True)): test2.x(1) with test2.if_test((0, True)): test2.cx(0, 1) test2.x(1) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test2) self.assertEqual(new_circuit, test2) if __name__ == "__main__": unittest.main()
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import Aer from qiskit_aqua import run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import clique from qiskit_aqua.algorithms import ExactEigensolver K = 3 # K means the size of the clique np.random.seed(100) num_nodes = 5 w = clique.random_graph(num_nodes, edge_prob=0.8, weight_range=10) print(w) def brute_force(): # brute-force way: try every possible assignment! def bitfield(n, L): result = np.binary_repr(n, L) return [int(digit) for digit in result] L = num_nodes # length of the bitstring that represents the assignment max = 2**L has_sol = False for i in range(max): cur = bitfield(i, L) cur_v = clique.satisfy_or_not(np.array(cur), w, K) if cur_v: has_sol = True break return has_sol, cur has_sol, sol = brute_force() if has_sol: print("solution is ", sol) else: print("no solution found for K=", K) qubit_op, offset = clique.get_clique_qubitops(w, K) algo_input = EnergyInput(qubit_op) params = { 'problem': {'name': 'ising'}, 'algorithm': {'name': 'ExactEigensolver'} } result = run_algorithm(params, algo_input) x = clique.sample_most_likely(len(w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) if clique.satisfy_or_not(ising_sol, w, K): print("solution is", ising_sol) else: print("no solution found for K=", K) algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[]) result = algo.run() x = clique.sample_most_likely(len(w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) if clique.satisfy_or_not(ising_sol, w, K): print("solution is", ising_sol) else: print("no solution found for K=", K) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'COBYLA' } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 10598}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = clique.sample_most_likely(len(w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) if clique.satisfy_or_not(ising_sol, w, K): print("solution is", ising_sol) else: print("no solution found for K=", K)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import warnings warnings.filterwarnings('ignore') import unittest import pandas as pd import numpy as np from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram, plot_bloch_multivector from QuantumAssertions import assertPhase, assertEqual from BenchmarkQA import returnPhase import math import qiskit.quantum_info import numpy as np backend = Aer.get_backend('aer_simulator') # deg = 20 # backend = Aer.get_backend('aer_simulator') # qc = QuantumCircuit(1,1) # qc.save_statevector() # statevector = backend.run(qc).result().get_statevector() # plot_bloch_multivector(statevector) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.p(10*2*math.pi/100, 0) qc.p(20*2*math.pi/100, 1) assertPhase(backend, qc, [0,1], [36,72], 100000, 0.01) qc = QuantumCircuit(2) qc.h(0) qc.h(1) #qc.p(0.5*2*math.pi/100, 1) assertEqual(backend, qc, 0, 1, 300000, 0.01) # ## benchmark 100 shots at 1000 runs # shots = 100 # runs = 5000 # df = pd.DataFrame(columns=['results']) # for i in range(runs): # qc = QuantumCircuit(1,1) # qc.h(0) # qc.p(20*2*math.pi/100, 0) # df = df.append({'results': returnPhase(backend, qc, [0], [0], shots, 180)}, ignore_index=True) # if (i % 10 == 9): # print(f"progress: {i+1}/{runs}") # df.hist(bins=12) # print(df) # ## benchmark 1000 shots at 1000 runs # shots = 1000 # runs = 5000 # df = pd.DataFrame(columns=['results']) # for i in range(runs): # qc = QuantumCircuit(1,1) # qc.h(0) # qc.p(20*2*math.pi/100, 0) # df = df.append({'results': returnPhase(backend, qc, [0], [0], shots, 180)}, ignore_index=True) # if (i % 10 == 9): # print(f"progress: {i+1}/{runs}") # df.hist(bins=12) # print(df) # shots = 10000 # runs = 5000 # df = pd.DataFrame(columns=['results']) # for i in range(runs): # qc = QuantumCircuit(1,1) # qc.h(0) # qc.p(20*2*math.pi/100, 0) # df = df.append({'results': returnPhase(backend, qc, [0], [0], shots, 180)}, ignore_index=True) # if (i % 10 == 9): # print(f"progress: {i+1}/{runs}") # df.hist(bins=12) # print(df) # shots = 100000 # runs = 5000 # df = pd.DataFrame(columns=['results']) # for i in range(runs): # qc = QuantumCircuit(1,1) # qc.h(0) # qc.p(20*2*math.pi/100, 0) # df = df.append({'results': returnPhase(backend, qc, [0], [0], shots, 180)}, ignore_index=True) # if (i % 10 == 9): # print(f"progress: {i+1}/{runs}") # df.hist(bins=12) # print(df)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for diagonal instruction. """ import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'diagonal'): QuantumCircuit.diagonal = QuantumCircuit.diag_gate def diagonal_gate_circuits_deterministic(final_measure=True): """Diagonal gate test circuits with deterministic count output.""" circuits = [] qr = QuantumRegister(2, 'qr') if final_measure: cr = ClassicalRegister(2, 'cr') regs = (qr, cr) else: regs = (qr, ) # 4 x Swap |00> <--> |01> states # 4 x Swap |00> <--> |10> states arg = [1, -1] for qubit in [0, 1]: for diag in [arg, np.array(arg), np.array(arg, dtype=float), np.array(arg, dtype=complex)]: circuit = QuantumCircuit(*regs) circuit.h(qubit) circuit.diagonal(list(diag), [qubit]) circuit.h(qubit) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 4 x Swap |00> <--> |11> states arg = [1, -1, -1, 1] for diag in [arg, np.array(arg), np.array(arg, dtype=float), np.array(arg, dtype=complex)]: circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.diagonal(list(diag), qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CS01.XX, exp(-1j * np.pi/k)|11> state for diag in [np.array([1, 1, 1, np.exp(-1j * np.pi / k)]) for k in [10, 100, 1000, 10000]]: circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.diagonal(list(diag), qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def diagonal_gate_counts_deterministic(shots, hex_counts=True): """Diagonal gate circuits reference counts.""" targets = [] if hex_counts: # Swap |00> <--> |01> states targets += 4 * [{'0x1': shots}] # Swap |00> <--> |10> states targets += 4 * [{'0x2': shots}] # Swap |00> <--> |11> states targets += 4 * [{'0x3': shots}] # CS01.XX, exp(-1j * np.pi/N)|11> state targets += 4 * [{'0x3': shots}] else: # Swap |00> <--> |01> states targets += 4 * [{'01': shots}] # Swap |00> <--> |10> states targets += 4 * [{'10': shots}] # Swap |00> <--> |11> states targets += 4 * [{'11': shots}] # CS01.XX, exp(-1j * np.pi/k)|11> state targets += 4 * [{'11': shots}] return targets def diagonal_gate_statevector_deterministic(): """Diagonal gate test circuits with deterministic counts.""" targets = [] # Swap |00> <--> |01> states targets += 4 * [np.array([0, 1, 0, 0])] # Swap |00> <--> |10> states targets += 4 * [np.array([0, 0, 1, 0])] # Swap |00> <--> |11> states targets += 4 * [np.array([0, 0, 0, 1])] # CS01.XX, exp(-1j * np.pi/k)|11> state targets += [np.array([0, 0, 0, np.exp(-1j * np.pi / k)]) for k in [10, 100, 1000, 10000]] return targets def diagonal_gate_unitary_deterministic(): """Diagonal gate circuits reference unitaries.""" targets = [] # Swap |00> <--> |01> states targets += 4 * [np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])] # Swap |00> <--> |10> states targets += 4 * [np.array([[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])] # Swap |00> <--> |11> states targets += 4 * [np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])] # CS01.XX, 1j|11> state targets += [np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [np.exp(-1j * np.pi / k), 0, 0, 0]]) for k in [10, 100, 1000, 10000]] return targets
https://github.com/lynkos/grovers-algorithm
lynkos
from argparse import ArgumentParser, Namespace, BooleanOptionalAction from qiskit import QuantumCircuit as qc from qiskit import QuantumRegister as qr from qiskit import transpile from qiskit_aer import AerSimulator from qiskit.result import Counts from matplotlib.pyplot import show, subplots, xticks, yticks from math import pi, sqrt from heapq import nlargest class GroversAlgorithm: def __init__(self, title: str = "Grover's Algorithm", n_qubits: int = 5, search: set[int] = { 11, 9, 0, 3 }, shots: int = 1000, fontsize: int = 10, print: bool = False, combine_states: bool = False) -> None: """ _summary_ Args: title (str, optional): Window title. Defaults to "Grover's Algorithm". n_qubits (int, optional): Number of qubits. Defaults to 5. search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }. shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000. fontsize (int, optional): Histogram's font size. Defaults to 10. print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False. combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False. """ # Parsing command line arguments self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False) self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states) self._args: Namespace = self._parser.parse_args() # Set of nonnegative ints to search for self.search: set[int] = set(self._args.search) # Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2) self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search } # N-qubit quantum register self._qubits: qr = qr(self._args.n_qubits, "qubit") def _print_circuit(self, circuit: qc, name: str) -> None: """Print quantum circuit. Args: circuit (qc): Quantum circuit to print. name (str): Quantum circuit's name. """ print(f"\n{name}:\n{circuit}") def _oracle(self, targets: set[str]) -> qc: """Mark target state(s) with negative phase. Args: targets (set[str]): N-qubit binary string(s) representing target state(s). Returns: qc: Quantum circuit representation of oracle. """ # Create N-qubit quantum circuit for oracle oracle = qc(self._qubits, name = "Oracle") for target in targets: # Reverse target state since Qiskit uses little-endian for qubit ordering target = target[::-1] # Flip zero qubits in target for i in range(self._args.n_qubits): if target[i] == "0": # Pauli-X gate oracle.x(i) # Simulate (N - 1)-control Z gate # 1. Hadamard gate oracle.h(self._args.n_qubits - 1) # 2. (N - 1)-control Toffoli gate oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1) # 3. Hadamard gate oracle.h(self._args.n_qubits - 1) # Flip back to original state for i in range(self._args.n_qubits): if target[i] == "0": # Pauli-X gate oracle.x(i) # Display oracle, if applicable if self._args.print: self._print_circuit(oracle, "ORACLE") return oracle def _diffuser(self) -> qc: """Amplify target state(s) amplitude, which decreases the amplitudes of other states and increases the probability of getting the correct solution (i.e. target state(s)). Returns: qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator). """ # Create N-qubit quantum circuit for diffuser diffuser = qc(self._qubits, name = "Diffuser") # Hadamard gate diffuser.h(self._qubits) # Oracle with all zero target state diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits))) # Hadamard gate diffuser.h(self._qubits) # Display diffuser, if applicable if self._args.print: self._print_circuit(diffuser, "DIFFUSER") return diffuser def _grover(self) -> qc: """Create quantum circuit representation of Grover's algorithm, which consists of 4 parts: (1) state preparation/initialization, (2) oracle, (3) diffuser, and (4) measurement of resulting state. Steps 2-3 are repeated an optimal number of times (i.e. Grover's iterate) in order to maximize probability of success of Grover's algorithm. Returns: qc: Quantum circuit representation of Grover's algorithm. """ # Create N-qubit quantum circuit for Grover's algorithm grover = qc(self._qubits, name = "Grover Circuit") # Intialize qubits with Hadamard gate (i.e. uniform superposition) grover.h(self._qubits) # # Apply barrier to separate steps grover.barrier() # Apply oracle and diffuser (i.e. Grover operator) optimal number of times for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))): grover.append(self._oracle(self._targets), list(range(self._args.n_qubits))) grover.append(self._diffuser(), list(range(self._args.n_qubits))) # Measure all qubits once finished grover.measure_all() # Display grover circuit, if applicable if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT") return grover def _outcome(self, winners: list[str], counts: Counts) -> None: """Print top measurement(s) (state(s) with highest frequency) and target state(s) in binary and decimal form, determine if top measurement(s) equals target state(s), then print result. Args: winners (list[str]): State(s) (N-qubit binary string(s)) with highest probability of being measured. counts (Counts): Each state and its respective frequency. """ print("WINNER(S):") print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n") print("TARGET(S):") print(f"Binary = {self._targets}\nDecimal = {self.search}\n") if not all(key in self._targets for key in winners): print("Target(s) not found...") else: winners_frequency, total = 0, 0 for value, frequency in counts.items(): if value in winners: winners_frequency += frequency total += frequency print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!") def _show_histogram(self, histogram_data) -> None: """Print outcome and display histogram of simulation results. Args: data: Each state and its respective frequency. """ # State(s) with highest count and their frequencies winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) } # Print outcome self._outcome(list(winners.keys()), histogram_data) # X-axis and y-axis value(s) for winners, respectively winners_x_axis = [ str(winner) for winner in [*winners] ] winners_y_axis = [ *winners.values() ] # All other states (i.e. non-winners) and their frequencies others = { state : frequency for state, frequency in histogram_data.items() if state not in winners } # X-axis and y-axis value(s) for all other states, respectively other_states_x_axis = "Others" if self._args.combine else [*others] other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ] # Create histogram for simulation results figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained") axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target") axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target") axes.legend(fontsize = self._args.fontsize) axes.grid(axis = "y", ls = "dashed") axes.set_axisbelow(True) # Set histogram title, x-axis title, and y-axis title respectively axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45)) axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3)) axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3)) # Set font properties for x-axis and y-axis labels respectively xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70) yticks(fontsize = self._args.fontsize, family = "monospace") # Set properties for annotations displaying frequency above each bar annotation = axes.annotate("", xy = (0, 0), xytext = (5, 5), xycoords = "data", textcoords = "offset pixels", ha = "center", va = "bottom", family = "monospace", weight = "bold", fontsize = self._args.fontsize, bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0) ) def _hover(event) -> None: """Display frequency above each bar upon hovering over it. Args: event: Matplotlib event. """ visibility = annotation.get_visible() if event.inaxes == axes: for bars in axes.containers: for bar in bars: cont, _ = bar.contains(event) if cont: x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height() annotation.xy = (x, y) annotation.set_text(y) annotation.set_visible(True) figure.canvas.draw_idle() return if visibility: annotation.set_visible(False) figure.canvas.draw_idle() # Display histogram id = figure.canvas.mpl_connect("motion_notify_event", _hover) show() figure.canvas.mpl_disconnect(id) def run(self) -> None: """ Run Grover's algorithm simulation. """ # Simulate Grover's algorithm locally backend = AerSimulator(method = "density_matrix") # Generate optimized grover circuit for simulation transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2) # Run Grover's algorithm simulation job = backend.run(transpiled_circuit, shots = self._args.shots) # Get simulation results results = job.result() # Get each state's histogram data (including frequency) from simulation results data = results.get_counts() # Display simulation results self._show_histogram(data) def _init_parser(self, title: str, n_qubits: int, search: set[int], shots: int, fontsize: int, print: bool, combine_states: bool) -> None: """ Helper method to initialize command line argument parser. Args: title (str): Window title. n_qubits (int): Number of qubits. search (set[int]): Set of nonnegative integers to search for using Grover's algorithm. shots (int): Amount of times the algorithm is simulated. fontsize (int): Histogram's font size. print (bool): Whether or not to print quantum circuit(s). combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not. """ self._parser.add_argument("-H, --help", action = "help", help = "show this help message and exit") self._parser.add_argument("-T, --title", type = str, default = title, dest = "title", metavar = "<title>", help = f"window title (default: \"{title}\")") self._parser.add_argument("-n, --n-qubits", type = int, default = n_qubits, dest = "n_qubits", metavar = "<n_qubits>", help = f"number of qubits (default: {n_qubits})") self._parser.add_argument("-s, --search", default = search, type = int, nargs = "+", dest = "search", metavar = "<search>", help = f"nonnegative integers to search for with Grover's algorithm (default: {search})") self._parser.add_argument("-S, --shots", type = int, default = shots, dest = "shots", metavar = "<shots>", help = f"amount of times the algorithm is simulated (default: {shots})") self._parser.add_argument("-f, --font-size", type = int, default = fontsize, dest = "fontsize", metavar = "<font_size>", help = f"histogram's font size (default: {fontsize})") self._parser.add_argument("-p, --print", action = BooleanOptionalAction, type = bool, default = print, dest = "print", help = f"whether or not to print quantum circuit(s) (default: {print})") self._parser.add_argument("-c, --combine", action = BooleanOptionalAction, type = bool, default = combine_states, dest = "combine", help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})") if __name__ == "__main__": GroversAlgorithm().run()
https://github.com/qiskit-community/prototype-zne
qiskit-community
# for loading execution context parameters from the environment import os from dotenv import load_dotenv # for (de)serializing results import json # for processing data import numpy as np # for plotting results import matplotlib as mpl import matplotlib.pyplot as plt # for defining the circuits and observables constituting our expectation value problems from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import SparsePauliOp # for using real quantum hardware from qiskit import IBMQ, transpile from qiskit_ibm_runtime import QiskitRuntimeService from zne import ZNEStrategy from zne import Estimator as ZneEstimator from zne.noise_amplification import NoiseAmplifier load_dotenv() TOKEN = os.environ["TOKEN"] HUB = os.environ["HUB"] GROUP = os.environ["GROUP"] PROJECT = os.environ["PROJECT"] BACKEND = os.environ["BACKEND"] service = QiskitRuntimeService(channel="ibm_quantum", instance=f"{HUB}/{GROUP}/{PROJECT}", token=TOKEN) IBMQ.enable_account(TOKEN) provider = IBMQ.get_provider(hub=HUB, group=GROUP, project=PROJECT) backend = provider.get_backend(BACKEND) mpl.rcParams['figure.dpi'] = 500 plt.rcParams.update({ "text.usetex": True, "font.family": "Computer Modern Roman" }) def plot_trial( noise_factors, measured_evs, measured_errors, trial_id="A", alpha=0.5, color="#dc267f", ): plt.plot(noise_factors, measured_evs, label=f"Measured (Trial {trial_id})", color=color) plt.fill_between( noise_factors, measured_evs - measured_errors, measured_evs + measured_errors, alpha=alpha, color=color, linewidth=0 ) def show_experiment( trials, exact_ev, experiment_repr, observable_repr, num_shots=4000, ev_range=None ): noise_factors = np.array(trials[0]["noise_factors"]) plt.plot([0, noise_factors[-1]], [exact_ev, exact_ev], "--", label=f"Exact", color="#000000") for trial_id, color, measured_data in zip(('A', 'B'), ("#dc267f", "#785ef0"), trials): measured_evs = np.array(measured_data["values"]) measured_errors = np.sqrt(np.array(measured_data["variances"]) / num_shots) plot_trial( noise_factors, measured_evs, measured_errors, trial_id=trial_id, color=color ) plt.title(experiment_repr) plt.xlabel("Noise Factor ($n$)") plt.ylabel(f"Expectation Value ($\langle {observable_repr} \\rangle$)") if ev_range: plt.ylim(ev_range) plt.legend() plt.show() class SingleGateFoldingAmplifier(NoiseAmplifier): def __init__(self, gate_name: str): self.gate_name = gate_name def amplify_circuit_noise(self, circuit: QuantumCircuit, noise_factor: float) -> QuantumCircuit: noisy_circuit = circuit.copy_empty_like() for instruction, qargs, cargs in circuit: if instruction.name == self.gate_name: for i in range(noise_factor): if i % 2 == 0: noisy_circuit.append(instruction, qargs, cargs) else: noisy_circuit.append(instruction.inverse(), qargs, cargs) noisy_circuit.barrier(qargs) else: noisy_circuit.append(instruction, qargs, cargs) return noisy_circuit x_circuit = QuantumCircuit(1) x_circuit.x(0) x_observable = SparsePauliOp.from_list([('Z', 1)]) x_exact_ev = -1.0 display(x_circuit.draw("mpl")) print(x_observable) print(x_exact_ev) x_granular_noise_factors = tuple(range(1, 599 + 2, 2)) x_behavioral_noise_factors = tuple(range(1, 5999, 20)) # with ZneEstimator( # circuits=[x_circuit], # observables=[x_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=x_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()), # ) as estimator: # x_granular_a_results = estimator( # circuits=[0], # observables=[0], # ) # x_granular_a_data = { # "noise_factors": list(x_granular_a_results.metadata[0]["zne"]["noise_factors"]), # "values": list(x_granular_a_results.metadata[0]["zne"]["values"]), # "variances": list(x_granular_a_results.metadata[0]["zne"]["variances"]), # } # with open('data/x/x_granular_a.json', 'w') as f: # json.dump(x_granular_a_data, f) with open('data/x/x_granular_a.json', 'r') as f: x_granular_a_data = json.load(f) # with ZneEstimator( # circuits=[x_circuit], # observables=[x_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=x_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()), # ) as estimator: # x_granular_b_results = estimator( # circuits=[0], # observables=[0], # ) # x_granular_b_data = { # "noise_factors": list(x_granular_b_results.metadata[0]["zne"]["noise_factors"]), # "values": list(x_granular_b_results.metadata[0]["zne"]["values"]), # "variances": list(x_granular_b_results.metadata[0]["zne"]["variances"]), # } # with open('data/x/x_granular_b.json', 'w') as f: # json.dump(x_granular_b_data, f) with open('data/x/x_granular_b.json', 'r') as f: x_granular_b_data = json.load(f) # with ZneEstimator( # circuits=[x_circuit], # observables=[x_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=x_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()), # ) as estimator: # x_behavioral_a_results = estimator( # circuits=[0], # observables=[0], # ) # x_behavioral_a_data = { # "noise_factors": list(x_behavioral_a_results.metadata[0]["zne"]["noise_factors"]), # "values": list(x_behavioral_a_results.metadata[0]["zne"]["values"]), # "variances": list(x_behavioral_a_results.metadata[0]["zne"]["variances"]), # } # with open('data/x/x_behavioral_a.json', 'w') as f: # json.dump(x_behavioral_a_data, f) with open('data/x/x_behavioral_a.json', 'r') as f: x_behavioral_a_data = json.load(f) # with ZneEstimator( # circuits=[x_circuit], # observables=[x_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=x_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()), # ) as estimator: # x_behavioral_b_results = estimator( # circuits=[0], # observables=[0], # ) # x_behavioral_b_data = { # "noise_factors": list(x_behavioral_b_results.metadata[0]["zne"]["noise_factors"]), # "values": list(x_behavioral_b_results.metadata[0]["zne"]["values"]), # "variances": list(x_behavioral_b_results.metadata[0]["zne"]["variances"]), # } # with open('data/x/x_behavioral_b.json', 'w') as f: # json.dump(x_behavioral_b_data, f) with open('data/x/x_behavioral_b.json', 'r') as f: x_behavioral_b_data = json.load(f) show_experiment([x_granular_a_data, x_granular_b_data], x_exact_ev, "$X$ Granular Folding Profile — $\langle 0 | X^n Z X^n | 0 \\rangle(n)$", 'Z') show_experiment([x_behavioral_a_data, x_behavioral_b_data], x_exact_ev, "$X$ Behavioral Folding Profile — $\langle 0 | X^n Z X^n | 0 \\rangle(n)$", 'Z') sx_circuit = QuantumCircuit(1) sx_circuit.sx(0) sx_observable = SparsePauliOp.from_list([('Y', 1)]) sx_exact_ev = -1.0 display(sx_circuit.draw("mpl")) print(sx_observable) print(sx_exact_ev) sx_granular_noise_factors = tuple(range(1, 599 + 2, 2)) sx_behavioral_noise_factors = tuple(range(1, 4999, 20)) # with ZneEstimator( # circuits=[sx_circuit], # observables=[sx_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=sx_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()), # ) as estimator: # sx_granular_a_results = estimator( # circuits=[0], # observables=[0], # ) # sx_granular_a_data = { # "noise_factors": list(sx_granular_a_results.metadata[0]["zne"]["noise_factors"]), # "values": list(sx_granular_a_results.metadata[0]["zne"]["values"]), # "variances": list(sx_granular_a_results.metadata[0]["zne"]["variances"]), # } # with open('data/sx/sx_granular_a.json', 'w') as f: # json.dump(sx_granular_a_data, f) with open('data/sx/sx_granular_a.json', 'r') as f: sx_granular_a_data = json.load(f) # with ZneEstimator( # circuits=[sx_circuit], # observables=[sx_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=sx_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()), # ) as estimator: # sx_granular_b_results = estimator( # circuits=[0], # observables=[0], # ) # sx_granular_b_data = { # "noise_factors": list(sx_granular_b_results.metadata[0]["zne"]["noise_factors"]), # "values": list(sx_granular_b_results.metadata[0]["zne"]["values"]), # "variances": list(sx_granular_b_results.metadata[0]["zne"]["variances"]), # } # with open('data/sx/sx_granular_b.json', 'w') as f: # json.dump(sx_granular_b_data, f) with open('data/sx/sx_granular_b.json', 'r') as f: sx_granular_b_data = json.load(f) # with ZneEstimator( # circuits=[sx_circuit], # observables=[sx_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=sx_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()), # ) as estimator: # sx_behavioral_a_results = estimator( # circuits=[0], # observables=[0], # ) # sx_behavioral_a_data = { # "noise_factors": list(sx_behavioral_a_results.metadata[0]["zne"]["noise_factors"]), # "values": list(sx_behavioral_a_results.metadata[0]["zne"]["values"]), # "variances": list(sx_behavioral_a_results.metadata[0]["zne"]["variances"]), # } # with open('data/sx/sx_behavioral_a.json', 'w') as f: # json.dump(sx_behavioral_a_data, f) with open('data/sx/sx_behavioral_a.json', 'r') as f: sx_behavioral_a_data = json.load(f) # with ZneEstimator( # circuits=[sx_circuit], # observables=[sx_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=sx_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()), # ) as estimator: # sx_behavioral_b_results = estimator( # circuits=[0], # observables=[0], # ) # sx_behavioral_b_data = { # "noise_factors": list(sx_behavioral_b_results.metadata[0]["zne"]["noise_factors"]), # "values": list(sx_behavioral_b_results.metadata[0]["zne"]["values"]), # "variances": list(sx_behavioral_b_results.metadata[0]["zne"]["variances"]), # } # with open('data/sx/sx_behavioral_b.json', 'w') as f: # json.dump(sx_behavioral_b_data, f) with open('data/sx/sx_behavioral_b.json', 'r') as f: sx_behavioral_b_data = json.load(f) show_experiment([sx_granular_a_data, sx_granular_b_data], sx_exact_ev, "$\sqrt X$ Granular Folding Profile — $\langle 0|{\sqrt X}^nY{\sqrt X}^n|0\\rangle(n)$", 'Y') show_experiment([sx_behavioral_a_data, sx_behavioral_b_data], sx_exact_ev, "$\sqrt X$ Behavioral Folding Profile — $\langle 0|{\sqrt X}^nY{\sqrt X}^n|0\\rangle(n)$", 'Y') rz_theta = Parameter('theta') rz_circuit = QuantumCircuit(1) rz_circuit.h(0) rz_circuit.rz(rz_theta, 0) rz_circuit.h(0) rz_observable = SparsePauliOp.from_list([('Z', 1)]) rz_theta = np.pi / 4 rz_exact_ev = np.cos(rz_theta) display(rz_circuit.draw('mpl')) print(rz_observable) print(rz_theta) print(rz_exact_ev) rz_granular_noise_factors = tuple(range(1, 599 + 2, 2)) # with ZneEstimator( # circuits=[rz_circuit], # observables=[rz_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=rz_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='rz')), # ) as estimator: # rz_granular_a_results = estimator( # circuits=[0], # observables=[0], # parameter_values=[rz_theta] # ) # rz_granular_a_data = { # "noise_factors": list(rz_granular_a_results.metadata[0]["zne"]["noise_factors"]), # "values": list(rz_granular_a_results.metadata[0]["zne"]["values"]), # "variances": list(rz_granular_a_results.metadata[0]["zne"]["variances"]), # } # with open('data/rz/rz_granular_a.json', 'w') as f: # json.dump(rz_granular_a_data, f) with open('data/rz/rz_granular_a.json', 'r') as f: rz_granular_a_data = json.load(f) # with ZneEstimator( # circuits=[rz_circuit], # observables=[rz_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=rz_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='rz')), # ) as estimator: # rz_granular_b_results = estimator( # circuits=[0], # observables=[0], # parameter_values=[rz_theta] # ) # rz_granular_b_data = { # "noise_factors": list(rz_granular_b_results.metadata[0]["zne"]["noise_factors"]), # "values": list(rz_granular_b_results.metadata[0]["zne"]["values"]), # "variances": list(rz_granular_b_results.metadata[0]["zne"]["variances"]), # } # with open('data/rz/rz_granular_b.json', 'w') as f: # json.dump(rz_granular_b_data, f) with open('data/rz/rz_granular_b.json', 'r') as f: rz_granular_b_data = json.load(f) show_experiment([rz_granular_a_data, rz_granular_b_data], rz_exact_ev, "$R_Z$ Folding Profile — $\langle0|H{R_Z(-\\frac\pi4)}^nHZH{R_Z(\\frac\pi4)}^nH|0\\rangle(n)$", 'Z', ev_range=(0.5, 0.9)) cx_circuit = QuantumCircuit(2) cx_circuit.x(0) cx_circuit.cx(0, 1) cx_observable = SparsePauliOp.from_list([('ZI', 1)]) cx_exact_ev = -1.0 display(cx_circuit.draw("mpl")) print(cx_observable) print(cx_exact_ev) cx_granular_noise_factors = tuple(range(1, 599 + 2, 2)) cx_behavioral_noise_factors = tuple(range(1, 5999, 20)) # with ZneEstimator( # circuits=[cx_circuit], # observables=[cx_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=cx_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='cx')), # ) as estimator: # cx_granular_a_results = estimator( # circuits=[0], # observables=[0], # ) # cx_granular_a_data = { # "noise_factors": list(cx_granular_a_results.metadata[0]["zne"]["noise_factors"]), # "values": list(cx_granular_a_results.metadata[0]["zne"]["values"]), # "variances": list(cx_granular_a_results.metadata[0]["zne"]["variances"]), # } # with open('data/cx/cx_granular_a.json', 'w') as f: # json.dump(cx_granular_a_data, f) with open('data/cx/cx_granular_a.json', 'r') as f: cx_granular_a_data = json.load(f) # with ZneEstimator( # circuits=[cx_circuit], # observables=[cx_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=cx_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='cx')), # ) as estimator: # cx_granular_b_results = estimator( # circuits=[0], # observables=[0], # ) # cx_granular_b_data = { # "noise_factors": list(cx_granular_b_results.metadata[0]["zne"]["noise_factors"]), # "values": list(cx_granular_b_results.metadata[0]["zne"]["values"]), # "variances": list(cx_granular_b_results.metadata[0]["zne"]["variances"]), # } # with open('data/cx/cx_granular_b.json', 'w') as f: # json.dump(cx_granular_b_data, f) with open('data/cx/cx_granular_b.json', 'r') as f: cx_granular_b_data = json.load(f) # with ZneEstimator( # circuits=[cx_circuit], # observables=[cx_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=cx_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='cx')), # ) as estimator: # cx_behavioral_a_results = estimator( # circuits=[0], # observables=[0], # ) # cx_behavioral_a_data = { # "noise_factors": list(cx_behavioral_a_results.metadata[0]["zne"]["noise_factors"]), # "values": list(cx_behavioral_a_results.metadata[0]["zne"]["values"]), # "variances": list(cx_behavioral_a_results.metadata[0]["zne"]["variances"]), # } # with open('data/cx/cx_behavioral_a.json', 'w') as f: # json.dump(cx_behavioral_a_data, f) with open('data/cx/cx_behavioral_a.json', 'r') as f: cx_behavioral_a_data = json.load(f) # with ZneEstimator( # circuits=[cx_circuit], # observables=[cx_observable], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=cx_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='cx')), # ) as estimator: # cx_behavioral_b_results = estimator( # circuits=[0], # observables=[0], # ) # cx_behavioral_b_data = { # "noise_factors": list(cx_behavioral_b_results.metadata[0]["zne"]["noise_factors"]), # "values": list(cx_behavioral_b_results.metadata[0]["zne"]["values"]), # "variances": list(cx_behavioral_b_results.metadata[0]["zne"]["variances"]), # } # with open('data/cx/cx_behavioral_b.json', 'w') as f: # json.dump(cx_behavioral_b_data, f) with open('data/cx/cx_behavioral_b.json', 'r') as f: cx_behavioral_b_data = json.load(f) show_experiment([cx_granular_a_data, cx_granular_b_data], cx_exact_ev, "$CX$ Granular Folding Profile — $\langle 00|(XI)({CX})^n(ZI)({CX})^n(XI)|00\\rangle(n)$", 'ZI') show_experiment([cx_behavioral_a_data, cx_behavioral_b_data], cx_exact_ev, "$CX$ Behavioral Folding Profile — $\langle 00|(XI)({CX})^n(ZI)({CX})^n(XI)|00\\rangle(n)$", 'ZI')
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb
https://github.com/acfilok96/Quantum-Computation
acfilok96
# Quantum Computation import qiskit print(qiskit.__version__) import qiskit.quantum_info as qi from qiskit.circuit.library import FourierChecking from qiskit.visualization import plot_histogram f = [1, -1, -1, -1] g = [1, 1, -1, -1] # How co-related fourier transform of function g to function f. # we will check for probability '00', if p(f,g) >= 0.05, then, # fourier transform of function g co-related to function f. circ = FourierChecking(f=f,g=g) circ.draw() zero = qi.Statevector.from_label('00') # '00' or '01' or '10' or '11' sv = zero.evolve(circ) probs = sv.probabilities_dict() plot_histogram(probs)
https://github.com/aaghazaly/quantum-project-using-qiskit
aaghazaly
''' Shor's Algorithm Shor's algorithm is a quantum computer algorithm for integer factorization. Informally, it solves the following problem: Given an integer N, find its prime factors. It was invented in 1994 by the American mathematician Peter Shor. Source: https://www.wikiwand.com/en/Shor%27s_algorithm Factorization problem can reduce to period finding problem. Consider the sequence of the powers of two 1, 2, 4, 8, 16, 32, 64, 128, ... Now, let's look at the same sequence 'mod 15': 1, 2, 4, 8, 1, 2, 4, 8, ... This is a modulo sequence that repeats every four numbers, that is, a periodic modulo sequence with a period of four. Reduction of factorization of N to the problem of finding the period of an integer 1 < x < N depends on the following result from number theory: The function F(a) = x^a mod N is a periodic function, where x is an integer coprime to N and a >= 0. Source: https://github.com/Qiskit/qiskit-community-tutorials/blob/b9266a4f9c1f6b3f4cf5117d9c443f9f1c3518cb/algorithms/shor_algorithm.ipynb ''' import math from qiskit import IBMQ, BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # We'll build circuit for a^x mod 15 for a = 2 qr = QuantumRegister(5) cr = ClassicalRegister(5) circuit = QuantumCircuit(qr, cr) # Initialize q[0] to |1> circuit.x(qr[0]) # Apply a**4 mod 15 circuit.h(qr[4]) circuit.h(qr[4]) circuit.measure(qr[4], cr[0]) circuit.reset(qr[4]) # Apply a**2 mod 15 circuit.h(qr[4]) circuit.cx(qr[4], qr[2]) circuit.cx(qr[4], qr[0]) circuit.u1(math.pi/2., qr[4]).c_if(cr, 1) circuit.u1(math.pi/2., qr[4]).c_if(cr, 1) circuit.h(qr[4]) circuit.measure(qr[4], cr[1]) circuit.reset(qr[4]) # Apply a mod 15 circuit.h(qr[4]) circuit.cswap(qr[4], qr[3], qr[2]) circuit.cswap(qr[4], qr[2], qr[1]) circuit.cswap(qr[4], qr[1], qr[0]) circuit.u1(3.*math.pi/4., qr[4]).c_if(cr, 3) circuit.u1(math.pi/2., qr[4]).c_if(cr, 2) circuit.u1(math.pi/4., qr[4]).c_if(cr, 1) circuit.h(qr[4]) circuit.measure(qr[4], cr[2]) # Run our circuit with local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(circuit, backend=backend, shots=shots).result() answer = results.get_counts() print(answer) # We see the measurements yield x = 0, 2, 4 and 6 with equal(ish) probability. # Using the continued fraction expansion for x/2^3, we note that only x = 2 and # 6 give the correct period r = 4, and thus the factors p = gcd(a^{r/2}+1,15) = 3 # and q = gcd(a^{r/2}-1,15) = 5.
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
def dec2den(j,N,d): den = [0 for k in range(0,N)] jv = j for k in range(0,N): if jv >= d**(N-1-k): den[k] = jv//(d**(N-1-k)) jv = jv - den[k]*d**(N-1-k) return den def den2dec(local,d): # local = list with the local computational base state values # d = individual qudit dimension N = len(local) j = 0 for k in range(0,N): j += local[k]*d**(N-1-k) return j # value of the global computational basis index def dec2den_opt(j,N,d): # optimized version den = [0 for k in range(0,N)] if j < d: den[N-1] = j; return den rem = [] # list for the remainder k = j while k >= d: rem.append(k%d) k = k//d rem.append(k%d) for j in range(0,len(rem)): den[N-1-j] = rem[j] return den import numpy as np def swap_qudits(d,N,t,c): # d = qudit dimension; N = No. of qudits; t = target qudit (0,...,N-1); c = control qudit (0,...,N-1) D = d**N; swap = np.zeros((D,D), dtype=int) # set all d^2N elements to 0 for k in range (0,d**N): localr = dec2den_opt(k,N,d) # sequence of values for the local basis #locall = [0 for k in range(0,N)] #for s in range(0,N): # locall[s] = localr[s] locall = localr.copy() #rt = localr[t]; locall[c] = localr[t] #rc = localr[c]; locall[t] = localr[c] globall = den2dec(locall,d) swap[globall,k] = 1 return swap d=2; N=2; t=0; c=1; print(swap_qudits(d,N,t,c)) # ok d=3; N=2; t=0; c=1; print(swap_qudits(d,N,t,c)) # ok d=2; N=3; t=0; c=2; print(swap_qudits(d,N,t,c)) # ok
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from sympy import Matrix from sympy.physics.quantum import TensorProduct ket0 = Matrix([1,0]) ket0 = Matrix([1,0]) TensorProduct(ket0, ket0) ket0 = Matrix([1,0]) ket1 = Matrix([0,1]) TensorProduct(ket0, ket1) ket1 = Matrix([0,1]) ket0 = Matrix([1,0]) TensorProduct(ket1, ket0) ket1 = Matrix([0,1]) ket0 = Matrix([1,0]) TensorProduct(ket1, ket1)
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
#!/usr/bin/env python # coding: utf-8 # In[2]: from dell_runtime import DellRuntimeProvider from qiskit import QuantumCircuit import pandas as pd from time import sleep import os import base64 import shutil import json # here = os.path.dirname(os.path.realpath(__file__)) # zipped = shutil.make_archive(here + "/tmp", "zip", here + "/qkad") # with open(zipped, "rb") as z: # data = z.read() # data = base64.urlsafe_b64encode(data) # sdata = str(data, "utf-8") # bdata = bytes(sdata, "utf-8") # sdata = str(bdata, "utf-8") # obj = { # 'data': sdata, # 'data_type': "DIR" # } # jsonstr = json.dumps(obj) # ljson = json.loads(jsonstr) # bdata = bytes(ljson['data'], "utf-8") # b64data = base64.urlsafe_b64decode(bdata) # with open(zipped, "wb") as temp: # temp.write(b64data) # shutil.unpack_archive(zipped, extract_dir=here + "/qkad1", format="zip") # os.remove(zipped) provider = DellRuntimeProvider() RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program" } provider.remote(os.getenv("SERVER_URL")) here = os.path.dirname(os.path.realpath(__file__)) program_id = provider.runtime.upload_program(here + "/qkad", metadata=RUNTIME_PROGRAM_METADATA) job = provider.runtime.run(program_id, options=None, inputs={}) res = job.result(timeout=1000) print(res)
https://github.com/AsishMandoi/VRP-explorations
AsishMandoi
import numpy as np class Initializer: def __init__(self, n, a, b): self.n = n self.a = a self.b = b def generate_nodes_and_weight_matrix(self): n = self.n a = self.a b = self.b np.random.seed(100*a + b) x = (np.random.rand(n) - 0.5) * 50 y = (np.random.rand(n) - 0.5) * 50 weight_matrix = np.zeros([n, n]) for i in range(n): for j in range(i+1, n): weight_matrix[i, j] = (x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2 weight_matrix[j, i] = weight_matrix[i, j] return x, y, weight_matrix from utils import VRPSolver, compare_solvers, random_routing_instance n=10 # number of clients m=3 # number of vehicles initializer = Initializer(n+1, n+1, 3) xc, yc, cost = initializer.generate_nodes_and_weight_matrix() ### Select the type of model to solve VRP # 1: Constrained Quadratic Model - A new model released by D-Wave Systems capable of encoding Quadratically Constrained Quadratic Programs (QCQPs) # 2: Binary Quadratic Model - A model that encodes Ising or QUBO problems model = 'CQM' ### The time limit (in seconds) for the solvers to run on the `LeapHybridCQMSampler` backend time_limit = 25 ### Select solver # 1: RAS (Route Activation Solver) # 2: FQS (Full QUBO Solver) # 3: GPS (Guillermo, Parfait, Saúl) (only using CQM) # 4: DBSCANS (Density-Based Spatial Clustering of Applications with Noise - Solver) # 5: SPS (Solution Partition Solver) solver = 'fqs' vrps = VRPSolver(n, m, cost, xc, yc, model=model, solver=solver, time_limit=time_limit) vrps.solve_vrp() vrps.plot_solution() # Number of iterations to get the average approximation ratio for a particular solver # Warning! More iterations will take more time and resources to run n_iter = 1 comparison_table = compare_solvers(n, m, cost, xc, yc, n_iter=n_iter, time_limit=time_limit) print('Minimum cost of best known solution:', comparison_table[0]['exact_min_cost']) for solver_id in comparison_table[1]: print(f'{solver_id}:', '\t', f'average min cost = {comparison_table[1][solver_id]["avg_min_cost"]}', '\t', f'average runtime = {comparison_table[1][solver_id]["avg_runtime"]}', '\t', f'number of variables = {comparison_table[1][solver_id]["num_vars"]}', '\t', f'approximation ratio = {comparison_table[1][solver_id]["approximation_ratio"]}' )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/erinaldi/bmn2-qiskit
erinaldi
import numpy as np from scipy.sparse import diags L = 8 # cutoff for Fock space a = diags(np.sqrt(np.linspace(1,L-1,L-1)),offsets=1) print(a.toarray()) from qiskit.opflow import MatrixOp qubitOp = MatrixOp(primitive=a) print(qubitOp.num_qubits) type(qubitOp) print(qubitOp) a_pauli = qubitOp.to_pauli_op() print(a_pauli) type(a_pauli) a_pauli.to_matrix() from scipy.sparse import identity iden = identity(L) qubitOp = MatrixOp(primitive=iden) print(qubitOp.num_qubits) i_pauli = qubitOp.to_pauli_op() print(i_pauli) i_pauli.to_matrix() Nmat = 6 # BMN2 for SU(2) has 6 bosonic matrices from qiskit.opflow import ListOp, TensoredOp boson = ListOp([i_pauli]*6) print(boson) print(boson[0]) type(boson[0]) # generically speaking, we construct the list of bosons and then take the outer product a_list = [] # this will contain a1...a6 as a list of ListOp for i in np.arange(0,Nmat): # loop over all operators operator_list = [i_pauli] * Nmat # only the identity repeated Nmat times operator_list[i] = a_pauli # the i^th element is now the annihilation operator for a single boson a_list.append(ListOp(operator_list)) print(a_list[0]) type(a_list[0]) # here we create a list of operators which are the tensor products... a_tensor = [TensoredOp(x) for x in a_list] print(a_tensor[0]) print(a_tensor[0].to_pauli_op()) a_tensor[0].num_qubits sparse = a_tensor[0].to_spmatrix() type(sparse) sparse.shape # from qiskit.utils import algorithm_globals # algorithm_globals.massive=True # needed to big matrices... # full = a_tensor[0].to_matrix() # len(full) # full.shape i_tensor = TensoredOp(ListOp([i_pauli] * Nmat)) type(i_tensor) print(i_tensor) i_tensor.to_pauli_op() from qiskit.opflow import I I^Nmat i_tensor.num_qubits # full = i_tensor.to_matrix() # len(full) print(i_tensor.to_spmatrix()) # for each boson they are constructed using a and adag x_tensor = [1/np.sqrt(2)*(~x + x) for x in a_tensor] print(x_tensor[0]) print(x_tensor[0].to_pauli_op()) print(x_tensor[0].to_spmatrix()) from qiskit.opflow import SummedOp H_zero = 0.5*Nmat*i_tensor print(H_zero) H_zero_pauli = 0.5*Nmat*(I^Nmat) print(H_zero.to_pauli_op()) print(H_zero_pauli) H_zero.to_spmatrix() H_zero.to_pauli_op() ### Harmonic oscillator # this should be summed over all the bosons (Nmat) H_list = [H_zero] for op in a_tensor: H_list.append((~op @ op)) H_osc = SummedOp(H_list) print(H_osc) type(H_osc) H_osc_pauli = H_osc.to_pauli_op() type(H_osc_pauli) H_osc_pauli.num_qubits H_osc.to_spmatrix() quartic1 = SummedOp([x_tensor[2]@x_tensor[2]@x_tensor[3]@x_tensor[3], \ x_tensor[2]@x_tensor[2]@x_tensor[4]@x_tensor[4], \ x_tensor[1]@x_tensor[1]@x_tensor[3]@x_tensor[3], \ x_tensor[1]@x_tensor[1]@x_tensor[5]@x_tensor[5], \ x_tensor[0]@x_tensor[0]@x_tensor[4]@x_tensor[4], \ x_tensor[0]@x_tensor[0]@x_tensor[5]@x_tensor[5]]) print(quartic1.to_pauli_op()) quartic2 = SummedOp([x_tensor[0]@x_tensor[2]@x_tensor[3]@x_tensor[5],\ x_tensor[0]@x_tensor[1]@x_tensor[3]@x_tensor[4],\ x_tensor[1]@x_tensor[2]@x_tensor[4]@x_tensor[5]], coeff = -2.0) print(quartic2.to_pauli_op()) type(quartic2) ### Quartic Interaction V = quartic1 + quartic2 V.num_qubits V_pauli = V.to_pauli_op() g2N = 0.2 N = 2 ### Full Hamiltonian H = H_osc + g2N / N * V type(H) H.to_pauli_op() type(H.to_pauli_op()) H.num_qubits testH = H.to_matrix_op() testH Hpauli = H.to_pauli_op() # the line below is also fine... # Hpauli1 = H_osc.to_pauli_op() + g2N / N * V.to_pauli_op() # Hpauli print(Hpauli) type(Hpauli) print(f"Number of terms in H: {len(Hpauli.oplist)}") # write expression to disk with open('pauliH_L8_bos2.txt','w') as f: print(Hpauli,file=f) import sys print(sys.getsizeof(Hpauli)) from pympler import asizeof print(f"Size of Hpauli in MB: {asizeof.asizeof(Hpauli)/1024/1024}") # print(asizeof.asized(Hpauli, detail=1).format()) from qiskit.algorithms import NumPyMinimumEigensolver npme = NumPyMinimumEigensolver() # result = npme.compute_minimum_eigenvalue(operator=H_osc) # result = npme.compute_minimum_eigenvalue(operator=H) result = npme.compute_minimum_eigenvalue(operator=Hpauli) # result = npme.compute_minimum_eigenvalue(operator=testH) print(result) ref_value = result.eigenvalue.real print(f'Ground state energy value: {ref_value:.5f}') from scipy.sparse import kron def build_operators(L: int, N: int) -> list: """Generate all the annihilation operators needed to build the hamiltonian Args: L (int): the cutoff of the single site Fock space N (int): the number of colors of gauge group SU(N) Returns: list: a list of annihilation operators, length=N_bos """ # The annihilation operator for the single boson a_b = diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1) # The identity operator of the Fock space of a single boson i_b = identity(L) # Bosonic Hilbert space N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> fixed for mini-BMN 2 product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times a_b_list = [] # this will contain a1...a6 for i in np.arange(0, N_bos): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[ i ] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append( operator_list[0] ) # start taking tensor products from first element for a in operator_list[1:]: a_b_list[i] = kron( a_b_list[i], a ) # do the outer product between each operator_list element return a_b_list a_b_list = build_operators(L,N) # Build the Hamiltonian # Start piece by piece x_list = [] # only use the bosonic operators for op in a_b_list: x_list.append(1 / np.sqrt(2) * (op.conjugate().transpose() + op)) # Free Hamiltonian H_k = 0 for a in a_b_list: H_k = H_k + a.conjugate().transpose() * a # vacuum energy H_k = H_k + 0.5 * Nmat * identity(L ** Nmat) am = MatrixOp(a_b_list[0]) # this takes a really long time even for L=4 print(am.to_pauli_op()) xm = MatrixOp(x_list[0]) print(xm.to_pauli_op()) Hm = MatrixOp(H_k) result = npme.compute_minimum_eigenvalue(operator=Hm) ref_value = result.eigenvalue.real print(f'Ground state energy value: {ref_value:.5f}') v_b1 = ( x_list[2] * x_list[2] * x_list[3] * x_list[3] + x_list[2] * x_list[2] * x_list[4] * x_list[4] + x_list[1] * x_list[1] * x_list[3] * x_list[3] + x_list[1] * x_list[1] * x_list[5] * x_list[5] + x_list[0] * x_list[0] * x_list[4] * x_list[4] + x_list[0] * x_list[0] * x_list[5] * x_list[5] ) v_b2 = -2.0 * ( x_list[0] * x_list[2] * x_list[3] * x_list[5] + x_list[0] * x_list[1] * x_list[3] * x_list[4] + x_list[1] * x_list[2] * x_list[4] * x_list[5] ) V_b = v_b1 + v_b2 vm = MatrixOp(v_b1) vm.to_pauli_op() vm = MatrixOp(v_b2) vm.to_pauli_op() # full hamiltonian H_full = H_k + g2N / N * V_b Hm = MatrixOp(H_full) Hm.to_pauli_op() result = npme.compute_minimum_eigenvalue(operator=Hm) ref_value = result.eigenvalue.real print(f'Ground state energy value: {ref_value:.5f}') result = npme.compute_minimum_eigenvalue(operator=Hm.to_pauli_op()) ref_value = result.eigenvalue.real print(f'Ground state energy value: {ref_value:.5f}') print(result)
https://github.com/deveshq/QC-with-qiskit
deveshq
import numpy as np #Importing standard Qiskit libraries from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.providers import * from qiskit.circuit import Parameter import matplotlib.pyplot as plt #Loading IBM Quantum account(s) provider = IBMQ.load_account() q = QuantumRegister(1,'q') e = QuantumRegister(1,'e') c = ClassicalRegister(1,'c') def damp_M(steps): qc = QuantumCircuit(q,e,c) theta = np.pi/8 qc.x(q) qc.barrier() for i in range(steps): if (i>0): qc.reset(e) qc.cry(theta,q,e) qc.cx(e,q) qc.measure(e,c) qc.barrier() qc.measure(q,c) sim = Aer.get_backend('qasm_simulator') job = execute(qc, sim, shots=1024) res = job.result() counts = res.get_counts() return counts qc = damp_M(1) qc.draw('mpl') steps = np.linspace(0,150,51) prob0 = [] for st in steps: co = damp_M(int(st)) if '1' in co: prob0.append(co['1']/1024) else: prob0.append(0) fig = plt.figure(figsize=(8,5)) plt.scatter(steps,prob0) plt.plot(steps,prob0) plt.xticks(size=12) plt.yticks(size=12) plt.title('\nMarkovian amplitude damping of a qubit', size=14) plt.xlabel(r'Steps $\longrightarrow$', size=13) plt.ylabel(r'Population density $\longrightarrow$', size=13) plt.show() q = QuantumRegister(1,'q') e = QuantumRegister(3,'e') c = ClassicalRegister(1,'c') def damp_NM(steps): qc = QuantumCircuit(q,e,c) t1 = np.pi/8 t2 = 5*np.pi/6 t3 = np.pi qc.x(q) qc.barrier() for i in range(steps): qc.cry(t1,q,e[0]) qc.cry(t2,q,e[1]) qc.cry(t3,q,e[2]) qc.cx(e[0],q[0]) qc.measure(e[0],c) qc.reset(e[0]) qc.swap(e[0],e[1]) qc.swap(e[1],e[2]) qc.barrier() qc.measure(q,c) sim = Aer.get_backend('qasm_simulator') job = execute(qc, sim, shots=1024) res = job.result() counts = res.get_counts() return counts qc = damp_NM(1) qc.draw('mpl') steps = np.linspace(0,150,51) prob0_NM = [] for st in steps: co = damp_NM(int(st)) if '1' in co: prob0_NM.append(co['1']/1024) else: prob0_NM.append(0) fig = plt.figure(figsize=(8,5)) plt.scatter(steps,prob0_NM) plt.plot(steps,prob0_NM) plt.xticks(size=12) plt.yticks(size=12) plt.title('\nNon-Markovian amplitude damping of a qubit', size=14) plt.xlabel(r'Steps $\longrightarrow$', size=13) plt.ylabel(r'Population density $\longrightarrow$', size=13) plt.show() fig = plt.figure(figsize=(8,5)) plt.plot(steps,prob0) #plt.scatter(steps,prob0) plt.plot(steps,prob0_NM) #plt.scatter(steps,prob0_NM) plt.xticks(size=12) plt.yticks(size=12) plt.legend(['Markovian','Non-Markovian']) plt.title('\nDamping of a qubit', size=14) plt.xlabel(r'Steps $\longrightarrow$', size=13) plt.ylabel(r'Population density $\longrightarrow$', size=13) plt.show()
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import numpy as np X = np.array([[0, 1], [1, 0]]) print("XX^dagger") print(X @ X.T.conj()) print("X^daggerX") print(X.T.conj() @ X) print("The norm of the state |0> before applying X") zero_ket = np.array([[1], [0]]) print(np.linalg.norm(zero_ket)) print("The norm of the state after applying X") print(np.linalg.norm(X @ zero_ket)) import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit_aer import AerSimulator from qiskit.quantum_info import Statevector np.set_printoptions(precision=3, suppress=True) backend_statevector = AerSimulator(method='statevector') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.x(q[0]) circuit.x(q[0]) # get the statevector state = Statevector.from_instruction(circuit) print(state.data) def mixed_state(pure_state, visibility): density_matrix = pure_state @ pure_state.T.conj() maximally_mixed_state = np.eye(4)/2**2 return visibility*density_matrix + (1-visibility)*maximally_mixed_state ϕ = np.array([[1],[0],[0],[1]])/np.sqrt(2) print("Maximum visibility is a pure state:") print(mixed_state(ϕ, 1.0)) print("The state is still entangled with visibility 0.8:") print(mixed_state(ϕ, 0.8)) print("Entanglement is lost by 0.6:") print(mixed_state(ϕ, 0.6)) print("Barely any coherence remains by 0.2:") print(mixed_state(ϕ, 0.2)) import matplotlib.pyplot as plt temperatures = [.5, 5, 2000] energies = np.linspace(0, 20, 100) fig, ax = plt.subplots() for i, T in enumerate(temperatures): probabilities = np.exp(-energies/T) Z = probabilities.sum() probabilities /= Z ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$") ax.set_xlim(0, 20) ax.set_ylim(0, 1.2*probabilities.max()) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlabel('Energy') ax.set_ylabel('Probability') ax.legend()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the CSPLayout pass""" import unittest from time import process_time from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import CSPLayout from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeTenerife, FakeRueschlikon, FakeTokyo, FakeYorktownV2 from qiskit.utils import optionals @unittest.skipUnless(optionals.HAS_CONSTRAINT, "needs python-constraint") class TestCSPLayout(QiskitTestCase): """Tests the CSPLayout pass""" seed = 42 def test_2q_circuit_2q_coupling(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 0) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_3q_circuit_5q_coupling(self): """3 qubits in Tenerife, without considering the direction qr1 / | qr0 - qr2 - 3 | / 4 """ cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 3) self.assertEqual(layout[qr[1]], 2) self.assertEqual(layout[qr[2]], 4) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_3q_circuit_5q_coupling_with_target(self): """3 qubits in Yorktown, without considering the direction qr1 / | qr0 - qr2 - 3 | / 4 """ target = FakeYorktownV2().target qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = CSPLayout(target, strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 3) self.assertEqual(layout[qr[1]], 2) self.assertEqual(layout[qr[2]], 4) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_9q_circuit_16q_coupling(self): """9 qubits in Rueschlikon, without considering the direction q0[1] - q0[0] - q1[3] - q0[3] - q1[0] - q1[1] - q1[2] - 8 | | | | | | | | q0[2] - q1[4] -- 14 ---- 13 ---- 12 ---- 11 ---- 10 --- 9 """ cmap16 = FakeRueschlikon().configuration().coupling_map qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr0[0]], 9) self.assertEqual(layout[qr0[1]], 6) self.assertEqual(layout[qr0[2]], 7) self.assertEqual(layout[qr0[3]], 5) self.assertEqual(layout[qr1[0]], 14) self.assertEqual(layout[qr1[1]], 12) self.assertEqual(layout[qr1[2]], 1) self.assertEqual(layout[qr1[3]], 8) self.assertEqual(layout[qr1[4]], 10) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_2q_circuit_2q_coupling_sd(self): """A simple example, considering the direction 0 -> 1 qr1 -> qr0 """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 0) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_3q_circuit_5q_coupling_sd(self): """3 qubits in Tenerife, considering the direction qr0 ↙ ↑ qr2 ← qr1 ← 3 ↑ ↙ 4 """ cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 2) self.assertEqual(layout[qr[2]], 0) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_9q_circuit_16q_coupling_sd(self): """9 qubits in Rueschlikon, considering the direction q0[1] → q0[0] → q1[3] → q0[3] ← q1[0] ← q1[1] → q1[2] ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ q0[2] ← q1[4] → 14 ← 13 ← 12 → 11 → 10 ← 9 """ cmap16 = FakeRueschlikon().configuration().coupling_map qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr0[0]], 9) self.assertEqual(layout[qr0[1]], 6) self.assertEqual(layout[qr0[2]], 7) self.assertEqual(layout[qr0[3]], 5) self.assertEqual(layout[qr1[0]], 14) self.assertEqual(layout[qr1[1]], 12) self.assertEqual(layout[qr1[2]], 1) self.assertEqual(layout[qr1[3]], 10) self.assertEqual(layout[qr1[4]], 8) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_5q_circuit_16q_coupling_no_solution(self): """5 qubits in Rueschlikon, no solution q0[1] ↖ ↗ q0[2] q0[0] q0[3] ↙ ↘ q0[4] """ cmap16 = FakeRueschlikon().configuration().coupling_map qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.cx(qr[0], qr[4]) dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertIsNone(layout) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "nonexistent solution") @staticmethod def create_hard_dag(): """Creates a particularly hard circuit (returns its dag) for Tokyo""" circuit = QuantumCircuit(20) circuit.cx(13, 12) circuit.cx(6, 0) circuit.cx(5, 10) circuit.cx(10, 7) circuit.cx(5, 12) circuit.cx(2, 15) circuit.cx(16, 18) circuit.cx(6, 4) circuit.cx(10, 3) circuit.cx(11, 10) circuit.cx(18, 16) circuit.cx(5, 12) circuit.cx(4, 0) circuit.cx(18, 16) circuit.cx(2, 15) circuit.cx(7, 8) circuit.cx(9, 6) circuit.cx(16, 17) circuit.cx(9, 3) circuit.cx(14, 12) circuit.cx(2, 15) circuit.cx(1, 16) circuit.cx(5, 3) circuit.cx(8, 12) circuit.cx(2, 1) circuit.cx(5, 3) circuit.cx(13, 5) circuit.cx(12, 14) circuit.cx(12, 13) circuit.cx(6, 4) circuit.cx(15, 18) circuit.cx(15, 18) return circuit_to_dag(circuit) def test_time_limit(self): """Hard to solve situations hit the time limit""" dag = TestCSPLayout.create_hard_dag() coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map) pass_ = CSPLayout(coupling_map, call_limit=None, time_limit=1) start = process_time() pass_.run(dag) runtime = process_time() - start self.assertLess(runtime, 3) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "time limit reached") def test_call_limit(self): """Hard to solve situations hit the call limit""" dag = TestCSPLayout.create_hard_dag() coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map) pass_ = CSPLayout(coupling_map, call_limit=1, time_limit=None) start = process_time() pass_.run(dag) runtime = process_time() - start self.assertLess(runtime, 1) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "call limit reached") def test_seed(self): """Different seeds yield different results""" seed_1 = 42 seed_2 = 43 cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_1 = CSPLayout(CouplingMap(cmap5), seed=seed_1) pass_1.run(dag) layout_1 = pass_1.property_set["layout"] pass_2 = CSPLayout(CouplingMap(cmap5), seed=seed_2) pass_2.run(dag) layout_2 = pass_2.property_set["layout"] self.assertNotEqual(layout_1, layout_2) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def Decrement(n): U = QuantumCircuit(n) control = [x for x in range(n-1)] for k in range(n-1): U.x(control) U.mcx(control, control[-1]+1) U.x(control) control.pop() U.x(0) U = U.to_gate() U.name = 'Decrement' #ctl_U = U.control() make it a controlled gate return U n = 3 mc = QuantumCircuit(n, n) U = Decrement(n) mc.append(U, range(n)) mc.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mc, backend=backend, shots=atp).result() ans = res.get_counts() mc.draw('mpl') plot_histogram(ans)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Sabre Swap pass""" import unittest import itertools import ddt import numpy.random from qiskit.circuit import Clbit, ControlFlowOp, Qubit from qiskit.circuit.library import CCXGate, HGate, Measure, SwapGate from qiskit.circuit.classical import expr from qiskit.circuit.random import random_circuit from qiskit.compiler.transpiler import transpile from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.providers.fake_provider import FakeMumbai, FakeMumbaiV2 from qiskit.transpiler.passes import SabreSwap, TrivialLayout, CheckMap from qiskit.transpiler import CouplingMap, Layout, PassManager, Target, TranspilerError from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.test._canonical import canonicalize_control_flow from qiskit.utils import optionals def looping_circuit(uphill_swaps=1, additional_local_minimum_gates=0): """A circuit that causes SabreSwap to loop infinitely. This looks like (using cz gates to show the symmetry, though we actually output cx for testing purposes): .. parsed-literal:: q_0: ─■──────────────── │ q_1: ─┼──■───────────── │ │ q_2: ─┼──┼──■────────── │ │ │ q_3: ─┼──┼──┼──■─────── │ │ │ │ q_4: ─┼──┼──┼──┼─────■─ │ │ │ │ │ q_5: ─┼──┼──┼──┼──■──■─ │ │ │ │ │ q_6: ─┼──┼──┼──┼──┼──── │ │ │ │ │ q_7: ─┼──┼──┼──┼──■──■─ │ │ │ │ │ q_8: ─┼──┼──┼──┼─────■─ │ │ │ │ q_9: ─┼──┼──┼──■─────── │ │ │ q_10: ─┼──┼──■────────── │ │ q_11: ─┼──■───────────── │ q_12: ─■──────────────── where `uphill_swaps` is the number of qubits separating the inner-most gate (representing how many swaps need to be made that all increase the heuristics), and `additional_local_minimum_gates` is how many extra gates to add on the outside (these increase the size of the region of stability). """ outers = 4 + additional_local_minimum_gates n_qubits = 2 * outers + 4 + uphill_swaps # This is (most of) the front layer, which is a bunch of outer qubits in the # coupling map. outer_pairs = [(i, n_qubits - i - 1) for i in range(outers)] inner_heuristic_peak = [ # This gate is completely "inside" all the others in the front layer in # terms of the coupling map, so it's the only one that we can in theory # make progress towards without making the others worse. (outers + 1, outers + 2 + uphill_swaps), # These are the only two gates in the extended set, and they both get # further apart if you make a swap to bring the above gate closer # together, which is the trick that creates the "heuristic hill". (outers, outers + 1), (outers + 2 + uphill_swaps, outers + 3 + uphill_swaps), ] qc = QuantumCircuit(n_qubits) for pair in outer_pairs + inner_heuristic_peak: qc.cx(*pair) return qc @ddt.ddt class TestSabreSwap(QiskitTestCase): """Tests the SabreSwap pass.""" def test_trivial_case(self): """Test that an already mapped circuit is unchanged. ┌───┐┌───┐ q_0: ──■──┤ H ├┤ X ├──■── ┌─┴─┐└───┘└─┬─┘ │ q_1: ┤ X ├──■────■────┼── └───┘┌─┴─┐ │ q_2: ──■──┤ X ├───────┼── ┌─┴─┐├───┤ │ q_3: ┤ X ├┤ X ├───────┼── └───┘└─┬─┘ ┌─┴─┐ q_4: ───────■───────┤ X ├ └───┘ """ coupling = CouplingMap.from_ring(5) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # F qc.cx(1, 0) qc.cx(4, 3) # F qc.cx(0, 4) passmanager = PassManager(SabreSwap(coupling, "basic")) new_qc = passmanager.run(qc) self.assertEqual(new_qc, qc) def test_trivial_with_target(self): """Test that an already mapped circuit is unchanged with target.""" coupling = CouplingMap.from_ring(5) target = Target(num_qubits=5) target.add_instruction(SwapGate(), {edge: None for edge in coupling.get_edges()}) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # F qc.cx(1, 0) qc.cx(4, 3) # F qc.cx(0, 4) passmanager = PassManager(SabreSwap(target, "basic")) new_qc = passmanager.run(qc) self.assertEqual(new_qc, qc) def test_lookahead_mode(self): """Test lookahead mode's lookahead finds single SWAP gate. ┌───┐ q_0: ──■──┤ H ├─────────────── ┌─┴─┐└───┘ q_1: ┤ X ├──■────■─────────■── └───┘┌─┴─┐ │ │ q_2: ──■──┤ X ├──┼────■────┼── ┌─┴─┐└───┘┌─┴─┐┌─┴─┐┌─┴─┐ q_3: ┤ X ├─────┤ X ├┤ X ├┤ X ├ └───┘ └───┘└───┘└───┘ q_4: ───────────────────────── """ coupling = CouplingMap.from_line(5) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # free qc.cx(1, 3) # F qc.cx(2, 3) # E qc.cx(1, 3) # E pm = PassManager(SabreSwap(coupling, "lookahead")) new_qc = pm.run(qc) self.assertEqual(new_qc.num_nonlocal_gates(), 7) def test_do_not_change_cm(self): """Coupling map should not change. See https://github.com/Qiskit/qiskit-terra/issues/5675""" cm_edges = [(1, 0), (2, 0), (2, 1), (3, 2), (3, 4), (4, 2)] coupling = CouplingMap(cm_edges) passmanager = PassManager(SabreSwap(coupling)) _ = passmanager.run(QuantumCircuit(coupling.size())) self.assertEqual(set(cm_edges), set(coupling.get_edges())) def test_do_not_reorder_measurements(self): """Test that SabreSwap doesn't reorder measurements to the same classical bit. With the particular coupling map used in this test and the 3q ccx gate, the routing would invariably the measurements if the classical successors are not accurately tracked. Regression test of gh-7950.""" coupling = CouplingMap([(0, 2), (2, 0), (1, 2), (2, 1)]) qc = QuantumCircuit(3, 1) qc.compose(CCXGate().definition, [0, 1, 2], []) # Unroll CCX to 2q operations. qc.h(0) qc.barrier() qc.measure(0, 0) # This measure is 50/50 between the Z states. qc.measure(1, 0) # This measure always overwrites with 0. passmanager = PassManager(SabreSwap(coupling)) transpiled = passmanager.run(qc) last_h = transpiled.data[-4] self.assertIsInstance(last_h.operation, HGate) first_measure = transpiled.data[-2] second_measure = transpiled.data[-1] self.assertIsInstance(first_measure.operation, Measure) self.assertIsInstance(second_measure.operation, Measure) # Assert that the first measure is on the same qubit that the HGate was applied to, and the # second measurement is on a different qubit (though we don't care which exactly - that # depends a little on the randomisation of the pass). self.assertEqual(last_h.qubits, first_measure.qubits) self.assertNotEqual(last_h.qubits, second_measure.qubits) # The 'basic' method can't get stuck in the same way. @ddt.data("lookahead", "decay") def test_no_infinite_loop(self, method): """Test that the 'release value' mechanisms allow SabreSwap to make progress even on circuits that get stuck in a stable local minimum of the lookahead parameters.""" qc = looping_circuit(3, 1) qc.measure_all() coupling_map = CouplingMap.from_line(qc.num_qubits) routing_pass = PassManager(SabreSwap(coupling_map, method)) n_swap_gates = 0 def leak_number_of_swaps(cls, *args, **kwargs): nonlocal n_swap_gates n_swap_gates += 1 if n_swap_gates > 1_000: raise Exception("SabreSwap seems to be stuck in a loop") # pylint: disable=bad-super-call return super(SwapGate, cls).__new__(cls, *args, **kwargs) with unittest.mock.patch.object(SwapGate, "__new__", leak_number_of_swaps): routed = routing_pass.run(qc) routed_ops = routed.count_ops() del routed_ops["swap"] self.assertEqual(routed_ops, qc.count_ops()) couplings = { tuple(routed.find_bit(bit).index for bit in instruction.qubits) for instruction in routed.data if len(instruction.qubits) == 2 } # Asserting equality to the empty set gives better errors on failure than asserting that # `couplings <= coupling_map`. self.assertEqual(couplings - set(coupling_map.get_edges()), set()) # Assert that the same keys are produced by a simulation - this is a test that the inserted # swaps route the qubits correctly. if not optionals.HAS_AER: return from qiskit import Aer sim = Aer.get_backend("aer_simulator") in_results = sim.run(qc, shots=4096).result().get_counts() out_results = sim.run(routed, shots=4096).result().get_counts() self.assertEqual(set(in_results), set(out_results)) def test_classical_condition(self): """Test that :class:`.SabreSwap` correctly accounts for classical conditions in its reckoning on whether a node is resolved or not. If it is not handled correctly, the second gate might not appear in the output. Regression test of gh-8040.""" with self.subTest("1 bit in register"): qc = QuantumCircuit(2, 1) qc.z(0) qc.z(0).c_if(qc.cregs[0], 0) cm = CouplingMap([(0, 1), (1, 0)]) expected = PassManager([TrivialLayout(cm)]).run(qc) actual = PassManager([TrivialLayout(cm), SabreSwap(cm)]).run(qc) self.assertEqual(expected, actual) with self.subTest("multiple registers"): cregs = [ClassicalRegister(3), ClassicalRegister(4)] qc = QuantumCircuit(QuantumRegister(2, name="q"), *cregs) qc.z(0) qc.z(0).c_if(cregs[0], 0) qc.z(0).c_if(cregs[1], 0) cm = CouplingMap([(0, 1), (1, 0)]) expected = PassManager([TrivialLayout(cm)]).run(qc) actual = PassManager([TrivialLayout(cm), SabreSwap(cm)]).run(qc) self.assertEqual(expected, actual) def test_classical_condition_cargs(self): """Test that classical conditions are preserved even if missing from cargs DAGNode field. Created from reproduction in https://github.com/Qiskit/qiskit-terra/issues/8675 """ with self.subTest("missing measurement"): qc = QuantumCircuit(3, 1) qc.cx(0, 2).c_if(0, 0) qc.measure(1, 0) qc.h(2).c_if(0, 0) expected = QuantumCircuit(3, 1) expected.swap(1, 2) expected.cx(0, 1).c_if(0, 0) expected.measure(2, 0) expected.h(1).c_if(0, 0) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) with self.subTest("reordered measurement"): qc = QuantumCircuit(3, 1) qc.cx(0, 1).c_if(0, 0) qc.measure(1, 0) qc.h(0).c_if(0, 0) expected = QuantumCircuit(3, 1) expected.cx(0, 1).c_if(0, 0) expected.measure(1, 0) expected.h(0).c_if(0, 0) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) def test_conditional_measurement(self): """Test that instructions with cargs and conditions are handled correctly.""" qc = QuantumCircuit(3, 2) qc.cx(0, 2).c_if(0, 0) qc.measure(2, 0).c_if(1, 0) qc.h(2).c_if(0, 0) qc.measure(1, 1) expected = QuantumCircuit(3, 2) expected.swap(1, 2) expected.cx(0, 1).c_if(0, 0) expected.measure(1, 0).c_if(1, 0) expected.h(1).c_if(0, 0) expected.measure(2, 1) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) @ddt.data("basic", "lookahead", "decay") def test_deterministic(self, heuristic): """Test that the output of the SabreSwap pass is deterministic for a given random seed.""" width = 40 # The actual circuit is unimportant, we just need one with lots of scoring degeneracy. qc = QuantumCircuit(width) for i in range(width // 2): qc.cx(i, i + (width // 2)) for i in range(0, width, 2): qc.cx(i, i + 1) dag = circuit_to_dag(qc) coupling = CouplingMap.from_line(width) pass_0 = SabreSwap(coupling, heuristic, seed=0, trials=1) pass_1 = SabreSwap(coupling, heuristic, seed=1, trials=1) dag_0 = pass_0.run(dag) dag_1 = pass_1.run(dag) # This deliberately avoids using a topological order, because that introduces an opportunity # for the re-ordering to sort the swaps back into a canonical order. def normalize_nodes(dag): return [(node.op.name, node.qargs, node.cargs) for node in dag.op_nodes()] # A sanity check for the test - if unequal seeds don't produce different outputs for this # degenerate circuit, then the test probably needs fixing (or Sabre is ignoring the seed). self.assertNotEqual(normalize_nodes(dag_0), normalize_nodes(dag_1)) # Check that a re-run with the same seed produces the same circuit in the exact same order. self.assertEqual(normalize_nodes(dag_0), normalize_nodes(pass_0.run(dag))) def test_rejects_too_many_qubits(self): """Test that a sensible Python-space error message is emitted if the DAG has an incorrect number of qubits.""" pass_ = SabreSwap(CouplingMap.from_line(4)) qc = QuantumCircuit(QuantumRegister(5, "q")) with self.assertRaisesRegex(TranspilerError, "More qubits in the circuit"): pass_(qc) def test_rejects_too_few_qubits(self): """Test that a sensible Python-space error message is emitted if the DAG has an incorrect number of qubits.""" pass_ = SabreSwap(CouplingMap.from_line(4)) qc = QuantumCircuit(QuantumRegister(3, "q")) with self.assertRaisesRegex(TranspilerError, "Fewer qubits in the circuit"): pass_(qc) @ddt.ddt class TestSabreSwapControlFlow(QiskitTestCase): """Tests for control flow in sabre swap.""" def test_shared_block(self): """Test multiple control flow ops sharing the same block instance.""" inner = QuantumCircuit(2) inner.cx(0, 1) qreg = QuantumRegister(4, "q") outer = QuantumCircuit(qreg, ClassicalRegister(1)) for pair in itertools.permutations(range(outer.num_qubits), 2): outer.if_test((outer.cregs[0], 1), inner, pair, []) coupling = CouplingMap.from_line(4) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(circuit_to_dag(outer)) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_blocks_use_registers(self): """Test that control flow ops using registers still use registers after routing.""" num_qubits = 2 qreg = QuantumRegister(num_qubits, "q") cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) qc = QuantumCircuit(qreg, cr1, cr2) with qc.if_test((cr1, False)): qc.cx(0, 1) qc.measure(0, cr2[0]) with qc.if_test((cr2, 0)): qc.cx(0, 1) coupling = CouplingMap.from_line(num_qubits) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(circuit_to_dag(qc)) outer_if_op = cdag.op_nodes(ControlFlowOp)[0].op self.assertEqual(outer_if_op.condition[0], cr1) inner_if_op = circuit_to_dag(outer_if_op.blocks[0]).op_nodes(ControlFlowOp)[0].op self.assertEqual(inner_if_op.condition[0], cr2) def test_pre_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[2]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[2]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(1, 2) expected.cx(0, 1) expected.measure(1, 2) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) efalse_body.x(1) new_order = [0, 2, 1, 3, 4] expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else_route_post_x(self): """test swap with if else controlflow construct; pre-cx and post x""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]]) qc.x(1) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(1, 2) expected.cx(0, 1) expected.measure(1, 2) new_order = [0, 2, 1, 3, 4] etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.x(2) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_post_if_else_route(self): """test swap with if else controlflow construct; post cx""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.barrier(qreg) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.cx(0, 2) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.barrier(qreg) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.barrier(qreg) expected.swap(1, 2) expected.cx(0, 1) expected.barrier(qreg) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else2(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) false_body = QuantumCircuit(qreg, creg[[0]]) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[0]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[0]], creg[[0]]) new_order = [0, 2, 1, 3, 4] expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_intra_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(1, 2) etrue_body.cx(0, 1) etrue_body.swap(1, 2) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(3, 4) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.swap(3, 4) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_if_else(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) etrue_body = QuantumCircuit(qreg, creg[[0]]) efalse_body = QuantumCircuit(qreg, creg[[0]]) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body.cx(0, 1) efalse_body.swap(0, 1) efalse_body.swap(3, 4) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.swap(3, 4) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_post_if_else(self): """test swap with if else controlflow construct; cx before, in, and after if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.h(3) qc.cx(3, 0) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(0, 1) expected.cx(1, 2) expected.measure(1, 0) etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) etrue_body.cx(0, 1) efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]]) expected.h(3) expected.swap(1, 2) expected.cx(3, 2) expected.barrier() expected.measure(qreg, creg[[1, 2, 0, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_if_expr(self): """Test simple if conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=58, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_if_else_expr(self): """Test simple if/else conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) true = QuantumCircuit(4) true.cx(0, 1) true.cx(0, 2) true.cx(0, 3) false = QuantumCircuit(4) false.cx(3, 0) false.cx(3, 1) false.cx(3, 2) qc = QuantumCircuit(4, 2) qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=58, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_no_layout_change(self): """test controlflow with no layout change needed""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) @ddt.data(1, 2, 3) def test_for_loop(self, nloops): """test stochastic swap with for_loop""" num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) for_body = QuantumCircuit(qreg) for_body.cx(0, 2) loop_parameter = None qc.for_loop(range(nloops), loop_parameter, for_body, qreg, []) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) efor_body = QuantumCircuit(qreg) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) loop_parameter = None expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, []) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop(self): """test while loop""" num_qubits = 4 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(len(qreg)) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) while_body = QuantumCircuit(qreg, creg) while_body.reset(qreg[2:]) while_body.h(qreg[2:]) while_body.cx(0, 3) while_body.measure(qreg[3], creg[3]) qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) ewhile_body = QuantumCircuit(qreg, creg) ewhile_body.reset(qreg[2:]) ewhile_body.h(qreg[2:]) ewhile_body.swap(0, 1) ewhile_body.swap(2, 3) ewhile_body.cx(1, 2) ewhile_body.measure(qreg[2], creg[3]) ewhile_body.swap(1, 0) ewhile_body.swap(3, 2) expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits) expected.barrier() expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop_expr(self): """Test simple while loop with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_switch_implicit_carg_use(self): """Test that a switch statement that uses cargs only implicitly via its ``target`` attribute and not explicitly in bodies of the cases is routed correctly, with the dependencies fulfilled correctly.""" coupling = CouplingMap.from_line(4) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) body = QuantumCircuit([Qubit()]) body.x(0) # If the classical wire condition isn't respected, then the switch would appear in the front # layer and be immediately eligible for routing, which would produce invalid output. qc = QuantumCircuit(4, 1) qc.cx(0, 1) qc.cx(1, 2) qc.cx(0, 2) qc.measure(2, 0) qc.switch(expr.lift(qc.clbits[0]), [(False, body.copy()), (True, body.copy())], [3], []) expected = QuantumCircuit(4, 1) expected.cx(0, 1) expected.cx(1, 2) expected.swap(2, 1) expected.cx(0, 1) expected.measure(1, 0) expected.switch( expr.lift(expected.clbits[0]), [(False, body.copy()), (True, body.copy())], [3], [] ) self.assertEqual(pass_(qc), expected) def test_switch_single_case(self): """Test routing of 'switch' with just a single case.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:]) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_nonexhaustive(self): """Test routing of 'switch' with several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(2, 3) case2.cx(4, 3) case2.swap(2, 3) expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_expr_single_case(self): """Test routing of 'switch' with an `Expr` target and just a single case.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(expr.bit_or(creg, 5), [(0, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) expected.switch(expr.bit_or(creg, 5), [(0, case0)], qreg[[0, 1, 2]], creg[:]) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_expr_nonexhaustive(self): """Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(2, 3) case2.cx(4, 3) case2.swap(2, 3) expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_nested_inner_cnot(self): """test swap in nested if else controlflow construct; swap in inner""" num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(0, 2) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, []) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_nested_outer_cnot(self): """test swap with nested if else controlflow construct; swap in outer""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(1, 3) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(1, 2) etrue_body.cx(0, 1) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.cx(2, 3) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], []) etrue_body.swap(1, 2) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg[[0, 1, 2, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_disjoint_looping(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) loop_body = QuantumCircuit(2) loop_body.cx(0, 1) qc.for_loop((0,), None, loop_body, [0, 2], []) cqc = SabreSwap(cm, "lookahead", seed=82, trials=1)(qc) expected = QuantumCircuit(qr) efor_body = QuantumCircuit(qr[[0, 1, 2]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) expected.for_loop((0,), None, efor_body, [0, 1, 2], []) self.assertEqual(cqc, expected) def test_disjoint_multiblock(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr[0:3] + cr[:]) true_body.cx(0, 1) false_body = QuantumCircuit(qr[0:3] + cr[:]) false_body.cx(0, 2) qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0]) cqc = SabreSwap(cm, "lookahead", seed=82, trials=1)(qc) expected = QuantumCircuit(qr, cr) etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) etrue_body.cx(0, 1) efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) efalse_body.swap(1, 2) efalse_body.cx(0, 1) efalse_body.swap(1, 2) expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]]) self.assertEqual(cqc, expected) def test_multiple_ops_per_layer(self): """Test circuits with multiple operations per layer""" num_qubits = 6 coupling = CouplingMap.from_line(num_qubits) check_map_pass = CheckMap(coupling) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) # This cx and the for_loop are in the same layer. qc.cx(0, 2) with qc.for_loop((0,)): qc.cx(3, 5) cqc = SabreSwap(coupling, "lookahead", seed=82, trials=1)(qc) check_map_pass(cqc) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qr) expected.swap(1, 2) expected.cx(0, 1) efor_body = QuantumCircuit(qr[[3, 4, 5]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(2, 1) expected.for_loop((0,), None, efor_body, [3, 4, 5], []) self.assertEqual(cqc, expected) def test_if_no_else_restores_layout(self): """Test that an if block with no else branch restores the initial layout.""" qc = QuantumCircuit(8, 1) with qc.if_test((qc.clbits[0], False)): # Just some arbitrary gates with no perfect layout. qc.cx(3, 5) qc.cx(4, 6) qc.cx(1, 4) qc.cx(7, 4) qc.cx(0, 5) qc.cx(7, 3) qc.cx(1, 3) qc.cx(5, 2) qc.cx(6, 7) qc.cx(3, 2) qc.cx(6, 2) qc.cx(2, 0) qc.cx(7, 6) coupling = CouplingMap.from_line(8) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) transpiled = pass_(qc) # Check the pass claims to have done things right. initial_layout = Layout.generate_trivial_layout(*qc.qubits) self.assertEqual(initial_layout, pass_.property_set["final_layout"]) # Check that pass really did do it right. inner_block = transpiled.data[0].operation.blocks[0] running_layout = initial_layout.copy() for instruction in inner_block: if instruction.operation.name == "swap": running_layout.swap(*instruction.qubits) self.assertEqual(initial_layout, running_layout) @ddt.ddt class TestSabreSwapRandomCircuitValidOutput(QiskitTestCase): """Assert the output of a transpilation with stochastic swap is a physical circuit.""" @classmethod def setUpClass(cls): super().setUpClass() cls.backend = FakeMumbai() cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map} cls.basis_gates = set(cls.backend.configuration().basis_gates) cls.basis_gates.update(["for_loop", "while_loop", "if_else"]) def assert_valid_circuit(self, transpiled): """Assert circuit complies with constraints of backend.""" self.assertIsInstance(transpiled, QuantumCircuit) self.assertIsNotNone(getattr(transpiled, "_layout", None)) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name in {"barrier", "measure"}: continue self.assertIn(instruction.operation.name, self.basis_gates) qargs = tuple(qubit_mapping[x] for x in instruction.qubits) if not isinstance(instruction.operation, ControlFlowOp): if len(qargs) > 2 or len(qargs) < 0: raise Exception("Invalid number of qargs for instruction") if len(qargs) == 2: self.assertIn(qargs, self.coupling_edge_set) else: self.assertLessEqual(qargs[0], 26) else: for block in instruction.operation.blocks: self.assertEqual(block.num_qubits, len(instruction.qubits)) self.assertEqual(block.num_clbits, len(instruction.clbits)) new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @ddt.data(*range(1, 27)) def test_random_circuit_no_control_flow(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, self.backend, routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @ddt.data(*range(1, 27)) def test_random_circuit_no_control_flow_target(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, routing_method="sabre", layout_method="sabre", seed_transpiler=12342, target=FakeMumbaiV2().target, ) self.assert_valid_circuit(tqc) @ddt.data(*range(4, 27)) def test_random_circuit_for_loop(self, size): """Test that transpiled random circuits with nested for loops are physical circuits.""" circuit = random_circuit(size, 3, measure=False, seed=12342) for_block = random_circuit(3, 2, measure=False, seed=12342) inner_for_block = random_circuit(2, 1, measure=False, seed=12342) with circuit.for_loop((1,)): with circuit.for_loop((1,)): circuit.append(inner_for_block, [0, 3]) circuit.append(for_block, [1, 0, 2]) circuit.measure_all() tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @ddt.data(*range(6, 27)) def test_random_circuit_if_else(self, size): """Test that transpiled random circuits with if else blocks are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) if_block = random_circuit(3, 2, measure=True, seed=12342) else_block = random_circuit(2, 1, measure=True, seed=12342) rng = numpy.random.default_rng(seed=12342) inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits)) if inner_clbit_count > circuit.num_clbits: circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)]) clbit_indices = list(range(circuit.num_clbits)) rng.shuffle(clbit_indices) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits]) with else_: circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits]) tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) if __name__ == "__main__": unittest.main()
https://github.com/RyosukeNORO/Shor-s-algorithm
RyosukeNORO
from qiskit import * import numpy as np import math from qiskit.tools.visualization import plot_histogram %matplotlib inline N = 15 a = 13 math.gcd(a, N) def axmodN(a, x, n, N): if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") qc = QuantumCircuit(n) for j in range(x): if a in [2,13]: qc.swap(2, 3) qc.swap(1, 2) qc.swap(0, 1) if a in [7,8]: qc.swap(0, 1) qc.swap(1, 2) qc.swap(2, 3) if a in [11]: qc.swap(0, 2) qc.swap(1, 3) if a in [7,11,13]: for k in range(n): qc.x(k) qc = qc.to_gate() qc.name = "%i^%i mod %i" % (a, x, N) qc = qc.control(1) return qc def QFTdagger(n): qc = QuantumCircuit(n) # Swap the qubits for i in range(n//2): qc.swap(i, n-i-1) # Operation for i in range(n): for j in range(i): qc.cu1(-np.pi/(2**(i-j)), j, i) qc.h(i) qc.name = "QFTdagger" return qc n = 4 # number of qubits needed to represent number that will be done prime factorization qr = QuantumRegister(2*n) # Prepare 2*n quantum registers as |x>|w> = |x3 x2 x1 x0>|w3 w2 w1 w0> cr = ClassicalRegister(2*n) qc = QuantumCircuit(qr, cr) # Hadamard gates for i in range(n): qc.h(qr[i]) # |w> -> |1> qc.x(qr[n]) # Implement U_f (f(x) = a^x (mod N)) U_f|x>|w> = |x>|w+f(x)> ("+" represents "XOR") for i in range(n): qc.append(axmodN(a, 2**i, n, N), [i]+[n+i for i in range(n)]) qc.barrier() # Implement QFTdagger qc.append(QFTdagger(n), range(n)) qc.barrier() # Measure qc.measure(range(n), range(n)) # Show quantum circuit qc.draw(initial_state=True) simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots=2048).result() plot_histogram(result.get_counts())
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# # your code is here # prob_dict = dict() prob_6 = 1/(7+5+4+2+6+1) prob_5 = 6/(7+5+4+2+6+1) prob_4 = 2/(7+5+4+2+6+1) prob_3 = 4/(7+5+4+2+6+1) prob_2 = 5/(7+5+4+2+6+1) prob_1 = 7/(7+5+4+2+6+1) prob_dict['6'] = prob_6 prob_dict['5'] = prob_5 prob_dict['4'] = prob_4 prob_dict['3'] = prob_3 prob_dict['2'] = prob_2 prob_dict['1'] = prob_1 print(prob_dict) # # your solution is here # from random import randrange import numpy as np state1 = randrange(101) state2 = randrange(101) state3 = randrange(101) state4 = randrange(101) sum_states = state1 + state2 + state3 + state4 state_vector = list() state_vector.append(state1/sum_states) state_vector.append(state2/sum_states) state_vector.append(state3/sum_states) state_vector.append(state4/sum_states) print(state_vector) state_vector = np.array(state_vector) # state vector print("state vector: " + str(np.transpose(state_vector))) print("all state probs has to sum up to 1: " + str(np.sum(state_vector)))
https://github.com/bertolinocastro/quantum-computing-algorithms
bertolinocastro
# A Quantum Circuit to Construct All Maximal Cliques Using Grover’s Search Algorithm ## Chu Ryang Wie ### DOI: https://arxiv.org/abs/1711.06146v2 from sympy import * #import sympy.physics.quantum as qp # quantum physics from sympy.physics.quantum.qubit import * from sympy.physics.quantum import Dagger, TensorProduct from sympy.physics.quantum.gate import * from sympy.physics.quantum.qapply import * N = Symbol('N', integer=True) #N = 8 # base network G: # 1 <-> 2 <-> 3 # Nodes: 1, 2, 3 # Edges: (1,2), (2,3) # Adjacency matrix for network G A = Matrix([ [0, 1, 0], [1, 0, 1], [0, 1, 0] ]) # creating qubits for n=3 basis q = [Qubit(f'{dummy:03b}') for dummy in range(2**3)] q # creating psi state vector kpsi = 1/sqrt(N)*sum(q) bpsi = 1/sqrt(N)*Dagger(sum(q)) # TODO: create in terms of matrices the O operator perfectly as the circuit described in the paper O = Matrix([ [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0,-1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0,-1, 0], [0, 0, 0, 0, 0, 0, 0, 1], ]) # step: constructing the U operator basics using a network with n=3 # function to represent qubit as matrix: qubit_to_matrix() U = 2*kpsi*bpsi U = qubit_to_matrix(U)-Matrix.eye(2**3) Hm = Matrix([[1,1],[1,-1]]) Hc = 1/sqrt(2) H3 = Hc**3*kronecker_product(Hm,Hm,Hm) q000 = qubit_to_matrix(q[0]) Ualt = H3*(2*q000*Dagger(q000)-Matrix.eye(8))*H3 def G(kpsi): return matrix_to_qubit(U*O*qubit_to_matrix(kpsi)) # working with a network made by two nodes # n = 2 # Nodes: 0, 1 # Edges: (0,1) A = Matrix([ [0,1], [1,0] ]) # tentando reescrever as contas utilizando seno e cosseno theta = Symbol('theta') # creating psi state vector kpsi = sin(theta/2)*1/sqrt(1)*(Qubit(1,1)) + cos(theta/2)*1/sqrt(3)*(Qubit(0,0)+Qubit(0,1)+Qubit(1,0)) bpsi = sin(theta/2)*1/sqrt(1)*Dagger(Qubit(1,1)) + cos(theta/2)*1/sqrt(3)*Dagger(Qubit(0,0)+Qubit(0,1)+Qubit(1,0)) U = 2*kpsi*bpsi U = qubit_to_matrix(U)-Matrix.eye(2**2) O = Matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0,-1] ]) # Creating Oracle based on paper algorithm def O_operator(ket): pass # teste Matrix.eye(8) - 2 * qubit_to_matrix(Qubit(0,0,0)*Dagger(Qubit(0,0,0))) X = Matrix([ [0,1], [1,0] ]) X Z = Matrix([ [1,0], [0,-1] ]) Tp = TensorProduct X3 = Tp(Tp(Matrix.eye(2),Matrix.eye(2)),X) Z3 = Matrix([ [1,0,0,0,0,0,0,0], [0,-1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1], ]) X3*Z3*X3 a= H3*4/sqrt(2) p=sqrt(2)/4*a*Matrix([1,1,1,-1,1,1,-1,1]) sqrt(2)/4*a*Matrix([1,0,-1,0,0,-1,0,1]) X.as_matrix() Tp = TensorProduct XX = Tp(Tp(Matrix([[0,1],[1,0]]),Matrix([[0,1],[1,0]])),Matrix([[0,1],[1,0]])) Z3 = Matrix([ [1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,-1], ]) XX*Z3*XX XX*Z3 Z3*XX HH = Tp(Tp(Matrix([[1,1],[1,-1]]),Matrix([[1,1],[1,-1]])),Matrix([[1,1],[1,-1]])) HH HH*XX*HH CX = Matrix([ [1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0], ]) CX
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/kerenavnery/qmail
kerenavnery
import Protocols ALICE_ADDR = 'localhost' BOB_ADDR = 'localhost' ALICE_PORT = 5005 BOB_PORT = 5006 def main(): Protocols.receive_a_qmail(BOB_PORT, ALICE_ADDR, ALICE_PORT, adversary=False) pass if __name__ == "__main__": main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem from qiskit_nature.settings import settings settings.dict_aux_operators = True driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["VibrationalEnergy"] print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) # this is now done explicitly and already requires the basis problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianLogResult from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis from qiskit_nature.settings import settings settings.dict_aux_operators = True log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") hamiltonian = log_result.get_vibrational_energy() print(hamiltonian) hamiltonian.basis = HarmonicBasis([2, 2, 3, 4]) op = hamiltonian.second_q_ops()["VibrationalEnergy"] print("\n".join(str(op).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianLogResult from qiskit_nature.second_q.formats import watson_to_problem from qiskit_nature.second_q.problems import HarmonicBasis log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") watson = log_result.get_watson_hamiltonian() print(watson) basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = watson_to_problem(watson, basis) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("VibrationalEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.opflow import X, Z, I, Y H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) print("========== H2 Molecule Hamiltonian for Four Qubits ==========\n") print(H2_molecule_Hamiltonian_4_qubits.to_matrix())
https://github.com/neelkamath/quantum-experiments
neelkamath
import sys sys.path.append('../') from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\ sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\ sampleCircuitF from entanglement import Ent import warnings warnings.filterwarnings('ignore') labels = [ 'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3', 'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F' ] samplers = [ sampleCircuitA, sampleCircuitB1, sampleCircuitB2, sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE, sampleCircuitF ] q = 4 for layer in range(1, 4): print(f'qubtis: {q}') print('-' * 25) for (label, sampler) in zip(labels, samplers): expr = Ent(sampler, layer=layer, epoch=3000) print(f'{label}(layer={layer}): {expr}') print()
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ linear-depth n-qubit controlled X with ancilla """ import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import C3XGate, C4XGate from qiskit.circuit import Gate from qclib.gates.toffoli import Toffoli from qclib.gates.util import apply_ctrl_state # pylint: disable=protected-access class McxVchainDirty(Gate): """ Implementation based on lemma 8 of Iten et al. (2016) arXiv:1501.06911. Decomposition of a multicontrolled X gate with at least k <= ceil(n/2) ancilae for n as the total number of qubits in the system. It also includes optimizations using approximated Toffoli gates up to a diagonal. """ def __init__( self, num_controls: int, num_target_qubit=1, ctrl_state=None, relative_phase=False, action_only=False, ): """ Parameters ---------- num_target_qubit num_controls ctrl_state relative_phase action_only """ self.control_qubits = QuantumRegister(num_controls) self.target_qubits = QuantumRegister(num_target_qubit) self.ctrl_state = ctrl_state self.relative_phase = relative_phase self.action_only = action_only num_ancilla = 0 self.ancilla_qubits = [] if num_controls - 2 > 0: num_ancilla = num_controls - 2 self.ancilla_qubits = QuantumRegister(num_ancilla) super().__init__( "mcx_vc_dirty", num_controls + num_ancilla + 1, [], "mcx_vc_dirty" ) @staticmethod def toffoli_multi_target(num_targets, side=None): """ " """ size = 2 + num_targets circuit = QuantumCircuit(size) if side == "l": for i in range(num_targets - 1): circuit.name = 'toff_left' circuit.cx(size - i - 2, size - i - 1) circuit.ccx(0, 1, 2) return circuit elif side == "r": circuit.name = 'toff_right' circuit.ccx(0, 1, 2) for i in range(num_targets - 1): circuit.cx(i + 2, i + 3) return circuit elif side is None: circuit.name = 'toff_l_and_r' for i in range(num_targets - 1): circuit.cx(size - i - 2, size - i - 1) circuit.ccx(0, 1, 2) for i in range(num_targets - 1): circuit.cx(i + 2, i + 3) return circuit def _define(self): self.definition = QuantumCircuit( self.control_qubits, self.ancilla_qubits, self.target_qubits ) num_ctrl = len(self.control_qubits) num_target = len(self.target_qubits) num_ancilla = num_ctrl - 2 targets_aux = self.target_qubits[0:1] + self.ancilla_qubits[:num_ancilla][::-1] self._apply_ctrl_state() if num_ctrl == 2: self.definition.append( self.toffoli_multi_target(len(self.target_qubits)), [*self.control_qubits, *self.target_qubits], ) elif num_ctrl == 1: for k, _ in enumerate(self.target_qubits): self.definition.mcx( control_qubits=self.control_qubits, target_qubit=self.target_qubits[k], mode="noancilla", ) elif not self.relative_phase and num_ctrl == 3 and num_target < 2: for k, _ in enumerate(self.target_qubits): self.definition.append( C3XGate(), [*self.control_qubits[:], self.target_qubits[k]], [] ) else: side = 'l' for j in range(2): self._action_circuit(j, num_ancilla, num_ctrl, targets_aux, side) side = 'r' for i, _ in enumerate(self.ancilla_qubits[1:]): # reset part controls = [self.control_qubits[2 + i], self.ancilla_qubits[i]] self.definition.append( Toffoli(cancel="left"), [*controls, self.ancilla_qubits[i + 1]] ) if self.action_only: control_1 = self.control_qubits[-1] control_2 = self.ancilla_qubits[-1] targets = self.target_qubits num_targets = len(targets) self.definition.append( self.toffoli_multi_target(num_targets, side), [control_1, control_2, *targets], ) break self._apply_ctrl_state() def _action_circuit(self, j, num_ancilla, num_ctrl, targets_aux, side): for i, _ in enumerate(self.control_qubits): # action part if i < num_ctrl - 2: if ( targets_aux[i] not in self.target_qubits or self.relative_phase ): # gate cancelling controls = [ self.control_qubits[num_ctrl - i - 1], self.ancilla_qubits[num_ancilla - i - 1], ] # cancel rightmost gates of action part # with leftmost gates of reset part if ( self.relative_phase and targets_aux[i] in self.target_qubits and j == 1 ): self.definition.append( Toffoli(cancel="left"), [*controls, targets_aux[i]] ) else: self.definition.append( Toffoli(cancel="right"), [*controls, targets_aux[i]] ) else: control_1 = self.control_qubits[num_ctrl - i - 1] control_2 = self.ancilla_qubits[num_ancilla - i - 1] targets = self.target_qubits num_targets = len(targets) self.definition.append( self.toffoli_multi_target(num_targets, side), [control_1, control_2, *targets], ) else: controls = [ self.control_qubits[num_ctrl - i - 2], self.control_qubits[num_ctrl - i - 1], ] self.definition.append(Toffoli(), [*controls, targets_aux[i]]) break @staticmethod def mcx_vchain_dirty( circuit, controls=None, target=None, ctrl_state=None, relative_phase=False, action_only=False, ): """ Implementation based on lemma 8 of Iten et al. (2016) arXiv:1501.06911. Decomposition of a multicontrolled X gate with at least k <= ceil(n/2) ancilae for n as the total number of qubits in the system. It also includes optimizations using approximated Toffoli gates up to a diagonal. """ circuit.append( McxVchainDirty(len(controls), ctrl_state, relative_phase, action_only), [*controls, target], ) McxVchainDirty._apply_ctrl_state = apply_ctrl_state class LinearMcx(Gate): """ Implementation based on lemma 9 of Iten et al. (2016) arXiv:1501.06911. Decomposition of a multicontrolled X gate with a dirty ancilla by splitting it into two sequences of two alternating multicontrolled X gates on k1 = ceil((n+1)/2) and k2 = floor((n+1)/2) qubits. For n the total number of qubits in the system. Where it also reuses some optimizations available """ def __init__(self, num_controls, ctrl_state=None, action_only=False): self.action_only = action_only self.ctrl_state = ctrl_state num_qubits = num_controls + 2 self.control_qubits = list(range(num_qubits - 2)) self.target_qubit = (num_qubits - 2,) self.ancilla_qubit = num_qubits - 1 super().__init__("linear_mcx", num_controls + 2, [], "mcx") def _define(self): self.definition = QuantumCircuit(self.num_qubits) self._apply_ctrl_state() if self.num_qubits < 5: self.definition.mcx( control_qubits=self.control_qubits, target_qubit=self.target_qubit, mode="noancilla", ) elif self.num_qubits == 5: self.definition.append( C3XGate(), [*self.control_qubits[:], self.target_qubit], [] ) elif self.num_qubits == 6: self.definition.append( C4XGate(), [*self.control_qubits[:], self.target_qubit], [] ) elif self.num_qubits == 7: self.definition.append( C3XGate(), [*self.control_qubits[:3], self.ancilla_qubit], [] ) self.definition.append( C3XGate(), [*self.control_qubits[3:], self.ancilla_qubit, self.target_qubit], [], ) self.definition.append( C3XGate(), [*self.control_qubits[:3], self.ancilla_qubit], [] ) self.definition.append( C3XGate(), [*self.control_qubits[3:], self.ancilla_qubit, self.target_qubit], [], ) else: # split controls to halve the number of qubits used for each mcx num_ctrl = len(self.control_qubits) k_2 = int(np.ceil(self.num_qubits / 2.0)) k_1 = num_ctrl - k_2 + 1 first_gate = McxVchainDirty(k_1, relative_phase=True).definition second_gate = McxVchainDirty(k_2).definition self.definition.append( first_gate, self.control_qubits[:k_1] + self.control_qubits[k_1 : k_1 + k_1 - 2] + [self.ancilla_qubit], ) self.definition.append( second_gate, [*self.control_qubits[k_1:], self.ancilla_qubit] + self.control_qubits[k_1 - k_2 + 2 : k_1] + [self.target_qubit], ) self.definition.append( first_gate, self.control_qubits[:k_1] + self.control_qubits[k_1 : k_1 + k_1 - 2] + [self.ancilla_qubit], ) last_gate = McxVchainDirty(k_2, action_only=self.action_only).definition self.definition.append( last_gate, [*self.control_qubits[k_1:], self.ancilla_qubit] + self.control_qubits[k_1 - k_2 + 2 : k_1] + [self.target_qubit], ) self._apply_ctrl_state() @staticmethod def mcx(circuit, controls=None, target=None, ctrl_state=None, action_only=False): """ Implementation based on lemma 9 of Iten et al. (2016) arXiv:1501.06911. Decomposition of a multicontrolled X gate with a dirty ancilla by splitting it into two sequences of two alternating multicontrolled X gates on k1 = ceil((n+1)/2) and k2 = floor((n+1)/2) qubits. For n the total number of qubits in the system. Where it also reuses some optimizations available """ circuit.append( LinearMcx(len(controls), ctrl_state, action_only), [*controls, target] ) LinearMcx._apply_ctrl_state = apply_ctrl_state
https://github.com/ShabaniLab/q-camp
ShabaniLab
import numpy as np from qiskit import * print("successful!") # define quantum circuit N = 15 qc = QuantumCircuit(N, N) # add quantum gates qc.h(0) for i in range(N - 1): qc.cnot(i, i + 1) # add barrier qc.barrier(range(N)) # add measurement gauge/device qc.measure(range(N), range(N)) qc.draw('mpl') # run the circuit # get the backend backend = Aer.get_backend('qasm_simulator') # do the measurements/execution job = execute(qc, backend, shots=10000) # get result result = job.result() counts = result.get_counts() print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.qasm3 program = """ OPENQASM 3.0; include "stdgates.inc"; input float[64] a; qubit[3] q; bit[2] mid; bit[3] out; let aliased = q[0:1]; gate my_gate(a) c, t { gphase(a / 2); ry(a) c; cx c, t; } gate my_phase(a) c { ctrl @ inv @ gphase(a) c; } my_gate(a * 2) aliased[0], q[{1, 2}][0]; measure q[0] -> mid[0]; measure q[1] -> mid[1]; while (mid == "00") { reset q[0]; reset q[1]; my_gate(a) q[0], q[1]; my_phase(a - pi/2) q[1]; mid[0] = measure q[0]; mid[1] = measure q[1]; } if (mid[0]) { let inner_alias = q[{0, 1}]; reset inner_alias; } out = measure q; """ circuit = qiskit.qasm3.loads(program) circuit.draw("mpl")
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
import pennylane as qml from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer import tensorflow as tf import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from IPython.display import clear_output clear_output(wait=False) import os import tensorflow as tf data_train = pd.read_csv("dataset/classic_train.csv") X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values data_test = pd.read_csv("dataset/classic_test.csv") X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values (X_train.shape, y_train.shape),(X_test.shape, y_test.shape) dev = qml.device("default.qubit", wires=4) def block(weights, wires): qml.CNOT(wires=[wires[0],wires[1]]) qml.RY(weights[0], wires=wires[0]) qml.RY(weights[1], wires=wires[1]) n_wires = 4 n_block_wires = 2 n_params_block = 2 n_blocks = qml.MERA.get_n_blocks(range(n_wires),n_block_wires) n_blocks @qml.qnode(dev) def circuit(weights, x): #statepreparation(x) qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True) #for i in range(4): #qml.Hadamard(wires=i) #qml.RY(x[i], wires=i) #qml.Hadamard(wires=i) #qml.RX(x[i+4], wires=i) #qml.RX(x[i+8], wires=i) #qml.CNOT(wires=[0,1]) #qml.CNOT(wires=[1,2]) #qml.CNOT(wires=[2,3]) #qml.CNOT(wires=[3,0]) #qml.CNOT(wires=[4,0]) #qml.CNOT(wires=[0,1]) #qml.CNOT(wires=[1,2]) #qml.CNOT(wires=[2,3]) #qml.CNOT(wires=[3,0]) for w in weights: #layer_1(w[:13]) #layer_2(w[12:21]) #layer_2(w[16:24]) #layer_3(w[21:]) qml.MERA(range(n_wires),n_block_wires,block, n_params_block, w) #print(w) #print(x) return qml.expval(qml.PauliZ(1)) def variational_classifier(weights, bias, x): return circuit(weights, x) + bias def square_loss(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - p) ** 2 loss = loss / len(labels) return loss def accuracy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): if abs(l - p) < 1e-5: loss = loss + 1 loss = loss / len(labels) return loss def cost(weights, bias, X, Y): #print(1) predictions = [variational_classifier(weights, bias, x) for x in X] return square_loss(Y, predictions) np.random.seed(0) num_layers = 1 weights_init = 2*np.pi * np.random.randn(num_layers,n_blocks, n_params_block, requires_grad=True) bias_init = np.array(0.0, requires_grad=True) print(weights_init, bias_init) print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3])(weights_init,np.asarray(X_train[0]))) fig, ax = qml.draw_mpl(circuit)(weights_init,np.asarray(X_train[0])) fig.show() for i in weights_init: print(i[0]) y_train = np.where(y_train < 1, -1, y_train) y_test = np.where(y_test < 1, -1, y_test) from sklearn.utils import shuffle X,y = shuffle(X_train, y_train, random_state=0) from sklearn.model_selection import train_test_split opt = NesterovMomentumOptimizer(0.4) batch_size = 32 num_data = len(y_train) num_train = 0.9 # train the variational classifier weights = weights_init bias = bias_init print() cost_g = [] acc_train = [] acc_test = [] plt.show() for it in range(50): X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True) # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train_70), (batch_size,)) feats_train_batch = X_train_70[batch_index] Y_train_batch = y_train_70[batch_index] weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch) # Compute predictions on train and validation set predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70] predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30] # Compute accuracy on train and validation set acc_tra = accuracy(y_train_70, predictions_train) acc_val = accuracy(y_test_30, predictions_val) cost_train = cost(weights, bias,X_train, y_train) cost_g.append(cost_train) acc_train.append(acc_tra) acc_test.append(acc_val) clear_output(wait=True) plt.plot(cost_g,label='cost') plt.plot(acc_train,label='acc_train') plt.plot(acc_test,label='acc_test') plt.legend(['cost','acc_train','acc_test']) plt.show() print( "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " "".format(it + 1, cost_train, acc_tra, acc_val) ) print(weights) x_test = [] for x in X_test.tolist(): if sum(x) == 0: x[0]=1 x_test.append( x/ np.linalg.norm(x)) x_test[0] y_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test] y_test_pred = [] for i in y_pred: if i < 0: y_test_pred.append(-1) else: y_test_pred.append(1) from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.preprocessing import StandardScaler # demonstration of calculating metrics for a neural network model using sklearn from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import cohen_kappa_score from sklearn.metrics import roc_auc_score accuracy = accuracy_score(y_test, y_test_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_test, y_test_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_test, y_test_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_test, y_test_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_test, y_test_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_test, y_test_pred) print('ROC AUC: %f' % auc) # confusion matrix test_matrix = confusion_matrix(y_test, y_test_pred) print(test_matrix) ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show() y_pred_1 = [int(i) for i in y_test_pred ] y_pred_1 = ["{}\n".format(i) for i in y_pred_1] with open(r'mera_1_layers_classic_dataset.csv', 'w') as fp: fp.writelines(y_pred_1)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * circuito = QuantumCircuit(2,2) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) # Primeiramente o qiskit inicializa os qubits nos estados 0 e 1 circuito = QuantumCircuit(2,2) circuito.x(0) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) circuito.y(0) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) # No tutorial sobre as portas Rx, Ry e Rz vimos que usando a porta Ry para rotacionar o qubit em pi/2 conseguimos # o estado |+> import math circuito.ry(math.pi/2,1) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) # Agora aplicando a porta Z circuito.z(1) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) circuito.id(1) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector)
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
%load_ext autoreload %autoreload 2 #!pip install pennylane #improt pennylane dependnecies import pennylane as qml from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer # load the csv files import pandas as pd # plot the historical acc and cost import matplotlib.pyplot as plt import seaborn as sns from IPython.display import clear_output clear_output(wait=False) import os data_train = pd.read_csv("dataset/fair_train.csv") X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values data_test = pd.read_csv("dataset/classic_test.csv") X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values (X_train.shape, y_train.shape),(X_test.shape, y_test.shape) dev = qml.device("default.qubit", wires=4) def layer_1(W): qml.RY(W[0], wires=0) qml.RY(W[1], wires=1) qml.RY(W[2], wires=2) qml.RY(W[3], wires=3) qml.Hadamard(wires=0) qml.Hadamard(wires=1) qml.Hadamard(wires=2) qml.Hadamard(wires=3) qml.RZ(W[4], wires=0) qml.RZ(W[5], wires=1) qml.RZ(W[6], wires=2) qml.RZ(W[7], wires=3) qml.CNOT(wires=[1,0]) qml.RY(W[8], wires=1) qml.CNOT(wires=[2,0]) qml.RY(W[9], wires=2) qml.CNOT(wires=[3,0]) qml.RY(W[10], wires=3) qml.CNOT(wires=[2,1]) qml.RY(W[11], wires=2) qml.CNOT(wires=[3,1]) qml.RY(W[12], wires=3) # qml.Hadamard(wires=0) # qml.Hadamard(wires=1) # qml.Hadamard(wires=2) # qml.Hadamard(wires=3) #qml.CNOT(wires=[1,0]) #qml.CNOT(wires=[2,0]) #qml.CNOT(wires=[3,0]) def block(weights, wires): qml.CNOT(wires=[wires[0],wires[1]]) qml.RY(weights[0], wires=wires[0]) qml.RY(weights[1], wires=wires[1]) n_wires = 4 n_block_wires = 2 n_params_block = 2 n_blocks = qml.MPS.get_n_blocks(range(n_wires),n_block_wires) n_blocks @qml.qnode(dev) def circuit(weights, x): #statepreparation(x) qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True) #for i in range(4): #qml.Hadamard(wires=i) #qml.RY(x[i], wires=i) #qml.Hadamard(wires=i) #qml.RX(x[i+4], wires=i) #qml.RX(x[i+8], wires=i) #qml.CNOT(wires=[0,1]) #qml.CNOT(wires=[1,2]) #qml.CNOT(wires=[2,3]) #qml.CNOT(wires=[3,0]) #qml.CNOT(wires=[4,0]) #qml.CNOT(wires=[0,1]) #qml.CNOT(wires=[1,2]) #qml.CNOT(wires=[2,3]) #qml.CNOT(wires=[3,0]) for w in weights: #layer_1(w[:13]) #layer_2(w[12:21]) #layer_2(w[16:24]) #layer_3(w[21:]) qml.MPS(range(n_wires),n_block_wires,block, n_params_block, w) #print(w) #print(x) return qml.expval(qml.PauliZ(3)) def variational_classifier(weights, bias, x): return circuit(weights, x) + bias def square_loss(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - p) ** 2 loss = loss / len(labels) return loss def accuracy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): if abs(l - p) < 1e-5: loss = loss + 1 loss = loss / len(labels) return loss def cost(weights, bias, X, Y): #print(1) predictions = [variational_classifier(weights, bias, x) for x in X] return square_loss(Y, predictions) np.random.seed(0) num_layers = 4 weights_init = 2*np.pi * np.random.randn(num_layers,3, 2, requires_grad=True) bias_init = np.array(0.0, requires_grad=True) print(weights_init, bias_init) print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3,4,5,6,7])(weights_init,np.asarray(X_train[0]))) for i in weights_init: print(i[0]) y_train = np.where(y_train < 1, -1, y_train) y_test = np.where(y_test < 1, -1, y_test) from sklearn.utils import shuffle X,y = shuffle(X_train, y_train, random_state=0) from sklearn.model_selection import train_test_split opt = NesterovMomentumOptimizer(0.4) batch_size = 32 num_data = len(y_train) num_train = 0.9 # train the variational classifier weights = weights_init bias = bias_init print() cost_g = [] acc_train = [] acc_test = [] plt.show() for it in range(50): X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True) # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train_70), (batch_size,)) feats_train_batch = X_train_70[batch_index] Y_train_batch = y_train_70[batch_index] weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch) # Compute predictions on train and validation set predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70] predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30] # Compute accuracy on train and validation set acc_tra = accuracy(y_train_70, predictions_train) acc_val = accuracy(y_test_30, predictions_val) cost_train = cost(weights, bias,X_train, y_train) cost_g.append(cost_train) acc_train.append(acc_tra) acc_test.append(acc_val) clear_output(wait=True) plt.plot(cost_g,label='cost') plt.plot(acc_train,label='acc_train') plt.plot(acc_test,label='acc_test') plt.legend(['cost','acc_train','acc_test']) plt.show() print( "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " "".format(it + 1, cost_train, acc_tra, acc_val) ) print(weights) x_test = [] for x in X_test.tolist(): if sum(x) == 0: x[0]=1 x_test.append( x/ np.linalg.norm(x)) x_test[0] y_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test] y_test_pred = [] for i in y_pred: if i < 0: y_test_pred.append(-1) else: y_test_pred.append(1) from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.preprocessing import StandardScaler # demonstration of calculating metrics for a neural network model using sklearn from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import cohen_kappa_score from sklearn.metrics import roc_auc_score accuracy = accuracy_score(y_test, y_test_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_test, y_test_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_test, y_test_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_test, y_test_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_test, y_test_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_test, y_test_pred) print('ROC AUC: %f' % auc) # confusion matrix test_matrix = confusion_matrix(y_test, y_test_pred) print(test_matrix) ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show() y_pred_1 = [int(i) for i in y_pred ] y_pred_1 = ["{}\n".format(i) for i in y_pred_1] with open(r'mps_4_layers.csv', 'w') as fp: fp.writelines(y_pred_1)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state)
https://github.com/tuf65651/quantum-research
tuf65651
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * backend = Aer.get_backend("qasm_simulator") """implelement gates from arxiv.org quant-ph/0410184, A new quantum ripple-carry addition circuit""" def MAJ(circuit, a, b, out): """Put out bit into state that majority of a b and out were in""" circuit.cx(out, a) circuit.cx(out, b) circuit.ccx(a,b, out) def UMA(circuit, u, m, a): """UnMajority and Add""" circuit.x(m) circuit.cx(u,m) circuit.ccx(u,m,a) circuit.x(m) circuit.cx(a,u) circuit.cx(a,m) a = QuantumRegister(6, 'a') b = QuantumRegister(6, 'b') c = QuantumRegister(1, 'c') y = QuantumRegister(1, 'z') y = ClassicalRegister(4, 'y') qc = QuantumCircuit(m,n,c,y) MAJ(qc, m[0], n[1], c[0]) qc.draw()
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution() plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5)) plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5)) G labels = nx.get_edge_attributes(G,'weight') labels import json # Array of JSON Objects products = [{"name": "HDD", "brand": "Samsung", "price": "$100"}, {"name": "Monitor", "brand": "Dell", "price": "$120"}, {"name": "Mouse", "brand": "Logitech", "price": "$10"}] # Print the original data print("The original JSON data:\n{0}".format(products)) # Sort the JSON data based on the value of the brand key products.sort(key=lambda x: x["price"]) # Print the sorted JSON data print("The sorted JSON data based on the value of the brand:\n{0}".format(products)) _LAMBDA UNIFORM_CONVERGENCE_SAMPLE import json # Array of JSON Objects # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) # Print the sorted JSON data UNIFORM_CONVERGENCE_SAMPLE np.max(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - UNIFORM_CONVERGENCE_SAMPLE[220]["probabilities"]) # generamos las distancias entre para la convergencia uniforme index = -1 for sample in UNIFORM_CONVERGENCE_SAMPLE: mean = sample["mean"] index += 1 distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"])) UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state UNIFORM_CONVERGENCE_SAMPLE import csv header = ['iteration', 'state', 'probability', 'mean'] header_q = ['iteration', 'distance'] with open('qaoa_cu.csv', 'w', encoding='UTF8') as f: with open('qaoa_distance.csv', 'w', encoding='UTF8') as q: writer = csv.writer(f) writer_q = csv.writer(q) # write the header writer.writerow(header) writer_q.writerow(header_q) iteration = 0 for sample in UNIFORM_CONVERGENCE_SAMPLE: iteration += 1 mean = sample["mean"] distance = sample["distance_pgs"] state = 0 for probability in sample["probabilities"]: state += 1 # write the data data = [iteration, state, probability, mean] writer.writerow(data) writer_q.writerow([iteration, distance]) #plot_histogram(job_2, color='midnightblue', title=str(mean), figsize=(30, 5)).savefig(str(contador) + "_2.png") #print(sample["mean"]) plot_histogram(job_2, color='midnightblue', title="New Histogram", figsize=(30, 5)).savefig('out.png')
https://github.com/Muhi0709/Quantum-K-Means
Muhi0709
import numpy as np import math # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.quantum_info import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator from qiskit.extensions import Initialize from qiskit.providers.ibmq.managed import IBMQJobManager # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import matplotlib.pyplot as plt backend=provider.get_backend('ibmq_qasm_simulator') data=np.load("data.npy") print("No of datapoints:", data.shape[1]) print("Dimension:", data.shape[0]) def compute_mean(x,d,k): #helperfunction to compute cluster means(used in all the follwing subparts) l=[] for i in range(k): a=np.mean(x,axis=1,where=x[d-1]==i+1)[:d-1] a[np.isnan(a)]=0 #handling empty slice and true dvide warnings l.append(a) return np.array(l) def quant_clustering(data,n=400,k=4,max_iter=20): dim=data.shape[0] means=np.load("means.npy") done=False ite=0 z=list(np.random.choice([1,2,3,4],n)) error=[] X_clus=np.vstack((data,z)) dim_new=X_clus.shape[0] err= np.sum(np.linalg.norm(X_clus[:dim_new-1].transpose()-means[(X_clus[dim_new-1]-1).astype("int64")],axis=1)**2,axis=0) error.append(err) while (not done) and ite<=max_iter: done=True circ=[] for i in range(n): for j in range(k): circuit=QuantumCircuit(12,1) dt=np.hstack((data[:,i],np.zeros(2**9-len(data[:,i])))) mean=np.hstack((means[j],np.zeros(2**9-len(means[j])))) a_norm=(dt/np.linalg.norm(dt)) if np.linalg.norm(dt)!=0 else np.array([0]*2**9) b_norm=(mean/np.linalg.norm(mean)) if np.linalg.norm(mean)!=0 else np.array([0]*2**9) c=np.hstack((a_norm,b_norm))/ 2**0.5 c_norm=c/np.linalg.norm(c) circuit.initialize(c_norm,range(10)) Z=(np.linalg.norm(dt)**2 + np.linalg.norm(mean)**2) circuit.initialize([Z**(-0.5) * np.linalg.norm(dt),-Z**(-0.5) * np.linalg.norm(mean)],11) circuit.h(11) circuit.cswap(11,10,9) circuit.h(11) circuit.measure(11,0) circ.append(circuit) circ = transpile(circ, backend=backend) job_manager = IBMQJobManager() job = job_manager.run(circ, backend=backend,name="clustering_ite_{}".format(ite),shots=8192) result= job.results() prob=np.array([result.get_counts(i)["0"]/((result.get_counts(i)["0"] if "0" in result.get_counts(i) else 0) +(result.get_counts(i)["1"] if "1" in result.get_counts(i) else 0)) for i in range(n*k)]) distances=list(4*Z*abs(prob-0.5)) for i in range(n): candidate=np.argmin(distances[k*i:k*i+k])+1 if z[i]!=candidate: done=False z[i]=candidate err=0 for i in range(n): err+=(distances[4*i+(z[i]-1)]) error.append(err) means=compute_mean(np.vstack((data,z)),len(data)+1,k) ite+=1 if ite==20 and done==False: print("Not Converged") print("Final_value:", np.round(error[-1],2)) elif done==True: print("Convergence:", np.round(error[-1],2)) plt.plot(error) plt.grid(True) plt.xlabel("Iteration number") plt.ylabel("Objective function") plt.title("Quantum") plt.show() return z z1=quant_clustering(data) np.save("cluster1.npy",np.array(z1)) from collections import Counter def plot_result(z,title): plt.title(title) c=Counter(z).most_common() cx=[x for x,y in c] cy=[y for x,y in c] plt.xticks(np.arange(0,5,1)) plt.yticks(np.arange(0,100,5)) plt.grid(True) plt.xlabel("cluster number") plt.ylabel("count") plt.bar(cx,cy) plt.show() plot_result(z1[:100],"covid") plot_result(z1[100:200],"normal") plot_result(z1[200:300],"opacity") plot_result(z1[300:],"viral") cluster_stat=list(enumerate(z1)) cluster_stat.sort(key= lambda x: x[1]) cluster1=[] cluster2=[] cluster3=[] cluster4=[] a=[0]*4 b=[0]*4 c=[0]*4 d=[0]*4 for i,j in cluster_stat: if j==1: if i<100: a[0]+=1 elif i>=100 and i<200: a[1]+=1 elif i>=200 and i<300: a[2]+=1 else: a[3]+=1 if j==2: if i<100: b[0]+=1 elif i>=100 and i<200: b[1]+=1 elif i>=200 and i<300: b[2]+=1 else: b[3]+=1 if j==3: if i<100: c[0]+=1 elif i>=100 and i<200: c[1]+=1 elif i>=200 and i<300: c[2]+=1 else: c[3]+=1 if j==4: if i<100: d[0]+=1 elif i>=100 and i<200: d[1]+=1 elif i>=200 and i<300: d[2]+=1 else: d[3]+=1 def plot_result2(a,title): plt.title(title) plt.grid(True) plt.xticks(np.arange(0,5,1)) plt.yticks(np.arange(0,100,5)) plt.bar(range(4),a) plt.xlabel("type") plt.ylabel("count") plt.show() plot_result2(a,"cluster 1") plot_result2(b,"cluster 2") plot_result2(c,"cluster 3") plot_result2(d,"cluster 4") means=np.load("means.npy") circuit=QuantumCircuit(12,1) dt=np.hstack((data[:,0],np.zeros(2**9-len(data[:,0])))) mean=np.hstack((means[1],np.zeros(2**9-len(means[1])))) a_norm=(dt/np.linalg.norm(dt)) if np.linalg.norm(dt)!=0 else np.array([0]*2**9) b_norm=(mean/np.linalg.norm(mean)) if np.linalg.norm(mean)!=0 else np.array([0]*2**9) c=np.hstack((a_norm,b_norm))/ 2**0.5 c_norm=c/np.linalg.norm(c) circuit.initialize(c_norm,range(10)) Z=(np.linalg.norm(dt)**2 + np.linalg.norm(mean)**2) circuit.initialize([Z**(-0.5) * np.linalg.norm(dt),-Z**(-0.5) * np.linalg.norm(mean)],10) circuit.h(11) circuit.cswap(11,10,9) circuit.h(11) circuit.measure(11,0) circuit.draw("latex") circuit = transpile(circuit, backend=backend) job_manager = IBMQJobManager() job = job_manager.run([circuit], backend=backend,name="clustering_ite_{}".format(1),shots=8192) result=job.results()
https://github.com/UST-QuAntiL/qiskit-service
UST-QuAntiL
import qiskit def get_circuit(**kwargs): reg = qiskit.QuantumRegister(1, "q") circuit = qiskit.QuantumCircuit(reg) circuit.h(reg) circuit.measure_all() return circuit if __name__ == "__main__": c = get_circuit() print(c)
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
alpine-quantum-technologies
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Run various circuits on an offline simulator controlled by an AQTResource. This tests whether the circuit pre-conditioning and results formatting works as expected. """ import re import typing from collections import Counter from fractions import Fraction from math import pi from typing import List import numpy as np import pytest import qiskit from qiskit import ClassicalRegister, QiskitError, QuantumCircuit, QuantumRegister from qiskit.providers.jobstatus import JobStatus from qiskit.result import Counts from qiskit_aer import AerSimulator from qiskit_experiments.library import QuantumVolume from qiskit_aqt_provider.aqt_resource import AQTResource from qiskit_aqt_provider.test.circuits import qft_circuit from qiskit_aqt_provider.test.fixtures import MockSimulator from qiskit_aqt_provider.test.resources import TestResource from qiskit_aqt_provider.test.timeout import timeout @pytest.mark.parametrize("shots", [200]) def test_empty_circuit(shots: int, offline_simulator_no_noise: AQTResource) -> None: """Run an empty circuit.""" qc = QuantumCircuit(1) qc.measure_all() job = qiskit.execute(qc, offline_simulator_no_noise, shots=shots) assert job.result().get_counts() == {"0": shots} def test_circuit_success_lifecycle() -> None: """Go through the lifecycle of a successful single-circuit job. Check that the job status visits the states QUEUED, RUNNING, and DONE. """ backend = TestResource(min_queued_duration=0.5, min_running_duration=0.5) backend.options.update_options(query_period_seconds=0.1) qc = QuantumCircuit(1) qc.measure_all() job = qiskit.execute(qc, backend) assert job.status() is JobStatus.QUEUED with timeout(2.0): while job.status() is JobStatus.QUEUED: continue assert job.status() is JobStatus.RUNNING with timeout(2.0): while job.status() is JobStatus.RUNNING: continue assert job.status() is JobStatus.DONE def test_error_circuit() -> None: """Check that errors in circuits are reported in the `errors` field of the Qiskit result metadata, where the keys are the circuit job ids. """ backend = TestResource(always_error=True) backend.options.update_options(query_period_seconds=0.1) qc = QuantumCircuit(1) qc.measure_all() result = qiskit.execute(qc, backend).result() assert result.success is False assert backend.error_message == result._metadata["error"] def test_cancelled_circuit() -> None: """Check that cancelled jobs return success = false.""" backend = TestResource(always_cancel=True) qc = QuantumCircuit(1) qc.measure_all() result = qiskit.execute(qc, backend).result() assert result.success is False @pytest.mark.parametrize("shots", [1, 100, 200]) def test_simple_backend_run(shots: int, offline_simulator_no_noise: AQTResource) -> None: """Run a simple circuit with `backend.run`.""" qc = QuantumCircuit(1) qc.rx(pi, 0) qc.measure_all() trans_qc = qiskit.transpile(qc, offline_simulator_no_noise) job = offline_simulator_no_noise.run(trans_qc, shots=shots) assert job.result().get_counts() == {"1": shots} @pytest.mark.parametrize("shots", [1, 100]) def test_simple_backend_execute(shots: int, offline_simulator_no_noise: AQTResource) -> None: """Run two simple circuits with `qiskit.execute()`.""" qc0 = QuantumCircuit(2) qc0.rx(pi, 0) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.rx(pi, 1) qc1.measure_all() # qiskit.execute calls the transpiler automatically job = qiskit.execute([qc0, qc1], backend=offline_simulator_no_noise, shots=shots) assert job.result().get_counts() == [{"01": shots}, {"10": shots}] @pytest.mark.parametrize("backend", [MockSimulator(noisy=False), MockSimulator(noisy=True)]) def test_simple_backend_execute_noisy(backend: MockSimulator) -> None: """Execute a simple circuit on a noisy and noiseless backend. Check that the noisy backend is indeed noisy. """ qc = QuantumCircuit(1) qc.rx(pi, 0) qc.measure_all() # the single qubit error is around 0.1% so to see at least one error, we need to do more than # 1000 shots. total_shots = 4000 # take some margin shots = 200 # maximum shots per submission assert total_shots % shots == 0 counts: typing.Counter[str] = Counter() for _ in range(total_shots // shots): job = qiskit.execute(qc, backend=backend, shots=shots) counts += Counter(job.result().get_counts()) assert sum(counts.values()) == total_shots if backend.noisy: assert set(counts.keys()) == {"0", "1"} assert counts["0"] < 0.1 * counts["1"] # very crude else: assert set(counts.keys()) == {"1"} @pytest.mark.parametrize("shots", [100]) def test_ancilla_qubits_mapping(shots: int, offline_simulator_no_noise: AQTResource) -> None: """Run a circuit with two quantum registers, with only one mapped to the classical memory.""" qr = QuantumRegister(2) qr_aux = QuantumRegister(3) memory = ClassicalRegister(2) qc = QuantumCircuit(qr, qr_aux, memory) qc.rx(pi, qr[0]) qc.ry(pi, qr[1]) qc.rxx(pi / 2, qr_aux[0], qr_aux[1]) qc.measure(qr, memory) trans_qc = qiskit.transpile(qc, offline_simulator_no_noise) job = offline_simulator_no_noise.run(trans_qc, shots=shots) # only two bits in the counts dict because memory has two bits width assert job.result().get_counts() == {"11": shots} @pytest.mark.parametrize("shots", [100]) def test_multiple_classical_registers(shots: int, offline_simulator_no_noise: AQTResource) -> None: """Run a circuit with the final state mapped to multiple classical registers.""" qr = QuantumRegister(5) memory_a = ClassicalRegister(2) memory_b = ClassicalRegister(3) qc = QuantumCircuit(qr, memory_a, memory_b) qc.rx(pi, qr[0]) qc.rx(pi, qr[3]) qc.measure(qr[:2], memory_a) qc.measure(qr[2:], memory_b) trans_qc = qiskit.transpile(qc, offline_simulator_no_noise) job = offline_simulator_no_noise.run(trans_qc, shots=shots) # counts are returned as "memory_b memory_a", msb first assert job.result().get_counts() == {"010 01": shots} @pytest.mark.parametrize("shots", [123]) @pytest.mark.parametrize("memory_opt", [True, False]) def test_get_memory_simple( shots: int, memory_opt: bool, offline_simulator_no_noise: AQTResource ) -> None: """Check that the raw bitstrings can be accessed for each shot via the get_memory() method in Qiskit's Result. The memory is only accessible if the `memory` option is set. """ qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() result = qiskit.execute(qc, offline_simulator_no_noise, shots=shots, memory=memory_opt).result() if memory_opt: memory = result.get_memory() assert set(memory) == {"11", "00"} assert len(memory) == shots else: with pytest.raises(QiskitError, match=re.compile("no memory", re.IGNORECASE)): result.get_memory() @pytest.mark.parametrize("shots", [123]) def test_get_memory_ancilla_qubits(shots: int, offline_simulator_no_noise: AQTResource) -> None: """Check that the raw bistrings returned by get_memory() in Qiskit's Result only contain the mapped classical bits. """ qr = QuantumRegister(2) qr_aux = QuantumRegister(3) memory = ClassicalRegister(2) qc = QuantumCircuit(qr, qr_aux, memory) qc.rx(pi, qr[0]) qc.ry(pi, qr[1]) qc.rxx(pi / 2, qr_aux[0], qr_aux[1]) qc.measure(qr, memory) job = qiskit.execute(qc, offline_simulator_no_noise, shots=shots, memory=True) memory = job.result().get_memory() assert set(memory) == {"11"} assert len(memory) == shots @pytest.mark.parametrize("shots", [123]) def test_get_memory_bit_ordering(shots: int, offline_simulator_no_noise: AQTResource) -> None: """Check that the bitstrings returned by the results produced by AQT jobs have the same bit order as the Qiskit Aer simulators. """ sim = AerSimulator(method="statevector") qc = QuantumCircuit(3) qc.rx(pi, 0) qc.rx(pi, 1) qc.measure_all() aqt_memory = ( qiskit.execute(qc, offline_simulator_no_noise, shots=shots, memory=True) .result() .get_memory() ) sim_memory = qiskit.execute(qc, sim, shots=shots, memory=True).result().get_memory() assert set(sim_memory) == set(aqt_memory) # sanity check: bitstrings are no palindromes assert not any(bitstring == bitstring[::-1] for bitstring in sim_memory) @pytest.mark.parametrize(("shots", "qubits"), [(100, 5), (100, 8)]) def test_bell_states(shots: int, qubits: int, offline_simulator_no_noise: AQTResource) -> None: """Create a N qubits Bell state.""" qc = QuantumCircuit(qubits) qc.h(0) for qubit in range(1, qubits): qc.cx(0, qubit) qc.measure_all() job = qiskit.execute(qc, offline_simulator_no_noise, shots=shots) counts = job.result().get_counts() assert set(counts.keys()) == {"0" * qubits, "1" * qubits} assert sum(counts.values()) == shots @pytest.mark.parametrize(("shots", "qubits"), [(100, 3)]) def test_simulator_quantum_volume( shots: int, qubits: int, offline_simulator_no_noise: AQTResource ) -> None: """Run a qiskit_experiments.library.QuantumVolume job. Check that the noiseless simulator has at least quantum volume 2**qubits. """ experiment = QuantumVolume(list(range(qubits)), offline_simulator_no_noise, trials=100) experiment.set_transpile_options(optimization_level=0) experiment.set_run_options(shots=shots) job = experiment.run() result = job.analysis_results("quantum_volume") assert result.value == (1 << qubits) assert result.extra["success"] def test_period_finding_circuit(offline_simulator_no_noise: AQTResource) -> None: """Run a period-finding circuit for the function 13**x mod 15 on the offline simulator. Do 20 evaluations of the 2-shot procedure and collect results. Check that the correct period (4) is found often enough. """ # The function to find the period of def f(x: int) -> int: return pow(13, x, 15) def f_circuit(num_qubits: int) -> QuantumCircuit: """Quantum circuit for f(x) = 13^x mod 15.""" qr_x = QuantumRegister(num_qubits, "x") qr_fx = QuantumRegister(4, "f(x)") # 4 bits are enough to store any modulo 15 value qc = QuantumCircuit(qr_x, qr_fx) qc.x(qr_fx[0]) qc.x(qr_fx[2]) qc.x(qr_x[0]) qc.ccx(qr_x[0], qr_x[1], qr_fx[0]) qc.x(qr_x[0]) qc.ccx(qr_x[0], qr_x[1], qr_fx[1]) qc.x(qr_x[0]) qc.x(qr_x[1]) qc.ccx(qr_x[0], qr_x[1], qr_fx[2]) qc.x(qr_x[0]) qc.ccx(qr_x[0], qr_x[1], qr_fx[3]) qc.x(qr_x[1]) return qc # Period finding circuit num_qubits = 8 qr_x = QuantumRegister(num_qubits, "x") qr_fx = QuantumRegister(4, "f(x)") cr_x = ClassicalRegister(num_qubits, "c_x") qc = QuantumCircuit(qr_x, qr_fx, cr_x) # Hadamard gates for x register for qubit in range(num_qubits): qc.h(qr_x[qubit]) # Create f(x) and QFT subcircuits, and add them to qc qc_f = f_circuit(num_qubits) qc_qft = qft_circuit(num_qubits) gate_f = qc_f.to_gate(label="f(x)") gate_qft = qc_qft.to_gate(label="QFT") qc.append(gate_f, range(num_qubits + 4)) qc.append(gate_qft, range(num_qubits)) # Measure qubits in x register qc.measure(qr_x, cr_x) def iteration() -> Counts: result = qiskit.execute(qc, offline_simulator_no_noise, shots=2).result() return result.get_counts() n_attempts = 20 results: List[bool] = [] # run the circuits (2 shots) n_attempts times # and do the classical post-processing to extract the period of the function f. for _ in range(n_attempts): try: x1, x2 = iteration().int_outcomes().keys() except ValueError: # identical results, skip continue m = num_qubits // 2 k1 = Fraction(x1, 2**num_qubits).limit_denominator(2**m - 1) k2 = Fraction(x2, 2**num_qubits).limit_denominator(2**m - 1) b1 = k1.denominator b2 = k2.denominator r = int(np.lcm(b1, b2)) results.append(f(r) == f(0)) # more than 50% of the attempts were successful assert len(results) > n_attempts * 0.5 # got the right result more than 50% of the successful attempts # this is quite loose, but doing more iterations would be annoyingly long on CI assert np.count_nonzero(results) > len(results) * 0.5
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
""" Import all required libraries. """ from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union # import the params object of the GlobalParameters class # this provides the parameters used to desribed and model # the problem the minimizer is supposed to use. from GlobalParameters import params """ This program provides an implementation of the Variational Quantum Linear Solver as presented by Bravo-Prieto et al. It is implemented for the QISKIT Quantum SDK. This version of the program uses the local cost function. Author: Alexander Cornelius Muehlhausen ######################################################################### ######### Core functions The core functions of the VQLS algorithm. """ def generate_ansatz(alpha: List[float]) -> QuantumCircuit: """ This function returns a circuit that implements the Ansatz V(alpha). """ qr_ansatz = QuantumRegister(params.n_qubits) circ_ansatz = QuantumCircuit(qr_ansatz) if not any(isinstance(item, list) for item in alpha): # this will reformat the list alpha to the required format (if needed) # this is necessary as the minimizer returns a list without sublists alpha = _format_alpha(alpha) # 0th sublayer for qubit in range(0, params.n_qubits): circ_ansatz.ry(alpha[0][qubit], qr_ansatz[qubit]) if params.n_qubits % 2 == 0: # all other sublayers for sublayer in range(1, 2 * params.n_layers, 2): # first sublayer of the current layer # controlled Z-Gate pairs for qubit_a, qubit_b in zip(qr_ansatz[::2], qr_ansatz[1::2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer], qr_ansatz): circ_ansatz.ry(rotation_param, qubit) # second sublayer of the current layer for qubit_a, qubit_b in zip(qr_ansatz[1::2], qr_ansatz[2::2]): circ_ansatz.cz(qubit_a, qubit_b) # and Ry to each qubit except the first and last one for rotation_param, qubit in zip(alpha[sublayer+1], qr_ansatz[1::]): circ_ansatz.ry(rotation_param, qubit) else: # all other sublayers for sublayer in range(1, 2 * params.n_layers, 2): # first sublayer of the current layer for qubit_a, qubit_b in zip(qr_ansatz[:params.n_qubits-1:2], qr_ansatz[1:params.n_qubits-1:2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer], qr_ansatz[:params.n_qubits-1:]): circ_ansatz.ry(rotation_param, qubit) # second sublayer for qubit_a, qubit_b in zip(qr_ansatz[1::2], qr_ansatz[2::2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer+1], qr_ansatz[1::]): circ_ansatz.ry(rotation_param, qubit) return circ_ansatz def hadamard_test( *, ansatz: Union[Gate, Operator] = None, first: Union[Gate, Operator] = None, first_uncontrolled: Union[Gate, Operator] = None, j: int = None, second_uncontrolled: Union[Gate, Operator] = None, second: Union[Gate, Operator] = None, im=None ): """ This function returns a circuit that implements the Hadamard Test. The ancilliary qubit is the last qubit; a measurement is applied to it. """ # prep of QuantumCircuit qr_had = QuantumRegister(params.n_qubits) circ_had = QuantumCircuit(qr_had) ancilla = QuantumRegister(1, name="ancilla") cr_had = ClassicalRegister(1) circ_had.add_register(ancilla) circ_had.add_register(cr_had) qubits_designation_control = [i for i in range(params.n_qubits)] qubits_designation_control.insert(0, params.n_qubits) def append_ifExists(obj: Union[Gate, Operator], control=False): """ Append gates to a circuit. Convert them to instructions if necessary. Control them if necessary. """ if isinstance(obj, (Gate, Operator)): _obj = obj.copy() if isinstance(_obj, Operator): _obj = _obj.to_instruction() if control is True: _obj = _obj.control(1) circ_had.append(_obj, qubits_designation_control) else: circ_had.append(_obj, qr_had) # act on the ancilla circ_had.h(ancilla) # if Im(<>) shall be calculated if im is not None: circ_had.sdg(ancilla) append_ifExists(ansatz) # clean up the circuit circ_had.barrier() # use this for $A_l$ append_ifExists(first, True) # use this for $U^{\dagger} append_ifExists(first_uncontrolled) # $Z_j$ if j is not None: circ_had.cz(params.n_qubits, qr_had[j]) # use this for $U$ append_ifExists(second_uncontrolled) # use this for $A^{\dagger}_m$ append_ifExists(second, True) # clean up the circuit circ_had.barrier() # last operation on the ancilla & measurement circ_had.h(ancilla) circ_had.measure(ancilla, cr_had) return circ_had def calculate_beta(alpha: List[float]) -> List[List[complex]]: """ This function calculates all parameters $\beta_{lm}$ that are required, i.e. all parameters with l, m so that $c_l$ and $c^{*}_m$ are not equal to 0. """ # preparation of the result list beta = [[complex(0, 0) for _ in params.coefficients] for _ in params.coefficients_conjugate] # generate Ansatz outside the loops for better performance V = generate_ansatz(alpha).to_gate() # $A^{\dagger}_m, (m, c^{*}_m)$ for gate_l, (l, coeff_l) in zip(params.decomposition_asGate, enumerate(params.coefficients)): if coeff_l == 0: continue # increase perfomance by ommiting unused $\beta$ # $A^{\dagger}_m, (m, c^{*}_m)$ for gate_m_adj, (m, coeff_m) in zip(params.decomposition_adjoint_asOperator, enumerate(params.coefficients_conjugate)): if coeff_m == 0: continue # increase perfomance by ommiting unused $\beta$ # circuit for Re ( <0| V(alpha)(+) A_m(+) A_l V(alpha) |0>) circ_had_re = hadamard_test(ansatz=V, first=gate_l, second=gate_m_adj) # circ_had_re.draw(output='mpl') # circuit for Im ( <0| V(alpha)(+) A_m(+) A_l V(alpha) |0>) circ_had_im = hadamard_test(ansatz=V, first=gate_l, second=gate_m_adj, im=1) # calculate Re and Im of $\beta_{lm}$ / simulate circuits expV_had_re = _calculate_expectationValue_HadamardTest(circ_had_re) expV_had_im = _calculate_expectationValue_HadamardTest(circ_had_im) # set together $\beta_{lm}$ from its real and imaginary part expV_had = complex(expV_had_re, expV_had_im) beta[l][m] = expV_had return beta def calculate_delta(alpha: List[float], beta: List[List[complex]]) -> List[List[complex]]: """ This function calculates all $\delta_{lm}$ that are required, i.e. all parameters with l, m so that $c_l$ and $c^{*}_m$ are not equal to 0. """ # initialize the list for the results delta = [[complex(0, 0) for _ in params.coefficients] for _ in params.coefficients_conjugate] # prepare $V(\vec{alpha})$, $U$ and $U^{\dagger}$ V = generate_ansatz(alpha).to_gate() U = _U_primitive().to_gate() U_dagger = U.copy() U_dagger = Operator(U_dagger) U_dagger = U_dagger.adjoint() # $A_l, (l, c_l)$ for gate_l, (l, coeff_l) in zip(params.decomposition_asGate, enumerate(params.coefficients)): if coeff_l == 0: continue # increase perfomance by ommiting unused $\delta$ # $A^{\dagger}_m, (m, c^{*}_m)$ for gate_m_adj, (m, coeff_m) in zip( params.decomposition_adjoint_asOperator, enumerate(params.coefficients_conjugate) ): if coeff_m == 0: continue # increase perfomance by ommiting unused $\delta$ temp = beta[l][m] # 1/n_qubits sum_j <0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0> for j in range(params.n_qubits): # Re(<0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>) circ_had_re = hadamard_test( ansatz=V, first=gate_l, first_uncontrolled=U_dagger, j=j, second_uncontrolled=U, second=gate_m_adj) # Im(<0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>) circ_had_im = hadamard_test( ansatz=V, first=gate_l, first_uncontrolled=U_dagger, j=j, second_uncontrolled=U, second=gate_m_adj, im=1) # calculate Re and Im of $\delta_{lm}$ / simulate circuits expV_had_re = _calculate_expectationValue_HadamardTest(circ_had_re) expV_had_im = _calculate_expectationValue_HadamardTest(circ_had_im) # set together $\delta_{lm}$ from its real and imaginary part # and execute the summation expV_had = complex(expV_had_re, expV_had_im) temp += 1/params.n_qubits * expV_had delta[l][m] = temp return delta def calculate_local_cost_function(alpha: List[float]) -> Union[complex, float]: """ returns cost = <x| H_local |x> / <psi|psi> with <x| H_local |x> = Sum_l_m c_l c_m(*) delta <psi|psi> = Sum_l_m c_l c_m(*) beta """ beta = calculate_beta(alpha) delta = calculate_delta(alpha, beta) xHx = 0 psipsi = 0 for l, coeff_l in enumerate(params.coefficients): for m, coeff_m_conj in enumerate(params.coefficients_conjugate): xHx += coeff_l * coeff_m_conj * delta[l][m] psipsi += coeff_l * coeff_m_conj * beta[l][m] # cost = xHx / psipsi cost = abs(xHx/psipsi) print(alpha) print("local cost function " + str(cost)) return cost def minimize_local_cost_function(method: str) -> List[float]: """ This function minimizes the local cost function. It returns the alpha for which the approximation A V(alpha_out) |0> approx |b> is optimal. Implements scipy.optimize.minimize . It provides several methods to minimize the cost function: Locally using scipy.optimize.minimize Basinhopping Differential evolution SHGO dual annealing """ # accepted methods for the minimizer # those deliver decent results, but COBYLA was favored minimization_methods = ["COBYLA", "Nelder-Mead", "Powell"] """ # some methods for the minimizer that were tested but failed to # deliver decent results minimization_methods_unsatisfactory = [ "CG", "BFGS", "L-BFGS-B", "TNC", "SLSQP", "trust-constr" ] """ # use minimize and the methods to find a local minimum if method in minimization_methods: min = minimize(calculate_local_cost_function, x0=params.alpha_0, method=method, options={'maxiter': params.COBYLA_maxiter}) # use basinhopping to find the global minimum # another decent minimiziation approach elif method == "basinhopping": min = basinhopping(calculate_local_cost_function, x0=params.alpha_0, niter=params.COBYLA_maxiter, minimizer_kwargs = {'method': "COBYLA"}) else: print("No valid method for the minimization was given!") return 0 print(min) alpha_out = min['x'] print(alpha_out) return alpha_out """ Fix the result. """ def postCorrection(qc: QuantumCircuit) -> QuantumCircuit: """ This function is used to apply post correction to the circuit generated by applying V(alpha) and A as the result is not identical to |b>. The result of a circuit built using the functions presented above returns the reverse of b with random sign errors. """ for i in range(params.n_qubits): qc.x(i) qc.z(i) return qc """ ######### Helper functions Functions that do not add to the logic of the algorithm but instead implement often used features or need to be changed sometimes. """ def _format_alpha(alpha_unformated: List[float]) -> List[List[float]]: """ This function formats a list to be in the correct form for the function that builds V(alpha). This means it will format the list to be of the form: [[0th sublayer], [1st sublayer], [2nd sublayer], ...] So for e.g. 4 qubits it will return (- stands for some random value): [[-,-,-,-],[-,-,-,-],[-,-],[-,-,-,-],[-,-]] and for e.g. 3 qubits: [[-,-],[-,-],[-,-],[-,-],[-,-]] """ alpha_formated = [] if any(isinstance(item, list) for item in alpha_unformated): return alpha_unformated else: if (params.n_qubits % 2) == 0: start = 0 end = params.n_qubits alpha_formated.append(alpha_unformated[start:params.n_qubits]) for _ in range(params.n_layers): start = end end = start + params.n_qubits alpha_formated.append(alpha_unformated[start:end]) start = end end = start + params.n_qubits - 2 alpha_formated.append(alpha_unformated[start:end]) else: start = 0 end = params.n_qubits alpha_formated.append(alpha_unformated[start:end]) for _ in range(params.n_layers): start = end end = start + params.n_qubits-1 alpha_formated.append(alpha_unformated[start:end]) start = end end = start + params.n_qubits - 1 alpha_formated.append(alpha_unformated[start:end]) return alpha_formated def _calculate_expectationValue_HadamardTest(circ_had: QuantumCircuit) -> float: """ Will return the expectation value for a given circuit for a Hadamard test. Supports different backends. Code snippets and best practices taken from Qiskit tutorials and documentation, e.g. https://qiskit.org/textbook/ch-paper-implementations/vqls.html . """ if params.qiskit_simulation_backend == 'statevector_simulator': backend = Aer.get_backend('statevector_simulator') t_circ = transpile(circ_had, backend) qobj = assemble(t_circ) p_0 = 0 p_1 = 0 for _ in range(params.qiskit_simulation_shots): job = backend.run(qobj) result = job.result() counts = result.get_counts(circ_had) p_0 += counts.get('0', 0) p_1 += counts.get('1', 0) return ((p_0 - p_1) / params.qiskit_simulation_shots) if params.qiskit_simulation_backend == 'qasm_simulator': backend = Aer.get_backend('qasm_simulator') job = execute(circ_had, backend, shots=params.qiskit_simulation_shots) result = job.result() counts = result.get_counts(circ_had) number = counts.get('1', 0) + counts.get('0', 0) p_0 = counts.get('0', 0)/number p_1 = counts.get('1', 0)/number return (p_0 - p_1) def _U_primitive() -> QuantumCircuit: """ This function generates a circuit that resembles a U gate that fulfills: U |0> = |b> . This is primitive because this circuit calculates / defines |b> as: |b> = U |0> = A H(0, 3) |0> """ qr_U_primitive = QuantumRegister(params.n_qubits) circ_U_primitive = QuantumCircuit(qr_U_primitive) """ for i in range(n_qubits): circ_U_primitive.h(i) """ circ_U_primitive.h(0) # optional # circ_U_primitive.h(1) # circ_U_primitive.h(1) # circ_U_primitive.h(2) circ_U_primitive.h(3) A_copy = params.A.copy() if isinstance(params.A, Operator): A_copy = A_copy.to_instruction() circ_U_primitive.append(A_copy, qr_U_primitive) return circ_U_primitive
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/ohadlev77/sat-circuits-engine
ohadlev77
# Copyright 2022-2023 Ohad Lev. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0, # or in the root directory of this package("LICENSE.txt"). # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Global constants and settings. """ from qiskit.providers.backend import Backend from qiskit import IBMQ from qiskit_aer import AerSimulator def BACKENDS(index: int) -> Backend: """ Returns a backend object according to `index`. This "constants" are assembled as a function in order to avoid errors that may raise from an `IBMQ.load_account()` command if an IBMQ API token isn't saved on the machine. Raises: (ValueError) - if the index entered isn't associated with a backend. """ if index == 0: return AerSimulator() if index == 1: provider = IBMQ.load_account() return provider.get_backend("ibmq_qasm_simulator") raise ValueError(f"No backends are defined for index {index}.") # Paths constants CONSTRAINTS_FORMAT_PATH = "sat_circuits_engine/data/constraints_format.md" DATA_PATH = "sat_circuits_engine/data/generated_data/" TEST_DATA_PATH = "sat_circuits_engine/data/test_data.json" # Default kwargs for Qiskit's transpile TRANSPILE_KWARGS = {"basis_gates": ["u", "cx"], "optimization_level": 3}
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='my token') provider.backends() from qiskit import QuantumCircuit, QuantumRegister from math import pi qr = QuantumRegister(6,'q') qc_par = QuantumCircuit(qr) for i in range(3): qc_par.rxx(pi/2,i,i+3) qc_par.draw() qr = QuantumRegister(6,'q') qc_star = QuantumCircuit(qr) for i in range(1,6): qc_star.rxx(pi/2,0,i) qc_star.draw() from qiskit import ClassicalRegister # Add the measurement register circs = [qc_par,qc_star] cr = ClassicalRegister(6,'c') for qc in circs: qc.add_register(cr) qc.measure(range(6),range(6)) from qiskit.providers.jobstatus import JobStatus from qiskit import Aer, execute # Choose the simulator backend backend = provider.get_backend("ionq_simulator") #backend = Aer.get_backend("qasm_simulator") # Run the circuit: def run_jobs(backend,circs,nshots): jobs = [] job_ids = [] qcs = [] for qc in circs: qcs.append(qc) job = backend.run(qc, shots=nshots) #job = execute(qc, backend, shots=nshots, memory=True) jobs.append(job) #job_ids.append(job.job_id()) return jobs jobs = run_jobs(backend,circs,1000) # Calculate output state populations def get_pops(res,nn,n): #print(res) pops = [0 for i in range(2**nn)] for key in res.keys(): pops[int(key,16)] = res[key]/n #pops[int(key,2)] = res[key]/n return pops # Fetch the result def get_jobs(jobs,nshots): results = [] for i in range(len(jobs)): result = jobs[i].result() print(result.data()['counts']) print(get_pops(result.data()['counts'],6,nshots)) results.append(get_pops(result.data()['counts'],6,nshots)) return results results = get_jobs(jobs,1000) def get_ion(res,ion): p1 = 0 for x in range(2**6): if (x&(2**ion)): p1 += res[x] return p1 def get_pair(res,pair): p00 = 0 p01 = 0 p10 = 0 p11 = 0 for x in range(2**6): if (x&(2**pair[0])>0) and (x&(2**pair[1])>0): p11 += res[x] elif (x&(2**pair[0])>0) and (x&(2**pair[1])==0): p01 += res[x] elif (x&(2**pair[1])>0) and (x&(2**pair[0])==0): p10 += res[x] elif (x&(2**pair[0])==0) and (x&(2**pair[1])==0): p00 += res[x] return [p00,p01,p10,p11] prsq = [get_pair(results[0],[i,i+3]) for i in range(3)] prbi = [get_ion(results[1],i) for i in range(6)] print(prbi) print(prsq) import matplotlib.pyplot as plt for i in range(3): plt.bar([x-0.3+0.3*i for x in range(4)],prsq[i],width=0.3,label="Pair "+str(i)+"-"+str(i+3)) plt.ylim([0,1]) plt.xticks(range(4), [bin(x)[2:].zfill(2) for x in range(4)],rotation=30) plt.ylabel("Output probability") plt.xlabel("Output state") plt.legend() plt.bar(range(6),prbi) plt.ylim([0,1]) plt.ylabel("State |1> probability") plt.xlabel("Qubit") # Switch the backend to run circuits on a quantum computer qpu_backend = provider.get_backend("ionq_qpu") jobs = run_jobs(qpu_backend,circs,1000) #Check if jobs are done for i in range(len(jobs)): print(jobs[i].status()) # Fetch the result results = get_jobs(jobs,1000) prsq_m = [get_pair(results[0],[i,i+3]) for i in range(3)] prbi_m = [get_ion(results[1],i) for i in range(6)] for i in range(3): plt.bar([x-0.3+0.3*i for x in range(4)],prsq_m[i],width=0.3,label="Pair "+str(i)+"-"+str(i+3)) plt.ylim([0,1]) plt.xticks(range(4), [bin(x)[2:].zfill(2) for x in range(4)],rotation=30) plt.ylabel("Output probability") plt.xlabel("Output state") plt.legend() plt.bar(range(6),prbi_m) plt.ylim([0,1]) plt.ylabel("State |1> probability") plt.xlabel("Qubit")
https://github.com/arnaucasau/Quantum-Computing-3SAT
arnaucasau
# imports import math # importing Qiskit from qiskit import QuantumCircuit, Aer, assemble, transpile from qiskit.visualization import plot_histogram f = open("cnf_test1.txt") info = f.readline().split(' ') literals = int(info[0]) clausulas = int(info[1]) lines = [line.rstrip('\n') for line in f] formula = [] for i in lines: l = i.split(' ') formula.append([int(l[0]),int(l[1]),int(l[2])]) n = literals + clausulas + 2 # Number of qubits in the circuit def initialize_grover(qc, qubits): # Superposition for i in range(literals+1): qc.h(qubits[i]) # State |-⟩ qc.x(n-1) qc.h(n-1) return qc qc = QuantumCircuit(n) # Creation of each clause. contador = 0 for c in formula: for i in range(3): if c[i] > 0: qc.x(abs(c[i])-1) qc.mct(list([abs(c[0])-1,abs(c[1])-1,abs(c[2])-1]), literals+1+contador) # multi-controlled-toffoli for i in range(3): if c[2-i] > 0: qc.x(abs(c[2-i])-1) contador+=1 # Checking of each clause qc.x(literals) # Augmented space for q in range(literals+1,n-1): qc.x(q) qc.mct(list(list([literals, *range(literals+1,n-1)])), n-1) for q in range(literals+1,n-1): qc.x(q) qc.x(literals) # Augmented space # Creation of each clause (symmetry). contador -= 1 for c in reversed(formula): for i in range(3): if c[i] > 0: qc.x(abs(c[i])-1) qc.mct(list([abs(c[0])-1,abs(c[1])-1,abs(c[2])-1]), literals+1+contador) for i in range(3): if c[2-i] > 0: qc.x(abs(c[2-i])-1) contador-=1 oracle = qc.to_gate() oracle.name = "Oracle" qc.draw() qc = QuantumCircuit(n) for qubit in range(literals+1): qc.h(qubit) for qubit in range(literals+1): qc.x(qubit) # Equivalent Diffuser. It gives us the opposite result in Quantum counting, therefore M will be the number of no solutions at the end. qc.mct(list([i for i in range(literals+1)]), n-1) ########## Original Diffuser ############################################################## #qc.mct(list([i for i in range(literals+1)]), literals+1) #qc.x(literals+1) #qc.cx(literals+1,n-1) #qc.x(literals+1) #qc.mct(list([i for i in range(literals+1)]), literals+1) ########################################################################################### for qubit in range(literals+1): qc.x(qubit) for qubit in range(literals+1): qc.h(qubit) inversionMean = qc.to_gate() inversionMean.name = "inversionMean" qc.draw() grover_iteration = QuantumCircuit(n) grover_iteration.append(oracle, list(range(n))) grover_iteration.append(inversionMean, list(range(n))) gi = grover_iteration.to_gate() gi.label = "GroverI" cgi = gi.control() def qft(n): circuit = QuantumCircuit(n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft_rotations(circuit, n): #Performs qft on the first n qubits in circuit (without swaps) if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(math.pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) # Comment this line if we use the 2 possible order of the QPE registers return circuit t = literals+1 # Number of counting qubits. qft_dagger = qft(t).to_gate().inverse() qft_dagger.label = "QFT†" qpe = QuantumCircuit(n+t, t) # Circuit with n+t qubits and t classical bits # Superposition for qubit in range(t+literals+1): qpe.h(qubit) # State |-⟩ qpe.x(n+t-1) qpe.h(n+t-1) # Grover iterations iterations = 1 for qubit in range(t): for i in range(iterations): qpe.append(cgi, [qubit] + [*range(t, n+t)]) # Using this line, uncomment the QFT swap. #qpe.append(cgrit, [(t-1)-qubit] + [*range(t, n+t)]) # Using this line, comment the QFT swap. iterations *= 2 # Application of QFT inverse to all counting qubits qpe.append(qft_dagger, range(t)) # Measure the counting qubits qpe.measure(range(t), range(t)) qpe.draw() # Quantum counting sinulation aer_sim = Aer.get_backend('aer_simulator') transpiled_qpe = transpile(qpe, aer_sim) qobj = assemble(transpiled_qpe) job = aer_sim.run(qobj) hist = job.result().get_counts() plot_histogram(hist) measured_str = max(hist, key=hist.get) measured_int = int(measured_str,2) print(measured_str) print("Register Output = %i" % measured_int) theta = (measured_int/(2**t))*math.pi*2 print("Theta = %.5f" % theta) N = 2**(literals+1) M = N * (math.sin(theta/2)**2) M = N-M # Diffuser faster only print(N,M) print("No. of Solutions = %.1f" % M) # Upper bound error for the number of solutions m = t - 1 err = (math.sqrt(2*M*N) + N/(2**(m+1)))*(2**(-m)) print("Error < %.2f" % err) rounds = math.pi/4.0*math.sqrt(N/M) print("Result:",rounds) print("Iterations R ≤",math.ceil(rounds)) if math.floor(rounds) == 0: rounds = round(rounds) else: rounds = math.floor(rounds) print("Iterations chosen:", rounds) grover_circuit = QuantumCircuit(n,literals+1) grover_circuit = initialize_grover(grover_circuit, list(range(n))) for i in range(rounds): grover_circuit.append(oracle, list(range(n))) grover_circuit.append(inversionMean, list(range(n))) for i in range(literals+1): grover_circuit.measure([i],[i]) grover_circuit.draw() # Grover's algorithm simulation aer_sim = Aer.get_backend('aer_simulator') transpiled_grover_circuit = transpile(grover_circuit, aer_sim) qobj = assemble(transpiled_grover_circuit) results = aer_sim.run(qobj, shots=1024).result() counts = results.get_counts() print("\nTotal count:",counts) plot_histogram(counts,figsize=(12,5))
https://github.com/ankitkmisra/Quantum-Computing-and-Cryptography
ankitkmisra
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import numpy as np import qiskit.quantum_info as qi # Loading your IBM Q account(s) provider = IBMQ.load_account() #This cell is just for seeing what the U tilde matrix looks like a, b, c, d = np.cos(np.pi/8), np.sin(np.pi/8), -np.sin(np.pi/8), np.cos(np.pi/8) u_tilde = np.array([[a,c],[b,d]]).reshape(2,2) print(u_tilde) #This cell defines the controlled variant of the U tilde matrix qc_for_u = QuantumCircuit(1) qc_for_u.ry(np.pi/4, 0) qc_for_u.name = "U" controlled_u_tilde = qc_for_u.to_gate().control(2) qc1 = QuantumCircuit(3) qc1.x(0) qc1.x(1) qc1.toffoli(0,1,2)#Flipping the third bit if the first two are zero qc1.x(0) #Essentially 000 -> 001 qc1.x(1) qc1.x(0) qc1.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one qc1.x(0) #Essentially 001 -> 011 qc1.append(controlled_u_tilde, [1, 2, 0]) qc1.x(0) qc1.toffoli(0,2,1)#Undoing the flip from before qc1.x(0) qc1.x(0) qc1.x(1) qc1.toffoli(0,1,2)#Undoing the flip from before qc1.x(0) qc1.x(1) qc1.draw('mpl') U_circ = qi.Operator(qc1).data print(U_circ) qc2 = QuantumCircuit(3) # Code for U qc2.x(0) qc2.x(1) qc2.toffoli(0,1,2)#Flipping the third bit if the first two are zero qc2.x(0) #Essentially 000 -> 001 qc2.x(1) qc2.x(0) qc2.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one qc2.x(0) #Essentially 001 -> 011 qc2.append(controlled_u_tilde, [1, 2, 0]) qc2.x(0) qc2.toffoli(0,2,1)#Undoing the flip from before qc2.x(0) qc2.x(0) qc2.x(1) qc2.toffoli(0,1,2)#Undoing the flip from before qc2.x(0) qc2.x(1) # Code for V qc2.x(0) qc2.toffoli(0,1,2) # |010> -> |011> qc2.x(0) qc2.toffoli(1,2,0) # V-tilde is the same as Toffoli qc2.x(0) qc2.toffoli(0,1,2) # Reversing the flip qc2.x(0) qc2.draw('mpl') def without_global_phase(matrix: np.ndarray, atol: float = 1e-8) : phases1 = np.angle(matrix[abs(matrix) > atol].ravel(order='F')) if len(phases1) > 0: matrix = np.exp(-1j * phases1[0]) * matrix return matrix V_circ = without_global_phase(qi.Operator(qc2).data) print(V_circ) #Function just returns norm ignoring global phase between unitaries def norm(unitary_a: np.ndarray, unitary_b: np.ndarray) : return np.linalg.norm(without_global_phase(unitary_b)-without_global_phase(unitary_a), ord=2) #Make the Pauli Y gate qcy = QuantumCircuit(1) for i in range(6): qcy.t(0) qcy.h(0) for i in range(4): qcy.t(0) qcy.h(0) for i in range(2): qcy.t(0) Y_circ = qi.Operator(qcy).data Y = np.array([[0,-1j],[1j,0]]) print(norm(Y_circ,Y)) print("Final Circuit:") qcy.draw('mpl') uni_q = np.array([[-0.25+0.60355339j, 0.60355339+0.45710678j], [0.60355339-0.45710678j, 0.25+0.60355339j]]).reshape(2,2) while True: qc3 = QuantumCircuit(1) for i in range(5): for j in range(np.random.randint(8)): qc3.t(0) qc3.h(0) for j in range(np.random.randint(8)): qc3.t(0) uni_q_circ = qi.Operator(qc3).data if norm(uni_q_circ,uni_q) < 1e-8: break print("Final Error: ", norm(uni_q_circ,uni_q)) print("Final Circuit:") qc3.draw('mpl') #Defining the gate as controlled_irx from qiskit.extensions import * pi_alpha = np.arccos(0.6) qc_for_irx = QuantumCircuit(1) irx = np.array([[1j*np.cos(pi_alpha/2),np.sin(pi_alpha/2)],[np.sin(pi_alpha/2),1j*np.cos(pi_alpha/2)]]).reshape(2,2) g_irx = UnitaryGate(data=irx,label=None) controlled_irx = g_irx.control(2) def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate n = 4 qcb = QuantumCircuit(n,n) qcb.x(0)#Ancilla qcb.x(1)#Ancilla You can use these two as control to use the controlled_irx gate count1 = 0 while abs(0.5 - (count1*pi_alpha/np.pi)%2) >= 1e-2 or count1 % 4 != 0: count1 += 1 count2 = 0 while abs(1.5 - (count2*pi_alpha/np.pi)%2) >= 1e-2 or count2 % 4 != 0: count2 += 1 count3 = 0 while abs(4.0 - (count3*pi_alpha/np.pi)%4) >= 1e-2 or count3 % 4 != 2: count3 += 1 for i in range(count1): # Rotation about x by pi/2 (count1 % 4 == 0) qcb.append(controlled_irx, [0, 1, 2]) qcb.cx(2, 3) for i in range(count2): # Rotation about x by -pi/2 (count2 % 4 == 0) qcb.append(controlled_irx, [0, 1, 2]) qcb.x(0) qcb.cx(3, 0) for i in range(count3): # Rotation about x by 0 (count3 % 4 == 2) qcb.append(controlled_irx, [0, 2, 3]) qcb.cx(3, 0) qcb.x(0) print("Executing circuit...") #Get state of qubit which should have the |+> state using the backend simulator i = 3 #Index for the qubit at |+> state qcb.h(i)#Puts the |+> state to |0> for i in range(4): qcb.measure(i, i) def run_circuit(qcb): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qcb, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qcb) print(counts) plot_histogram(counts)
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/LohitPotnuru/GroverAlgorithm_Qiskit
LohitPotnuru
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit_nature.second_q.hamiltonians import QuadraticHamiltonian # create Hamiltonian hermitian_part = np.array( [ [1.0, 2.0, 0.0, 0.0], [2.0, 1.0, 2.0, 0.0], [0.0, 2.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0], ] ) antisymmetric_part = np.array( [ [0.0, 3.0, 0.0, 0.0], [-3.0, 0.0, 3.0, 0.0], [0.0, -3.0, 0.0, 3.0], [0.0, 0.0, -3.0, 0.0], ] ) constant = 4.0 hamiltonian = QuadraticHamiltonian( hermitian_part=hermitian_part, antisymmetric_part=antisymmetric_part, constant=constant, ) # convert it to a FermionicOp and print it hamiltonian_ferm = hamiltonian.second_q_op() print(hamiltonian_ferm) # get the transformation matrix W and orbital energies {epsilon_j} ( transformation_matrix, orbital_energies, transformed_constant, ) = hamiltonian.diagonalizing_bogoliubov_transform() print(f"Shape of matrix W: {transformation_matrix.shape}") print(f"Orbital energies: {orbital_energies}") print(f"Transformed constant: {transformed_constant}") from qiskit_nature.second_q.circuit.library import FermionicGaussianState occupied_orbitals = (0, 2) eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant print(f"Eigenvalue: {eig}") circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals) circuit.draw("mpl") from qiskit.quantum_info import Statevector from qiskit_nature.second_q.mappers import JordanWignerMapper # simulate the circuit to get the final state state = np.array(Statevector(circuit)) # convert the Hamiltonian to a matrix hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix() # check that the state is an eigenvector with the expected eigenvalue np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8) # create Hamiltonian hermitian_part = np.array( [ [1.0, 2.0, 0.0, 0.0], [2.0, 1.0, 2.0, 0.0], [0.0, 2.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0], ] ) constant = 4.0 hamiltonian = QuadraticHamiltonian( hermitian_part=hermitian_part, constant=constant, ) print(f"Hamiltonian conserves particle number: {hamiltonian.conserves_particle_number()}") # get the transformation matrix W and orbital energies {epsilon_j} ( transformation_matrix, orbital_energies, transformed_constant, ) = hamiltonian.diagonalizing_bogoliubov_transform() print(f"Shape of matrix W: {transformation_matrix.shape}") print(f"Orbital energies: {orbital_energies}") print(f"Transformed constant: {transformed_constant}") from qiskit_nature.second_q.circuit.library import SlaterDeterminant occupied_orbitals = (0, 2) eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant print(f"Eigenvalue: {eig}") circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)]) circuit.draw("mpl") from qiskit_nature.second_q.circuit.library import BogoliubovTransform from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity from scipy.linalg import expm # create Hamiltonian n_modes = 5 hermitian_part = np.array(random_hermitian(n_modes)) hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part) # diagonalize Hamiltonian ( transformation_matrix, orbital_energies, _, ) = hamiltonian.diagonalizing_bogoliubov_transform() # set simulation time and construct time evolution circuit time = 1.0 register = QuantumRegister(n_modes) circuit = QuantumCircuit(register) bog_circuit = BogoliubovTransform(transformation_matrix) # change to the diagonal basis of the Hamiltonian circuit.append(bog_circuit.inverse(), register) # perform time evolution by applying z rotations for q, energy in zip(register, orbital_energies): circuit.rz(-energy * time, q) # change back to the original basis circuit.append(bog_circuit, register) # simulate the circuit initial_state = random_statevector(2**n_modes) final_state = initial_state.evolve(circuit) # compute the correct state by direct exponentiation hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix() exact_evolution_op = expm(-1j * time * hamiltonian_jw) expected_state = exact_evolution_op @ np.array(initial_state) # check that the simulated state is correct fidelity = state_fidelity(final_state, expected_state) np.testing.assert_allclose(fidelity, 1.0, atol=1e-8) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Glebegor/Quantum-programming-algorithms
Glebegor
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, Aer, execute from qiskit.tools.visualization import plot_histogram from IPython.core.display import display print("Ch 4: Quantum coin tosses") print("-------------------------") q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.measure(q, c) display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() counts = result.get_counts(qc) print(counts) display(plot_histogram(counts))
https://github.com/usamisaori/Grover
usamisaori
import qiskit from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram import numpy as np from qiskit import execute, Aer simulator = Aer.get_backend('qasm_simulator') import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') from qiskit.quantum_info import DensityMatrix, Operator # Quantum circuit to unitary matrix def getDensityMatrix(circuit): return DensityMatrix(circuit).data state_0 = np.array([1, 0]) # |0> state_1 = np.array([0, 1]) # |1> from functools import reduce Dag = lambda matrix: matrix.conj().T # Dag(M) = M† Kron = lambda *matrices: reduce(np.kron, matrices) # Kron(state_0, state_0) is |00> def pm(matrix): for row in range(len(matrix)): for col in range (len(matrix[row])): print("{:.3f}".format(matrix[row][col]), end = " ") print() # https://qiskit.org/textbook/ch-algorithms/grover.html def initCircuit(n): circuit = QuantumCircuit(n, n) for i in range(n): circuit.h(i) circuit.barrier() return circuit inputCircuit_3q = initCircuit(3) inputCircuit_3q.draw(output='mpl') def createOracle_6(): circuit = QuantumCircuit(3, 3) # Oracle for find 6 # U_f circuit.x(0) circuit.h(2) circuit.ccx(0, 1, 2) circuit.h(2) circuit.x(0) circuit.barrier() return circuit oracleCircuit_6 = createOracle_6() oracleCircuit_6.draw(output='mpl') # where the entry that correspond to the marked item will have a negative phase pm(Operator(oracleCircuit_6).data) Operator(oracleCircuit_6).data # H R H, where R = 2|0><0| - I def createR_3q(): circuit = QuantumCircuit(3, 3) circuit.x(2) circuit.x(0) circuit.x(1) circuit.h(2) circuit.ccx(0, 1, 2) circuit.barrier(0) circuit.barrier(1) circuit.h(2) circuit.x(2) circuit.x(0) circuit.x(1) return circuit R_3q = createR_3q() R_3q.draw(output='mpl') pm(Operator(R_3q).data) print('|000>', Kron(state_0, state_0, state_0)) print('R|000>',Operator(R_3q).data @ Kron(state_0, state_0, state_0) ) print('|010>', Kron(state_0, state_1, state_0)) print('R|010>',Operator(R_3q).data @ Kron(state_0, state_1, state_0) ) print('|110>', Kron(state_1, state_1, state_0)) print('R|110>',Operator(R_3q).data @ Kron(state_1, state_1, state_0) ) # H R H def createDiffuser_3q(): circuit = QuantumCircuit(3, 3) circuit.h(0) circuit.h(1) circuit.h(2) circuit = circuit.compose(createR_3q()) circuit.h(0) circuit.h(1) circuit.h(2) circuit.barrier() return circuit diffuserCircuit_3q = createDiffuser_3q() diffuserCircuit_3q.draw(output='mpl') pm(Operator(diffuserCircuit_3q).data) def createGroverIteration(oracle, diffuser): return oracle.compose(diffuser) groverIteration_3q = createGroverIteration(createOracle_6(), createDiffuser_3q()) groverIteration_3q.draw(output='mpl') groverIteration_3q = createGroverIteration(createOracle_6(), createDiffuser_3q()) inputCircuit_3q = initCircuit(3) inputCircuit_3q.draw(output='mpl') inputCircuit_3q.measure([0, 1, 2], [0, 1, 2]) job = execute(inputCircuit_3q, simulator, shots = 10000) results = job.result() counts = results.get_counts(inputCircuit_3q) print(counts) plot_histogram(counts, figsize=(10, 5), color="#FFFFCC", title="superposition state - 3 qubits") grover_3q_1 = initCircuit(3).compose(groverIteration_3q.copy()) grover_3q_1.draw(output='mpl') grover_3q_1.measure([0, 1, 2], [0, 1, 2]) job = execute(grover_3q_1, simulator, shots = 10000) results = job.result() counts = results.get_counts(grover_3q_1) print(counts) plot_histogram(counts, figsize=(10, 5), color="#FFBB00", title="one iteration - find 6") grover_3q_2 = initCircuit(3).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy()) # grover_3q_2.draw(output='mpl') grover_3q_2.measure([0, 1, 2], [0, 1, 2]) job = execute(grover_3q_2, simulator, shots = 10000) results = job.result() counts = results.get_counts(grover_3q_2) print(counts) plot_histogram(counts, figsize=(10, 5), color="#FF8822", title="two iteration - find 6") grover_3q_3 = initCircuit(3).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy()) # grover_3q_3.draw(output='mpl') grover_3q_3.measure([0, 1, 2], [0, 1, 2]) job = execute(grover_3q_3, simulator, shots = 10000) results = job.result() counts = results.get_counts(grover_3q_3) print(counts) plot_histogram(counts, figsize=(10, 5), color="#FFFF3F", title="three iteration - find 6")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Useful additional packages import matplotlib.pyplot as plt import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u(pi/2,pi/4,pi/8,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.p(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.id(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.x(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.y(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.z(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.h(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.s(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.sdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.t(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.tdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rx(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ry(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rz(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.crz(pi/2,q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cp(pi/2,q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cswap(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.measure(q, c) qc.draw() backend = BasicAer.get_backend('qasm_simulator') job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) # Initializing a three-qubit quantum state import math desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw() backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state state_fidelity(desired_vector,qc_state) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='my token') provider.backends() from qiskit import * #import qiskit.aqua as aqua #from qiskit.quantum_info import Pauli #from qiskit.aqua.operators.primitive_ops import PauliOp from qiskit.circuit.library import PhaseEstimation from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram %matplotlib inline import pyscf from pyscf import gto, scf, cc from matplotlib import pyplot as plt import numpy as np from qiskit_ionq import IonQProvider provider = IonQProvider("sUkOPlNLf6vamkFMB3SuHR2qYR5cLaMn") from qiskit.providers.jobstatus import JobStatus import time as timer g = {"I": -0.4804, "Z0": 0.3435, "Z1": -0.4347, "Z0Z1": 0.5716, "X0X1": 0.0910, "Y0Y1": 0.0910} """ This function implements the controlled exp(-iHt) Inputs: phase: phase to correct weights: Pauli weights time: Time order_index: Pauli operator index iter_num: iteration trotter_step: trotter steps Output: qc: Quantum circuit """ def buildControlledHam(phase, time, iter_num): # initialize the circuit qc = QuantumCircuit(3, 3) # Hardmard on ancilla qc.h(0) # initialize to |01> qc.x(2) # Z0 qc.crz(g["Z0"] * time * 2 * 2**iter_num, 0, 2) # Y0Y1 qc.rz(np.pi/2, 1) qc.rz(np.pi/2, 2) qc.h(1) qc.h(2) qc.cx(1, 2) qc.crz(g["Y0Y1"] * time * 2 * 2**iter_num, 0, 2) qc.cx(1, 2) qc.h(1) qc.h(2) qc.rz(-np.pi/2, 1) qc.rz(-np.pi/2, 2) # Z1 qc.crz(g["Z1"] * time * 2 * 2**iter_num, 0, 1) # X0X1 qc.h(1) qc.h(2) qc.cx(1, 2) qc.crz(g["X0X1"] * time * 2 * 2**iter_num, 0, 2) qc.cx(1, 2) qc.h(1) qc.h(2) # phase correction qc.rz(phase, 0) # inverse QFT qc.h(0) qc.measure([0, 1, 2],[0, 1, 2]) return qc """ This function implements the controlled exp(-iHt) Inputs: weights: Pauli weights time: Time order_index: Pauli operator index tot_num_iter: number of iterations trotter_step: trotter steps Output: bits: list of measured bits """ def IPEA(time, tot_num_iter, backend_id): # get backend if (backend_id == "qasm_simulator"): backend = Aer.get_backend(backend_id) else: backend = provider.get_backend("ionq_qpu") # bits bits = [] # phase correction phase = 0.0 # loop over iterations for i in range(tot_num_iter-1, -1, -1): # construct the circuit qc = buildControlledHam(phase, time, i) # run the circuit job = execute(qc, backend) if (backend_id == "ionq_qpu"): # Check if job is done while job.status() is not JobStatus.DONE: print("Job status is", job.status() ) timer.sleep(60) # once we break out of that while loop, we know our job is finished print("Job status is", job.status() ) # get result result = job.result() # get current bit this_bit = int(max(result.get_counts(), key=result.get_counts().get)[-1]) bits.append(this_bit) # update phase correction phase /= 2 phase -= (2 * np.pi * this_bit / 4.0) return bits """ This function that computes eigenvalues from bit list Inputs: bits: list of measured bits time: Time Output: eig: eigenvalue """ def eig_from_bits(bits, time): eig = 0. m = len(bits) # loop over all bits for k in range(len(bits)): eig += bits[k] / (2**(m-k)) eig *= -2*np.pi eig /= time return eig """ This function that performs classical post-processing Inputs: eig: eigenvalue weights: Pauli operator weights R: Bond distance Output: energy: total energy """ def post_process(eig, weights, R): # initialize energy energy = eig # Z0Z1 contribution energy -= weights["Z0Z1"] # I contribution energy += weights["I"] # Nuclear Repulsion ( assume R is in Angstrom ) energy += 1.0/ (R * 1.88973) # return energy return energy # backend backend_id = "qasm_simulator" # Bond Length R = 0.75 # time t = 0.74 # number of iteration max_num_iter = 8 # get exact energy # This function initialises a molecule mol = pyscf.M( atom = 'H 0 0 0; H 0 0 0.75', # in Angstrom basis = 'sto-6g', symmetry = False, ) myhf = mol.RHF().run() # create an FCI solver based on the SCF object # cisolver = pyscf.fci.FCI(myhf) print('E(FCI) = %.12f' % cisolver.kernel()[0]) error_list = [] # perform IPEA for i in range(1, max_num_iter + 1): bits = IPEA(t, i, backend_id) # re-construct phase eig = eig_from_bits(bits, t) print(eig, 'eig') # re-construct energy eng = post_process(eig, g, R) print("Total Energy is %.7f for R = %.2f, t = %.3f with %d iterations" % (eng, R, t, i) ) backend_id = "qpu" error_list = [] # perform IPEA for i in range(1, max_num_iter + 1): bits = IPEA(t, i, backend_id) # re-construct phase eig = eig_from_bits(bits, t) # re-construct energy eng = post_process(eig, g, R) print("Total Energy is %.7f for R = %.2f, t = %.3f with %d iterations" % (eng, R, t, i) )
https://github.com/AbeerVaishnav13/4-qubit-design
AbeerVaishnav13
import warnings warnings.filterwarnings('ignore') from qiskit_metal import designs, MetalGUI design = designs.DesignPlanar() design.overwrite_enabled = True design.chips.main.size_x = '12mm' design.chips.main.size_y = '10mm' gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL design.delete_all_components() design_span_x = 5 design_span_y = 3 half_chip_width = design_span_x / 2 half_chip_height = design_span_y / 2 connection_pads_options = dict( a = dict(loc_W=1, loc_H=-1), b = dict(loc_W=1, loc_H=1), c = dict(loc_W=-1, loc_H=-1) ) transmons = [] transmons.append(TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'-{half_chip_width}mm', pos_y=f'{-half_chip_height}mm', connection_pads=dict(**connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q2', options=dict(pos_x=f'0mm', pos_y=f'{half_chip_height}mm', orientation=-90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q3', options=dict(pos_x=f'0mm', pos_y=f'{-half_chip_height}mm', orientation=90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q4', options=dict(pos_x=f'{half_chip_width}mm', pos_y=f'{half_chip_height}mm', orientation=180, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal import Dict fillet='99.99um' options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight=start_strght, end_straight=end_strght ), total_length=length, fillet = '99.9um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) asym_h = 100 asym_v = 100 cpw = [] cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw2', 'Q3', 'b', 'Q2', 'b', '8 mm', f'-{asym_v}um', '0.6mm', '0.4mm')) cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled readouts_lwc = [] control_lwc = [] offset_x = 0 offset_y = 1 #Readouts readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1', options = dict( pos_x = '-5mm', pos_y = f'-{half_chip_height+offset_y}mm', lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2', options = dict( pos_x = '-1mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3', options = dict( pos_x = '1mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4', options = dict( pos_x = '5mm', pos_y = f'{half_chip_height+offset_y}mm', orientation = 180, lead_length = '30um'))) #Controls control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1', options = dict( pos_x = '-5mm', pos_y = '2mm', lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2', options = dict( pos_x = '4mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3', options = dict( pos_x = '-4mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4', options = dict( pos_x = '5mm', pos_y = '-2mm', orientation = 180, lead_length = '30um'))) gui.rebuild() gui.autoscale() readout_lines = [] asym_14 = 700 asym_23 = 700 options = Dict( lead=Dict( start_straight='430um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um')) readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um')) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from collections import OrderedDict import numpy as np control_lines = [] def connectRouteAnchor(name: str, component1: str, pin1: str, component2: str, pin2: str, anchor_points: OrderedDict) -> RouteAnchors: options_line_cl = dict( pin_inputs = dict(start_pin = dict(component = component1, pin = pin1), end_pin = dict(component = component2, pin = pin2)), anchors = anchor_points, lead = dict(start_straight = '200um', end_straight = '225um'), fillet = fillet ) return RouteAnchors(design, name, options_line_cl) anchors1c = OrderedDict() anchors1c[0] = np.array([-4, -1.42]) anchors1c[1] = np.array([-4, 2]) control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c)) anchors2c = OrderedDict() anchors2c[0] = np.array([0.08, 3.25]) anchors2c[1] = np.array([4, 3.25]) control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c)) anchors3c = OrderedDict() anchors3c[0] = np.array([-0.08, -3.25]) anchors3c[1] = np.array([-4, -3.25]) control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c)) anchors4c = OrderedDict() anchors4c[0] = np.array([4, 1.42]) anchors4c[1] = np.array([4, -2]) control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c)) gui.rebuild() gui.autoscale() gui.screenshot() # Qubit Frequencies # Q1 : 5 # Q2 : 5.1 # Q3 : 5.2 # Q4 : 5.3 # Readout Frequencies # R1 : 7 # R2 : 7.1 # R3 : 7.2 # R4 : 7.3 # CPW Frequencies # cpw1 : 7.5 # cpw2 : 7.6 # cpw3 : 7.7 # cpw4 : 7.8 # cpw5 : 7.9 from qiskit_metal.analyses.quantization import LOManalysis c1 = LOManalysis(design, "q3d") q3d1 = c1.sim.renderer q3d1.start() transmons[0].options.pad_gap = '40um' transmons[0].options.pad_width = '405um' transmons[0].options.pad_height = '90um' gui.rebuild() # IMPORTANT q3d1.activate_ansys_design("Tune_Q1", 'capacitive') q3d1.render_design(['Q1'], [('Q1', 'c'), ('Q1', 'a'),('Q1', 'b'),('Q1', 'Charge_Line')]) #q3d1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/q1.png") q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05 ) q3d1.analyze_setup("Setup") c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix() c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes() c1.sim.capacitance_matrix c1.setup.junctions = Dict(Lj=12, Cj=1) c1.setup.freq_readout = 7.5 c1.setup.freq_bus = [7.8, 7.5, 15] c1.run_lom() c1.lumped_oscillator_all c1.plot_convergence() c1.plot_convergence_chi() from qiskit_metal.analyses.quantization import LOManalysis c2 = LOManalysis(design, "q3d") q3d2 = c2.sim.renderer q3d2.start() transmons[1].options.pad_gap = '40um' transmons[1].options.pad_width = '378um' transmons[1].options.pad_height = '90um' gui.rebuild() q3d2.activate_ansys_design("Tune_Q2", 'capacitive') q3d2.render_design(['Q2'], [('Q2', 'c'), ('Q2', 'a'),('Q2', 'b'),('Q2', 'd'),('Q2', 'Charge_Line')]) #q3d2.save_screenshot(path="C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/q2.png") q3d2.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05 ) q3d2.analyze_setup("Setup") c2.sim.capacitance_matrix, c2.sim.units = q3d2.get_capacitance_matrix() c2.sim.capacitance_all_passes, _ = q3d2.get_capacitance_all_passes() c2.sim.capacitance_matrix c2.setup.junctions = Dict(Lj=12, Cj=1) c2.setup.freq_readout = 7.1 c2.setup.freq_bus = [7.5, 7.6, 7.9, 17] c2.run_lom() c2.lumped_oscillator_all c2.plot_convergence() c2.plot_convergence_chi() from qiskit_metal.analyses.quantization import LOManalysis c3 = LOManalysis(design, "q3d") q3d3 = c3.sim.renderer q3d3.start() transmons[2].options.pad_gap = '40um' transmons[2].options.pad_width = '353um' transmons[2].options.pad_height = '90um' gui.rebuild() q3d3.activate_ansys_design("Tune_Q3", 'capacitive') q3d3.render_design(['Q3'], [('Q3', 'c'), ('Q3', 'a'),('Q3', 'b'),('Q3', 'd'),('Q3', 'Charge_Line')]) #q3d3.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/q3.png") q3d3.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05 ) q3d3.analyze_setup("Setup") c3.sim.capacitance_matrix, c3.sim.units = q3d3.get_capacitance_matrix() c3.sim.capacitance_all_passes, _ = q3d3.get_capacitance_all_passes() c3.sim.capacitance_matrix c3.setup.junctions = Dict(Lj=12, Cj=1) c3.setup.freq_readout = 7.3 c3.setup.freq_bus = [7.7, 7.6, 7.8, 17] c3.run_lom() c3.lumped_oscillator_all c3.plot_convergence() c3.plot_convergence_chi() from qiskit_metal.analyses.quantization import LOManalysis c4 = LOManalysis(design, "q3d") q3d4 = c4.sim.renderer q3d4.start() transmons[3].options.pad_gap = '40um' transmons[3].options.pad_width = '344um' transmons[3].options.pad_height = '90um' gui.rebuild() q3d4.activate_ansys_design("Tune_Q4", 'capacitive') q3d4.render_design(['Q4'], [('Q4', 'c'), ('Q4', 'a'),('Q4', 'b'),('Q4', 'Charge_Line')]) #q3d4.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/q4.png") q3d4.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05 ) q3d4.analyze_setup("Setup") c4.sim.capacitance_matrix, c4.sim.units = q3d4.get_capacitance_matrix() c4.sim.capacitance_all_passes, _ = q3d4.get_capacitance_all_passes() c4.sim.capacitance_matrix c4.setup.junctions = Dict(Lj=12, Cj=1) c4.setup.freq_readout = 7.4 c4.setup.freq_bus = [7.9, 7.7, 15] c4.run_lom() c4.lumped_oscillator_all c4.plot_convergence() c4.plot_convergence_chi()
https://github.com/steffencruz/FockWits
steffencruz
# diplacementn_qubits_per_mode=2 # rotation # squeezing from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister from qiskit import execute,Aer import numpy as np from scipy.linalg import expm import matplotlib.pyplot as plt import argparse class CVGates: def __init__(self,n_qubits_per_mode=2): self.n_qubits_per_mode = n_qubits_per_mode self.n_dim = 2**n_qubits_per_mode I = np.eye(self.n_dim) # Annihilation operator self.a = np.zeros((self.n_dim,self.n_dim)) for i in range(self.n_dim-1): self.a[i,i+1]= np.sqrt(i+1) # Creation operator self.a_dag = self.a.conj().T # Number operator self.N = np.matmul(self.a_dag,self.a) # 2-qumodes operators self.a1 = np.kron(self.a, I) self.a2 = np.kron(I, self.a) self.a1_dag = self.a1.conj().T self.a2_dag = self.a2.conj().T def D(self, alpha): # Displacement operator matrix for nxn arg = alpha*self.a_dag-np.conjugate(alpha)*self.a return expm(arg) def S(self, z): #Single mode squeezing a2 = np.matmul(self.a, self.a) a2_dag = np.matmul(self.a_dag, self.a_dag) arg = np.conjugate(z)*a2 - z*a2_dag return expm(arg) def R(self, phi): arg = 1j*phi*np.matmul(self.a_dag, self.a) return expm(arg) def K(self, kappa): j = np.complex(0,1) arg = j*kappa*np.matmul(self.N, self.N) return expm(arg) def S2(self, z): #two mode squeeze a12 = np.matmul(self.a1, self.a2) a12_dag = np.matmul(self.a1_dag, self.a2_dag) arg = np.conjugate(z)*a12 - z*a12_dag return expm(arg) def BS(self, phi): a12dag = np.matmul(self.a1, self.a2_dag) a1dag2 = np.matmul(self.a1_dag, self.a2) arg = phi*a12dag - np.conjugate(phi)*a1dag2 return expm(arg) def test(self,op='D',vals=None,v0=None): if vals is None: vals = [0.0,0.1,0.2,0.3,0.4] if v0 is None: v0 = np.zeros(self.n_dim) v0[0]=1 allowed_op = ['S','D','R'] if op not in allowed_op: print('Operation \'%s\' not recognized. Must be in'%(op),allowed_op) return for v in vals: mat = eval('self.{}({})'.format(op,v)) state0 = np.matmul(mat,v0) state0 = state0*state0.conj() plt.plot(state0,'-o',ms=3,lw=1,alpha=0.5,label='{}'.format(round(v,3))) labels = ['{:04b}'.format(i) for i in range(self.n_dim)] plt.xticks(range(self.n_dim),labels,rotation=80) plt.xlabel('Qubit') plt.ylabel('Probability') plt.legend(title=op) plt.title('Results for {} Qubits per Mode'.format(self.n_qubits_per_mode)) plt.pause(0.1) if __name__=='__main__': # parse some optional arguments parser = argparse.ArgumentParser() parser.add_argument('-n','--number_per_mode', help='Number of qubits per mode',choices=[1,2,3,4],nargs='?',const=2,type=int) args = parser.parse_args() if args.number_per_mode is None: args.number_per_mode = 2 m = CVGates(args.number_per_mode) # standard init v0 = np.zeros(m.n_dim) v0[0] = 1 # displacement dmat = m.D(0.1) new_input= np.matmul(dmat,v0) # build circuit q = QuantumRegister(name='qr',size=args.number_per_mode) c = ClassicalRegister(name='cr',size=args.number_per_mode) circ = QuantumCircuit(q,c) circ.initialize(new_input, q)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.vqd import VQD from volta.utils import classical_solver class TestVQDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="swap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] message = ( "VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))" ) self.assertAlmostEqual(want, got, decimal_place, message) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimal_place, message) class TestVQDDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() # backend = BasicAer.get_backend("qasm_simulator") backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="dswap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class TestVQDAmplitude(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="amplitude", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class VQDRaiseError(unittest.TestCase): def test_not_implemented_overlapping_method(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) with self.assertRaises(NotImplementedError): VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="test", ), if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/nunofernandes-plight/Qiskit_Textbook_Worstation
nunofernandes-plight
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi qc = QuantumCircuit(1) # Create a quantum circuit with one qubit qc = QuantumCircuit(1) # Create a quantum circuit with one qubit initial_state = [0,1] # Define initial_state as |1> qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit qc.draw() # Let's view our circuit backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit qc = QuantumCircuit(1) # Create a quantum circuit with one qubit initial_state = [0,1] # Define initial_state as |1> qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit result = execute(qc,backend).result() # Do the simulation, returning the result output_state = result.get_statevector() print(output_state) # Display the output state vector qc.measure_all() qc.draw() result = execute(qc,backend).result() counts = result.get_counts() plot_histogram(counts) initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q_0> qc = QuantumCircuit(1) # Must redefine qc qc.initialize(initial_state, 0) # Initialise the 0th qubit in the state `initial_state` state = execute(qc,backend).result().get_statevector() # Execute the circuit print(state) # Print the result results = execute(qc,backend).result().get_counts() plot_histogram(results) vector = [1,1] qc.initialize(vector, 0) qc = QuantumCircuit(1) # We are redefining qc initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j] qc.initialize(initial_state, 0) qc.draw() state = execute(qc, backend).result().get_statevector() print("Qubit State = " + str(state)) qc.measure_all() qc.draw() state = execute(qc, backend).result().get_statevector() print("State of Measured Qubit = " + str(state)) from qiskit_textbook.widgets import plot_bloch_vector_spherical coords = [pi/2,0,1] # [Theta, Phi, Radius] plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates import qiskit qiskit.__qiskit_version__
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/usamisaori/qLipschitz
usamisaori
import numpy as np from qiskit.quantum_info import DensityMatrix, Statevector def getDensityMatrix(circuit): return DensityMatrix(circuit).data def getStatevector(circuit): return Statevector(circuit).data from functools import reduce Dag = lambda matrix: matrix.conj().T Kron = lambda *matrices: reduce(np.kron, matrices) def powerSets(items): N = len(items) combs = [] for i in range(2 ** N): comb = [] for j in range(N): if (i >> j) % 2: comb.append(items[j]) combs.append(comb) return combs # Measurements psi_0 = np.array([1.0, 0.0]) psi_1 = np.array([0.0, 1.0]) I = np.eye(2) M_0 = psi_0.reshape([2, 1]) @ psi_0.reshape([1, 2]).conj() M_1 = psi_1.reshape([2, 1]) @ psi_1.reshape([1, 2]).conj() def getMeasurements(qubits_num): measurement_0 = [M_0] measurement_1 = [M_1] for i in range(qubits_num - 1): measurement_0.append(I) measurement_1.append(I) return [ Kron(*measurement_0), Kron(*measurement_1) ] class Algorithm: def __init__(self, model_circuit, measurements, outputs): # DensityMatrix of model self.E = getDensityMatrix(model_circuit) # Measurements self.M = dict() for index, output in enumerate(outputs): self.M[output] = measurements[index] # Outputs self.O = outputs self.O_ = powerSets(outputs) def qLipschitz(A): E, M, O, O_ = A.E, A.M, A.O, A.O_ # Step 1: Calculate W_i W = dict() for i in O: W[i] = Dag(E) @ Dag(M[i]) @ M[i] @ E # Step 2: Calculate K_star K_star = 0; vectors = [None, None] M_star = np.zeros(E.shape) for S in O_: if len(S) == 0: continue # calculate M_S = Σ Wi M_S = np.zeros(E.shape).astype('complex64') for i in S: M_S += W[i] # calculate eigenvalues and eigenvectors of M_S eigenvalues, eigenvectors = np.linalg.eigh(M_S) min_index = np.where(eigenvalues == eigenvalues.min()) max_index = np.where(eigenvalues == eigenvalues.max()) # calculate K_S K_S = np.linalg.norm(eigenvalues[max_index][0] - eigenvalues[min_index][0]) if K_S > K_star: K_star = K_S vectors[0] = eigenvectors.T[max_index][0] vectors[1] = eigenvectors.T[min_index][0] return K_star, np.array(vectors) def FairVeriQ(A, epsilon, delta): # epsilon <= 1 and delta > 0 K_star, kernel = Lipschitz(A) if delta >= K_star * epsilon: return True, None else: return False, kernel def generateBiasPair(sigma, kernel, epsilon): psi, phi = kernel size = len(psi) psi = psi.reshape(size, 1) @ Dag(psi.reshape(size, 1)) phi = phi.reshape(size, 1) @ Dag(phi.reshape(size, 1)) rou_psi = epsilon * psi + (1 - epsilon) * sigma rou_phi = epsilon * phi + (1 - epsilon) * sigma return np.array([ rou_psi, rou_phi ]) class QLipschitz: def __init__(self, model_circuit, outputs): measurements = getMeasurements(model_circuit.num_qubits) self.A = Algorithm(model_circuit, measurements, outputs) @property def constant(self): return qLipschitz(self.A) def fairVeriQ(self, epsilon, delta): return FairVeriQ(self.A, epsilon, delta) def generateBiasPair(self, sigma, kernel, epsilon): return generateBiasPair(sigma, kernel, epsilon) __all__ = ['QLipschitz']
https://github.com/C2QA/bosonic-qiskit
C2QA
import c2qa import pytest import qiskit import math import numpy import random def test_cv_c_d(capsys): """The cv_c_d gate should discretize all params (i.e., default behavior)""" with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) theta = random.random() beta = -theta circuit.cv_c_d(theta=theta, beta=beta, qumode=qmr[0], qubit=qr[0]) gate = circuit.data[0].operation total_steps = 2 discretized_params = gate.calculate_segment_params(current_step=1, total_steps=total_steps, keep_state=True) print(f"Original theta={theta}") print(f"Discretized params {discretized_params}") assert discretized_params[0] == (theta / total_steps) assert discretized_params[1] == (beta / total_steps) def test_cv_c_schwinger(capsys): """The cv_c_schwinger gate should discretize the first param, but the others not""" with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) beta = random.random() theta_1 = random.random() phi_1 = random.random() theta_2 = random.random() phi_2 = random.random() circuit.cv_c_schwinger([beta, theta_1, phi_1, theta_2, phi_2], qmr[0], qmr[1], qr[0]) gate = circuit.data[0].operation total_steps = 2 discretized_params = gate.calculate_segment_params(current_step=1, total_steps=total_steps, keep_state=True) print(f"Original params {(beta, theta_1, phi_1, theta_2, phi_2)}") print(f"Discretized params {discretized_params}") assert discretized_params[0] == (beta / total_steps) assert discretized_params[1] == theta_1 assert discretized_params[2] == phi_1 assert discretized_params[3] == theta_2 assert discretized_params[4] == phi_2 @pytest.mark.skip(reason="Enable and test manually with debug breakpoint in__calculate_segment_params to ensure only first param is discretized") def test_cv_c_schwinger_animate(capsys): """The cv_c_schwinger gate should discretize the first param, but the others not""" with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) beta = random.random() theta_1 = random.random() phi_1 = random.random() theta_2 = random.random() phi_2 = random.random() circuit.cv_c_schwinger([beta, theta_1, phi_1, theta_2, phi_2], qmr[0], qmr[1], qr[0]) c2qa.animate.animate_wigner( circuit, file="tests/test_cv_c_schwinger_animate.gif", axes_min=-8, axes_max=8, animation_segments=2, shots=1, ) def test_discretize_with_pershot_statevector(capsys): with capsys.disabled(): qmr = c2qa.QumodeRegister(1, 3) creg = qiskit.ClassicalRegister(3) circ = c2qa.CVCircuit(qmr, creg) circ.cv_initialize(7, qmr[0]) circ.cv_delay(duration=100, qumode=qmr[0], unit="ns") circ.cv_measure(qmr[0], creg) noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=0.02, circuit=circ, time_unit="ns") state, result, fock_counts = c2qa.util.simulate(circ, noise_passes=noise_pass, discretize=True, shots=2, per_shot_state_vector=True) assert result.success def test_accumulated_counts_cv_c_r(capsys): def simulate_test(discretize: bool): qmr = c2qa.QumodeRegister(1, 3) anc = qiskit.circuit.AncillaRegister(1) cr = qiskit.circuit.ClassicalRegister(1) circ = c2qa.CVCircuit(qmr, anc, cr) circ.initialize([1, 0], anc[0]) # Ancilla in |g> circ.cv_initialize(3, qmr[0]) # Qumode in |3> # Photon number parity circuit circ.h(anc[0]) circ.cv_c_r(numpy.pi / 2, qmr[0], anc[0], duration=1, unit="µs") circ.h(anc[0]) circ.measure(anc[0], cr[0]) # Simulate noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=0.1, circuit=circ, time_unit="µs") state, result, fock_counts = c2qa.util.simulate(circ, noise_passes=noise_pass, discretize=discretize, shots=3000) print("##############") print(f"Result counts: {result.get_counts()}") print(f"Fock counts: {fock_counts}") assert result.success with capsys.disabled(): print() print("NOT DISCRETIZED") simulate_test(discretize=False) print() print("DISCRETIZED") simulate_test(discretize=True) def test_accumulated_counts_cv_d(capsys): def simulate_test(discretize: bool): num_qumodes = 1 num_qubits_per_qumode = 4 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(3, qmr[0]) circuit.cv_d(1.5, qmr[0], duration=100, unit="ns") photon_loss_rate = 0.02 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass, discretize=discretize, shots=200) print("##############") print(f"Result counts: {result.get_counts()}") print(f"Fock counts: {fock_counts}") assert result.success with capsys.disabled(): print() print("NOT DISCRETIZED") simulate_test(discretize=False) print() print("DISCRETIZED") simulate_test(discretize=True) def test_manual_vs_auto_discretize(capsys): def simulate_test(manually_discretize: bool): qmr = c2qa.QumodeRegister(1, 3) anc = qiskit.circuit.AncillaRegister(1) cr = qiskit.circuit.ClassicalRegister(1) circ = c2qa.CVCircuit(qmr, anc, cr) circ.initialize([1, 0], anc[0]) # Ancilla in |g> circ.cv_initialize(3, qmr[0]) # Qumode in |3> # Photon number parity circuit circ.h(anc[0]) if manually_discretize: for _ in range(10): # Manually discretize cv_c_r gate circ.cv_c_r(numpy.pi/20, qmr[0], anc[0], duration=0.1, unit="µs") else: circ.cv_c_r(numpy.pi/2, qmr[0], anc[0], duration=1, unit="µs") circ.h(anc[0]) circ.measure(anc[0], cr[0]) # Simulate noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=0.1, circuit=circ, time_unit="µs") return c2qa.util.simulate(circ, noise_passes=noise_pass, shots=3000, discretize=(not manually_discretize)) with capsys.disabled(): min_percent_diff = 99999 max_percent_diff = 0 for i in range(20): print() print(f"Test {i}") print("Manual Discretization") _, result_man, _ = simulate_test(manually_discretize=True) counts_man = result_man.get_counts() print(counts_man) print("Auto Discretization") _, result_auto, _ = simulate_test(manually_discretize=False) counts_auto = result_auto.get_counts() print(counts_auto) assert result_man.success assert result_auto.success for key in counts_man: max_value = max(counts_man[key], counts_auto[key]) min_value = min(counts_man[key], counts_auto[key]) diff = max_value - min_value percent_diff = diff / max_value * 100 min_percent_diff = min(percent_diff, min_percent_diff) max_percent_diff = max(percent_diff, max_percent_diff) print(f"Key '{key}' percent difference {percent_diff}") assert math.isclose(counts_man[key], counts_auto[key], rel_tol=0.25) print(f"Min percent diff {min_percent_diff}") print(f"Max percent diff {max_percent_diff}")
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Many Body Localization Benchmark Program - Qiskit """ import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict verbose = False # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z, method=2): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :param method: the method used to generate hamiltonian circuit :return: return a Qiskit circuit for this Hamiltonian ''' # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name="main") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() ''' Method 1: Basic implementation of exp(i * t * (XX + YY + ZZ)) ''' if method == 1: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) ''' Method 2: Use an optimal XXYYZZ combined operator See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf ''' if method == 2: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc ############### Result Data Analysis # Analyze and print measured results # Compute the quality of the result based on operator expectation for each state def analyze_and_print_result(qc, result, num_qubits, type, num_shots): counts = result.get_counts(qc) if verbose: print(f"For type {type} measured: {counts}") ################### IMBALANCE CALCULATION ONE ####################### expectation_a = 0 for key in counts.keys(): # compute the operator expectation for this state lambda_a = sum([((-1) ** i) * ((-1) ** int(bit)) for i, bit in enumerate(key)])/num_qubits prob = counts[key] / num_shots # probability of this state expectation_a += lambda_a * prob ##################################################################### ################### IMBALANCE CALCULATION TWO ####################### # this is the imbalance calculation explicitely defined in Sonika's notes prob_one = {} for i in range(num_qubits): prob_one[i] = 0 for key in counts.keys(): for i in range(num_qubits): if key[::-1][i] == '1': prob_one[i] += counts[key] / num_shots I_numer = 0 I_denom = 0 for i in prob_one.keys(): I_numer += (-1)**i * prob_one[i] I_denom += prob_one[i] I = I_numer/I_denom ##################################################################### if verbose: print(f"\tMeasured Imbalance: {I}, measured expectation_a: {expectation_a}") # rescaled fideltiy fidelity = I/0.4 # rescaled expectation_a expectation_a = expectation_a/0.4 # We expect expecation_a to give 1. We would like to plot the deviation from the true expectation. return counts, fidelity ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=2, max_qubits=8, max_circuits=300, num_shots=100, method=2, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main"): print("Many Body Localization Benchmark Program - Qiskit") print(f"... using circuit method {method}") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even #print(f"min, max qubits = {min_qubits} {max_qubits}") # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, expectation_a = analyze_and_print_result(qc, result, num_qubits, type, num_shots) metrics.store_metric(num_qubits, type, 'fidelity', expectation_a) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project) ex.set_noise_model() # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = max_circuits num_qubits = input_size print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # parameters of simulation w = 20 # strength of disorder k = 100 # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = 1.2 # time of simulation for circuit_id in range(num_circuits): # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() h_x = 2 * np.random.random(num_qubits) - 1 # random numbers between [-1, 1] h_z = 2 * np.random.random(num_qubits) - 1 qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z, method=method) metrics.store_metric(num_qubits, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method == 1: print("\n********\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\n********\nXXYYZZ =") print(XXYYZZ_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - Hamiltonian Simulation ({method}) - Qiskit") # if main, execute method if __name__ == '__main__': run()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile, QuantumCircuit import qiskit.quantum_info as qi from qiskit_aer import AerSimulator from qiskit_aer.noise import NoiseModel, amplitude_damping_error from qiskit.tools.visualization import plot_histogram # CNOT matrix operator with qubit-0 as control and qubit-1 as target cx_op = qi.Operator([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]) # iSWAP matrix operator iswap_op = qi.Operator([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]]) # CNOT in terms of iSWAP and single-qubit gates cx_circ = QuantumCircuit(2, name='cx<iSWAP>') # Add gates cx_circ.sdg(1) cx_circ.h(1) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0, 1], label='iswap') cx_circ.sdg(0) cx_circ.h(0) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0, 1], label='iswap') cx_circ.s(1) print(cx_circ) # Simulate the unitary for the circuit using Operator: unitary = qi.Operator(cx_circ) print(unitary) f_ave = qi.average_gate_fidelity(cx_op, unitary) print("Average Gate Fidelity: F = {:f}".format(f_ave)) 'unitary' in AerSimulator().configuration().basis_gates # Error parameters param_q0 = 0.05 # damping parameter for qubit-0 param_q1 = 0.1 # damping parameter for qubit-1 # Construct the error qerror_q0 = amplitude_damping_error(param_q0) qerror_q1 = amplitude_damping_error(param_q1) iswap_error = qerror_q1.tensor(qerror_q0) # Build the noise model by adding the error to the "iswap" gate noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap') noise_model.add_basis_gates(['unitary']) print(noise_model.basis_gates) # Bell state circuit where iSWAPS should be inserted at barrier locations bell_circ = QuantumCircuit(2, 2, name='bell') bell_circ.h(0) bell_circ.append(cx_circ, [0, 1]) bell_circ.measure([0,1], [0,1]) print(bell_circ) # Create ideal simulator backend and transpile circuit sim_ideal = AerSimulator() tbell_circ = transpile(bell_circ, sim_ideal) ideal_result = sim_ideal.run(tbell_circ).result() ideal_counts = ideal_result.get_counts(0) plot_histogram(ideal_counts, title='Ideal output for iSWAP bell-state preparation') # Create noisy simulator and transpile circuit sim_noise = AerSimulator(noise_model=noise_model) tbell_circ_noise = transpile(bell_circ, sim_noise) # Run on the simulator without noise noise_result = sim_noise.run(tbell_circ_noise).result() noise_counts = noise_result.get_counts(bell_circ) plot_histogram(noise_counts, title='Noisy output for iSWAP bell-state preparation') import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/erikberter/qiskit-quantum-artificial-life
erikberter
from qiskit import * from qiskit.aqua.circuits.gates import cry from qiskit.visualization import plot_histogram import numpy as np import random import sys import matplotlib.pyplot as plt theta = 2*np.pi/3 thetaR = np.pi/4 fileNum = 30 # Devuelve el valor esperado de un circuito con un solo bit de registro def getExpectedValue(qc, sim = Aer.get_backend('qasm_simulator') , shots=8192): job = execute(qc, sim, shots=shots) count = job.result().get_counts() a,b = [count[a]/shots if a in count else 0 for a in ['0','1']] return a-b def printHistogram(qc, sim = Aer.get_backend('qasm_simulator') , shots=8192): job = execute(qc, sim, shots=shots) return plot_histogram(job.result().get_counts()) # Devuelve la Gate time_Lapse que aplica una iteracion de paso de tiempo # # Changed : Float que representa el valor en radianes del gate CRY def getDecoherence(changed): decoherenceG = QuantumCircuit(2,1, name='decoherence') decoherenceG.ry(changed,1) decoherenceG.cx(0,1) decoherenceG.ry(-changed,1) decoherenceG.cx(0,1) decoherenceG.cx(1,0) decoherenceG.measure([1],[0]) decoherenceG.reset(1) return decoherenceG # Crea un circuito general de una Artificial Life de poblacion 1 # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuit(pop=1,time=3, initial=theta, changed=theta, measure = True): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Aumenta el la cantidad de capas de tiempo del circuito. def addTimeLapse(qc,time,measure=False, changed = theta): decoherenceG = getDecoherence(changed).to_instruction() qBits = int(len(qc.qubits)/3) for i in range(0,time): #cry for j in range(qBits): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) # Crea un escenario general de clonacion de poblacion asexual mediante clonacion exponencial # # time : Integer representando la cantidad de iteraciones # pop : Integer representando la cantidad de poblacion que tendra el algoritmo # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # mutationRate : Float que representa el ratio de mutacion def getCircuitG(time=3, pop=2, initial=theta, changed=theta, mutationRate = 0, mutation=False): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) qc.u3(initial,0,0,0) qc.cx(0,1) actPop = 1 qc.barrier() for i in range(0,time): # Adding the Time_Lapse gates for j in range(0,actPop): qc.append(decoherenceG, [3*j+1,3*j+2],[j]) qc.barrier() # Adding the new population actPopi = actPop for z in range(0,min(actPop, pop-actPop)): qc.cx(3*z, 3*actPopi) if mutation: x = np.random.normal(loc=0, scale=mutationRate) qc.rx(x, 3*actPopi) y = np.random.normal(loc=0, scale=mutationRate) qc.ry(y, 3*actPopi) qc.cx(3*actPopi, 3*actPopi+1) qc.barrier() actPopi+=1 actPop = actPopi qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Crea un circuito general de una Artificial Life de poblacion 1 con un background customizado # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuitCB(pop=1,time=3, initial=theta, changed=theta, measure = True, background_change=[np.pi/4,np.pi/8,np.pi/4], background_sign = [0,1,0]): qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): decoherenceG = getDecoherence(background_change[i]).to_instruction() if(background_sign[i]==1): qc.x(j*3+1) qc.append(decoherenceG, [j*3+1,j*3+2],[j]) if(background_sign[i]==1): qc.x(j*3+1) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Devuelve un circuito de un conjunto de individuos con reproduccion sexual def getSexualCircuit(): q=QuantumRegister(10) c=ClassicalRegister(2) qc=QuantumCircuit(q,c) qc.h(q[0]) qc.cx(q[0],q[2]) qc.h(q[3]) qc.cx(q[3],q[5]) qc.barrier() qc.cx(q[2],q[6]) qc.cx(q[5],q[6]) qc.barrier() qc.u3(np.pi/4,0,0,q[0]) qc.cx(q[0],q[1]) qc.u3(3*np.pi/4,0,0,q[3]) qc.cx(q[3],q[4]) qc.barrier() qc.h(q[8]) qc.cu3(5*np.pi/2,0,0,q[0],q[8]) qc.cu3(5*np.pi/2,0,0,q[3],q[8]) qc.cx(q[8],q[7]) qc.barrier() qc.x(q[6]) qc.ccx(q[6],q[7],q[8]) qc.x(q[6]) qc.barrier() qc.cx(q[8],q[9]) qc.measure(q[6],c[0]) qc.measure(q[8],c[1]) return qc # Crea un circuito general de una Artificial Life de poblacion 1 con un background customizado # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuitCB(pop=1,time=3, initial=theta, changed=theta, measure = True, background_change=[np.pi/4,np.pi/8,np.pi/4], background_sign = [0,1,0]): qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): decoherenceG = getDecoherence(background_change[i]).to_instruction() if(background_sign[i]==1): qc.x(j*3+1) qc.append(decoherenceG, [j*3+1,j*3+2],[j]) if(background_sign[i]==1): qc.x(j*3+1) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc
https://github.com/DmitriiNabok/QuantumKitchenSinks
DmitriiNabok
import numpy as np import matplotlib.pyplot as plt import time # Qiskit from qiskit.circuit import QuantumCircuit, ParameterVector # Scikit from sklearn.model_selection import train_test_split, StratifiedKFold, StratifiedShuffleSplit, GridSearchCV from sklearn import metrics from sklearn.linear_model import LogisticRegression from qks.QuantumKitchenSinks import QuantumKitchenSinks from qks.ProjectedQuantumKitchenSinks import ProjectedQuantumKitchenSinks seed = 12345 np.random.seed(seed) from sklearn.datasets import make_moons from sklearn.preprocessing import MinMaxScaler from qks.visualization_tools import plot_dataset, plot_predictions, plot_decisions n_samples = 100 X, y = make_moons(n_samples=n_samples, noise=0.2, random_state=22) y = 2*y-1 # Data rescaling xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax), copy=False).fit_transform(X) train_size = 15 test_size = 15 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, stratify=y, random_state=seed ) # Visualize the dataset fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 6)) axes = [xmin, xmax, xmin, xmax] ax1.set_title("Total", fontsize=24) plot_dataset(X, y, ax1, axes) ax2.set_title("Train", fontsize=24) plot_dataset(X_train, y_train, ax2, axes, marker='s', size=80) ax3.set_title("Test", fontsize=22) plot_dataset(X_test, y_test, ax3, axes, marker='^', size=100) plt.rcParams['font.size'] = 15 plt.tight_layout() plt.show() from sklearn.svm import SVC param_grid = { "gamma": [0.001, 0.005, 0.01, 0.1, 0.5, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 5.0, 10.0], "C": [1, 2, 4, 6, 8, 10, 100, 1000], } gs = GridSearchCV( estimator=SVC(kernel='rbf'), param_grid=param_grid, scoring='balanced_accuracy', n_jobs=1, refit=True, cv=StratifiedKFold(n_splits=2, shuffle=True, random_state=seed), ) gs.fit(X_train, y_train) print('Best grid search parameters:', gs.best_params_) print('Best training score:', gs.best_score_) clf = gs.best_estimator_ y_pred = clf.predict(X_train) acc_tr = metrics.balanced_accuracy_score(y_true=y_train, y_pred=y_pred) mcc_tr = metrics.matthews_corrcoef(y_true=y_train, y_pred=y_pred) y_pred = clf.predict(X_test) acc_te = metrics.balanced_accuracy_score(y_true=y_test, y_pred=y_pred) mcc_te = metrics.matthews_corrcoef(y_true=y_test, y_pred=y_pred) print() print(f"Scores ACC-MCC (train - test): {acc_tr:.2f} {mcc_tr:.2f} {acc_te:.2f} {mcc_te:.2f}") print() t0 = time.perf_counter() fig, ax = plt.subplots(1, 1, figsize=(6, 5)) N = 10 x0s = np.linspace(xmin, xmax, N) x1s = np.linspace(xmin, xmax, N) x0, x1 = np.meshgrid(x0s, x1s) XX = np.c_[x0.ravel(), x1.ravel()] y_pred = clf.decision_function(XX).reshape(x0.shape) ax.contourf(x0, x1, y_pred, cmap=plt.cm.RdBu, alpha=1.0) ax.scatter(X[:, 0], X[:, 1], s=80, c=y, marker='s', cmap=plt.cm.Paired_r, edgecolors="k") plt.tight_layout() plt.show() t1 = time.perf_counter() print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) ) ##################################################### # Wrapper for the quantum kitchen sinks classifier ##################################################### def clf_QKS(fm, X_train, y_train, X_test, y_test, n_episodes, stddev): """ """ n_features = len(X_train[0]) qks = QuantumKitchenSinks( n_features, fm, n_episodes=n_episodes, stddev=stddev, sampling='normal', seed=seed ) emb_tr = qks.embedding(X_train) clf = LogisticRegression(random_state=seed, max_iter=1000).fit(emb_tr, y_train) y_pred = clf.predict(emb_tr) acc_tr = metrics.balanced_accuracy_score(y_true=y_train, y_pred=y_pred) mcc_tr = metrics.matthews_corrcoef(y_true=y_train, y_pred=y_pred) emb_te = qks.embedding(X_test) y_pred = clf.predict(emb_te) acc_te = metrics.balanced_accuracy_score(y_true=y_test, y_pred=y_pred) mcc_te = metrics.matthews_corrcoef(y_true=y_test, y_pred=y_pred) return clf, qks, [acc_tr, mcc_tr, acc_te, mcc_te] ############################################################# # Feature Map ############################################################# n_features = len(X[0]) n_qubits = 2 n_layers = 1 n_params = 2 theta = ParameterVector('θ', length=n_params) fm = QuantumCircuit(n_qubits) j = 0 for r in range(n_layers): for i in range(n_qubits): fm.ry(theta[j%n_params], i); j += 1 for i in range(n_qubits-1): fm.cx(i, i+1) print(fm.draw(fold=120, plot_barriers=False)) ############################################################# # QKS ############################################################# t0 = time.perf_counter() clf, qks, scores = clf_QKS(fm, X_train, y_train, X_test, y_test, n_episodes=20, stddev=3.0) print() print(f"Scores ACC-MCC (train - test): {scores[0]:.2f} {scores[1]:.2f} {scores[2]:.2f} {scores[3]:.2f}") print() t1 = time.perf_counter() print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) ) t0 = time.perf_counter() fig, ax = plt.subplots(1, 1, figsize=(6, 5)) N = 10 x0s = np.linspace(xmin, xmax, N) x1s = np.linspace(xmin, xmax, N) x0, x1 = np.meshgrid(x0s, x1s) XX = np.c_[x0.ravel(), x1.ravel()] emb_X = qks.embedding(XX) y_pred = clf.decision_function(emb_X).reshape(x0.shape) ax.contourf(x0, x1, y_pred, cmap=plt.cm.RdBu, alpha=1.0) ax.scatter(X[:, 0], X[:, 1], s=80, c=y, marker='s', cmap=plt.cm.Paired_r, edgecolors="k") plt.tight_layout() plt.show() t1 = time.perf_counter() print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) ) ############################################################## # Wrapper for the projected quantum kitchen sinks classifier ############################################################## def clf_pQKS(fm, X_train, y_train, X_test, y_test, n_episodes, stddev, proj='z'): """ """ n_features = len(X_train[0]) qks = ProjectedQuantumKitchenSinks( n_features, fm, projection=proj, n_episodes=n_episodes, stddev=stddev, sampling='normal', seed=seed, method='statevector' ) emb_tr = qks.embedding(X_train) clf = LogisticRegression(random_state=seed, max_iter=1000).fit(emb_tr, y_train) y_pred = clf.predict(emb_tr) acc_tr = metrics.balanced_accuracy_score(y_true=y_train, y_pred=y_pred) mcc_tr = metrics.matthews_corrcoef(y_true=y_train, y_pred=y_pred) emb_te = qks.embedding(X_test) y_pred = clf.predict(emb_te) acc_te = metrics.balanced_accuracy_score(y_true=y_test, y_pred=y_pred) mcc_te = metrics.matthews_corrcoef(y_true=y_test, y_pred=y_pred) return clf, qks, [acc_tr, mcc_tr, acc_te, mcc_te] ############################################################# # Feature Map ############################################################# n_features = len(X[0]) n_qubits = 2 n_layers = 1 n_params = 2 theta = ParameterVector('θ', length=n_params) fm = QuantumCircuit(n_qubits) j = 0 for r in range(n_layers): for i in range(n_qubits): fm.ry(theta[j%n_params], i); j += 1 for i in range(n_qubits-1): fm.cx(i, i+1) print(fm.draw(fold=120, plot_barriers=False)) ############################################################# # Projected QKS ############################################################# t0 = time.perf_counter() clf, qks, scores = clf_pQKS(fm, X_train, y_train, X_test, y_test, n_episodes=20, stddev=3.0, proj='xyz') print() print(f"Scores ACC-MCC (train - test): {scores[0]:.2f} {scores[1]:.2f} {scores[2]:.2f} {scores[3]:.2f}") print() t1 = time.perf_counter() print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) ) t0 = time.perf_counter() fig, ax = plt.subplots(1, 1, figsize=(6, 5)) N = 10 x0s = np.linspace(xmin, xmax, N) x1s = np.linspace(xmin, xmax, N) x0, x1 = np.meshgrid(x0s, x1s) XX = np.c_[x0.ravel(), x1.ravel()] emb_X = qks.embedding(XX) y_pred = clf.decision_function(emb_X).reshape(x0.shape) ax.contourf(x0, x1, y_pred, cmap=plt.cm.RdBu, alpha=1.0) ax.scatter(X[:, 0], X[:, 1], s=80, c=y, marker='s', cmap=plt.cm.Paired_r, edgecolors="k") plt.tight_layout() plt.show() t1 = time.perf_counter() print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
import random from qiskit import QuantumCircuit from QiskitPBT.input_generators.input_generator import InputGenerator class BalancedOracleInputGenerator(InputGenerator): def __init__(self, low, high): self.low = low self.high = high def generate(self, seed): random.seed(seed) num_qubits = random.randint(self.low, self.high) circuit = QuantumCircuit(num_qubits) # make a random array of 0s and 1s xs = [random.randint(0, 1) for _ in range(num_qubits - 1)] # random array of 0s and 1s, but we must guarantee at least one 1 if num_qubits > 1: rand_bits = [int(i) for i in bin(random.randint(1, 2**(num_qubits - 1) - 1))[2:]] cxs = [0]*((num_qubits - 1) - len(rand_bits)) + rand_bits else: cxs = [] for idx, i in enumerate(xs): if i == 1: circuit.x(circuit.qubits[idx]) for idx, i in enumerate(cxs): if i == 1: circuit.cx(circuit.qubits[idx], circuit.qubits[-1]) for idx, i in enumerate(xs): if i == 1: circuit.x(circuit.qubits[idx]) return circuit class ConstantOracleInputGenerator(InputGenerator): def __init__(self, low, high): self.low = low self.high = high def generate(self, seed): random.seed(seed) num_qubits = random.randint(self.low, self.high) # randomly choose between constant 0 and constant 1 constant = random.randint(0, 1) qc = QuantumCircuit(num_qubits) if constant == 1: qc.x(qc.qubits[-1]) return qc class RandomOracleInputGenerator(InputGenerator): def __init__(self, low, high): self.low = low self.high = high def generate(self, seed): random.seed(seed) # randomly choose between constant 0 and constant 1 oracle_choice = random.randint(0, 1) if oracle_choice == 1: return ConstantOracleInputGenerator(self.low, self.high).generate(seed) else: return BalancedOracleInputGenerator(self.low, self.high).generate(seed) # defines a function that vertically merges two circuits, so that the first circuit is on top of the second, with the # last qubit of the first circuit being connected to the last qubit of the second circuit def vmerge(circuit1, circuit2): # as one register is merged, we need to subtract by one new_size = circuit1.num_qubits + circuit2.num_qubits - 1 qc = QuantumCircuit(new_size) qc.compose(circuit1, list(range(0, circuit1.num_qubits - 1)) + [new_size - 1], inplace=True) # need to start after the first circuit ends qc.compose(circuit2, list(range(circuit1.num_qubits - 1, new_size - 1)) + [new_size - 1], inplace=True) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np # Import Qiskit from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as qi Aer.backends() simulator = Aer.get_backend('aer_simulator') # Create circuit circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) plot_histogram(counts, title='Bell-State counts') # Run and get memory result = simulator.run(circ, shots=10, memory=True).result() memory = result.get_memory(circ) print(memory) # Increase shots to reduce sampling variance shots = 10000 # Stabilizer simulation method sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer') job_stabilizer = sim_stabilizer.run(circ, shots=shots) counts_stabilizer = job_stabilizer.result().get_counts(0) # Statevector simulation method sim_statevector = Aer.get_backend('aer_simulator_statevector') job_statevector = sim_statevector.run(circ, shots=shots) counts_statevector = job_statevector.result().get_counts(0) # Density Matrix simulation method sim_density = Aer.get_backend('aer_simulator_density_matrix') job_density = sim_density.run(circ, shots=shots) counts_density = job_density.result().get_counts(0) # Matrix Product State simulation method sim_mps = Aer.get_backend('aer_simulator_matrix_product_state') job_mps = sim_mps.run(circ, shots=shots) counts_mps = job_mps.result().get_counts(0) plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps], title='Counts for different simulation methods', legend=['stabilizer', 'statevector', 'density_matrix', 'matrix_product_state']) from qiskit_aer import AerError # Initialize a GPU backend # Note that the cloud instance for tutorials does not have a GPU # so this will raise an exception. try: simulator_gpu = Aer.get_backend('aer_simulator') simulator_gpu.set_options(device='GPU') except AerError as e: print(e) # Configure a single-precision statevector simulator backend simulator = Aer.get_backend('aer_simulator_statevector') simulator.set_options(precision='single') # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) print(counts) # Construct quantum circuit without measure circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_statevector() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get statevector result = simulator.run(circ).result() statevector = result.get_statevector(circ) plot_state_city(statevector, title='Bell state') # Construct quantum circuit without measure circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_unitary() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get unitary result = simulator.run(circ).result() unitary = result.get_unitary(circ) print("Circuit unitary:\n", np.asarray(unitary).round(5)) # Construct quantum circuit without measure steps = 5 circ = QuantumCircuit(1) for i in range(steps): circ.save_statevector(label=f'psi_{i}') circ.rx(i * np.pi / steps, 0) circ.save_statevector(label=f'psi_{steps}') # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() data = result.data(0) data # Generate a random statevector num_qubits = 2 psi = qi.random_statevector(2 ** num_qubits, seed=100) # Set initial state to generated statevector circ = QuantumCircuit(num_qubits) circ.set_statevector(psi) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Use initilize instruction to set initial state circ = QuantumCircuit(num_qubits) circ.initialize(psi, range(num_qubits)) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get result data result = simulator.run(circ).result() result.data(0) num_qubits = 2 rho = qi.random_density_matrix(2 ** num_qubits, seed=100) circ = QuantumCircuit(num_qubits) circ.set_density_matrix(rho) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Generate a random Clifford C num_qubits = 2 stab = qi.random_clifford(num_qubits, seed=100) # Set initial state to stabilizer state C|0> circ = QuantumCircuit(num_qubits) circ.set_stabilizer(stab) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Generate a random unitary num_qubits = 2 unitary = qi.random_unitary(2 ** num_qubits, seed=100) # Set initial state to unitary circ = QuantumCircuit(num_qubits) circ.set_unitary(unitary) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/ArunSehrawat/Quantum_Machine_Learning_use_cases_with_Qiskit
ArunSehrawat
import numpy as np import matplotlib.pyplot as plt import time, copy, warnings import networkx as nx n = 17 # = number of qubits dim = 2**n # = dimension of the n-qubit Hilbert space Q = np.random.randint(-10, 10, (n, n)) Q = np.triu(Q) print(f'{Q} = Q matrix') def plot_Q_matrix(): plt.matshow(Q, cmap='bwr') plt.xticks(np.arange(n)) plt.yticks(np.arange(n)) cb = plt.colorbar(shrink=0.7) plt.title(f'Q matrix') plt.show() plot_Q_matrix() #---------------------------------------------------------------------------- 'In the graph, a node represents a qubit (binary variables), width of the edge (i,j) is proportional to Q_ij' plt.subplots(figsize=(10,8)) g = nx.Graph() edges = [] for i in range(n): for j in range(i, n): if Q[i,j]!=0: edges.append((i, j, Q[i,j])) g.add_weighted_edges_from(edges) pos = nx.spring_layout(g, seed=0) nx.draw_networkx(g, pos, node_size= 700, node_color='magenta', width=list(nx.get_edge_attributes(g, "weight").values())) %%time def energy(x, Q): # x in an integer, one-to-one correspondence: x <--> x_bin x_bin = np.array([int(i) for i in np.binary_repr(x, n)]) # x_bin has n components, each one is either 0 (spin-up) or 1(spin-down) E = np.linalg.multi_dot([x_bin, Q, x_bin]) # E_x = energy for a given x return E def energies(Q): n = Q.shape[0] # number of qubits dim = 2**n # dimension of the n-qubit Hilbert space xE = [] for x in range(dim): E = energy(x, Q) xE.append([x, E]) return np.array(xE) # collection of all possible 2**n energies for different x #---------------------------------------------------------------------------- xE = energies(Q=Q) engs = xE[:,1] print(f'energies for different x = [...E_x...] = {engs}') #============================================================================== min_eng = np.min(engs) max_eng = np.max(engs) plt.rcParams["figure.figsize"] = (12,10) plt.scatter(np.arange(dim), engs, s=1, c='blue') plt.axhline(y = 0, color = 'black', linestyle = '-') plt.axhline(y = min_eng, color = 'red', linestyle = '-') plt.ylabel(r'energy = $E_x = \langle x|H|x\rangle$', fontsize=20) plt.xlabel('x', fontsize=20) plt.show() xmins = np.where(engs==min_eng)[0] xmins_bin = [[int(i) for i in np.binary_repr(xmin, n)] for xmin in xmins] print(f'global min_energy = {min_eng}') print(f'global min_energy eigenstates = {xmins} = {xmins_bin}\n') print(f'global max_energy = {max_eng}') from qiskit_optimization import QuadraticProgram #!pip install qiskit[optimization] from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE, QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.primitives import Sampler from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import SPSA, COBYLA qp = QuadraticProgram() for i in range(n): qp.binary_var(f'x{i}') linear = [Q[i,i] for i in range(n)] quadratic = {} for i in range(n): for j in range(i+1, n): quadratic[(f'x{i}', f'x{j}')] = Q[i,j] qp.minimize(linear=linear, quadratic=quadratic) qp %%time exact = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = exact.solve(qp) print(result.prettyprint()) print() %%time ansatz = TwoLocal(n, "ry", "cx", reps=3, entanglement="linear") # construct ansatz for VQE vqe = SamplingVQE(sampler=Sampler(), ansatz=ansatz, optimizer=COBYLA(maxiter=10)) # construct VQE meo_vqe = MinimumEigenOptimizer(min_eigen_solver=vqe) # run VQE result_vqe = meo_vqe.solve(qp) print(result_vqe.prettyprint()) print() %%time qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=10), reps=3) # construct QAOA meo_qaoa = MinimumEigenOptimizer(min_eigen_solver=qaoa) # run QAOA result_qaoa = meo_qaoa.solve(qp) print(result_qaoa.prettyprint()) print()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline with open("e2d1_raw.pkl", "rb") as f: raw = pickle.load(f) with open("e2d1_qrem.pkl", "rb") as f: qrem = pickle.load(f) with open("e2d1_zne.pkl", "rb") as f: zne = pickle.load(f) with open("e2d1_zne_pt.pkl", "rb") as f: zne_pt = pickle.load(f) num_steps_list = raw["num_steps_list"] raw_fid_list = raw["fid"] raw_stddev_list = raw["stddev"] num_steps_list = qrem["num_steps_list"] qrem_fid_list = qrem["fid"] qrem_stddev_list = qrem["stddev"] num_steps_list = zne["num_steps_list"] zne_fid_list = zne["fid"] zne_stddev_list = zne["stddev"] num_steps_list = zne_pt["num_steps_list"] zne_pt_fid_list = zne_pt["fid"] zne_pt_stddev_list = zne_pt["stddev"] plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list, raw_fid_list) plt.scatter(num_steps_list, qrem_fid_list) plt.scatter(num_steps_list, zne_fid_list) plt.scatter(num_steps_list, zne_pt_fid_list) limit = 13 plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list[:limit], raw_fid_list[:limit], marker="o") plt.scatter(num_steps_list[:limit], qrem_fid_list[:limit], marker="v") plt.scatter(num_steps_list[:limit], zne_fid_list[:limit], marker="x") plt.scatter(num_steps_list[:limit], zne_pt_fid_list[:limit], marker="*") plt.xlabel("number of trotter steps") plt.ylabel("state fidelity") plt.legend(("without error mitigations", "with QREM", "with QREM and ZNE", "with QREM, ZNE and Pauli Twirling")) plt.title("The effect of error mitigations") zne_pt_fid_list[12] import qiskit.tools.jupyter %qiskit_version_table
https://github.com/filipecorrea/deutsch-jozsa
filipecorrea
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # ...we have a 0% chance of measuring 000. assert answer.get('000', 0) == 0 def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() transpiled_dj_circuit = transpile(dj_circuit, aer_sim) results = aer_sim.run(transpiled_dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) # ...the most likely result is 1111. assert max(answer, key=answer.get) == '1111' from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import * # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit $q_{0}$, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{1}$, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{2}$, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') # Import Aer from qiskit import Aer # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = backend.run(circ) result = job.result() outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = backend.run(circ) result = job.result() # Show the results print(result.get_unitary(circ, decimals=3)) # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3), range(3)) # The Qiskit circuit object supports composition using # the compose method. circ.add_register(meas.cregs[0]) qc = circ.compose(meas) #drawing the circuit qc.draw() # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jatin-47/QGSS-2021
jatin-47
# General Imports import numpy as np # Visualisation Imports import matplotlib.pyplot as plt # Scikit Imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, MinMaxScaler # Qiskit Imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load digits dataset digits = datasets.load_digits(n_class=2) # Plot example '0' and '1' fig, axs = plt.subplots(1, 2, figsize=(6,3)) axs[0].set_axis_off() axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest') axs[1].set_axis_off() axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest') plt.show() # Split dataset sample_train, sample_test, label_train, label_test = train_test_split( digits.data, digits.target, test_size=0.2, random_state=22) # Reduce dimensions n_dim = 4 pca = PCA(n_components=n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Normalise std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Scale samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Select train_size = 100 sample_train = sample_train[:train_size] label_train = label_train[:train_size] test_size = 20 sample_test = sample_test[:test_size] label_test = label_test[:test_size] print(sample_train[0], label_train[0]) print(sample_test[0], label_test[0]) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.draw('mpl') # 3 features, depth 1 map_zz = ZZFeatureMap(feature_dimension=3, reps=1) map_zz.draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.draw('mpl') def custom_data_map_func(x): coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x)) return coeff map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'], data_map_func=custom_data_map_func) #map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.draw('mpl') # rotation block: rot = QuantumCircuit(2) params = ParameterVector('r', 2) rot.ry(params[0], 0) rot.rz(params[1], 1) # entanglement block: ent = QuantumCircuit(4) params = ParameterVector('e', 3) ent.crx(params[0], 0, 1) ent.crx(params[1], 1, 2) ent.crx(params[2], 2, 3) nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent, entanglement='linear', insert_barriers=True) nlocal.draw('mpl') qubits = 3 repeats = 2 x = ParameterVector('x', length=qubits) var_custom = QuantumCircuit(qubits) for _ in range(repeats): for i in range(qubits): var_custom.rx(x[i], i) for i in range(qubits): for j in range(i + 1, qubits): var_custom.cx(i, j) var_custom.p(x[i] * x[j], j) var_custom.cx(i, j) var_custom.barrier() var_custom.draw('mpl') print(sample_train[0]) encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.draw(output='mpl') x = [-0.1,0.2] # YOUR CODE HERE encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4) ex1_circuit =encode_map_x.bind_parameters(x) ex1_circuit.draw(output='mpl') from qc_grader import grade_lab3_ex1 # Note that the grading function is expecting a quantum circuit grade_lab3_ex1(ex1_circuit) zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(sample_train[0]) print(sample_train[1]) zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1]) zz_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) counts['0000']/sum(counts.values()) matrix_train = zz_kernel.evaluate(x_vec=sample_train) matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("testing kernel matrix") plt.show() x = [-0.1,0.2] y = [0.4,-0.6] # YOUR CODE HERE encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4) zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator')) zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y) backend =Aer.get_backend('qasm_simulator') job = execute(zz_circuit_x2,backend,shots=8192, seed_simulator=1024, seed_transpiler=1024) counts_x2 = job.result().get_counts(zz_circuit_x2) amplitude= counts_x2['00']/sum(counts_x2.values()) from qc_grader import grade_lab3_ex2 # Note that the grading function is expecting a floating point number grade_lab3_ex2(amplitude) zzpc_svc = SVC(kernel='precomputed') zzpc_svc.fit(matrix_train, label_train) zzpc_score = zzpc_svc.score(matrix_test, label_test) print(f'Precomputed kernel classification test score: {zzpc_score}') zzcb_svc = SVC(kernel=zz_kernel.evaluate) zzcb_svc.fit(sample_train, label_train) zzcb_score = zzcb_svc.score(sample_test, label_test) print(f'Callable kernel classification test score: {zzcb_score}') classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid'] for kernel in classical_kernels: classical_svc = SVC(kernel=kernel) classical_svc.fit(sample_train, label_train) classical_score = classical_svc.score(sample_test, label_test) print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring """Test scheduled circuit (quantum circuit with duration).""" from ddt import ddt, data from qiskit import QuantumCircuit, QiskitError from qiskit import transpile, assemble, BasicAer from qiskit.circuit import Parameter from qiskit.providers.fake_provider import FakeParis from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.test.base import QiskitTestCase @ddt class TestScheduledCircuit(QiskitTestCase): """Test scheduled circuit (quantum circuit with duration).""" def setUp(self): super().setUp() self.backend_with_dt = FakeParis() self.backend_without_dt = FakeParis() delattr(self.backend_without_dt.configuration(), "dt") self.dt = 2.2222222222222221e-10 self.simulator_backend = BasicAer.get_backend("qasm_simulator") def test_schedule_circuit_when_backend_tells_dt(self): """dt is known to transpiler by backend""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) # 160[dt] qc.h(1) # 160[dt] sc = transpile(qc, self.backend_with_dt, scheduling_method="alap", layout_method="trivial") self.assertEqual(sc.duration, 450610) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450450) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") qobj = assemble(sc, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 450450) self.assertEqual(qobj.experiments[0].instructions[4].name, "delay") self.assertEqual(qobj.experiments[0].instructions[4].params[0], 450450) def test_schedule_circuit_when_transpile_option_tells_dt(self): """dt is known to transpiler by transpile option""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) qc.h(1) sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", dt=self.dt, layout_method="trivial", ) self.assertEqual(sc.duration, 450610) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450450) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") def test_schedule_circuit_in_sec_when_no_one_tells_dt(self): """dt is unknown and all delays and gate times are in SI""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") qc.delay(100, 0, unit="ns") qc.h(0) qc.h(1) sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", layout_method="trivial" ) self.assertAlmostEqual(sc.duration, 450610 * self.dt) self.assertEqual(sc.unit, "s") self.assertEqual(sc.data[0].operation.name, "delay") self.assertAlmostEqual(sc.data[0].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[0].operation.unit, "s") self.assertEqual(sc.data[1].operation.name, "rz") self.assertAlmostEqual(sc.data[1].operation.duration, 160 * self.dt) self.assertEqual(sc.data[1].operation.unit, "s") self.assertEqual(sc.data[4].operation.name, "delay") self.assertAlmostEqual(sc.data[4].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[4].operation.unit, "s") with self.assertRaises(QiskitError): assemble(sc, self.backend_without_dt) def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self): """dt is unknown but delays and gate times have a mix of SI and dt""" qc = QuantumCircuit(2) qc.delay(100, 0, unit="ns") qc.delay(30, 0, unit="dt") qc.h(0) qc.h(1) with self.assertRaises(QiskitError): transpile(qc, self.backend_without_dt, scheduling_method="alap") def test_transpile_single_delay_circuit(self): qc = QuantumCircuit(1) qc.delay(1234, 0) sc = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(sc.duration, 1234) self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 1234) self.assertEqual(sc.data[0].operation.unit, "dt") def test_transpile_t1_circuit(self): qc = QuantumCircuit(1) qc.x(0) # 320 [dt] qc.delay(1000, 0, unit="ns") # 4500 [dt] qc.measure_all() # 19584 [dt] scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(scheduled.duration, 23060) def test_transpile_delay_circuit_with_backend(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(100, 1, unit="ns") # 450 [dt] qc.cx(0, 1) # 1760 [dt] scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" ) self.assertEqual(scheduled.duration, 2082) def test_transpile_delay_circuit_without_backend(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) scheduled = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)], ) self.assertEqual(scheduled.duration, 1200) def test_transpile_circuit_with_custom_instruction(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5154""" bell = QuantumCircuit(2, name="bell") bell.h(0) bell.cx(0, 1) qc = QuantumCircuit(2) qc.delay(500, 1) qc.append(bell.to_instruction(), [0, 1]) scheduled = transpile( qc, scheduling_method="alap", instruction_durations=[("bell", [0, 1], 1000)] ) self.assertEqual(scheduled.duration, 1500) def test_transpile_delay_circuit_with_dt_but_without_scheduling_method(self): qc = QuantumCircuit(1) qc.delay(100, 0, unit="ns") transpiled = transpile(qc, backend=self.backend_with_dt) self.assertEqual(transpiled.duration, None) # not scheduled self.assertEqual(transpiled.data[0].operation.duration, 450) # unit is converted ns -> dt def test_transpile_delay_circuit_without_scheduling_method_or_durs(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) not_scheduled = transpile(qc) self.assertEqual(not_scheduled.duration, None) def test_raise_error_if_transpile_with_scheduling_method_but_without_durations(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) with self.assertRaises(TranspilerError): transpile(qc, scheduling_method="alap") def test_invalidate_schedule_circuit_if_new_instruction_is_appended(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") # append a gate to a scheduled circuit scheduled.h(0) self.assertEqual(scheduled.duration, None) def test_default_units_for_my_own_duration_users(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) # accept None for qubits scheduled = transpile( qc, basis_gates=["h", "cx", "delay"], scheduling_method="alap", instruction_durations=[("h", 0, 200), ("cx", None, 900)], ) self.assertEqual(scheduled.duration, 1400) # prioritize specified qubits over None scheduled = transpile( qc, basis_gates=["h", "cx", "delay"], scheduling_method="alap", instruction_durations=[("h", 0, 200), ("cx", None, 900), ("cx", [0, 1], 800)], ) self.assertEqual(scheduled.duration, 1300) def test_unit_seconds_when_using_backend_durations(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) # usual case scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" ) self.assertEqual(scheduled.duration, 2132) # update durations durations = InstructionDurations.from_backend(self.backend_with_dt) durations.update([("cx", [0, 1], 1000 * self.dt, "s")]) scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", instruction_durations=durations, layout_method="trivial", ) self.assertEqual(scheduled.duration, 1500) def test_per_qubit_durations(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5109""" qc = QuantumCircuit(3) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.h(1) sc = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", None, 200), ("cx", [0, 1], 700)], ) self.assertEqual(sc.qubit_start_time(0), 300) self.assertEqual(sc.qubit_stop_time(0), 1200) self.assertEqual(sc.qubit_start_time(1), 500) self.assertEqual(sc.qubit_stop_time(1), 1400) self.assertEqual(sc.qubit_start_time(2), 0) self.assertEqual(sc.qubit_stop_time(2), 0) self.assertEqual(sc.qubit_start_time(0, 1), 300) self.assertEqual(sc.qubit_stop_time(0, 1), 1400) qc.measure_all() sc = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx", "measure"], instruction_durations=[("h", None, 200), ("cx", [0, 1], 700), ("measure", None, 1000)], ) q = sc.qubits self.assertEqual(sc.qubit_start_time(q[0]), 300) self.assertEqual(sc.qubit_stop_time(q[0]), 2400) self.assertEqual(sc.qubit_start_time(q[1]), 500) self.assertEqual(sc.qubit_stop_time(q[1]), 2400) self.assertEqual(sc.qubit_start_time(q[2]), 1400) self.assertEqual(sc.qubit_stop_time(q[2]), 2400) self.assertEqual(sc.qubit_start_time(*q), 300) self.assertEqual(sc.qubit_stop_time(*q), 2400) def test_change_dt_in_transpile(self): qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) # default case scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="asap") org_duration = scheduled.duration # halve dt in sec = double duration in dt scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="asap", dt=self.dt / 2 ) self.assertEqual(scheduled.duration, org_duration * 2) @data("asap", "alap") def test_duration_on_same_instruction_instance(self, scheduling_method): """See: https://github.com/Qiskit/qiskit-terra/issues/5771""" assert self.backend_with_dt.properties().gate_length( "cx", (0, 1) ) != self.backend_with_dt.properties().gate_length("cx", (1, 2)) qc = QuantumCircuit(3) qc.cz(0, 1) qc.cz(1, 2) sc = transpile(qc, backend=self.backend_with_dt, scheduling_method=scheduling_method) cxs = [inst.operation for inst in sc.data if inst.operation.name == "cx"] self.assertNotEqual(cxs[0].duration, cxs[1].duration) def test_transpile_and_assemble_delay_circuit_for_simulator(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5962""" qc = QuantumCircuit(1) qc.delay(100, 0, "ns") circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 1e-7) def test_transpile_and_assemble_t1_circuit_for_simulator(self): """Check if no scheduling is done in transpiling for simulator backends""" qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(0.1, 0, "us") qc.measure(0, 0) circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertAlmostEqual(qobj.experiments[0].instructions[1].params[0], 1e-7) # Tests for circuits with parameterized delays def test_can_transpile_circuits_after_assigning_parameters(self): """Check if not scheduled but duration is converted in dt""" idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.duration, 450) # converted in dt def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) circ = transpile(qc, self.backend_with_dt) circ = circ.assign_parameters({idle_dur: 0.1}) qobj = assemble(circ, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertEqual(qobj.experiments[0].instructions[1].params[0], 450) def test_can_transpile_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.unit, "dt") # converted in dt self.assertEqual( circ.data[1].operation.duration, idle_dur * 1e-6 / self.dt ) # still parameterized def test_fail_to_assemble_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = transpile(qc, self.backend_with_dt) with self.assertRaises(QiskitError): assemble(qc, self.backend_with_dt) @data("asap", "alap") def test_can_schedule_circuits_with_bounded_parameters(self, scheduling_method): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) circ = transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) self.assertIsNotNone(circ.duration) # scheduled @data("asap", "alap") def test_fail_to_schedule_circuits_with_unbounded_parameters(self, scheduling_method): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter with self.assertRaises(TranspilerError): transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """PrimitiveOp Class""" from typing import Dict, List, Optional, Set, Union, cast import numpy as np import scipy.linalg from scipy.sparse import spmatrix from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector from qiskit.utils.deprecation import deprecate_func class PrimitiveOp(OperatorBase): r""" Deprecated: A class for representing basic Operators, backed by Operator primitives from Terra. This class (and inheritors) primarily serves to allow the underlying primitives to "flow" - i.e. interoperability and adherence to the Operator formalism - while the core computational logic mostly remains in the underlying primitives. For example, we would not produce an interface in Terra in which ``QuantumCircuit1 + QuantumCircuit2`` equaled the Operator sum of the circuit unitaries, rather than simply appending the circuits. However, within the Operator flow summing the unitaries is the expected behavior. Note that all mathematical methods are not in-place, meaning that they return a new object, but the underlying primitives are not copied. """ def __init_subclass__(cls): cls.__new__ = lambda cls, *args, **kwargs: super().__new__(cls) @staticmethod # pylint: disable=unused-argument def __new__( cls, primitive: Union[ Instruction, QuantumCircuit, List, np.ndarray, spmatrix, Operator, Pauli, SparsePauliOp ], coeff: Union[complex, ParameterExpression] = 1.0, ) -> "PrimitiveOp": """A factory method to produce the correct type of PrimitiveOp subclass based on the primitive passed in. Primitive and coeff arguments are passed into subclass's init() as-is automatically by new(). Args: primitive: The operator primitive being wrapped. coeff: A coefficient multiplying the primitive. Returns: The appropriate PrimitiveOp subclass for ``primitive``. Raises: TypeError: Unsupported primitive type passed. """ # pylint: disable=cyclic-import if isinstance(primitive, (Instruction, QuantumCircuit)): from .circuit_op import CircuitOp return super().__new__(CircuitOp) if isinstance(primitive, (list, np.ndarray, spmatrix, Operator)): from .matrix_op import MatrixOp return super().__new__(MatrixOp) if isinstance(primitive, Pauli): from .pauli_op import PauliOp return super().__new__(PauliOp) if isinstance(primitive, SparsePauliOp): from .pauli_sum_op import PauliSumOp return super().__new__(PauliSumOp) raise TypeError( "Unsupported primitive type {} passed into PrimitiveOp " "factory constructor".format(type(primitive)) ) @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase], coeff: Union[complex, ParameterExpression] = 1.0, ) -> None: """ Args: primitive: The operator primitive being wrapped. coeff: A coefficient multiplying the primitive. """ super().__init__() self._primitive = primitive self._coeff = coeff @property def primitive(self) -> Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase]: """The primitive defining the underlying function of the Operator. Returns: The primitive object. """ return self._primitive @property def coeff(self) -> Union[complex, ParameterExpression]: """ The scalar coefficient multiplying the Operator. Returns: The coefficient. """ return self._coeff @property def num_qubits(self) -> int: raise NotImplementedError @property def settings(self) -> Dict: """Return operator settings.""" return {"primitive": self._primitive, "coeff": self._coeff} def primitive_strings(self) -> Set[str]: raise NotImplementedError def add(self, other: OperatorBase) -> OperatorBase: raise NotImplementedError def adjoint(self) -> OperatorBase: raise NotImplementedError def equals(self, other: OperatorBase) -> bool: raise NotImplementedError def mul(self, scalar: Union[complex, ParameterExpression]) -> OperatorBase: if not isinstance(scalar, (int, float, complex, ParameterExpression)): raise ValueError( "Operators can only be scalar multiplied by float or complex, not " "{} of type {}.".format(scalar, type(scalar)) ) # Need to return self.__class__ in case the object is one of the inherited OpPrimitives return self.__class__(self.primitive, coeff=self.coeff * scalar) def tensor(self, other: OperatorBase) -> OperatorBase: raise NotImplementedError def tensorpower(self, other: int) -> Union[OperatorBase, int]: # Hack to make Z^(I^0) work as intended. if other == 0: return 1 if not isinstance(other, int) or other < 0: raise TypeError("Tensorpower can only take positive int arguments") temp = PrimitiveOp(self.primitive, coeff=self.coeff) # type: OperatorBase for _ in range(other - 1): temp = temp.tensor(self) return temp def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: # pylint: disable=cyclic-import from ..list_ops.composed_op import ComposedOp new_self, other = self._expand_shorter_operator_and_permute(other, permutation) if isinstance(other, ComposedOp): comp_with_first = new_self.compose(other.oplist[0]) if not isinstance(comp_with_first, ComposedOp): new_oplist = [comp_with_first] + other.oplist[1:] return ComposedOp(new_oplist, coeff=other.coeff) return ComposedOp([new_self] + other.oplist, coeff=other.coeff) return ComposedOp([new_self, other]) def _expand_dim(self, num_qubits: int) -> OperatorBase: raise NotImplementedError def permute(self, permutation: List[int]) -> OperatorBase: raise NotImplementedError def exp_i(self) -> OperatorBase: """Return Operator exponentiation, equaling e^(-i * op)""" # pylint: disable=cyclic-import from ..evolutions.evolved_op import EvolvedOp return EvolvedOp(self) def log_i(self, massive: bool = False) -> OperatorBase: """Return a ``MatrixOp`` equivalent to log(H)/-i for this operator H. This function is the effective inverse of exp_i, equivalent to finding the Hermitian Operator which produces self when exponentiated.""" # pylint: disable=cyclic-import from ..operator_globals import EVAL_SIG_DIGITS from .matrix_op import MatrixOp return MatrixOp( np.around( scipy.linalg.logm(self.to_matrix(massive=massive)) / -1j, decimals=EVAL_SIG_DIGITS ) ) def __str__(self) -> str: raise NotImplementedError def __repr__(self) -> str: return f"{type(self).__name__}({repr(self.primitive)}, coeff={self.coeff})" def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: raise NotImplementedError @property def parameters(self): params = set() if isinstance(self.primitive, (OperatorBase, QuantumCircuit)): params.update(self.primitive.parameters) if isinstance(self.coeff, ParameterExpression): params.update(self.coeff.parameters) return params def assign_parameters(self, param_dict: dict) -> OperatorBase: param_value = self.coeff if isinstance(self.coeff, ParameterExpression): unrolled_dict = self._unroll_param_dict(param_dict) if isinstance(unrolled_dict, list): # pylint: disable=cyclic-import from ..list_ops.list_op import ListOp return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict]) if self.coeff.parameters <= set(unrolled_dict.keys()): binds = {param: unrolled_dict[param] for param in self.coeff.parameters} param_value = complex(self.coeff.bind(binds)) if abs(param_value.imag) == 0: param_value = param_value.real return self.__class__(self.primitive, coeff=param_value) # Nothing to collapse here. def reduce(self) -> OperatorBase: return self def to_matrix(self, massive: bool = False) -> np.ndarray: raise NotImplementedError def to_matrix_op(self, massive: bool = False) -> OperatorBase: """Returns a ``MatrixOp`` equivalent to this Operator.""" coeff = self.coeff op = self.copy() op._coeff = 1 prim_mat = op.to_matrix(massive=massive) from .matrix_op import MatrixOp return MatrixOp(prim_mat, coeff=coeff) def to_instruction(self) -> Instruction: """Returns an ``Instruction`` equivalent to this Operator.""" raise NotImplementedError def to_circuit(self) -> QuantumCircuit: """Returns a ``QuantumCircuit`` equivalent to this Operator.""" qc = QuantumCircuit(self.num_qubits) qc.append(self.to_instruction(), qargs=range(self.primitive.num_qubits)) return qc.decompose() def to_circuit_op(self) -> OperatorBase: """Returns a ``CircuitOp`` equivalent to this Operator.""" from .circuit_op import CircuitOp if self.coeff == 0: return CircuitOp(QuantumCircuit(self.num_qubits), coeff=0) return CircuitOp(self.to_circuit(), coeff=self.coeff) def to_pauli_op(self, massive: bool = False) -> OperatorBase: """Returns a sum of ``PauliOp`` s equivalent to this Operator.""" # pylint: disable=cyclic-import from .matrix_op import MatrixOp mat_op = cast(MatrixOp, self.to_matrix_op(massive=massive)) sparse_pauli = SparsePauliOp.from_operator(mat_op.primitive) if not sparse_pauli.to_list(): from ..operator_globals import I return (I ^ self.num_qubits) * 0.0 from .pauli_op import PauliOp if len(sparse_pauli) == 1: label, coeff = sparse_pauli.to_list()[0] coeff = coeff.real if np.isreal(coeff) else coeff return PauliOp(Pauli(label), coeff * self.coeff) from ..list_ops.summed_op import SummedOp return SummedOp( [ PrimitiveOp( Pauli(label), coeff.real if coeff == coeff.real else coeff, ) for (label, coeff) in sparse_pauli.to_list() ], self.coeff, )
https://github.com/IdhamHabibie/grover_algorithm_2_qubits
IdhamHabibie
# Run this if you haven't install qiskit, pylatexenc, and truth-table-generator !pip install qiskit !pip install qiskit --upgrade !pip3 install pylatexenc !pip install truth-table-generator #initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector from qiskit.aqua.components import oracles # import basic plot tools from qiskit.visualization import plot_histogram # Bold Color class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' # Apply the H Gate def initialize_s(qc, qubits): """Apply a H-gate to 'qubits' in qc""" for q in qubits: qc.h(q) return qc # Quantum 2 qubits def list_qubit(n): list_measurement = [] for i in range(n): list_measurement.append(i) return(list_measurement) # Build the Oracle Function def oracle(n_qubits, reversed_qubit): # Define the Quantum Circuit grover_circuit = QuantumCircuit(3*n_qubits+1) # List Reversed list_reversed = list(range(n_qubits)) list_reversed.reverse() print("Vous avez", n_qubits , "qubits") grover_circuit = initialize_s(grover_circuit, list(range(n_qubits))) # Build the Oracle for i in range(n_qubits): grover_circuit.cx(i,i+n_qubits) # Cx Gate for i in range(n_qubits): grover_circuit.cx(i+n_qubits, i + (2*n_qubits)) # X Gate list_new = [] for j in range(2): for i in range(n_qubits+1): if(i == n_qubits): grover_circuit.h(i + (2*n_qubits)) else: grover_circuit.x(i + (2*n_qubits)) if(j != 1): for i in range((n_qubits)): list_new.append((2*n_qubits)+i) grover_circuit.mct(list_new,(3*n_qubits)) # CX Gate for i in list_reversed: grover_circuit.cx(i+n_qubits,i + (2*n_qubits)) # CX Gate for i in list_reversed: grover_circuit.cx(i, i + n_qubits) # We will return the diffuser as a gate U_s = grover_circuit.to_gate() U_s.name = "Oracle" return(U_s) # Build the Diffuser Function def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "Diffuser" return(U_s) # Build the Diffuser Function def diffuser_un(nqubits): # Quantum Circuit A little bit qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "Diffuser" return U_s # Build the Statevector def state_vector(circuit): sv_sim = Aer.get_backend('statevector_simulator') job_sim = execute(grover_circuit, sv_sim) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex return vector2latex(statevec, pretext="|\\psi\\rangle =") # Running the Program def probabilities(grover_circuit): backend = Aer.get_backend('qasm_simulator') results = execute(grover_circuit, backend=backend, shots=1024).result() answer = results.get_counts() return(answer) # Load IBM Q account and get the least busy backend device def experiment_device(grover_circuit): provider = IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=backend, shots=1024, optimization_level=3) job_monitor(job, interval = 2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) # AND Gate # Position Argument : It depends on the argument of where you put in the Truth Table (1st, 2nd, 3rd) def and_gate(n_qubits): # Define the Quantum Circuit qc = QuantumCircuit(n_qubits + 1) # Multi Controlled Toffoli Gate qc.mcx([0,1], n_qubits) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "$AND Gate$" return(U_s) # NAND Gate # Position Argument : It depends on the argument of where you put in the Truth Table (1st, 2nd, 3rd) def nand_gate(n_qubits): # Define the Quantum Circuit qc = QuantumCircuit(n_qubits + 1) # X-Gate NAND Gate for i in range(n_qubits+1): qc.x(i) # Multi Controlled Toffoli Gate qc.mcx([0,1], n_qubits) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "$NAND Gate$" return(U_s) # OR GATE # Position Argument : It depends on the argument of where you put in the Truth Table (1st, 2nd, 3rd) def or_gate(n_qubits): # Define the Quantum Circuit qc = QuantumCircuit(n_qubits + 1) # Range n_qubits for i in range(2): qc.x(i) # Besides of the Toffoli qc.x(n_qubits) # Multi Controlled Toffoli Gate qc.mcx([0,1], n_qubits) # We will return the OR as a gate U_s = qc.to_gate() U_s.name = "$OR GATE$" return(U_s) # XOR Gate # Position Argument : It depends on the XOR Gate def xor_gate(n_qubits): # Define the Quantum Circuit qc = QuantumCircuit(n_qubits) # This is the CNOT Gate and X Gate qc.cx(0,1) # We will return the OR as a gate U_s = qc.to_gate() U_s.name = "$XOR GATE$" return(U_s) # XnOR Gate # Position Argument : It depends on the XOR Gate def xnor_gate(n_qubits): # Define the Quantum Circuit qc = QuantumCircuit(n_qubits) # This is the CNOT Gate and X Gate qc.x(n_qubits-1) qc.cx(0,n_qubits-1) # We will return the OR as a gate U_s = qc.to_gate() U_s.name = "$XNOR GATE$" return(U_s) # Implication Gate def implies_gate(n_qubits): # Define the Quantum Circuit qc = QuantumCircuit(n_qubits+1) # This is the CNOT Gate and Toffoli Gate. # The existing implies in here. qc.x(n_qubits) qc.cx(0,1) qc.x(0) qc.mcx([0,1], n_qubits) # We will return the OR as a gate U_s = qc.to_gate() U_s.name = "$Implies GATE$" return(U_s) # Special Gate def special_gate(n_qubits): # Define the Quantum Circuit qc = QuantumCircuit(n_qubits+1) # This is the CNOT Gate and Toffoli Gate. # The existing implies in here. qc.x([0,1]) qc.mcx([0,1], n_qubits) qc.cx(0,1) qc.cx(1,2) qc.mcx([0,1], n_qubits) # We will return the OR as a gate U_s = qc.to_gate() U_s.name = "$Special GATE$" return(U_s) import ttg import pandas as pd # For example 2 qubits # ~q # p xor q statement = True while(statement != False): # Define Variable list_calculation = [] list_input = [] iniput = '' output = '' # Defining how many qubits used for this gate print("How many qubits that you are looking?" + color.BOLD + " Par Exemple : 1 for 1 qubit, 2 for qubits, 3 for qubits" + color.END) print("----------------------------------------") n_qubits = int(input()) print("----------------------------------------") # Rules of the Truth Table print(f"You have filled" + color.BOLD + f" {n_qubits} qubits," +color.END + " so you must filled" + color.BOLD + f" {n_qubits} argument" + color.END+ " as follows") # The Calculation qubits for i in range(n_qubits): print(f"The {i+1}-th Argument") print("----------------------") # String output string = input() list_calculation.append(string) # String input inputan = chr(ord('p')+i) list_input.append(inputan) # Create the Table table = ttg.Truths(list_input, list_calculation) table_pd = table.as_pandas() display(table_pd) # Inputan and Output for i in range(n_qubits): iniput = iniput + " " + table_pd.iloc[:,i].astype(str) output = output + table_pd.iloc[:,i+n_qubits].astype(str) # Convert to the dataframe dataframe = pd.DataFrame({"input":iniput, "output":output}) # Check if there is any duplicates in the output (which is not correspond to what we want) statement = dataframe.output.duplicated().any() if(statement == True): print(color.RED + "Sorry, there is a duplicate output!" + color.END) # Successful print("Well done you have " + color.BLUE + "filled it correctly" + color.END) # Question remark of my qubits print("--------------------------------------------------") print("Quels qubits souhaitez-vous rechercher? " + color.BOLD + "Par Exemple : 0, 01, 101, 1100" + color.END) qubit = input() print("--------------------------------------------------") # Argument arg = 0 while arg !=1: if(len(qubit)!= n_qubits): print(color.RED + "Sorry, it's wrong!" + color.END + " Please put the same input with the " + color.BOLD + "total qubits before" + color.END) # Question remark of my qubits print("--------------------------------------------------") print("Quels qubits souhaitez-vous rechercher? " + color.BOLD + "Par Exemple : 0, 01, 101, 1100" + color.END) qubit = input() print("--------------------------------------------------") arg = 0 else: print("Correct") print("--------------------------------------------------") arg = 1 # Analysis the input qubit # Initialize to 1 # %config InlineBackend.figure_format = 'svg' # Makes the images fit initial_state = [0,1] analyse_iteration = [] # Reversing the Qubit Information reversed_qubit = qubit[::-1] # Initialize the Quantum Circuit if(n_qubits != 1): grover_circuit = QuantumCircuit((3*(n_qubits)) + 1, n_qubits) else: grover_circuit = QuantumCircuit((3*(n_qubits)) + 2, n_qubits) # List Reversed if(n_qubits !=1): list_reversed = list(range(n_qubits)) list_reversed.reverse() else: list_reversed = list(range(n_qubits+2)) list_reversed.reverse() # Define the classical bits cbit = n_qubits print("Vous Avez", n_qubits , "qubits") # Initialize the Quantum Circuit (How much the total qubits + ancilla qubits needed) grover_circuit = initialize_s(grover_circuit, list(range(n_qubits))) # Iteration print("How many interation do you want?") iteration = int(input()) print("--------------------------------------------------") # Desired Value ->(&) for i,j in enumerate(reversed_qubit): if(n_qubits != 1): # If n_qubits is not equal to 1 if(int(j) == 1): grover_circuit.initialize(initial_state, int(i) + (3*(n_qubits))-2) else: # If equal to 1 if(int(j) == 1): grover_circuit.initialize(initial_state, int(i) + (3*(n_qubits))-1) # All the Circuits for i in range(iteration): if(n_qubits != 1): # Initialize the Hadamard on the last grover_circuit.initialize(initial_state, (3*(n_qubits))) grover_circuit.barrier() # Build the Flip Gate for Truth Table. Tres IMPORTANT !! for i in range(n_qubits): grover_circuit.cx(i, i + n_qubits) grover_circuit.barrier() #### C'est un important -> Truth Table Gate # # X Gate aja grover_circuit.swap(2,3) grover_circuit.x([2,3]) grover_circuit.cx(3,2) # This is swapping gates (It should be on the above) grover_circuit.barrier() # CX Gate for i in range(n_qubits): grover_circuit.cx(i+n_qubits, i + (2*n_qubits)) grover_circuit.barrier() # X Gate list_new = [] for j in range(2): for i in range(n_qubits+1): if(i == n_qubits): grover_circuit.h(i + (2*n_qubits)) else: grover_circuit.x(i + (2*n_qubits)) if(j != 1): for i in range((n_qubits)): list_new.append((2*n_qubits)+i) grover_circuit.mct(list_new,(3*n_qubits)) grover_circuit.barrier() # CX Gate for i in list_reversed: grover_circuit.cx(i+n_qubits,i + (2*n_qubits)) grover_circuit.barrier() # # # CNOT Gate grover_circuit.cx(3,2) grover_circuit.x([2,3]) grover_circuit.swap(2,3) # Last Oracle for i in list_reversed: grover_circuit.cx(i, i + n_qubits) grover_circuit.barrier() # Diffusion grover_circuit.append(diffuser(n_qubits), list(range(n_qubits))) grover_circuit.barrier() # # Result Oriented # result_2 = probabilities(grover_circuit) # analyse_iteration.append(result_2[qubit]) # If there is a Single Qubit over it else: # Initialize the Hazamard on the last grover_circuit.initialize(initial_state, (3*(n_qubits))+1) grover_circuit.barrier() # Build the Oracle for i in range(n_qubits+2): grover_circuit.cx(i,i+n_qubits) grover_circuit.barrier() # X Gate list_new = [] for j in range(2): for i in range(n_qubits+2): if(i == n_qubits+1): grover_circuit.h(i + (2*n_qubits)) else: grover_circuit.x(i + (2*n_qubits)) if(j != 1): for i in range((n_qubits)+1): list_new.append((2*n_qubits)+i) grover_circuit.mct(list_new,(3*n_qubits)+1) grover_circuit.barrier() # Last Oracle for i in list_reversed: grover_circuit.cx(i, i + n_qubits) grover_circuit.barrier() # Grover Diffuser Un grover_circuit.append(diffuser_un(n_qubits), list(range(n_qubits))) # Measurement grover_circuit.measure(list(range(n_qubits)),list(range(n_qubits))) grover_circuit.draw(output = 'mpl') # Explorez le Probabilities %config InlineBackend.figure_format = 'svg' # Makes the images fit result_2 = probabilities(grover_circuit) print("Simulation Result") plot_histogram(result_2)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for 1-qubit Clifford gate instructions. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # ========================================================================== # H-gate # ========================================================================== def h_gate_circuits_deterministic(final_measure=True): """H-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # HH=I circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def h_gate_counts_deterministic(shots, hex_counts=True): """H-gate circuits reference counts.""" targets = [] if hex_counts: # HH=I targets.append({'0x0': shots}) else: # HH=I targets.append({'0': shots}) return targets def h_gate_statevector_deterministic(): """H-gate circuits reference statevectors.""" targets = [] # HH=I targets.append(np.array([1, 0])) return targets def h_gate_unitary_deterministic(): """H-gate circuits reference unitaries.""" targets = [] # HH=I targets.append(np.eye(2)) return targets def h_gate_circuits_nondeterministic(final_measure=True): """X-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # H circuit = QuantumCircuit(*regs) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def h_gate_counts_nondeterministic(shots, hex_counts=True): """H-gate circuits reference counts.""" targets = [] if hex_counts: # H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # H targets.append({'0': shots / 2, '1': shots / 2}) return targets def h_gate_statevector_nondeterministic(): """H-gate circuits reference statevectors.""" targets = [] # H targets.append(np.array([1, 1]) / np.sqrt(2)) return targets def h_gate_unitary_nondeterministic(): """H-gate circuits reference unitaries.""" targets = [] # HH=I targets.append(np.array([[1, 1], [1, -1]]) / np.sqrt(2)) return targets # ========================================================================== # X-gate # ========================================================================== def x_gate_circuits_deterministic(final_measure=True): """X-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # X circuit = QuantumCircuit(*regs) circuit.x(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # XX = I circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.x(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HXH=Z circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.x(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def x_gate_counts_deterministic(shots, hex_counts=True): """X-gate circuits reference counts.""" targets = [] if hex_counts: # X targets.append({'0x1': shots}) # XX = I targets.append({'0x0': shots}) # HXH=Z targets.append({'0x0': shots}) else: # X targets.append({'1': shots}) # XX = I targets.append({'0': shots}) # HXH=Z targets.append({'0': shots}) return targets def x_gate_statevector_deterministic(): """X-gate circuits reference statevectors.""" targets = [] # X targets.append(np.array([0, 1])) # XX = I targets.append(np.array([1, 0])) # HXH=Z targets.append(np.array([1, 0])) return targets def x_gate_unitary_deterministic(): """X-gate circuits reference unitaries.""" targets = [] # X targets.append(np.array([[0, 1], [1, 0]])) # XX = I targets.append(np.eye(2)) # HXH=Z targets.append(np.array([[1, 0], [0, -1]])) return targets # ========================================================================== # Z-gate # ========================================================================== def z_gate_circuits_deterministic(final_measure=True): """Z-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Z alone circuit = QuantumCircuit(*regs) circuit.z(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HZH = X circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.z(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HZZH = I circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.z(qr) circuit.barrier(qr) circuit.z(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def z_gate_counts_deterministic(shots, hex_counts=True): """Z-gate circuits reference counts.""" targets = [] if hex_counts: # Z targets.append({'0x0': shots}) # HZH = X targets.append({'0x1': shots}) # HZZH = I targets.append({'0x0': shots}) else: # Z targets.append({'0': shots}) # HZH = X targets.append({'1': shots}) # HZZH = I targets.append({'0': shots}) return targets def z_gate_statevector_deterministic(): """Z-gate circuits reference statevectors.""" targets = [] # Z targets.append(np.array([1, 0])) # HZH = X targets.append(np.array([0, 1])) # HZZH = I targets.append(np.array([1, 0])) return targets def z_gate_unitary_deterministic(): """Z-gate circuits reference unitaries.""" targets = [] # Z targets.append(np.array([[1, 0], [0, -1]])) # HZH = X targets.append(np.array([[0, 1], [1, 0]])) # HZZH = I targets.append(np.eye(2)) return targets # ========================================================================== # Y-gate # ========================================================================== def y_gate_circuits_deterministic(final_measure=True): """Y-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Y circuit = QuantumCircuit(*regs) circuit.y(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # YY = I circuit = QuantumCircuit(*regs) circuit.y(qr) circuit.barrier(qr) circuit.y(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HYH = -Y circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.y(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def y_gate_counts_deterministic(shots, hex_counts=True): """Y-gate circuits reference counts.""" targets = [] if hex_counts: # Y targets.append({'0x1': shots}) # YY = I targets.append({'0x0': shots}) # HYH = -Y targets.append({'0x1': shots}) else: # Y targets.append({'1': shots}) # YY = I targets.append({'0': shots}) # HYH = -Y targets.append({'1': shots}) return targets def y_gate_statevector_deterministic(): """Y-gate circuits reference statevectors.""" targets = [] # Y targets.append(np.array([0, 1j])) # YY = I targets.append(np.array([1, 0])) # HYH = -Y targets.append(np.array([0, -1j])) return targets def y_gate_unitary_deterministic(): """Y-gate circuits reference unitaries.""" targets = [] # Y targets.append(np.array([[0, -1j], [1j, 0]])) # YY = I targets.append(np.eye(2)) # HYH = -Y targets.append(np.array([[0, 1j], [-1j, 0]])) return targets # ========================================================================== # S-gate # ========================================================================== def s_gate_circuits_deterministic(final_measure=True): """S-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # S circuit = QuantumCircuit(*regs) circuit.s(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # S.X circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.s(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HSSH = HZH = X circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.s(qr) circuit.barrier(qr) circuit.s(qr) circuit.barrier(qr) circuit.h(qr) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) return circuits def s_gate_counts_deterministic(shots, hex_counts=True): """S-gate circuits reference counts.""" targets = [] if hex_counts: # S targets.append({'0x0': shots}) # S.X targets.append({'0x1': shots}) # HSSH = HZH = X targets.append({'0x1': shots}) else: # S targets.append({'0': shots}) # S.X targets.append({'1': shots}) # HSSH = HZH = X targets.append({'1': shots}) return targets def s_gate_statevector_deterministic(): """S-gate circuits reference statevectors.""" targets = [] # S targets.append(np.array([1, 0])) # S.X targets.append(np.array([0, 1j])) # HSSH = HZH = X targets.append(np.array([0, 1])) return targets def s_gate_unitary_deterministic(): """S-gate circuits reference unitaries.""" targets = [] # S targets.append(np.diag([1, 1j])) # S.X targets.append(np.array([[0, 1], [1j, 0]])) # HSSH = HZH = X targets.append(np.array([[0, 1], [1, 0]])) return targets def s_gate_circuits_nondeterministic(final_measure=True): """S-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # SH circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.s(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HSH circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.s(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def s_gate_counts_nondeterministic(shots, hex_counts=True): """S-gate circuits reference counts.""" targets = [] if hex_counts: # S.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # H.S.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # S.H targets.append({'0': shots / 2, '1': shots / 2}) # H.S.H targets.append({'0': shots / 2, '1': shots / 2}) return targets def s_gate_statevector_nondeterministic(): """S-gate circuits reference statevectors.""" targets = [] # S.H targets.append(np.array([1, 1j]) / np.sqrt(2)) # H.S.H targets.append(np.array([1 + 1j, 1 - 1j]) / 2) return targets def s_gate_unitary_nondeterministic(): """S-gate circuits reference unitaries.""" targets = [] # S.H targets.append(np.array([[1, 1], [1j, -1j]]) / np.sqrt(2)) # H.S.H targets.append(np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]]) / 2) return targets # ========================================================================== # S^dagger-gate # ========================================================================== def sdg_gate_circuits_deterministic(final_measure=True): """Sdg-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Sdg circuit = QuantumCircuit(*regs) circuit.sdg(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Sdg.Sdg.H = H.Z.H = X circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.sdg(qr) circuit.barrier(qr) circuit.sdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Sdg.S.H = I circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.s(qr) circuit.barrier(qr) circuit.sdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def sdg_gate_counts_deterministic(shots, hex_counts=True): """Sdg-gate circuits reference counts.""" targets = [] if hex_counts: # Sdg targets.append({'0x0': shots}) # H.Sdg.Sdg.H = H.Z.H = X targets.append({'0x1': shots}) # H.Sdg.S.H = I targets.append({'0x0': shots}) else: # Sdg targets.append({'0': shots}) # H.Sdg.Sdg.H = H.Z.H = X targets.append({'1': shots}) # H.Sdg.S.H = I targets.append({'0': shots}) return targets def sdg_gate_statevector_deterministic(): """Sdg-gate circuits reference statevectors.""" targets = [] # Sdg targets.append(np.array([1, 0])) # H.Sdg.Sdg.H = H.Z.H = X targets.append(np.array([0, 1])) # H.Sdg.S.H = I targets.append(np.array([1, 0])) return targets def sdg_gate_unitary_deterministic(): """Sdg-gate circuits reference unitaries.""" targets = [] # Sdg targets.append(np.diag([1, -1j])) # H.Sdg.Sdg.H = H.Z.H = X targets.append(np.array([[0, 1], [1, 0]])) # H.Sdg.S.H = I targets.append(np.eye(2)) return targets def sdg_gate_circuits_nondeterministic(final_measure=True): """Sdg-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Sdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.sdg(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Sdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.sdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def sdg_gate_counts_nondeterministic(shots, hex_counts=True): """Sdg-gate circuits reference counts.""" targets = [] if hex_counts: # Sdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # H.Sdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # Sdg.H targets.append({'0': shots / 2, '1': shots / 2}) # H.Sdg.H targets.append({'0': shots / 2, '1': shots / 2}) return targets def sdg_gate_statevector_nondeterministic(): """Sdg-gate circuits reference statevectors.""" targets = [] # Sdg.H targets.append(np.array([1, -1j]) / np.sqrt(2)) # H.Sdg.H targets.append(np.array([1 - 1j, 1 + 1j]) / 2) return targets def sdg_gate_unitary_nondeterministic(): """Sdg-gate circuits reference unitaries.""" targets = [] # Sdg.H targets.append(np.array([[1, 1], [-1j, 1j]]) / np.sqrt(2)) # H.Sdg.H targets.append(np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]]) / 2) return targets
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Deutsch-Jozsa Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Deutsch-Jozsa" np.random.seed(0) verbose = False # saved circuits for display QC_ = None C_ORACLE_ = None B_ORACLE_ = None ############### Circuit Definition # Create a constant oracle, appending gates to given circuit def constant_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") output = np.random.randint(2) if output == 1: qc.x(input_size) global C_ORACLE_ if C_ORACLE_ == None or num_qubits <= 21: if num_qubits < 21: C_ORACLE_ = qc return qc # Create a balanced oracle. # Perform CNOTs with each input qubit as a control and the output bit as the target. # Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. def balanced_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") b_str = "10101010101010101010" # permit input_string up to 20 chars for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) qc.barrier() for qubit in range(input_size): qc.cx(qubit, input_size) qc.barrier() for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) global B_ORACLE_ if B_ORACLE_ == None or num_qubits <= 21: if num_qubits < 21: B_ORACLE_ = qc return qc # Create benchmark circuit def DeutschJozsa (num_qubits, type): # Size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qr = QuantumRegister(num_qubits) cr = ClassicalRegister(input_size) qc = QuantumCircuit(qr, cr, name=f"dj-{num_qubits}-{type}") for qubit in range(input_size): qc.h(qubit) qc.x(input_size) qc.h(input_size) qc.barrier() # Add a constant or balanced oracle function if type == 0: Uf = constant_oracle(input_size, num_qubits) else: Uf = balanced_oracle(input_size, num_qubits) qc.append(Uf, qr) qc.barrier() for qubit in range(num_qubits): qc.h(qubit) # uncompute ancilla qubit, not necessary for algorithm qc.x(input_size) qc.barrier() for i in range(input_size): qc.measure(i, i) # save smaller circuit and oracle subcircuit example for display global QC_ if QC_ == None or num_qubits <= 21: if num_qubits < 21: QC_ = qc # return a handle to the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the type, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, type, num_shots): # Size of input is one less than available qubits input_size = num_qubits - 1 if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For type {type} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) if type == 0: key = '0'*input_size else: key = '1'*input_size # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity def run(min_qubits=3, max_qubits=14, skip_qubits=1, max_circuits=3, num_shots=1000, backend_id='dm_simulator', provider_backend=None, exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # Validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # Create context identifier if context is None: context = f"{benchmark_name} Benchmark" # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) print("num_qubits ===== ", num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type), num_shots) metrics.store_metric(num_qubits, type, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, exec_options=exec_options, context=context) # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 # Determine number of circuits to execute for this group num_circuits = min(2, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # Loop over only 2 circuits for type in range(num_circuits): # Create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = DeutschJozsa(num_qubits, type).reverse_bits() # reverse_bits() is applying to handle the change in endianness print(f"DJ Circuit for qubit size of {num_qubits} and type {type} : \n{qc} ") metrics.store_metric(num_qubits, type, 'create_time', time.time() - ts) # Collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # Submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, type, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # Print a sample circuit # print("Sample Circuit:"); print(QC_ if QC_ is not None else " ... too large!") print("\nConstant Oracle 'Uf' ="); print(C_ORACLE_ if C_ORACLE_ is not None else " ... too large or not used!") print("\nBalanced Oracle 'Uf' ="); print(B_ORACLE_ if B_ORACLE_ is not None else " ... too large or not used!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': run()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from math import pi import numpy as np import rustworkx as rx from qiskit_nature.second_q.hamiltonians.lattices import ( BoundaryCondition, HyperCubicLattice, Lattice, LatticeDrawStyle, LineLattice, SquareLattice, TriangularLattice, ) from qiskit_nature.second_q.hamiltonians import FermiHubbardModel num_nodes = 11 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() line_lattice.draw_without_boundary() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC edge_parameter = 1.0 + 1.0j onsite_parameter = 1.0 line_lattice = LineLattice( num_nodes=num_nodes, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(line_lattice.graph.weighted_edge_list()) line_lattice.to_adjacency_matrix() line_lattice.to_adjacency_matrix(weighted=True) rows = 5 cols = 4 boundary_condition = BoundaryCondition.OPEN square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 edge_parameter = (1.0, 1.0 + 1.0j) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction onsite_parameter = 1.0 square_lattice = SquareLattice( rows=rows, cols=cols, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(square_lattice.graph.weighted_edge_list()) size = (3, 4, 5) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.OPEN, BoundaryCondition.OPEN, ) cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition) # function for setting the positions def indextocoord_3d(index: int, size: tuple, angle) -> list: z = index // (size[0] * size[1]) a = index % (size[0] * size[1]) y = a // size[0] x = a % size[0] vec_x = np.array([1, 0]) vec_y = np.array([np.cos(angle), np.sin(angle)]) vec_z = np.array([0, 1]) return_coord = x * vec_x + y * vec_y + z * vec_z return return_coord.tolist() pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))]) cubic_lattice.draw(style=LatticeDrawStyle(pos=pos)) rows = 4 cols = 3 boundary_condition = BoundaryCondition.OPEN triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() rows = 4 cols = 3 boundary_condition = BoundaryCondition.PERIODIC triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() graph = rx.PyGraph(multigraph=False) # multigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) # make a lattice general_lattice = Lattice(graph) set(general_lattice.graph.weighted_edge_list()) general_lattice.draw() general_lattice.draw(self_loop=True) general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True)) square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC) t = -1.0 # the interaction parameter v = 0.0 # the onsite potential u = 5.0 # the interaction parameter U fhm = FermiHubbardModel( square_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) ham = fhm.second_q_op().simplify() print(ham) graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix. u = 5.0 # the interaction parameter U fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u) ham = fhm.second_q_op().simplify() print(ham) from qiskit_nature.second_q.problems import LatticeModelProblem num_nodes = 4 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) fhm = FermiHubbardModel( line_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) lmp = LatticeModelProblem(fhm) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper numpy_solver = NumPyMinimumEigensolver() qubit_mapper = JordanWignerMapper() calc = GroundStateEigensolver(qubit_mapper, numpy_solver) res = calc.solve(lmp) print(res) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Depth pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import CountOpsLongestPath from qiskit.test import QiskitTestCase class TestCountOpsLongestPathPass(QiskitTestCase): """Tests for CountOpsLongestPath analysis methods.""" def test_empty_dag(self): """Empty DAG has empty counts.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = CountOpsLongestPath() _ = pass_.run(dag) self.assertDictEqual(pass_.property_set["count_ops_longest_path"], {}) def test_just_qubits(self): """A dag with 9 operations (3 CXs, 2Xs, 2Ys and 2 Hs) on the longest path """ # ┌───┐┌───┐┌───┐ # q0_0: ──■──┤ X ├┤ Y ├┤ H ├──■───────────────────■── # ┌─┴─┐└───┘└───┘└───┘┌─┴─┐┌───┐┌───┐┌───┐┌─┴─┐ # q0_1: ┤ X ├───────────────┤ X ├┤ X ├┤ Y ├┤ H ├┤ X ├ # └───┘ └───┘└───┘└───┘└───┘└───┘ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) circuit.y(qr[1]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = CountOpsLongestPath() _ = pass_.run(dag) count_ops = pass_.property_set["count_ops_longest_path"] self.assertDictEqual(count_ops, {"cx": 3, "x": 2, "y": 2, "h": 2}) if __name__ == "__main__": unittest.main()
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import qiskit versions = qiskit.__qiskit_version__ print("The version of Qiskit is",versions['qiskit']) print() print("The version of each component:") for key in versions: print(key,"->",versions[key]) !pip install qiskit[visualization] --user #!pip install -U qiskit --user #!pip uninstall qiskit # import the objects from qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # create a quantum circuit and its register objects qreg = QuantumRegister(2) # quantum register with two quantum bits creg = ClassicalRegister(2) # classical register with two classical bit circuit = QuantumCircuit(qreg,creg) # quantum circuit composed by a quantum register and a classical register # apply a Hadamard gate to the first qubit circuit.h(qreg[0]) # set the second qubit to state |1> circuit.x(qreg[1]) # apply CNOT(first_qubit,second_qubit) circuit.cx(qreg[0],qreg[1]) # measure the both qubits circuit.measure(qreg,creg) print("The execution of the cell was completed, and the circuit was created :)") # draw circuit circuit.draw(output='mpl') # the output will be a "matplotlib.Figure" object ## execute the circuit 1024 times job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024) # get the result counts = job.result().get_counts(circuit) print(counts)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Base state fidelity interface """ from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Sequence, Mapping import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from ..algorithm_job import AlgorithmJob from .state_fidelity_result import StateFidelityResult class BaseStateFidelity(ABC): r""" An interface to calculate state fidelities (state overlaps) for pairs of (parametrized) quantum circuits. The calculation depends on the particular fidelity method implementation, but can be always defined as the state overlap: .. math:: |\langle\psi(x)|\phi(y)\rangle|^2 where :math:`x` and :math:`y` are optional parametrizations of the states :math:`\psi` and :math:`\phi` prepared by the circuits ``circuit_1`` and ``circuit_2``, respectively. """ def __init__(self) -> None: # use cache for preventing unnecessary circuit compositions self._circuit_cache: Mapping[tuple[int, int], QuantumCircuit] = {} @staticmethod def _preprocess_values( circuits: QuantumCircuit | Sequence[QuantumCircuit], values: Sequence[float] | Sequence[Sequence[float]] | None = None, ) -> Sequence[Sequence[float]]: """ Checks whether the passed values match the shape of the parameters of the corresponding circuits and formats values to 2D list. Args: circuits: List of circuits to be checked. values: Parameter values corresponding to the circuits to be checked. Returns: A 2D value list if the values match the circuits, or an empty 2D list if values is None. Raises: ValueError: if the number of parameter values doesn't match the number of circuit parameters TypeError: if the input values are not a sequence. """ if isinstance(circuits, QuantumCircuit): circuits = [circuits] if values is None: for circuit in circuits: if circuit.num_parameters != 0: raise ValueError( f"`values` cannot be `None` because circuit <{circuit.name}> has " f"{circuit.num_parameters} free parameters." ) return [[]] else: # Support ndarray if isinstance(values, np.ndarray): values = values.tolist() if len(values) > 0 and isinstance(values[0], np.ndarray): values = [v.tolist() for v in values] if not isinstance(values, Sequence): raise TypeError( f"Expected a sequence of numerical parameter values, " f"but got input type {type(values)} instead." ) # ensure 2d if len(values) > 0 and not isinstance(values[0], Sequence) or len(values) == 0: values = [values] return values def _check_qubits_match(self, circuit_1: QuantumCircuit, circuit_2: QuantumCircuit) -> None: """ Checks that the number of qubits of 2 circuits matches. Args: circuit_1: (Parametrized) quantum circuit. circuit_2: (Parametrized) quantum circuit. Raises: ValueError: when ``circuit_1`` and ``circuit_2`` don't have the same number of qubits. """ if circuit_1.num_qubits != circuit_2.num_qubits: raise ValueError( f"The number of qubits for the first circuit ({circuit_1.num_qubits}) " f"and second circuit ({circuit_2.num_qubits}) are not the same." ) @abstractmethod def create_fidelity_circuit( self, circuit_1: QuantumCircuit, circuit_2: QuantumCircuit ) -> QuantumCircuit: """ Implementation-dependent method to create a fidelity circuit from 2 circuit inputs. Args: circuit_1: (Parametrized) quantum circuit. circuit_2: (Parametrized) quantum circuit. Returns: The fidelity quantum circuit corresponding to ``circuit_1`` and ``circuit_2``. """ raise NotImplementedError def _construct_circuits( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], ) -> Sequence[QuantumCircuit]: """ Constructs the list of fidelity circuits to be evaluated. These circuits represent the state overlap between pairs of input circuits, and their construction depends on the fidelity method implementations. Args: circuits_1: (Parametrized) quantum circuits. circuits_2: (Parametrized) quantum circuits. Returns: List of constructed fidelity circuits. Raises: ValueError: if the length of the input circuit lists doesn't match. """ if isinstance(circuits_1, QuantumCircuit): circuits_1 = [circuits_1] if isinstance(circuits_2, QuantumCircuit): circuits_2 = [circuits_2] if len(circuits_1) != len(circuits_2): raise ValueError( f"The length of the first circuit list({len(circuits_1)}) " f"and second circuit list ({len(circuits_2)}) is not the same." ) circuits = [] for (circuit_1, circuit_2) in zip(circuits_1, circuits_2): # TODO: improve caching, what if the circuit is modified without changing the id? circuit = self._circuit_cache.get((id(circuit_1), id(circuit_2))) if circuit is not None: circuits.append(circuit) else: self._check_qubits_match(circuit_1, circuit_2) # re-parametrize input circuits # TODO: make smarter checks to avoid unnecesary reparametrizations parameters_1 = ParameterVector("x", circuit_1.num_parameters) parametrized_circuit_1 = circuit_1.assign_parameters(parameters_1) parameters_2 = ParameterVector("y", circuit_2.num_parameters) parametrized_circuit_2 = circuit_2.assign_parameters(parameters_2) circuit = self.create_fidelity_circuit( parametrized_circuit_1, parametrized_circuit_2 ) circuits.append(circuit) # update cache self._circuit_cache[id(circuit_1), id(circuit_2)] = circuit return circuits def _construct_value_list( self, circuits_1: Sequence[QuantumCircuit], circuits_2: Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, ) -> list[float]: """ Preprocesses input parameter values to match the fidelity circuit parametrization, and return in list format. Args: circuits_1: (Parametrized) quantum circuits preparing the first list of quantum states. circuits_2: (Parametrized) quantum circuits preparing the second list of quantum states. values_1: Numerical parameters to be bound to the first circuits. values_2: Numerical parameters to be bound to the second circuits. Returns: List of parameter values for fidelity circuit. """ values_1 = self._preprocess_values(circuits_1, values_1) values_2 = self._preprocess_values(circuits_2, values_2) values = [] if len(values_2[0]) == 0: values = list(values_1) elif len(values_1[0]) == 0: values = list(values_2) else: for (val_1, val_2) in zip(values_1, values_2): values.append(val_1 + val_2) return values @abstractmethod def _run( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, **options, ) -> StateFidelityResult: r""" Computes the state overlap (fidelity) calculation between two (parametrized) circuits (first and second) for a specific set of parameter values (first and second). Args: circuits_1: (Parametrized) quantum circuits preparing :math:`|\psi\rangle`. circuits_2: (Parametrized) quantum circuits preparing :math:`|\phi\rangle`. values_1: Numerical parameters to be bound to the first set of circuits values_2: Numerical parameters to be bound to the second set of circuits. options: Primitive backend runtime options used for circuit execution. The order of priority is\: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. Returns: The result of the fidelity calculation. """ raise NotImplementedError def run( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, **options, ) -> AlgorithmJob: r""" Runs asynchronously the state overlap (fidelity) calculation between two (parametrized) circuits (first and second) for a specific set of parameter values (first and second). This calculation depends on the particular fidelity method implementation. Args: circuits_1: (Parametrized) quantum circuits preparing :math:`|\psi\rangle`. circuits_2: (Parametrized) quantum circuits preparing :math:`|\phi\rangle`. values_1: Numerical parameters to be bound to the first set of circuits. values_2: Numerical parameters to be bound to the second set of circuits. options: Primitive backend runtime options used for circuit execution. The order of priority is\: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. Returns: Primitive job for the fidelity calculation. The job's result is an instance of ``StateFidelityResult``. """ job = AlgorithmJob(self._run, circuits_1, circuits_2, values_1, values_2, **options) job.submit() return job def _truncate_fidelities(self, fidelities: Sequence[float]) -> Sequence[float]: """ Ensures fidelity result in [0,1]. Args: fidelities: Sequence of raw fidelity results. Returns: List of truncated fidelities. """ return np.clip(fidelities, 0, 1).tolist()
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.providers import JobStatus from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.providers.aer.noise import NoiseModel from qiskit.tools.visualization import plot_histogram from math import * import import_ipynb import numpy as np import math import itertools from network_setup import * # Helper Functions def find_num_states(numprobs, in_edges): if in_edges == 0: # if parent node numstates = numprobs elif in_edges > 0: # if child node numstates = (numprobs/(2**(in_edges+1))) * 2 return numstates def find_numstates_parents(graph, parentvarnames): """Eqn 21 from https://arxiv.org/pdf/2004.14803.pdf""" numstates_parents = 0 for i in range(len(parentvarnames)): parent = parentvarnames[i] parentprobs = graph[parent] numprobs = len(parentprobs[1]) # number of states if parent node, number of conditional states if child node in_edges = len(graph[parent][0]) # aka num of parents of this parent numstates_parents += find_num_states(numprobs, in_edges) return numstates_parents #TODO assertAlmostEqual(angle_from_probability(0.2, 0.8), 2.2143) def angle_from_probability(p0, p1): '''Equation 20 from https://arxiv.org/pdf/2004.14803.pdf''' angle = 2 * atan2(sqrt(p1), sqrt(p0)) return angle def num_qbits_needed_general(graph): '''Equation 22 from https://arxiv.org/pdf/2004.14803.pdf''' sumterm = 0 ancillaterms = [] varnum = 0 for var in graph: probs = graph[var] numprobs = len(probs[1]) # number of states if parent node, number of conditional states if child node in_edges = len(graph[var][0]) # aka num of parents numstates = find_num_states(numprobs, in_edges) sumterm += math.ceil(np.log2(numstates)) if in_edges > 0: parentvarnames = graph[var][0] # list of parent names numstates_parents = find_numstates_parents(graph, parentvarnames) ancillaterm = numstates_parents/2 + math.ceil(np.log2(numstates)) - 1 ancillaterms.append(ancillaterm) qbits = sumterm + max(ancillaterms) -1 # equation (22) WITH AN EXTRA -1 cbits = sumterm # number of measurements return (qbits, cbits) def num_qbits_needed(graph): '''Equation 15 from https://arxiv.org/pdf/2004.14803.pdf''' max_edges = -1 for state in graph: in_edges = len(graph[state][0]) # aka num of parents if in_edges > max_edges: max_edges = in_edges qbits = len(graph) + max_edges - 1 # equation (15) cbits = len(graph) # number of measurements return (qbits, cbits) def run_circuit(circuit, output_file='results', draw_circuit=True, use_sim=True, use_noise=False, use_qcomp=False, shots=1024): if draw_circuit: %config InlineBackend.figure_format circuit.draw(output='mpl') if use_noise or use_qcomp: IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_qasm_simulator') if use_sim: simulator = Aer.get_backend('qasm_simulator') if use_noise: noise_model = NoiseModel.from_backend(qcomp) basis_gates = noise_model.basis_gates coupling_map = qcomp.configuration().coupling_map job = execute(circuit, backend=simulator, coupling_map=coupling_map, noise_model=noise_model, basis_gates=basis_gates, shots=shots) else: job = execute(circuit, backend=simulator, shots=shots) print(job.result().get_counts()) plot_histogram(job.result().get_counts()).savefig(output_file+"-sim.png") if use_qcomp: job = execute(circuit, backend=qcomp, shots=shots) job_monitor(job) if(job.status() == JobStatus.ERROR): print("Error: Check with IBMQ") print(job.result().get_counts()) plot_histogram(job.result().get_counts()).savefig(output_file+'-qcomp.png') return job.result() def check_node_processed(bit_assignment, node): # split node into states states = node.replace(' ','').split(',') if len(states) <= 2: # qbit has been assigned return node in bit_assignment else: # this means multistate qbits have been processed (down to LSB) return (node +'q0') in bit_assignment def add_cnry(circuit, n, angle, control_bits, target, ancilla_bits): ''' Creates generalized cny gate for any n. circuit: existing circuit to modify n: number of control bits required (number of "C"s wanted for this gate) angle: angle to rotate by (rad) control_bits: list (len n) target: qbit you want to rotate ancilla_bits: list (len n-1); these are left clean (in same state as initially) Note: could also try rewriting using Qiskit's built-in mcx gates https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.mcx.html https://qiskit.org/documentation/tutorials/circuits_advanced/1_advanced_circuits.html ''' # TODO Qiskit has some of these higher order gates implemented # Check that Qiskits version matches whats described in the paper and change to those if n == 1: circuit.cry(angle,control_bits[0],target) return circuit # assert some things are true assert n >= 2 assert len(control_bits) == n assert len(ancilla_bits) >= n-1 #circuit.barrier() # for visualization # hardcode first ccx gate circuit.ccx(control_bits[0], control_bits[1], ancilla_bits[0]) # loop to create ccx gates for i in range(2, n): circuit.ccx(control_bits[i], ancilla_bits[i-2], ancilla_bits[i-1]) # add rotate block circuit.cry(angle, ancilla_bits[n-2], target) # loop to create remaining ccx gates for i in range(n-1, 1, -1): circuit.ccx(control_bits[i], ancilla_bits[i-2], ancilla_bits[i-1]) # hardcode last ccx gate circuit.ccx(control_bits[0], control_bits[1], ancilla_bits[0]) #circuit.barrier() # for visualization return circuit def controlled_m_qbit_rotation(circuit, control_qbits, target_qbits, probs, ancilla_bits): ''' From Fig. 9 in paper recursive to build m-1 rotation (decompose rotation gate)''' if len(target_qbits) == 0: return circuit # how many target qbits do we have? num_targets = len(target_qbits) p0 = 0 for i in range(2**(num_targets-1)): # prob that the qbit is 0 p0 += probs[i] p1 = 0 for i in range(2**(num_targets-1), min(len(probs), 2**(num_targets))): p1 += probs[i] angle = angle_from_probability(p0, p1) # add controlled rotation gate qc = add_cnry(circuit, len(control_qbits), angle, control_qbits, target_qbits[0], ancilla_bits[:(len(control_qbits)-1)]) # recursively add another controlled m rot for MSB = 1 qc = controlled_m_qbit_rotation(circuit, control_qbits+[target_qbits[0]], target_qbits[1:], probs[2**(num_targets-1):], ancilla_bits) # now add an x gate qc.x(target_qbits[0]) # add another controlled m rot for MSB = 0 qc = controlled_m_qbit_rotation(circuit, control_qbits+[target_qbits[0]], target_qbits[1:], probs[:2**(num_targets-1)], ancilla_bits) # add one last x gate qc.x(target_qbits[0]) return qc # This is the heavy lifter of the project # This function turns a graph into the quantum circuit def create_circuit(graph, qc, starting_qbit=0, ancilla_bits=[]): # Create a dictionary to hold which states are assigned to which qubits and counters to track the allocation bit_assignment = {} last_free_qbit = qc.num_qubits-1 next_free_qbit = starting_qbit # Allocate ancilla_bits # Count number of qbits needed and the remaining bits are ancillia needed_qbits = 0 for node in graph: num_states = len(node.split(',')) if num_states == 1: num_states = 2 needed_qbits += ceil(log2(num_states)) if ancilla_bits == []: for i in range(qc.num_qubits-needed_qbits): ancilla_bits.append(last_free_qbit) last_free_qbit -= 1 else: pass # TODO Assert we have enough qubits ############################## PARENTLESS/ROOT NODES ############################## # loop and find the parentless/root nodes, assign their rotations first # States are ',' seperated for node in graph: number_of_parents = len(graph[node][0]) if number_of_parents == 0: probs = graph[node][1] # how many states does this parentless/root node have? root_states = node.replace(' ','').split(',') if len(root_states) <= 2: # root node has 2 states, simple controlled rotate qc.ry(angle_from_probability(probs[0], probs[1]), next_free_qbit) # keep track of what node is what qbit bit_assignment[node] = next_free_qbit next_free_qbit += 1 else: # root node has 2+ states needed_qbits = ceil(log2(len(root_states))) sub_start_qbit = next_free_qbit # bit allocation time for i in range(needed_qbits): bit_assignment[node+'q'+str(i)] = next_free_qbit next_free_qbit += 1 # Create a graph for the recursive call and populate it sub_graph = {} sub_probs_list = [] # now calculate rotations for i in range(needed_qbits-1, -1, -1): sub_parents_list = [] sub_probs_list = [] for j in range(needed_qbits-1, i, -1): # get a list of sub parents # Sub_parent names are just the index of the qubit, not symbolic sub_parents_list.append(str(j)) # Calculate marginal probabilities from subsets of the table for k in range(0, len(probs), int(2**(i+1))): subsubsub_probif0 = 0 subsubsub_probif1 = 0 for x in range(k, k+int(2**(i)), 1): subsubsub_probif0 += probs[x] for x in range(k+int(2**(i)), min(int(k+2**(i+1)), len(probs)), 1): subsubsub_probif1 += probs[x] total = subsubsub_probif0 + subsubsub_probif1 sub_marg_0 = subsubsub_probif0 / total sub_marg_1 = subsubsub_probif1 / total sub_probs_list.append(sub_marg_0) sub_probs_list.append(sub_marg_1) # now we have completete sub parent and sub prob lists sub_graph[str(i)] = (sub_parents_list, sub_probs_list) # Recursively call this function to implement the sub graph (qc, _, ancilla_bits) = create_circuit(sub_graph,qc, sub_start_qbit, ancilla_bits) ############################## PARENTED NODES ############################## # now deal with all other parented nodes qc.barrier() # for visualization # loop and find each node that has all its parents complete and add it # TODO: A topological sort will prevent useless looping and this while True block while True: # loop until no states are added found_new = False for node in graph: # Get all the states for this node states = node.replace(' ','').split(',') # Check that this node is unprocessed but all it's parents are if check_node_processed(bit_assignment, node): # node has been processed continue all_parents = True # flag to detect if all parents are processed for parent in graph[node][0]: # check if parent has been processed if not check_node_processed(bit_assignment, parent): # parent has not been processed :( try a new node all_parents = False break if not all_parents: # check next node continue # otherwise, now we found a node we are ready to process! number_of_parents = len(graph[node][0]) found_new = True # do bit assignments if len(states) <= 2: needed_qbits = 1 bit_assignment[node] = next_free_qbit target_qbits = [next_free_qbit] next_free_qbit += 1 else: # node has 2+ states needed_qbits = ceil(log2(len(states))) sub_start_qbit = next_free_qbit target_qbits = [] # bit allocation time for i in range(needed_qbits): bit_assignment[node+'q'+str(i)] = next_free_qbit target_qbits.append(next_free_qbit) next_free_qbit += 1 # count number of columns in prob table # This is done by counting the number of states in the parents and the child # This determines the implied shape of the probability table # TODO: The table should just have this shape count = 1 parent_state_enumeration = [] for parent_states in graph[node][0]: parent_state = parent_states.replace(' ','').split(',') if len(parent_state) == 1: parent_state_enumeration.append([0,1]) count *= 2 else: count *= len(parent_state) parent_state_enumeration.append([i for i in range(len(parent_state))]) parent_state_total = itertools.product(*parent_state_enumeration) # Now encode each collumn in the probability table into the circuit for i, parent_state_combo in enumerate(parent_state_total): ########## ADD FIRST ROW OF X GATES IF PARENT QUBIT IS 0 ########## assert len(parent_state_combo) == number_of_parents all_parent_qbits = [] # loop through node's parents for j, parent in enumerate(graph[node][0]): # convert to binary string (on a per parent basis) num_parent_bits = ceil(log2(len(parent.split(',')))) # This allows 2 state nodes to optionally not have a comma if len(parent.split(',')) == 1: num_parent_bits = 1 #FIXME: There has to be a better way to detect where to apply X gates current_state = bin(parent_state_combo[j])[2:].zfill(num_parent_bits)[::-1] # apply x gates to each one of the qbits for each parent (going down) if num_parent_bits == 1: # only one bit all_parent_qbits.append(bit_assignment[parent]) if current_state == '0': # add an x gate qc.x(bit_assignment[parent]) else: # Multibit parent, selectivly X for k in range(num_parent_bits): current_parent_bit = bit_assignment[parent+'q'+str(k)] all_parent_qbits.append(current_parent_bit) if current_state[k] == '0': qc.x(current_parent_bit) ########## ADD ROTATION GATES ########## this_num_states = len(states) if this_num_states == 1: this_num_states = 2 probs = graph[node][1] # Extract this collumn of probabilities this_state_probs = probs[(i*this_num_states):(i+1)*this_num_states] qc.barrier() qc = controlled_m_qbit_rotation(qc, all_parent_qbits, target_qbits, this_state_probs, ancilla_bits) qc.barrier() ########## ADD SECOND ROW OF X GATES ########## # loop through node's parents and add the complementary X gates as done above # TODO This should be a function, not repeated code for j, parent in enumerate(graph[node][0]): # convert to binary string (on a per parent basis) num_parent_bits = ceil(log2(len(parent.split(',')))) if len(parent.split(',')) == 1: num_parent_bits = 1 current_state = bin(parent_state_combo[j])[2:].zfill(num_parent_bits)[::-1] # apply x gates going back up if num_parent_bits == 1: # only one bit if current_state == '0': # add an x gate qc.x(bit_assignment[parent]) else: for k in range(num_parent_bits): current_parent_bit = bit_assignment[parent+'q'+str(k)] if current_state[k] == '0': # add an x gate qc.x(current_parent_bit) qc.barrier() # done!!! if not found_new: # completed a full loop over the nodes and all were added break # Report Bit Assignments, also returned print(bit_assignment) return (qc, bit_assignment, ancilla_bits) def make_circuit(network, size=(4,3), draw = True): graph = build_graph(network) qc = QuantumCircuit(size[0], size[1]) qc, bits, _ = create_circuit(graph, qc) if draw == True: qc.draw(output="mpl") for i in range(len(bits)): qc.measure(i,i) return qc #change lesser here to alabio or mallard to try different example covid models #Mallard requires 16 qubits and has 10 measurable states, size=(4,3) #Alabio requires size=(32,16) qc = make_circuit(get_lesser_model_nodes, size=(4,3)) result = run_circuit(qc, "lesser_model", draw_circuit=True, shots=1024, use_sim=True, use_qcomp=False, use_noise=False) # Here are the first 2 examples from the paper # The paper provides full circuits for these graphs that can be compared against to ensure accuracy # size = (5,4) oil_graph = {'IR': ([], [.75, .25]), # From 2004.14803, Fig 10 'SM': (['IR'], [.3, .7, .8, .2]), #P(0|!A), P(1|!A), P(0|A), P(1|A) 'OI': ([], [.6, .4]), 'SP': (['OI', 'SM'], [.9, .1, .5, .5, .4, .6, .2, .8]) } # size = (12,10) liquidity = {'X1': (['X9'], [.488,.552,.067,.933]), 'X2': (['X4'], [.76,.24,1,0]), 'X3': (['X5'], [1,0,.949,.051]), 'X4': (['X9', 'X1'], [.151,.849,.874,.126,1,0,1,0]), 'X5': (['X8','X4'],[0,1,0,1,.723,.277,.311,.689]), 'X6': ([], [.98,.02]), 'X7': (['X6'],[.988,.012,.429,.571]), 'X8': (['X7'],[.006,.994,.875,.125]), 'X9': (['X8'],[0,1,.982,.018]), 'X10': (['X4','X2','X1'],[.684,.316,0,1,0,1,.474,.526,1,0,0,1,.481,.519,1,0]) }
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Linear-depth Multicontrolled Special Unitary """ from typing import Union, List import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library import RZGate, RYGate from qiskit.circuit.library import UnitaryGate from qiskit.synthesis import OneQubitEulerDecomposer from qiskit.circuit import Gate, Qubit from qclib.gates.mcx import LinearMcx, McxVchainDirty from qclib.gates.util import check_su2, apply_ctrl_state, isclose # pylint: disable=protected-access class Ldmcsu(Gate): """ Linear depth Multi-Controlled Gate for Special Unitary ------------------------------------------------ Multicontrolled gate decomposition with linear cost. `unitary` must be a SU(2) matrix. """ def __init__(self, unitary, num_controls, ctrl_state: str = None): check_su2(unitary) self.unitary = unitary self.controls = QuantumRegister(num_controls) self.target = QuantumRegister(1) self.num_controls = num_controls + 1 self.ctrl_state = ctrl_state super().__init__("ldmcsu", self.num_controls, [], "ldmcsu") def _define(self): self.definition = QuantumCircuit(self.controls, self.target) is_main_diag_real = isclose(self.unitary[0, 0].imag, 0.0) and isclose( self.unitary[1, 1].imag, 0.0 ) is_secondary_diag_real = isclose(self.unitary[0, 1].imag, 0.0) and isclose( self.unitary[1, 0].imag, 0.0 ) if not is_main_diag_real and not is_secondary_diag_real: # U = V D V^-1, where the entries of the diagonal D are the eigenvalues # `eig_vals` of U and the column vectors of V are the eigenvectors # `eig_vecs` of U. These columns are orthonormal and the main diagonal # of V is real-valued. eig_vals, eig_vecs = np.linalg.eig(self.unitary) x_vecs, z_vecs = self._get_x_z(eig_vecs) self.half_linear_depth_mcv( x_vecs, z_vecs, self.controls, self.target, self.ctrl_state, inverse=True, ) self.linear_depth_mcv( np.diag(eig_vals), self.controls, self.target, self.ctrl_state, general_su2_optimization=True, ) self.half_linear_depth_mcv( x_vecs, z_vecs, self.controls, self.target, self.ctrl_state ) else: if not is_secondary_diag_real: self.definition.h(self.target) self.linear_depth_mcv(self.unitary, self.controls, self.target, self.ctrl_state) if not is_secondary_diag_real: self.definition.h(self.target) @staticmethod def _get_x_z(su2): is_secondary_diag_real = isclose(su2[0, 1].imag, 0.0) and isclose( su2[1, 0].imag, 0.0 ) if is_secondary_diag_real: x_value = su2[0, 1] z_value = su2[1, 1] else: x_value = -su2[0, 1].real z_value = su2[1, 1] - su2[0, 1].imag * 1.0j return x_value, z_value @staticmethod def _compute_gate_a(x_value, z_value): if x_value == 0: alpha = (z_value + 0j) ** (1 / 4) beta = 0.0 else: alpha_r = np.sqrt((np.sqrt((z_value.real + 1.0) / 2.0) + 1.0) / 2.0) alpha_i = z_value.imag / ( 2.0 * np.sqrt((z_value.real + 1.0) * (np.sqrt((z_value.real + 1.0) / 2.0) + 1.0)) ) alpha = alpha_r + 1.0j * alpha_i beta = x_value / ( 2.0 * np.sqrt((z_value.real + 1.0) * (np.sqrt((z_value.real + 1.0) / 2.0) + 1.0)) ) s_op = np.array([[alpha, -np.conj(beta)], [beta, np.conj(alpha)]]) return s_op def linear_depth_mcv( self, su2_unitary, controls: Union[QuantumRegister, List[Qubit]], target: Qubit, ctrl_state: str = None, general_su2_optimization=False, ): """ Theorem 1 - https://arxiv.org/pdf/2302.06377.pdf """ # S gate definition x_value, z_value = self._get_x_z(su2_unitary) op_a = Ldmcsu._compute_gate_a(x_value, z_value) gate_a = UnitaryGate(op_a) num_ctrl = len(controls) k_1 = int(np.ceil(num_ctrl / 2.0)) k_2 = int(np.floor(num_ctrl / 2.0)) ctrl_state_k_1 = None ctrl_state_k_2 = None if ctrl_state is not None: ctrl_state_k_1 = ctrl_state[::-1][:k_1][::-1] ctrl_state_k_2 = ctrl_state[::-1][k_1:][::-1] if not general_su2_optimization: mcx_1 = McxVchainDirty(k_1, ctrl_state=ctrl_state_k_1).definition self.definition.append( mcx_1, controls[:k_1] + controls[k_1 : 2 * k_1 - 2] + [target] ) self.definition.append(gate_a, [target]) mcx_2 = McxVchainDirty( k_2, ctrl_state=ctrl_state_k_2, action_only=general_su2_optimization ).definition self.definition.append( mcx_2.inverse(), controls[k_1:] + controls[k_1 - k_2 + 2 : k_1] + [target] ) self.definition.append(gate_a.inverse(), [target]) mcx_3 = McxVchainDirty(k_1, ctrl_state=ctrl_state_k_1).definition self.definition.append( mcx_3, controls[:k_1] + controls[k_1 : 2 * k_1 - 2] + [target] ) self.definition.append(gate_a, [target]) mcx_4 = McxVchainDirty(k_2, ctrl_state=ctrl_state_k_2).definition self.definition.append( mcx_4, controls[k_1:] + controls[k_1 - k_2 + 2 : k_1] + [target] ) self.definition.append(gate_a.inverse(), [target]) def half_linear_depth_mcv( self, x_value, z_value, controls: Union[QuantumRegister, List[Qubit]], target: Qubit, ctrl_state: str = None, inverse: bool = False, ): """ Theorem 4 - https://arxiv.org/pdf/2302.06377.pdf """ alpha_r = np.sqrt((z_value.real + 1.0) / 2.0) alpha_i = z_value.imag / np.sqrt(2 * (z_value.real + 1.0)) alpha = alpha_r + 1.0j * alpha_i beta = x_value / np.sqrt(2 * (z_value.real + 1.0)) s_op = np.array([[alpha, -np.conj(beta)], [beta, np.conj(alpha)]]) # S gate definition s_gate = UnitaryGate(s_op) # Hadamard equivalent definition h_gate = UnitaryGate(np.array([[-1, 1], [1, 1]]) * 1 / np.sqrt(2)) num_ctrl = len(controls) k_1 = int(np.ceil(num_ctrl / 2.0)) k_2 = int(np.floor(num_ctrl / 2.0)) ctrl_state_k_1 = None ctrl_state_k_2 = None if ctrl_state is not None: ctrl_state_k_1 = ctrl_state[::-1][:k_1][::-1] ctrl_state_k_2 = ctrl_state[::-1][k_1:][::-1] if inverse: self.definition.h(target) self.definition.append(s_gate, [target]) mcx_2 = McxVchainDirty( k_2, ctrl_state=ctrl_state_k_2, action_only=True ).definition self.definition.append( mcx_2, controls[k_1:] + controls[k_1 - k_2 + 2 : k_1] + [target] ) self.definition.append(s_gate.inverse(), [target]) self.definition.append(h_gate, [target]) else: mcx_1 = McxVchainDirty(k_1, ctrl_state=ctrl_state_k_1).definition self.definition.append( mcx_1, controls[:k_1] + controls[k_1 : 2 * k_1 - 2] + [target] ) self.definition.append(h_gate, [target]) self.definition.append(s_gate, [target]) mcx_2 = McxVchainDirty(k_2, ctrl_state=ctrl_state_k_2).definition self.definition.append( mcx_2, controls[k_1:] + controls[k_1 - k_2 + 2 : k_1] + [target] ) self.definition.append(s_gate.inverse(), [target]) self.definition.h(target) @staticmethod def ldmcsu( circuit, unitary, controls: Union[QuantumRegister, List[Qubit]], target: Qubit, ctrl_state: str = None, ): """ Apply multi-controlled SU(2) https://arxiv.org/abs/2302.06377 """ circuit.append( Ldmcsu(unitary, len(controls), ctrl_state=ctrl_state), [*controls, target] ) class LdMcSpecialUnitary(Gate): """ Linear-depth Multicontrolled Special Unitary -------------------------------------------- Implements the gate decompostion of any gate in SU(2) with linear depth (Ld) presented in Lemma 7.9 in Barenco et al., 1995 (arXiv:quant-ph/9503016) with optimizations from Theorem 5 of Iten et al., 2016 (arXiv:1501.06911) """ def __init__(self, unitary, num_controls, ctrl_state=None): if not check_su2(unitary): raise ValueError("Operator must be in SU(2)") self.unitary = np.array(unitary, dtype=complex) if num_controls > 0: self.control_qubits = QuantumRegister(num_controls) else: self.control_qubits = [] self.target_qubit = QuantumRegister(1) self.num_qubits = num_controls + 1 self.ctrl_state = ctrl_state if self.ctrl_state is None: self.ctrl_state = "1" * num_controls super().__init__("ldmc_su2", self.num_qubits, [], "LdMcSu2") @staticmethod def get_abc_operators(beta, gamma, delta): """ Creates A,B and C matrices such that ABC = I """ # A a_rz = RZGate(beta).to_matrix() a_ry = RYGate(gamma / 2).to_matrix() a_matrix = a_rz.dot(a_ry) # B b_ry = RYGate(-gamma / 2).to_matrix() b_rz = RZGate(-(delta + beta) / 2).to_matrix() b_matrix = b_ry.dot(b_rz) # C c_matrix = RZGate((delta - beta) / 2).to_matrix() a_gate = UnitaryGate(a_matrix, label="A") b_gate = UnitaryGate(b_matrix, label="B") c_gate = UnitaryGate(c_matrix, label="C") return a_gate, b_gate, c_gate def _define(self): self.definition = QuantumCircuit(self.control_qubits, self.target_qubit) if len(self.control_qubits) > 0: self._apply_ctrl_state() theta, phi, lamb, _ = OneQubitEulerDecomposer._params_zyz(self.unitary) a_gate, b_gate, c_gate = LdMcSpecialUnitary.get_abc_operators( phi, theta, lamb ) self._apply_abc(a_gate, b_gate, c_gate) self._apply_ctrl_state() else: self.unitary(self.unitary, self.target_qubit) def _apply_abc(self, a_gate: UnitaryGate, b_gate: UnitaryGate, c_gate: UnitaryGate): """ Applies ABC matrices to the quantum circuit according to theorem 5 of Iten et al. 2016 (arXiv:1501.06911). Parameters ---------- a_gate, b_gate and c_gate expceted to be special unitary gates """ if len(self.control_qubits) < 3: self.definition.append(c_gate, [self.target_qubit]) self.definition.mcx(self.control_qubits, self.target_qubit) self.definition.append(b_gate, [self.target_qubit]) self.definition.mcx(self.control_qubits, self.target_qubit) self.definition.append(a_gate, [self.target_qubit]) else: ancilla = self.control_qubits[-1] action_only = True if len(self.control_qubits) < 6: action_only = False # decompose A, B and C to use their optimized controlled versions theta_a, phi_a, lam_a, _ = OneQubitEulerDecomposer._params_zyz( a_gate.to_matrix() ) theta_b, phi_b, lam_b, _ = OneQubitEulerDecomposer._params_zyz( b_gate.to_matrix() ) theta_c, phi_c, lam_c, _ = OneQubitEulerDecomposer._params_zyz( c_gate.to_matrix() ) a_a, b_a, c_a = LdMcSpecialUnitary.get_abc_operators(phi_a, theta_a, lam_a) a_b, b_b, c_b = LdMcSpecialUnitary.get_abc_operators(phi_b, theta_b, lam_b) a_c, b_c, c_c = LdMcSpecialUnitary.get_abc_operators(phi_c, theta_c, lam_c) # definition of left mcx, which will also be inverted as the right mcx mcx_gate = LinearMcx( len(self.control_qubits[:-1]), action_only=action_only ).definition # decomposed controlled C self.definition.unitary(c_c, self.target_qubit) self.definition.cx(ancilla, self.target_qubit) self.definition.unitary(b_c, self.target_qubit) self.definition.cx(ancilla, self.target_qubit) self.definition.unitary(a_c, self.target_qubit) self.definition.append( mcx_gate, self.control_qubits[:-1] + [self.target_qubit] + [ancilla] ) # decomposed controlled B self.definition.unitary(c_b, self.target_qubit) self.definition.cx(ancilla, self.target_qubit) self.definition.unitary(b_b, self.target_qubit) self.definition.cx(ancilla, self.target_qubit) self.definition.unitary(a_b, self.target_qubit) self.definition.append( mcx_gate.inverse(), self.control_qubits[:-1] + [self.target_qubit] + [ancilla], ) # decomposed A self.definition.unitary(c_a, self.target_qubit) self.definition.cx(ancilla, self.target_qubit) self.definition.unitary(b_a, self.target_qubit) self.definition.cx(ancilla, self.target_qubit) self.definition.unitary(a_a, self.target_qubit) @staticmethod def ldmcsu(circuit, unitary, controls, target, ctrl_state=None): """ Linear-depth Multicontrolled Special Unitary -------------------------------------------- Implements the gate decompostion of any gate in SU(2) with linear depth (Ld) presented in Lemma 7.9 in Barenco et al., 1995 (arXiv:quant-ph/9503016) with optimizations from Theorem 5 of Iten et al., 2016 (arXiv:1501.06911) """ circuit.append( LdMcSpecialUnitary(unitary, len(controls), ctrl_state), [*controls, target] ) LdMcSpecialUnitary._apply_ctrl_state = apply_ctrl_state
https://github.com/lynnlangit/learning-quantum
lynnlangit
# Code blocks for qiskit notebook ## Block 1 - Setup import math import numpy as np from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.algorithms import Shor ## Block 2 - Run N = 15 backend = Aer.get_backend('aer_simulator') quantum_instance = QuantumInstance(backend, shots=1024) shor = Shor(quantum_instance=quantum_instance) result = shor.factor(N) print(f"The list of factors of {N} as computed by the Shor's algorithm is {result.factors[0]}.") ## Block 3 - Eval Perf print(f'Computed of qubits for circuit: {4 * math.ceil(math.log(N, 2)) + 2}') print(f'Actual number of qubits of circuit: {shor.construct_circuit(N).num_qubits}') ## Block 4 - Version Info import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright