Path: blob/main/qec101/Images/toric/solution1_button.py
1127 views
# reveal_cudaq.py1import ipywidgets as widgets2from IPython.display import display, Markdown3import runpy, tempfile, os45_NV_GREEN = "#76b900"67# your example as a raw‐string8_CODE = """\9L=31011stabilizers_z = [] # Plaquette stabilizers that flag Z errors12for row in range(L):13for col in range(L):14stabilizers_z.append(L*row + col+L**2) #left15stabilizers_z.append(L*row + col ) #top16stabilizers_z.append((L*row + (col+1)%L)+L**2) #right17stabilizers_z.append(L*((row + 1)%L) +col) #bottom181920stabilizers_x = [] # vertex stabilizers that flag X errors21for row in range(L):22for col in range(L):23stabilizers_x.append( (L*row + (col -1 )%L)) #left24stabilizers_x.append(L*((row-1)%L) + col + L**2) #top25stabilizers_x.append(L*row +col) #right26stabilizers_x.append(L*row +col + L**2 ) #bottom27282930print("plaq")31for x in range(L**2):32print(stabilizers_z[4*x], stabilizers_z[4*x+1],stabilizers_z[4*x+2],stabilizers_z[4*x+3])3334print("vertex")35for x in range(L**2):36print(stabilizers_x[4*x], stabilizers_x[4*x+1],stabilizers_x[4*x+2],stabilizers_x[4*x+3])37"""3839def show_cudaq_solution():40"""41Returns a Reveal‐Answer widget that displays the CUDA‑Q code42and then runs it, showing its printed output.43"""44btn = widgets.Button(45description="Reveal Answer",46style={"button_color": _NV_GREEN, "font_weight": "bold"},47layout=widgets.Layout(width="180px")48)49out = widgets.Output()5051def _on_click(_):52out.clear_output()53with out:54# 1) show the source55display(Markdown("```python\n" + _CODE + "\n```"))56# 2) write to a temp .py file so inspect.getsource will succeed57fd, path = tempfile.mkstemp(suffix=".py")58with os.fdopen(fd, "w") as f:59f.write(_CODE)60try:61# 3) execute that file as __main__62runpy.run_path(path, run_name="__main__")63finally:64os.remove(path)6566btn.on_click(_on_click)67return widgets.VBox([btn, out])686970