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,932 @@
1
+ """Layout → LOM: compose the components' LOM fragments along the design's connectivity into a ``circuit.json``.
2
+
3
+ Mapping (see :mod:`quantcore_circuits.lom.fragment` for the component side):
4
+
5
+ ===================================== =============================================================================
6
+ layout lumped model
7
+ ===================================== =============================================================================
8
+ component its fragment: nodes (FEM islands), elements, port → node map
9
+ ``cpw`` route port ↔ port a wire: both ports' nodes become one conductor (named after the route when it
10
+ joins pads, e.g. the feedline ``FL``)
11
+ route port → hanger / short free end λ/4 resonator ``TLres`` from the port's node to ground (+ ``HANGER``
12
+ coupling element to the feedline node: coupled-line κ)
13
+ route port → open free end λ/2 resonator (open–open) to ground
14
+ route free end → hanger (no port) a resonator on its own node ``<route>.line`` (island ``<route>``): λ/4 when
15
+ exactly one end is shorted (``term=0`` / ``end="short"``), else λ/2
16
+ ``meander`` route port ↔ port λ/2 bus resonator: both end nodes join one resonator node
17
+ route on a ``control:*`` port control line (flux bias of that qubit's SQUID), no circuit element; the
18
+ conductor is grounded at the qubit, so its pad's port is dropped
19
+ snap placement (gap 0) the two ports' nodes join (galvanic)
20
+ ``design.couplings`` C / L between the resolved ends (an end may be a route: its conductor); a
21
+ value-less C from a cell's coupled section (``Fragment.hangers``) is a HANGER
22
+ line end on a zero-length termination wired / snapped to it, or drawn on its body: the line end takes its
23
+ termination (CpweOpenEnd: open)
24
+ component lines joined end to end one line (a chain: route between two line ports, wire / snap between
25
+ them): its two free ends decide wire / λ/4 / λ/2, its length is the sum; a
26
+ pass-through cell (taper, ``Line.through``) only extends it (one Z0: the
27
+ width step is not modelled), the TLres takes the main line's or route's name
28
+ ===================================== =============================================================================
29
+
30
+ Values are component estimates (calibration, CPW formulas, coupled-line κ); :func:`quantcore_circuits.circuit.
31
+ fill.fill` replaces capacitances by FEM C-matrix values where the island labels match. Element names follow the
32
+ convention used everywhere else: ``C_<Q>``, ``J_<Q>``, ``Cg_<Q>_<claw>``, ``Cc_<Q>_<claw>``, ``<route>`` (TLres),
33
+ ``K_<route>`` (hanger), ``Port_<pad>``.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from dataclasses import dataclass, field
39
+
40
+ from quantcore_circuits.circuit.schema import CircuitModel
41
+ from quantcore_circuits.lom.fragment import QUBIT_NODES, Element, Fragment, generic_fragment, lom_model
42
+
43
+ DRIVE_C_FF = 0.1 # charge-line ↔ island capacitance when nothing better is known (rough)
44
+ DEFAULT_TOL = {"f_q_GHz": 0.02, "alpha_MHz": 10.0, "f_GHz": 0.01, "g_MHz": 10.0, "chi_MHz": 0.1, "kappa_MHz": 0.2}
45
+
46
+
47
+ class _UF:
48
+ def __init__(self):
49
+ self.parent: dict[str, str] = {}
50
+
51
+ def find(self, x: str) -> str:
52
+ self.parent.setdefault(x, x)
53
+ while self.parent[x] != x:
54
+ self.parent[x] = self.parent[self.parent[x]]
55
+ x = self.parent[x]
56
+ return x
57
+
58
+ def union(self, a: str, b: str) -> None:
59
+ ra, rb = self.find(a), self.find(b)
60
+ if ra != rb:
61
+ if rb == "gnd":
62
+ ra, rb = rb, ra
63
+ self.parent[rb] = ra
64
+
65
+
66
+ @dataclass
67
+ class LomBuild:
68
+ model: CircuitModel
69
+ notes: list[str] = field(default_factory=list)
70
+ port_map: dict[str, str] = field(default_factory=dict) # "Q1.claw_n" → circuit node
71
+ unconnected: list[str] = field(default_factory=list) # component ports with a node but no connection
72
+
73
+
74
+ def lom_from_design(source, select: list[str] | None = None, name: str | None = None, plan=None) -> LomBuild:
75
+ """Build the lumped circuit of ``source`` (all of it, or the instances/routes in ``select``)."""
76
+ from quantcore_circuits.assembly.last_good import plan_for_lom, resolve # pylint: disable=import-outside-toplevel
77
+ from quantcore_circuits.circuit.bridges import tl_resonator # pylint: disable=import-outside-toplevel
78
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
79
+ from quantcore_circuits.design.schema import CHIP, FreeEnd, HangerEnd # pylint: disable=import-outside-toplevel
80
+ from quantcore_circuits.lom.calibration import hanger_k, hanger_kappa_MHz # pylint: disable=C0415
81
+ from quantcore_circuits.lom.metal_models import metal_only_without_pocket # pylint: disable=C0415
82
+ from quantcore_circuits.pdk import get_pdk # pylint: disable=import-outside-toplevel
83
+
84
+ design = load_design(source)
85
+ pdk = get_pdk(design.pdk)
86
+ # a route that failed to build is replaced by its last good one (with a warning), or named as missing
87
+ plan = resolve(plan) if plan is not None else plan_for_lom(design, source)
88
+ chosen = set(select) if select else set(design.instances) | set(design.routes)
89
+ notes: list[str] = list(getattr(plan, "warnings", []))
90
+ uf = _UF()
91
+ uf.find("gnd")
92
+ nodes: dict[str, dict] = {} # global node → {"island": ...}
93
+ elements: list[Element] = []
94
+ port_map: dict[str, str] = {}
95
+ knobs: dict = {}
96
+ kind_of: dict[str, str] = {} # global node → "qubit" | "coupler" | "pad" | ...
97
+ used_ports: set[str] = set()
98
+ line_states: list[dict] = [] # component lines (see lom.fragment.Line)
99
+ port_line: dict[str, tuple[dict, int]] = {} # 'INST.port' -> (line state, end index)
100
+ main_node: dict[str, str] = {} # instance → node holding its junction (or its 'island')
101
+ sole_node: dict[str, str] = {} # instance → its only node (a feedline segment, a pad), for couplings to it
102
+ line_of: dict[tuple[str, str], dict] = {} # (instance, line name) → line state
103
+ ext_hangers: dict[str, list[dict]] = {} # instance → Fragment.hangers
104
+ straps: list[str] = [] # global nodes of Fragment.straps (grounded when no port on them is joined)
105
+
106
+ def glob(inst: str, local: str) -> str:
107
+ if local == "gnd":
108
+ return "gnd"
109
+ return inst if local == "island" else f"{inst}.{local}"
110
+
111
+ for iname, inst in design.instances.items():
112
+ if iname not in chosen:
113
+ continue
114
+ fn = lom_model(inst.cell)
115
+ ports = sorted(plan.instances[iname].local_ports)
116
+ if fn:
117
+ frag = fn(iname, inst, pdk)
118
+ no_pocket = metal_only_without_pocket(design, plan, iname)
119
+ if no_pocket: # a metal-only Metal cell on the ground plane: nothing electrical
120
+ frag = Fragment(port_nodes={p: "gnd" for p in set(frag.port_nodes) | set(ports)}, notes=[no_pocket])
121
+ else: # a cell without ports (label, marker, finger shape) has nothing to map: no note either
122
+ frag = generic_fragment(iname, inst, ports) if ports else Fragment()
123
+ notes += frag.notes
124
+ knobs.update(frag.knobs)
125
+ for local, spec in frag.nodes.items():
126
+ g = glob(iname, local)
127
+ nodes[g] = dict(spec)
128
+ kind_of[g] = "qubit" if local in QUBIT_NODES else ("pad" if local == "pad" else "coupler")
129
+ uf.find(g)
130
+ if len(frag.nodes) == 1:
131
+ sole_node[iname] = glob(iname, next(iter(frag.nodes)))
132
+ if frag.hangers:
133
+ ext_hangers[iname] = list(frag.hangers)
134
+ straps += [glob(iname, n) for n in frag.straps if n in frag.nodes]
135
+ for line in frag.lines:
136
+ st = {"line": line, "inst": iname, "node": glob(iname, line.node), "state": [None, None], "extra": 0.0}
137
+ st["hangers"], st["ext"], st["routes"], st["free_routes"] = [], [], [], []
138
+ st["peer"] = [None, None] # (line state, end) of another line joined to that end
139
+ st["length"] = line.length_um
140
+ if line.through and line.length_um <= 0: # a pass-through cell without a length parameter
141
+ st["length"] = _port_distance(plan, iname, line.ports)
142
+ line_of[(iname, line.name)] = st
143
+ kind_of.setdefault(st["node"], "line")
144
+ line_states.append(st)
145
+ for i, port in enumerate(line.ports):
146
+ if port:
147
+ port_line[f"{iname}.{port}"] = (st, i)
148
+ for e in frag.elements:
149
+ elements.append(Element(e.name, e.type, tuple(glob(iname, n) for n in e.nodes), e.value, e.knob, e.note))
150
+ if e.type in ("JJ", "SQUID") and iname not in main_node:
151
+ main_node[iname] = glob(iname, next(n for n in e.nodes if n != "gnd"))
152
+ if iname not in main_node and "island" in frag.nodes:
153
+ main_node[iname] = iname
154
+ for port, local in frag.port_nodes.items():
155
+ port_map[f"{iname}.{port}"] = local if local.startswith("control:") else glob(iname, local)
156
+
157
+ # chip-frame launchers ("chip.WN", ...): a 50 Ω port each, like a BondPad
158
+ for rname, route in design.routes.items():
159
+ if rname not in chosen:
160
+ continue
161
+ for end in (route.from_, route.to):
162
+ if isinstance(end, str) and end.startswith(f"{CHIP}.") and end not in port_map:
163
+ launcher = end.split(".", 1)[1]
164
+ nodes[end] = {"island": end}
165
+ kind_of[end] = "pad"
166
+ uf.find(end)
167
+ elements.append(
168
+ Element(
169
+ f"Port_{launcher}",
170
+ "R",
171
+ (end, "gnd"),
172
+ {"R_ohm": 50.0, "source": "design"},
173
+ note="chip-frame launcher (sample-holder port)",
174
+ )
175
+ )
176
+ port_map[end] = end
177
+
178
+ # declared couplings (design.couplings): ``wire`` couplings join two ports galvanically (overlapping metal), like
179
+ # a snap with no gap; C/L couplings are resolved after the route pass (an end may name a route's conductor)
180
+ wired: dict[str, str] = {} # 'INST.port' → the port it is wired to
181
+ coupling_at = len(elements) # C/L coupling elements keep their place in the netlist
182
+ for cname, c in design.couplings.items():
183
+ if c.type != "wire":
184
+ continue
185
+ pa, pb = (port_map.get(e) for e in c.between)
186
+ if any(e.split(".", 1)[0] not in chosen for e in c.between):
187
+ continue # an end outside the selection
188
+ if pa is None or pb is None or pa.startswith("control:") or pb.startswith("control:"):
189
+ notes.append(f"wire {cname}: cannot resolve {list(c.between)} to circuit nodes (skipped)")
190
+ continue
191
+ uf.union(pa, pb)
192
+ used_ports.update(c.between)
193
+ wired[c.between[0]], wired[c.between[1]] = c.between[1], c.between[0]
194
+
195
+ # snap placement with no gap: the two ports touch (galvanic)
196
+ for iname, inst in design.instances.items():
197
+ pl = inst.place
198
+ if iname not in chosen or not (pl.snap and pl.to):
199
+ continue
200
+ own = pl.snap if "." in pl.snap else f"{iname}.{pl.snap}"
201
+ pa, pb = port_map.get(own), port_map.get(pl.to)
202
+ if pa is None or pb is None or pa.startswith("control:") or pb.startswith("control:"):
203
+ continue
204
+ if pl.gap:
205
+ notes.append(f"{iname}: snapped to {pl.to} with a {pl.gap:g} µm gap (not connected in the LOM)")
206
+ continue
207
+ uf.union(pa, pb)
208
+
209
+ controls: dict[str, dict] = {}
210
+ resonators: list[tuple[str, object]] = []
211
+ route_conductor: dict[str, str] = {} # cpw route → a node on its conductor
212
+ route_node: dict[str, str | None] = {} # any route → the node a coupling to it attaches to (None: none)
213
+ wire_length: dict[str, float] = {} # cpw route (a wire) → its length
214
+ for rname, route in design.routes.items():
215
+ if rname not in chosen:
216
+ continue
217
+ specs = [route.from_, route.to]
218
+ if not isinstance(specs[0], str) and isinstance(specs[1], str):
219
+ specs.reverse() # a free end given as "from": the port end is the resonator's coupler end
220
+ ends = []
221
+ for end in specs:
222
+ if isinstance(end, str):
223
+ used_ports.add(end)
224
+ ends.append(port_map.get(end, f"unknown:{end}"))
225
+ elif isinstance(end, HangerEnd):
226
+ ends.append(f"hanger:{end.hanger}")
227
+ elif isinstance(end, FreeEnd):
228
+ ends.append("gnd" if end.term == 0 else "open")
229
+ a, b = ends
230
+ rp = plan.routes[rname]
231
+ length = rp.length or route.length
232
+ if any(e.startswith("control:") for e in ends):
233
+ ctl = next(e for e in ends if e.startswith("control:"))
234
+ qubit_port = specs[0] if ends[0] == ctl else specs[1]
235
+ other = b if ends[0] == ctl else a
236
+ qubit = qubit_port.split(".", 1)[0]
237
+ ctl_kind = ctl.split(":", 1)[1]
238
+ controls[rname] = {
239
+ "kind": ctl_kind if ctl_kind == "drive" else ctl_kind + "_bias",
240
+ "target": f"J_{qubit}",
241
+ "line": rname,
242
+ "length_um": length,
243
+ }
244
+ real = other not in ("gnd", "open") and not other.startswith(("hanger:", "unknown:", "control:"))
245
+ route_node[rname] = other if real and ctl_kind == "drive" else None # a flux line is grounded
246
+ if ctl_kind == "drive":
247
+ # a charge line ends open next to the qubit: its conductor keeps its port, with a small C to the
248
+ # island (drive coupling, Purcell/T1 through the drive port)
249
+ if real and qubit in main_node:
250
+ elements.append(
251
+ Element(
252
+ f"Cd_{qubit}",
253
+ "C",
254
+ (main_node[qubit], other),
255
+ {
256
+ "estimate": DRIVE_C_FF,
257
+ "unit": "fF",
258
+ "fem": "cmatrix",
259
+ "estimate_source": "rough: typical open-ended charge line next to a transmon",
260
+ "estimate_kind": "rough",
261
+ "uncertainty": "±100%",
262
+ },
263
+ note="drive (charge) line coupling",
264
+ )
265
+ )
266
+ continue
267
+ if real:
268
+ uf.union("gnd", other) # the bias line is shorted to ground at the qubit
269
+ continue
270
+ if any(e.startswith("unknown:") for e in ends):
271
+ notes.append(f"route {rname}: end(s) {[e for e in ends if e.startswith('unknown:')]} not in the selection")
272
+ continue
273
+ if not any(isinstance(sp, str) for sp in specs):
274
+ # no port at either end (a free end ↔ a hanger, two free ends): a resonator on its own conductor
275
+ own = f"{rname}.line"
276
+ nodes[own] = {"island": rname}
277
+ kind_of[own] = "line"
278
+ uf.find(own)
279
+ route_node[rname] = own
280
+ resonators.append((rname, (own, b, route, rp, length, specs)))
281
+ continue
282
+ far = b
283
+ la = port_line.get(specs[0]) if isinstance(specs[0], str) else None
284
+ lb = port_line.get(specs[1]) if isinstance(specs[1], str) else None
285
+ if la and (far.startswith("hanger:") or far in ("gnd", "open")):
286
+ # the route continues a component's line to a free end / hanger: one longer line
287
+ st, idx = la
288
+ st["extra"] += length or 0.0
289
+ st["routes"].append(rname)
290
+ route_node[rname] = st["node"]
291
+ if far.startswith("hanger:"):
292
+ st["state"][idx] = "short" if specs[1].end == "short" else "open"
293
+ st["hangers"].append((rname, specs[1], far.split(":", 1)[1]))
294
+ else:
295
+ st["state"][idx] = "short" if far == "gnd" else "open"
296
+ st["free_routes"].append(rname)
297
+ continue
298
+ meander_bus = route.type == "meander" and far in nodes and not (la or lb)
299
+ route_node[rname] = a # a resonator route: its coupler-end node; a wire: its conductor
300
+ if far.startswith("hanger:") or far in ("gnd", "open") or meander_bus:
301
+ resonators.append((rname, (a, far, route, rp, length, [] if meander_bus else [specs[1]])))
302
+ continue
303
+ # cpw between two conductors: one wire (a component line it touches gets the route's length)
304
+ for line_end, other in ((la, b), (lb, a)):
305
+ if line_end:
306
+ st, idx = line_end
307
+ st["extra"] += (length or 0.0) / (2 if la and lb else 1)
308
+ st["state"][idx] = "joined" if la and lb else other
309
+ st["routes"].append(rname)
310
+ if la and lb: # line → route → line: one line (see the component lines below)
311
+ la[0]["peer"][la[1]], lb[0]["peer"][lb[1]] = lb, la
312
+ uf.union(a, b)
313
+ route_conductor[rname] = a # what a hanger on this route couples to (after all wires merge)
314
+ if not (la or lb):
315
+ wire_length[rname] = length or 0.0
316
+ if kind_of.get(a) == "pad" and kind_of.get(b) == "pad":
317
+ nodes.setdefault(f"route:{rname}", {})
318
+ uf.union(a, f"route:{rname}")
319
+ kind_of[f"route:{rname}"] = "feedline"
320
+
321
+ def ensure_feedline(fl: str) -> str:
322
+ fl_node = f"route:{fl}"
323
+ if fl_node not in nodes and fl in route_conductor: # e.g. one segment of a feedline split by tees
324
+ return route_conductor[fl]
325
+ if fl_node not in nodes: # feedline outside the selection: keep its conductor + both port loads
326
+ nodes[fl_node] = {}
327
+ kind_of[fl_node] = "feedline"
328
+ elements.append(
329
+ Element(
330
+ f"Port_{fl}",
331
+ "R",
332
+ (fl_node, "gnd"),
333
+ {"R_ohm": 25.0, "source": "design"},
334
+ note="feedline seen from the resonator: two 50 Ω ports in parallel",
335
+ )
336
+ )
337
+ return fl_node
338
+
339
+ def facing_gap(h, rname):
340
+ """The hanger's ground strip as the calibration sees it: narrowed facing gaps (``coupler_gap`` /
341
+ ``line_gap``) bring the conductors closer by what they save, as a narrower strip between full gaps would."""
342
+ if h.coupler_gap is None and h.line_gap is None:
343
+ return h.ground_gap
344
+ b_r = plan.routes[rname].params.get("b", pdk.cpw_b)
345
+ b_l = plan.routes[h.hanger].params.get("b", pdk.cpw_b) if h.hanger in plan.routes else pdk.cpw_b
346
+ saved = (b_r - (h.coupler_gap if h.coupler_gap is not None else b_r)) + (
347
+ b_l - (h.line_gap if h.line_gap is not None else b_l))
348
+ return h.ground_gap - saved
349
+
350
+ def hanger_element(ename, node, other, coupling_um, gap_um, end, tl, kind, knob):
351
+ kappa = None
352
+ if tl:
353
+ kappa = hanger_kappa_MHz(tl["f_GHz"], tl["vp_m_s"], coupling_um, gap_um)
354
+ if kind == "lambda/2":
355
+ kappa /= 2 # same coupled section, twice the stored energy of a λ/4 at the same end voltage
356
+ src = "coupled-line Q_ext (calibration)" + (" / 2 for a λ/2 mode (rough)" if kind == "lambda/2" else "")
357
+ return Element(
358
+ ename,
359
+ "HANGER",
360
+ (node, other),
361
+ {
362
+ "coupling_length_um": coupling_um,
363
+ "ground_gap_um": gap_um,
364
+ "end": end,
365
+ "k": hanger_k(gap_um),
366
+ "kappa_MHz": kappa,
367
+ "estimate_source": src,
368
+ },
369
+ {"param": knob} if knob else None,
370
+ )
371
+
372
+ def tl_value(kind, length, a_um, b_um):
373
+ tl = tl_resonator(length, a_um, b_um, design.pdk) if length else {}
374
+ value = {
375
+ "kind": kind,
376
+ "length_um": length,
377
+ "a_um": a_um,
378
+ "b_um": b_um,
379
+ "source": "layout",
380
+ **{k: tl[k] for k in ("f_GHz", "Z0_ohm", "vp_m_s") if k in tl},
381
+ # kinetic inductance of the film (decision #45): L_k beside L_geo, nH/m, and the fraction of the line's L
382
+ **{k: round(tl[k], 6) for k in ("L_geo_nH_per_m", "L_k_nH_per_m", "alpha_k") if k in tl},
383
+ }
384
+ if kind == "lambda/2" and tl:
385
+ value["f_GHz"] = tl["f_GHz"] * 2
386
+ return value, tl
387
+
388
+ # declared C/L couplings: one element each between the resolved nodes (a value-less C from a component line's
389
+ # coupled section to a conductor no port carries is that line's HANGER instead)
390
+ coupling_elements: list[Element] = []
391
+ for cname, c in design.couplings.items():
392
+ if c.type == "wire":
393
+ continue
394
+ ends_c, outside = [], []
395
+ for end in c.between:
396
+ inst_name, _, rest = end.partition(".")
397
+ if inst_name in design.instances:
398
+ if inst_name not in chosen:
399
+ outside.append(end)
400
+ elif not rest:
401
+ ends_c.append(main_node.get(inst_name) or sole_node.get(inst_name))
402
+ elif end in port_map:
403
+ ends_c.append(port_map[end])
404
+ else:
405
+ ends_c.append(glob(inst_name, rest) if glob(inst_name, rest) in nodes else None)
406
+ elif end in design.routes: # the route's conductor
407
+ if end not in chosen:
408
+ outside.append(end)
409
+ else:
410
+ ends_c.append(route_node.get(end))
411
+ else:
412
+ ends_c.append(None)
413
+ is_hanger = c.type == "C" and c.value is None
414
+ if outside:
415
+ # a resonator in the selection hanging off a feedline route outside it: keep the feedline + port loads
416
+ # (as for a route's hanger end); any other coupling with an end outside the selection is left out
417
+ fl = outside[0]
418
+ inside = c.between[1] if c.between[0] == fl else c.between[0]
419
+ if (
420
+ is_hanger
421
+ and len(outside) == 1
422
+ and fl in design.routes
423
+ and ends_c[0]
424
+ and ext_hangers.get(inside.partition(".")[0])
425
+ ):
426
+ ends_try = [ends_c[0], f"route:{fl}"] if c.between[1] == fl else [f"route:{fl}", ends_c[0]]
427
+ hanger = _hanger_coupling(c, ends_try, ext_hangers, line_of, glob)
428
+ if hanger:
429
+ st, spec, _ = hanger
430
+ st["ext"].append(
431
+ (cname if cname.startswith("K_") else f"K_{cname}", ensure_feedline(fl), spec, c.note)
432
+ )
433
+ continue
434
+ if None in ends_c or any(n.startswith("control:") for n in ends_c):
435
+ notes.append(f"coupling {cname}: cannot resolve {list(c.between)} to circuit nodes (skipped)")
436
+ continue
437
+ hanger = _hanger_coupling(c, ends_c, ext_hangers, line_of, glob) if is_hanger else None
438
+ if hanger: # a component line's coupled section to a conductor no port carries: HANGER, not a C
439
+ st, spec, other = hanger
440
+ st["ext"].append((cname if cname.startswith("K_") else f"K_{cname}", other, spec, c.note))
441
+ continue
442
+ value = {"estimate": c.value, "estimate_source": "declared", "estimate_kind": "declared"}
443
+ if c.type == "C":
444
+ value["unit"] = "fF"
445
+ if c.fem:
446
+ value["fem"] = "cmatrix"
447
+ else:
448
+ value |= {"unit": "nH", "L_nH": c.value}
449
+ coupling_elements.append(Element(f"{c.type}_{cname}", c.type, tuple(ends_c), value, note=c.note))
450
+ elements[coupling_at:coupling_at] = coupling_elements
451
+
452
+ # component lines (lom.fragment.Line): what each end meets decides wire, λ/4 or λ/2. Lines joined end to end (a
453
+ # route between two line ports, a wire coupling or snap between them, a zero-length termination on a line end)
454
+ # are one line, a chain: e.g. a shorted end → route → taper → route → hanger is one λ/4
455
+ snapped = {p for p in port_map if _snapped(design, p)}
456
+ # zero-length terminations (CpweOpenEnd, OpenToGround, ...): a line end joined to one (wire / snap) takes its
457
+ # termination; an unjoined line end drawn on one (the legacy "resonatorGnd" cut box) does too
458
+ terms = {p: v for p, v in port_line.items() if _is_termination(v[0]["line"])}
459
+ on_term = _ends_on_terminations(plan, design, line_states, terms, used_ports | snapped)
460
+ order = sorted(line_states, key=lambda s: _is_termination(s["line"])) # terminations last
461
+ for st in order:
462
+ line, inst = st["line"], st["inst"]
463
+ for i, port in enumerate(line.ports):
464
+ if st["state"][i] is not None:
465
+ continue # a route reached it, or a line joined to it did
466
+ ref = f"{inst}.{port}" if port else None
467
+ partner = (wired.get(ref) or _snap_partner(design, ref)) if ref else None
468
+ peer = port_line.get(partner) if partner else None
469
+ if ref in on_term:
470
+ tport, dist = on_term[ref]
471
+ tst, tidx = terms[tport]
472
+ _join(st, i, tst, tidx)
473
+ used_ports.update((ref, tport))
474
+ uf.union(st["node"], tst["node"]) # the cut box sits on the line end: one conductor, as if wired
475
+ notes.append(
476
+ f"{ref}: nothing joined, but the end lies on the termination {tport} ({dist:.1f} µm apart): "
477
+ f"modelled {tst['line'].term[tidx]} (declare a wire coupling {ref} ↔ {tport} to make it explicit)"
478
+ )
479
+ elif ref is None or (ref not in used_ports and ref not in snapped):
480
+ st["state"][i] = line.term[i]
481
+ elif peer and peer[0]["state"][peer[1]] is None and peer[0] is not st:
482
+ _join(st, i, *peer) # wired / snapped to another line's end (a termination: its end condition)
483
+ elif partner and partner in port_map and not peer:
484
+ st["state"][i] = port_map[partner] # snapped / wired to another component's conductor (see below)
485
+ else:
486
+ st["state"][i] = "through" # joined to something this model cannot follow: a wire
487
+ chain_uf = _UF()
488
+ for st in order:
489
+ for peer in st["peer"]:
490
+ if peer:
491
+ chain_uf.union(str(id(st)), str(id(peer[0])))
492
+ chains: dict[str, list[dict]] = {} # in line order: a chain sits where its first non-termination line is
493
+ for st in order:
494
+ chains.setdefault(chain_uf.find(str(id(st))), []).append(st)
495
+ chain_info: list[dict] = []
496
+ wire_on, wire_len = dict(route_conductor), dict(wire_length) # wires on a resonator's conductor (_tap_extra)
497
+ for members in chains.values():
498
+ outer = [m["state"][i] for m in members for i in (0, 1) if m["state"][i] != "joined"]
499
+ kinds = []
500
+ for s_ in outer:
501
+ if s_ in ("short", "open", "through"):
502
+ kinds.append(s_)
503
+ else: # the conductor a route / wire / snap joined this end to
504
+ kinds.append("through" if kind_of.get(s_) in ("pad", "feedline") else "coupler")
505
+ free = [k for k in kinds if k in ("short", "open")]
506
+ extra = sum(m["extra"] for m in members)
507
+ touched = any(
508
+ f"{m['inst']}.{p}" in used_ports or f"{m['inst']}.{p}" in snapped
509
+ for m in members
510
+ for p in m["line"].ports
511
+ if p
512
+ )
513
+ info = {
514
+ "members": members,
515
+ "kinds": kinds,
516
+ "length": sum(m["length"] for m in members) + extra,
517
+ "extra": extra,
518
+ # terminations alone, or pass-through sections nothing joins: no line of their own
519
+ "zero": not extra
520
+ and (
521
+ all(_is_termination(m["line"]) for m in members)
522
+ or (all(m["line"].through for m in members) and not touched)
523
+ ),
524
+ "wire": "through" in kinds
525
+ or len(outer) != 2 # a ring, or a line joined at a branch point
526
+ or not (any(m["line"].resonator for m in members) or free),
527
+ }
528
+ chain_info.append(info)
529
+ if info["wire"] and extra and info["length"] > 0: # a wire through line(s): its routes and lines extend
530
+ label = "+".join(m["line"].name for m in members) # a resonator on its conductor (see _tap_extra)
531
+ wire_on[label], wire_len[label] = members[0]["node"], info["length"]
532
+
533
+ # a resonator route on a conductor that wires (cpw routes) extend away from any port, feedline or qubit island,
534
+ # e.g. a readout drawn as claw → straight → splitter → shorted tail: the wires are part of the resonator line
535
+ tap_extra = _tap_extra(resonators, uf, nodes, kind_of, wire_on, wire_len)
536
+ for rname, (a, far, route, rp, length, far_specs) in resonators:
537
+ a_um, b_um = rp.params.get("a", pdk.cpw_a), rp.params.get("b", pdk.cpw_b)
538
+ extra_wires = tap_extra.get(rname)
539
+ if extra_wires:
540
+ length = (length or 0.0) + sum(extra_wires.values())
541
+ if far_specs: # free / hanger end(s); a port end is the coupler (open) end
542
+ ends_t = [_end_term(sp) for sp in far_specs] + ["open"] * (2 - len(far_specs))
543
+ kind = "lambda/4" if ends_t.count("short") == 1 else "lambda/2"
544
+ else: # a meander port ↔ port: a λ/2 bus joining both ends
545
+ kind = "lambda/2"
546
+ uf.union(a, far)
547
+ value, tl = tl_value(kind, length, a_um, b_um)
548
+ if extra_wires:
549
+ value["extra_length_um"] = round(sum(extra_wires.values()), 3)
550
+ value["source"] = f"layout: {rname} + the wire route(s) {sorted(extra_wires)} on its conductor"
551
+ notes.append(
552
+ f"{rname}: one {kind} line of {length:.0f} µm = route + {sorted(extra_wires)} (the wires join it to "
553
+ "its coupler end; any other branch on that conductor is a tap, not modelled as a separate line)"
554
+ )
555
+ if len(far_specs) == 2:
556
+ notes.append(f"{rname}: no port at either end ({' / '.join(ends_t)}): a {kind} line on its own conductor")
557
+ elements.append(Element(rname, "TLres", (a, "gnd"), value, {"param": f"{rname}.length"}))
558
+ if route.length:
559
+ knobs[f"{rname}.length"] = (round(route.length * 0.8, 1), round(route.length * 1.25, 1))
560
+ hangers_ = [sp for sp in far_specs if isinstance(sp, HangerEnd)]
561
+ for i, h in enumerate(hangers_):
562
+ fl_node = ensure_feedline(h.hanger)
563
+ elements.append(
564
+ hanger_element(
565
+ f"K_{rname}" + (f"_{i}" if i else ""),
566
+ a,
567
+ fl_node,
568
+ h.length,
569
+ facing_gap(h, rname),
570
+ h.end,
571
+ tl,
572
+ kind,
573
+ f"{rname}.coupler_length",
574
+ )
575
+ )
576
+
577
+ def route_len(r: str) -> float:
578
+ return plan.routes[r].length or design.routes[r].length or 0.0
579
+
580
+ for info in chain_info:
581
+ members, kinds = info["members"], info["kinds"]
582
+ if info["zero"]: # terminations / pass-through sections only, nothing on them
583
+ st = members[0]
584
+ line, inst = st["line"], st["inst"]
585
+ if all(m["line"].through for m in members): # a lone taper: its unterminated ends join the ground plane
586
+ for m in members:
587
+ uf.union("gnd", m["node"])
588
+ notes.append(
589
+ f"{'+'.join(m['line'].name for m in members)}: pass-through section with nothing joined (ground)"
590
+ )
591
+ elif (
592
+ len(members) == 1
593
+ and _is_termination(line)
594
+ and not any(f"{inst}.{p}" in used_ports or f"{inst}.{p}" in snapped for p in line.ports if p)
595
+ ):
596
+ notes.append(f"{line.name}: termination with nothing joined (no element; its port maps to ground)")
597
+ for p in line.ports:
598
+ if p:
599
+ port_map[f"{inst}.{p}"] = "gnd" # no conductor of its own (an end condition only)
600
+ continue # zero length: nothing to model on its own
601
+ if info["wire"]:
602
+ for m in members:
603
+ lname = m["line"].name
604
+ if m["line"].resonator:
605
+ notes.append(f"{lname}: resonator line with an end on a port/feedline, modelled as a wire")
606
+ for ename, *_ in m["ext"]:
607
+ notes.append(f"{ename}: {lname} is a wire here, so its coupled section is not a hanger (dropped)")
608
+ for rname, *_ in m["hangers"]:
609
+ notes.append(f"K_{rname}: {lname} is a wire here, so the hanger of {rname} is dropped")
610
+ continue # a wire: its ports are one conductor already
611
+ shorts = kinds.count("short")
612
+ kind = "lambda/4" if shorts == 1 else "lambda/2"
613
+ length = info["length"]
614
+ routes = list(dict.fromkeys(r for m in members for r in m["routes"]))
615
+ named = [m for m in members if not (m["line"].through or _is_termination(m["line"]))]
616
+ main = max(named, key=lambda m: (m["line"].resonator, m["length"])) if named else None
617
+ if main:
618
+ ename, knob, a_um, b_um = main["line"].name, main["line"].knob, main["line"].a_um, main["line"].b_um
619
+ elif routes: # terminations / pass-through sections only: the route is the line (one to a hanger or free end)
620
+ ends_ = [r for m in members for r, *_ in m["hangers"]] + [r for m in members for r in m["free_routes"]]
621
+ ename = ends_[0] if ends_ else max(routes, key=route_len)
622
+ knob = f"{ename}.length"
623
+ rpp = plan.routes[ename].params
624
+ a_um, b_um = rpp.get("a", pdk.cpw_a), rpp.get("b", pdk.cpw_b)
625
+ else:
626
+ m0 = members[0]["line"]
627
+ ename, knob, a_um, b_um = m0.name, m0.knob, m0.a_um, m0.b_um
628
+ value, tl = tl_value(kind, length, a_um, b_um)
629
+ if not main and routes and length - route_len(ename) > 1e-6: # fill() rebuilds f from route + extra
630
+ value["extra_length_um"] = round(length - route_len(ename), 3)
631
+ names_ = [m["line"].name for m in members]
632
+ # one line, possibly ended by terminations wired / snapped / drawn on it (no route between them)
633
+ plain = main and all(m is main or (_is_termination(m["line"]) and not m["extra"]) for m in members)
634
+ if plain:
635
+ extra = info["extra"]
636
+ value["source"] = "layout (component line)" + (f" + {extra:.0f} µm of routes" if extra else "")
637
+ elif len(members) == 1 and len(routes) == 1 and _is_termination(members[0]["line"]):
638
+ value["source"] = f"layout: route {ename} ending in {names_[0]}"
639
+ else:
640
+ value["source"] = "layout: " + " + ".join(names_) + (f" + route(s) {', '.join(routes)}" if routes else "")
641
+ through = [m["line"].name for m in members if m["line"].through]
642
+ notes.append(
643
+ f"{ename}: one {kind} line of {length:.0f} µm through {names_}"
644
+ + (f" and route(s) {routes}" if routes else "")
645
+ + (
646
+ f"; pass-through section(s) {through} enter by (equivalent) length only, the width step is not "
647
+ f"modelled (one Z0, a/b {a_um:g}/{b_um:g} µm)"
648
+ if through
649
+ else ""
650
+ )
651
+ )
652
+ node = (main or members[0])["node"]
653
+ elements.append(Element(ename, "TLres", (node, "gnd"), value, {"param": knob} if knob else None))
654
+ for m in members:
655
+ line, inst = m["line"], m["inst"]
656
+ if not m["ext"] and any(h["line"] == line.name for h in ext_hangers.get(inst, [])):
657
+ notes.append(
658
+ f"{line.name}: its coupler section runs next to a conductor no port carries; declare "
659
+ f"d.couple('K_{line.name}', '{inst}', '<feedline instance>') for the hanger κ"
660
+ )
661
+ for hname, other, spec, cnote in m["ext"]:
662
+ el = hanger_element(
663
+ hname,
664
+ node,
665
+ other,
666
+ spec["coupling_length_um"],
667
+ spec["ground_gap_um"],
668
+ spec.get("end", "short"),
669
+ tl,
670
+ kind,
671
+ None,
672
+ )
673
+ if spec.get("source"):
674
+ el.value["estimate_source"] += f"; {spec['source']}"
675
+ el.note = cnote or (
676
+ f"{line.name}: coupled section next to a conductor no port carries (declared coupling)"
677
+ )
678
+ elements.append(el)
679
+ for i, c in enumerate(line.couplings):
680
+ elements.append(
681
+ hanger_element(
682
+ f"K_{line.name}" + (f"_{i}" if i else ""),
683
+ node,
684
+ glob(inst, c["node"]),
685
+ c["coupling_length_um"],
686
+ c["ground_gap_um"],
687
+ "short" if shorts else "open",
688
+ tl,
689
+ kind,
690
+ None,
691
+ )
692
+ )
693
+ for rname, h, fl in m["hangers"]:
694
+ elements.append(
695
+ hanger_element(
696
+ f"K_{rname}",
697
+ node,
698
+ ensure_feedline(fl),
699
+ h.length,
700
+ facing_gap(h, rname),
701
+ h.end,
702
+ tl,
703
+ kind,
704
+ f"{rname}.coupler_length",
705
+ )
706
+ )
707
+
708
+ # ground straps (airbridges): with no port on them joined they land on the ground plane on both sides
709
+ grounded = []
710
+ for g in straps:
711
+ on = [p for p, n in port_map.items() if n == g]
712
+ if uf.find(g) != uf.find("gnd") and not any(p in used_ports or p in snapped for p in on):
713
+ uf.union("gnd", g)
714
+ grounded.append(g.rsplit(".", 1)[0])
715
+ if grounded:
716
+ shown = ", ".join(grounded[:6]) + (f", … ({len(grounded)} in all)" if len(grounded) > 6 else "")
717
+ notes.append(f"airbridge(s) with no port joined are ground straps (ports → gnd, no element): {shown}")
718
+
719
+ # resolve conductors → circuit nodes
720
+ classes: dict[str, list[str]] = {}
721
+ for n in list(nodes) + ["gnd"]:
722
+ classes.setdefault(uf.find(n), []).append(n)
723
+ names: dict[str, str] = {}
724
+ for root, members in classes.items():
725
+ if uf.find("gnd") == root:
726
+ for m in members:
727
+ names[m] = "gnd"
728
+ continue
729
+ routes_ = [m.split(":", 1)[1] for m in members if m.startswith("route:")]
730
+ prefer = [m for m in members if kind_of.get(m) == "qubit"] or [
731
+ m for m in members if kind_of.get(m) == "coupler"
732
+ ]
733
+ names_ = routes_ or prefer or sorted(members)
734
+ nm = names_[0]
735
+ for m in members:
736
+ names[m] = nm
737
+ out_nodes: dict[str, dict] = {"gnd": {"ground": True}}
738
+ for members in classes.values():
739
+ nm = names[members[0]]
740
+ if nm == "gnd":
741
+ continue
742
+ islands = [nodes[m]["island"] for m in members if nodes.get(m, {}).get("island")]
743
+ if any(m.startswith("route:") for m in members):
744
+ islands = [nm, *islands]
745
+ layout = {"island": islands[0]} if islands else {}
746
+ if len(islands) > 1:
747
+ layout["aliases"] = islands[1:]
748
+ out_nodes[nm] = {"layout": layout}
749
+
750
+ branches: dict[str, dict] = {}
751
+ for e in elements:
752
+ n1, n2 = (names.get(n, n) for n in e.nodes)
753
+ if n1 == n2:
754
+ notes.append(f"{e.name}: both ends on {n1} after merging conductors (dropped)")
755
+ continue
756
+ branches[e.name] = {"type": e.type, "nodes": [n1, n2], "value": e.value, **({"knob": e.knob} if e.knob else {})}
757
+ for port, n in list(port_map.items()):
758
+ port_map[port] = names.get(n, n)
759
+ referenced = {n for b in branches.values() for n in b["nodes"]}
760
+ for nm in [n for n in out_nodes if n != "gnd" and n not in referenced]:
761
+ notes.append(f"node {nm} has no elements (dropped)")
762
+ del out_nodes[nm]
763
+ # sub-circuits with no element path to ground (e.g. a lone junction or capacitor that nothing connects to)
764
+ # cannot be part of the lumped circuit: drop them with a note instead of failing the whole build
765
+ reached, changed = {"gnd"}, True
766
+ while changed:
767
+ changed = False
768
+ for b in branches.values():
769
+ n1, n2 = b["nodes"]
770
+ if (n1 in reached) != (n2 in reached):
771
+ reached |= {n1, n2}
772
+ changed = True
773
+ floating = sorted(set(out_nodes) - reached)
774
+ if floating:
775
+ dropped = [bn for bn, b in branches.items() if b["nodes"][0] in floating or b["nodes"][1] in floating]
776
+ notes.append(f"node(s) {floating} have no path to ground; dropped with their elements {dropped}")
777
+ for bn in dropped:
778
+ del branches[bn]
779
+ for nm in floating:
780
+ del out_nodes[nm]
781
+
782
+ targets = {}
783
+ for inst, tgt in design.targets.items():
784
+ for q, v in tgt.items():
785
+ targets[f"{inst}.{q}"] = {"value": v, "tol": DEFAULT_TOL.get(q, abs(v) * 0.01)}
786
+ unconnected = sorted(
787
+ p
788
+ for p, n in port_map.items()
789
+ if p not in used_ports
790
+ and not n.startswith("control:")
791
+ and p.rsplit(".", 1)[1] not in ("squid_a", "squid_b") # junction ends: not connection ports
792
+ and p.split(".", 1)[0] in chosen
793
+ and not _snapped(design, p)
794
+ )
795
+ model = CircuitModel.model_validate(
796
+ {
797
+ "name": name or f"{design.name}_lom",
798
+ "design": design.name,
799
+ "nodes": out_nodes,
800
+ "branches": branches,
801
+ "knobs": knobs,
802
+ "targets": targets,
803
+ "controls": controls,
804
+ }
805
+ )
806
+ return LomBuild(model, notes, port_map, unconnected)
807
+
808
+
809
+ def _hanger_coupling(c, ends, ext_hangers, line_of, glob):
810
+ """(line state, hanger spec, other node) when coupling ``c`` (no value) joins a component that declares a
811
+ coupled section to an outside conductor (``Fragment.hangers``) to that conductor; else None."""
812
+ for i, end in enumerate(c.between):
813
+ inst, _, rest = end.partition(".")
814
+ for spec in ext_hangers.get(inst, []):
815
+ st = line_of.get((inst, spec["line"]))
816
+ if st is None or (rest and glob(inst, rest) != st["node"]):
817
+ continue
818
+ other = ends[1 - i]
819
+ if other != st["node"]:
820
+ return st, spec, other
821
+ return None
822
+
823
+
824
+ def _tap_extra(resonators, uf, nodes, kind_of, route_conductor, wire_length) -> dict[str, dict[str, float]]:
825
+ """{resonator route: {wire route: length}} for resonator routes (to a free end or hanger) that start on a
826
+ conductor which cpw wires extend, when that conductor has no port, feedline or qubit island and carries only
827
+ this one resonator."""
828
+ members: dict[str, list[str]] = {}
829
+ for n in nodes:
830
+ members.setdefault(uf.find(n), []).append(n)
831
+ per_root: dict[str, list[str]] = {}
832
+ for rname, (a, far, *_rest) in resonators:
833
+ if far.startswith("hanger:") or far in ("gnd", "open"):
834
+ per_root.setdefault(uf.find(a), []).append(rname)
835
+ out = {}
836
+ for root, rnames in per_root.items():
837
+ if len(rnames) != 1 or root == uf.find("gnd"):
838
+ continue
839
+ if any(kind_of.get(m) in ("pad", "feedline", "qubit") for m in members.get(root, [])):
840
+ continue
841
+ wires = {w: wire_length[w] for w, n in route_conductor.items() if w in wire_length and uf.find(n) == root}
842
+ if any(wires.values()):
843
+ out[rnames[0]] = wires
844
+ return out
845
+
846
+
847
+ def _end_term(spec) -> str:
848
+ """``"short"`` / ``"open"`` of a route end that is not a port (a hanger's termination, a free end's ``term``)."""
849
+ if hasattr(spec, "hanger"):
850
+ return "short" if spec.end == "short" else "open"
851
+ return "short" if spec.term == 0 else "open"
852
+
853
+
854
+ def _join(st, i, other, j) -> None:
855
+ """Join end ``i`` of line state ``st`` to end ``j`` of ``other``: one line through both."""
856
+ st["state"][i] = other["state"][j] = "joined"
857
+ st["peer"][i], other["peer"][j] = (other, j), (st, i)
858
+
859
+
860
+ def _port_distance(plan, inst: str, ports) -> float:
861
+ """Straight distance (µm) between an instance's two line ports in the plan (0 if one is missing)."""
862
+ placed = plan.instances.get(inst)
863
+ pts = [placed.ports[p].pos for p in ports if p and placed and p in placed.ports]
864
+ return (pts[0] - pts[1]).length() if len(pts) == 2 else 0.0
865
+
866
+
867
+ def _is_termination(line) -> bool:
868
+ """A zero-length line with one port (CpweOpenEnd, Metal OpenToGround / ShortToGround): only an end condition."""
869
+ return line.length_um <= 0 and sum(1 for p in line.ports if p) == 1
870
+
871
+
872
+ def _ends_on_terminations(plan, design, line_states, terms, joined, tol=1.0) -> dict[str, tuple[str, float]]:
873
+ """{line-end port: (termination port, distance µm)} for unjoined line ends (no wire, snap or route) that lie on
874
+ the drawn body of an unjoined termination: the body runs ``length`` (cell parameter; else the gap) from the
875
+ termination's port against its direction, ``a/2 + b`` to each side (± ``tol``). Each termination ends one line
876
+ (the nearest end)."""
877
+ free_terms = {}
878
+ for tport, (tst, _idx) in terms.items():
879
+ if tport in joined or tst["routes"]:
880
+ continue
881
+ inst, _, pname = tport.partition(".")
882
+ placed = plan.instances.get(inst)
883
+ port = placed.ports.get(pname) if placed else None
884
+ if port is None or port.dir is None:
885
+ continue
886
+ line = tst["line"]
887
+ try:
888
+ depth = float(design.instances[inst].params.get("length", line.b_um))
889
+ except (TypeError, ValueError):
890
+ depth = line.b_um
891
+ free_terms[tport] = (port, depth, line.a_um / 2 + line.b_um)
892
+ if not free_terms:
893
+ return {}
894
+ best: dict[str, tuple[str, float]] = {}
895
+ for st in line_states:
896
+ line = st["line"]
897
+ if _is_termination(line):
898
+ continue
899
+ for i, pname in enumerate(line.ports):
900
+ ref = f"{st['inst']}.{pname}" if pname else None
901
+ if ref is None or ref in joined or st["state"][i] is not None:
902
+ continue
903
+ placed = plan.instances.get(st["inst"])
904
+ port = placed.ports.get(pname) if placed else None
905
+ if port is None:
906
+ continue
907
+ for tport, (tp, depth, half) in free_terms.items():
908
+ v = port.pos - tp.pos
909
+ along = -(v.x * tp.dir.x + v.y * tp.dir.y)
910
+ across = abs(v.x * tp.dir.y - v.y * tp.dir.x)
911
+ if -tol <= along <= depth + tol and across <= half + tol:
912
+ dist = v.length()
913
+ if tport not in best or dist < best[tport][1]:
914
+ best[tport] = (ref, dist)
915
+ return {ref: (tport, dist) for tport, (ref, dist) in best.items()}
916
+
917
+
918
+ def _snapped(design, port: str) -> bool:
919
+ return _snap_partner(design, port) is not None
920
+
921
+
922
+ def _snap_partner(design, port: str) -> str | None:
923
+ """The port that ``port`` is snapped to (either side of a snap placement), or None."""
924
+ for name, other in design.instances.items():
925
+ pl = other.place
926
+ if pl.snap and pl.to:
927
+ snap = pl.snap if "." in pl.snap else f"{name}.{pl.snap}"
928
+ if port == snap:
929
+ return pl.to
930
+ if port == pl.to:
931
+ return snap
932
+ return None