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,991 @@
1
+ """The KLayout plugin's Simulate / Results / Fab steps as library functions (the CLI and the plugin call these).
2
+
3
+ * **Subset** (:func:`resolve_selection`, :func:`plan_subset_groups`): for a capacitance analysis (Q3D) the qubits
4
+ among the components selected in KLayout (a selected readout route names its qubit), each with its couplers; the
5
+ resonators are cut to a short stub port (:mod:`quantcore_circuits.sim_tools.subset`). For an eigenmode / driven
6
+ analysis :func:`selection_group`: exactly what is selected (qubit, resonator, feedline, pads), plus the routes that
7
+ join two selected parts and the pads at the ends of a selected line; junctions are lumped L‖C ports, lines leaving
8
+ the box end in 50 Ω. Nothing selected: ``default`` takes the first qubit with a readout; ``whole`` the built-in
9
+ ``chip`` group (slow).
10
+ * **Solver settings**: :func:`solver_settings` (fast / accurate / custom), passed to the export; after a solve
11
+ :func:`convergence_feedback` reads AEDT's convergence table and proposes the next run's passes / criterion
12
+ (``build/<name>/convergence.json``, which the plugin's Simulate dialog offers).
13
+ * **Automatic** (:func:`run_auto`, ``qcc sim auto``): subset → export → solve in a *new* non-graphical AEDT (never the
14
+ user's open one) → ``loop.analyse`` → the dashboard run state that the plugin's Results tab reads. Progress goes to a
15
+ small status file the plugin polls.
16
+ * **Manual** (:func:`export_manual`, ``qcc sim subset``): the job folder plus a README that says what to run and what to
17
+ bring back; :func:`import_results` (``qcc results import``) reads a solved job folder or a ``results.json`` back.
18
+ * **Tune** (:func:`propose`, :func:`apply_knobs`; ``qcc results propose`` / ``apply``): ``loop.feedback`` as a
19
+ preview of old → new knob values, and the design with those knobs set.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import tempfile
27
+ import time
28
+ from datetime import UTC, datetime
29
+ from pathlib import Path
30
+
31
+ RESULTS_FORMAT = """\
32
+ results/results.json (what `qcc results import` reads; every key except "analysis" is optional)
33
+
34
+ {
35
+ "analysis": "q3d_cmatrix", # q3d_cmatrix | hfss_eigenmode | eigenmode_epr | hfss_driven | ...
36
+ "group": "gui_sim", # the sim group the job simulated (default: the job.json's, else "chip")
37
+ "cmatrix": { # capacitance matrix, MAXWELL form, one row / column per metal net
38
+ "labels": ["Q1.island", "Q1.claw_n", "FL"], # net names: <instance>.island, <instance>.<port>, or a route name
39
+ "unit": "fF",
40
+ "matrix": [[ 85.2, -4.1, -1.2], # positive diagonal, non-positive off-diagonal; ground = the rest
41
+ [ -4.1, 22.0, -0.3],
42
+ [ -1.2, -0.3, 310.0]]
43
+ },
44
+ "eigenmodes": [ # linear modes of an eigenmode run (GHz; Q optional)
45
+ {"mode": 1, "f_GHz": 5.31, "Q": 1.2e6},
46
+ {"mode": 2, "f_GHz": 7.04, "Q": 4.0e4}
47
+ ]
48
+ }
49
+
50
+ The labels must be the net names of the design's circuit (`qcc results template DESIGN` writes them, with a zero
51
+ matrix, as a starting point). Row / column order is yours. Matrices in "mutual" form (positive off-diagonals) are
52
+ converted. A whole solved job folder works too: `qcc results import DESIGN JOB_FOLDER` (it collects the raw AEDT
53
+ outputs itself when results/results.json is missing).
54
+ """
55
+
56
+
57
+ # ---- helpers ------------------------------------------------------------------------------------------------------
58
+ def now() -> str:
59
+ return datetime.now(UTC).isoformat(timespec="seconds")
60
+
61
+
62
+ def _json_path(design) -> Path:
63
+ path = Path(design)
64
+ if path.suffix != ".json":
65
+ raise ValueError(f"{path.name}: the GUI flow needs the design as a .json file (qcc design to-python writes .py)")
66
+ return path
67
+
68
+
69
+ def jobs_root(design) -> Path:
70
+ """``<design folder>/build/jobs``."""
71
+ return Path(design).resolve().parent / "build" / "jobs"
72
+
73
+
74
+ AEDT_PATH_LIMIT = 250 # AEDT's own folders add name + ~70 characters to the job folder path (Windows MAX_PATH is 259)
75
+
76
+
77
+ def aedt_path_too_long(job_dir, analysis: str = "q3d_cmatrix") -> bool:
78
+ """AEDT fails with "Failed to copy local file ... The system cannot find the path specified" when the project's
79
+ ``*.aedtresults`` folders pass Windows' 260-character limit; the job folder name is repeated in them."""
80
+ name = Path(job_dir).name
81
+ return os.name == "nt" and len(str(Path(job_dir).resolve())) + len(name) + 75 > AEDT_PATH_LIMIT
82
+
83
+
84
+ def short_job_dir(design, group: str, analysis: str) -> Path:
85
+ """The job folder: ``<design folder>/build/jobs/<design>_<group>_<analysis>``, or, when that path is too long for
86
+ AEDT, a short one under the temp folder (``qcc_jobs/<design>_<group>_<analysis>``)."""
87
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
88
+
89
+ name = f"{load_design(design).name}_{group}_{analysis}"
90
+ job = jobs_root(design) / name
91
+ if aedt_path_too_long(job, analysis):
92
+ job = Path(tempfile.gettempdir()) / "qcc_jobs" / name
93
+ return job
94
+
95
+
96
+ def run_dir(design) -> Path:
97
+ """``<design folder>/build/<name>``: where the GUI flow keeps its run (the sidecar finds ``state.json`` there)."""
98
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
99
+
100
+ return Path(design).resolve().parent / "build" / load_design(design).name
101
+
102
+
103
+ # ---- the subset -----------------------------------------------------------------------------------------------------
104
+ def _by_selection(design, names, analysis: str) -> bool: # noqa: ARG001 (design: kept for a later rule)
105
+ """Whether ``names`` are simulated as they are (:func:`selection_group`): eigenmode / driven runs. A capacitance
106
+ run is the qubit subset (:func:`plan_subset_groups`)."""
107
+ from quantcore_circuits.sim_tools.builder import analysis_kind # pylint: disable=import-outside-toplevel
108
+
109
+ return analysis_kind(analysis) in ("eigenmode", "driven")
110
+
111
+
112
+ def junctions(design, names=None) -> dict[str, dict]:
113
+ """The resolved junction of each component that has one (``names``: only those): the sidecar's
114
+ ``instances.<name>.junction`` — ``{"kind", "Lj0_nH", "Cj_fF", "flux_phi0", "asym", "Lj_eff_nH", "source"}`` (the
115
+ LOM's values, which the eigenmode / driven exports put on the lumped sheet)."""
116
+ from quantcore_circuits.assembly.sidecar import instance_junction_entry # pylint: disable=import-outside-toplevel
117
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
118
+ from quantcore_circuits.pdk import get_pdk # pylint: disable=import-outside-toplevel
119
+
120
+ d = load_design(design)
121
+ pdk = get_pdk(d.pdk)
122
+ out = {}
123
+ for n in d.instances if names is None else [n for n in names if n in d.instances]:
124
+ entry = instance_junction_entry(n, d.instances[n], pdk)
125
+ if entry is not None:
126
+ out[n] = entry
127
+ return out
128
+
129
+
130
+ def missing_junctions(design, names=None) -> dict[str, str]:
131
+ """``{name: message}``: the components among ``names`` (None: all) whose junction has no L_J for an eigenmode /
132
+ driven run (no design value and no drawn trilayer junction, or a symmetric SQUID at Φ = ½); the message says where
133
+ to set it (the plugin's pre-check; ``qcc design junctions``)."""
134
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
135
+ from quantcore_circuits.lom.fragment import missing_junction_message # pylint: disable=import-outside-toplevel
136
+
137
+ d = load_design(design)
138
+ return {n: missing_junction_message(n, d.instances[n]) if "error" not in j else f"{n}: {j['error']}"
139
+ for n, j in junctions(d, names).items() if j.get("Lj_eff_nH") is None}
140
+
141
+
142
+ def placement_junction(cell: str, params: dict | None = None, pdk=None) -> dict | None:
143
+ """The simulation / LOM junction a new ``cell`` gets when it is placed: ``{"Lj_nH", "Cj_fF", "source"}``, or None
144
+ for a component without a junction, plus ``drawn``: the trilayer junction the cell draws (same keys), or None. A
145
+ drawn trilayer junction gives its PDK-rule value (also a KQC cell left at its default junction: the build draws it
146
+ as the PDK trilayer); a chosen non-trilayer type (KQC Manhattan, Sim, ...) has no PDK value, so it gets the PDK
147
+ nominal SQUID (``"Quantcore Squid"``). The plugin writes
148
+ it into ``design.json`` at placement (the value is a simulation value, fixed per component)."""
149
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
150
+ from quantcore_circuits.lom.fragment import ( # pylint: disable=import-outside-toplevel
151
+ cell_params,
152
+ drawn_junction,
153
+ instance_junction,
154
+ )
155
+
156
+ d = load_design({"name": "placement", **({"pdk": pdk} if pdk else {}),
157
+ "instances": {"X": {"cell": cell, "place": {"at": [0, 0]}, "params": dict(params or {})}}})
158
+ ej = instance_junction("X", d.instances["X"], d.pdk)
159
+ if ej is None or ej.kind is None:
160
+ return None
161
+ shown = drawn_junction(cell_params(d.instances["X"]), getattr(d.pdk, "junction", None))
162
+ drawn = None if shown is None else {"Lj_nH": float(shown[0]), "Cj_fF": float(shown[1]), "source": shown[2]}
163
+ if ej.lj0_nH is not None:
164
+ return {"Lj_nH": float(ej.lj0_nH), "Cj_fF": float(ej.cj_fF), "source": "drawn trilayer junction, PDK rule",
165
+ "drawn": drawn}
166
+ nominal = drawn_junction({"junction_type": "Quantcore Squid"})
167
+ if nominal is None:
168
+ return None
169
+ return {"Lj_nH": float(nominal[0]), "Cj_fF": float(nominal[1]), "source": "PDK nominal SQUID", "drawn": drawn}
170
+
171
+
172
+ def resolve_selection(design, names, default: bool = False) -> tuple[list[str], list[str]]:
173
+ """``(qubits, notes)`` from ``names`` (instance and route names, e.g. what is selected in KLayout). A qubit stands for
174
+ itself, a readout route for its qubit; pads, couplers and other lines come in with their qubit and are ignored.
175
+ ``default``: with no qubit in ``names``, the first qubit that has a readout resonator."""
176
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
177
+ from quantcore_circuits.sim_tools.subset import has_junction, readout_of # pylint: disable=import-outside-toplevel
178
+
179
+ d = load_design(design)
180
+ qubits_all = sorted((n for n in d.instances if has_junction(d, n)), key=_natural)
181
+ chosen, notes = [], []
182
+ for n in names:
183
+ if n in d.instances and n in qubits_all:
184
+ chosen.append(n)
185
+ elif n in d.routes:
186
+ owner = next((q for q in qubits_all if readout_of(d, q) == n), None)
187
+ if owner:
188
+ chosen.append(owner)
189
+ else:
190
+ notes.append(f"{n}: not a readout line of a qubit; it comes in with its qubit if it needs to")
191
+ elif n in d.instances:
192
+ notes.append(f"{n}: not a qubit; it comes in with its qubit if it needs to")
193
+ else:
194
+ notes.append(f"{n}: not in the design")
195
+ chosen = list(dict.fromkeys(chosen))
196
+ if not chosen and default:
197
+ with_ro = [q for q in qubits_all if readout_of(d, q)]
198
+ pick = (with_ro or qubits_all)[:1]
199
+ if pick:
200
+ notes.append(f"default subset: {pick[0]} with its readout")
201
+ chosen = pick
202
+ return chosen, notes
203
+
204
+
205
+ def _natural(name: str):
206
+ import re # pylint: disable=import-outside-toplevel
207
+
208
+ return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", name)]
209
+
210
+
211
+ def plan_subset_groups(design, qubits, name: str = "gui_sim", margin_um: float = 300.0, analysis: str = "q3d_cmatrix",
212
+ split: str = "auto"):
213
+ """``(group names, {group: spec dict}, SubsetGroup plan)`` for ``qubits``; the design file is not changed."""
214
+ from quantcore_circuits.designer import Designer # pylint: disable=import-outside-toplevel
215
+
216
+ d = Designer.load(design, autosave=False)
217
+ names = d.sim_subset(name, qubits=list(qubits), margin_um=margin_um, analyses=[analysis], split=split)
218
+ return names, {g: d.data["sim_groups"][g] for g in names}, d.subset_plan
219
+
220
+
221
+ def write_groups(design, specs: dict, prefix: str = "gui_sim") -> bool:
222
+ """Put the sim groups ``specs`` into the design.json (only that key is touched) and drop the earlier ``prefix``
223
+ groups that are not in ``specs``. Returns whether the file changed."""
224
+ path = _json_path(design)
225
+ data = json.loads(path.read_text(encoding="utf-8"))
226
+ groups = data.setdefault("sim_groups", {})
227
+ before = json.dumps(groups, sort_keys=True)
228
+ for g in [g for g in groups if (g == prefix or g.startswith(prefix + "_")) and g not in specs]:
229
+ del groups[g]
230
+ groups.update(specs)
231
+ if json.dumps(groups, sort_keys=True) == before:
232
+ return False
233
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
234
+ return True
235
+
236
+
237
+ def selection_group(design, names, analysis: str = "hfss_eigenmode", margin_um: float = 300.0) -> tuple[dict, list[str]]:
238
+ """The sim group of exactly the selected components (``names``: instances and routes) for ``analysis``: plus the
239
+ routes that join two selected parts (a hanger from a selected qubit onto a selected line counts) and the
240
+ instances at the ends of a selected route (a feedline's bond pads). Returns ``(spec, notes)``."""
241
+ from quantcore_circuits.design import load_design, split_port_ref # pylint: disable=import-outside-toplevel
242
+ from quantcore_circuits.design.schema import FreeEnd, HangerEnd # pylint: disable=import-outside-toplevel
243
+
244
+ d = load_design(design)
245
+ notes, sel = [], []
246
+ for n in names:
247
+ if n in d.instances or n in d.routes:
248
+ sel.append(n)
249
+ else:
250
+ notes.append(f"{n}: not in the design")
251
+ if not sel:
252
+ raise ValueError("nothing to simulate: select components (KLayout's select tool) or choose the whole chip")
253
+
254
+ def ends(route):
255
+ out = []
256
+ for e in (route.from_, route.to):
257
+ if isinstance(e, str):
258
+ out.append(split_port_ref(e)[0])
259
+ elif isinstance(e, HangerEnd):
260
+ out.append(e.hanger)
261
+ elif not isinstance(e, FreeEnd):
262
+ out.append(None)
263
+ return out
264
+
265
+ chosen = set(sel)
266
+ for rname, route in d.routes.items(): # routes joining selected parts
267
+ e = ends(route)
268
+ if rname not in chosen and e and all(x in chosen for x in e):
269
+ sel.append(rname)
270
+ chosen.add(rname)
271
+ notes.append(f"{rname}: joins {' and '.join(e)}, comes in")
272
+ for rname in [n for n in sel if n in d.routes]: # the instances at a selected route's ends (pads)
273
+ for x in ends(d.routes[rname]):
274
+ if x and x in d.instances and x not in chosen:
275
+ sel.append(x)
276
+ chosen.add(x)
277
+ notes.append(f"{x}: at an end of {rname}, comes in")
278
+ return {"select": sel, "margin_um": float(margin_um), "analyses": [analysis]}, notes
279
+
280
+
281
+ SOLVER_MODES = ("fast", "accurate", "custom")
282
+
283
+
284
+ def solver_settings(analysis: str, mode: str = "fast", custom: dict | None = None) -> tuple[bool, dict]:
285
+ """``(fast, settings)`` for the export: ``fast`` = :data:`~quantcore_circuits.sim_tools.export.FAST_SETTINGS`
286
+ (minutes, not converged), ``accurate`` = the analysis defaults (``DEFAULT_SETTINGS``), ``custom`` = the defaults
287
+ with ``custom`` on top (e.g. what :func:`convergence_feedback` proposed, or the plugin's Settings)."""
288
+ if mode not in SOLVER_MODES:
289
+ raise ValueError(f"solver mode {mode!r}: one of {', '.join(SOLVER_MODES)}")
290
+ if mode == "fast":
291
+ return True, {}
292
+ return False, dict(custom or {}) if mode == "custom" else {}
293
+
294
+
295
+ _CRITERION = {"q3d_cmatrix": "percent_error", "hfss_eigenmode": "max_delta_f", "eigenmode_epr": "max_delta_f",
296
+ "hfss_driven": "max_delta_s"}
297
+
298
+
299
+ def convergence_feedback(job_dir) -> dict:
300
+ """What AEDT's adaptive meshing did in a solved job and what the next run should use: ``{"analysis",
301
+ "converged", "passes", "last_delta", "target", "settings" (the job's), "next" (proposed settings, empty when it
302
+ converged), "message"}``. Not converged: one and a half times the passes (at least +4), and the criterion kept;
303
+ converged in fewer passes than allowed: the settings stay. Never raises (a job without a convergence table says
304
+ so)."""
305
+ from quantcore_circuits.analysis.results import collect_results, parse_convergence # noqa pylint: disable=C0415
306
+
307
+ job_dir = Path(job_dir)
308
+ try:
309
+ job = json.loads((job_dir / "job.json").read_text(encoding="utf-8"))
310
+ except (OSError, ValueError):
311
+ return {"converged": None, "next": {}, "message": f"{job_dir.name}: no job.json"}
312
+ analysis, settings = job.get("analysis", ""), dict(job.get("settings") or {})
313
+ tables = sorted(job_dir.glob("*_project_convergence.txt"))
314
+ try:
315
+ conv = parse_convergence(tables[0]) if tables else (collect_results(job_dir).get("convergence") or {})
316
+ except Exception as e: # noqa: BLE001
317
+ conv = {"error": f"{type(e).__name__}: {e}"}
318
+ passes = conv.get("passes") or []
319
+ deltas = [x for x in (conv.get("delta") or []) if x is not None]
320
+ key = _CRITERION.get(analysis)
321
+ out = {"analysis": analysis, "job": str(job_dir), "converged": conv.get("converged"), "passes": len(passes),
322
+ "last_delta": deltas[-1] if deltas else None, "target": conv.get("target") or settings.get(key),
323
+ "settings": settings, "next": {}}
324
+ if not passes:
325
+ out["message"] = f"{job_dir.name}: no convergence table (did the solve finish?)"
326
+ return out
327
+ if not conv.get("converged") and out["last_delta"] is not None and out["target"] is not None and out["last_delta"] <= float(out["target"]): # Q3D's table has no "Converged" line: Δ below the target
328
+ out["converged"] = conv["converged"] = True
329
+ if conv.get("converged"):
330
+ out["message"] = (f"converged in {len(passes)} passes (last Δ {out['last_delta']:.3g} vs "
331
+ f"{out['target']}): the settings stay")
332
+ return out
333
+ max_p = int(settings.get("maximum_passes") or len(passes))
334
+ nxt = {"maximum_passes": max(max_p + 4, int(round(max_p * 1.5)))}
335
+ if key and settings.get(key) is not None:
336
+ nxt[key] = settings[key]
337
+ out["next"] = nxt
338
+ last = f"{out['last_delta']:.3g}" if out["last_delta"] is not None else "?"
339
+ out["message"] = (f"NOT converged after {len(passes)} passes (last Δ {last} vs target {out['target']}): raise the "
340
+ f"maximum passes (e.g. {nxt['maximum_passes']}) in AEDT, solve there and import the job folder")
341
+ return out
342
+
343
+
344
+ def pick_groups(design, names=None, default: bool = False, whole: bool = False, name: str = "gui_sim",
345
+ margin_um: float = 300.0, analysis: str = "q3d_cmatrix", write: bool = True) -> dict:
346
+ """Decide what to simulate and (``write``) store the sim groups in the design.json. Returns ``{"groups": [...],
347
+ "whole": bool, "notes": [...], "describe": markdown}``."""
348
+ if whole:
349
+ return {"groups": ["chip"], "whole": True, "notes": ["the whole chip: slow and memory hungry"], "describe": ""}
350
+ if names and _by_selection(design, names, analysis):
351
+ spec, notes = selection_group(design, names, analysis, margin_um)
352
+ group = f"{name}_sel"
353
+ if write:
354
+ write_groups(design, {group: spec}, name)
355
+ return {"groups": [group], "whole": False, "notes": notes, "specs": {group: spec},
356
+ "describe": "renders: " + ", ".join(spec["select"])}
357
+ qubits, notes = resolve_selection(design, names or [], default=default)
358
+ if not qubits:
359
+ raise ValueError("no qubit to simulate: a Q3D run is a qubit's islands and couplers; select a qubit, or choose "
360
+ "eigenmode for lines / resonators / pads (or the default subset / the whole chip)\n"
361
+ + "\n".join(notes))
362
+ groups, specs, plan = plan_subset_groups(design, qubits, name, margin_um, analysis)
363
+ if write:
364
+ write_groups(design, specs, name)
365
+ from quantcore_circuits.sim_tools.subset import describe # pylint: disable=import-outside-toplevel
366
+
367
+ notes += [n for sg in plan for n in sg.notes]
368
+ return {"groups": groups, "whole": False, "qubits": qubits, "notes": list(dict.fromkeys(notes)),
369
+ "describe": describe(plan)}
370
+
371
+
372
+ # ---- status file (the plugin polls it) --------------------------------------------------------------------------------
373
+ class Status:
374
+ """``{"state": running|done|failed, "step", "n", "of", "message", ...}`` written atomically."""
375
+
376
+ def __init__(self, path, steps: int = 4):
377
+ self.path = Path(path) if path else None
378
+ self.data = {"state": "running", "step": "starting", "n": 0, "of": steps, "message": "", "started": now()}
379
+ self.write()
380
+
381
+ def set(self, **kw) -> None:
382
+ self.data.update(kw)
383
+ self.write()
384
+
385
+ def step(self, n: int, name: str, message: str = "") -> None:
386
+ self.set(n=n, step=name, message=message)
387
+
388
+ def write(self) -> None:
389
+ if self.path is None:
390
+ return
391
+ self.path.parent.mkdir(parents=True, exist_ok=True)
392
+ tmp = self.path.with_suffix(".tmp")
393
+ tmp.write_text(json.dumps(self.data, indent=1), encoding="utf-8")
394
+ os.replace(tmp, self.path)
395
+
396
+
397
+ # ---- automatic -------------------------------------------------------------------------------------------------------
398
+ def run_auto(design, names=None, default: bool = False, whole: bool = False, analysis: str = "q3d_cmatrix",
399
+ name: str = "gui_sim", margin_um: float = 300.0, aedt: str | None = "batch", fast: bool = True,
400
+ timeout: float = 3600.0, status=None, progress: float = 10.0, readout: bool = True, say=print,
401
+ settings: dict | None = None) -> dict:
402
+ """Subset → export → solve in a new AEDT → analyse. Returns ``{"groups", "jobs", "seconds", "rows", "run_dir"}``;
403
+ raises on a failed step (the ``status`` file then says which)."""
404
+ from quantcore_circuits.circuit.consensus import report_markdown # pylint: disable=import-outside-toplevel
405
+ from quantcore_circuits.sim_tools import build_simulation, export_job, hfss # pylint: disable=C0415
406
+ from quantcore_circuits.sim_tools.ansys import find_ansys_executable # pylint: disable=import-outside-toplevel
407
+
408
+ st = status if isinstance(status, Status) else Status(status, steps=4)
409
+ t0 = time.time()
410
+ try:
411
+ design = _json_path(design).resolve()
412
+ if find_ansys_executable() is None:
413
+ raise RuntimeError("AEDT 2024 R1 or newer was not found (set QCC_ANSYS_EXECUTABLE); use Export sim job "
414
+ "and solve it on a machine that has AEDT")
415
+ st.step(1, "subset", "choosing what to simulate")
416
+ plan = pick_groups(design, names, default, whole, name, margin_um, analysis)
417
+ for n in plan["notes"]:
418
+ say(f"note: {n}")
419
+ groups = plan["groups"]
420
+ say(f"simulating {', '.join(groups)} ({analysis}, {'fast' if fast else 'full'} settings) in a new "
421
+ f"{'non-graphical ' if (aedt or 'batch') == 'batch' else ''}AEDT")
422
+ root = jobs_root(design)
423
+ jobs = []
424
+ for i, g in enumerate(groups):
425
+ st.step(2, "solve", f"{g} ({i + 1}/{len(groups)}): export, then solve in AEDT")
426
+ job_dir = short_job_dir(design, g, analysis)
427
+ if not str(job_dir).startswith(str(root)):
428
+ say(f"note: the design folder is too deep for AEDT (Windows paths over 260 characters); the job goes "
429
+ f"to {job_dir}")
430
+ if aedt_path_too_long(job_dir, analysis):
431
+ raise RuntimeError(f"the path {job_dir} is too long for AEDT; move the design to a shorter folder")
432
+ # export, check the geometry AEDT would get (touching nets, junction ports without a polygon, metal to the
433
+ # box top), and only then solve: a broken export stops here instead of after minutes in AEDT
434
+ setup = build_simulation(design, g, analysis)
435
+ export_job(setup, job_dir, overwrite=True, fast=fast, **(settings or {}))
436
+ check_export(job_dir, say)
437
+ r = hfss.solve_job(job_dir, aedt=aedt, timeout=timeout, progress=progress)
438
+ say(f"{g}: {'ok' if r.ok else 'FAILED'} in {r.seconds:.0f} s (log {r.log})")
439
+ fb = convergence_feedback(job_dir)
440
+ say(f"{g}: mesh {fb['message']}")
441
+ save_feedback(design, fb)
442
+ if not r.ok:
443
+ raise RuntimeError(f"the AEDT solve of {g} failed or timed out; see {r.log}")
444
+ jobs.append(job_dir)
445
+ out = analyse_jobs(design, jobs, st=st, readout=readout, source="auto", say=say)
446
+ out.update(groups=groups, seconds=round(time.time() - t0, 1))
447
+ st.set(state="done", n=4, step="done", message=out["summary"], finished=now(), rows=out["rows"])
448
+ say(report_markdown(out.pop("_rows"), "Consensus"))
449
+ return out
450
+ except BaseException as e: # noqa: BLE001
451
+ st.set(state="failed", message=f"{type(e).__name__}: {e}", finished=now())
452
+ raise
453
+
454
+
455
+ def check_export(job_dir, say=print, strict: bool = True) -> dict:
456
+ """:func:`~quantcore_circuits.sim_tools.geometry_check.check_job` on an exported job: warnings become notes; errors
457
+ (what AEDT would reject or solve wrongly) raise ``RuntimeError`` (``strict``) or are printed as warnings."""
458
+ from quantcore_circuits.sim_tools.geometry_check import check_job # pylint: disable=import-outside-toplevel
459
+
460
+ job_dir = Path(job_dir)
461
+ try:
462
+ rep = check_job(job_dir)
463
+ except Exception as e: # noqa: BLE001 (the check must never block on its own failure)
464
+ say(f"note: {job_dir.name}: geometry check skipped ({type(e).__name__}: {e})")
465
+ return {"errors": [], "warnings": []}
466
+ for w in rep["warnings"]:
467
+ say(f"note: {job_dir.name}: {w}")
468
+ if rep["errors"]:
469
+ text = "; ".join(rep["errors"][:6])
470
+ if strict:
471
+ raise RuntimeError(f"{job_dir.name}: the exported geometry would fail in AEDT, so nothing was solved: "
472
+ f"{text} (scripts/check_sim_export.py check \"{job_dir}\")")
473
+ for e in rep["errors"]:
474
+ say(f"warning: {job_dir.name}: {e}")
475
+ return rep
476
+
477
+
478
+ def save_feedback(design, feedback: dict) -> Path:
479
+ """``build/<name>/convergence.json``: the last solve's convergence and the proposed next settings, per analysis
480
+ (the plugin's Simulate dialog shows it and can use the proposal)."""
481
+ path = run_dir(design) / "convergence.json"
482
+ path.parent.mkdir(parents=True, exist_ok=True)
483
+ try:
484
+ data = json.loads(path.read_text(encoding="utf-8"))
485
+ except (OSError, ValueError):
486
+ data = {}
487
+ data[feedback.get("analysis") or "unknown"] = {**feedback, "when": now()}
488
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
489
+ return path
490
+
491
+
492
+ def analyse_jobs(design, jobs, st: Status | None = None, readout: bool = True, source: str = "auto", say=print) -> dict:
493
+ """``loop.analyse`` of the whole-chip circuit filled from ``jobs`` (subset jobs fill their own components, the rest
494
+ keeps the layout's estimates), recorded in ``<design>/build/<name>/state.json`` and ``flow.json``."""
495
+ from quantcore_circuits import loop # pylint: disable=import-outside-toplevel
496
+ from quantcore_circuits.design import design_hash, load_design # pylint: disable=import-outside-toplevel
497
+ from quantcore_circuits.track import Run # pylint: disable=import-outside-toplevel
498
+
499
+ if st:
500
+ st.step(3, "analyse", "extracting values, LOM and QuTiP, comparing with the targets")
501
+ rd = run_dir(design)
502
+ run = Run(design, rd)
503
+ jobs = [Path(j) for j in jobs]
504
+ an = loop.analyse(design, jobs if len(jobs) > 1 else jobs[0], "chip", run=run, readout=readout, out_dir=rd)
505
+ d = load_design(design)
506
+ rows = [{"param": r.param, "target": r.target, "tol": r.tol, "value": r.chosen, "by": r.chosen_by,
507
+ "status": r.status, "unit": r.unit} for r in an.rows if r.target is not None or r.chosen is not None]
508
+ record = {"schema": "qcc-flow/0.1", "when": now(), "source": source, "jobs": [str(j) for j in jobs],
509
+ "group": "chip", "design_hash": design_hash(d), "goal": an.goal.get("summary")}
510
+ (rd / "flow.json").write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
511
+ for note in an.filled.notes:
512
+ say(f"note: {note}")
513
+ saved = save_results_copies(design, jobs, say=say) if source == "auto" else []
514
+ return {"run_dir": str(rd), "jobs": [str(j) for j in jobs], "rows": rows, "summary": an.goal.get("summary", ""),
515
+ "_rows": an.rows, "results_files": [str(p) for p in saved]}
516
+
517
+
518
+ def save_results_copies(design, jobs, say=print) -> list[Path]:
519
+ """Keep what a solve returned under a name that says what it is: ``build/<name>/<name>_<group>_results.json`` (a
520
+ copy of the job's ``results/results.json``; the plugin's Simulate > Open results file… reads it back)."""
521
+ out = []
522
+ rd = run_dir(design)
523
+ for job in jobs:
524
+ job = Path(job)
525
+ src = job / "results" / "results.json"
526
+ if not src.exists():
527
+ continue
528
+ group = ""
529
+ for f in (job / "job.json", src):
530
+ try:
531
+ group = str(json.loads(f.read_text(encoding="utf-8")).get("group") or "")
532
+ except (OSError, ValueError):
533
+ group = ""
534
+ if group:
535
+ break
536
+ group = "".join(c if c.isalnum() or c in "-_." else "_" for c in (group or job.name))
537
+ dest = rd / f"{rd.name}_{group}_results.json"
538
+ try:
539
+ rd.mkdir(parents=True, exist_ok=True)
540
+ dest.write_bytes(src.read_bytes())
541
+ except OSError as e:
542
+ say(f"note: could not save {dest.name}: {e}")
543
+ continue
544
+ say(f"results saved: {dest}")
545
+ out.append(dest)
546
+ return out
547
+
548
+
549
+ def flow_record(design) -> dict | None:
550
+ """What the last automatic run / import analysed (``flow.json``), plus whether the design changed since."""
551
+ from quantcore_circuits.design import design_hash, load_design # pylint: disable=import-outside-toplevel
552
+
553
+ path = run_dir(design) / "flow.json"
554
+ if not path.exists():
555
+ return None
556
+ rec = json.loads(path.read_text(encoding="utf-8"))
557
+ rec["stale"] = rec.get("design_hash") != design_hash(load_design(design))
558
+ return rec
559
+
560
+
561
+ # ---- manual --------------------------------------------------------------------------------------------------------
562
+ README = """\
563
+ # Simulation job: {design} / {group} ({analysis})
564
+
565
+ Made by Quantcore (`qcc sim subset`) on {when}. The design is `{design}`, the box simulates: {select}.
566
+ Settings: {settings}.
567
+
568
+ ## Solve it
569
+
570
+ **On this machine, in AEDT {aedt}:**
571
+
572
+ 1. Double-click `simulation.bat` (Windows) or run `bash simulation.sh`. It starts a new non-graphical AEDT, solves
573
+ the job and writes `results/results.json`. (Or: `qcc hfss solve "{job}"`.)
574
+ 2. By hand: open AEDT, *Tools > Run Script...* and run `scripts/qcc_solve.py` with the argument
575
+ `{sim}.json` (the script is in the `scripts` folder; it imports the geometry, adds the ports, solves and
576
+ exports the results next to it). `scripts/qcc_render.py` does the same without solving: it saves the project so
577
+ you can look at the mesh and ports first.
578
+
579
+ **A finer solve:** open `{sim}_project.aedt` in AEDT, change the setup (passes, convergence, mesh), solve, then run
580
+ `scripts/qcc_collect.py` there (*Tools > Run Script...*, no arguments): it exports what you solved (results and the
581
+ convergence table) into this folder without solving again or saving. Or close the project and run
582
+ `qcc hfss collect "{job}"`. Then import the folder (below).
583
+
584
+ **On another machine:** copy this whole folder over, run `scripts/qcc_solve.py` in AEDT as above (AEDT 2024 R1 or newer;
585
+ quantcore-circuits is only needed for `simulation.bat`'s last line, the results collection), and bring the folder back.
586
+
587
+ ## Bring back
588
+
589
+ The whole job folder (you can leave out the `*.aedtresults` folders, they are large), or at least:
590
+
591
+ - `results/results.json` (written by `simulation.bat` / `qcc results collect`), or
592
+ - `{sim}_project_results.json`, `{sim}_project_qcc.json` and the `.eig` / `.sNp` files AEDT exported (then Quantcore
593
+ collects the results itself).
594
+
595
+ Then in KLayout: *Quantcore > Simulate > Import results...* and pick the folder or the `results.json`, or on the
596
+ command line: `qcc results import "{design_path}" "<folder or results.json>"`.
597
+
598
+ ## Your own results script
599
+
600
+ Any extraction that writes this JSON works (see `results_template.json` here for the net names of this job):
601
+
602
+ ```
603
+ {fmt}
604
+ ```
605
+ """
606
+
607
+
608
+ def export_manual(design, names=None, default: bool = False, whole: bool = False, out=None,
609
+ analysis: str = "q3d_cmatrix", name: str = "gui_sim", margin_um: float = 300.0, fast: bool = True,
610
+ write_group: bool = True, say=print, settings: dict | None = None,
611
+ group: str | None = None) -> list[Path]:
612
+ """Write the job folder(s) of the subset (no solve): KQC export, AEDT scripts, ``job.json``, ``README.md`` and
613
+ ``results_template.json``. ``out``: the folder for one box, or the parent of several. ``group``: a saved ``sim_groups``
614
+ entry, exported as it is (nothing is written to the design). Returns the job folders."""
615
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
616
+ from quantcore_circuits.sim_tools import build_simulation, export_job # pylint: disable=import-outside-toplevel
617
+ from quantcore_circuits.sim_tools.aedt_scripts import write_scripts # pylint: disable=import-outside-toplevel
618
+ from quantcore_circuits.sim_tools.ansys import find_ansys_executable # pylint: disable=import-outside-toplevel
619
+ from quantcore_circuits.sim_tools.export import tighter_or_equal # noqa: F401 pylint: disable=C0415
620
+
621
+ design = Path(design).resolve()
622
+ is_json = design.suffix == ".json"
623
+ d = load_design(design)
624
+ if group:
625
+ if group not in d.sim_groups:
626
+ raise ValueError(f"no sim group {group!r}; available: {sorted(d.sim_groups)}")
627
+ groups, source, notes = [group], d, []
628
+ elif whole:
629
+ groups, source = ["chip"], design
630
+ notes = ["the whole chip: slow and memory hungry"]
631
+ else:
632
+ if names and _by_selection(design, names, analysis):
633
+ spec, notes = selection_group(design, names, analysis, margin_um)
634
+ groups, specs = [f"{name}_sel"], {f"{name}_sel": spec}
635
+ else:
636
+ qubits, notes = resolve_selection(design, names or [], default=default)
637
+ if not qubits:
638
+ raise ValueError("no qubit to simulate: name a qubit (--instances Q1,R1), or use --default / --whole")
639
+ groups, specs, plan = plan_subset_groups(design, qubits, name, margin_um, analysis)
640
+ notes += [n for sg in plan for n in sg.notes]
641
+ if write_group and is_json:
642
+ write_groups(design, specs, name)
643
+ source = design
644
+ else: # a .py design, or no write: simulate an in-memory copy with the groups
645
+ data = d.to_json_dict()
646
+ data["sim_groups"].update(specs)
647
+ source = load_design(data)
648
+ jobs = []
649
+ for g in groups:
650
+ job = (Path(out) if out and len(groups) == 1 else (Path(out) if out else jobs_root(design)) /
651
+ f"{d.name}_{g}_{analysis}")
652
+ setup = build_simulation(source, g, analysis)
653
+ export_job(setup, job, overwrite=True, fast=fast, **(settings or {}))
654
+ write_scripts(job)
655
+ job = job.resolve()
656
+ check_export(job, say, strict=False)
657
+ meta = json.loads((job / "job.json").read_text(encoding="utf-8"))
658
+ exe = find_ansys_executable()
659
+ (job / "README.md").write_text(README.format(
660
+ design=d.name, design_path=design, group=g, analysis=analysis, when=now(), job=job,
661
+ select=", ".join(meta.get("select") or []) or "the whole chip", sim=meta["simulation_name"],
662
+ settings=", ".join(f"{k} {v}" for k, v in (meta.get("settings") or {}).items()) or "defaults",
663
+ aedt=("(found here: " + str(exe) + ")") if exe else "(not found on this machine)", fmt=RESULTS_FORMAT),
664
+ encoding="utf-8")
665
+ (job / "results_template.json").write_text(
666
+ json.dumps(results_template(source, g, analysis, meta), indent=2) + "\n", encoding="utf-8")
667
+ say(f"job {job}")
668
+ if aedt_path_too_long(job, analysis): # the automatic run relocates such a job; a manual export only warns
669
+ say(f"warning: the job folder path is too long for AEDT on Windows ({len(str(job))} characters; AEDT's "
670
+ "result folders would pass 260): solve it from a shorter folder, e.g. "
671
+ f"{Path(tempfile.gettempdir()) / 'qcc_jobs' / job.name}")
672
+ jobs.append(job)
673
+ for n in notes:
674
+ say(f"note: {n}")
675
+ return jobs
676
+
677
+
678
+ def preview_groups(design, names=None, default: bool = False, whole: bool = False, analysis: str = "q3d_cmatrix",
679
+ margin_um: float = 300.0, name: str = "gui_sim", group: str | None = None) -> dict:
680
+ """What an export of the same arguments renders, for drawing it in KLayout (``qcc sim preview``): per box its
681
+ rectangle, the components and routes in it, and every port (50 Ω edge ports, cut stubs, junction ports) with its
682
+ position. It runs :func:`~quantcore_circuits.sim_tools.build_simulation` exactly as :func:`export_manual` does (same
683
+ group, same box, same ports; ``export_job`` then writes them as files), and writes nothing.
684
+
685
+ ``group`` previews a saved ``sim_groups`` entry as it is (``analysis`` None: its first analysis). Otherwise the
686
+ group comes from ``names`` / ``default`` / ``whole`` and ``analysis`` like in :func:`export_manual`."""
687
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
688
+ from quantcore_circuits.sim_tools import build_simulation # pylint: disable=import-outside-toplevel
689
+ from quantcore_circuits.sim_tools.builder import CHIP_GROUP, group_spec # pylint: disable=import-outside-toplevel
690
+
691
+ design = Path(design).resolve()
692
+ d = load_design(design)
693
+ notes: list[str] = []
694
+ if group:
695
+ if group not in d.sim_groups and group != CHIP_GROUP:
696
+ raise ValueError(f"no sim group {group!r}; available: {sorted(d.sim_groups)}")
697
+ groups, source = [group], d
698
+ if not analysis:
699
+ analysis = (group_spec(d, group).analyses or ["eigenmode_epr"])[0]
700
+ elif whole:
701
+ groups, source = [CHIP_GROUP], d
702
+ notes.append("the whole chip: slow and memory hungry")
703
+ else:
704
+ if names and _by_selection(design, names, analysis):
705
+ spec, notes = selection_group(design, names, analysis, margin_um)
706
+ groups, specs = [f"{name}_sel"], {f"{name}_sel": spec}
707
+ else:
708
+ qubits, notes = resolve_selection(design, names or [], default=default)
709
+ if not qubits:
710
+ raise ValueError("no qubit to simulate: name a qubit (--instances Q1,R1), or use --default / --whole")
711
+ groups, specs, plan = plan_subset_groups(design, qubits, name, margin_um, analysis)
712
+ notes += [n for sg in plan for n in sg.notes]
713
+ data = d.to_json_dict()
714
+ data["sim_groups"].update(specs) # in memory: the design file is not touched
715
+ source = load_design(data)
716
+ out = []
717
+ for g in groups:
718
+ spec = group_spec(source, g)
719
+ rec = {"name": g, "analysis": analysis, "select": list(spec.select), "margin_um": spec.margin_um,
720
+ "group_ports": dict(spec.ports), "ports": [], "routes": [], "notes": []}
721
+ if g == CHIP_GROUP and g not in source.sim_groups: # the die: no cut, no ports, nothing to build here
722
+ rec.update(box=[float(v) for v in source.chip.box], whole=True, select=[*source.instances, *source.routes])
723
+ else:
724
+ setup = build_simulation(source, g, analysis)
725
+ box = setup.box
726
+ data = {row["number"]: row for row in setup.simulation.get_port_data()} # what the exported KQC json holds
727
+ ports = []
728
+ for info in setup.ports:
729
+ row = data.get(info.number, {})
730
+ at, gnd = row.get("signal_location"), row.get("ground_location")
731
+ ports.append({"number": info.number, "kind": info.kind, "name": info.name, "net": info.excitation,
732
+ "at": [round(at[0], 3), round(at[1], 3)] if at else None,
733
+ "ground": [round(gnd[0], 3), round(gnd[1], 3)] if gnd else None,
734
+ "junction": bool(row.get("junction")),
735
+ "polygon": [[round(q[0], 3), round(q[1], 3)] for q in row.get("polygon", [])]})
736
+ rec.update(box=[box.left, box.bottom, box.right, box.top], whole=False, ports=ports,
737
+ routes=list(setup.routes), notes=list(setup.notes))
738
+ out.append(rec)
739
+ return {"design": d.name, "analysis": analysis, "groups": out, "notes": list(dict.fromkeys(notes))}
740
+
741
+
742
+ def results_template(design, group: str = "chip", analysis: str = "q3d_cmatrix", meta: dict | None = None) -> dict:
743
+ """A ``results.json`` skeleton: the net names of the design's circuit, a zero matrix (see :data:`RESULTS_FORMAT`)."""
744
+ from quantcore_circuits.circuit.derive import circuit_from_design # pylint: disable=import-outside-toplevel
745
+
746
+ nets = list((meta or {}).get("nets", {}).values())
747
+ if not nets:
748
+ model = circuit_from_design(design, group)
749
+ nets = [n for node, spec in model.nodes.items() if not spec.ground for n in spec.nets]
750
+ nets = list(dict.fromkeys(nets))
751
+ out = {"analysis": analysis, "group": group,
752
+ "cmatrix": {"labels": nets, "unit": "fF", "matrix": [[0.0] * len(nets) for _ in nets]}}
753
+ if analysis in ("hfss_eigenmode", "eigenmode_epr"):
754
+ out["eigenmodes"] = [{"mode": 1, "f_GHz": 0.0, "Q": None}]
755
+ return out
756
+
757
+
758
+ # ---- import --------------------------------------------------------------------------------------------------------
759
+ def validate_results(design, results: dict, group: str | None = None) -> tuple[list[str], list[str]]:
760
+ """``(errors, warnings)`` of a results dict against the design's circuit nets."""
761
+ import numpy as np # pylint: disable=import-outside-toplevel
762
+
763
+ from quantcore_circuits.circuit.derive import circuit_from_design # pylint: disable=import-outside-toplevel
764
+
765
+ errors, warns = [], []
766
+ if not isinstance(results, dict) or "analysis" not in results:
767
+ return ['no "analysis" key: not a results.json (qcc results template DESIGN shows the format)'], warns
768
+ cm = results.get("cmatrix")
769
+ if cm is not None:
770
+ labels = cm.get("labels") or []
771
+ try:
772
+ mat = np.asarray(cm.get("matrix"), dtype=float)
773
+ except (TypeError, ValueError):
774
+ return ['cmatrix.matrix is not a number matrix'], warns
775
+ if mat.ndim != 2 or mat.shape[0] != mat.shape[1] or mat.shape[0] != len(labels):
776
+ errors.append(f"cmatrix: {len(labels)} labels but the matrix is {mat.shape[0]}×{mat.shape[-1]}"
777
+ if mat.ndim == 2 else "cmatrix.matrix must be a square matrix")
778
+ else:
779
+ if (np.diag(mat) <= 0).any():
780
+ warns.append("cmatrix: a diagonal entry is not positive (is this the Maxwell matrix, in fF?)")
781
+ if mat.size and np.abs(mat - mat.T).max() > 1e-3 * (np.abs(mat).max() or 1.0):
782
+ warns.append("cmatrix is not symmetric")
783
+ if cm.get("unit", "fF") != "fF":
784
+ warns.append(f"cmatrix.unit is {cm.get('unit')!r}; Quantcore reads fF")
785
+ try:
786
+ model = circuit_from_design(design, group or results.get("group") or "chip")
787
+ known = {n for spec in model.nodes.values() for n in spec.nets} | set(
788
+ load_routes(design))
789
+ hit = [lab for lab in labels if lab in known]
790
+ if labels and not hit:
791
+ errors.append("none of the cmatrix labels is a net of this design; expected names like "
792
+ f"{sorted(known)[:6]} (qcc results template DESIGN lists them)")
793
+ elif len(hit) < len(labels):
794
+ warns.append("cmatrix labels not in the design (ignored): "
795
+ f"{[lab for lab in labels if lab not in known]}")
796
+ except Exception as e: # noqa: BLE001
797
+ warns.append(f"could not check the net names ({type(e).__name__}: {e})")
798
+ modes = results.get("eigenmodes")
799
+ if modes is not None and not all(isinstance(m, dict) and "f_GHz" in m for m in modes):
800
+ errors.append('eigenmodes must be a list of {"f_GHz": ..., "Q": ...}')
801
+ if cm is None and not modes and not results.get("sparams") and not results.get("epr"):
802
+ errors.append("no cmatrix, eigenmodes, epr or sparams in the results: nothing to read")
803
+ return errors, warns
804
+
805
+
806
+ def load_routes(design) -> list[str]:
807
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
808
+
809
+ return list(load_design(design).routes)
810
+
811
+
812
+ def stage_import(design, source, group: str | None = None) -> tuple[Path, list[str], list[str]]:
813
+ """Make ``source`` (a solved job folder, its results/ folder or a results.json) an analysable job folder:
814
+ ``(job dir, errors, warnings)``. A folder without ``results/results.json`` is collected from its raw AEDT outputs; a
815
+ loose results file is copied into ``<design folder>/build/jobs/<design>_imported_<stem>/``."""
816
+ from quantcore_circuits.analysis.results import collect_results # pylint: disable=import-outside-toplevel
817
+ from quantcore_circuits.design import design_hash, load_design # pylint: disable=import-outside-toplevel
818
+
819
+ d = load_design(design)
820
+ src = Path(source)
821
+ if not src.exists():
822
+ return src, [f"{src} does not exist"], []
823
+ if src.is_file() and src.parent.name == "results" and (src.parent.parent / "job.json").exists():
824
+ src = src.parent.parent
825
+ warns: list[str] = []
826
+ if src.is_dir() and src.name == "results" and (src.parent / "job.json").exists():
827
+ src = src.parent
828
+ if src.is_dir():
829
+ res_file = src / "results" / "results.json"
830
+ raw = [p for pat in ("*_project_results.json", "*_project_qcc.json", "*_project_convergence.txt", "*.eig",
831
+ "*.s*p") for p in src.glob(pat)]
832
+ stale = res_file.exists() and raw and max(p.stat().st_mtime for p in raw) > res_file.stat().st_mtime
833
+ if not res_file.exists() or stale: # e.g. re-exported after a finer solve in AEDT (scripts/qcc_collect.py)
834
+ try:
835
+ collect_results(src)
836
+ except Exception as e: # noqa: BLE001
837
+ return src, [f"{src}: no results/results.json and the raw outputs could not be read ({e})"], []
838
+ if stale:
839
+ warns.append(f"{src.name}: read again from the AEDT outputs (newer than results/results.json)")
840
+ job_dir = src
841
+ else:
842
+ try:
843
+ data = json.loads(src.read_text(encoding="utf-8"))
844
+ except ValueError as e:
845
+ return src, [f"{src.name} is not JSON ({e})"], []
846
+ job_dir = jobs_root(design) / f"{d.name}_imported_{src.stem}"
847
+ (job_dir / "results").mkdir(parents=True, exist_ok=True)
848
+ data.setdefault("group", group or "chip")
849
+ (job_dir / "results" / "results.json").write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
850
+ (job_dir / "job.json").write_text(json.dumps({
851
+ "schema": "qcc-job/0.1", "design": d.name, "design_hash": design_hash(d), "group": data["group"],
852
+ "analysis": data.get("analysis"), "imported_from": str(src.resolve()), "created": now(),
853
+ "status": "imported"}, indent=2) + "\n", encoding="utf-8")
854
+ results = json.loads((job_dir / "results" / "results.json").read_text(encoding="utf-8"))
855
+ job = json.loads((job_dir / "job.json").read_text(encoding="utf-8")) if (job_dir / "job.json").exists() else {}
856
+ errors, w = validate_results(design, results, group or job.get("group"))
857
+ warns += w
858
+ if job.get("design") and job["design"] != d.name:
859
+ warns.append(f"the job was made for the design {job['design']!r}, this is {d.name!r}")
860
+ ours = design_hash(d)
861
+ if job.get("design_hash") and job["design_hash"] not in (ours,) and job.get("group_hash") != ours:
862
+ warns.append("the design has changed since this job was exported (the values may not match the layout)")
863
+ grp = group or results.get("group") or job.get("group")
864
+ if grp and grp != "chip" and grp not in d.sim_groups:
865
+ warns.append(f"sim group {grp!r} is not in this design; its values are used for the whole chip")
866
+ return job_dir, errors, warns
867
+
868
+
869
+ def import_results(design, sources, group: str | None = None, readout: bool = True, say=print) -> dict:
870
+ """Read solved job folders / results files back: validate, then :func:`analyse_jobs`."""
871
+ jobs, all_warns = [], []
872
+ for s in sources:
873
+ job_dir, errors, warns = stage_import(design, s, group)
874
+ if errors:
875
+ raise ValueError("\n".join(errors))
876
+ all_warns += warns
877
+ jobs.append(job_dir)
878
+ for w in all_warns:
879
+ say(f"warning: {w}")
880
+ for job_dir in jobs: # the convergence of what was imported (a finer solve made in AEDT, too)
881
+ fb = convergence_feedback(job_dir)
882
+ if fb.get("converged") is not None:
883
+ say(f"{Path(job_dir).name}: mesh {fb['message']}")
884
+ save_feedback(design, fb)
885
+ out = analyse_jobs(design, jobs, readout=readout, source="import", say=say)
886
+ out["warnings"] = all_warns
887
+ return out
888
+
889
+
890
+ # ---- tune --------------------------------------------------------------------------------------------------------
891
+ def _diff(a, b, path=()):
892
+ """Leaf changes between two JSON-like values: ``[(path, old, new)]``."""
893
+ if isinstance(a, dict) and isinstance(b, dict):
894
+ out = []
895
+ for k in dict.fromkeys([*a, *b]):
896
+ if k not in a or k not in b:
897
+ out.append(((*path, k), a.get(k), b.get(k)))
898
+ else:
899
+ out += _diff(a[k], b[k], (*path, k))
900
+ return out
901
+ if isinstance(a, list) and isinstance(b, list) and len(a) == len(b):
902
+ return [c for i, (x, y) in enumerate(zip(a, b)) for c in _diff(x, y, (*path, i))]
903
+ if isinstance(a, (int, float)) and isinstance(b, (int, float)) and not isinstance(a, bool):
904
+ return [] if abs(a - b) <= 1e-9 * max(1.0, abs(a)) else [(path, a, b)]
905
+ return [] if a == b else [(path, a, b)]
906
+
907
+
908
+ def propose(design, jobs=None, out=None, say=print) -> dict:
909
+ """``loop.analyse`` + ``loop.feedback``: the next revision as a preview. ``jobs`` None: the last run's jobs
910
+ (``flow.json``), else the layout's estimates. Returns ``{"tunable", "message", "knobs": [{knob, old, new}],
911
+ "moved": [...], "predicted": {...}, "objective", "revision", "basis", "notes": [...]}``; ``out`` also gets it as
912
+ JSON. Every qubit with a LOM model and a λ/4 or λ/2 readout pair is tuned; ``notes`` say what is not and why. The
913
+ revision is written but not built (Apply rebuilds)."""
914
+ from quantcore_circuits import loop # pylint: disable=import-outside-toplevel
915
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
916
+ from quantcore_circuits.optimise import knob_path # pylint: disable=import-outside-toplevel
917
+ from quantcore_circuits.track import Run # pylint: disable=import-outside-toplevel
918
+
919
+ rd = run_dir(design)
920
+ rec = flow_record(design)
921
+ if jobs is None and rec and rec.get("jobs"):
922
+ jobs = [j for j in rec["jobs"] if Path(j).exists()] or None
923
+ run = Run(design, rd)
924
+ basis = ("the FEM results of " + ", ".join(Path(j).name for j in jobs)) if jobs else "the layout's own estimates"
925
+ an = loop.analyse(design, (jobs if len(jobs) > 1 else jobs[0]) if jobs else None, "chip", run=run,
926
+ readout=False, out_dir=rd)
927
+ res = {"tunable": False, "message": "", "knobs": [], "moved": [], "predicted": {}, "objective": None,
928
+ "revision": None, "basis": basis, "stale": bool(rec and rec.get("stale")), "notes": []}
929
+ if not any(r.target is not None for r in an.rows):
930
+ res["message"] = "There are no targets to tune towards: set targets (f_q, alpha, f_r, g) for the qubit and resonator."
931
+ elif not an.filled.pairs:
932
+ res["message"] = ("Nothing can be tuned automatically yet: no qubit has a readout resonator in the circuit (a "
933
+ "lambda/4 or lambda/2 line on a coupler of one qubit). Change the layout by hand and re-run "
934
+ "the simulation.")
935
+ else:
936
+ try:
937
+ prop, rev, _ = loop.feedback(an, run, design, build_revision=False)
938
+ except Exception as e: # noqa: BLE001
939
+ res["message"] = f"Nothing can be tuned automatically for this design yet ({type(e).__name__}: {e})."
940
+ prop = None
941
+ if prop is not None:
942
+ d_old = load_design(design)
943
+ old = d_old.to_json_dict()
944
+ new = json.loads(Path(rev).read_text(encoding="utf-8"))
945
+ res["knobs"] = [{"knob": k, "old": prop.start_knobs.get(k), "new": v} for k, v in prop.knobs.items()
946
+ if prop.start_knobs.get(k) != v]
947
+ listed = [tuple(knob_path(d_old, k)) for k in prop.knobs]
948
+ # a knob's own change, or the list / option it lives in when the knob created it (an unset parameter)
949
+ res["moved"] = [{"path": _path_text(p), "old": o, "new": n} for p, o, n in _diff(old, new)
950
+ if not any(tuple(p)[:len(kp)] == kp or kp[:len(p)] == tuple(p) for kp in listed)]
951
+ res.update(predicted=prop.predicted, objective=float(prop.objective), revision=str(rev),
952
+ at_bounds=list(prop.at_bounds), notes=list(prop.notes))
953
+ if res["knobs"]:
954
+ res["tunable"] = True
955
+ res["message"] = (f"Predicted distance from the targets after the change: {prop.objective:.2g} "
956
+ "tolerances (0 = on target). The prediction is from a surrogate; simulate again to check.")
957
+ else:
958
+ res["message"] = "Already on target to within the surrogate's resolution: no knob needs to change."
959
+ if prop.notes:
960
+ res["message"] += f" {len(prop.notes)} note(s) on what is not tuned (listed below)."
961
+ if out:
962
+ Path(out).write_text(json.dumps(res, indent=2, default=float) + "\n", encoding="utf-8")
963
+ return res
964
+
965
+
966
+ def _path_text(path) -> str:
967
+ parts = list(path)
968
+ if len(parts) >= 4 and parts[0] == "instances" and parts[2] == "params":
969
+ return ".".join(str(p) for p in [parts[1], *parts[3:]])
970
+ if len(parts) >= 3 and parts[0] in ("instances", "routes"):
971
+ return ".".join(str(p) for p in parts[1:])
972
+ return ".".join(str(p) for p in parts)
973
+
974
+
975
+ def apply_knobs(design, proposal: dict, out=None) -> dict:
976
+ """The design with the proposal's knobs set (``codesign.apply``: moves the waypoints that follow a port too), as a
977
+ design.json dict. Raises when a knob no longer has the value the proposal started from."""
978
+ from quantcore_circuits import codesign as cd # pylint: disable=import-outside-toplevel
979
+ from quantcore_circuits.design import load_design # pylint: disable=import-outside-toplevel
980
+ from quantcore_circuits.optimise import get_knob # pylint: disable=import-outside-toplevel
981
+
982
+ d = load_design(design)
983
+ for k in proposal["knobs"]:
984
+ now_value = get_knob(d, k["knob"])
985
+ if k.get("old") is not None and abs(float(now_value) - float(k["old"])) > 1e-6 * max(1.0, abs(float(k["old"]))):
986
+ raise ValueError(f"{k['knob']} is {now_value} now, the proposal started from {k['old']}: the design changed "
987
+ "since the proposal; propose again")
988
+ new = cd.apply(d, {k["knob"]: k["new"] for k in proposal["knobs"]}).to_json_dict()
989
+ if out:
990
+ Path(out).write_text(json.dumps(new, indent=2) + "\n", encoding="utf-8")
991
+ return new