Path: blob/main/quick-start-to-quantum/interactive_widget/t_and_s_gate.py
1128 views
def create_t_and_s_widget():1# Clear any existing widgets2import IPython.display3IPython.display.clear_output()45import cudaq6import ipywidgets as widgets7from ipywidgets import interactive_output, HBox, VBox8from IPython.display import display, clear_output9import numpy as np1011# Kernel to initialize a qubit and apply T or S gate12@cudaq.kernel13def state_kernel(theta: float, phi: float, gate_choice: int):14qubit = cudaq.qubit()15ry(theta, qubit)16rz(phi, qubit)1718if gate_choice == 1:19t(qubit)20elif gate_choice == 2:21s(qubit)2223# Function to update the Bloch sphere plots24def update_bloch_spheres(theta, phi):25with output_bloch:26clear_output(wait=True)2728bloch_spheres = []2930# Get all three states31initial_state = cudaq.get_state(state_kernel, theta, phi, 0)32t_state = cudaq.get_state(state_kernel, theta, phi, 1)33s_state = cudaq.get_state(state_kernel, theta, phi, 2)3435# Create Bloch spheres36bloch_spheres.append(cudaq.add_to_bloch_sphere(initial_state))37bloch_spheres.append(cudaq.add_to_bloch_sphere(t_state))38bloch_spheres.append(cudaq.add_to_bloch_sphere(s_state))3940# Show all three spheres41cudaq.show(bloch_spheres, nrows=1, ncols=3)42print("Initial State | After T Gate | After S Gate")4344# Function to display the state in plain text45def update_state_output(theta, phi):46with output_state:47clear_output(wait=True)48theta_half = round(theta / 2, 3)49phi = round(phi, 3)50expression = f"|ψ⟩ = cos({theta_half})|0⟩ + sin({theta_half})e^(i{phi})|1⟩"51print('Initial state:')52print(expression)5354# Create interactive controls55slider_theta = widgets.FloatSlider(min=0, max=2*np.pi, step=0.01, value=0,56description='θ:', continuous_update=False)57slider_phi = widgets.FloatSlider(min=0, max=2*np.pi, step=0.01, value=0,58description='φ:', continuous_update=False)5960# Create output widgets61output_bloch = widgets.Output()62output_state = widgets.Output()6364def update_all(theta, phi):65update_bloch_spheres(theta, phi)66update_state_output(theta, phi)6768# Create interactive output69interactive_plot = interactive_output(70update_all,71{72'theta': slider_theta,73'phi': slider_phi,74}75)7677# Layout78title = widgets.HTML(value="<h3>Comparing T and S Gates on Quantum States</h3>")79slider_box = HBox([slider_theta, slider_phi])8081# Create and return the widget82widget = VBox([83title,84output_state,85slider_box,86output_bloch87])8889return widget9091# When imported, this will create and display a new widget92if __name__ == '__main__':93widget = create_t_and_s_widget()94display(widget)959697