Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
NVIDIA
GitHub Repository: NVIDIA/cuda-q-academic
Path: blob/main/qec101/Images/toric/solution1_button.py
1127 views
1
# reveal_cudaq.py
2
import ipywidgets as widgets
3
from IPython.display import display, Markdown
4
import runpy, tempfile, os
5
6
_NV_GREEN = "#76b900"
7
8
# your example as a raw‐string
9
_CODE = """\
10
L=3
11
12
stabilizers_z = [] # Plaquette stabilizers that flag Z errors
13
for row in range(L):
14
for col in range(L):
15
stabilizers_z.append(L*row + col+L**2) #left
16
stabilizers_z.append(L*row + col ) #top
17
stabilizers_z.append((L*row + (col+1)%L)+L**2) #right
18
stabilizers_z.append(L*((row + 1)%L) +col) #bottom
19
20
21
stabilizers_x = [] # vertex stabilizers that flag X errors
22
for row in range(L):
23
for col in range(L):
24
stabilizers_x.append( (L*row + (col -1 )%L)) #left
25
stabilizers_x.append(L*((row-1)%L) + col + L**2) #top
26
stabilizers_x.append(L*row +col) #right
27
stabilizers_x.append(L*row +col + L**2 ) #bottom
28
29
30
31
print("plaq")
32
for x in range(L**2):
33
print(stabilizers_z[4*x], stabilizers_z[4*x+1],stabilizers_z[4*x+2],stabilizers_z[4*x+3])
34
35
print("vertex")
36
for x in range(L**2):
37
print(stabilizers_x[4*x], stabilizers_x[4*x+1],stabilizers_x[4*x+2],stabilizers_x[4*x+3])
38
"""
39
40
def show_cudaq_solution():
41
"""
42
Returns a Reveal‐Answer widget that displays the CUDA‑Q code
43
and then runs it, showing its printed output.
44
"""
45
btn = widgets.Button(
46
description="Reveal Answer",
47
style={"button_color": _NV_GREEN, "font_weight": "bold"},
48
layout=widgets.Layout(width="180px")
49
)
50
out = widgets.Output()
51
52
def _on_click(_):
53
out.clear_output()
54
with out:
55
# 1) show the source
56
display(Markdown("```python\n" + _CODE + "\n```"))
57
# 2) write to a temp .py file so inspect.getsource will succeed
58
fd, path = tempfile.mkstemp(suffix=".py")
59
with os.fdopen(fd, "w") as f:
60
f.write(_CODE)
61
try:
62
# 3) execute that file as __main__
63
runpy.run_path(path, run_name="__main__")
64
finally:
65
os.remove(path)
66
67
btn.on_click(_on_click)
68
return widgets.VBox([btn, out])
69
70