Path: blob/main/qec101/Images/toric/solution4_button.py
1125 views
# reveal_cudaq.py1import ipywidgets as widgets2from IPython.display import display, Markdown3import runpy, tempfile, os45_NV_GREEN = "#76b900"678# your example as a raw‐string9_CODE = """\10import networkx as nx11import matplotlib.pyplot as plt1213def toric_distance(u, v, L):1415dx = abs(u[0] - v[0])16dx = min(dx, L - dx)17dy = abs(u[1] - v[1])18dy = min(dy, L - dy)19return dx + dy2021def mwpm_decoder_toric(flagged_stabilizers, L):2223G = nx.Graph()24# Add each flagged stabilizer as a node25for i, coord in enumerate(flagged_stabilizers):26G.add_node(i, pos=coord)2728# Add edges with wrapped Manhattan distance as weight29for i in range(len(flagged_stabilizers)):30for j in range(i + 1, len(flagged_stabilizers)):31dist = toric_distance(flagged_stabilizers[i], flagged_stabilizers[j], L)32G.add_edge(i, j, weight=dist)3334# Draw the graph35pos = {node: G.nodes[node]['pos'] for node in G.nodes}36nx.draw(G, pos, with_labels=True, node_size=500, font_weight='bold')37# Add edge labels (i.e., distances)38edge_labels = nx.get_edge_attributes(G, 'weight')39nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)40plt.title("Toric Code Graph (Distances on Edges)")41plt.show()4243#Performs MWPM44matching_indices = nx.min_weight_matching(G)4546# Convert node indices back to stabilizer coordinates for clarity47matching_solution = []48for i, j in matching_indices:49matching_solution.append((G.nodes[i]['pos'], G.nodes[j]['pos']))50return matching_solution5152flagged_1 = [(2, 1), (1, 3), (2, 4), (1, 6), (4,5), (5,2)]53flagged_2 = [(1, 0), (1, 6), (2, 1), (3, 4), (5,3), (4,6)]54L = 75556print("MWPM solution 1:",mwpm_decoder_toric(flagged_1, L))57print("MWPM solution 2:", mwpm_decoder_toric(flagged_2, L))58"""596061_ANSWER_TEXT_1 = """\62**Answer:**6364A logical error occurs6566<img src="Images/toric/mwpmsolution1.png" title="Landscape Image" width="600">67"""6869_ANSWER_TEXT_2 = """\70**Answer:**7172A logical error does not occur7374<img src="Images/toric/mwpmsolution2.png" title="Landscape Image" width="600">75"""7677def show_cudaq_solution():78"""79Returns a Reveal‐Answer widget that displays the CUDA‑Q code80and then runs it, showing its printed output.81"""82btn = widgets.Button(83description="Reveal Answer",84style={"button_color": _NV_GREEN, "font_weight": "bold"},85layout=widgets.Layout(width="180px")86)87out = widgets.Output()8889def _on_click(_):90out.clear_output()91with out:92# 1) show the source93display(Markdown("```python\n" + _CODE + "\n```"))94# 2) write to a temp .py file so inspect.getsource will succeed95fd, path = tempfile.mkstemp(suffix=".py")96with os.fdopen(fd, "w") as f:97f.write(_CODE)98try:99# 3) execute that file as __main__100runpy.run_path(path, run_name="__main__")101finally:102os.remove(path)103display(Markdown(_ANSWER_TEXT_1))104display(Markdown(_ANSWER_TEXT_2))105106btn.on_click(_on_click)107return widgets.VBox([btn, out])108109110