Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
NVIDIA
GitHub Repository: NVIDIA/cuda-q-academic
Path: blob/main/qec101/Images/toric/solution4_button.py
1125 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
9
# your example as a raw‐string
10
_CODE = """\
11
import networkx as nx
12
import matplotlib.pyplot as plt
13
14
def toric_distance(u, v, L):
15
16
dx = abs(u[0] - v[0])
17
dx = min(dx, L - dx)
18
dy = abs(u[1] - v[1])
19
dy = min(dy, L - dy)
20
return dx + dy
21
22
def mwpm_decoder_toric(flagged_stabilizers, L):
23
24
G = nx.Graph()
25
# Add each flagged stabilizer as a node
26
for i, coord in enumerate(flagged_stabilizers):
27
G.add_node(i, pos=coord)
28
29
# Add edges with wrapped Manhattan distance as weight
30
for i in range(len(flagged_stabilizers)):
31
for j in range(i + 1, len(flagged_stabilizers)):
32
dist = toric_distance(flagged_stabilizers[i], flagged_stabilizers[j], L)
33
G.add_edge(i, j, weight=dist)
34
35
# Draw the graph
36
pos = {node: G.nodes[node]['pos'] for node in G.nodes}
37
nx.draw(G, pos, with_labels=True, node_size=500, font_weight='bold')
38
# Add edge labels (i.e., distances)
39
edge_labels = nx.get_edge_attributes(G, 'weight')
40
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
41
plt.title("Toric Code Graph (Distances on Edges)")
42
plt.show()
43
44
#Performs MWPM
45
matching_indices = nx.min_weight_matching(G)
46
47
# Convert node indices back to stabilizer coordinates for clarity
48
matching_solution = []
49
for i, j in matching_indices:
50
matching_solution.append((G.nodes[i]['pos'], G.nodes[j]['pos']))
51
return matching_solution
52
53
flagged_1 = [(2, 1), (1, 3), (2, 4), (1, 6), (4,5), (5,2)]
54
flagged_2 = [(1, 0), (1, 6), (2, 1), (3, 4), (5,3), (4,6)]
55
L = 7
56
57
print("MWPM solution 1:",mwpm_decoder_toric(flagged_1, L))
58
print("MWPM solution 2:", mwpm_decoder_toric(flagged_2, L))
59
"""
60
61
62
_ANSWER_TEXT_1 = """\
63
**Answer:**
64
65
A logical error occurs
66
67
<img src="Images/toric/mwpmsolution1.png" title="Landscape Image" width="600">
68
"""
69
70
_ANSWER_TEXT_2 = """\
71
**Answer:**
72
73
A logical error does not occur
74
75
<img src="Images/toric/mwpmsolution2.png" title="Landscape Image" width="600">
76
"""
77
78
def show_cudaq_solution():
79
"""
80
Returns a Reveal‐Answer widget that displays the CUDA‑Q code
81
and then runs it, showing its printed output.
82
"""
83
btn = widgets.Button(
84
description="Reveal Answer",
85
style={"button_color": _NV_GREEN, "font_weight": "bold"},
86
layout=widgets.Layout(width="180px")
87
)
88
out = widgets.Output()
89
90
def _on_click(_):
91
out.clear_output()
92
with out:
93
# 1) show the source
94
display(Markdown("```python\n" + _CODE + "\n```"))
95
# 2) write to a temp .py file so inspect.getsource will succeed
96
fd, path = tempfile.mkstemp(suffix=".py")
97
with os.fdopen(fd, "w") as f:
98
f.write(_CODE)
99
try:
100
# 3) execute that file as __main__
101
runpy.run_path(path, run_name="__main__")
102
finally:
103
os.remove(path)
104
display(Markdown(_ANSWER_TEXT_1))
105
display(Markdown(_ANSWER_TEXT_2))
106
107
btn.on_click(_on_click)
108
return widgets.VBox([btn, out])
109
110