Path: blob/main/quick-start-to-quantum/interactive_widget/bloch_sphere_state_visualization.py
1122 views
# Interactive widget to visualize the state |ψ⟩ = cos(θ/2)|0⟩ + sin(θ/2)e^{iφ}|1⟩ on the Bloch sphere12def create_state_widget():3# Clear any existing widgets4import IPython.display5IPython.display.clear_output()67import cudaq8import ipywidgets as widgets9from ipywidgets import interactive_output, HBox, VBox10from IPython.display import display, clear_output11import numpy as np121314# Kernel to initialize a qubit and set it to the state |ψ⟩ = cos(θ/2)|0⟩ + sin(θ/2)e^{iφ}|1⟩15@cudaq.kernel16def state_kernel(theta: float, phi: float):17qubit = cudaq.qubit()18ry(theta, qubit)19rz(phi, qubit)2021# Function to update the Bloch sphere plot based on the slider values22def update_bloch_sphere(theta, phi):23with output_bloch:24clear_output(wait=True) # Clear previous output25state = cudaq.get_state(state_kernel, theta, phi)26bloch_sphere = cudaq.add_to_bloch_sphere(state)27cudaq.show(bloch_sphere)2829# Function to update the circuit diagram based on the slider values30def update_circuit_diagram(theta, phi):31with output_circuit:32clear_output(wait=True) # Clear previous output33print(cudaq.draw(state_kernel, theta, phi))3435# Function to display the state in plain text with rounded angles36def update_state_output(theta, phi):37with output_state:38clear_output(wait=True) # Clear previous output39theta_half = round(theta / 2, 3)40phi = round(phi, 3)41expression = f"|ψ⟩ = cos({theta_half})|0⟩ + sin({theta_half})e^(i{phi})|1⟩"42print('|ψ⟩ = cos(θ/2)|0⟩ + sin(θ/2)e^(iφ)|1⟩')43print(expression)4445# Create interactive sliders for angles46slider_theta = widgets.FloatSlider(min=0, max=2*np.pi, step=0.01, value=0, description='θ:', continuous_update=False)47slider_phi = widgets.FloatSlider(min=0, max=2*np.pi, step=0.01, value=0, description='φ:', continuous_update=False)4849# Add a new title to the widget50title = widgets.HTML(value="<h3>Visualize the State |ψ⟩ with Varying Angles θ and φ (in radians)</h3>")5152# Display the title and sliders53display(title)5455# Create output widgets56output_bloch = widgets.Output()57output_circuit = widgets.Output()58output_state = widgets.Output()5960def update_all(theta, phi):61update_bloch_sphere(theta, phi)62update_circuit_diagram(theta, phi)63update_state_output(theta, phi)6465interactive_plot = interactive_output(update_all, {'theta': slider_theta, 'phi': slider_phi})6667# Arrange sliders horizontally68slider_box = HBox([slider_theta, slider_phi])6970# Display the state output above the sliders and the interactive plots side by side71display(VBox([output_state, slider_box, HBox([output_bloch, output_circuit])]))7273# When imported, this will create and display a new widget74if __name__ == '__main__':75widget = create_state_widget()76display(widget)7778