Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
NVIDIA
GitHub Repository: NVIDIA/cuda-q-academic
Path: blob/main/quick-start-to-quantum/interactive_widget/t_and_s_gate.py
1128 views
1
def create_t_and_s_widget():
2
# Clear any existing widgets
3
import IPython.display
4
IPython.display.clear_output()
5
6
import cudaq
7
import ipywidgets as widgets
8
from ipywidgets import interactive_output, HBox, VBox
9
from IPython.display import display, clear_output
10
import numpy as np
11
12
# Kernel to initialize a qubit and apply T or S gate
13
@cudaq.kernel
14
def state_kernel(theta: float, phi: float, gate_choice: int):
15
qubit = cudaq.qubit()
16
ry(theta, qubit)
17
rz(phi, qubit)
18
19
if gate_choice == 1:
20
t(qubit)
21
elif gate_choice == 2:
22
s(qubit)
23
24
# Function to update the Bloch sphere plots
25
def update_bloch_spheres(theta, phi):
26
with output_bloch:
27
clear_output(wait=True)
28
29
bloch_spheres = []
30
31
# Get all three states
32
initial_state = cudaq.get_state(state_kernel, theta, phi, 0)
33
t_state = cudaq.get_state(state_kernel, theta, phi, 1)
34
s_state = cudaq.get_state(state_kernel, theta, phi, 2)
35
36
# Create Bloch spheres
37
bloch_spheres.append(cudaq.add_to_bloch_sphere(initial_state))
38
bloch_spheres.append(cudaq.add_to_bloch_sphere(t_state))
39
bloch_spheres.append(cudaq.add_to_bloch_sphere(s_state))
40
41
# Show all three spheres
42
cudaq.show(bloch_spheres, nrows=1, ncols=3)
43
print("Initial State | After T Gate | After S Gate")
44
45
# Function to display the state in plain text
46
def update_state_output(theta, phi):
47
with output_state:
48
clear_output(wait=True)
49
theta_half = round(theta / 2, 3)
50
phi = round(phi, 3)
51
expression = f"|ψ⟩ = cos({theta_half})|0⟩ + sin({theta_half})e^(i{phi})|1⟩"
52
print('Initial state:')
53
print(expression)
54
55
# Create interactive controls
56
slider_theta = widgets.FloatSlider(min=0, max=2*np.pi, step=0.01, value=0,
57
description='θ:', continuous_update=False)
58
slider_phi = widgets.FloatSlider(min=0, max=2*np.pi, step=0.01, value=0,
59
description='φ:', continuous_update=False)
60
61
# Create output widgets
62
output_bloch = widgets.Output()
63
output_state = widgets.Output()
64
65
def update_all(theta, phi):
66
update_bloch_spheres(theta, phi)
67
update_state_output(theta, phi)
68
69
# Create interactive output
70
interactive_plot = interactive_output(
71
update_all,
72
{
73
'theta': slider_theta,
74
'phi': slider_phi,
75
}
76
)
77
78
# Layout
79
title = widgets.HTML(value="<h3>Comparing T and S Gates on Quantum States</h3>")
80
slider_box = HBox([slider_theta, slider_phi])
81
82
# Create and return the widget
83
widget = VBox([
84
title,
85
output_state,
86
slider_box,
87
output_bloch
88
])
89
90
return widget
91
92
# When imported, this will create and display a new widget
93
if __name__ == '__main__':
94
widget = create_t_and_s_widget()
95
display(widget)
96
97