def main(): qr, qc, crx, crz = setup() # initialize state to teleport vector_to_teleport = random_statevector(2) qc = initialize_teleport_state(qc, tel_qbit=TELEPORT_QBIT, state=vector_to_teleport.data) qc.barrier() # craete bell pair, as q1 and q2 where q1 shared with Alice and q2 with Bob qc = create_bell_pair(qc, a=A_QBIT, b=B_QBIT) # find i, j value (which bell states craetes pair q0 and q1 together), i is related to state (q0) and # j to Alice's entangeletn quibit q1 qc.barrier() qc = alice_bell_measurement(qc, psi=TELEPORT_QBIT, a=A_QBIT) qc.barrier() # evaluate bell measurment of Alice's total state # measured values are stored in crz and crx qc = measure_and_send(qc, a=TELEPORT_QBIT, b=A_QBIT, bit_a=0, bit_b=1) # apply gates regards to teleportation protocol theory qc.barrier() qc, crz, crx = bob_gates(qc, B_QBIT, crz=crz, crx=crx) plot_teleport_state_vector(vector_to_teleport.data) out_vector = q.execute(qc, STATE_VECTOR_BACKEND).result().get_statevector() plot_bloch_multivector(out_vector) # qc.draw("mpl") plt.show()
def simulate_bloch_sphere(qc, title): qc.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') out_state = execute(qc, backend).result().get_statevector() print(out_state) plot_bloch_multivector(out_state) # plot_bloch_multivector(out_state, title=title) # plt.title(title) plt.show()
def show_qc(qc: QuantumCircuit): """ Display the given state vector of the quantum circuit """ # print(qc.draw()) backend = Aer.get_backend('statevector_simulator') out = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out).show() return out
def controled_sdg_gate_bloch(): qc.h(0) qc.x(1) # Add controlled-Sdg gate qc.cu1(-np.pi / 2, 0, 1) statevector_backend = q.Aer.get_backend('statevector_simulator') final_state = q.execute(qc, statevector_backend).result().get_statevector() plot_bloch_multivector(final_state) plt.show()
def ry_controller(): qc.x(0) theta = np.pi / 4 qc.ry(theta / 2, t) qc.cx(c, t) qc.ry(-theta / 2, t) qc.cx(c, t) statevector_backend = q.Aer.get_backend('statevector_simulator') final_state = q.execute(qc, statevector_backend).result().get_statevector() plot_bloch_multivector(final_state) plt.show()
def create_images(gate, theta=0.0, phi=0.0, lam=0.0): # Set the loop parameters steps = 20.0 theta_steps = theta / steps phi_steps = phi / steps lam_steps = lam / steps n, theta, phi, lam = 0, 0.0, 0.0, 0.0 # Create image and animation tools global q_images, b_images, q_filename, b_filename b_images = [] q_images = [] b_filename = "animated_qubit" q_filename = "animated_qsphere" # The image creation loop while n < steps + 1: qc = QuantumCircuit(1) if gate == "u3": qc.u3(theta, phi, lam, 0) title = "U3: \u03B8 = " + str(round( theta, 2)) + " \u03D5 = " + str(round( phi, 2)) + " \u03BB = " + str(round(lam, 2)) elif gate == "u2": qc.u2(phi, lam, 0) title = "U2: \u03D5 = " + str(round(phi, 2)) + " \u03BB = " + str( round(lam, 2)) else: qc.h(0) qc.u1(phi, 0) title = "U1: \u03D5 = " + str(round(phi, 2)) # Get the statevector of the qubit # Create Bloch sphere images plot_bloch_multivector(get_psi(qc), title).savefig('images/bloch' + str(n) + '.png') imb = Image.open('images/bloch' + str(n) + '.png') b_images.append(imb) # Create Q sphere images plot_state_qsphere(psi).savefig('images/qsphere' + str(n) + '.png') imq = Image.open('images/qsphere' + str(n) + '.png') q_images.append(imq) # Rev our loop n += 1 theta += theta_steps phi += phi_steps lam += lam_steps
def blochSphere(self, circuit): from qiskit import Aer from qiskit import execute from qiskit.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend=simulator).result() statevector = result.get_statevector() return plot_bloch_multivector(statevector)
def execute_circuit_sv(self): sv_sim = Aer.get_backend('statevector_simulator') result = execute(self.circuit, sv_sim).result() state = result.get_statevector(self.circuit) circuit_diagram = self.circuit.draw('mpl') bloch_sphere = plot_bloch_multivector(state) return circuit_diagram, state, bloch_sphere
def get_psi(circuit, title): show_bloch = True if show_bloch: from qiskit.visualization import plot_bloch_multivector backend = Aer.get_backend('statevector_simulator') result = execute(circuit, backend).result() psi = result.get_statevector(circuit) print(title) display(qc.draw('mpl')) display(plot_bloch_multivector(psi))
def apply_gate(): """Uses widget_state to apply the last selected gate, update the code cell and prepare widget_state for the next selection""" functionmap = { 'I': 'qc.iden', 'X': 'qc.x', 'Y': 'qc.y', 'Z': 'qc.z', 'H': 'qc.h', 'S': 'qc.s', 'T': 'qc.t', 'Sdg': 'qc.sdg', 'Tdg': 'qc.tdg', 'CX': 'qc.cx', 'CZ': 'qc.cz', 'SWAP': 'qc.swap' } gate = widget_state.current_gate qubits = widget_state.qubits widget_state.code += " " if len(qubits) == 2: widget_state.code += functionmap[gate] widget_state.code += "({0}, {1})\n".format(qubits[0], qubits[1]) widget_state.qubits.pop() elif widget_state.current_gate == 'Clear': widget_state.code = "" else: widget_state.code += functionmap[gate] + "({})\n".format(qubits[0]) qc = QuantumCircuit(nqubits) # This is especially awful I know, please don't judge me exec(widget_state.code.replace(" ", "")) qc.draw('mpl').savefig('circuit_widget_temp.svg', format='svg') if bloch or dirac or qsphere: ket = execute(qc, backend).result().get_statevector() if bloch: plot_bloch_multivector(ket, show_state_labels=True).savefig( 'circuit_widget_temp_bs.svg', format='svg') if qsphere: plot_state_qsphere(ket, show_state_labels=True).savefig( 'circuit_widget_temp_qs.svg', format='svg') if dirac: widget_state.statevec = ket
def draw_quantum_circuit(qc: QuantumCircuit, draw_circuit=True, draw_unitary=True, draw_final_state=True, draw_bloch_sphere=False, draw_q_sphere=False, draw_histogram=False): if draw_circuit: # Visualize the quantum circuit print('Quantum circuit:') print(qc.draw()) if draw_unitary: try: # Visualize the unitary operator backend = Aer.get_backend('unitary_simulator') unitary = execute(qc, backend).result().get_unitary() print('Unitary:') for row in unitary: print(' '.join([display_complex(elem) for elem in row])) except QiskitError: # If a qunatum circuit contains a measure operation, the process is # not reversible anymore, and hence cannot be represented by a # Unitary matrix. We just ignore this operation in that case. pass if draw_final_state or draw_bloch_sphere or draw_q_sphere: # Visualize the final state # final_state for 2 qubits = a |00> + b |01> + c |10> + d |11> backend = Aer.get_backend('statevector_simulator') final_state = execute(qc, backend).result().get_statevector() if draw_final_state: print('Final state:') for elem in final_state: print(display_complex(elem)) if draw_bloch_sphere: plot_bloch_multivector(final_state).show() if draw_q_sphere: plot_state_qsphere(final_state).show() if draw_histogram: backend = Aer.get_backend('statevector_simulator') results = execute(qc, backend).result().get_counts() plot_histogram(results).show()
def qiskit(): # Plotting Single Bloch Sphere plot_bloch_vector([0, 1, 0], title='Bloch Sphere') # Building Quantum Circuit to use for multiqubit systems qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) # Plotting Multi Bloch System state = Statevector.from_instruction(qc) plot_bloch_multivector(state, title="New Bloch Multivector") # Plotting Bloch City Scape plot_state_city(state, color=['midnightblue', 'midnightblue'], title="New State City") # Plotting Bloch Pauli Vectors plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
def not_corrected(error, ry_error, rz_error): # Non-corrected code qco = QuantumCircuit(1, 1) print("\nOriginal qubit, in state |0>") display(plot_bloch_multivector(get_psi(qco))) display(plot_state_qsphere(get_psi(qco))) # Add error add_error(error, qco, ry_error, rz_error) print("\nQubit with error...") display(plot_bloch_multivector(get_psi(qco))) display(plot_state_qsphere(get_psi(qco))) qco.measure(0, 0) display(qco.draw('mpl')) job = execute(qco, backend, shots=1000) counts = job.result().get_counts() print("\nResult of qubit error:") print("-----------------------") print(counts)
def qgate_out(circuit, start): # Print the circuit psi = get_psi(circuit) if start != "n": print("\nCircuit:") print("--------") print(circuit) print("\nState vector:") print("-------------") print(np.around(psi, decimals=3)) display(plot_bloch_multivector(psi)) if circuit.num_qubits > 1 and gate in control_gates: display(plot_state_qsphere(psi)) return (psi)
def s_vec(circuit): backend = Aer.get_backend('statevector_simulator') print(circuit.num_qubits, "qubit quantum circuit:\n------------------------") print(circuit) psi = execute(circuit, backend).result().get_statevector(circuit) print("State vector for the", circuit.num_qubits, "qubit circuit:\n\n", psi) print("\nState vector as Bloch sphere:") display(plot_bloch_multivector(psi)) print("\nState vector as Q sphere:") display(plot_state_qsphere(psi)) measure(circuit) input("Press enter to continue...\n")
def get_psi(circuit, vis): from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere from qiskit import Aer, execute global psi backend = Aer.get_backend('statevector_simulator') psi = execute(circuit, backend).result().get_statevector(circuit) if vis == "Q": display(plot_state_qsphere(psi)) elif vis == "M": print(psi) elif vis == "B": display(plot_bloch_multivector(psi)) vis = "" print_psi(psi) return (psi)
def auto_bloch(): # Graphical representation of the Bloch Spheres for the game sequence HXH qc = QuantumCircuit(4, 1) # Prepare each qubit to visualize the states after each step # qc.x(1) would change the initial position of q1 and results in different superposition qc.h(1) # Qubit 1 - superposition after H gate qc.h(2) qc.x(2) # Qubit 2 - superposition after H and X gate (similar after H and iden) qc.h(3) qc.x(3) qc.h(3) # Qubit 3 - result head after H, X and H qc.measure([3], [0]) # Measure qubit 3 - would colapse if in s#perposition backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend).result() print ("qubit0: initial position, qubit1: applying H, qubit2: applying X (after H), qubit3: applying H (after X and H)") return plot_bloch_multivector(job.get_statevector(qc)) # Visualize quantum states
def show_multivector(coords): qc = qiskit.QuantumCircuit(1) non_normalized = np.array([complex(*coords[0:2]), complex(*coords[2:4])]) # Normalize each component part_normalized = np.nan_to_num(non_normalized / np.abs(non_normalized)) # nan -> 0 # Normalize all components initial_state = part_normalized / np.linalg.norm(part_normalized) qc.initialize(initial_state, 0) backend = qiskit.Aer.get_backend('statevector_simulator') out = qiskit.execute(qc, backend).result().get_statevector() plt = plot_bloch_multivector(out) return visualizer._export_png(plt)
def personal_bloch(moveA1, moveB1, moveA2): # Graphical representation of the Bloch Spheres for the game sequence of the player qc = QuantumCircuit(4, 1) # Prepare each qubit to visualize the states after the according moves # 1. move of A if moveA1 == 0 : qc.iden(1) qc.iden(2) qc.iden(3) elif moveA1 == 1 : qc.x(1) qc.x(2) qc.x(3) elif moveA1 == 2 : qc.h(1) qc.h(2) qc.h(3) # 1. move of B if moveB1 == 0 : qc.iden(2) qc.iden(3) elif moveB1 == 1 : qc.x(2) qc.x(3) # 2. move of A if moveA2 == 0 : qc.iden(3) elif moveA2 == 1 : qc.x(3) elif moveA2 == 2 : qc.h(3) backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend).result() print('Your moves were: ',moveA1, moveB1, moveA2) print('The states of the qubits for this game sequence can be visualized as follows:') return plot_bloch_multivector(job.get_statevector(qc)) # Visualize quantum states
def plot_2_qubits(): fig = plot_bloch_multivector([0, 1, 0, 0]) fig.savefig('png/out.png') plt.close()
def getBlochSphere(qc): '''plot multi qubit bloch sphere''' vec = getStateVector(qc) return plot_bloch_multivector(vec)
def update_output(): out_state = execute(qc,backend).result().get_statevector() if qsphere: image.value = plot_state_qsphere(out_state) else: image.value = plot_bloch_multivector(out_state)
from math import pi #gates = operations that changes qubits! # Pauli gate!! # multiply qubit's statevector by the gate to see the effect!! # 1 qubit!! quantum_circuit = QuantumCircuit(1) quantum_circuit.x(0) quantum_circuit.draw('mpl') plt.show() # plot_bloch_multivector takes in the qubit's statevector instead of the Bloch vector!! backend = Aer.get_backend('statevector_simulator') res= execute(quantum_circuit, backend).result().get_statevector() plot_bloch_multivector(res) plt.show() # Pauli Y and Z gates ==> rotations about the y and z axes!! quantum_circuit.y(0) quantum_circuit.z(0) plt.show() # but these gates operate very similar to classical bits ==> want to instead use superposition!! # use Hadamard gate instead! # superposition of |0> and |1> ==> hadamard gate quantum_circuit.h(0) quantum_circuit.draw('mpl') plt.show()
plot_histogram([counts, second_counts], legend=legend) plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15, 12), color=['orange', 'black'], bar_labels=False) from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_state_paulivec, plot_state_hinton from qiskit.visualization import plot_state_qsphere backend = BasicAer.get_backend('statevector_simulator') result = execute(bell, backend).result() psi = result.get_statevector(bell) plot_state_city(psi) plot_state_hinton(psi) plot_state_qsphere(psi) plot_state_paulivec(psi) plot_bloch_multivector(psi) plot_state_city(psi, title="My City", color=['black', 'orange']) plot_state_hinton(psi, title="My Hinton")
However, there are systems of qubits whose state cannot be described as the tensor product of its constituent sub-systems. Such systems are called "entangled" in nature. This property of entanglement is one of the most fundamentally important quantum mechanical property and is exploited a great deal in various of use cases. For example, let us take the quantum state as described below \begin{equation} |\psi\rangle = a|00\rangle + b|11\rangle \\ a,b \neq 0 \end{equation} This state cannot be expressed as a tensor product of $2$ qubits, and, hence, is an entangled state. qcE = QuantumCircuit(2) qcE.initialize([1/2**0.5,0,0,1/2**0.5], [0,1]) qcE.draw() backend = Aer.get_backend('statevector_simulator') result = execute(qcE,backend).result() out_state = result.get_statevector() print(out_state) plot_bloch_multivector(out_state) # Qubits are Not Separable ## Bell States A commonly used set of entangled states which are orthogonal to each other is the set of Bell states which is \begin{equation} |\Phi^+\rangle = \frac{|00\rangle + |11\rangle}{\sqrt{2}} \\ |\Phi^-\rangle = \frac{|00\rangle - |11\rangle}{\sqrt{2}} \\ |\Psi^+\rangle = \frac{|01\rangle + |10\rangle}{\sqrt{2}} \\ |\Psi^-\rangle = \frac{|01\rangle - |10\rangle}{\sqrt{2}} \end{equation}
statevec = result.get_statevector() nr_qubits = circuit.qregs[0].size nr_cbits = circuit.cregs[0].size circuit.measure(list(range(nr_qubits)), list(range(nr_cbits))) qasm_result = q.execute(circuit, backend=qasm_simulator, shots=2**12).result() counts = qasm_result.get_counts() return statevec, counts def normalize_vector(vector: List) -> List: norm = sqrt(sum([abs(x)**2 for x in vector])) return [x / norm for x in vector] qc = q.QuantumCircuit(1, 1) # Create a quantum circuit with one qubit initial_state = normalize_vector([sqrt(1 / 3), sqrt(2 / 3)]) # initial_state = normalize_vector([sqrt(1 / 3), 1j * sqrt(2 / 3)]) qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit statevec, counts = do_job(qc) print(statevec) plot_bloch_multivector(statevec).show() # plot_histogram([counts]).show() qc.measure_all() statevec, counts = do_job(qc) print(statevec) plot_bloch_multivector(statevec).show()
return c n = int(input("Enter the number of qbits : ")) # number of input bits y = int( input("Choose 1 if you want balanced or 0 if you want constant function") ) #function selection circuit = q.QuantumCircuit(n + 1, n + 1) #quantumbits = n+1 and classicalbits=n+1 circuit.x(n) circuit.barrier() #Used for better visualization circuit = hadamard(circuit) circuit.h(n) circuit.barrier() if y == 1: circuit = blackbox_balanced(circuit) #calling the balanced function if y == 0: circuit = blackbox_constant(circuit) #calling the constant function circuit.barrier() circuit = hadamard(circuit) circuit.draw(output='mpl', filename='djckt.png') originalstate = q.execute(circuit, backend=statevec_sim).result().get_statevector() circuit.measure( [i for i in range(n)], [i for i in range(n)]) #measuring n quantum bits to n classical bits original_count = q.execute(circuit, backend=qasm_sim).result().get_counts() print(circuit) plot_bloch_multivector(originalstate).show() plot_histogram(original_count).show()
\begin{equation} |\psi\rangle = \alpha|0\rangle + e^{i\phi}\beta|1\rangle \end{equation} For normalisation, we know that $\sqrt{\alpha^2 + \beta^2} = 1$. Hence, we can describe $\alpha$ and $\beta$ using a single variable $\theta$ as $\alpha = \cos{\tfrac{\theta}{2}}$ and $\beta=\sin{\tfrac{\theta}{2}}$. So, for real $\theta$ and $\phi$, we get \begin{equation} |\psi\rangle = \cos{\tfrac{\theta}{2}}|0\rangle + e^{i\phi}\sin{\tfrac{\theta}{2}}|1\rangle \end{equation} Using $\theta$ and $\phi$ as the polar coordinates, we can map any single qubit state to a point on a sphere of radius $1$. This sphere is called the Bloch Sphere. plot_bloch_multivector([0,0,1,0]) plot_bloch_multivector([1/2**0.5,1/2**0.5]) ## Rotation Gates With respect to the Bloch Sphere (defined above), we have the rotation gates along the 3 axes, namely RX, RY and RZ. These gates perform a rotation of the qubit vector along the specified axis by an angle $\theta$. \begin{align}\begin{aligned}\newcommand{\th}{\frac{\theta}{2}}\\\begin{split}RX(\theta) = \begin{pmatrix} \cos{\th} & -i\sin{\th} \\ -i\sin{\th} & \cos{\th} \end{pmatrix}\end{split}\end{aligned} \end{align}
from math import sqrt, pi from qiskit import QuantumCircuit, BasicAer, execute from qiskit.visualization import plot_bloch_multivector # change alpha beta as you want alpha = 1 / sqrt(2) beta = 1j / sqrt(2) # 2D complex vector representing the quantum state vector = [alpha, beta] # create a quantum circuit with only one qubit qc = QuantumCircuit(1) # initialzie the qubit as the vector we defined # arg 0 is the index of the only qubit we created qc.initialize(vector, 0) # simulate the state # note that statevector_simulator is used for calculating statevector (Quantum State) backend = BasicAer.get_backend('statevector_simulator') result = execute(qc, backend).result() state = result.get_statevector(qc) # plot the state on a Bloch sphere plot_bloch_multivector(state)
def qonduit_visualization_state_plot_bloch_multivector(state): return interactive(lambda sv: display(plot_bloch_multivector(sv)), sv=fixed(state))