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,1038 @@
1
+ """Surrogates (M11) and the co-design loop (M12): extracted parameters → new knob values → new design revision.
2
+
3
+ **Elements.** Every transmon–readout pair of the filled circuit (:func:`~quantcore_circuits.circuit.fill.fill`:
4
+ grounded and floating qubits, λ/4 and λ/2 readouts) reduces to the same 2-node network: ``C_island`` (island →
5
+ ground, the qubit mode of a floating transmon), ``Cg`` (island ↔ coupler) and ``C_coupler`` (coupler → ground), plus
6
+ the junction ``Lj_nH`` and the resonator line (``length_um``, λ/4 or λ/2).
7
+
8
+ **Surrogate (knob → element value).** Each capacitance gets a power law in the geometry knobs,
9
+ ``v = v0 (k/k0)^p · Π (k_j/k_j0)^p_j``, anchored at the latest point (space mapping: the anchor is the measurement —
10
+ FEM, or the layout's own estimates — so the surrogate is exact there). The exponents are the local sensitivities of
11
+ the component's own LOM model (its fragment re-evaluated at ±2 % of each knob, the branch values scaled by
12
+ estimate(k)/estimate(k0) and reduced to the pair), so they hold for every qubit class with a LOM model; an Xmon's
13
+ are its calibration exponents (1.0, 1.0, 0.8). With two or more FEM points at different knob values the primary
14
+ exponent is refitted (log–log least squares). Junction inductance and resonator length are knobs themselves.
15
+
16
+ Knobs per class (:data:`QUBIT_KNOBS`: the island-capacitance knob, the coupler knob for C_g; ``<node>`` is the
17
+ readout coupler's node in the qubit's LOM, e.g. ``claw_n``, ``cplr1``, ``readout``):
18
+
19
+ ======================================= ================================ =======================================
20
+ class island (C_Σ) coupler (C_g)
21
+ ======================================= ================================ =======================================
22
+ ``Xmon`` ``cross_length`` ``claw_length``
23
+ ``Swissmon`` ``arm_length.*`` (all four arms) ``cpl_length.<i>``
24
+ ``CircularTransmonSingleIsland`` ``r_island`` ``couplers_arc_amplitude.<i>``
25
+ ``ConcentricTransmon`` ``r_inner`` ``couplers_arc_amplitude.<i>``
26
+ ``DoublePads(Splines)`` ``island_island_gap`` ``coupler_extent.0``
27
+ ``TwoPadTransmon`` ``pad_height`` its coupler cell (below)
28
+ ``Flipmon`` ``top_circle_radius`` ``coupler_length``
29
+ ``Gatemon`` ``island_size.*`` its coupler cell (below)
30
+ ``TransmonTaperedInsets`` ``pad_width`` ``connection_pads.<node>.pad_width``
31
+ ``metal:TransmonPocket`` (CL, 6, Teeth) ``pad_width`` ``connection_pads.<node>.pad_width``
32
+ ``metal:TransmonCross`` (FL) ``cross_length`` ``connection_pads.<node>.claw_length``
33
+ ``metal:TransmonStar`` ``arm_length`` ``connection_pads.<node>.claw_length``
34
+ ``metal:TransmonConcentric`` ``gap`` ``res_s``
35
+ ``metal:TransmonConcentricType2`` ``gap`` ``finger_<NE|NW|SW>_length``
36
+ ``metal:TransmonInterdigitated`` ``finger_height`` ``cc_width`` (bus: ``cc_top*_width``)
37
+ ``metal:StarQubit`` ``center_radius`` ``gap_readout`` / ``gap_couplers``
38
+ coupler cells (:data:`COUPLER_KNOBS`) ``PadCoupler.pad_height`` ``GatemonCoupler.coupling_capacitance``
39
+ ======================================= ================================ =======================================
40
+
41
+ ``L_J``: ``<Q>.junction.Lj_nH`` when the design sets it (a drawn junction without a design value is not tuned).
42
+ Resonator: the TLres knob (``<R>.length``, a line cell's ``resonator_length`` / ``cpw_len``), or the one meander route
43
+ with a length on the resonator's conductor; the rest of the line is a constant ``extra_length_um``. A knob that is
44
+ missing, not a number or without effect in the LOM is left out and the surrogate says why (``notes``).
45
+
46
+ **Forward model.** Elements → the same 2-node network the estimators quantise (:class:`~quantcore_circuits.circuit.
47
+ fill.TransmonReadout`, λ/4 or λ/2) → the dressed spectrum of :mod:`quantcore_circuits.circuit.hamiltonian`
48
+ (transmon in the charge basis + resonator, no RWA; diagonalised with numpy, the same matrices as the QuTiP model)
49
+ → f_q, α, f_r, g, χ.
50
+
51
+ **Proposal (L0 + L1).** Bounded least squares over the knobs on ``(predicted − target)/tol`` for the four targets;
52
+ a knob whose target is not set stays where it is (no α target: the island knob is kept, and so on). When the
53
+ surrogate can re-evaluate the LOM (``surrogate_from_fill`` on a real circuit), the solution is checked against the
54
+ LOM at the proposed knobs and the exponents corrected along the move (secant), up to three times, and if that does
55
+ not settle the last solve runs on the LOM itself: a large move stays accurate for non-power-law estimates. (The LOM
56
+ rounds its estimates to 2–3 significant figures; a rebuilt revision can differ from the proposal by that, and a
57
+ second Propose closes the gap.) The result is a new design revision
58
+ (``build/<name>/revisions/rev<k>.json``); the source design is never touched unless :func:`accept` is called.
59
+
60
+ **Loop (L2).** :func:`run` repeats evaluate → update surrogates → propose until every target is within tolerance or
61
+ ``max_iter``; ``evaluate(design) -> FilledCircuit`` is the FEM step (Q3D/Palace job → :func:`circuit.fill.fill`),
62
+ or any stand-in for testing.
63
+ """
64
+
65
+ from __future__ import annotations
66
+
67
+ import copy
68
+ import json
69
+ import math
70
+ import re
71
+ from dataclasses import asdict, dataclass, field
72
+ from pathlib import Path
73
+
74
+ import numpy as np
75
+
76
+ from quantcore_circuits.circuit.fill import FilledCircuit, TransmonReadout
77
+
78
+
79
+ @dataclass
80
+ class ElementModel:
81
+ element: str
82
+ knob: str | None # primary knob (None: the element has no geometry knob and keeps its anchor value)
83
+ k0: float
84
+ v0: float
85
+ p: float = 1.0
86
+ prior_p: float = 1.0
87
+ samples: list[tuple[float, float]] = field(default_factory=list)
88
+ # secondary knobs (additive): knob → [k0, exponent], e.g. a floating qubit's island C on its coupler pad's width
89
+ others: dict[str, list[float]] = field(default_factory=dict)
90
+
91
+ def predict(self, k: float) -> float:
92
+ return self.v0 * (k / self.k0) ** self.p
93
+
94
+ def value(self, knobs: dict[str, float]) -> float:
95
+ """The element at ``knobs`` (primary and secondary knobs; a knob missing from ``knobs`` stays at its k0)."""
96
+ v = self.predict(knobs[self.knob]) if self.knob is not None and self.knob in knobs else self.v0
97
+ for k, (k0, p) in self.others.items():
98
+ if k in knobs:
99
+ v *= (knobs[k] / k0) ** p
100
+ return v
101
+
102
+ def invert(self, v: float) -> float:
103
+ return self.k0 * (v / self.v0) ** (1 / self.p)
104
+
105
+ def add(self, k: float | None, v: float, knobs: dict[str, float] | None = None) -> None:
106
+ """New FEM point: re-anchor, and refit the exponent when the knob has moved (the sign of the prior is kept:
107
+ a gap knob lowers its capacitance). ``knobs``: the point's other knob values (re-anchors ``others``)."""
108
+ for name, entry in self.others.items():
109
+ if knobs and name in knobs:
110
+ entry[0] = float(knobs[name])
111
+ if self.knob is None or k is None:
112
+ self.v0 = float(v)
113
+ return
114
+ self.samples.append((float(k), float(v)))
115
+ self.k0, self.v0 = float(k), float(v)
116
+ ks = np.array([s[0] for s in self.samples])
117
+ vs = np.array([s[1] for s in self.samples])
118
+ if len(set(np.round(ks, 9))) >= 2 and (vs > 0).all():
119
+ slope = np.polyfit(np.log(ks), np.log(vs), 1)[0]
120
+ self.p = float(np.clip(slope, 0.1, 3.0) if self.prior_p >= 0 else np.clip(slope, -3.0, -0.1))
121
+
122
+
123
+ @dataclass
124
+ class PairSurrogate:
125
+ """Surrogate for one transmon + λ/4 or λ/2 readout pair (module docstring)."""
126
+
127
+ qubit: str
128
+ resonator: str
129
+ c_island: ElementModel
130
+ cg: ElementModel
131
+ c_coupler: ElementModel
132
+ lj_nH: float
133
+ cj_fF: float
134
+ length_um: float # the resonator knob's value (the line is length_um + extra_length_um long)
135
+ a_um: float
136
+ b_um: float
137
+ pdk: str
138
+ # additive fields; the defaults keep the λ/4 + <Q>.junction.Lj_nH + <R>.length surrogate of the synthesis
139
+ kind: str = "lambda/4"
140
+ extra_length_um: float = 0.0
141
+ lj_knob: str | None = "" # "": <qubit>.junction.Lj_nH; None: L_J is not a knob
142
+ length_knob: str | None = "" # "": <resonator>.length; None: the resonator length is not a knob
143
+ lj_scale: float = 1.0 # model L_J / knob value (a list of junction values: the first over their mean)
144
+ cell: str = ""
145
+ notes: list[str] = field(default_factory=list)
146
+
147
+ def __post_init__(self):
148
+ if self.lj_knob == "":
149
+ self.lj_knob = f"{self.qubit}.junction.Lj_nH"
150
+ if self.length_knob == "":
151
+ self.length_knob = f"{self.resonator}.length"
152
+
153
+ @property
154
+ def knobs(self) -> dict[str, float]:
155
+ out: dict[str, float] = {}
156
+ for m in (self.c_island, self.cg):
157
+ if m.knob is not None:
158
+ out.setdefault(m.knob, m.k0)
159
+ if self.lj_knob:
160
+ out[self.lj_knob] = self.lj_nH / self.lj_scale
161
+ if self.length_knob:
162
+ out[self.length_knob] = self.length_um
163
+ return out
164
+
165
+ def elements(self, knobs: dict[str, float]) -> dict[str, float]:
166
+ lj = knobs[self.lj_knob] * self.lj_scale if self.lj_knob and self.lj_knob in knobs else self.lj_nH
167
+ length = knobs[self.length_knob] if self.length_knob and self.length_knob in knobs else self.length_um
168
+ return {
169
+ "C_island_fF": self.c_island.value(knobs),
170
+ "Cg_fF": self.cg.value(knobs),
171
+ "C_coupler_fF": self.c_coupler.value(knobs),
172
+ "Lj_nH": lj,
173
+ "length_um": length + self.extra_length_um,
174
+ }
175
+
176
+ def predict(self, knobs: dict[str, float]) -> dict[str, float]:
177
+ return forward(
178
+ self.elements(knobs), self.cj_fF, self.a_um, self.b_um, self.pdk, self.qubit, self.resonator, self.kind
179
+ )
180
+
181
+ def to_json(self) -> dict:
182
+ return asdict(self)
183
+
184
+ def _with_lom(self, lom, paths: dict) -> PairSurrogate:
185
+ """Attach the LOM re-evaluation (:class:`_PairLom`, not part of :meth:`to_json`) that :func:`propose` uses to
186
+ check and refine a proposal; ``paths``: geometry knob → (instance, parameter path)."""
187
+ self._lom = lom # pylint: disable=attribute-defined-outside-init
188
+ self._paths = paths # pylint: disable=attribute-defined-outside-init
189
+ return self
190
+
191
+
192
+ def forward(
193
+ el: dict,
194
+ cj_fF: float,
195
+ a_um: float,
196
+ b_um: float,
197
+ pdk: str,
198
+ qubit: str = "Q",
199
+ resonator: str = "R",
200
+ kind: str = "lambda/4",
201
+ ) -> dict:
202
+ """Element values → dressed parameters, keyed like the targets. ``el["length_um"]`` is the whole line; ``kind``
203
+ its mode (``"lambda/2"``: twice the λ/4 frequency of the same line, the λ/2 equivalent LC)."""
204
+ from quantcore_circuits.circuit.bridges import tl_resonator # pylint: disable=import-outside-toplevel
205
+ from quantcore_circuits.circuit.fill import _tl_kind, two_node_model # pylint: disable=import-outside-toplevel
206
+
207
+ cg = el["Cg_fF"]
208
+ maxwell = np.array([[el["C_island_fF"] + cg, -cg], [-cg, el["C_coupler_fF"] + cg]])
209
+ tl = tl_resonator(el["length_um"], a_um, b_um, pdk)
210
+ if kind != "lambda/4":
211
+ tl = _tl_kind(tl, kind)
212
+ pair = TransmonReadout(
213
+ qubit, resonator, ["i", "c"], maxwell, el["Lj_nH"], cj_fF, tl["f_GHz"], tl["Z0_ohm"], kind=kind
214
+ )
215
+ tn = two_node_model(pair)
216
+ d = dressed_levels(tn["EJ_GHz"], tn["EC_GHz"], tn["f_r_loaded_GHz"], tn["g_n_MHz"], nq=5, nr=5)
217
+ return {
218
+ f"{qubit}.f_q_GHz": d["f_q_GHz"],
219
+ f"{qubit}.alpha_MHz": d["alpha_MHz"],
220
+ f"{resonator}.f_GHz": d["f_r_GHz"],
221
+ f"{resonator}.g_MHz": d["g_MHz"],
222
+ f"{resonator}.chi_MHz": d["chi_MHz"],
223
+ }
224
+
225
+
226
+ def dressed_levels(ej_GHz: float, ec_GHz: float, f_r_GHz: float, g_n_MHz: float, nq: int = 5, nr: int = 5,
227
+ ncut: int = 20) -> dict:
228
+ """:func:`quantcore_circuits.circuit.hamiltonian.dressed` of the same model (charge-basis transmon truncated to
229
+ ``nq`` levels + resonator + g_n n̂(a + a†), no RWA), built and diagonalised with numpy instead of QuTiP objects
230
+ (the surrogate's forward model runs it hundreds of times; same matrices, same bare-state labelling)."""
231
+ n = np.arange(-ncut, ncut + 1)
232
+ ht = np.diag(4 * ec_GHz * n.astype(float) ** 2) - ej_GHz / 2 * (np.eye(len(n), k=1) + np.eye(len(n), k=-1))
233
+ e, v = np.linalg.eigh(ht)
234
+ v = v[:, :nq]
235
+ eq = e[:nq] - e[0]
236
+ nmat = v.T @ np.diag(n.astype(float)) @ v
237
+ a = np.diag(np.sqrt(np.arange(1, nr, dtype=float)), 1)
238
+ h = np.kron(np.diag(eq), np.eye(nr)) + f_r_GHz * np.kron(np.eye(nq), a.T @ a)
239
+ h = h + g_n_MHz / 1e3 * np.kron(nmat, a + a.T)
240
+ evals, evecs = np.linalg.eigh(h)
241
+ evals = evals - evals[0]
242
+ idx = np.argmax(np.abs(evecs) ** 2, axis=0)
243
+ labels = [(int(k) // nr, int(k) % nr) for k in idx]
244
+
245
+ def lev(qn, rn):
246
+ return float(evals[labels.index((qn, rn))])
247
+
248
+ return {
249
+ "f_q_GHz": lev(1, 0),
250
+ "f_r_GHz": lev(0, 1),
251
+ "alpha_MHz": (lev(2, 0) - 2 * lev(1, 0)) * 1e3,
252
+ "chi_MHz": (lev(1, 1) - lev(1, 0) - lev(0, 1)) * 1e3,
253
+ "g_MHz": g_n_MHz * abs(nmat[0, 1]),
254
+ }
255
+
256
+
257
+ PRIORS = {"C_island": 1.0, "Cg": 1.0, "C_coupler": 0.8}
258
+
259
+ # ---- knobs per qubit class (module docstring) ------------------------------------------------------------------------
260
+ _CORNERS = {"pin1": "NE", "pin2": "NW", "pin3": "SW"}
261
+ _INTERDIGITATED = {"readout": "cc", "bus1": "cc_topleft", "bus2": "cc_topright"}
262
+
263
+
264
+ def _index(node: str, base: int) -> str | None:
265
+ m = re.search(r"(\d+)$", node or "")
266
+ return str(int(m.group(1)) - base) if m else None
267
+
268
+
269
+ def _pads(option: str):
270
+ return lambda node: f"connection_pads.{node}.{option}" if node else None
271
+
272
+
273
+ # class → (island knob, coupler knob as a function of the readout coupler's local node); paths are under the instance
274
+ QUBIT_KNOBS: dict[str, tuple] = {
275
+ "Xmon": ("cross_length", lambda node: "claw_length"),
276
+ "Swissmon": ("arm_length.*", lambda node: f"cpl_length.{_index(node, 0)}" if _index(node, 0) else None),
277
+ "CircularTransmonSingleIsland": (
278
+ "r_island", lambda node: f"couplers_arc_amplitude.{_index(node, 1)}" if _index(node, 1) else None),
279
+ "ConcentricTransmon": (
280
+ "r_inner", lambda node: f"couplers_arc_amplitude.{_index(node, 1)}" if _index(node, 1) else None),
281
+ "DoublePads": ("island_island_gap", lambda node: "coupler_extent.0"),
282
+ "DoublePadsSplines": ("island_island_gap", lambda node: "coupler_extent.0"),
283
+ "TwoPadTransmon": ("pad_height", lambda node: None),
284
+ "Flipmon": ("top_circle_radius", lambda node: "coupler_length"),
285
+ "Gatemon": ("island_size.*", lambda node: None),
286
+ "TransmonTaperedInsets": ("pad_width", _pads("pad_width")),
287
+ "metal:TransmonPocket": ("pad_width", _pads("pad_width")),
288
+ "metal:TransmonPocketCL": ("pad_width", _pads("pad_width")),
289
+ "metal:TransmonPocket6": ("pad_width", _pads("pad_width")),
290
+ "metal:TransmonPocketTeeth": ("pad_width", _pads("pad_width")),
291
+ "metal:TransmonCross": ("cross_length", _pads("claw_length")),
292
+ "metal:TransmonCrossFL": ("cross_length", _pads("claw_length")),
293
+ "metal:TransmonStar": ("arm_length", _pads("claw_length")),
294
+ "metal:TransmonConcentric": ("gap", lambda node: "res_s" if node == "pin1" else None),
295
+ "metal:TransmonConcentricType2": (
296
+ "gap", lambda node: f"finger_{_CORNERS[node]}_length" if node in _CORNERS else None),
297
+ "metal:TransmonInterdigitated": (
298
+ "finger_height", lambda node: f"{_INTERDIGITATED[node]}_width" if node in _INTERDIGITATED else None),
299
+ "metal:StarQubit": (
300
+ "center_radius", lambda node: "gap_readout" if node == "pin_rdout" else ("gap_couplers" if node else None)),
301
+ }
302
+ # cells that put C_g between a qubit and its readout line (the qubit's own rule has no coupler knob)
303
+ COUPLER_KNOBS: dict[str, str] = {"PadCoupler": "pad_height", "GatemonCoupler": "coupling_capacitance"}
304
+ SENSITIVITY_STEP = 0.02 # relative knob step of the LOM sensitivities (central difference)
305
+ MIN_EXPONENT = 0.02 # |d ln C / d ln k| below this on every element: the knob does nothing in the LOM
306
+
307
+
308
+ def _cell_classes(cell: str) -> list[str]:
309
+ """Rule keys of a cell, most specific first: ``metal:<Class>`` (and its Metal bases), else the class and its MRO."""
310
+ if cell.startswith("metal:"):
311
+ from quantcore_circuits.layouts.metal import canonical_class_name # pylint: disable=import-outside-toplevel
312
+ from quantcore_circuits.lom.metal_models import metal_mro # pylint: disable=import-outside-toplevel
313
+
314
+ try:
315
+ name = canonical_class_name(cell.split(":", 1)[1])
316
+ except (ImportError, ValueError):
317
+ name = cell.split(":", 1)[1]
318
+ return [f"metal:{c}" for c in metal_mro(name)]
319
+ try:
320
+ from quantcore_circuits.layouts.registry import resolve_cell # pylint: disable=import-outside-toplevel
321
+
322
+ return [k.__name__ for k in resolve_cell(cell).__mro__]
323
+ except Exception: # noqa: BLE001 (an unknown cell: no rule)
324
+ return [cell]
325
+
326
+
327
+ def _rule(table: dict, cell: str):
328
+ return next((table[c] for c in _cell_classes(cell) if c in table), None)
329
+
330
+
331
+ def _num_knob(design, knob: str) -> float | None:
332
+ """The knob's value as a positive float, or None (missing, not a number, zero)."""
333
+ from quantcore_circuits.optimise import get_knob, knob_number # pylint: disable=import-outside-toplevel
334
+
335
+ try:
336
+ v = knob_number(get_knob(design, knob))
337
+ except (KeyError, ValueError, TypeError, IndexError):
338
+ return None
339
+ return v if np.isfinite(v) and v > 0 else None
340
+
341
+
342
+ class _PairLom:
343
+ """The LOM side of one pair: re-evaluates the components that own its knobs and reduces the circuit to the pair's
344
+ (C_island, Cg, C_coupler), with every branch scaled from its anchor value by estimate(k) / estimate(k0)."""
345
+
346
+ def __init__(self, filled: FilledCircuit, pair, junction: str, cache: dict | None = None):
347
+ from quantcore_circuits.pdk import get_pdk # pylint: disable=import-outside-toplevel
348
+
349
+ model, values = filled.model, filled.values
350
+ self.design, self.pdk = filled.design, get_pdk(filled.design.pdk)
351
+ gnd = model.ground
352
+ self.nodes = tuple(n for n in model.branches[junction].nodes if n != gnd)
353
+ self.cnode = model.branches[pair.resonator].nodes[0]
354
+ touch = set(self.nodes) | {self.cnode}
355
+ self.branches = {
356
+ b: tuple(x.nodes) for b, x in model.branches.items() if x.type == "C" and touch & set(x.nodes)
357
+ }
358
+ self.anchor = {b: float(values[b].value or 0.0) for b in self.branches}
359
+ cache = {} if cache is None else cache # shared by the pairs of one circuit: each fragment is built once
360
+ self._est0: dict[str, dict] = cache.setdefault("est0", {})
361
+ self._frag0: dict[str, object] = cache.setdefault("frag0", {})
362
+
363
+ def coupling(self) -> list[str]:
364
+ """C branches between the qubit's island(s) and the coupler node, largest first."""
365
+ out = [b for b, n in self.branches.items() if self.cnode in n and set(n) & set(self.nodes)]
366
+ return sorted(out, key=lambda b: -self.anchor[b])
367
+
368
+ def reduce(self, vals: dict[str, float]) -> tuple[float, float, float]:
369
+ from types import SimpleNamespace as NS # pylint: disable=import-outside-toplevel
370
+
371
+ from quantcore_circuits.circuit.fill import _c_between, _c_total, _floating_maxwell # pylint: disable=C0415
372
+
373
+ model = NS(branches={b: NS(type="C", nodes=n) for b, n in self.branches.items()})
374
+ values = {b: NS(value=v) for b, v in vals.items()}
375
+ if len(self.nodes) == 2:
376
+ m, _ = _floating_maxwell(model, values, self.nodes[0], self.nodes[1], self.cnode)
377
+ else:
378
+ q = self.nodes[0]
379
+ cg = _c_between(model, values, q, self.cnode)
380
+ m = np.array([[_c_total(model, values, q), -cg], [-cg, _c_total(model, values, self.cnode)]])
381
+ return float(m[0].sum()), float(-m[0, 1]), float(m[1].sum())
382
+
383
+ def estimates(self, inst: str, sets: dict[str, float] | None = None) -> dict[str, float]:
384
+ """C estimates of ``inst``'s LOM fragment with its parameters ``sets`` (path under the instance → value)."""
385
+ if not sets and inst in self._est0:
386
+ return self._est0[inst]
387
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
388
+ from quantcore_circuits.lom.estimates import exact_values # pylint: disable=import-outside-toplevel
389
+ from quantcore_circuits.lom.fragment import lom_model # pylint: disable=import-outside-toplevel
390
+ from quantcore_circuits.optimise import set_knob # pylint: disable=import-outside-toplevel
391
+
392
+ spec = self.design.instances[inst].model_dump(mode="json", by_alias=True)
393
+ spec["place"] = {"at": [0.0, 0.0]} # the LOM does not depend on the placement (a snap needs its partner)
394
+ mini = load_design({"schema": "qcc/0.1", "name": "lom", "pdk": self.design.pdk, "instances": {inst: spec}})
395
+ for path, v in (sets or {}).items():
396
+ mini = set_knob(mini, f"{inst}.{path}", v)
397
+ with exact_values(): # unrounded estimates: a ±2 % step must show
398
+ frag = lom_model(mini.instances[inst].cell)(inst, mini.instances[inst], self.pdk)
399
+ out = {e.name: float(e.value["estimate"]) for e in frag.elements
400
+ if e.type == "C" and isinstance(e.value.get("estimate"), (int, float)) and e.value["estimate"] > 0}
401
+ if not sets:
402
+ self._est0[inst] = out
403
+ self._frag0[inst] = frag
404
+ return out
405
+
406
+ def port_net(self, port: str) -> str | None:
407
+ """The FEM net label of the conductor a component port ``INST.port`` lands on (its LOM fragment's port node)."""
408
+ inst, _, name = port.partition(".")
409
+ if inst not in self.design.instances:
410
+ return None
411
+ try:
412
+ self.estimates(inst)
413
+ except Exception: # noqa: BLE001 (a cell without a model)
414
+ return None
415
+ frag = self._frag0.get(inst)
416
+ local = frag.port_nodes.get(name) if frag else None
417
+ if not local or local == "gnd" or local.startswith("control:"):
418
+ return None
419
+ return (frag.nodes.get(local) or {}).get("island")
420
+
421
+ def at(self, knobs: dict[str, float], paths: dict[str, tuple[str, str]]) -> tuple[float, float, float]:
422
+ """(C_island, Cg, C_coupler) with ``knobs`` (knob → value; ``paths``: knob → (instance, path))."""
423
+ by_inst: dict[str, dict[str, float]] = {}
424
+ for k, v in knobs.items():
425
+ if k in paths:
426
+ inst, path = paths[k]
427
+ by_inst.setdefault(inst, {})[path] = v
428
+ vals = dict(self.anchor)
429
+ for inst, sets in by_inst.items():
430
+ est0, est = self.estimates(inst), self.estimates(inst, sets)
431
+ for b in vals:
432
+ if b in est and est0.get(b):
433
+ vals[b] = self.anchor[b] * est[b] / est0[b]
434
+ return self.reduce(vals)
435
+
436
+
437
+ def _owner(branch: str, design) -> str | None:
438
+ for inst in sorted(design.instances, key=len, reverse=True):
439
+ if re.match(rf"^[A-Za-z]+_{re.escape(inst)}(_.*)?$", branch):
440
+ return inst
441
+ return None
442
+
443
+
444
+ def _junction_of(model, pair) -> str | None:
445
+ if f"J_{pair.qubit}" in model.branches:
446
+ return f"J_{pair.qubit}"
447
+ return next((n for n, b in model.branches.items() if b.type in ("JJ", "SQUID") and pair.qubit in b.nodes), None)
448
+
449
+
450
+ def surrogate_from_fill(filled: FilledCircuit, pair_index: int = 0, cache: dict | None = None) -> PairSurrogate:
451
+ """Anchor a surrogate at the point of ``filled`` (FEM or the layout's estimates; knob values read from its design).
452
+
453
+ A real circuit (``filled.model``) gets the generic surrogate of the module docstring; a bare ``FilledCircuit``
454
+ without a model (a test stand-in for the FEM step) the Xmon one: cross / claw with the prior exponents.
455
+ ``cache``: shared between the pairs of one circuit (each component's LOM fragment is built once)."""
456
+ if getattr(filled, "model", None) is None:
457
+ return _xmon_surrogate(filled, pair_index)
458
+ return _generic_surrogate(filled, pair_index, cache)
459
+
460
+
461
+ def _xmon_surrogate(filled: FilledCircuit, pair_index: int) -> PairSurrogate:
462
+ from quantcore_circuits.assembly import plan_design # pylint: disable=import-outside-toplevel
463
+ from quantcore_circuits.optimise import get_knob # pylint: disable=import-outside-toplevel
464
+ from quantcore_circuits.pdk import get_pdk # pylint: disable=import-outside-toplevel
465
+
466
+ p = filled.pairs[pair_index]
467
+ design = filled.design
468
+ q, r = p.qubit, p.resonator
469
+ cross, claw = float(get_knob(design, f"{q}.cross_length")), float(get_knob(design, f"{q}.claw_length"))
470
+ rp = plan_design(design).routes[r]
471
+ pdk = get_pdk(design.pdk)
472
+ models = {}
473
+ for name, knob, k, v in (
474
+ ("C_island", f"{q}.cross_length", cross, p.c_island_fF - p.cj_fF),
475
+ ("Cg", f"{q}.claw_length", claw, p.cg_fF),
476
+ ("C_coupler", f"{q}.claw_length", claw, p.c_coupler_fF),
477
+ ):
478
+ m = ElementModel(name, knob, k, v, PRIORS[name], PRIORS[name])
479
+ m.add(k, v)
480
+ models[name] = m
481
+ return PairSurrogate(
482
+ q,
483
+ r,
484
+ models["C_island"],
485
+ models["Cg"],
486
+ models["C_coupler"],
487
+ p.lj_nH,
488
+ p.cj_fF,
489
+ float(rp.length),
490
+ rp.params.get("a", pdk.cpw_a),
491
+ rp.params.get("b", pdk.cpw_b),
492
+ design.pdk,
493
+ cell="Xmon",
494
+ )
495
+
496
+
497
+ def _generic_surrogate(filled: FilledCircuit, pair_index: int, cache: dict | None = None) -> PairSurrogate:
498
+ from quantcore_circuits.pdk import get_pdk # pylint: disable=import-outside-toplevel
499
+
500
+ p = filled.pairs[pair_index]
501
+ design, model, values = filled.design, filled.model, filled.values
502
+ pdk = get_pdk(design.pdk)
503
+ q, r = p.qubit, p.resonator
504
+ notes: list[str] = []
505
+ jname = _junction_of(model, p)
506
+ qinst = jname[2:] if jname and jname.startswith("J_") and jname[2:] in design.instances else q.split(".", 1)[0]
507
+ if qinst not in design.instances or jname is None:
508
+ raise ValueError(f"{q}: no qubit instance or junction for the pair {q}/{r}")
509
+ cell = design.instances[qinst].cell
510
+ lom = _PairLom(filled, p, jname, cache)
511
+
512
+ # the knobs: island on the qubit; C_g on the owner of the qubit ↔ coupler capacitance
513
+ paths: dict[str, tuple[str, str]] = {}
514
+ island_knob = coupler_knob = None
515
+ rule = _rule(QUBIT_KNOBS, cell)
516
+ if rule is None:
517
+ notes.append(f"{qinst} ({cell}): no knob rule for this class; its LOM's knob annotations are used if numeric")
518
+ island_path = rule[0] if rule else _annotated(model, lom, qinst, island=True)
519
+ if island_path and _num_knob(design, f"{qinst}.{island_path}") is not None:
520
+ island_knob = f"{qinst}.{island_path}"
521
+ paths[island_knob] = (qinst, island_path)
522
+ else:
523
+ notes.append(f"{qinst} ({cell}): no island-capacitance knob ({island_path or 'none'} is not a number in the "
524
+ "design or the cell defaults); C_Σ is kept")
525
+ cpl = lom.coupling()
526
+ if not cpl:
527
+ raise ValueError(f"{q}/{r}: no capacitance between the qubit and its readout coupler")
528
+ owner = _owner(cpl[0], design)
529
+ node = cpl[0][len(f"Cg_{owner}_"):] if owner and cpl[0].startswith(f"Cg_{owner}_") else None
530
+ if owner is None:
531
+ coupler_path = None
532
+ notes.append(f"{qinst}: its C_g is the declared coupling {cpl[0]!r} (a value, not a geometry knob); kept")
533
+ elif owner == qinst:
534
+ coupler_path = rule[1](node) if rule else _annotated(model, lom, qinst, branch=cpl[0])
535
+ else:
536
+ coupler_path = _rule(COUPLER_KNOBS, design.instances[owner].cell)
537
+ if coupler_path is None:
538
+ coupler_path = _annotated(model, lom, owner, branch=cpl[0])
539
+ if coupler_path and owner and _num_knob(design, f"{owner}.{coupler_path}") is not None:
540
+ coupler_knob = f"{owner}.{coupler_path}"
541
+ paths[coupler_knob] = (owner, coupler_path)
542
+ elif owner is not None:
543
+ notes.append(f"{qinst}: no C_g knob on {owner} ({design.instances[owner].cell}"
544
+ + (f", {coupler_path} is not a number" if coupler_path else "") + "); C_g is kept")
545
+
546
+ # local exponents of (C_island, Cg, C_coupler) in each knob, from the LOM
547
+ base = lom.reduce(lom.anchor)
548
+ expo: dict[str, tuple[float, float, float]] = {}
549
+ for k in list(paths):
550
+ k0 = _num_knob(design, k)
551
+ hi_, lo_ = lom.at({k: k0 * (1 + SENSITIVITY_STEP)}, paths), lom.at({k: k0 * (1 - SENSITIVITY_STEP)}, paths)
552
+ den = math.log((1 + SENSITIVITY_STEP) / (1 - SENSITIVITY_STEP))
553
+ e = tuple(round(math.log(a / b) / den, 6) if a > 0 and b > 0 else 0.0 for a, b in zip(hi_, lo_))
554
+ if max(abs(x) for x in e) < MIN_EXPONENT:
555
+ notes.append(f"{k}: no effect on the qubit's capacitances in the LOM; not used as a knob")
556
+ del paths[k]
557
+ island_knob = None if k == island_knob else island_knob
558
+ coupler_knob = None if k == coupler_knob else coupler_knob
559
+ continue
560
+ expo[k] = e
561
+
562
+ def element(name: str, i: int, v0: float, primary: str | None) -> ElementModel:
563
+ prim = primary if primary in expo else None
564
+ p_prim = expo[prim][i] if prim else 1.0
565
+ m = ElementModel(name, prim, _num_knob(design, prim) if prim else 1.0, v0, p_prim, p_prim)
566
+ m.add(m.k0 if prim else None, v0)
567
+ for k, e in expo.items():
568
+ if k != prim and abs(e[i]) >= 1e-6:
569
+ m.others[k] = [_num_knob(design, k), e[i]]
570
+ return m
571
+
572
+ c_isl = element("C_island", 0, p.c_island_fF - p.cj_fF, island_knob)
573
+ c_g = element("Cg", 1, p.cg_fF, coupler_knob)
574
+ c_c = element("C_coupler", 2, p.c_coupler_fF, coupler_knob)
575
+ if abs(base[0] - c_isl.v0) > 1e-6 * max(1.0, abs(c_isl.v0)) or abs(base[1] - c_g.v0) > 1e-6 * max(1.0, c_g.v0):
576
+ notes.append(f"{q}/{r}: the pair's capacitances differ from the reduced LOM ({base}); sensitivities are "
577
+ "approximate")
578
+
579
+ # L_J
580
+ inst = design.instances[qinst]
581
+ lj_raw = inst.junction.Lj_nH if inst.junction else None
582
+ lj_knob, lj_scale = None, 1.0
583
+ if isinstance(lj_raw, list) and lj_raw:
584
+ lj_knob = f"{qinst}.junction.Lj_nH.*"
585
+ lj_scale = float(lj_raw[0]) / float(np.mean(lj_raw))
586
+ elif lj_raw is not None:
587
+ lj_knob = f"{qinst}.junction.Lj_nH"
588
+ else:
589
+ notes.append(f"{qinst}: L_J comes from the drawn junction (no junction.Lj_nH in the design): not tuned; set "
590
+ "junction.Lj_nH to make it a knob")
591
+ lj_scale *= p.ej_sum_ratio # a flux-biased SQUID: the model's L(Φ) over the knob's zero-flux L_J0
592
+
593
+ # the resonator line
594
+ tlv = values[r]
595
+ total = float(tlv.estimate or model.branches[r].value.get("length_um") or 0.0)
596
+ kind = tlv.extra.get("kind", p.kind)
597
+ length_knob, k_len = _length_knob(design, model, lom, r, total)
598
+ if length_knob is None:
599
+ notes.append(f"{r}: no length knob (a line without a numeric length parameter, e.g. a cpw route drawn by its "
600
+ "waypoints); f_r is kept")
601
+ k_len = total
602
+ bv = model.branches[r].value
603
+ return PairSurrogate(
604
+ q, r, c_isl, c_g, c_c, p.lj_nH, p.cj_fF, k_len,
605
+ float(bv.get("a_um", pdk.cpw_a)), float(bv.get("b_um", pdk.cpw_b)), design.pdk,
606
+ kind=kind, extra_length_um=max(total - k_len, 0.0) if length_knob else 0.0,
607
+ lj_knob=lj_knob, length_knob=length_knob, lj_scale=lj_scale, cell=cell, notes=notes,
608
+ )._with_lom(lom, paths)
609
+
610
+
611
+ def _annotated(model, lom: _PairLom, inst: str, island: bool = False, branch: str | None = None) -> str | None:
612
+ """A knob path from the LOM's own element annotation (``knob: {"param": "<inst>.<path>"}``): of ``branch``, or of
613
+ the qubit's island capacitance (the largest C on its island nodes)."""
614
+ if branch is None and island:
615
+ own = [b for b, n in lom.branches.items() if set(n) & set(lom.nodes) and lom.cnode not in n]
616
+ branch = max(own, key=lambda b: lom.anchor[b], default=None)
617
+ knob = (model.branches[branch].knob or {}).get("param") if branch in model.branches else None
618
+ return knob.split(".", 1)[1] if knob and knob.startswith(f"{inst}.") else None
619
+
620
+
621
+ def _length_knob(design, model, lom: _PairLom, r: str, total: float) -> tuple[str | None, float]:
622
+ """(the resonator's length knob, its value): its TLres knob when that is a length (``<R>.length``, a line cell's
623
+ ``resonator_length``), else the one meander route with a length that ends on the resonator's conductor (a
624
+ coupler cell's line continued by a route: the route's length is the knob, the cell's line a constant)."""
625
+ knob = (model.branches[r].knob or {}).get("param")
626
+ cands = [knob] if knob and re.search(r"len", knob.rsplit(".", 1)[-1]) else []
627
+ nets = set(model.nodes[lom.cnode].nets) if lom.cnode in model.nodes else set()
628
+ routes = [n for n, route in design.routes.items() if route.length and route.type == "meander"
629
+ and any(isinstance(e, str) and lom.port_net(e) in nets for e in (route.from_, route.to))]
630
+ if len(routes) == 1 and f"{routes[0]}.length" not in cands:
631
+ cands.append(f"{routes[0]}.length")
632
+ for k in cands:
633
+ v = _num_knob(design, k)
634
+ if v is not None and v <= total + max(1.0, 1e-3 * total): # a meander is planned to within a few nm
635
+ return k, v
636
+ return None, total
637
+
638
+
639
+ def update_surrogate(s: PairSurrogate, filled: FilledCircuit, knobs: dict[str, float], pair_index: int = 0) -> None:
640
+ p = filled.pairs[pair_index]
641
+ s.c_island.add(knobs.get(s.c_island.knob) if s.c_island.knob else None, p.c_island_fF - p.cj_fF, knobs)
642
+ s.cg.add(knobs.get(s.cg.knob) if s.cg.knob else None, p.cg_fF, knobs)
643
+ s.c_coupler.add(knobs.get(s.c_coupler.knob) if s.c_coupler.knob else None, p.c_coupler_fF, knobs)
644
+ if s.lj_knob and s.lj_knob in knobs:
645
+ s.lj_nH = knobs[s.lj_knob] * s.lj_scale
646
+ if s.length_knob and s.length_knob in knobs:
647
+ s.length_um = knobs[s.length_knob]
648
+
649
+
650
+ @dataclass
651
+ class Proposal:
652
+ knobs: dict[str, float]
653
+ predicted: dict[str, float]
654
+ residuals: dict[str, float] # (predicted − target)/tol
655
+ elements: dict[str, float]
656
+ start_knobs: dict[str, float]
657
+ objective: float
658
+ at_bounds: list[str] = field(default_factory=list) # knobs pinned at a bound (the optimum may lie outside)
659
+ notes: list[str] = field(default_factory=list) # what could not be tuned and why (additive)
660
+
661
+
662
+ REFINE_TOL = 1e-3 # relative LOM ↔ surrogate mismatch at the proposal above which the exponents are corrected
663
+
664
+
665
+ def propose(
666
+ s: PairSurrogate,
667
+ targets: dict,
668
+ bounds: dict[str, tuple[float, float]] | None = None,
669
+ anchor: dict[str, float] | None = None,
670
+ refine: int = 3,
671
+ ) -> Proposal:
672
+ """Bounded least squares on the surrogate: knobs that put every target inside its tolerance.
673
+
674
+ ``anchor``: values measured at the current knobs (e.g. the consensus' chosen estimator). The surrogate's
675
+ predictions are scaled by measured / predicted at the start, so it corrects the measured gap even when its own
676
+ model (the dressed spectrum) and the chosen estimator differ (a surrogate bias correction).
677
+
678
+ ``refine``: a surrogate that can re-evaluate its LOM (:func:`surrogate_from_fill`) checks the solution there; when
679
+ an element differs by more than ``REFINE_TOL`` its exponents are corrected along the move (a secant through the
680
+ anchor and the proposal, so the anchor stays exact) and the problem is solved again, at most ``refine`` times. If
681
+ it still differs (two knobs that interact strongly, e.g. a floating qubit's pads and its connection pad), the last
682
+ solve uses the LOM itself (ratio-scaled to the anchor) as the forward model, from the surrogate's solution.
683
+
684
+ Only the knobs this pair's targets ask for move (:func:`_free_knobs`); the others keep their value.
685
+ """
686
+ from scipy.optimize import least_squares # pylint: disable=import-outside-toplevel
687
+
688
+ keys = [
689
+ k
690
+ for k in (f"{s.qubit}.f_q_GHz", f"{s.qubit}.alpha_MHz", f"{s.resonator}.f_GHz", f"{s.resonator}.g_MHz")
691
+ if k in targets
692
+ ]
693
+ tv = {k: (targets[k].value if hasattr(targets[k], "value") else targets[k]["value"]) for k in keys}
694
+ tt = {k: (targets[k].tol if hasattr(targets[k], "tol") else targets[k]["tol"]) for k in keys}
695
+ names = _free_knobs(s, keys)
696
+ x0 = np.array([s.knobs[n] for n in names], dtype=float)
697
+ bounds = bounds or {}
698
+ lo = np.array([bounds.get(n, (v * 0.4, v * 2.0))[0] for n, v in zip(names, x0)])
699
+ hi = np.array([bounds.get(n, (v * 0.4, v * 2.0))[1] for n, v in zip(names, x0)])
700
+ pred0 = s.predict(dict(zip(names, x0)))
701
+ x0 = np.clip(x0, lo, hi)
702
+ scale = x0.copy()
703
+ bias = {k: anchor[k] / pred0[k] for k in keys if anchor and anchor.get(k) is not None and pred0.get(k)}
704
+ notes = list(getattr(s, "notes", []) or [])
705
+
706
+ fixed = {n: v for n, v in s.knobs.items() if n not in names} # knobs no target of this pair asks for
707
+
708
+ def corrected(knobs):
709
+ pred = s.predict({**fixed, **knobs})
710
+ return {k: v * bias.get(k, 1.0) for k, v in pred.items()}
711
+
712
+ def residual(xs):
713
+ pred = corrected(dict(zip(names, xs * scale)))
714
+ return np.array([(pred[k] - tv[k]) / tt[k] for k in keys])
715
+
716
+ if not names or not keys:
717
+ knobs = {**fixed, **dict(zip(names, (float(round(v, 3)) for v in x0)))}
718
+ pred = corrected(knobs)
719
+ res = {k: (pred[k] - tv[k]) / tt[k] for k in keys}
720
+ if not s.knobs:
721
+ notes.append(f"{s.qubit}/{s.resonator}: nothing to tune (no knob)")
722
+ return Proposal(knobs, pred, res, s.elements(knobs), dict(s.knobs),
723
+ float(math.sqrt(sum(r * r for r in res.values()))), [], notes)
724
+ start = x0 / scale
725
+ mismatch = False
726
+ for _ in range(refine + 1):
727
+ sol = least_squares(residual, start, bounds=(lo / scale, hi / scale), x_scale=1.0, diff_step=1e-3)
728
+ knobs = {n: float(round(v, 3)) for n, v in zip(names, sol.x * scale)}
729
+ mismatch = refine > 0 and _refine(s, {**fixed, **knobs})
730
+ if not mismatch:
731
+ break
732
+ start = np.clip(sol.x, lo / scale, hi / scale)
733
+ elements = None
734
+ if mismatch: # the power laws do not settle (knobs that interact strongly): solve on the LOM itself from here
735
+ lom, paths = s._lom, s._paths # pylint: disable=protected-access
736
+
737
+ def lom_elements(knobs):
738
+ el = s.elements({**fixed, **knobs})
739
+ ci, cg, cc = lom.at({k: v for k, v in {**fixed, **knobs}.items() if k in paths}, paths)
740
+ return {**el, "C_island_fF": ci, "Cg_fF": cg, "C_coupler_fF": cc}
741
+
742
+ def corrected(knobs): # noqa: F811 (the LOM forward replaces the surrogate's)
743
+ pred = forward(lom_elements(knobs), s.cj_fF, s.a_um, s.b_um, s.pdk, s.qubit, s.resonator, s.kind)
744
+ return {k: v * bias.get(k, 1.0) for k, v in pred.items()}
745
+
746
+ sol = least_squares(residual, np.clip(sol.x, lo / scale, hi / scale), bounds=(lo / scale, hi / scale),
747
+ x_scale=1.0, diff_step=1e-3)
748
+ knobs = {n: float(round(v, 3)) for n, v in zip(names, sol.x * scale)}
749
+ elements = lom_elements(knobs)
750
+ # in the surrogate's knob order; an untouched knob keeps its exact value (no change is reported for it)
751
+ knobs = {n: knobs[n] if n in knobs else fixed[n] for n in s.knobs}
752
+ pred = corrected(knobs)
753
+ res = {k: (pred[k] - tv[k]) / tt[k] for k in keys}
754
+ pinned = [n for n, x, a, b in zip(names, sol.x * scale, lo, hi) if min(abs(x - a), abs(x - b)) <= 1e-6 * abs(x)]
755
+ return Proposal(
756
+ knobs, pred, res, elements or s.elements(knobs), dict(s.knobs),
757
+ float(math.sqrt(sum(r * r for r in res.values()))), pinned, notes,
758
+ )
759
+
760
+
761
+ TARGET_OF = {"C_island": "alpha_MHz", "Cg": "g_MHz", "C_coupler": "g_MHz"}
762
+
763
+
764
+ def _free_knobs(s: PairSurrogate, keys: list[str]) -> list[str]:
765
+ """The knobs this pair's targets ask for — L_J for f_q, the island knob for α, the coupler knob for g, the length
766
+ for f_r — in the surrogate's order. A knob with no target of its own stays where it is (with fewer targets than
767
+ knobs the least squares would otherwise drift knobs nobody asked to change)."""
768
+ want = {k.rsplit(".", 1)[1] for k in keys}
769
+ roles: dict[str, set[str]] = {}
770
+ for m in (s.c_island, s.cg, s.c_coupler):
771
+ if m.knob is not None and m.element in TARGET_OF:
772
+ roles.setdefault(m.knob, set()).add(TARGET_OF[m.element])
773
+ if s.lj_knob:
774
+ roles.setdefault(s.lj_knob, set()).add("f_q_GHz")
775
+ if s.length_knob:
776
+ roles.setdefault(s.length_knob, set()).add("f_GHz")
777
+ return [n for n in s.knobs if n not in roles or roles[n] & want]
778
+
779
+
780
+ def _refine(s: PairSurrogate, knobs: dict[str, float]) -> bool:
781
+ """Compare the surrogate's capacitances at ``knobs`` with the LOM's; on a mismatch correct the exponents (Broyden
782
+ secant in log space, the anchor fixed) and return True."""
783
+ lom, paths = getattr(s, "_lom", None), getattr(s, "_paths", None)
784
+ if lom is None or not paths:
785
+ return False
786
+ geo = {k: v for k, v in knobs.items() if k in paths}
787
+ true = lom.at(geo, paths)
788
+ changed = False
789
+ for m, t in zip((s.c_island, s.cg, s.c_coupler), true):
790
+ pred = m.value(knobs)
791
+ if t <= 0 or pred <= 0 or abs(t / pred - 1) <= REFINE_TOL:
792
+ continue
793
+ steps = {}
794
+ if m.knob is not None and m.knob in geo:
795
+ steps[m.knob] = math.log(geo[m.knob] / m.k0)
796
+ for k, (k0, _) in m.others.items():
797
+ if k in geo:
798
+ steps[k] = math.log(geo[k] / k0)
799
+ norm = sum(x * x for x in steps.values())
800
+ if norm < 1e-12:
801
+ continue
802
+ delta = math.log(t / pred)
803
+ for k, x in steps.items():
804
+ if k == m.knob:
805
+ m.p += delta * x / norm
806
+ else:
807
+ m.others[k][1] += delta * x / norm
808
+ changed = True
809
+ return changed
810
+
811
+
812
+ def surrogates_from_fill(filled: FilledCircuit, notes: list[str] | None = None) -> list[PairSurrogate]:
813
+ """One surrogate per qubit (its first, readout, pair) — multi-qubit chips. A pair whose surrogate cannot be built
814
+ is left out with a line in ``notes`` (when given; else the error is raised)."""
815
+ out, seen, cache = [], set(), {}
816
+ for i, p in enumerate(filled.pairs):
817
+ if p.qubit not in seen:
818
+ seen.add(p.qubit)
819
+ try:
820
+ out.append(surrogate_from_fill(filled, i, cache))
821
+ except Exception as e: # noqa: BLE001
822
+ if notes is None:
823
+ raise
824
+ notes.append(f"{p.qubit}/{p.resonator}: not tuned ({type(e).__name__}: {e})")
825
+ return out
826
+
827
+
828
+ def unpaired_notes(filled: FilledCircuit) -> list[str]:
829
+ """A line for every qubit (junction) of the circuit that has no readout pair (nothing reads it out, or only a bus
830
+ that several qubits share): Propose cannot tune it."""
831
+ model = getattr(filled, "model", None)
832
+ if model is None:
833
+ return []
834
+ paired = {p.qubit for p in filled.pairs}
835
+ out = []
836
+ for name, b in model.branches.items():
837
+ if b.type not in ("JJ", "SQUID"):
838
+ continue
839
+ q = name[2:] if name.startswith("J_") else name
840
+ if q in paired or any(n in paired for n in b.nodes):
841
+ continue
842
+ out.append(f"{q}: no readout resonator pair (a λ/4 or λ/2 line on a coupler of this qubit alone); not tuned")
843
+ return out
844
+
845
+
846
+ def propose_all(
847
+ surrogates: list[PairSurrogate],
848
+ targets: dict,
849
+ bounds: dict[str, tuple[float, float]] | None = None,
850
+ anchor: dict[str, float] | None = None,
851
+ ) -> Proposal:
852
+ """:func:`propose` for every pair, merged into one proposal.
853
+
854
+ The pairs share no knobs and the surrogate has no qubit–qubit terms, so each pair is solved on its own;
855
+ the merged objective is the norm over all targets. Cross-couplings (buses, ZZ) need a joint model.
856
+ """
857
+ props = [propose(s, targets, bounds, anchor) for s in surrogates]
858
+ if len(props) == 1:
859
+ return props[0]
860
+ merged = Proposal({}, {}, {}, {}, {}, 0.0, [], [])
861
+ for s, p in zip(surrogates, props):
862
+ merged.knobs.update(p.knobs)
863
+ merged.predicted.update(p.predicted)
864
+ merged.residuals.update(p.residuals)
865
+ merged.elements.update({f"{s.qubit}.{k}": v for k, v in p.elements.items()})
866
+ merged.start_knobs.update(p.start_knobs)
867
+ merged.at_bounds += p.at_bounds
868
+ merged.notes += p.notes
869
+ merged.objective = float(math.sqrt(sum(r * r for r in merged.residuals.values())))
870
+ return merged
871
+
872
+
873
+ def apply(design_source, knobs: dict[str, float], follow_ports: bool = True, reach_um: float = 300.0, plan=None):
874
+ """Design with ``knobs`` set (instances' params, junction fields, route fields; the paths of
875
+ :func:`quantcore_circuits.optimise.get_knob`).
876
+
877
+ ``follow_ports``: a geometry knob can move a port (a longer Xmon cross moves its flux port). Waypoints that sit
878
+ on such a port's axis within ``reach_um`` of it (e.g. a taper just before the port) move with the port, so the
879
+ route keeps its shape instead of folding back. Only the instances whose parameters change (and those snapped to
880
+ them) are planned again; ``plan``: the source design's plan when the caller has it (else it is planned here).
881
+ """
882
+ from quantcore_circuits.assembly import plan_design # pylint: disable=import-outside-toplevel
883
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
884
+ from quantcore_circuits.optimise import INSTANCE_FIELDS, set_knob # pylint: disable=import-outside-toplevel
885
+
886
+ design = load_design(design_source)
887
+ changed = set()
888
+ for k in knobs:
889
+ head, _, rest = k.partition(".")
890
+ if head in design.instances and rest.split(".", 1)[0] not in INSTANCE_FIELDS: # a geometry parameter
891
+ changed.add(head)
892
+ follow_ports = follow_ports and bool(changed)
893
+ before = (plan or plan_design(design)).all_ports() if follow_ports else {}
894
+ for k, v in knobs.items():
895
+ design = set_knob(design, k, v)
896
+ if not follow_ports:
897
+ return design
898
+ after = _ports_without_routes(design, changed)
899
+ data = design.to_json_dict()
900
+ moved = False
901
+ for route in data["routes"].values():
902
+ for end in (route.get("from"), route.get("to")):
903
+ if not isinstance(end, str) or end not in before or end not in after:
904
+ continue
905
+ old, new = before[end], after[end]
906
+ delta = (new.pos.x - old.pos.x, new.pos.y - old.pos.y)
907
+ if abs(delta[0]) < 1e-9 and abs(delta[1]) < 1e-9:
908
+ continue
909
+ for i, node in enumerate(route.get("nodes", [])):
910
+ at = node["at"] if isinstance(node, dict) else node
911
+ rel = (at[0] - old.pos.x, at[1] - old.pos.y)
912
+ along = rel[0] * old.dir.x + rel[1] * old.dir.y
913
+ across = abs(rel[0] * old.dir.y - rel[1] * old.dir.x)
914
+ if across < 1e-3 and 0 < along <= reach_um:
915
+ new_at = [round(at[0] + delta[0], 4), round(at[1] + delta[1], 4)]
916
+ if isinstance(node, dict):
917
+ node["at"] = new_at
918
+ else:
919
+ route["nodes"][i] = new_at
920
+ moved = True
921
+ return design.model_validate(data) if moved else design
922
+
923
+
924
+ def _ports_without_routes(design, only: set[str] | None = None):
925
+ """Instance ports of ``design`` without planning its routes (they may not be routable yet). ``only``: plan just
926
+ these instances, with what they are snapped to and what is snapped to them (the other ports do not move)."""
927
+ from quantcore_circuits.assembly import plan_design # pylint: disable=import-outside-toplevel
928
+
929
+ data = design.to_json_dict()
930
+ data["routes"] = {}
931
+ data["sim_groups"] = {}
932
+ if only is not None:
933
+ keep = _snap_closure(design, only)
934
+ data["instances"] = {k: v for k, v in data["instances"].items() if k in keep}
935
+ data["couplings"] = {}
936
+ data["targets"] = {}
937
+ data["nets"] = "derived"
938
+ return plan_design(design.model_validate(data)).all_ports()
939
+
940
+
941
+ def _snap_closure(design, names: set[str]) -> set[str]:
942
+ """``names`` plus every instance snapped to one of them and every instance one of them is snapped to."""
943
+ keep = set(names)
944
+ links = []
945
+ for n, inst in design.instances.items():
946
+ to = getattr(inst.place, "to", None)
947
+ if getattr(inst.place, "snap", None) and isinstance(to, str) and to.split(".", 1)[0] in design.instances:
948
+ links.append((n, to.split(".", 1)[0]))
949
+ grew = True
950
+ while grew:
951
+ grew = False
952
+ for a, b in links:
953
+ if (a in keep) != (b in keep):
954
+ keep |= {a, b}
955
+ grew = True
956
+ return keep
957
+
958
+
959
+ def write_revision(design, run_dir: str | Path, iteration: int) -> Path:
960
+ path = Path(run_dir) / "revisions" / f"rev{iteration}.json"
961
+ path.parent.mkdir(parents=True, exist_ok=True)
962
+ path.write_text(json.dumps(design.to_json_dict(), indent=2) + "\n", encoding="utf-8")
963
+ return path
964
+
965
+
966
+ def accept(revision: str | Path, design_path: str | Path) -> Path:
967
+ """Copy an accepted revision over the source design file (keeps a ``.bak``)."""
968
+ design_path = Path(design_path)
969
+ backup = design_path.with_suffix(design_path.suffix + ".bak")
970
+ backup.write_text(design_path.read_text(encoding="utf-8"), encoding="utf-8")
971
+ design_path.write_text(Path(revision).read_text(encoding="utf-8"), encoding="utf-8")
972
+ return design_path
973
+
974
+
975
+ @dataclass
976
+ class LoopStep:
977
+ iteration: int
978
+ knobs: dict[str, float]
979
+ measured: dict[str, float]
980
+ residuals: dict[str, float]
981
+ objective: float
982
+ proposal: Proposal | None
983
+ revision: str | None
984
+
985
+
986
+ def run(
987
+ design_source,
988
+ evaluate,
989
+ targets: dict,
990
+ max_iter: int = 5,
991
+ run_dir: str | Path = "build/codesign",
992
+ bounds=None,
993
+ estimator="scqubits",
994
+ on_step=None,
995
+ ) -> list[LoopStep]:
996
+ """Co-design loop (module docstring). ``evaluate(design) -> FilledCircuit``; ``on_step(LoopStep)`` is called
997
+ after every iteration (e.g. to update the dashboard)."""
998
+ from quantcore_circuits.circuit.adapters import ADAPTERS # pylint: disable=import-outside-toplevel
999
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
1000
+
1001
+ design = load_design(design_source)
1002
+ surrogate = None
1003
+ steps: list[LoopStep] = []
1004
+ for it in range(max_iter + 1):
1005
+ filled = evaluate(design)
1006
+ measured = ADAPTERS[estimator](filled)
1007
+ if surrogate is None:
1008
+ surrogate = surrogate_from_fill(filled)
1009
+ else:
1010
+ update_surrogate(surrogate, filled, steps[-1].proposal.knobs)
1011
+ keys = [k for k in targets if k in measured]
1012
+ res = {k: (measured[k] - _tv(targets[k])) / _tt(targets[k]) for k in keys}
1013
+ obj = float(math.sqrt(sum(r * r for r in res.values())))
1014
+ done = all(abs(r) <= 1 for r in res.values())
1015
+ prop = None if done or it == max_iter else propose(surrogate, targets, bounds)
1016
+ rev = None
1017
+ if prop is not None:
1018
+ design = apply(design, prop.knobs)
1019
+ rev = str(write_revision(design, run_dir, it + 1))
1020
+ step = LoopStep(it, dict(surrogate.knobs), measured, res, obj, prop, rev)
1021
+ steps.append(step)
1022
+ if on_step:
1023
+ on_step(step)
1024
+ if done:
1025
+ break
1026
+ return steps
1027
+
1028
+
1029
+ def _tv(t):
1030
+ return t.value if hasattr(t, "value") else t["value"]
1031
+
1032
+
1033
+ def _tt(t):
1034
+ return t.tol if hasattr(t, "tol") else t["tol"]
1035
+
1036
+
1037
+ def copy_targets(targets: dict) -> dict:
1038
+ return {k: {"value": _tv(v), "tol": _tt(v)} for k, v in copy.deepcopy(targets).items()}