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,1690 @@
1
+ """Design sim-group → KQC ``Simulation``.
2
+
3
+ For a ``sim_groups`` entry the builder:
4
+
5
+ 1. derives a simulation design: junctions of the selected qubits become KQC ``"Sim"`` junctions; for capacitance
6
+ analyses, selected routes attached to selected instances are *cut* (removed) and replaced by a short
7
+ waveguide-to-port stub at that port, so the coupler becomes its own net (the resonator itself is modelled as a
8
+ transmission line in LOM); no ground grid, no chip frame;
9
+ 2. builds it and cuts out the box spanned by the selected instances/routes plus ``margin_um``;
10
+ 3. adds ports: junction ``InternalPort`` (eigenmode / driven: L at the design flux and C_J as the LOM takes them,
11
+ :func:`lumped_junction`; capacitance: a placeholder L, the gap stays open), waveguide-to-port stubs, and one
12
+ port per route crossing the box edge — an ``EdgePort`` for capacitance analyses; for eigenmode, where KQC forbids
13
+ edge ports, a 50 Ω lumped ``InternalPort`` next to the edge (KQC's ``use_internal_ports="at_edge"`` geometry), so
14
+ the crossing line is terminated and the eigenmode Q gives κ / Purcell. Where a straight line crosses the box edge
15
+ at an angle, that port sits on the line's own axis just inside the box, its cut square to the line
16
+ (:func:`line_port`; driven: the same lumped port instead of a wave port);
17
+ 4. passes the PDK stack (substrate, permittivity, box heights).
18
+
19
+ The group name ``"chip"`` (unless the design defines its own) means the whole chip: every instance and route is kept
20
+ uncut, the box is the chip box, and each cell exposing ``lumped_signal``/``lumped_ground`` refpoints (bond pads) gets a
21
+ 50 Ω lumped port. In other groups, the selected pads get that port, and so do the pads that terminate the
22
+ selection (snapped to a selected instance, or at an end of a selected route): a selected feedline is never floating.
23
+
24
+ The returned :class:`SimSetup` records the port number → design name mapping used later to label C-matrices.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import math
30
+ import warnings
31
+ from dataclasses import dataclass, field
32
+
33
+ from kqcircuits.defaults import default_faces
34
+ from kqcircuits.pya_resolver import pya
35
+ from kqcircuits.simulations.port import EdgePort, InternalPort
36
+ from kqcircuits.simulations.simulation import Simulation
37
+
38
+ from quantcore_circuits.assembly import build
39
+ from quantcore_circuits.design import Design, load_design, split_port_ref
40
+ from quantcore_circuits.design.schema import SimGroup
41
+ from quantcore_circuits.layouts.registry import resolve_cell
42
+ from quantcore_circuits.lom.fragment import (
43
+ effective_junction,
44
+ instance_junction,
45
+ junction_values,
46
+ missing_junction_message,
47
+ )
48
+ from quantcore_circuits.pdk import get_pdk
49
+
50
+ CAPACITANCE_ANALYSES = {"q3d_cmatrix", "elmer_cap", "palace_cap"}
51
+ EIGENMODE_ANALYSES = {"hfss_eigenmode", "eigenmode_epr", "palace_eig"}
52
+ DRIVEN_ANALYSES = {"hfss_driven"} # S-parameters (e.g. a hanger's S21 → κ, to calibrate the LOM coupling k)
53
+ ALL_ANALYSES = CAPACITANCE_ANALYSES | EIGENMODE_ANALYSES | DRIVEN_ANALYSES
54
+ CHIP_GROUP = "chip"
55
+
56
+
57
+ def analysis_kind(analysis: str) -> str:
58
+ """ "capacitance", "eigenmode", "driven" or a plugin's kind (see :mod:`quantcore_circuits.plugins`)."""
59
+ if analysis in CAPACITANCE_ANALYSES:
60
+ return "capacitance"
61
+ if analysis in EIGENMODE_ANALYSES:
62
+ return "eigenmode"
63
+ if analysis in DRIVEN_ANALYSES:
64
+ return "driven"
65
+ from quantcore_circuits.plugins import analysis_plugins # pylint: disable=import-outside-toplevel
66
+
67
+ plugins = analysis_plugins()
68
+ if analysis in plugins:
69
+ return plugins[analysis].kind
70
+ raise ValueError(f"unknown analysis {analysis!r}; choose from {sorted(ALL_ANALYSES | set(plugins))}")
71
+
72
+
73
+ @dataclass
74
+ class SimPortInfo:
75
+ number: int
76
+ kind: str # "junction" | "waveguide" | "edge" | "edge_lumped" (eigenmode 50 Ω; driven: an angled line) | "lumped"
77
+ name: str # design-level label, e.g. "Q1.junction", "Q1.claw_n", "FL"
78
+ excitation: str | None = None # net label used for C-matrix rows (island, coupler, feedline)
79
+
80
+
81
+ @dataclass
82
+ class SimSetup:
83
+ design: Design
84
+ group: str
85
+ analysis: str
86
+ simulation: Simulation
87
+ ports: list[SimPortInfo] = field(default_factory=list)
88
+ box: pya.DBox | None = None
89
+ waveguide_length: float = 100.0 # µm of CPW stub added at cut coupler ports
90
+ nets: dict[int, str] = field(default_factory=dict) # KQC excitation number → net label (C-matrix rows)
91
+ geometry: dict = field(default_factory=dict) # what the export dropped: ground grid, airbridges (→ job.json)
92
+ notes: list[str] = field(default_factory=list)
93
+ routes: list[str] = field(default_factory=list) # routes present (not cut) in the simulated geometry (→ job.json)
94
+
95
+ def port_labels(self) -> dict[int, str]:
96
+ return {p.number: p.excitation or p.name for p in self.ports}
97
+
98
+
99
+ def is_junction_cell(cell_ref: str) -> bool:
100
+ """A junction cell — KQC ``Junction`` subclasses (Manhattan, NoSquid, Sim, SuperInductor, …), the Quantcore
101
+ trilayer cells, Metal junctions (``metal:SNAIL``, …: category ``junction``). They belong in a qubit's gap (or a
102
+ code-built layout's): placed on their own they are not a qubit, so the export gives them no qubit treatment (see
103
+ :func:`build_simulation`: a junction port only where the cell bridges two different conductors)."""
104
+ if cell_ref.startswith("static:"):
105
+ return False
106
+ try:
107
+ cls = resolve_cell(cell_ref)
108
+ except Exception: # noqa: BLE001 (an unknown cell is reported by the build, not here)
109
+ return False
110
+ from kqcircuits.junctions.junction import Junction # pylint: disable=import-outside-toplevel
111
+
112
+ return getattr(cls, "qcc_category", "") == "junction" or (isinstance(cls, type) and issubclass(cls, Junction))
113
+
114
+
115
+ def _is_qubit(cell_ref: str) -> bool:
116
+ if cell_ref.startswith("static:") or is_junction_cell(cell_ref):
117
+ return False
118
+ cls = resolve_cell(cell_ref)
119
+ # KQC/Quantcore qubits have a junction_type; wrapped cells (metal:<Class>) declare their category instead
120
+ return "junction_type" in cls.get_schema() or getattr(cls, "qcc_category", "") in ("qubit", "coupler")
121
+
122
+
123
+ def _has_param(cell_ref: str, param: str) -> bool:
124
+ if cell_ref.startswith("static:"):
125
+ return False
126
+ try:
127
+ return param in resolve_cell(cell_ref).get_schema()
128
+ except Exception: # noqa: BLE001 (an unknown cell is reported by the build, not here)
129
+ return False
130
+
131
+
132
+ def strip_layers(result, airbridges: bool = False, bumps: bool = True) -> dict:
133
+ """Remove geometry a simulation must not contain from a built layout, in place.
134
+
135
+ * the ground grid (cheese) — always: FEM exports are never cheesed;
136
+ * airbridges (``*airbridge_pads`` / ``*airbridge_flyover``, which KQC's ``Simulation`` would insert as PEC pads
137
+ and bridges) — unless ``airbridges=True``;
138
+ * indium bumps (``*indium_bump``) when ``bumps=False`` (a one-face simulation): with no opposite face KQC extends a
139
+ bump as PEC from the face to the top of the simulation box, a pillar that shorts its island to the outer
140
+ boundary (HFSS) or adds its capacitance (Q3D).
141
+
142
+ Returns ``{"ground_grid_shapes", "airbridge_shapes", "airbridges"}`` (shape counts removed), plus
143
+ ``"indium_bump_shapes"`` when bumps were removed.
144
+ """
145
+ layout = result.layout
146
+ out = {"ground_grid_shapes": 0, "airbridge_shapes": 0, "airbridges": "kept" if airbridges else "dropped"}
147
+ for li in layout.layer_indexes():
148
+ name = layout.get_info(li).name or ""
149
+ key = "ground_grid_shapes" if name.endswith("ground_grid") else None
150
+ if key is None and not airbridges and "airbridge" in name:
151
+ key = "airbridge_shapes"
152
+ if key is None and not bumps and name.endswith("indium_bump"):
153
+ key = "indium_bump_shapes"
154
+ if key is None:
155
+ continue
156
+ n = sum(cell.shapes(li).size() for cell in layout.each_cell())
157
+ if n:
158
+ layout.clear_layer(li)
159
+ out[key] = out.get(key, 0) + n
160
+ return out
161
+
162
+
163
+ CONTACT_PATCH_UM = 0.5 # metal square joining two pieces that touch at one point (see vertex_contact_patches)
164
+
165
+
166
+ def _faces(faces) -> list[str]:
167
+ out = []
168
+ for f in faces or []:
169
+ out += _faces(f) if isinstance(f, (list, tuple)) else [str(f)]
170
+ return out
171
+
172
+
173
+ def vertex_contact_patches(result, box: pya.DBox, faces, size: float = CONTACT_PATCH_UM) -> dict[str, list[pya.DBox]]:
174
+ """``{face: [patch boxes]}`` joining metal pieces that touch at a single point inside ``box``.
175
+
176
+ KQC decides nets with ``Region.interacting``, which counts a point contact (a polygon vertex on another piece's
177
+ boundary) as connected; Q3D's ``AutoIdentifyNets`` does not, splits the KQC net and stops with "Object … in Net
178
+ 'Net1' and object … in Net '…' are touching". Typical source: junction metal (a Sim pad, a fab junction window)
179
+ drawn exactly up to a curved island edge, e.g. a neighbour Flipmon's trilayer window on its disc. A ``size`` µm
180
+ square of ``base_metal_addition`` centred on the contact makes the join an overlap, so AEDT agrees with KQC's nets
181
+ (it only adds metal where KQC already counted the pieces as one conductor). A patch that would also touch a third
182
+ piece is left out."""
183
+ layout = result.layout
184
+ dbu = layout.dbu
185
+ ibox = pya.Region(box.to_itype(dbu))
186
+ out: dict[str, list[pya.DBox]] = {}
187
+ for face in _faces(faces):
188
+ layers = default_faces.get(face) or {}
189
+ if "base_metal_gap_wo_grid" not in layers:
190
+ continue
191
+
192
+ def region(name, layers=layers):
193
+ idx = layout.find_layer(layers[name]) if name in layers else None
194
+ return pya.Region(result.top.begin_shapes_rec(idx)) if idx is not None else pya.Region()
195
+
196
+ metal = ibox - (region("base_metal_gap_wo_grid") - region("base_metal_addition"))
197
+ pieces = metal.merged(True, 0) # min coherence: pieces touching at a point stay separate
198
+ if pieces.count() < 2:
199
+ continue
200
+ regions = [pya.Region(p) for p in pieces.each()]
201
+ boxes = [r.bbox() for r in regions]
202
+ half = size / 2 / dbu
203
+ for i, a in enumerate(regions):
204
+ for j in range(i + 1, len(regions)):
205
+ if not boxes[i].touches(boxes[j]) or a.interacting(regions[j]).is_empty():
206
+ continue
207
+ touch = a.sized(1) & regions[j].sized(1)
208
+ for spot in touch.each():
209
+ c = spot.bbox().center()
210
+ patch = pya.Region(pya.Box(c.x - half, c.y - half, c.x + half, c.y + half))
211
+ third = any(
212
+ k not in (i, j) and not r.interacting(patch).is_empty() for k, r in enumerate(regions)
213
+ )
214
+ if not third:
215
+ out.setdefault(face, []).append(patch.bbox().to_dtype(dbu))
216
+ return out
217
+
218
+
219
+ # ---- the simulated metal of one face, as KQC derives it (junction ports, island nets, line cuts) --------------------
220
+ KQC_EDGE_TOL_UM = 0.007 # a point this close (per axis) to a metal edge is found by KQC (find_edge…: 0.01 µm, Euclid)
221
+ JJ_AXIS_REACH_UM = 120.0 # how far past each junction pin the junction axis is searched for the island edges
222
+ GDS_MAX_POINTS = 4000 # sim polygons stay below the 4095-point GDS XY record (0x8000 bytes) with this
223
+ FACE_METAL_MARGIN_UM = 400.0 # FaceMetal reads the layout this far around the box (straighten_box moves edges)
224
+ SIM_SMOOTH_UM = 0.05 # largest deviation from the drawn bends when a sim polygon must lose points (C8)
225
+
226
+
227
+ class FaceMetal:
228
+ """The metal of ``face`` inside ``box`` as KQC's ``Simulation`` builds it: box − (gap − addition), plus ``etch``
229
+ boxes (on the gap layer) and ``metal`` boxes (addition), optionally with the etch ``smooth``-ed (µm, the sim-only
230
+ bend simplification). ``pieces`` are its conductors; ``boxed[k]``: piece k touches the box edge (ground)."""
231
+
232
+ def __init__(self, result, box: pya.DBox, face: str, etch=(), metal=(), smooth: float = 0.0):
233
+ layout = result.layout
234
+ self.dbu = dbu = layout.dbu
235
+ layers = default_faces.get(face) or {}
236
+
237
+ def region(name):
238
+ idx = layout.find_layer(layers[name]) if name in layers else None
239
+ if idx is None:
240
+ return pya.Region()
241
+ return pya.Region(result.top.begin_shapes_rec_overlapping(idx, window.to_itype(dbu))) & window_region
242
+
243
+ window = box.enlarged(FACE_METAL_MARGIN_UM, FACE_METAL_MARGIN_UM) # room for the C6 box search
244
+ window_region = pya.Region(window.to_itype(dbu))
245
+ gap, add = region("base_metal_gap_wo_grid"), region("base_metal_addition")
246
+ for b in etch:
247
+ gap.insert(b.to_itype(dbu))
248
+ for b in metal:
249
+ add.insert(b.to_itype(dbu))
250
+ lith = gap - add
251
+ if smooth > 0:
252
+ lith = lith.smoothed(max(1, round(smooth / dbu)), True)
253
+ self._init(box, lith, dbu)
254
+
255
+ @classmethod
256
+ def from_etch(cls, etch: pya.Region, box: pya.DBox, dbu: float = 0.001) -> FaceMetal:
257
+ """A FaceMetal of a plain etch region (dbu units): synthetic geometry for tests."""
258
+ fm = cls.__new__(cls)
259
+ fm.dbu = dbu
260
+ fm._init(box, etch, dbu)
261
+ return fm
262
+
263
+ def _init(self, box: pya.DBox, lith: pya.Region, dbu: float) -> None:
264
+ self.lith = lith # the etch (gap − addition) around the box, uncut by it
265
+ self.box = box
266
+ self.box_region = pya.Region(box.to_itype(dbu))
267
+ self.metal = (self.box_region - lith).merged()
268
+ self.pieces = [pya.Region(p) for p in self.metal.each()]
269
+ self._bboxes = [p.bbox() for p in self.pieces]
270
+ border = self.box_region.edges()
271
+ self.boxed = [not p.interacting(border).is_empty() for p in self.pieces]
272
+ self.edges = self.metal.edges()
273
+
274
+ def _probe(self, p: pya.DPoint, half: float) -> pya.Region:
275
+ ip = p.to_itype(self.dbu)
276
+ h = max(1, round(half / self.dbu))
277
+ return pya.Region(pya.Box(ip.x - h, ip.y - h, ip.x + h, ip.y + h))
278
+
279
+ def piece_at(self, p: pya.DPoint) -> int | None:
280
+ """The conductor at ``p`` (None in etch); a point on an edge belongs to the piece it touches."""
281
+ probe = self._probe(p, self.dbu)
282
+ bb = probe.bbox()
283
+ hits = [k for k, r in enumerate(self.pieces)
284
+ if self._bboxes[k].touches(bb) and not r.interacting(probe).is_empty()]
285
+ if len(hits) <= 1:
286
+ return hits[0] if hits else None
287
+ return max(hits, key=lambda k: (self.pieces[k] & probe).area())
288
+
289
+ def on_edge(self, p: pya.DPoint, tol: float = KQC_EDGE_TOL_UM) -> bool:
290
+ """``p`` lies on a metal edge (where KQC's ``find_edge_from_point_in_polygons`` finds one)."""
291
+ return not self.edges.interacting(self._probe(p, tol)).is_empty()
292
+
293
+ def max_points(self) -> int:
294
+ """Most points of one metal or gap polygon as a GDS writer stores it (holes keyholed into the hull)."""
295
+ gap = (self.box_region - self.metal).merged()
296
+ return max([p.num_points() + 2 * p.holes() for r in (self.metal, gap) for p in r.each()] or [0])
297
+
298
+
299
+ def junction_gap(fm: FaceMetal, a: pya.DPoint, b: pya.DPoint, reach: float = JJ_AXIS_REACH_UM):
300
+ """``(signal point, ground point)`` on the facing edges of the two conductors a junction drawn from ``a`` (island
301
+ side) to ``b`` bridges, found along its axis — wherever its pins sit: on the edges, inside the metal (a junction
302
+ overlapping into the islands) or short of them (a pin in a cut-out, StarQubit's line ending between its two leads).
303
+ Among the gaps between two *different* conductors on the axis (not two box-edge grounds) the one overlapping the
304
+ pins' span, nearest its middle, wins. None if there is none (both ends on one conductor, a zero-length junction)."""
305
+ d = a.distance(b)
306
+ if d < 2 * fm.dbu:
307
+ return None
308
+ u = (a - b) * (1.0 / d)
309
+ p0, p1 = b - u * reach, a + u * reach
310
+ inside = pya.Edges(pya.Edge(p0.to_itype(fm.dbu), p1.to_itype(fm.dbu))) & fm.metal
311
+
312
+ def t(p): # µm along the axis from b towards a
313
+ return (p.to_dtype(fm.dbu) - b).sprod(u)
314
+
315
+ spans = sorted(tuple(sorted((t(e.p1), t(e.p2)))) for e in inside.each())
316
+ merged: list[list[float]] = []
317
+ for s0, s1 in spans:
318
+ if merged and s0 <= merged[-1][1] + 2 * fm.dbu:
319
+ merged[-1][1] = max(merged[-1][1], s1)
320
+ else:
321
+ merged.append([s0, s1])
322
+ tags = [fm.piece_at(b + u * ((s0 + s1) / 2)) for s0, s1 in merged]
323
+ best = None
324
+ for k in range(len(merged) - 1):
325
+ ci, cj = tags[k], tags[k + 1]
326
+ if ci is None or cj is None or ci == cj or (fm.boxed[ci] and fm.boxed[cj]):
327
+ continue
328
+ g0, g1 = merged[k][1], merged[k + 1][0]
329
+ key = (max(0.0, g0 - d, -g1), abs((g0 + g1) / 2 - d / 2))
330
+ if best is None or key < best[0]:
331
+ best = (key, g0, g1)
332
+ if best is None:
333
+ return None
334
+ return b + u * best[2], b + u * best[1]
335
+
336
+
337
+ JJ_SHEET_CLEARANCE_UM = 1.0 # metal-free margin along the long sides of a builder-drawn junction sheet
338
+
339
+
340
+ def junction_sheet(fm: FaceMetal, sig: pya.DPoint, gnd: pya.DPoint, width: float = 10.0, min_width: float = 0.5,
341
+ clearance: float = JJ_SHEET_CLEARANCE_UM):
342
+ """``(polygon points, width)``: the junction's lumped sheet between ``gnd`` and ``sig`` (points on the two metal
343
+ edges): a strip on the axis, ``width`` wide or narrower until no metal lies within ``clearance`` of it away from its
344
+ ends (metal along its long sides would short the lumped element), cut to the gap (its ends follow the metal edges,
345
+ so nothing of the sheet lies on metal and both ends touch a conductor). None if not even ``min_width`` fits."""
346
+ v = sig - gnd
347
+ length = v.length()
348
+ if length < 2 * fm.dbu:
349
+ return None
350
+ u = v * (1.0 / length)
351
+ n = pya.DVector(-u.y, u.x)
352
+ mid = (gnd + v * 0.5).to_itype(fm.dbu)
353
+ w = min(width, max(length, min_width))
354
+ while w >= min_width - 1e-9:
355
+ end = min(w, length / 3) # metal may reach into the strip near oblique end edges
356
+ hw = w / 2 + min(clearance, w / 2)
357
+ core = pya.DPolygon([gnd + u * end + n * hw, sig - u * end + n * hw, sig - u * end - n * hw,
358
+ gnd + u * end - n * hw])
359
+ ext = w + 1.0
360
+ strip = pya.DPolygon([gnd - u * ext + n * (w / 2), sig + u * ext + n * (w / 2), sig + u * ext - n * (w / 2),
361
+ gnd - u * ext - n * (w / 2)])
362
+ if (pya.Region(core.to_itype(fm.dbu)) & fm.metal).area() * fm.dbu**2 < 1e-4:
363
+ parts = [p for p in (pya.Region(strip.to_itype(fm.dbu)) - fm.metal).each() if p.inside(mid)]
364
+ if parts:
365
+ poly = parts[0].to_dtype(fm.dbu)
366
+ ts = [(pt - gnd).sprod(u) for pt in poly.each_point_hull()]
367
+ if min(ts) > -ext + 0.5 and max(ts) < length + ext - 0.5: # bounded by metal at both ends
368
+ return [pya.DPoint(pt.x, pt.y) for pt in poly.each_point_hull()], w
369
+ w /= 2
370
+ return None
371
+
372
+
373
+ def _has_junction_type(cell_ref: str) -> bool:
374
+ """KQC/Quantcore qubits take ``junction_type`` (→ ``"Sim"`` for simulation); wrapped cells do not."""
375
+ return not cell_ref.startswith("static:") and "junction_type" in resolve_cell(cell_ref).get_schema()
376
+
377
+
378
+ def junction_nets(name: str, inst, pdk) -> tuple[str, str | None]:
379
+ """FEM net labels on the two sides of a qubit's junction: (``squid_a`` side, ``squid_b`` side or None = ground).
380
+
381
+ Taken from the component's LOM model (island labels such as ``Q1.island``, or ``Q1.island1``/``Q1.island2`` for a
382
+ floating transmon, whose junction connects two islands); ``<name>.island`` when there is no model.
383
+ """
384
+ from quantcore_circuits.lom.fragment import lom_model # pylint: disable=import-outside-toplevel
385
+
386
+ default = (f"{name}.island", None)
387
+ fn = lom_model(inst.cell)
388
+ if fn is None:
389
+ return default
390
+ try:
391
+ frag = fn(name, inst, pdk)
392
+ except Exception: # noqa: BLE001 (a model that cannot evaluate must not block the export)
393
+ return default
394
+ jj = next((e for e in frag.elements if e.type in ("JJ", "SQUID")), None)
395
+ if jj is None:
396
+ return default
397
+
398
+ def label(node):
399
+ return (frag.nodes.get(node) or {}).get("island") or f"{name}.{node}"
400
+
401
+ if "gnd" in jj.nodes:
402
+ return label(next(n for n in jj.nodes if n != "gnd")), None
403
+ a = frag.port_nodes.get("squid_a", jj.nodes[0])
404
+ b = frag.port_nodes.get("squid_b", jj.nodes[1])
405
+ return label(a), (label(b) if b != "gnd" else None)
406
+
407
+
408
+ def lumped_junction(name: str, inst, pdk, notes: list | None = None) -> tuple[float, float]:
409
+ """(L nH, C_J fF) of a qubit's junction as a lumped RLC sheet (eigenmode, driven): the values its LOM takes
410
+ (:func:`~quantcore_circuits.lom.fragment.instance_junction`: the design's junction, else the drawn trilayer junction
411
+ on the PDK rule), L at the design flux. ``notes`` gets the source; raises when there is no L, saying where to set
412
+ it."""
413
+ # a cell whose model draws no junction element (SquidTermination: its SQUID is line length) still has a junction
414
+ # port here: the design / drawn values
415
+ ej = instance_junction(name, inst, pdk) or effective_junction(inst)
416
+ try:
417
+ lj = ej.lj_eff_nH if ej is not None else None
418
+ except ValueError: # Φ = ½ with d = 0
419
+ lj = None
420
+ if lj is None:
421
+ raise ValueError(missing_junction_message(name, inst, ej))
422
+ if notes is not None:
423
+ notes.append(f"{name}: {ej.describe()}")
424
+ return lj, ej.cj_fF
425
+
426
+
427
+ def net_names(
428
+ sim: Simulation,
429
+ probes: list[tuple[str, pya.DPoint]],
430
+ near: list[tuple[str, pya.DPoint]] | None = None,
431
+ reach: float = 100.0,
432
+ ) -> dict[int, str]:
433
+ """Label KQC's signal excitations by probing points: the first probe inside an excitation's metal names it.
434
+
435
+ KQC numbers signals by conductor (``Simulation.split_metal_layers_by_excitation``): ports sharing a conductor
436
+ share one excitation, and floating conductors follow in arbitrary order, so port k is not always net k.
437
+ ``near`` probes that land in ground name the nearest unnamed conductor within ``reach`` µm (bounding-box
438
+ distance), e.g. a floating claw whose port tail is joined to a grounded resonator.
439
+ """
440
+ from kqcircuits.simulations.simulation import get_simulation_layer_by_name # pylint: disable=C0415
441
+
442
+ regions: dict[int, pya.Region] = {}
443
+ for name, layer in sim.layers.items():
444
+ exc = layer.get("excitation")
445
+ if exc: # produce_layers moved the regions into the simulation cell
446
+ shapes = sim.cell.shapes(sim.layout.layer(get_simulation_layer_by_name(name)))
447
+ regions.setdefault(exc, pya.Region()).insert(pya.Region(shapes))
448
+ names: dict[int, str] = {}
449
+ for label, point in probes:
450
+ ip = point.to_itype(sim.layout.dbu)
451
+ for exc, region in sorted(regions.items()):
452
+ if exc not in names and not region.interacting(pya.Edge(ip, ip)).is_empty():
453
+ names[exc] = label
454
+ break
455
+ # proximity fallback: a component-port probe that lands in ground (e.g. a claw tail joined to a shorted resonator)
456
+ # names the nearest still-unnamed conductor within ``reach`` µm (the floating claw body next to it)
457
+ for label, point in near or []:
458
+ ip = point.to_itype(sim.layout.dbu)
459
+ if any(not r.interacting(pya.Edge(ip, ip)).is_empty() for r in regions.values()):
460
+ continue # inside a conductor: handled (or deliberately skipped) above
461
+ best = None
462
+ for exc, region in regions.items():
463
+ if exc in names or label in names.values():
464
+ continue
465
+ bb = region.bbox().to_dtype(sim.layout.dbu)
466
+ dx = max(bb.left - point.x, 0.0, point.x - bb.right)
467
+ dy = max(bb.bottom - point.y, 0.0, point.y - bb.top)
468
+ dist = (dx * dx + dy * dy) ** 0.5
469
+ if dist <= reach and (best is None or dist < best[0]):
470
+ best = (dist, exc)
471
+ if best is not None:
472
+ names[best[1]] = label
473
+ # one label per conductor: two probes with the same label on different conductors means the geometry split what
474
+ # the design treats as one (e.g. a line etched through an island). Keep both, visibly, instead of merging them.
475
+ seen: dict[str, int] = {}
476
+ for exc in sorted(names):
477
+ label = names[exc]
478
+ seen[label] = seen.get(label, 0) + 1
479
+ if seen[label] > 1:
480
+ names[exc] = f"{label}#{seen[label]}"
481
+ return names
482
+
483
+
484
+ def _port_probes(sim: Simulation, labels: dict[int, str], far_sides: dict[int, str]) -> list[tuple[str, pya.DPoint]]:
485
+ """Probe points as KQC uses them: signal side of each port (and the far island of floating junction ports)."""
486
+ out = []
487
+ for port in sorted(sim.ports, key=lambda p: p.number):
488
+ if port.number not in labels:
489
+ continue
490
+ if hasattr(port, "ground_location"):
491
+ v = port.signal_location - port.ground_location
492
+ v = sim.minimum_point_spacing * v / v.abs()
493
+ out.append((labels[port.number], port.signal_location + v))
494
+ if port.number in far_sides:
495
+ out.append((far_sides[port.number], port.ground_location - v))
496
+ else:
497
+ out.append((labels[port.number], port.signal_location))
498
+ return out
499
+
500
+
501
+ def group_spec(design: Design, group: str) -> SimGroup:
502
+ """The sim group ``group`` of ``design``; ``"chip"`` defaults to the whole chip with nothing cut."""
503
+ if group in design.sim_groups:
504
+ return design.sim_groups[group]
505
+ if group == CHIP_GROUP:
506
+ return SimGroup(
507
+ select=[*design.instances, *design.routes],
508
+ margin_um=0.0,
509
+ analyses=sorted(ALL_ANALYSES),
510
+ ports={r: "keep" for r in design.routes},
511
+ )
512
+ raise ValueError(f"no sim group {group!r}; available: {sorted(design.sim_groups) + [CHIP_GROUP]}")
513
+
514
+
515
+ def simulation_design(design: Design, group: str, analysis: str) -> tuple[Design, list[tuple[str, str]]]:
516
+ """Copy of ``design`` prepared for simulating ``group``; also returns the cut (instance, port) pairs."""
517
+ kind = analysis_kind(analysis)
518
+ g = group_spec(design, group)
519
+ data = design.to_json_dict()
520
+ data["chip"]["params"] = {
521
+ **data["chip"]["params"],
522
+ "with_grid": False,
523
+ "cheese": "original", # no PDK band either: FEM exports are never cheesed
524
+ "frames_enabled": [],
525
+ "die_frame": False,
526
+ }
527
+ selected = set(g.select)
528
+ for name, inst in data["instances"].items():
529
+ if _has_param(inst["cell"], "with_grid"):
530
+ inst["params"]["with_grid"] = False # never cheese a simulation (whole-cell KQC chips have their own grid)
531
+ if name in selected and _has_junction_type(inst["cell"]) and inst["params"].get("junction_type") != "No Squid":
532
+ inst["params"]["junction_type"] = "Sim" # wrapped qubits (metal:<Class>) keep their junction line
533
+ if inst["params"].get("junction_window"):
534
+ # the fab junction window is metal bridging island and ground; the simulated junction is the port
535
+ inst["params"]["junction_window"] = []
536
+ cuts = []
537
+ # ports={"<route>": "cut"} (subset simulation): the route goes for every analysis. Capacitance: an end on a selected
538
+ # *qubit* gets the waveguide-to-port stub, so the coupling pad is its own net (``<Q>.<port>``). Eigenmode / driven:
539
+ # the pad is left open (it still loads the qubit through its capacitance; no bus mode, no loss) — a stub port at a
540
+ # pocket pad has no port polygon (KQC finds no ground edge inside the pocket), so AEDT would skip it anyway. An end
541
+ # on any other component (a bus tee) is left open.
542
+ for rname, how in g.ports.items():
543
+ if how != "cut" or rname not in data["routes"]:
544
+ continue
545
+ for end in (design.routes[rname].from_, design.routes[rname].to):
546
+ if isinstance(end, str):
547
+ inst, port = split_port_ref(end)
548
+ from quantcore_circuits.sim_tools.subset import has_junction # pylint: disable=C0415
549
+
550
+ if kind == "capacitance" and inst in selected and has_junction(design, inst):
551
+ cuts.append((inst, port))
552
+ del data["routes"][rname]
553
+ if kind == "capacitance":
554
+ from quantcore_circuits.design.schema import HangerEnd # pylint: disable=import-outside-toplevel
555
+
556
+ # feedlines that other routes hang from stay (removing one would leave its hangers without a line)
557
+ hosts = {r.to.hanger for r in design.routes.values() if isinstance(r.to, HangerEnd)}
558
+ hosts |= {r.from_.hanger for r in design.routes.values() if isinstance(r.from_, HangerEnd)}
559
+ for rname in list(data["routes"]):
560
+ if rname not in selected or g.ports.get(rname) in ("keep", "cut") or rname in hosts:
561
+ continue
562
+ route = design.routes[rname]
563
+ for end in (route.from_, route.to):
564
+ if isinstance(end, str):
565
+ inst, port = split_port_ref(end)
566
+ if inst in selected:
567
+ cuts.append((inst, port))
568
+ del data["routes"][rname]
569
+ # couplings are LOM-only (no geometry); drop those that name a route the cut removed, so the design validates
570
+ data["couplings"] = {
571
+ k: c
572
+ for k, c in (data.get("couplings") or {}).items()
573
+ if all(e in data["routes"] or e.split(".", 1)[0] in data["instances"] for e in c["between"])
574
+ }
575
+ data["sim_groups"] = {} # the derived design is only built, never simulated by group again
576
+ return Design.model_validate(data), cuts
577
+
578
+
579
+ def grounded_routes(design: Design) -> set[str]:
580
+ """Routes whose centre conductor is galvanically grounded (they must not become C-matrix nets).
581
+
582
+ A route is grounded if an end is a short: a free end with ``term == 0``, a hanger with ``end == "short"``, or a
583
+ port that the cell class lists in ``qcc_shorted_ports`` (e.g. the Xmon flux-line tip).
584
+ """
585
+ from quantcore_circuits.design.schema import FreeEnd, HangerEnd # pylint: disable=import-outside-toplevel
586
+
587
+ out = set()
588
+ for name, route in design.routes.items():
589
+ for end in (route.from_, route.to):
590
+ if isinstance(end, FreeEnd) and end.term == 0:
591
+ out.add(name)
592
+ elif isinstance(end, HangerEnd) and end.end == "short":
593
+ out.add(name)
594
+ elif isinstance(end, str):
595
+ inst, port = split_port_ref(end)
596
+ cell = design.instances[inst].cell if inst in design.instances else "static:"
597
+ if not cell.startswith("static:") and port in getattr(resolve_cell(cell), "qcc_shorted_ports", ()):
598
+ out.add(name)
599
+ return out
600
+
601
+
602
+ def _selection_box(result, names: list[str], margin: float) -> pya.DBox:
603
+ box = pya.DBox()
604
+ layout = result.layout
605
+ gap_layer = layout.layer(pya.LayerInfo(130, 1)) # 1t1_base_metal_gap_wo_grid
606
+ for inst in result.cell.each_inst():
607
+ if inst.property("id") in names:
608
+ cell = layout.cell(inst.cell_index)
609
+ b = cell.dbbox_per_layer(gap_layer)
610
+ if b.empty():
611
+ b = cell.dbbox()
612
+ box += b.transformed(inst.dcplx_trans)
613
+ if box.empty():
614
+ raise ValueError(f"nothing selected for simulation: {names}")
615
+ box = box.enlarged(margin, margin)
616
+ return pya.DBox(round(box.left), round(box.bottom), round(box.right), round(box.top))
617
+
618
+
619
+ def _route_paths(result) -> dict[str, pya.Region]:
620
+ """Route name → its centre conductor (``1t1_waveguide_path``) in chip coordinates."""
621
+ layout = result.layout
622
+ path_layer = layout.layer(pya.LayerInfo(135, 1)) # 1t1_waveguide_path (centre conductor)
623
+ out: dict[str, pya.Region] = {}
624
+ for inst in result.cell.each_inst():
625
+ name = inst.property("id")
626
+ cell = layout.cell(inst.cell_index)
627
+ if name and cell.name.startswith("Waveguide Composite"):
628
+ region = pya.Region(cell.begin_shapes_rec(path_layer)).transformed(inst.cplx_trans)
629
+ out.setdefault(name, pya.Region()).insert(region)
630
+ return out
631
+
632
+
633
+ def _edge_crossings(result, box: pya.DBox, exclude: set[str], every: bool = False,
634
+ paths: dict[str, pya.Region] | None = None) -> list[tuple[str, pya.DPoint]]:
635
+ """Points on the box edge where route centre conductors cross it: one per route (a capacitance net needs one
636
+ port), or with ``every`` each crossing (eigenmode: every line end leaving the box is terminated)."""
637
+ dbu = result.layout.dbu
638
+ band = 2 * dbu
639
+ out = []
640
+ edges = [
641
+ pya.DBox(box.left - band, box.bottom, box.left + band, box.top),
642
+ pya.DBox(box.right - band, box.bottom, box.right + band, box.top),
643
+ pya.DBox(box.left, box.bottom - band, box.right, box.bottom + band),
644
+ pya.DBox(box.left, box.top - band, box.right, box.top + band),
645
+ ]
646
+ for name, region in (paths if paths is not None else _route_paths(result)).items():
647
+ if name in exclude:
648
+ continue
649
+ found = []
650
+ for i, edge in enumerate(edges):
651
+ hit = (region & pya.Region(edge.to_itype(dbu))).merged()
652
+ for poly in hit.each(): # one point per place the conductor crosses this edge
653
+ c = poly.bbox().center().to_dtype(dbu)
654
+ found.append(
655
+ [
656
+ pya.DPoint(box.left, c.y),
657
+ pya.DPoint(box.right, c.y),
658
+ pya.DPoint(c.x, box.bottom),
659
+ pya.DPoint(c.x, box.top),
660
+ ][i]
661
+ )
662
+ out += [(name, p) for p in (found if every else found[:1])]
663
+ return out
664
+
665
+
666
+ EDGE_SHIFT_STEP_UM = 2.0
667
+
668
+
669
+ def edge_port_ok(lith: pya.Region, box: pya.DBox, pos: pya.DPoint, a: float, b: float, dbu: float) -> bool:
670
+ """Whether KQC builds the polygon of the 50 Ω edge port at crossing ``pos`` (see :func:`build_simulation`: signal
671
+ 1 µm inside the box edge, ground ``a`` further in, the line etched between them ``a + b`` wide): after that etch
672
+ both points must lie on a metal edge. On a bend, a taper or a diagonal they do not and AEDT skips the port (C6;
673
+ a straight diagonal gets its port on its own axis instead, :func:`line_port`). ``lith``: the face's etch
674
+ (gap − addition), uncut by the box."""
675
+ out = _outward(box, pos)
676
+ t = pya.DVector(-out.y, out.x) * ((a + b) / 2)
677
+ signal = pos - out * 1.0
678
+ ground = signal - out * a
679
+ h = a + b + 5.0
680
+ win = pya.DBox(pos.x - h, pos.y - h, pos.x + h, pos.y + h) & box
681
+ etch = pya.Region(pya.DPolygon([signal - t, signal + t, ground + t, ground - t]).to_itype(dbu))
682
+ edges = (pya.Region(win.to_itype(dbu)) - lith - etch).edges()
683
+ tol = max(1, round(KQC_EDGE_TOL_UM / dbu))
684
+
685
+ def on_edge(p):
686
+ ip = p.to_itype(dbu)
687
+ return not edges.interacting(pya.Region(pya.Box(ip.x - tol, ip.y - tol, ip.x + tol, ip.y + tol))).is_empty()
688
+
689
+ return on_edge(signal) and on_edge(ground)
690
+
691
+
692
+ def crossing_square(path: pya.Region, box: pya.DBox, pos: pya.DPoint, a: float, b: float, dbu: float) -> bool:
693
+ """The route's centre conductor (``path``) crosses the box edge at ``pos`` roughly at 90°: inside a band as deep as
694
+ the 50 Ω edge port (``1 + a + b``) it is one piece, ``a`` to ``a + b/2`` wide along the edge, reaching across the
695
+ band. Rules out an edge that runs along the line (a bend tangent to the edge) or a diagonal crossing, where KQC may
696
+ still find edges but the port and the cut are skewed (a straight one gets a :func:`line_port`)."""
697
+ out = _outward(box, pos)
698
+ t = pya.DVector(abs(out.y), abs(out.x))
699
+ depth = 1.0 + a + b
700
+ half = a / 2 + b + 2.0
701
+ band = pya.Region(pya.DBox(pos - out * depth - t * half, pos + t * half).to_itype(dbu))
702
+ piece = (path & band).merged()
703
+ if piece.count() != 1:
704
+ return False
705
+ bb = next(piece.each()).bbox().to_dtype(dbu)
706
+ width = abs(bb.width() * t.x + bb.height() * t.y)
707
+ along = abs(bb.width() * out.x + bb.height() * out.y)
708
+ return a - 0.01 <= width <= a + b / 2 and along >= depth - 0.01
709
+
710
+
711
+ # ---- C6b: a straight line the box edge crosses at an angle: the 50 Ω port on the line's own axis ---------------------
712
+ LINE_PORT_MAX_ANGLE_DEG = 80.0 # a line closer than 90° − this to the box edge gets no port on its axis
713
+ LINE_PORT_STRAIGHT_SIN = 2e-3 # centre-line segments this close to parallel (~0.1°) count as one straight
714
+ LINE_PORT_WALK_UM = 500.0 # how far a straight is followed inwards from the box edge
715
+ EDGE_GAP_EXTENSION_UM = 1.0 # KQC's at-edge port: its signal point (here: the cut's nearest corner) this far inside
716
+
717
+
718
+ @dataclass(frozen=True)
719
+ class LinePort:
720
+ """The 50 Ω port of a straight line the box edge crosses at an angle, on the line's own axis (:func:`line_port`).
721
+ The cut runs from ``signal`` along ``direction`` (``a − 2·over_etching`` long, ``a + b`` wide, square to the line);
722
+ the stub from ``signal`` out to the box edge stays metal, as the at-edge port's 1 µm stub."""
723
+
724
+ edge: pya.DPoint # where the centre line crosses the box edge
725
+ signal: pya.DPoint # the cut's outer side, on the axis
726
+ direction: pya.DVector # unit vector along the line, into the box
727
+ angle: float # deg between the line and the box edge's normal
728
+
729
+
730
+ def _route_spines(result) -> dict[str, list[list[pya.DPoint]]]:
731
+ """Route name → its centre lines in chip coordinates (µm): KQC's zero-width ``waveguide_path`` paths, one point
732
+ list per straight / curved element (the conductor polygons on the same layer are :func:`_route_paths`)."""
733
+ layout = result.layout
734
+ path_layer = layout.layer(pya.LayerInfo(135, 1)) # 1t1_waveguide_path
735
+ out: dict[str, list[list[pya.DPoint]]] = {}
736
+ for inst in result.cell.each_inst():
737
+ name = inst.property("id")
738
+ cell = layout.cell(inst.cell_index)
739
+ if not (name and cell.name.startswith("Waveguide Composite")):
740
+ continue
741
+ it = cell.begin_shapes_rec(path_layer)
742
+ while not it.at_end():
743
+ shape = it.shape()
744
+ if shape.is_path():
745
+ t = inst.dcplx_trans * it.dtrans()
746
+ pts = [t * p for p in shape.dpath.each_point()]
747
+ if len(pts) > 1:
748
+ out.setdefault(name, []).append(pts)
749
+ it.next()
750
+ return out
751
+
752
+
753
+ def _spine_crossing(spines: list[list[pya.DPoint]], box: pya.DBox, pos: pya.DPoint, reach: float):
754
+ """Where a centre line crosses the box edge at ``pos`` (the crossing nearest to it within ``reach`` µm): ``(point
755
+ on the edge, unit vector along the line into the box, µm the line runs straight from there inwards)``, or None."""
756
+ out = _outward(box, pos)
757
+ segs = [(p, q) for pts in spines for p, q in zip(pts, pts[1:]) if p.distance(q) > 1e-6]
758
+ best = None
759
+ for p, q in segs:
760
+ dp, dq = (p - pos).sprod(out), (q - pos).sprod(out) # µm outside the box edge (< 0: inside)
761
+ if dp * dq > 0 or min(dp, dq) >= 0:
762
+ continue
763
+ x = p + (q - p) * (dp / (dp - dq))
764
+ if x.distance(pos) <= reach and (best is None or x.distance(pos) < best[0]):
765
+ best = (x.distance(pos), x, p if dp < 0 else q)
766
+ if best is None:
767
+ return None
768
+ _, x, tip = best
769
+ u = (tip - x) * (1.0 / tip.distance(x))
770
+ straight = tip.distance(x)
771
+ while straight < LINE_PORT_WALK_UM: # a straight split into elements (nodes, airbridges): collinear segments
772
+ nxt = None
773
+ for p, q in segs:
774
+ for s, e in ((p, q), (q, p)):
775
+ w = e - s
776
+ if s.distance(tip) < 0.002 and w.sprod(u) > 0 and abs(w.vprod(u)) < LINE_PORT_STRAIGHT_SIN * w.length():
777
+ nxt = e
778
+ if nxt is None:
779
+ break
780
+ straight += tip.distance(nxt)
781
+ tip = nxt
782
+ return x, u, straight
783
+
784
+
785
+ def line_port(spines: list[list[pya.DPoint]], box: pya.DBox, pos: pya.DPoint, a: float, b: float) -> LinePort | None:
786
+ """The 50 Ω port of the line crossing the box edge at ``pos``, on the line's own axis (C6b). KQC's at-edge port
787
+ cuts along the box normal: where the line crosses at an angle its points miss the metal edges, the port has no
788
+ polygon and AEDT skips it. Here the cut is square to the line, ``a + b`` wide, with its corner nearest the box
789
+ edge 1 µm inside it (the at-edge port's signal point); the line must run straight from the edge to ``b`` past the
790
+ cut. At 90° this is the at-edge geometry. ``spines``: the route's centre lines (:func:`_route_spines`). None on a
791
+ bend or a taper (:func:`straighten_box` moves the edge) and for a line within 90° − ``LINE_PORT_MAX_ANGLE_DEG`` of
792
+ the edge."""
793
+ found = _spine_crossing(spines, box, pos, a + b) if spines else None
794
+ if found is None:
795
+ return None
796
+ x, u, straight = found
797
+ cos = -u.sprod(_outward(box, pos))
798
+ if cos < math.cos(math.radians(LINE_PORT_MAX_ANGLE_DEG)):
799
+ return None
800
+ sin = math.sqrt(max(0.0, 1.0 - cos * cos))
801
+ s = (EDGE_GAP_EXTENSION_UM + (a + b) / 2 * sin) / cos # along the line, edge → the cut's outer side
802
+ if straight < s + a + b:
803
+ return None
804
+ return LinePort(x, x + u * s, u, math.degrees(math.acos(min(1.0, cos))))
805
+
806
+
807
+ def line_port_ok(lith: pya.Region, box: pya.DBox, edge: pya.DPoint, signal: pya.DPoint, ground: pya.DPoint,
808
+ etch_width: float, dbu: float) -> bool:
809
+ """Whether KQC builds the polygon of the 50 Ω port cut from ``signal`` to ``ground``, ``etch_width`` wide (both
810
+ points on a metal edge after the cut, as :func:`edge_port_ok` checks), and the cut parts the line: the stub
811
+ beyond the signal side is not the line beyond the ground side, and it reaches the box edge (``edge``: where the
812
+ line crosses it) like the at-edge port's stub. ``lith``: the face's etch (gap − addition), uncut by the box."""
813
+ d = ground - signal
814
+ if d.length() == 0:
815
+ return False
816
+ v = d * (1.0 / d.length())
817
+ t = pya.DVector(-v.y, v.x) * (etch_width / 2)
818
+ cut = pya.Region(pya.DPolygon([signal - t, signal + t, ground + t, ground - t]).to_itype(dbu))
819
+ win = (pya.DBox(edge, signal) + pya.DBox(ground, ground)).enlarged(etch_width + 5.0, etch_width + 5.0) & box
820
+ metal = pya.Region(win.to_itype(dbu)) - lith - cut
821
+ edges = metal.edges()
822
+ tol = max(1, round(KQC_EDGE_TOL_UM / dbu))
823
+
824
+ def probe(p, h=tol):
825
+ ip = p.to_itype(dbu)
826
+ return pya.Region(pya.Box(ip.x - h, ip.y - h, ip.x + h, ip.y + h))
827
+
828
+ if edges.interacting(probe(signal)).is_empty() or edges.interacting(probe(ground)).is_empty():
829
+ return False
830
+ stub, line = metal.interacting(probe(signal - v * 0.05, 1)), metal.interacting(probe(ground + v * 0.05, 1))
831
+ if stub.is_empty() or line.is_empty() or not (stub & line).is_empty():
832
+ return False
833
+ return not stub.interacting(pya.Region(box.to_itype(dbu)).edges()).is_empty()
834
+
835
+
836
+ def crossing_port(path: pya.Region, spines: list[list[pya.DPoint]], lith: pya.Region, box: pya.DBox, pos: pya.DPoint,
837
+ a: float, b: float, dbu: float, over_etching: float = 0.0):
838
+ """How the 50 Ω port of the line crossing the box edge at ``pos`` is built (C6): ``"edge"`` — a square crossing
839
+ where KQC's at-edge port works (:func:`edge_port_ok`, :func:`crossing_square`; the port as it always was); a
840
+ :class:`LinePort` — a straight line crossing at an angle, the port on its own axis (:func:`line_port`,
841
+ :func:`line_port_ok`); None — neither (a bend, a taper: :func:`straighten_box` moves the edge; if the edge stays,
842
+ the port has no polygon). ``path``: the route's centre conductor, ``spines``: its centre lines."""
843
+ if edge_port_ok(lith, box, pos, a, b, dbu) and crossing_square(path, box, pos, a, b, dbu):
844
+ return "edge"
845
+ lp = line_port(spines, box, pos, a, b)
846
+ if lp is not None and line_port_ok(lith, box, lp.edge, lp.signal, lp.signal + lp.direction * (a - 2 * over_etching),
847
+ a + b, dbu):
848
+ return lp
849
+ return None
850
+
851
+
852
+ def _crossing_ports(result, box, exclude, route_ab, paths, default_ab, lith, spines,
853
+ over_etching=0.0) -> list[tuple[str, pya.DPoint, object]]:
854
+ """``[(route, crossing, crossing_port(...))]`` for every line end leaving ``box``."""
855
+ dbu = result.layout.dbu
856
+ out = []
857
+ for r, p in _edge_crossings(result, box, exclude, every=True, paths=paths):
858
+ a, b = route_ab.get(r, default_ab)
859
+ out.append((r, p, crossing_port(paths[r], spines.get(r, []), lith, box, p, a, b, dbu, over_etching)))
860
+ return out
861
+
862
+
863
+ def _bad_crossings(result, box, exclude, route_ab, paths, default_ab, lith, spines,
864
+ over_etching=0.0) -> list[tuple[str, pya.DPoint]]:
865
+ return [(r, p) for r, p, how in _crossing_ports(result, box, exclude, route_ab, paths, default_ab, lith, spines,
866
+ over_etching) if how is None]
867
+
868
+
869
+ def straighten_box(result, box: pya.DBox, exclude: set[str], route_ab: dict, default_ab: tuple,
870
+ inner: pya.DBox, limit: pya.DBox, max_out: float, max_in: float,
871
+ lith: pya.Region, over_etching: float = 0.0) -> tuple[pya.DBox, list[str]]:
872
+ """Move box edges so every line that leaves the box is cut on a straight section (C6): the eigenmode / driven
873
+ 50 Ω edge port needs that — at 90° KQC's at-edge port, at an angle a port on the line's own axis
874
+ (:func:`crossing_port`); on a bend or a taper KQC finds no edges and AEDT skips the port. An edge
875
+ with a bad crossing moves out (up to ``max_out`` µm from where it was, inside ``limit``) or in (up to ``max_in``,
876
+ never into ``inner``) by the smallest step that leaves no bad crossing on it and no more elsewhere; a line whose
877
+ crossing then moves to the next edge (a bend at a corner of the box) is handled on that edge in the next round.
878
+ The original box is kept when nothing improves. Returns (box, notes)."""
879
+ paths = _route_paths(result)
880
+ paths = {k: v for k, v in paths.items() if k not in exclude}
881
+ spines = {k: v for k, v in _route_spines(result).items() if k not in exclude}
882
+
883
+ def bad_of(b):
884
+ return _bad_crossings(result, b, exclude, route_ab, paths, default_ab, lith, spines, over_etching)
885
+
886
+ bad0 = bad_of(box)
887
+ if not bad0:
888
+ return box, []
889
+ sides = ("left", "right", "bottom", "top")
890
+ sign = {"left": -1, "right": 1, "bottom": -1, "top": 1}
891
+ orig = {"left": box.left, "right": box.right, "bottom": box.bottom, "top": box.top}
892
+
893
+ def side_of(b, p):
894
+ v = _outward(b, p)
895
+ return sides[[(-1, 0), (1, 0), (0, -1), (0, 1)].index((int(v.x), int(v.y)))]
896
+
897
+ def moved(b, side, off): # off > 0: outwards, measured from the original edge
898
+ c = {"left": b.left, "right": b.right, "bottom": b.bottom, "top": b.top}
899
+ c[side] = orig[side] + sign[side] * off
900
+ return pya.DBox(c["left"], c["bottom"], c["right"], c["top"])
901
+
902
+ def fits(b):
903
+ return limit.contains(b.p1) and limit.contains(b.p2) and b.contains(inner.p1) and b.contains(inner.p2)
904
+
905
+ # 2 µm steps near the edge, 10 µm beyond 60 µm (a bend spans up to 2r)
906
+ steps = [k * EDGE_SHIFT_STEP_UM for k in range(1, int(60.0 / EDGE_SHIFT_STEP_UM) + 1)]
907
+ steps += [60.0 + 10.0 * k for k in range(1, int(max(max_out, max_in, 60.0) - 60.0) // 10 + 1)]
908
+
909
+ def search(cur, bad, strict):
910
+ for _round in range(3):
911
+ progressed = False
912
+ for side in sides:
913
+ if not [c for c in bad if side_of(cur, c[1]) == side]:
914
+ continue
915
+ done = False
916
+ for step in steps:
917
+ for off in (step, -step):
918
+ if (off > 0 and off > max_out) or (off < 0 and -off > max_in):
919
+ continue
920
+ cand = moved(cur, side, off)
921
+ if not fits(cand):
922
+ continue
923
+ cbad = bad_of(cand)
924
+ fewer = len(cbad) < len(bad) if strict else len(cbad) <= len(bad)
925
+ if fewer and not [c for c in cbad if side_of(cand, c[1]) == side]:
926
+ cur, bad, done = cand, cbad, True
927
+ break
928
+ if done:
929
+ progressed = True
930
+ break
931
+ if not bad or not progressed:
932
+ break
933
+ return cur, bad
934
+
935
+ # strict first (each move removes a bad crossing); then let a crossing move on to the next edge (a bend at a
936
+ # corner of the box) from wherever that left off
937
+ cur, bad = search(box, bad0, True)
938
+ if bad:
939
+ cur2, bad2 = search(cur, bad, False)
940
+ if len(bad2) < len(bad):
941
+ cur, bad = cur2, bad2
942
+ notes = []
943
+ if len(bad) >= len(bad0):
944
+ return box, []
945
+ final = {"left": cur.left, "right": cur.right, "bottom": cur.bottom, "top": cur.top}
946
+ moves = [f"{s} {'out' if (final[s] - orig[s]) * sign[s] > 0 else 'in'} by {abs(final[s] - orig[s]):g} µm"
947
+ for s in sides if abs(final[s] - orig[s]) > 1e-9]
948
+ fixed = sorted({r for r, _ in bad0})
949
+ angled = sorted({r for r, _, how in _crossing_ports(result, cur, exclude, route_ab, paths, default_ab, lith,
950
+ spines, over_etching)
951
+ if isinstance(how, LinePort) and r in fixed})
952
+ where = ("on a straight section at 90° (the 50 Ω edge port needs one)" if not angled else
953
+ f"on a straight section (the 50 Ω edge port needs one; {', '.join(angled)} at an angle, the port on the "
954
+ "line's own axis)")
955
+ notes.append(f"box edge(s) moved ({', '.join(moves)}) so {', '.join(fixed)} leave the box {where}"
956
+ + (f"; still on a bend: {', '.join(sorted({r for r, _ in bad}))}" if bad else ""))
957
+ return cur, notes
958
+
959
+
960
+ def _terminating_pads(design: Design, selected: set[str], refp: dict) -> list[str]:
961
+ """Pads (cells with ``lumped_signal``/``lumped_ground`` refpoints) that terminate the selection: attached by a
962
+ snap to a selected instance, or at an end of a selected route. They join the group with their 50 Ω port, so a
963
+ selected feedline is never left floating."""
964
+ near = set()
965
+ for name, route in design.routes.items():
966
+ if name in selected:
967
+ near |= {split_port_ref(e)[0] for e in (route.from_, route.to) if isinstance(e, str)}
968
+ for name, inst in design.instances.items():
969
+ p = inst.place
970
+ if p.snap and p.to:
971
+ other = split_port_ref(p.to)[0]
972
+ if name in selected:
973
+ near.add(other)
974
+ elif other in selected:
975
+ near.add(name)
976
+ return sorted(
977
+ n
978
+ for n in near - selected
979
+ if n in design.instances and f"{n}_lumped_signal" in refp and f"{n}_lumped_ground" in refp
980
+ )
981
+
982
+
983
+ def _connected_ports(sim_design: Design, cuts) -> set[str]:
984
+ """``"<inst>.<port>"`` keys with something attached in the simulated design: a route end, a snap, a cut stub."""
985
+ out = {f"{i}.{p}" for i, p in cuts}
986
+ for route in sim_design.routes.values():
987
+ out |= {e for e in (route.from_, route.to) if isinstance(e, str)}
988
+ for name, inst in sim_design.instances.items():
989
+ pl = inst.place
990
+ if pl.snap and pl.to:
991
+ out |= {f"{name}.{pl.snap}", pl.to}
992
+ return out
993
+
994
+
995
+ def lead_open_ends(fm: FaceMetal, ports: dict, islands: dict[str, set[int]], connected: set[str],
996
+ default_ab: tuple) -> list[tuple[str, pya.DPolygon]]:
997
+ """``[(port key, etch polygon)]``: an open end (``b`` long, ``a + 2b`` wide) beyond each unconnected port of a
998
+ simulated qubit whose own junction island (``islands``: qubit → its island pieces) runs through the port into the
999
+ ground plane (the island piece reaches the box edge) — a galvanic lead left unrouted (TwoPadTransmon's ``left``
1000
+ lead ends on the pocket edge). Unetched, it joins the island to the ground plane; the fab cell is unchanged, the
1001
+ etch goes into the simulation only (C4)."""
1002
+ out = []
1003
+ for key, p in sorted(ports.items()):
1004
+ inst = key.split(".", 1)[0]
1005
+ if inst not in islands or key in connected or p.dir is None or p.dir.length() == 0:
1006
+ continue
1007
+ d = p.dir * (1.0 / p.dir.length())
1008
+ inside, outside = fm.piece_at(p.pos - d * 0.3), fm.piece_at(p.pos + d * 0.3)
1009
+ if inside is None or inside not in islands[inst] or outside != inside or not fm.boxed[inside]:
1010
+ continue
1011
+ out.append((key, _open_end(p, default_ab)))
1012
+ return out
1013
+
1014
+
1015
+ def _open_end(p, default_ab: tuple) -> pya.DPolygon | None:
1016
+ """Etch of an open CPW end beyond port ``p``: ``b`` long (outwards), ``a + 2b`` wide."""
1017
+ if p.dir is None or p.dir.length() == 0:
1018
+ return None
1019
+ d = p.dir * (1.0 / p.dir.length())
1020
+ a, b = p.a or default_ab[0], p.b or default_ab[1]
1021
+ t = pya.DVector(-d.y, d.x) * (a / 2 + b)
1022
+ return pya.DPolygon([p.pos - t, p.pos + t, p.pos + d * b + t, p.pos + d * b - t])
1023
+
1024
+
1025
+ def galvanic_routes(fm: FaceMetal, islands: set[int], crossings) -> tuple[set[str], set[int]]:
1026
+ """Routes whose box crossing lies on a junction island (a galvanic lead line leaving the box: the island would be
1027
+ joined to the box edge = ground) and the islands still on the box edge without such a route (C4)."""
1028
+ routes, via = set(), set()
1029
+ for route, pos in crossings:
1030
+ k = fm.piece_at(pos - _outward(fm.box, pos) * 0.3)
1031
+ if k is not None and k in islands:
1032
+ routes.add(route)
1033
+ via.add(k)
1034
+ return routes, {k for k in islands if fm.boxed[k] and k not in via}
1035
+
1036
+
1037
+ def _outward(box: pya.DBox, p: pya.DPoint) -> pya.DVector:
1038
+ """Outward unit normal of the box edge that ``p`` lies on."""
1039
+ d = {
1040
+ (-1, 0): abs(p.x - box.left),
1041
+ (1, 0): abs(p.x - box.right),
1042
+ (0, -1): abs(p.y - box.bottom),
1043
+ (0, 1): abs(p.y - box.top),
1044
+ }
1045
+ return pya.DVector(*min(d, key=d.get))
1046
+
1047
+
1048
+ def build_simulation(
1049
+ source,
1050
+ group: str,
1051
+ analysis: str,
1052
+ waveguide_length: float = 100.0,
1053
+ airbridges: bool | None = None,
1054
+ **sim_params,
1055
+ ) -> SimSetup:
1056
+ """Create the KQC ``Simulation`` for ``group``/``analysis`` (see module docstring).
1057
+
1058
+ The simulated geometry never has the ground grid (cheese). Airbridges are dropped for speed unless
1059
+ ``airbridges=True`` (or the group's ``settings["airbridges"]``); a note flags crossing bridges whose line is then
1060
+ open at the crossing."""
1061
+ design = load_design(source)
1062
+ g = group_spec(design, group)
1063
+ keep_ab = bool(g.settings.get("airbridges", False)) if airbridges is None else bool(airbridges)
1064
+ whole_chip = group == CHIP_GROUP and group not in design.sim_groups
1065
+ pdk = get_pdk(design.pdk)
1066
+ sim_design, cuts = simulation_design(design, group, analysis)
1067
+ result = build(sim_design)
1068
+ faces = list(sim_params.get("face_stack") or pdk.simulation_params().get("face_stack") or [])
1069
+ geometry = strip_layers(result, airbridges=keep_ab, bumps=len(faces) > 1)
1070
+ notes = []
1071
+ if geometry["ground_grid_shapes"]:
1072
+ notes.append(f"ground grid removed from the simulation ({geometry['ground_grid_shapes']} shapes)")
1073
+ if geometry.get("indium_bump_shapes"):
1074
+ notes.append(
1075
+ f"indium bumps dropped ({geometry['indium_bump_shapes']} shapes): the simulation has one face "
1076
+ f"({', '.join(map(str, faces)) or '?'}), so a bump would be a PEC pillar to the top of the box; the "
1077
+ "flip-chip top face (2b1) is not simulated"
1078
+ )
1079
+ crossing = sorted(
1080
+ name
1081
+ for name, r in sim_design.routes.items()
1082
+ if (name in g.select or whole_chip) and any(getattr(w, "airbridge", False) for w in (r.nodes or []))
1083
+ )
1084
+ if not keep_ab and crossing:
1085
+ notes.append(
1086
+ f"crossing airbridges dropped on {', '.join(crossing)}: those lines are open at the crossing in the "
1087
+ "simulation; use airbridges=True (sim group settings) to keep them"
1088
+ )
1089
+ refp = result.refpoints
1090
+ select = list(g.select) + ([] if whole_chip else _terminating_pads(design, set(g.select), refp))
1091
+ box = pya.DBox(*design.chip.box) if whole_chip else _selection_box(result, select, g.margin_um)
1092
+ ports_ports = result.plan.all_ports()
1093
+ face = (_faces(faces) or [pdk.face])[0]
1094
+ default_ab = (pdk.cpw_a, pdk.cpw_b)
1095
+ route_ab = {
1096
+ name: (rp.params.get("a", pdk.cpw_a), rp.params.get("b", pdk.cpw_b)) for name, rp in result.plan.routes.items()
1097
+ }
1098
+ grounded = grounded_routes(sim_design)
1099
+ over_etching = float(sim_params.get("over_etching") or 0.0) # KQC Simulation param (the PDK leaves it 0)
1100
+ eigen = analysis_kind(analysis) == "eigenmode"
1101
+ # eigenmode terminates every line end in 50 Ω; a driven run needs a wave port on every line end (S21)
1102
+ every = analysis_kind(analysis) in ("eigenmode", "driven")
1103
+ if every: # ports={"<route>": "edge"}: a grounded line the box cuts (a qubit's λ/4 readout) is terminated too
1104
+ grounded -= {r for r, how in g.ports.items() if how == "edge"}
1105
+
1106
+ # the analysis metal (FaceMetal) stands in an open end for each cut route's waveguide stub, which KQC adds later and
1107
+ # which keeps the coupler pad / lead off the ground plane
1108
+ stub_ends = [_open_end(ports_ports[f"{i}.{p}"], default_ab) for i, p in cuts if f"{i}.{p}" in ports_ports]
1109
+ stub_ends = [e for e in stub_ends if e is not None]
1110
+ # C8: a metal / gap polygon of more than GDS_MAX_POINTS points (long meanders and spirals keyholed into one ground
1111
+ # polygon) gets its bends simplified by at most SIM_SMOOTH_UM, in the simulation only (DesignSimulation below)
1112
+ fm = FaceMetal(result, box, face, etch=stub_ends)
1113
+ smooth = SIM_SMOOTH_UM if fm.max_points() > GDS_MAX_POINTS else 0.0
1114
+ if smooth:
1115
+ fm = FaceMetal(result, box, face, etch=stub_ends, smooth=smooth)
1116
+
1117
+ infos: list[SimPortInfo] = []
1118
+ junctions = []
1119
+ junction_probes: list[tuple[str, pya.DPoint]] = []
1120
+ island_points: dict[str, list] = {} # qubit → a point on each of its junction islands (C4)
1121
+ for name in g.select:
1122
+ inst = design.instances.get(name)
1123
+ if inst is None:
1124
+ continue
1125
+ junction_cell = is_junction_cell(inst.cell)
1126
+ if not junction_cell and not _is_qubit(inst.cell):
1127
+ continue
1128
+ # Quantcore cells expose the junction ends directly; KQC qubits through their "Sim" junction sub-cell
1129
+ a = refp.get(f"{name}_port_squid_a") or refp.get(f"{name}_squid_port_squid_a")
1130
+ b = refp.get(f"{name}_port_squid_b") or refp.get(f"{name}_squid_port_squid_b")
1131
+ if a is None or b is None:
1132
+ continue
1133
+ sheet = None
1134
+ if a.distance(b) < 2 * fm.dbu:
1135
+ notes.append(f"{name}: zero-length junction (squid_a = squid_b at ({a.x:.2f}, {a.y:.2f})): no junction "
1136
+ "port")
1137
+ continue
1138
+ kqc_edges = fm.on_edge(a) and fm.on_edge(b)
1139
+ if junction_cell or not kqc_edges:
1140
+ # C3: a junction cell is simulated as a junction only where it bridges two conductors (a code-built layout);
1141
+ # C5: pins off the metal edges (Metal qubits) — the port spans the gap between the edges on the junction
1142
+ # axis
1143
+ found = junction_gap(fm, a, b)
1144
+ if found is None and junction_cell:
1145
+ notes.append(f"{name}: junction cell {inst.cell} does not bridge two conductors here (placed on its "
1146
+ "own, both ends on one metal): no junction port, it is simulated as drawn metal — "
1147
+ "simulate the qubit that contains it")
1148
+ continue
1149
+ if found is None:
1150
+ outside = "" if box.contains(a) and box.contains(b) else (
1151
+ " — a junction pin lies outside the simulation box: increase margin_um")
1152
+ notes.append(f"{name}: KQC finds no metal edge at the junction pins and the junction axis crosses no "
1153
+ "gap between two conductors: the junction port stays at the drawn pins (check the "
1154
+ f"geometry){outside}")
1155
+ elif not (kqc_edges and found[0].distance(a) < 0.01 and found[1].distance(b) < 0.01):
1156
+ sig, gnd = found
1157
+ sheet = junction_sheet(fm, sig, gnd, JJ_PORT_WIDTH_UM)
1158
+ notes.append(
1159
+ f"{name}: junction port spans the gap on the junction axis from ({gnd.x:.2f}, {gnd.y:.2f}) to "
1160
+ f"({sig.x:.2f}, {sig.y:.2f}) µm ({sig.distance(gnd):.2f} µm; the drawn pins ({a.x:.2f}, "
1161
+ f"{a.y:.2f}) / ({b.x:.2f}, {b.y:.2f}) are not on the metal edges)"
1162
+ + (f", sheet {sheet[1]:g} µm wide" if sheet else ", no clean sheet fits: KQC's edge polygon")
1163
+ )
1164
+ a, b = sig, gnd
1165
+ if analysis_kind(analysis) in ("eigenmode", "driven"):
1166
+ # the lumped RLC sheet (and the EPR Lj) take the junction as the LOM does: L at the design flux, C_J
1167
+ lj, cj = lumped_junction(name, inst, pdk, notes)
1168
+ else: # capacitance: the gap stays open, L is a placeholder (the design value, else 10 nH)
1169
+ lj, cj = junction_values(inst)
1170
+ net_a, net_b = junction_nets(name, inst, pdk)
1171
+ junctions.append((name, a, b, (lj or 10.0) * 1e-9, cj * 1e-15, net_a, net_b, sheet))
1172
+ # naming only (the port geometry stays as KQC wants it): the island metal next to each junction end
1173
+ junction_probes.append((net_a, _onto_metal(result, a, b)))
1174
+ island_points.setdefault(name, []).append(_island_point(fm, a, b))
1175
+ if net_b:
1176
+ junction_probes.append((net_b, _onto_metal(result, b, a)))
1177
+ island_points[name].append(_island_point(fm, b, a))
1178
+
1179
+ def islands_by(m: FaceMetal) -> dict[str, set[int]]:
1180
+ return {q: {k for k in (m.piece_at(p) for p in pts if p is not None) if k is not None}
1181
+ for q, pts in island_points.items()}
1182
+
1183
+ def islands_of(m: FaceMetal) -> set[int]:
1184
+ return set().union(*islands_by(m).values()) if island_points else set()
1185
+
1186
+ # C4: an unrouted galvanic lead of a simulated qubit runs into the ground plane → an open end in the simulation
1187
+ open_ends = lead_open_ends(fm, ports_ports, islands_by(fm), _connected_ports(sim_design, cuts), default_ab)
1188
+ etch_extra = [poly for _, poly in open_ends]
1189
+ if open_ends:
1190
+ fm = FaceMetal(result, box, face, etch=stub_ends + etch_extra, smooth=smooth)
1191
+ geometry["lead_open_ends"] = [key for key, _ in open_ends]
1192
+ notes.append(f"open end etched beyond the unrouted lead(s) {', '.join(k for k, _ in open_ends)} (simulation "
1193
+ "only): the lead met the ground plane at the pocket edge and joined its junction island to ground")
1194
+
1195
+ def galvanic(m: FaceMetal, b: pya.DBox):
1196
+ if whole_chip:
1197
+ return set(), set()
1198
+ forced_, stuck_ = galvanic_routes(m, islands_of(m), _edge_crossings(result, b, set(), every=True))
1199
+ return forced_ & grounded, stuck_
1200
+
1201
+ # C4: a grounded line (λ/4, hanger short) galvanic to an island and cut by the box joins the island to the box edge
1202
+ forced, stuck = galvanic(fm, box)
1203
+ if every and not whole_chip: # C6: lines leave the box on a straight section (50 Ω edge port)
1204
+ inner = box.enlarged(-g.margin_um, -g.margin_um)
1205
+ r_max = max([float(rp.params.get("r", 100.0)) for rp in result.plan.routes.values()] or [100.0])
1206
+ new_box, box_notes = straighten_box(result, box, grounded - forced, route_ab, default_ab, inner,
1207
+ pya.DBox(*design.chip.box),
1208
+ min(max(g.margin_um, 2 * r_max + 30.0), FACE_METAL_MARGIN_UM - 50.0),
1209
+ g.margin_um / 2, fm.lith, over_etching)
1210
+ if new_box != box:
1211
+ box = new_box
1212
+ notes += box_notes
1213
+ fm = FaceMetal(result, box, face, etch=stub_ends + etch_extra, smooth=smooth)
1214
+ forced, stuck = galvanic(fm, box)
1215
+ if forced:
1216
+ grounded -= forced
1217
+ notes.append(f"{', '.join(sorted(forced))}: galvanic to a junction island and cut by the box, so terminated at "
1218
+ "the box edge (50 Ω / edge port) instead of joining the island to the box edge (ground)")
1219
+ if stuck:
1220
+ notes.append(f"{len(stuck)} junction island(s) still reach the box edge (joined to the ground plane or a line "
1221
+ "the export cannot terminate)")
1222
+ contact_patches = vertex_contact_patches(result, box, faces)
1223
+ if contact_patches:
1224
+ n_patches = sum(len(v) for v in contact_patches.values())
1225
+ geometry["vertex_contacts_joined"] = n_patches
1226
+ where = ", ".join(f"({b.center().x:.1f}, {b.center().y:.1f})" for v in contact_patches.values() for b in v)
1227
+ notes.append(
1228
+ f"{n_patches} metal piece(s) touching at a single point joined with a {CONTACT_PATCH_UM:g} µm patch at "
1229
+ f"{where} µm: KQC counts a point contact as connected, Q3D does not (\"objects … are touching\")"
1230
+ )
1231
+
1232
+ stubs = []
1233
+ for inst, port in cuts:
1234
+ p = ports_ports[f"{inst}.{port}"]
1235
+ stubs.append((f"{inst}.{port}", p))
1236
+ crossings = [] if whole_chip else _edge_crossings(result, box, grounded, every=every)
1237
+ # C6b: a straight line the box edge crosses at an angle gets its 50 Ω port on its own axis (crossing index →
1238
+ # LinePort); a square crossing keeps KQC's at-edge port (eigenmode) / the wave port (driven), unchanged
1239
+ line_ports: dict[int, LinePort] = {}
1240
+ if every and crossings:
1241
+ paths, spines = _route_paths(result), _route_spines(result)
1242
+ for i, (route, pos) in enumerate(crossings):
1243
+ a, b = route_ab.get(route, default_ab)
1244
+ how = crossing_port(paths.get(route, pya.Region()), spines.get(route, []), fm.lith, box, pos, a, b,
1245
+ fm.dbu, over_etching)
1246
+ if isinstance(how, LinePort):
1247
+ line_ports[i] = how
1248
+ if line_ports:
1249
+ listed = ", ".join(f"{crossings[i][0]} {lp.angle:.0f}°" for i, lp in sorted(line_ports.items()))
1250
+ notes.append(
1251
+ f"{len(line_ports)} 50 Ω port(s) on the line's own axis ({listed} from the box edge's normal): the box "
1252
+ "edge crosses these lines at an angle, so each port cuts its line square, just inside the box (the short "
1253
+ "piece out to the box edge stays metal, as at a square crossing)"
1254
+ + ("" if eigen else "; driven: a lumped 50 Ω port instead of a wave port (a wave port needs the line "
1255
+ "normal to the box face)")
1256
+ )
1257
+ lumped = [] # pads (cells with lumped_signal/lumped_ground refpoints): the whole chip's, or the selected ones
1258
+ for name in design.instances if whole_chip else [n for n in select if n in design.instances]:
1259
+ sig, gnd = refp.get(f"{name}_lumped_signal"), refp.get(f"{name}_lumped_ground")
1260
+ if sig is not None and gnd is not None and box.contains(sig) and box.contains(gnd):
1261
+ lumped.append((name, sig, gnd))
1262
+
1263
+ chip_index = result.cell.cell_index()
1264
+ far_sides: dict[int, str] = {}
1265
+ sheets: dict[int, tuple] = {} # junction port number → (sheet polygon points, width) where the builder drew it
1266
+ line_port_numbers: set[int] = set() # C6b ports (on a line's own axis)
1267
+
1268
+ class DesignSimulation(Simulation):
1269
+ def build(self):
1270
+ self.cell.insert(pya.DCellInstArray(chip_index, pya.DTrans()))
1271
+ for f, patches in contact_patches.items():
1272
+ shapes = self.cell.shapes(self.layout.layer(default_faces[f]["base_metal_addition"]))
1273
+ for patch in patches:
1274
+ shapes.insert(patch)
1275
+ if etch_extra: # C4 open ends (simulation only)
1276
+ shapes = self.cell.shapes(self.layout.layer(default_faces[face]["base_metal_gap_wo_grid"]))
1277
+ for poly in etch_extra:
1278
+ shapes.insert(poly)
1279
+ n = 0
1280
+ for name, a, b, lj, cj, net_a, net_b, sheet in junctions:
1281
+ n += 1
1282
+ self.ports.append( # floating transmon: the far island must not be forced to ground
1283
+ InternalPort(
1284
+ n, *self.etched_line(a, b), inductance=lj, capacitance=cj, junction=True, floating=bool(net_b)
1285
+ )
1286
+ )
1287
+ infos.append(SimPortInfo(n, "junction", f"{name}.junction", net_a))
1288
+ if sheet:
1289
+ sheets[n] = sheet
1290
+ if net_b:
1291
+ far_sides[n] = net_b
1292
+ for label, p in stubs:
1293
+ n += 1
1294
+ self.produce_waveguide_to_port(
1295
+ p.pos,
1296
+ p.pos + p.dir * 10,
1297
+ n,
1298
+ use_internal_ports=True,
1299
+ waveguide_length=waveguide_length,
1300
+ a=p.a,
1301
+ b=p.b,
1302
+ )
1303
+ infos.append(SimPortInfo(n, "waveguide", label, label))
1304
+ for i, (route, pos) in enumerate(crossings):
1305
+ n += 1
1306
+ lp = line_ports.get(i)
1307
+ if lp is not None: # C6b: a straight line at an angle: the port on its own axis, cut square to it
1308
+ a, b = route_ab.get(route, (pdk.cpw_a, pdk.cpw_b))
1309
+ outer, inner_ = lp.signal, lp.signal + lp.direction * (a - 2 * self.over_etching)
1310
+ # eigenmode: the at-edge order (signal on the stub out to the box edge, ground on the line);
1311
+ # driven: a terminal lumped port, signal on the line, the stub (box wall = ground) its reference
1312
+ sig, gnd = (outer, inner_) if eigen else (inner_, outer)
1313
+ self.ports.append(InternalPort(n, sig, gnd, etch_width=a + b, resistance=50.0,
1314
+ floating=eigen and route in forced))
1315
+ infos.append(SimPortInfo(n, "edge_lumped", route, route))
1316
+ line_port_numbers.add(n)
1317
+ elif eigen: # lumped 50 Ω port 1 µm inside the edge, across the centre conductor (KQC "at_edge")
1318
+ a, b = route_ab.get(route, (pdk.cpw_a, pdk.cpw_b))
1319
+ out = _outward(self.box, pos)
1320
+ signal = pos - 1.0 * out
1321
+ ground = signal - (a - 2 * self.over_etching) * out
1322
+ # a line galvanic to a junction island (C4): floating, or KQC makes the island part of ground
1323
+ self.ports.append(InternalPort(n, signal, ground, etch_width=a + b, resistance=50.0,
1324
+ floating=route in forced))
1325
+ infos.append(SimPortInfo(n, "edge_lumped", route, route))
1326
+ else:
1327
+ self.ports.append(EdgePort(n, pos))
1328
+ infos.append(SimPortInfo(n, "edge", route, route))
1329
+ for name, sig, gnd in lumped:
1330
+ n += 1
1331
+ self.ports.append(InternalPort(n, *self.etched_line(sig, gnd), resistance=50.0))
1332
+ infos.append(SimPortInfo(n, "lumped", f"{name}.pad", f"{name}.pad"))
1333
+
1334
+ def simplified_region(self, region, expansion=0.0):
1335
+ out = super().simplified_region(region, expansion)
1336
+ return out.smoothed(max(1, round(smooth / self.layout.dbu)), True) if smooth else out # C8, sim only
1337
+
1338
+ def get_port_data(self):
1339
+ out = []
1340
+ for p in super().get_port_data():
1341
+ if p.get("junction") and p["number"] in sheets:
1342
+ p = sheet_junction_port(p, *sheets[p["number"]])
1343
+ elif p.get("junction"):
1344
+ p = narrow_junction_port(p)
1345
+ elif p["number"] in line_port_numbers:
1346
+ p = edge_midpoint_locations(p)
1347
+ out.append(p)
1348
+ return out
1349
+
1350
+ DesignSimulation.__name__ = f"DesignSimulation_{group}"
1351
+ params = {
1352
+ **pdk.simulation_params(),
1353
+ "name": f"{design.name}_{group}_{analysis}",
1354
+ "box": box,
1355
+ "use_internal_ports": True,
1356
+ "use_ports": True,
1357
+ **sim_params,
1358
+ }
1359
+ sim = DesignSimulation(result.layout, **params)
1360
+ if smooth:
1361
+ geometry["bends_simplified_um"] = smooth
1362
+ notes.append(f"bends simplified by at most {smooth:g} µm in the simulation (a polygon had more than "
1363
+ f"{GDS_MAX_POINTS} points, the GDS XY record limit); the fab layout is unchanged")
1364
+ labels = {p.number: p.excitation or p.name for p in infos}
1365
+ # KQC qubits mark their islands (probe_island, probe_island_1/_2): those name the island nets first
1366
+ islands = [
1367
+ (f"{name}.{key[len(name) + 7 :].replace('_', '')}", pos)
1368
+ for name in g.select
1369
+ for key, pos in sorted(refp.items())
1370
+ if key.startswith(f"{name}_probe_island")
1371
+ ]
1372
+ lom_probes = _lom_port_probes(design, select, ports_ports)
1373
+ probes = islands + _port_probes(sim, labels, far_sides) + junction_probes + _cell_probes(design, select, result)
1374
+ probes += lom_probes + _route_probes(result, select, sim_design)
1375
+ nets = net_names(sim, probes, near=lom_probes)
1376
+ named = label_unnamed(sim, nets, result, select, design)
1377
+ if named:
1378
+ nets.update(named)
1379
+ notes.append(f"{len(named)} conductor(s) no port or LOM node touches, named after their component: "
1380
+ f"{', '.join(sorted(named.values()))} (cut where dropped airbridges crossed, floating parts of a "
1381
+ "cell, or ground enclosed by it; airbridges=True keeps the bridges)")
1382
+ # an internal port without a port polygon is skipped by KQC's AEDT import (KQC only logs it): a missing junction
1383
+ # L_J or 50 Ω termination. Eigenmode / driven only (Q3D uses nets, not ports). Typical causes: the box edge cuts a
1384
+ # line in a bend or a taper that the box straightening could not avoid (edge_lumped; a straight line at any angle
1385
+ # gets a port on its own axis, C6b), or a junction line that is not axis-aligned.
1386
+ if every:
1387
+ port_data = {d["number"]: d for d in sim.get_port_data()}
1388
+ for p in infos:
1389
+ d = port_data.get(p.number, {})
1390
+ if d.get("type") == "InternalPort" and "polygon" not in d:
1391
+ why = (
1392
+ "the box edge cuts the line in a bend or a taper (a straight line gets a port at any angle); "
1393
+ "change margin_um so the edge crosses a straight section"
1394
+ if p.kind == "edge_lumped"
1395
+ else "KQC found no metal edge at its signal/ground points (e.g. a diagonal junction line)"
1396
+ )
1397
+ notes.append(f"port {p.number} ({p.name}, {p.kind}): no port polygon, so AEDT skips it — {why}")
1398
+ warnings.warn(f"{design.name} {group}/{analysis}: {notes[-1]}", stacklevel=2)
1399
+ return SimSetup(design, group, analysis, sim, infos, box, waveguide_length, nets, geometry, notes,
1400
+ sorted(sim_design.routes))
1401
+
1402
+
1403
+ def edge_midpoint_locations(p: dict) -> dict:
1404
+ """A port polygon KQC built on slanted edges (C6b): its corners are the found edges' end points on the database
1405
+ grid, so the drawn signal / ground points (off the grid) can lie a fraction of a nm off the polygon's slanted
1406
+ sides, and AEDT then refuses the port's current line ("Both endpoints of the directed line must lie on the
1407
+ boundary face"). The exported locations become the midpoints of KQC's own signal and ground edges, which lie on
1408
+ the polygon; KQC's nets were assigned from the drawn points already. Without a polygon nothing changes."""
1409
+ if "polygon" not in p or "signal_edge" not in p or "ground_edge" not in p:
1410
+ return p
1411
+ out = dict(p)
1412
+ for loc, edge in (("signal_location", "signal_edge"), ("ground_location", "ground_edge")):
1413
+ (x1, y1, z1), (x2, y2, _) = p[edge]
1414
+ out[loc] = [(x1 + x2) / 2, (y1 + y2) / 2, z1]
1415
+ return out
1416
+
1417
+
1418
+ JJ_PORT_WIDTH_UM = 10.0 # junction lumped-RLC sheet width where KQC's own edges are too long (see below)
1419
+ JJ_PORT_MAX_EDGE_UM = 20.0
1420
+
1421
+
1422
+ def narrow_junction_port(p: dict, width: float = JJ_PORT_WIDTH_UM, max_edge: float = JJ_PORT_MAX_EDGE_UM) -> dict:
1423
+ """The junction port sheet as a ``width``-wide rectangle on the junction line (signal → ground location).
1424
+
1425
+ KQC spans the port polygon between the *whole* metal edges nearest the signal and ground points. With a junction
1426
+ drawn on lead stubs (KQC qubits, Xmon + Quantcore Junction) those are short (≈ 8 µm) and kept. Where the junction
1427
+ bridges a plain gap they are the island's and the ground's whole edges: chip 12's TransmonCrossFL (signal 50 µm,
1428
+ ground 90–1145 µm: a skewed trapezoid sheet, no qubit eigenmode), IBM pocket pads (750 µm both), and a diagonal
1429
+ StarQubit line has no edge at all (no polygon, AEDT skips the port). Those get the rectangle instead; the ends sit
1430
+ on the metal boundary (``etched_line``), the current line is unchanged."""
1431
+ def length(e):
1432
+ return math.dist(e[0][:2], e[1][:2])
1433
+
1434
+ edges = [p.get("signal_edge"), p.get("ground_edge")]
1435
+ if "polygon" in p and all(e is not None and length(e) <= max_edge for e in edges):
1436
+ return p
1437
+ s, g = p["signal_location"], p["ground_location"]
1438
+ dx, dy = g[0] - s[0], g[1] - s[1]
1439
+ d = math.hypot(dx, dy)
1440
+ if d == 0:
1441
+ return p
1442
+ known = [length(e) for e in edges if e is not None]
1443
+ w = min([width] + known) / 2
1444
+ tx, ty = -dy / d * w, dx / d * w
1445
+ z = s[2] if len(s) > 2 else 0.0
1446
+ out = dict(p)
1447
+ out["signal_edge"] = ((s[0] - tx, s[1] - ty, z), (s[0] + tx, s[1] + ty, z))
1448
+ out["ground_edge"] = ((g[0] + tx, g[1] + ty, z), (g[0] - tx, g[1] - ty, z))
1449
+ out["polygon"] = [list(out["signal_edge"][0]), list(out["signal_edge"][1]), list(out["ground_edge"][0]),
1450
+ list(out["ground_edge"][1])]
1451
+ return out
1452
+
1453
+
1454
+ def sheet_junction_port(p: dict, polygon, width: float) -> dict:
1455
+ """Port data with the builder's junction sheet (:func:`junction_sheet`): ``polygon`` replaces KQC's; the signal /
1456
+ ground edges are ``width`` long across the junction axis at the port's signal / ground points."""
1457
+ s, g = p["signal_location"], p["ground_location"]
1458
+ z = s[2] if len(s) > 2 else 0.0
1459
+ dx, dy = g[0] - s[0], g[1] - s[1]
1460
+ d = math.hypot(dx, dy) or 1.0
1461
+ tx, ty = -dy / d * width / 2, dx / d * width / 2
1462
+ out = dict(p)
1463
+ out["polygon"] = [[q.x, q.y, z] for q in polygon]
1464
+ out["signal_edge"] = ((s[0] - tx, s[1] - ty, z), (s[0] + tx, s[1] + ty, z))
1465
+ out["ground_edge"] = ((g[0] + tx, g[1] + ty, z), (g[0] - tx, g[1] - ty, z))
1466
+ return out
1467
+
1468
+
1469
+ def _gds_points(poly) -> int:
1470
+ return poly.num_points() + 2 * poly.holes() # a GDS writer keyholes each hole into the hull
1471
+
1472
+
1473
+ def split_large_gds_polygons(path, limit: int = GDS_MAX_POINTS, overlap_um: float = 0.01) -> int:
1474
+ """Rewrite each polygon of the simulation GDS ``path`` with more than ``limit`` points (a GDS XY record holds at
1475
+ most 4095) as pieces of the same conductor that overlap by ``overlap_um`` along the cuts, inside the original
1476
+ outline (a layer's pieces that KLayout's writer split at 8000 points, edge to edge, are rejoined first). For HFSS
1477
+ jobs only: every metal sheet is PEC there, so the pieces act as one conductor; Q3D's ``AutoIdentifyNets`` keeps
1478
+ overlapping objects as separate nets (AEDT 2024 R1 render). Used where simplifying bends is not enough (many holes,
1479
+ e.g. flux-trap rows); done on the written file, after KQC built the port polygons from the whole outlines. Layers
1480
+ without such a polygon are not touched; returns the number of polygons rewritten (0: file unchanged)."""
1481
+ layout = pya.Layout()
1482
+ layout.read(str(path))
1483
+ ov = max(1, round(overlap_um / layout.dbu))
1484
+ count = 0
1485
+ for cell in layout.each_cell():
1486
+ for li in layout.layer_indexes():
1487
+ shapes = cell.shapes(li)
1488
+ if not any((s.is_polygon() or s.is_simple_polygon()) and _gds_points(s.polygon) > limit
1489
+ for s in shapes.each()):
1490
+ continue
1491
+ merged = pya.Region(shapes).merged() # also rejoins pieces a writer split at 8000 points
1492
+ shapes.clear()
1493
+ for poly in merged.each():
1494
+ if _gds_points(poly) <= limit:
1495
+ shapes.insert(poly)
1496
+ continue
1497
+ whole = pya.Region(poly)
1498
+ todo, pieces = [poly], []
1499
+ while todo:
1500
+ q = todo.pop()
1501
+ if _gds_points(q) <= limit - 100:
1502
+ pieces.append(q)
1503
+ else:
1504
+ todo += list(q.split())
1505
+ for piece in pieces:
1506
+ for part in (pya.Region(piece).sized(ov) & whole).each():
1507
+ shapes.insert(part)
1508
+ count += 1
1509
+ if count:
1510
+ opts = pya.SaveLayoutOptions()
1511
+ opts.set_format_from_filename(str(path))
1512
+ opts.write_context_info = False
1513
+ layout.write(str(path), opts)
1514
+ return count
1515
+
1516
+
1517
+ def _island_point(fm: FaceMetal, p: pya.DPoint, other: pya.DPoint) -> pya.DPoint | None:
1518
+ """A point on the island metal at junction end ``p`` (just past it, away from ``other``), or None."""
1519
+ d = p.distance(other)
1520
+ for step in (0.3, 1.0, 0.0):
1521
+ q = p + (p - other) * (step / d) if d else p
1522
+ if fm.piece_at(q) is not None:
1523
+ return q
1524
+ return None
1525
+
1526
+
1527
+ def _cell_probes(design: Design, select: list[str], result) -> list[tuple[str, pya.DPoint]]:
1528
+ """Probes a cell declares for its LOM nodes (``qcc_probes(params) -> {node: (x, y)}``, cell frame, µm): islands
1529
+ no port touches (JtwpaChain's chain islands ``n1``…), labelled with the node's FEM island."""
1530
+ from quantcore_circuits.lom.fragment import lom_model # pylint: disable=import-outside-toplevel
1531
+
1532
+ trans = {inst.property("id"): inst.dcplx_trans for inst in result.cell.each_inst() if inst.property("id")}
1533
+ pdk = get_pdk(design.pdk)
1534
+ out = []
1535
+ for name in select:
1536
+ inst = design.instances.get(name)
1537
+ if inst is None or inst.cell.startswith("static:") or name not in trans:
1538
+ continue
1539
+ fn = getattr(resolve_cell(inst.cell), "qcc_probes", None)
1540
+ if fn is None:
1541
+ continue
1542
+ try:
1543
+ points = fn(dict(inst.params or {}))
1544
+ model = lom_model(inst.cell)
1545
+ frag = model(name, inst, pdk) if model else None
1546
+ except Exception: # noqa: BLE001 (naming must not block the export)
1547
+ continue
1548
+ for node, (x, y) in points.items():
1549
+ label = ((frag.nodes.get(node) or {}).get("island") if frag else None) or f"{name}.{node}"
1550
+ out.append((label, trans[name] * pya.DPoint(x, y)))
1551
+ return out
1552
+
1553
+
1554
+ def _excitation_regions(sim) -> dict[int, pya.Region]:
1555
+ from kqcircuits.simulations.simulation import get_simulation_layer_by_name # pylint: disable=C0415
1556
+
1557
+ regions: dict[int, pya.Region] = {}
1558
+ for name, layer in sim.layers.items():
1559
+ exc = layer.get("excitation")
1560
+ if exc:
1561
+ shapes = sim.cell.shapes(sim.layout.layer(get_simulation_layer_by_name(name)))
1562
+ regions.setdefault(exc, pya.Region()).insert(pya.Region(shapes))
1563
+ return regions
1564
+
1565
+
1566
+ def label_unnamed(sim, nets: dict[int, str], result, select: list[str], design: Design) -> dict[int, str]:
1567
+ """Labels for signal conductors no probe named (C7): a piece of a selected cell's own line (its waveguide path;
1568
+ a spiral cut where a dropped airbridge crossed) → the cell's LOM island when it has exactly one (``X.res#2``), a
1569
+ piece of a route's line → the route; any other conductor inside a selected cell → ``<cell>.floating[k]``
1570
+ (floating parts such as a coupler's cross, ground enclosed by the cell); else ``floating<k>``."""
1571
+ from quantcore_circuits.lom.fragment import lom_model # pylint: disable=import-outside-toplevel
1572
+
1573
+ regions = _excitation_regions(sim)
1574
+ todo = [e for e in sorted(regions) if e not in nets]
1575
+ if not todo:
1576
+ return {}
1577
+ layout = result.layout
1578
+ dbu = layout.dbu
1579
+ path_layer = layout.layer(pya.LayerInfo(135, 1)) # 1t1_waveguide_path
1580
+ pdk = get_pdk(design.pdk)
1581
+ cells = {} # selected instance → (bbox, own line path, line label)
1582
+ for inst in result.cell.each_inst():
1583
+ name = inst.property("id")
1584
+ if name not in select or name not in design.instances:
1585
+ continue
1586
+ cell = layout.cell(inst.cell_index)
1587
+ path = pya.Region(cell.begin_shapes_rec(path_layer)).transformed(inst.cplx_trans)
1588
+ di = design.instances[name]
1589
+ model = lom_model(di.cell) if not di.cell.startswith("static:") else None
1590
+ try:
1591
+ frag = model(name, di, pdk) if model else None
1592
+ except Exception: # noqa: BLE001
1593
+ frag = None
1594
+ isl = [v.get("island") for v in (frag.nodes.values() if frag else []) if v and v.get("island")]
1595
+ # a piece of the cell's own line is that line's island only if the cell has one (a resonator: X.res)
1596
+ cells[name] = (inst.dbbox(), path if len(isl) == 1 else pya.Region(), isl[0] if len(isl) == 1 else "")
1597
+ routes = _route_paths(result)
1598
+ raw: dict[int, str] = {}
1599
+ for e in todo:
1600
+ r = regions[e]
1601
+ label = next((line for _, (_, path, line) in cells.items() if not path.is_empty() and
1602
+ not r.interacting(path).is_empty()), None)
1603
+ label = label or next((rn for rn, path in routes.items() if not r.interacting(path).is_empty()), None)
1604
+ if label is None:
1605
+ c = r.bbox().to_dtype(dbu).center()
1606
+ inside = [(bb.area(), n) for n, (bb, _, _) in cells.items() if bb.contains(c)]
1607
+ label = f"{min(inside)[1]}.floating" if inside else "floating"
1608
+ raw[e] = label
1609
+ out: dict[int, str] = {}
1610
+ used = list(nets.values())
1611
+ for e, label in raw.items():
1612
+ same = [x for x in raw.values() if x == label]
1613
+ if label.endswith("floating"):
1614
+ k = sum(1 for x in out.values() if x.startswith(label)) + 1
1615
+ out[e] = label if len(same) == 1 and label not in used else f"{label}{k}"
1616
+ else:
1617
+ k = sum(1 for x in used + list(out.values()) if x == label or x.startswith(label + "#")) + 1
1618
+ out[e] = label if k == 1 else f"{label}#{k}"
1619
+ return out
1620
+
1621
+
1622
+ def _onto_metal(result, p: pya.DPoint, other: pya.DPoint, reach: float = 60.0, step: float = 0.5) -> pya.DPoint:
1623
+ """A point on the metal at a junction end, for *naming* the island net: ``p`` itself if it touches metal, else the
1624
+ first metal point moving away from ``other`` along the junction line (within ``reach`` µm). Some Metal qubits
1625
+ (StarQubit) end their junction line inside an etched slot, so the port probe lands in etch and the island stays
1626
+ unnamed. The port geometry itself is not changed (KQC places junction ports inside the gap by design)."""
1627
+ layout = result.layout
1628
+ gap = pya.Region(result.cell.begin_shapes_rec(layout.layer(pya.LayerInfo(130, 1)))) # 1t1_base_metal_gap_wo_grid
1629
+
1630
+ def metal(pt): # touches metal: on metal, or on the metal/etch boundary (where KQC's own ports sit)
1631
+ box = pya.Region(pya.DBox(pt.x - 0.05, pt.y - 0.05, pt.x + 0.05, pt.y + 0.05).to_itype(layout.dbu))
1632
+ return not (box - gap).is_empty()
1633
+
1634
+ if metal(p):
1635
+ return p
1636
+ d = p - other
1637
+ if d.length() == 0:
1638
+ return p
1639
+ d = d / d.length()
1640
+ k = step
1641
+ while k <= reach:
1642
+ q = p + d * k
1643
+ if metal(q):
1644
+ return q
1645
+ k += step
1646
+ return p
1647
+
1648
+
1649
+ def _route_probes(result, select: list[str], sim_design: Design) -> list[tuple[str, pya.DPoint]]:
1650
+ """A probe on each selected route that stays in the simulation (not cut): the middle of its longest straight
1651
+ segment (on the centre conductor even where corners are rounded), labelled with the route name."""
1652
+ out = []
1653
+ for name in select:
1654
+ rp = result.plan.routes.get(name)
1655
+ if rp is None or name not in sim_design.routes:
1656
+ continue
1657
+ pts = rp.polyline()
1658
+ if len(pts) < 2:
1659
+ continue
1660
+ a, b = max(zip(pts, pts[1:]), key=lambda ab: (ab[1] - ab[0]).length())
1661
+ out.append((name, a + (b - a) * 0.5))
1662
+ return out
1663
+
1664
+
1665
+ def _lom_port_probes(design: Design, select: list[str], ports: dict) -> list[tuple[str, pya.DPoint]]:
1666
+ """Fallback probes: each selected component's ports, labelled with the FEM island of the LOM node they map to.
1667
+
1668
+ Names conductors no simulation port touches (e.g. a resonator component next to a feedline: ``R2.res``). A probe
1669
+ sits 0.5 µm inside the component, behind the port. Ports mapped to ground or a control are skipped.
1670
+ """
1671
+ from quantcore_circuits.lom.fragment import lom_model # pylint: disable=import-outside-toplevel
1672
+
1673
+ pdk = get_pdk(design.pdk)
1674
+ out = []
1675
+ for name in select:
1676
+ inst = design.instances.get(name)
1677
+ fn = lom_model(inst.cell) if inst is not None and not inst.cell.startswith("static:") else None
1678
+ if fn is None:
1679
+ continue
1680
+ try:
1681
+ frag = fn(name, inst, pdk)
1682
+ except Exception: # noqa: BLE001 (a model that cannot evaluate must not block the export)
1683
+ continue
1684
+ for port, local in sorted(frag.port_nodes.items()):
1685
+ p = ports.get(f"{name}.{port}")
1686
+ if p is None or local == "gnd" or local.startswith("control:"):
1687
+ continue
1688
+ label = (frag.nodes.get(local) or {}).get("island") or f"{name}.{local}"
1689
+ out.append((label, p.pos - p.dir * 0.5 if p.dir is not None else p.pos))
1690
+ return out