quantcore-circuits 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. quantcore_circuits/__init__.py +57 -0
  2. quantcore_circuits/analysis/__init__.py +12 -0
  3. quantcore_circuits/analysis/_metal.py +70 -0
  4. quantcore_circuits/analysis/amplifiers.py +263 -0
  5. quantcore_circuits/analysis/circuits.py +117 -0
  6. quantcore_circuits/analysis/epr.py +231 -0
  7. quantcore_circuits/analysis/epr_lumped.py +372 -0
  8. quantcore_circuits/analysis/extract.py +119 -0
  9. quantcore_circuits/analysis/lom.py +80 -0
  10. quantcore_circuits/analysis/results.py +549 -0
  11. quantcore_circuits/analysis/store.py +81 -0
  12. quantcore_circuits/analysis/synthesis.py +118 -0
  13. quantcore_circuits/analysis/transmon.py +126 -0
  14. quantcore_circuits/assembly/__init__.py +17 -0
  15. quantcore_circuits/assembly/builder.py +127 -0
  16. quantcore_circuits/assembly/drc.py +683 -0
  17. quantcore_circuits/assembly/last_good.py +137 -0
  18. quantcore_circuits/assembly/netlist.py +174 -0
  19. quantcore_circuits/assembly/plan.py +605 -0
  20. quantcore_circuits/assembly/sidecar.py +270 -0
  21. quantcore_circuits/autotrack.py +605 -0
  22. quantcore_circuits/cards.py +878 -0
  23. quantcore_circuits/circuit/__init__.py +14 -0
  24. quantcore_circuits/circuit/adapters.py +305 -0
  25. quantcore_circuits/circuit/bridges.py +353 -0
  26. quantcore_circuits/circuit/consensus.py +158 -0
  27. quantcore_circuits/circuit/derive.py +28 -0
  28. quantcore_circuits/circuit/draw.py +198 -0
  29. quantcore_circuits/circuit/fill.py +828 -0
  30. quantcore_circuits/circuit/hamiltonian.py +193 -0
  31. quantcore_circuits/circuit/kinetic.py +102 -0
  32. quantcore_circuits/circuit/schema.py +139 -0
  33. quantcore_circuits/cli.py +1085 -0
  34. quantcore_circuits/codesign.py +1038 -0
  35. quantcore_circuits/data/selftest_q1_r1.json +44 -0
  36. quantcore_circuits/design/__init__.py +44 -0
  37. quantcore_circuits/design/io.py +98 -0
  38. quantcore_circuits/design/pyscript.py +395 -0
  39. quantcore_circuits/design/schema.py +398 -0
  40. quantcore_circuits/designer.py +625 -0
  41. quantcore_circuits/guiflow.py +991 -0
  42. quantcore_circuits/kqc_files.py +208 -0
  43. quantcore_circuits/layouts/__init__.py +118 -0
  44. quantcore_circuits/layouts/catalog.py +520 -0
  45. quantcore_circuits/layouts/chips/__init__.py +0 -0
  46. quantcore_circuits/layouts/chips/design_chip.py +325 -0
  47. quantcore_circuits/layouts/chips/frame.py +235 -0
  48. quantcore_circuits/layouts/junctions/__init__.py +0 -0
  49. quantcore_circuits/layouts/junctions/jj_fingers.py +99 -0
  50. quantcore_circuits/layouts/junctions/legacy_junctions.py +237 -0
  51. quantcore_circuits/layouts/junctions/sim_gap.py +48 -0
  52. quantcore_circuits/layouts/junctions/trilayer.py +541 -0
  53. quantcore_circuits/layouts/metal/__init__.py +105 -0
  54. quantcore_circuits/layouts/metal/component.py +332 -0
  55. quantcore_circuits/layouts/metal/geometry.py +462 -0
  56. quantcore_circuits/layouts/others/__init__.py +0 -0
  57. quantcore_circuits/layouts/others/amplifiers.py +1139 -0
  58. quantcore_circuits/layouts/others/bond_pad.py +119 -0
  59. quantcore_circuits/layouts/others/connector_pads.py +190 -0
  60. quantcore_circuits/layouts/others/couplers.py +21 -0
  61. quantcore_circuits/layouts/others/cpw_segment.py +131 -0
  62. quantcore_circuits/layouts/others/cpwe.py +661 -0
  63. quantcore_circuits/layouts/others/keepout.py +66 -0
  64. quantcore_circuits/layouts/others/legacy_resonators.py +645 -0
  65. quantcore_circuits/layouts/others/markers.py +201 -0
  66. quantcore_circuits/layouts/others/qpdk_cells.py +263 -0
  67. quantcore_circuits/layouts/others/shapes.py +114 -0
  68. quantcore_circuits/layouts/others/spirals.py +140 -0
  69. quantcore_circuits/layouts/others/sqdmetal_cells.py +90 -0
  70. quantcore_circuits/layouts/others/test_pads.py +461 -0
  71. quantcore_circuits/layouts/ports.py +119 -0
  72. quantcore_circuits/layouts/qubits/__init__.py +0 -0
  73. quantcore_circuits/layouts/qubits/legacy_transmon.py +124 -0
  74. quantcore_circuits/layouts/qubits/qpdk_cells.py +374 -0
  75. quantcore_circuits/layouts/qubits/sqdmetal_cells.py +376 -0
  76. quantcore_circuits/layouts/qubits/trilayer_concentric.py +65 -0
  77. quantcore_circuits/layouts/qubits/xmon.py +375 -0
  78. quantcore_circuits/layouts/registry.py +418 -0
  79. quantcore_circuits/layouts/wafers/__init__.py +0 -0
  80. quantcore_circuits/layouts/wafers/fab_export.py +454 -0
  81. quantcore_circuits/layouts/wafers/legacy_wafer.py +111 -0
  82. quantcore_circuits/layouts/wafers/wafer.py +469 -0
  83. quantcore_circuits/live/__init__.py +6 -0
  84. quantcore_circuits/live/klayout.py +225 -0
  85. quantcore_circuits/live/klive.py +61 -0
  86. quantcore_circuits/live/snapshot.py +185 -0
  87. quantcore_circuits/live/watch.py +93 -0
  88. quantcore_circuits/lom/__init__.py +15 -0
  89. quantcore_circuits/lom/builder.py +932 -0
  90. quantcore_circuits/lom/calibration.py +82 -0
  91. quantcore_circuits/lom/estimates.py +235 -0
  92. quantcore_circuits/lom/fragment.py +421 -0
  93. quantcore_circuits/lom/kqc_models.py +734 -0
  94. quantcore_circuits/lom/metal_models.py +917 -0
  95. quantcore_circuits/lom/quantcore_models.py +784 -0
  96. quantcore_circuits/lom/simulate.py +636 -0
  97. quantcore_circuits/lom/synthesize.py +189 -0
  98. quantcore_circuits/loop.py +610 -0
  99. quantcore_circuits/optimise.py +423 -0
  100. quantcore_circuits/pdk/__init__.py +451 -0
  101. quantcore_circuits/plots.py +876 -0
  102. quantcore_circuits/plugins.py +69 -0
  103. quantcore_circuits/review/__init__.py +57 -0
  104. quantcore_circuits/review/server.py +251 -0
  105. quantcore_circuits/review/static/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  106. quantcore_circuits/review/static/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  107. quantcore_circuits/review/static/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  108. quantcore_circuits/review/static/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  109. quantcore_circuits/review/static/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  110. quantcore_circuits/review/static/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  111. quantcore_circuits/review/static/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  112. quantcore_circuits/review/static/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  113. quantcore_circuits/review/static/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  114. quantcore_circuits/review/static/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  115. quantcore_circuits/review/static/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  116. quantcore_circuits/review/static/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  117. quantcore_circuits/review/static/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  118. quantcore_circuits/review/static/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  119. quantcore_circuits/review/static/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  120. quantcore_circuits/review/static/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  121. quantcore_circuits/review/static/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  122. quantcore_circuits/review/static/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  123. quantcore_circuits/review/static/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  124. quantcore_circuits/review/static/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  125. quantcore_circuits/review/static/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  126. quantcore_circuits/review/static/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  127. quantcore_circuits/review/static/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  128. quantcore_circuits/review/static/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  129. quantcore_circuits/review/static/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  130. quantcore_circuits/review/static/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  131. quantcore_circuits/review/static/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  132. quantcore_circuits/review/static/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  133. quantcore_circuits/review/static/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  134. quantcore_circuits/review/static/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  135. quantcore_circuits/review/static/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  136. quantcore_circuits/review/static/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  137. quantcore_circuits/review/static/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  138. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  139. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  140. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  141. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  142. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  143. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  144. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  145. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  146. quantcore_circuits/review/static/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  147. quantcore_circuits/review/static/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  148. quantcore_circuits/review/static/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  149. quantcore_circuits/review/static/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  150. quantcore_circuits/review/static/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  151. quantcore_circuits/review/static/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  152. quantcore_circuits/review/static/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  153. quantcore_circuits/review/static/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  154. quantcore_circuits/review/static/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  155. quantcore_circuits/review/static/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  156. quantcore_circuits/review/static/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  157. quantcore_circuits/review/static/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  158. quantcore_circuits/review/static/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  159. quantcore_circuits/review/static/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  160. quantcore_circuits/review/static/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  161. quantcore_circuits/review/static/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  162. quantcore_circuits/review/static/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  163. quantcore_circuits/review/static/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  164. quantcore_circuits/review/static/assets/index-CDHdrFyA.css +1 -0
  165. quantcore_circuits/review/static/assets/index-CSx05Og4.js +409 -0
  166. quantcore_circuits/review/static/assets/inter-cyrillic-400-normal-HOLc17fK.woff +0 -0
  167. quantcore_circuits/review/static/assets/inter-cyrillic-400-normal-obahsSVq.woff2 +0 -0
  168. quantcore_circuits/review/static/assets/inter-cyrillic-500-normal-BasfLYem.woff2 +0 -0
  169. quantcore_circuits/review/static/assets/inter-cyrillic-500-normal-CxZf_p3X.woff +0 -0
  170. quantcore_circuits/review/static/assets/inter-cyrillic-600-normal-4D_pXhcN.woff +0 -0
  171. quantcore_circuits/review/static/assets/inter-cyrillic-600-normal-CWCymEST.woff2 +0 -0
  172. quantcore_circuits/review/static/assets/inter-cyrillic-700-normal-CjBOestx.woff2 +0 -0
  173. quantcore_circuits/review/static/assets/inter-cyrillic-700-normal-DrXBdSj3.woff +0 -0
  174. quantcore_circuits/review/static/assets/inter-cyrillic-ext-400-normal-BQZuk6qB.woff2 +0 -0
  175. quantcore_circuits/review/static/assets/inter-cyrillic-ext-400-normal-DQukG94-.woff +0 -0
  176. quantcore_circuits/review/static/assets/inter-cyrillic-ext-500-normal-B0yAr1jD.woff2 +0 -0
  177. quantcore_circuits/review/static/assets/inter-cyrillic-ext-500-normal-BmqWE9Dz.woff +0 -0
  178. quantcore_circuits/review/static/assets/inter-cyrillic-ext-600-normal-Bcila6Z-.woff +0 -0
  179. quantcore_circuits/review/static/assets/inter-cyrillic-ext-600-normal-Dfes3d0z.woff2 +0 -0
  180. quantcore_circuits/review/static/assets/inter-cyrillic-ext-700-normal-BjwYoWNd.woff2 +0 -0
  181. quantcore_circuits/review/static/assets/inter-cyrillic-ext-700-normal-LO58E6JB.woff +0 -0
  182. quantcore_circuits/review/static/assets/inter-greek-400-normal-B4URO6DV.woff2 +0 -0
  183. quantcore_circuits/review/static/assets/inter-greek-400-normal-q2sYcFCs.woff +0 -0
  184. quantcore_circuits/review/static/assets/inter-greek-500-normal-BIZE56-Y.woff2 +0 -0
  185. quantcore_circuits/review/static/assets/inter-greek-500-normal-Xzm54t5V.woff +0 -0
  186. quantcore_circuits/review/static/assets/inter-greek-600-normal-BZpKdvQh.woff +0 -0
  187. quantcore_circuits/review/static/assets/inter-greek-600-normal-plRanbMR.woff2 +0 -0
  188. quantcore_circuits/review/static/assets/inter-greek-700-normal-BUv2fZ6O.woff +0 -0
  189. quantcore_circuits/review/static/assets/inter-greek-700-normal-C3JjAnD8.woff2 +0 -0
  190. quantcore_circuits/review/static/assets/inter-greek-ext-400-normal-DGGRlc-M.woff2 +0 -0
  191. quantcore_circuits/review/static/assets/inter-greek-ext-400-normal-KugGGMne.woff +0 -0
  192. quantcore_circuits/review/static/assets/inter-greek-ext-500-normal-2j5mBUwD.woff +0 -0
  193. quantcore_circuits/review/static/assets/inter-greek-ext-500-normal-C4iEst2y.woff2 +0 -0
  194. quantcore_circuits/review/static/assets/inter-greek-ext-600-normal-B8X0CLgF.woff +0 -0
  195. quantcore_circuits/review/static/assets/inter-greek-ext-600-normal-DRtmH8MT.woff2 +0 -0
  196. quantcore_circuits/review/static/assets/inter-greek-ext-700-normal-BoQ6DsYi.woff +0 -0
  197. quantcore_circuits/review/static/assets/inter-greek-ext-700-normal-qfdV9bQt.woff2 +0 -0
  198. quantcore_circuits/review/static/assets/inter-latin-400-normal-C38fXH4l.woff2 +0 -0
  199. quantcore_circuits/review/static/assets/inter-latin-400-normal-CyCys3Eg.woff +0 -0
  200. quantcore_circuits/review/static/assets/inter-latin-500-normal-BL9OpVg8.woff +0 -0
  201. quantcore_circuits/review/static/assets/inter-latin-500-normal-Cerq10X2.woff2 +0 -0
  202. quantcore_circuits/review/static/assets/inter-latin-600-normal-CiBQ2DWP.woff +0 -0
  203. quantcore_circuits/review/static/assets/inter-latin-600-normal-LgqL8muc.woff2 +0 -0
  204. quantcore_circuits/review/static/assets/inter-latin-700-normal-BLAVimhd.woff +0 -0
  205. quantcore_circuits/review/static/assets/inter-latin-700-normal-Yt3aPRUw.woff2 +0 -0
  206. quantcore_circuits/review/static/assets/inter-latin-ext-400-normal-77YHD8bZ.woff +0 -0
  207. quantcore_circuits/review/static/assets/inter-latin-ext-400-normal-C1nco2VV.woff2 +0 -0
  208. quantcore_circuits/review/static/assets/inter-latin-ext-500-normal-BxGbmqWO.woff +0 -0
  209. quantcore_circuits/review/static/assets/inter-latin-ext-500-normal-CV4jyFjo.woff2 +0 -0
  210. quantcore_circuits/review/static/assets/inter-latin-ext-600-normal-CIVaiw4L.woff +0 -0
  211. quantcore_circuits/review/static/assets/inter-latin-ext-600-normal-D2bJ5OIk.woff2 +0 -0
  212. quantcore_circuits/review/static/assets/inter-latin-ext-700-normal-Ca8adRJv.woff2 +0 -0
  213. quantcore_circuits/review/static/assets/inter-latin-ext-700-normal-TidjK2hL.woff +0 -0
  214. quantcore_circuits/review/static/assets/inter-vietnamese-400-normal-Bbgyi5SW.woff +0 -0
  215. quantcore_circuits/review/static/assets/inter-vietnamese-400-normal-DMkecbls.woff2 +0 -0
  216. quantcore_circuits/review/static/assets/inter-vietnamese-500-normal-DOriooB6.woff2 +0 -0
  217. quantcore_circuits/review/static/assets/inter-vietnamese-500-normal-mJboJaSs.woff +0 -0
  218. quantcore_circuits/review/static/assets/inter-vietnamese-600-normal-BuLX-rYi.woff +0 -0
  219. quantcore_circuits/review/static/assets/inter-vietnamese-600-normal-Cc8MFFhd.woff2 +0 -0
  220. quantcore_circuits/review/static/assets/inter-vietnamese-700-normal-BZaoP0fm.woff +0 -0
  221. quantcore_circuits/review/static/assets/inter-vietnamese-700-normal-DlLaEgI2.woff2 +0 -0
  222. quantcore_circuits/review/static/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  223. quantcore_circuits/review/static/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  224. quantcore_circuits/review/static/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
  225. quantcore_circuits/review/static/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
  226. quantcore_circuits/review/static/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  227. quantcore_circuits/review/static/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  228. quantcore_circuits/review/static/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
  229. quantcore_circuits/review/static/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
  230. quantcore_circuits/review/static/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  231. quantcore_circuits/review/static/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  232. quantcore_circuits/review/static/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  233. quantcore_circuits/review/static/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  234. quantcore_circuits/review/static/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  235. quantcore_circuits/review/static/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  236. quantcore_circuits/review/static/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  237. quantcore_circuits/review/static/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
  238. quantcore_circuits/review/static/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  239. quantcore_circuits/review/static/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
  240. quantcore_circuits/review/static/index.html +14 -0
  241. quantcore_circuits/review/static/logo-quantcore-black.png +0 -0
  242. quantcore_circuits/review/static/logo-quantcore-white.png +0 -0
  243. quantcore_circuits/review/static/sample/chip.png +0 -0
  244. quantcore_circuits/review/static/sample/chip_rev1.png +0 -0
  245. quantcore_circuits/review/static/sample/q1.png +0 -0
  246. quantcore_circuits/review/static/sample/q2.png +0 -0
  247. quantcore_circuits/review/static/sample-state.json +3747 -0
  248. quantcore_circuits/route/__init__.py +5 -0
  249. quantcore_circuits/route/router.py +694 -0
  250. quantcore_circuits/route/waveguide.py +187 -0
  251. quantcore_circuits/selftest.py +224 -0
  252. quantcore_circuits/sim_tools/__init__.py +6 -0
  253. quantcore_circuits/sim_tools/aedt_attach.py +66 -0
  254. quantcore_circuits/sim_tools/aedt_progress.py +224 -0
  255. quantcore_circuits/sim_tools/aedt_project.py +302 -0
  256. quantcore_circuits/sim_tools/aedt_scripts.py +397 -0
  257. quantcore_circuits/sim_tools/aedt_session.py +275 -0
  258. quantcore_circuits/sim_tools/ansys.py +90 -0
  259. quantcore_circuits/sim_tools/builder.py +1690 -0
  260. quantcore_circuits/sim_tools/export.py +470 -0
  261. quantcore_circuits/sim_tools/geometry_check.py +342 -0
  262. quantcore_circuits/sim_tools/hfss.py +583 -0
  263. quantcore_circuits/sim_tools/palace.py +197 -0
  264. quantcore_circuits/sim_tools/runner.py +179 -0
  265. quantcore_circuits/sim_tools/subset.py +364 -0
  266. quantcore_circuits/track.py +671 -0
  267. quantcore_circuits-0.0.1.dist-info/METADATA +204 -0
  268. quantcore_circuits-0.0.1.dist-info/RECORD +272 -0
  269. quantcore_circuits-0.0.1.dist-info/WHEEL +5 -0
  270. quantcore_circuits-0.0.1.dist-info/entry_points.txt +2 -0
  271. quantcore_circuits-0.0.1.dist-info/licenses/LICENSE +674 -0
  272. quantcore_circuits-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,44 @@
1
+ {
2
+ "schema": "qcc/0.1",
3
+ "name": "q1_r1_feedline",
4
+ "pdk": "quantcore_nb_sapphire_v1",
5
+ "chip": {
6
+ "box": [0, 0, 7500, 7500],
7
+ "params": {"with_grid": false, "name_chip": "Q1R1"}
8
+ },
9
+ "instances": {
10
+ "PAD_W": {"cell": "BondPad", "place": {"at": [1125, 3750], "rot": 270}},
11
+ "PAD_E": {"cell": "BondPad", "place": {"at": [6375, 3750], "rot": 90}},
12
+ "PAD_F": {"cell": "BondPad", "params": {"a": 4, "b": 6, "pad_width": 300, "pad_height": 300, "pad_gap": 150,
13
+ "taper_length": 300}, "place": {"at": [2964.5, 750], "rot": 0}},
14
+ "Q1": {
15
+ "cell": "Xmon",
16
+ "params": {"cross_length": 300, "arm_width": 25, "gap": 25, "claws": ["n"], "flux_port": true,
17
+ "junction_type": "Trilayer Squid"},
18
+ "place": {"at": [2975, 2200]},
19
+ "junction": {"Lj_nH": 12.0, "Cj_fF": 2.0}
20
+ }
21
+ },
22
+ "routes": {
23
+ "FL": {"from": "PAD_W.a", "to": "PAD_E.a", "type": "cpw", "airbridges": "none"},
24
+ "R1": {
25
+ "from": "Q1.claw_n",
26
+ "to": {"hanger": "FL", "s": 2000, "length": 300, "side": "right", "ground_gap": 6},
27
+ "type": "meander",
28
+ "length": 4200
29
+ },
30
+ "FLUX": {
31
+ "from": "PAD_F.a",
32
+ "to": "Q1.flux",
33
+ "a": 4, "b": 6,
34
+ "nodes": [{"at": [2964.5, 1967.0], "a": 1, "b": 7.5}]
35
+ }
36
+ },
37
+ "targets": {
38
+ "Q1": {"f_q_GHz": 5.1, "alpha_MHz": -220},
39
+ "R1": {"f_GHz": 7.2, "g_MHz": 90}
40
+ },
41
+ "sim_groups": {
42
+ "Q1R1": {"select": ["Q1", "R1"], "margin_um": 300, "analyses": ["q3d_cmatrix", "eigenmode_epr"]}
43
+ }
44
+ }
@@ -0,0 +1,44 @@
1
+ """design.json model: schema, loading and hashing."""
2
+
3
+ from quantcore_circuits.design.io import canonical_json, design_hash, load_design, save_design
4
+ from quantcore_circuits.design.schema import (
5
+ CHIP,
6
+ SCHEMA_VERSION,
7
+ Chip,
8
+ Coupling,
9
+ Design,
10
+ FreeEnd,
11
+ HangerEnd,
12
+ Instance,
13
+ Junction,
14
+ Launchers,
15
+ Place,
16
+ PortSpec,
17
+ Route,
18
+ SimGroup,
19
+ Waypoint,
20
+ split_port_ref,
21
+ )
22
+
23
+ __all__ = [
24
+ "CHIP",
25
+ "SCHEMA_VERSION",
26
+ "Chip",
27
+ "Coupling",
28
+ "Design",
29
+ "FreeEnd",
30
+ "HangerEnd",
31
+ "Instance",
32
+ "Junction",
33
+ "Launchers",
34
+ "Place",
35
+ "PortSpec",
36
+ "Route",
37
+ "SimGroup",
38
+ "Waypoint",
39
+ "canonical_json",
40
+ "design_hash",
41
+ "load_design",
42
+ "save_design",
43
+ "split_port_ref",
44
+ ]
@@ -0,0 +1,98 @@
1
+ """Load, save and hash designs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import runpy
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from quantcore_circuits.design.schema import Design
12
+
13
+
14
+ def load_design(source: str | Path | dict | Design) -> Design:
15
+ """Load a design from a ``.json`` file, a ``.py`` file, a dict or a :class:`Design`.
16
+
17
+ A ``.py`` design file must define ``design`` (a dict or :class:`Design`) or a function ``design()`` returning one.
18
+ """
19
+ if isinstance(source, Design):
20
+ return source
21
+ if isinstance(source, dict):
22
+ return Design.model_validate(source)
23
+ path = Path(source)
24
+ if path.suffix == ".py":
25
+ namespace = runpy.run_path(str(path), run_name="__qcc_design__")
26
+ obj = namespace.get("design")
27
+ if obj is None:
28
+ raise ValueError(f"{path} must define `design` (dict, Design or callable)")
29
+ if callable(obj) and not isinstance(obj, Design):
30
+ obj = obj()
31
+ return load_design(obj)
32
+ with open(path, encoding="utf-8") as f:
33
+ data = json.load(f)
34
+ data.setdefault("name", path.stem)
35
+ return Design.model_validate(data)
36
+
37
+
38
+ def save_design(design: Design, path: str | Path) -> Path:
39
+ path = Path(path)
40
+ path.write_text(json.dumps(design.to_json_dict(), indent=2) + "\n", encoding="utf-8")
41
+ return path
42
+
43
+
44
+ def canonical_json(data: Any) -> str:
45
+ """Deterministic JSON: sorted keys, no whitespace, floats normalised so 1 == 1.0."""
46
+
47
+ def norm(x):
48
+ if isinstance(x, dict):
49
+ return {str(k): norm(v) for k, v in x.items()}
50
+ if isinstance(x, (list, tuple)):
51
+ return [norm(v) for v in x]
52
+ if isinstance(x, float) and x.is_integer():
53
+ return int(x)
54
+ return x
55
+
56
+ return json.dumps(norm(data), sort_keys=True, separators=(",", ":"))
57
+
58
+
59
+ def tool_versions(pdk_name: str | None = None) -> dict[str, str]:
60
+ """Versions that change geometry or physics: quantcore-circuits, KQC, KLayout and the PDK."""
61
+ from importlib.metadata import PackageNotFoundError, version # pylint: disable=import-outside-toplevel
62
+
63
+ out = {}
64
+ for pkg in ("quantcore-circuits", "kqcircuits", "klayout"):
65
+ try:
66
+ out[pkg] = version(pkg)
67
+ except PackageNotFoundError:
68
+ out[pkg] = "unknown"
69
+ if pdk_name is not None:
70
+ from quantcore_circuits.pdk import get_pdk # pylint: disable=import-outside-toplevel
71
+
72
+ out["pdk"] = f"{pdk_name}@{get_pdk(pdk_name).version}"
73
+ return out
74
+
75
+
76
+ def design_hash(design: Design, extra: dict | None = None, short: bool = True) -> str:
77
+ """sha256 over the canonical design JSON plus tool versions (the results-store key).
78
+
79
+ ``targets`` are excluded: changing a target does not change geometry or simulation results.
80
+ """
81
+ data = design.to_json_dict()
82
+ data.pop("targets", None)
83
+ payload = {"design": data, "versions": tool_versions(design.pdk), "extra": extra or {}}
84
+ digest = hashlib.sha256(canonical_json(payload).encode("utf-8")).hexdigest()
85
+ return digest[:16] if short else digest
86
+
87
+
88
+ def group_hash(design: Design, group: str, short: bool = True) -> str:
89
+ """:func:`design_hash` of what one sim group's jobs see: the design with only that group's spec (the others are
90
+ left out), so adding or changing *another* sim group (a new subset) does not make this group's kept results look
91
+ like another revision. Written to ``job.json`` as ``group_hash`` (additive; older jobs only have
92
+ ``design_hash``)."""
93
+ data = design.to_json_dict()
94
+ data.pop("targets", None)
95
+ data["sim_groups"] = {group: data.get("sim_groups", {}).get(group)}
96
+ payload = {"design": data, "versions": tool_versions(design.pdk), "extra": {}}
97
+ digest = hashlib.sha256(canonical_json(payload).encode("utf-8")).hexdigest()
98
+ return digest[:16] if short else digest
@@ -0,0 +1,395 @@
1
+ """design.json → a readable Python script that rebuilds the same design with the :class:`Designer` API.
2
+
3
+ ``qcc design to-python DESIGN -o design.py`` (the KLayout plugin's *Design ▸ Save as Python script*) writes the script;
4
+ running it writes the design.json again (``python design.py`` or ``%run design.py``) and leaves the live
5
+ :class:`~quantcore_circuits.designer.Designer` as ``d`` so the chip can be continued as code.
6
+
7
+ The script is checked before it is returned: it is executed here and the design it builds must have the same
8
+ ``design_hash`` as the source. What the Designer calls cannot say (a static cell's ports, explicit ``nets``, another
9
+ chip cell, a coupling's ``fem`` flag, a waypoint's corner radius, …) is written for that one entry as a plain
10
+ ``d.data[...] = {...}`` assignment with a comment, so the round trip never silently drops anything.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import keyword
17
+ import re
18
+ from pathlib import Path
19
+
20
+ from quantcore_circuits.design import canonical_json, design_hash, load_design
21
+ from quantcore_circuits.designer import Designer
22
+
23
+ _ADD_ARGS = {"name", "cell", "at", "rot", "mirror", "snap", "to", "snap_gap", "junction", "edge", "self"}
24
+ _SECTIONS = ("instances", "routes", "couplings", "targets", "sim_groups")
25
+ _WIDTH = 100
26
+
27
+
28
+ class RoundTripError(RuntimeError):
29
+ """The generated script did not rebuild the same design."""
30
+
31
+
32
+ def _is_ident(name: str) -> bool:
33
+ return bool(re.fullmatch(r"[A-Za-z_]\w*", name)) and not keyword.iskeyword(name)
34
+
35
+
36
+ def _num(x) -> str:
37
+ if isinstance(x, float) and x.is_integer() and abs(x) < 1e15:
38
+ return f"{x:.1f}"
39
+ return repr(x)
40
+
41
+
42
+ def lit(value, indent: int = 0, width: int = _WIDTH) -> str:
43
+ """A Python literal for JSON-like ``value``: one line when it fits, else one entry per line."""
44
+ one = _one_line(value)
45
+ if len(one) + indent <= width or not isinstance(value, (dict, list)) or not value:
46
+ return one
47
+ pad = " " * (indent + 4)
48
+ if isinstance(value, dict):
49
+ body = [f"{pad}{json.dumps(str(k))}: {lit(v, indent + 4, width)}," for k, v in value.items()]
50
+ return "{\n" + "\n".join(body) + "\n" + " " * indent + "}"
51
+ body = [f"{pad}{lit(v, indent + 4, width)}," for v in value]
52
+ return "[\n" + "\n".join(body) + "\n" + " " * indent + "]"
53
+
54
+
55
+ def _one_line(value) -> str:
56
+ if isinstance(value, dict):
57
+ return "{" + ", ".join(f"{json.dumps(str(k))}: {_one_line(v)}" for k, v in value.items()) + "}"
58
+ if isinstance(value, (list, tuple)):
59
+ return "[" + ", ".join(_one_line(v) for v in value) + "]"
60
+ if isinstance(value, str):
61
+ return json.dumps(value, ensure_ascii=False)
62
+ if value is None or isinstance(value, bool):
63
+ return repr(value)
64
+ if isinstance(value, (int, float)):
65
+ return _num(value)
66
+ return repr(value)
67
+
68
+
69
+ def _point(p) -> str:
70
+ return f"({_num(p[0])}, {_num(p[1])})"
71
+
72
+
73
+ def _call(head: str, args: list[str], indent: int = 0) -> str:
74
+ """``head(a, b, k=v)`` on one line, or one argument per line when it is too long."""
75
+ one = f"{head}({', '.join(args)})"
76
+ if len(one) + indent <= _WIDTH:
77
+ return one
78
+ pad = " " * (indent + 4)
79
+ return f"{head}(\n" + "\n".join(f"{pad}{a}," for a in args) + f"\n{' ' * indent})"
80
+
81
+
82
+ def _kw(args: list[str], key: str, value, default=None) -> None:
83
+ if value is not None and value != default:
84
+ args.append(f"{key}={lit(value, 8)}")
85
+
86
+
87
+ # ---- one statement per design entry ---------------------------------------------------------------------------------
88
+ def _instance_stmt(name: str, spec: dict) -> str | None:
89
+ """``d.add(...)`` for an instance, or None when the Designer call cannot say it."""
90
+ params = spec.get("params") or {}
91
+ if spec.get("ports") or any(k in _ADD_ARGS or not _is_ident(k) for k in params):
92
+ return None
93
+ place = spec["place"]
94
+ args = [json.dumps(name), json.dumps(spec["cell"], ensure_ascii=False)]
95
+ if place.get("snap") is not None:
96
+ args += [f"snap={json.dumps(place['snap'])}", f"to={json.dumps(place['to'])}"]
97
+ _kw(args, "snap_gap", place.get("gap"), 0.0)
98
+ else:
99
+ args.append(f"at={_point(place['at'])}")
100
+ _kw(args, "rot", place.get("rot"), 0.0)
101
+ _kw(args, "edge", place.get("edge"))
102
+ _kw(args, "mirror", place.get("mirror") or None)
103
+ j = spec.get("junction")
104
+ if j:
105
+ jun = {k: v for k, v in j.items() if v is not None}
106
+ for key in ("Cj_fF", "flux_phi0", "asym"): # defaults stay out of the script
107
+ if jun.get(key) == 0.0:
108
+ jun.pop(key)
109
+ args.append(f"junction={lit(jun, 8)}")
110
+ args += [f"{k}={lit(v, 8)}" for k, v in params.items()]
111
+ return _call("d.add", args)
112
+
113
+
114
+ def _end_expr(end) -> str:
115
+ if isinstance(end, str):
116
+ return json.dumps(end)
117
+ if "hanger" in end:
118
+ near = end.get("near")
119
+ args = [f"s={_num(end['s'])}"] if end.get("s") is not None else [f"near={_point(near)}"]
120
+ args.append(f"length={_num(end['length'])}")
121
+ for key, default in (("side", "left"), ("ground_gap", 6.0), ("direction", "forward"), ("end", "short"),
122
+ ("open_gap", 6.0), ("bend", True), ("coupler_gap", None), ("line_gap", None)):
123
+ if end.get(key, default) != default:
124
+ args.append(f"{key}={lit(end[key])}")
125
+ return _call(f"d[{json.dumps(end['hanger'])}].hanger", args, 8)
126
+ args = [_point(end["at"])]
127
+ if end.get("dir") is not None:
128
+ args.append(f"dir={_num(end['dir'])}")
129
+ if end.get("term", 0.0) != 0.0:
130
+ args.append(f"term={_num(end['term'])}")
131
+ return _call("d.free_end", args, 8)
132
+
133
+
134
+ def _node_expr(node) -> str:
135
+ if not isinstance(node, dict):
136
+ return _point(node)
137
+ extra = {k: v for k, v in node.items() if k not in ("at", "airbridge", "a", "b", "params") and v is not None}
138
+ if extra or not all(_is_ident(k) for k in node.get("params") or {}):
139
+ return lit({k: v for k, v in node.items() if v not in (None, False, {})} | {"at": list(node["at"])}, 8)
140
+ args = [_point(node["at"])]
141
+ _kw(args, "a", node.get("a"))
142
+ _kw(args, "b", node.get("b"))
143
+ if node.get("airbridge"):
144
+ args.append("airbridge=True")
145
+ args += [f"{k}={lit(v)}" for k, v in (node.get("params") or {}).items()]
146
+ return _call("d.waypoint", args, 8)
147
+
148
+
149
+ def _route_stmt(name: str, spec: dict) -> str | None:
150
+ args = [json.dumps(name), _end_expr(spec["from"]), _end_expr(spec["to"])]
151
+ after = [] # options Designer.route cannot take: RouteHandle.set(...)
152
+ if spec.get("type") == "meander":
153
+ args.append(f"meander={_num(spec['length'])}")
154
+ elif spec.get("length") is not None:
155
+ after.append(f"length={_num(spec['length'])}")
156
+ if spec.get("nodes"):
157
+ nodes = [_node_expr(n) for n in spec["nodes"]]
158
+ one = "[" + ", ".join(nodes) + "]"
159
+ args.append(f"nodes={one}" if len(one) < 70 and "\n" not in one else
160
+ "nodes=[\n" + "".join(f" {n},\n" for n in nodes) + " ]")
161
+ for key in ("a", "b", "r"):
162
+ _kw(args, key, spec.get(key))
163
+ _kw(args, "airbridges", spec.get("airbridges"), "none")
164
+ _kw(args, "meander_direction", spec.get("meander_direction"), 1)
165
+ for key in ("meander_segment", "meanders"):
166
+ if spec.get(key) is not None and not (key == "meanders" and spec[key] == -1):
167
+ after.append(f"{key}={lit(spec[key])}")
168
+ if spec.get("params"):
169
+ after.append(f"params={lit(spec['params'], 8)}")
170
+ text = _call("d.route", args)
171
+ if after:
172
+ text += "." + _call("set", after)
173
+ return text
174
+
175
+
176
+ def _coupling_stmt(name: str, spec: dict) -> str | None:
177
+ if spec.get("fem", True) is not True:
178
+ return None
179
+ args = [json.dumps(name), json.dumps(spec["between"][0]), json.dumps(spec["between"][1])]
180
+ kind, value = spec.get("type", "C"), spec.get("value")
181
+ if kind == "wire":
182
+ args.append("wire=True")
183
+ elif kind == "L":
184
+ args.append(f"L_nH={_num(value)}")
185
+ elif value is not None:
186
+ args.append(f"C_fF={_num(value)}")
187
+ if spec.get("note"):
188
+ args.append(f"note={json.dumps(spec['note'], ensure_ascii=False)}")
189
+ return _call("d.couple", args)
190
+
191
+
192
+ def _group_stmt(name: str, spec: dict) -> str | None:
193
+ args = [json.dumps(name), lit(spec["select"], 8)]
194
+ _kw(args, "margin_um", spec.get("margin_um"), 300.0)
195
+ _kw(args, "analyses", spec.get("analyses"), ["eigenmode_epr", "q3d_cmatrix"])
196
+ _kw(args, "ports", spec.get("ports") or None)
197
+ _kw(args, "settings", spec.get("settings") or None)
198
+ return _call("d.sim_group", args)
199
+
200
+
201
+ def _targets_stmt(targets: dict) -> str | None:
202
+ if not targets or not all(_is_ident(k) for k in targets):
203
+ return None
204
+ body = "".join(f" {k}={lit(v, 4)},\n" for k, v in targets.items())
205
+ return "d.targets(\n" + body + ")"
206
+
207
+
208
+ def _raw_stmt(section: str, name: str, spec) -> str:
209
+ return f"d.data[{json.dumps(section)}][{json.dumps(name)}] = {lit(spec)}"
210
+
211
+
212
+ # ---- ordering -------------------------------------------------------------------------------------------------------
213
+ def _instance_order(instances: dict) -> list[str]:
214
+ """Snap-placed instances after the instance they snap to (the Designer checks each ``add`` at once)."""
215
+ out, seen = [], set()
216
+
217
+ def visit(name, stack=()):
218
+ if name in seen or name in stack:
219
+ return
220
+ to = (instances[name]["place"].get("to") or "").split(".", 1)[0]
221
+ if to in instances and to != name:
222
+ visit(to, (*stack, name))
223
+ seen.add(name)
224
+ out.append(name)
225
+
226
+ for n in instances:
227
+ visit(n)
228
+ return out
229
+
230
+
231
+ def _route_order(routes: dict) -> list[str]:
232
+ """Routes that hang off another route after it."""
233
+ out, seen = [], set()
234
+
235
+ def visit(name, stack=()):
236
+ if name in seen or name in stack:
237
+ return
238
+ for end in (routes[name]["from"], routes[name]["to"]):
239
+ if isinstance(end, dict) and end.get("hanger") in routes:
240
+ visit(end["hanger"], (*stack, name))
241
+ seen.add(name)
242
+ out.append(name)
243
+
244
+ for n in routes:
245
+ visit(n)
246
+ return out
247
+
248
+
249
+ # ---- the script -----------------------------------------------------------------------------------------------------
250
+ def _header(data: dict) -> str:
251
+ chip = data["chip"]
252
+ args = [json.dumps(data["name"]), f"box=({', '.join(_num(v) for v in chip['box'])})"]
253
+ if data["pdk"] != Designer("x").data["pdk"]:
254
+ args.append(f"pdk={json.dumps(data['pdk'])}")
255
+ if chip.get("launchers") is not None:
256
+ args.append(f"launchers={lit(chip['launchers'], 4)}")
257
+ params = {k: v for k, v in (chip.get("params") or {}).items() if not (k == "with_grid" and v is False)}
258
+ if params:
259
+ args.append(f"chip={lit(params, 4)}")
260
+ return _call("d = Designer", args)
261
+
262
+
263
+ def _statements(data: dict, raw: set) -> list[tuple[str, str | None, str]]:
264
+ """(section, entry name, statement) in build order; ``raw`` entries are written as ``d.data[...]`` assignments."""
265
+ out = []
266
+
267
+ def one(section, name, fn):
268
+ spec = data[section][name]
269
+ stmt = None if (section, name) in raw else fn(name, spec)
270
+ out.append((section, name, stmt if stmt is not None else _raw_stmt(section, name, spec)))
271
+
272
+ for n in _instance_order(data["instances"]):
273
+ one("instances", n, _instance_stmt)
274
+ for n in _route_order(data["routes"]):
275
+ one("routes", n, _route_stmt)
276
+ for n in data.get("couplings") or {}:
277
+ one("couplings", n, _coupling_stmt)
278
+ if data.get("targets"):
279
+ stmt = None if "targets" in raw else _targets_stmt(data["targets"])
280
+ out.append(("targets", None, stmt or "d.data[\"targets\"] = " + lit(data["targets"])))
281
+ for n in data.get("sim_groups") or {}:
282
+ one("sim_groups", n, _group_stmt)
283
+ return out
284
+
285
+
286
+ def _fixes(data: dict, raw: set) -> list[str]:
287
+ """What the Designer arguments do not cover: another chip cell, explicit ``nets``."""
288
+ out = []
289
+ chip = data["chip"]
290
+ if chip.get("cell") != "quantcore_circuits.assembly.DesignChip" or "chip" in raw:
291
+ out.append("d.data[\"chip\"] = " + lit(chip))
292
+ elif "with_grid" not in (chip.get("params") or {}):
293
+ out.append("d.data[\"chip\"][\"params\"].pop(\"with_grid\") # the Designer adds with_grid=False by default")
294
+ if data.get("nets", "derived") != "derived":
295
+ out.append("d.data[\"nets\"] = " + lit(data["nets"]))
296
+ return out
297
+
298
+
299
+ _PRELUDE = "from pathlib import Path\n\nfrom quantcore_circuits.designer import Designer\n"
300
+
301
+
302
+ def _compose(data: dict, raw: set, label: str) -> tuple[str, list]:
303
+ """(script text, its statements)."""
304
+ stmts = _statements(data, raw)
305
+ lines = [
306
+ f'"""Rebuilds the design "{data["name"]}" with the Quantcore Designer API.',
307
+ "",
308
+ f"Generated by `qcc design to-python` from {label}. Run it (`python design.py`) to write the design.json",
309
+ "again, or `%run` it in a notebook to carry on drawing as code: `d` is the live Designer.",
310
+ '"""',
311
+ "",
312
+ *_PRELUDE.rstrip("\n").split("\n"),
313
+ "",
314
+ _header(data),
315
+ ]
316
+ last = None
317
+ for section, _name, stmt in stmts:
318
+ if section != last:
319
+ lines += ["", f"# {section.replace('_', ' ')}"]
320
+ last = section
321
+ if stmt.startswith("d.data["):
322
+ stmt = "# (plain data: the Designer call cannot say every field of this entry)\n" + stmt
323
+ lines.append(stmt)
324
+ fixes = _fixes(data, raw)
325
+ if fixes:
326
+ lines += ["", "# chip and net settings the Designer arguments do not cover", *fixes]
327
+ lines += ["", 'if __name__ == "__main__":', f" d.save(Path(__file__).with_name({json.dumps(data['name'] + '.json')}))", ""]
328
+ return "\n".join(lines), stmts
329
+
330
+
331
+ def _run(data: dict, stmts: list, raw: set):
332
+ """Execute the header and statements; (Designer, None), or (None, entry that failed, error text)."""
333
+ ns: dict = {}
334
+ exec(_PRELUDE, ns) # noqa: S102
335
+ exec(_header(data), ns) # noqa: S102
336
+ for section, name, stmt in stmts:
337
+ try:
338
+ exec(stmt, ns) # noqa: S102
339
+ except Exception as e: # noqa: BLE001
340
+ return None, (section, name) if name else section, f"{type(e).__name__}: {e}"
341
+ for fix in _fixes(data, raw):
342
+ exec(fix, ns) # noqa: S102
343
+ return ns["d"], None, ""
344
+
345
+
346
+ def _diff(want: dict, got: dict) -> set:
347
+ """Entries ``(section, name)`` (or ``"targets"`` / ``"chip"``) where the rebuilt design differs from the source."""
348
+ bad = set()
349
+ for section in ("instances", "routes", "couplings", "sim_groups"):
350
+ w, g = want.get(section) or {}, got.get(section) or {}
351
+ bad |= {(section, n) for n in set(w) | set(g) if canonical_json(w.get(n)) != canonical_json(g.get(n))}
352
+ if canonical_json(want.get("targets") or {}) != canonical_json(got.get("targets") or {}):
353
+ bad.add("targets")
354
+ if canonical_json(want["chip"]) != canonical_json(got["chip"]):
355
+ bad.add("chip")
356
+ return bad
357
+
358
+
359
+ def design_to_python(source, check: bool = True) -> str:
360
+ """The script text for ``source`` (a design file, dict or :class:`Design`). With ``check`` (default) the script is
361
+ executed and must rebuild a design with the same ``design_hash`` (else :class:`RoundTripError`); an entry the
362
+ Designer rejects or rebuilds differently is written as plain data."""
363
+ design = load_design(source)
364
+ data = design.to_json_dict()
365
+ label = Path(source).name if isinstance(source, (str, Path)) else f"the design {design.name}"
366
+ raw: set = set()
367
+ script, stmts = _compose(data, raw, label)
368
+ if not check:
369
+ return script
370
+ for _ in range(6):
371
+ built, failed, error = _run(data, stmts, raw)
372
+ if built is None:
373
+ if failed in raw or failed is None:
374
+ raise RoundTripError(f"{design.name}: the generated script fails at {failed}: {error}")
375
+ raw.add(failed)
376
+ else:
377
+ rebuilt = built.design
378
+ if design_hash(rebuilt) == design_hash(design) and canonical_json(rebuilt.to_json_dict()) == canonical_json(data):
379
+ return script
380
+ bad = _diff(data, rebuilt.to_json_dict()) - raw
381
+ if not bad:
382
+ raise RoundTripError(f"{design.name}: the rebuilt design differs from the source in an unexpected place")
383
+ raw |= bad
384
+ script, stmts = _compose(data, raw, label)
385
+ raise RoundTripError(f"{design.name}: the generated script does not rebuild the same design")
386
+
387
+
388
+ def write_python(source, out: str | Path, check: bool = True) -> Path:
389
+ out = Path(out)
390
+ out.parent.mkdir(parents=True, exist_ok=True)
391
+ out.write_text(design_to_python(source, check=check), encoding="utf-8")
392
+ return out
393
+
394
+
395
+ __all__ = ["RoundTripError", "design_to_python", "lit", "write_python"]