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,876 @@
1
+ """Plot helpers following the project plot style (thesis style), plus PlotSpec builders shared with the dashboard.
2
+
3
+ Style: the Quantcore palette, inward ticks with minor ticks on all sides
4
+ (:func:`thesis_axes`), serif LaTeX text when a TeX install works (checked once in a subprocess, cached), PDF fonts
5
+ embedded. Sizes: figure width = fraction of \\textwidth × 6.0 in, so the
6
+ matplotlib font size is the printed size; pick a layout from :data:`FIGSIZES` and its font tier with
7
+ :func:`figure`.
8
+
9
+ Data is passed around as *PlotSpecs* (``reviewer/contract/state.ts``): the same dict is drawn by the React dashboard
10
+ and by :func:`plot_spec` here. Builders: :func:`xy_spec`, :func:`bar_spec`, :func:`levels_spec`, :func:`heatmap_spec`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import math
17
+ import os
18
+ import re
19
+ import subprocess
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ COLORS = ["#185adb", "#f9813a", "#da0037", "#206a5d", "#444444", "#c4fb6d", "#e84a5f", "#3edbf0", "#ff847c", "#ffc947"]
24
+
25
+ TIERS = {
26
+ 1: {
27
+ "font.size": 12,
28
+ "axes.labelsize": 12,
29
+ "axes.titlesize": 12,
30
+ "xtick.labelsize": 10,
31
+ "ytick.labelsize": 10,
32
+ "legend.fontsize": 10,
33
+ },
34
+ 2: {
35
+ "font.size": 11,
36
+ "axes.labelsize": 11,
37
+ "axes.titlesize": 11,
38
+ "xtick.labelsize": 9,
39
+ "ytick.labelsize": 9,
40
+ "legend.fontsize": 10,
41
+ },
42
+ 3: {
43
+ "font.size": 10,
44
+ "axes.labelsize": 10,
45
+ "axes.titlesize": 10,
46
+ "xtick.labelsize": 8.5,
47
+ "ytick.labelsize": 8.5,
48
+ "legend.fontsize": 9,
49
+ },
50
+ 4: {
51
+ "font.size": 9,
52
+ "axes.labelsize": 9,
53
+ "axes.titlesize": 9,
54
+ "xtick.labelsize": 8,
55
+ "ytick.labelsize": 8,
56
+ "legend.fontsize": 8,
57
+ },
58
+ }
59
+
60
+ # (figsize inches, font tier, LaTeX width) — plot size tables A and B
61
+ FIGSIZES = {
62
+ "single": ((6.0, 4.0), 1, r"\textwidth"),
63
+ "wide": ((6.0, 2.0), 1, r"\textwidth"),
64
+ "timetrace": ((6.0, 2.25), 1, r"\textwidth"),
65
+ "square_big": ((4.5, 4.5), 1, r"0.75\textwidth"),
66
+ "square_medium": ((3.6, 3.6), 1, r"0.6\textwidth"),
67
+ "two": ((6.0, 2.5), 2, r"\textwidth"),
68
+ "two_square": ((6.0, 3.2), 2, r"\textwidth"),
69
+ "re_im": ((6.0, 2.8), 2, r"\textwidth"),
70
+ "grid2x2": ((6.0, 5.0), 2, r"\textwidth"),
71
+ "three": ((6.0, 2.0), 3, r"\textwidth"),
72
+ "three_square": ((6.0, 2.6), 3, r"\textwidth"),
73
+ "four_square": ((6.0, 1.9), 4, r"\textwidth"),
74
+ "three_stacked": ((6.0, 6.5), 1, r"\textwidth"),
75
+ }
76
+
77
+ _RC = {
78
+ "font.size": 12,
79
+ "axes.labelsize": 12,
80
+ "axes.titlesize": 12,
81
+ "xtick.labelsize": 10,
82
+ "ytick.labelsize": 10,
83
+ "xtick.direction": "in",
84
+ "ytick.direction": "in",
85
+ "legend.fontsize": 10,
86
+ "figure.titlesize": 12,
87
+ "font.family": "serif",
88
+ "axes.linewidth": 1.2,
89
+ "axes.labelpad": 4.0,
90
+ "axes.titlepad": 6.0,
91
+ "lines.linewidth": 2.2,
92
+ "lines.markersize": 4.0,
93
+ "lines.markeredgewidth": 0.9,
94
+ "xtick.major.size": 6,
95
+ "ytick.major.size": 6,
96
+ "xtick.minor.size": 3,
97
+ "ytick.minor.size": 3,
98
+ "xtick.major.width": 1.2,
99
+ "ytick.major.width": 1.2,
100
+ "xtick.minor.width": 1.0,
101
+ "ytick.minor.width": 1.0,
102
+ "xtick.major.pad": 3.5,
103
+ "ytick.major.pad": 3.5,
104
+ "figure.dpi": 120,
105
+ "savefig.dpi": 300,
106
+ "savefig.bbox": "tight",
107
+ "savefig.pad_inches": 0.02,
108
+ "pdf.fonttype": 42,
109
+ "ps.fonttype": 42,
110
+ "axes.grid": False,
111
+ }
112
+
113
+ _TEX_CACHE = Path(os.environ.get("LOCALAPPDATA", Path.home() / ".cache")) / "qcc" / "usetex.json"
114
+
115
+
116
+ def latex_available(timeout: float = 120.0) -> bool:
117
+ """Whether matplotlib ``text.usetex`` works here (tested once in a subprocess so a TeX prompt can't hang us)."""
118
+ try:
119
+ return bool(json.loads(_TEX_CACHE.read_text())["ok"])
120
+ except (OSError, ValueError, KeyError):
121
+ pass
122
+ code = (
123
+ "import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt, tempfile, os;"
124
+ "plt.rcParams.update({'text.usetex': True, 'font.family': 'serif'});"
125
+ "f, a = plt.subplots(figsize=(1, 1)); a.set_title(r'$\\alpha\\,\\Phi_0$');"
126
+ "f.savefig(os.path.join(tempfile.gettempdir(), '_qcc_latex_test.png'))"
127
+ )
128
+ try:
129
+ ok = (
130
+ subprocess.run([sys.executable, "-c", code], capture_output=True, timeout=timeout, check=False).returncode
131
+ == 0
132
+ )
133
+ except (OSError, subprocess.TimeoutExpired):
134
+ ok = False
135
+ _TEX_CACHE.parent.mkdir(parents=True, exist_ok=True)
136
+ _TEX_CACHE.write_text(json.dumps({"ok": ok}))
137
+ return ok
138
+
139
+
140
+ def use_style(usetex: bool | None = None) -> bool:
141
+ """Apply the guideline style; returns whether LaTeX text is on (falls back to Computer Modern mathtext)."""
142
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
143
+
144
+ try:
145
+ import scienceplots # noqa: F401 pylint: disable=import-outside-toplevel,unused-import
146
+
147
+ plt.style.use(["science"])
148
+ except ImportError:
149
+ pass # optional; the rcParams below are the guideline
150
+ plt.rcParams["axes.prop_cycle"] = plt.cycler("color", COLORS)
151
+ plt.rcParams.update(_RC)
152
+ tex = latex_available() if usetex is None else usetex
153
+ plt.rcParams.update({"text.usetex": True} if tex else {"text.usetex": False, "mathtext.fontset": "cm"})
154
+ return tex
155
+
156
+
157
+ def use_tier(n: int) -> None:
158
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
159
+
160
+ plt.rcParams.update(TIERS[n])
161
+
162
+
163
+ def thesis_axes(ax, xminor: int = 5, yminor: int = 5):
164
+ """Minor ticks and consistent spine widths (project plot style). Call once per axis."""
165
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
166
+ from matplotlib.ticker import AutoMinorLocator # pylint: disable=import-outside-toplevel
167
+
168
+ if ax.get_xscale() == "linear":
169
+ ax.xaxis.set_minor_locator(AutoMinorLocator(xminor))
170
+ if ax.get_yscale() == "linear":
171
+ ax.yaxis.set_minor_locator(AutoMinorLocator(yminor))
172
+ ax.tick_params(which="both", top=True, right=True)
173
+ for s in ax.spines.values():
174
+ s.set_linewidth(plt.rcParams["axes.linewidth"])
175
+ return ax
176
+
177
+
178
+ def figure(layout: str = "single", nrows: int = 1, ncols: int = 1, **kw):
179
+ """``plt.subplots`` with the guideline figsize and font tier for ``layout`` (see :data:`FIGSIZES`)."""
180
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
181
+
182
+ size, tier, _ = FIGSIZES[layout]
183
+ use_tier(tier)
184
+ fig, axes = plt.subplots(nrows, ncols, figsize=size, layout="constrained", **kw)
185
+ for ax in axes.flat if hasattr(axes, "flat") else [axes]:
186
+ thesis_axes(ax)
187
+ return fig, axes
188
+
189
+
190
+ _TEX = {
191
+ "Φ0": r"\Phi_0",
192
+ "Φ": r"\Phi",
193
+ "α": r"\alpha",
194
+ "χ": r"\chi",
195
+ "κ": r"\kappa",
196
+ "Σ": r"\Sigma",
197
+ "µ": r"\mu",
198
+ "μ": r"\mu",
199
+ "Ω": r"\Omega",
200
+ "ε": r"\varepsilon",
201
+ "λ": r"\lambda",
202
+ "‖": r"\|",
203
+ "⟩": r"\rangle",
204
+ "−": "-",
205
+ "×": r"\times",
206
+ "·": r"\cdot",
207
+ "Δ": r"\Delta",
208
+ "ω": r"\omega",
209
+ "π": r"\pi",
210
+ }
211
+
212
+
213
+ _SUB = re.compile(r"(?<![A-Za-z0-9.])([A-Za-z])_([A-Za-z0-9ΣΦαχκΩλωπ]{1,3})(?![A-Za-z0-9_])")
214
+
215
+
216
+ def tex(s: str | None) -> str | None:
217
+ """Unicode label → mathtext/LaTeX label: ``f_q``/``C_Σ`` (single-letter base) become subscripts, Greek and kets
218
+ become math, and text-mode specials are escaped under usetex (``metal_lom`` stays literal)."""
219
+ if s is None:
220
+ return None
221
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
222
+
223
+ usetex = plt.rcParams.get("text.usetex")
224
+ greek = sorted(_TEX.items(), key=lambda kv: -len(kv[0]))
225
+ pieces = [] # (is_math, text)
226
+ pos = 0
227
+ for m in _SUB.finditer(s):
228
+ pieces += [(False, s[pos : m.start()]), (True, f"{m.group(1)}_{{{m.group(2)}}}")]
229
+ pos = m.end()
230
+ pieces.append((False, s[pos:]))
231
+ out = []
232
+ for is_math, t in pieces:
233
+ if is_math:
234
+ for k, v in greek:
235
+ t = t.replace(k, v + " " if v[0] == "\\" else v)
236
+ out.append(f"${t}$")
237
+ continue
238
+ if usetex:
239
+ for ch in ("_", "%", "&", "#"):
240
+ t = t.replace(ch, "\\" + ch)
241
+ for k, v in greek:
242
+ t = t.replace(k, f"${v}$")
243
+ out.append(t.replace("$$", "") if not usetex else t.replace("$$", "").replace("|", "$|$"))
244
+ return "".join(out).replace("$$", "")
245
+
246
+
247
+ # ---- PlotSpec builders -----------------------------------------------------------------------------------------
248
+ def xy_spec(ident, title, tab, series, x_label=None, y_label=None, ref_lines=None, log_y=False, caption=None):
249
+ """``series``: list of dicts {name, x, y, kind?, dashed?}."""
250
+ spec = {"id": ident, "title": title, "tab": tab, "kind": "xy", "series": series}
251
+ for k, v in (("xLabel", x_label), ("yLabel", y_label), ("refLines", ref_lines), ("caption", caption)):
252
+ if v:
253
+ spec[k] = v
254
+ if log_y:
255
+ spec["logY"] = True
256
+ return spec
257
+
258
+
259
+ def bar_spec(ident, title, tab, bars, y_label=None, caption=None):
260
+ """``bars``: list of {label, values: {series: value}}."""
261
+ spec = {"id": ident, "title": title, "tab": tab, "kind": "bar", "bars": bars}
262
+ if y_label:
263
+ spec["yLabel"] = y_label
264
+ if caption:
265
+ spec["caption"] = caption
266
+ return spec
267
+
268
+
269
+ def levels_spec(ident, title, tab, levels, caption=None):
270
+ spec = {"id": ident, "title": title, "tab": tab, "kind": "levels", "levels": levels}
271
+ if caption:
272
+ spec["caption"] = caption
273
+ return spec
274
+
275
+
276
+ def heatmap_spec(ident, title, tab, rows, cols, values, unit, caption=None):
277
+ spec = {
278
+ "id": ident,
279
+ "title": title,
280
+ "tab": tab,
281
+ "kind": "heatmap",
282
+ "heatmap": {"rows": rows, "cols": cols, "values": values, "unit": unit},
283
+ }
284
+ if caption:
285
+ spec["caption"] = caption
286
+ return spec
287
+
288
+
289
+ # ---- PlotSpec → matplotlib ---------------------------------------------------------------------------------------
290
+ def plot_spec(spec: dict, ax=None, legend: bool = True):
291
+ """Draw a PlotSpec on ``ax`` (a new guideline-sized figure if omitted). Returns the axis."""
292
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
293
+ import numpy as np # pylint: disable=import-outside-toplevel
294
+
295
+ if ax is None:
296
+ layout = {"levels": "square_medium", "heatmap": "square_medium"}.get(spec["kind"], "single")
297
+ _, ax = figure(layout)
298
+ kind = spec["kind"]
299
+ if kind == "xy":
300
+ for i, s in enumerate(spec.get("series", [])):
301
+ style = {"linestyle": "--" if s.get("dashed") else "-", "color": COLORS[i % len(COLORS)]}
302
+ if s.get("kind") == "scatter":
303
+ ax.plot(s["x"], s["y"], "o", label=tex(s["name"]), color=style["color"])
304
+ elif s.get("kind") == "step":
305
+ ax.step(s["x"], s["y"], where="mid", label=tex(s["name"]), **style)
306
+ else:
307
+ ax.plot(s["x"], s["y"], label=tex(s["name"]), **style)
308
+ for r in spec.get("refLines", []):
309
+ line = ax.axhline if r["axis"] == "y" else ax.axvline
310
+ line(r["value"], color="#888888", linestyle=":", linewidth=1.0)
311
+ if r["axis"] == "y":
312
+ ax.annotate(
313
+ tex(r["label"]),
314
+ (1.0, r["value"]),
315
+ xycoords=("axes fraction", "data"),
316
+ ha="right",
317
+ va="bottom",
318
+ fontsize="small",
319
+ color="#666666",
320
+ )
321
+ if spec.get("logY"):
322
+ ax.set_yscale("log")
323
+ if legend and len(spec.get("series", [])) > 1:
324
+ ax.legend(frameon=False)
325
+ elif kind == "bar":
326
+ bars = spec.get("bars", [])
327
+ names = sorted({n for b in bars for n in b["values"]})
328
+ width = 0.8 / max(len(names), 1)
329
+ for j, n in enumerate(names):
330
+ xs = [i + (j - (len(names) - 1) / 2) * width for i in range(len(bars))]
331
+ ys = [b["values"].get(n) or 0 for b in bars]
332
+ ax.bar(xs, ys, width, label=tex(n), color=COLORS[j % len(COLORS)])
333
+ ax.set_xticks(
334
+ range(len(bars)),
335
+ [tex(b["label"]) for b in bars],
336
+ rotation=30 if len(bars) > 3 else 0,
337
+ ha="right" if len(bars) > 3 else "center",
338
+ )
339
+ ax.tick_params(axis="x", which="minor", bottom=False, top=False)
340
+ ax.axhline(0, color="#888888", linewidth=0.8)
341
+ if legend and len(names) > 1:
342
+ ax.legend(frameon=False, loc="upper left", bbox_to_anchor=(1.0, 1.0), fontsize="small")
343
+ elif kind == "levels":
344
+ levels = spec.get("levels", [])
345
+ groups = sorted({lv.get("group", "") for lv in levels}) or [""]
346
+ for lv in levels:
347
+ gx = groups.index(lv.get("group", ""))
348
+ ax.hlines(lv["energy"], gx - 0.3, gx + 0.3, color=COLORS[0], linewidth=2)
349
+ ax.annotate(tex(lv["label"]), (gx + 0.33, lv["energy"]), va="center", fontsize="small")
350
+ ax.set_xlim(-0.6, len(groups) - 0.1)
351
+ ax.set_xticks(range(len(groups)), [g or "" for g in groups])
352
+ ax.tick_params(axis="x", which="both", length=0)
353
+ ax.set_ylabel(spec.get("yLabel") or "Energy $E/h$ (GHz)")
354
+ elif kind == "heatmap":
355
+ hm = spec["heatmap"]
356
+ vals = np.asarray(hm["values"], dtype=float)
357
+ im = ax.imshow(np.abs(vals), cmap="Blues")
358
+ for (i, j), v in np.ndenumerate(vals):
359
+ ax.text(
360
+ j,
361
+ i,
362
+ f"{v:.2f}",
363
+ ha="center",
364
+ va="center",
365
+ fontsize="small",
366
+ color="white" if abs(v) > 0.6 * np.abs(vals).max() else "#111111",
367
+ )
368
+ ax.set_xticks(range(len(hm["cols"])), [tex(c) for c in hm["cols"]], rotation=30, ha="right")
369
+ ax.set_yticks(range(len(hm["rows"])), [tex(r) for r in hm["rows"]])
370
+ ax.minorticks_off()
371
+ plt.colorbar(im, ax=ax, label=tex(f"|C| ({hm['unit']})"))
372
+ if spec.get("xLabel") and kind != "levels":
373
+ ax.set_xlabel(tex(spec["xLabel"]))
374
+ if spec.get("yLabel") and kind not in ("levels",):
375
+ ax.set_ylabel(tex(spec["yLabel"]))
376
+ ax.set_title(tex(spec.get("title")))
377
+ return ax
378
+
379
+
380
+ # ---- FEM results: convergence, S21 with its notch fit, EPR ------------------------------------------------------
381
+ # Inputs are the dicts ``analysis.results.collect_results`` writes (``results.json``), a job folder (or its
382
+ # ``results/``), or an ``*_project_convergence.txt``. The matplotlib helpers and the dashboard specs read the same
383
+ # data (:func:`convergence_data`), so the notebook figure and the Plots tab agree.
384
+ def _read_results(x) -> dict:
385
+ """``results.json`` dict from a dict, a ``results.json`` path, a job folder or its ``results/`` folder, or a
386
+ ``*_project_convergence.txt`` (then only ``convergence`` is filled)."""
387
+ if isinstance(x, dict):
388
+ return x
389
+ path = Path(x)
390
+ if path.is_file() and path.suffix == ".txt":
391
+ from quantcore_circuits.analysis.results import parse_convergence # pylint: disable=import-outside-toplevel
392
+
393
+ return {"convergence": {"file": path.name, **parse_convergence(path)}}
394
+ for cand in (path, path / "results.json", path / "results" / "results.json"):
395
+ if cand.is_file():
396
+ return json.loads(cand.read_text(encoding="utf-8"))
397
+ txt = sorted(path.glob("*_project_convergence.txt")) if path.is_dir() else []
398
+ if txt:
399
+ return _read_results(txt[0])
400
+ raise FileNotFoundError(f"no results.json or convergence file under {path}")
401
+
402
+
403
+ def convergence_data(x, label: str | None = None) -> dict | None:
404
+ """One job's adaptive-pass convergence as plain lists: ``label``, ``analysis``, ``criterion``, ``target``,
405
+ ``converged``, ``passes``, ``elements`` (solved tets per pass), ``delta`` (None on pass 1), ``mode_GHz``
406
+ (eigenmode jobs: mode -> frequency per pass). None when the job has no convergence data."""
407
+ res = _read_results(x)
408
+ conv = res.get("convergence") or {}
409
+ if not conv.get("passes"):
410
+ return None
411
+ name = label or res.get("analysis") or conv.get("file") or "job"
412
+ if res.get("group") and not label:
413
+ name = f"{name} ({res['group']})"
414
+ n = len(conv["passes"])
415
+ return {
416
+ "label": name,
417
+ "analysis": res.get("analysis"),
418
+ "criterion": conv.get("criterion"),
419
+ "target": conv.get("target"),
420
+ "converged": conv.get("converged"),
421
+ "passes": list(conv["passes"]),
422
+ "elements": list(conv.get("elements") or [None] * n),
423
+ "delta": list(conv.get("delta") or [None] * n),
424
+ "mode_GHz": conv.get("mode_GHz") or {},
425
+ }
426
+
427
+
428
+ def _conv_inputs(x, label=None) -> list[dict]:
429
+ # a dict is one job when it looks like a results dict, otherwise a mapping label -> job
430
+ if isinstance(x, dict) and not {"convergence", "passes", "analysis"} & set(x):
431
+ items = list(x.items())
432
+ elif isinstance(x, (list, tuple)):
433
+ items = [(None, v) for v in x]
434
+ else:
435
+ items = [(label, x)]
436
+ out = []
437
+ for k, v in items:
438
+ if v is None:
439
+ continue
440
+ d = convergence_data(v, label=k if isinstance(k, str) else None)
441
+ if d:
442
+ out.append(d)
443
+ return out
444
+
445
+
446
+ def _delta_points(j: dict) -> list[tuple]:
447
+ return [(p, e, v) for p, e, v in zip(j["passes"], j["elements"], j["delta"]) if v is not None]
448
+
449
+
450
+ def plot_convergence(results_or_job, ax=None, label: str | None = None):
451
+ """Adaptive-pass convergence of one job (a ``results.json`` dict / path, a job folder, a convergence text file) or
452
+ of several (``{label: ...}`` or a list). Returns the first axis (``ax.figure.axes`` has the rest).
453
+
454
+ With ``ax`` only that panel is drawn: the criterion (delta %, max delta f %, max |delta S|) against the pass, a
455
+ dotted criterion line, and the mesh size (solved tets) on a secondary top axis for a single job; jobs with
456
+ different criteria are drawn as delta / target so the line at 1 is the criterion. Without ``ax`` a figure with the
457
+ pass panel, the same delta against the tet count (log), and, for an eigenmode job, each mode's frequency relative
458
+ to its last pass.
459
+ """
460
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
461
+ import numpy as np # pylint: disable=import-outside-toplevel
462
+ from matplotlib.ticker import MaxNLocator # pylint: disable=import-outside-toplevel
463
+
464
+ jobs = _conv_inputs(results_or_job, label)
465
+ if not jobs:
466
+ raise ValueError("no convergence data in the given results")
467
+ modes = jobs[0]["mode_GHz"] if len(jobs) == 1 else {}
468
+ own = ax is None
469
+ if own:
470
+ _, axes = figure("three_square", 1, 3 if modes else 2)
471
+ axes = list(axes.flat)
472
+ ax = axes[0]
473
+ rel = len({j["criterion"] for j in jobs}) > 1
474
+
475
+ def series(j):
476
+ d = _delta_points(j)
477
+ scale = 1.0 / j["target"] if rel and j["target"] else 1.0
478
+ return [p for p, _, _ in d], [e for _, e, _ in d], [v * scale for _, _, v in d]
479
+
480
+ for i, j in enumerate(jobs):
481
+ x, _, y = series(j)
482
+ col = COLORS[i % len(COLORS)]
483
+ ax.plot(x, y, "o-", color=col, label=tex(j["label"]) if len(jobs) > 1 else None, ms=4)
484
+ if j["target"] is not None and not rel:
485
+ ax.axhline(j["target"], color=col, linestyle=":", linewidth=1.0)
486
+ ax.annotate(
487
+ "criterion " + ("met" if j["converged"] else "not met"),
488
+ (1.0, j["target"]),
489
+ xycoords=("axes fraction", "data"),
490
+ ha="right",
491
+ va="bottom",
492
+ fontsize="small",
493
+ color="#666666",
494
+ )
495
+ if rel:
496
+ ax.axhline(1.0, color="#888888", linestyle=":", linewidth=1.0)
497
+ ax.set_yscale("log")
498
+ ax.set_xlabel("adaptive pass")
499
+ ax.set_ylabel("$\\Delta$ / target" if rel else tex(jobs[0]["criterion"] or "delta"))
500
+ ax.xaxis.set_major_locator(MaxNLocator(integer=True))
501
+ ax.xaxis.set_minor_locator(plt.NullLocator())
502
+ if len(jobs) > 1:
503
+ ax.legend(frameon=False, fontsize="small")
504
+ elif not own and None not in jobs[0]["elements"]:
505
+ pa, el = np.asarray(jobs[0]["passes"], float), np.asarray(jobs[0]["elements"], float)
506
+ top = ax.secondary_xaxis("top", functions=(lambda p: np.interp(p, pa, el), lambda n: np.interp(n, el, pa)))
507
+ top.set_xlabel("solved tets")
508
+ if own:
509
+ ax.set_title("(a) per pass")
510
+ bx = axes[1]
511
+ for i, j in enumerate(jobs):
512
+ _, e, y = series(j)
513
+ col = COLORS[i % len(COLORS)]
514
+ if e and None not in e:
515
+ bx.plot(e, y, "o-", color=col, ms=4)
516
+ if j["target"] is not None and not rel:
517
+ bx.axhline(j["target"], color=col, linestyle=":", linewidth=1.0)
518
+ if rel:
519
+ bx.axhline(1.0, color="#888888", linestyle=":", linewidth=1.0)
520
+ bx.set_xscale("log")
521
+ bx.set_yscale("log")
522
+ bx.xaxis.set_minor_formatter(plt.NullFormatter())
523
+ bx.set_xlabel("solved tets")
524
+ bx.set_title("(b) per mesh size")
525
+ if modes:
526
+ cx = axes[2]
527
+ for i, (m, fs) in enumerate(modes.items()):
528
+ d = (np.asarray(fs) - fs[-1]) * 1e3
529
+ cx.plot(range(1, len(fs) + 1), d, "o-", ms=3, color=COLORS[i % len(COLORS)], label=f"mode {m}")
530
+ cx.axhline(0, color="#888888", linewidth=0.8)
531
+ cx.set_xlabel("adaptive pass")
532
+ cx.set_ylabel("$f - f_{\\mathrm{last}}$ (MHz)")
533
+ cx.xaxis.set_major_locator(MaxNLocator(integer=True))
534
+ cx.xaxis.set_minor_locator(plt.NullLocator())
535
+ cx.legend(frameon=False, fontsize="x-small")
536
+ cx.set_title("(c) mode frequencies")
537
+ return ax
538
+
539
+
540
+ def convergence_specs(results_or_job, label: str | None = None, tab: str = "plots") -> list[dict]:
541
+ """Dashboard specs of a job's convergence: delta per pass with the criterion line, delta against the tet count
542
+ and, for eigenmode jobs, each mode's frequency per pass."""
543
+ specs = []
544
+ for j in _conv_inputs(results_or_job, label):
545
+ key = re.sub(r"[^A-Za-z0-9]+", "_", j["label"]).strip("_").lower()
546
+ pts = _delta_points(j)
547
+ if not pts:
548
+ continue
549
+ crit = j["criterion"] or "delta"
550
+ ref = [{"axis": "y", "value": j["target"], "label": "criterion"}] if j["target"] is not None else None
551
+ status = "converged" if j["converged"] else "stopped before the criterion"
552
+ specs.append(
553
+ xy_spec(
554
+ f"conv_{key}",
555
+ f"Convergence: {j['label']}",
556
+ tab,
557
+ [{"name": crit, "x": [p for p, _, _ in pts], "y": [v for _, _, v in pts], "kind": "line"}],
558
+ "Adaptive pass",
559
+ crit,
560
+ ref,
561
+ log_y=True,
562
+ caption=f"{crit}, target {j['target']}: {status} after {j['passes'][-1]} passes",
563
+ )
564
+ )
565
+ if len(pts) > 1 and all(e is not None for _, e, _ in pts):
566
+ specs.append(
567
+ xy_spec(
568
+ f"conv_{key}_mesh",
569
+ f"Convergence against mesh: {j['label']}",
570
+ tab,
571
+ [{"name": crit, "x": [e for _, e, _ in pts], "y": [v for _, _, v in pts], "kind": "line"}],
572
+ "Solved tets",
573
+ crit,
574
+ ref,
575
+ log_y=True,
576
+ caption="criterion against the mesh size of each pass",
577
+ )
578
+ )
579
+ if j["mode_GHz"]:
580
+ ser = [
581
+ {
582
+ "name": f"mode {m}",
583
+ "x": list(range(1, len(fs) + 1)),
584
+ "y": [round((v - fs[-1]) * 1e3, 4) for v in fs],
585
+ "kind": "line",
586
+ }
587
+ for m, fs in j["mode_GHz"].items()
588
+ ]
589
+ specs.append(
590
+ xy_spec(
591
+ f"conv_{key}_modes",
592
+ f"Mode frequencies per pass: {j['label']}",
593
+ tab,
594
+ ser,
595
+ "Adaptive pass",
596
+ "f - f(last pass) (MHz)",
597
+ caption="each mode's frequency relative to its last-pass value",
598
+ )
599
+ )
600
+ return specs
601
+
602
+
603
+ def _notch_model(f, f0, ql, qc_abs, phi, amp=1.0):
604
+ import numpy as np # pylint: disable=import-outside-toplevel
605
+
606
+ return amp * np.abs(1 - (ql / qc_abs) * np.exp(1j * phi) / (1 + 2j * ql * (f / f0 - 1)))
607
+
608
+
609
+ def _s21_trace(results, f_GHz=None, s21=None, job_dir=None):
610
+ """(f_GHz, complex S21) from explicit arrays, or the ``*_SMatrix.s2p`` next to a job's results; else None."""
611
+ import numpy as np # pylint: disable=import-outside-toplevel
612
+
613
+ if f_GHz is not None and s21 is not None:
614
+ return np.asarray(f_GHz, float), np.asarray(s21, complex)
615
+ cands = []
616
+ if job_dir:
617
+ cands.append(Path(job_dir))
618
+ if isinstance(results, (str, Path)):
619
+ p = Path(results)
620
+ base = p if p.is_dir() else p.parent
621
+ cands += [base, base.parent]
622
+ for base in cands:
623
+ for fn in sorted(base.glob("*_SMatrix.s2p")) if base.is_dir() else []:
624
+ from quantcore_circuits.analysis.results import parse_touchstone # pylint: disable=import-outside-toplevel
625
+
626
+ f, s, _ = parse_touchstone(fn)
627
+ return f, s[:, 1, 0]
628
+ return None
629
+
630
+
631
+ def _notch_window(n: dict, trace):
632
+ """(f0, Q_l, |Q_c|, phi, half-width GHz, amplitude of the trace's baseline or 1) of one notch fit."""
633
+ import numpy as np # pylint: disable=import-outside-toplevel
634
+
635
+ f0, ql, phi = n["f0_GHz"], n["Q_loaded"], n.get("phi", 0.0)
636
+ half = 8 * f0 / ql # eight linewidths each side
637
+ amp = 1.0
638
+ if trace is not None:
639
+ f, s = trace
640
+ amp = float(np.abs(s[np.abs(f - f0) <= max(half, 25 * f0 / ql)]).max())
641
+ return f0, ql, n["Q_coupling"] * math.cos(phi), phi, half, amp
642
+
643
+
644
+ def plot_s21_fit(results, ax=None, f_GHz=None, s21=None, job_dir=None, notch: str | None = None):
645
+ """|S21| of a driven job with its notch fit, the fitted f0, kappa_ext and Q_i written on the panel.
646
+
647
+ ``results``: the ``results.json`` dict (``sparams.notch`` holds the fits), a path to it, or a job folder with an
648
+ ``*_SMatrix.s2p`` (the trace is read and re-fitted with :func:`analysis.results.fit_notches`). The trace itself is
649
+ not stored in ``results.json``: pass ``f_GHz`` / ``s21`` or ``job_dir`` to draw the data, otherwise only the fitted
650
+ model curve (normalised to 1 off resonance) is shown and the title says so. ``notch``: one fit's key; default all
651
+ fits, one panel each (up to 4) when ``ax`` is not given, the first when it is. Returns the first axis.
652
+ """
653
+ import numpy as np # pylint: disable=import-outside-toplevel
654
+
655
+ trace = _s21_trace(results, f_GHz, s21, job_dir)
656
+ fits: dict = {}
657
+ try:
658
+ fits = (_read_results(results).get("sparams") or {}).get("notch") or {}
659
+ except FileNotFoundError:
660
+ pass
661
+ if trace is not None and not fits:
662
+ from quantcore_circuits.analysis.results import fit_notches # pylint: disable=import-outside-toplevel
663
+
664
+ fits = {f"S21#{i + 1}": fit for i, fit in enumerate(fit_notches(*trace))}
665
+ if not fits:
666
+ raise ValueError("no notch fit in the results (and no trace to fit)")
667
+ keys = [notch] if notch else list(fits)
668
+ keys = keys[: 1 if ax is not None else 4]
669
+ if ax is None:
670
+ _, axes = figure("three_square" if len(keys) > 1 else "single", 1, len(keys))
671
+ axs = [axes] if len(keys) == 1 else list(axes.flat)
672
+ else:
673
+ axs = [ax]
674
+ for a, k in zip(axs, keys):
675
+ n = fits[k]
676
+ f0, ql, qc, phi, half, amp = _notch_window(n, trace)
677
+ if trace is not None:
678
+ f, s = trace
679
+ sel = np.abs(f - f0) <= half
680
+ if sel.sum() < 5:
681
+ sel = np.ones_like(f, dtype=bool)
682
+ a.plot(f[sel], np.abs(s[sel]) / amp, ".", ms=3, color=COLORS[4], label="data")
683
+ fx = np.linspace(f[sel].min(), f[sel].max(), 800)
684
+ else:
685
+ fx = np.linspace(f0 - half, f0 + half, 800)
686
+ a.plot(fx, _notch_model(fx, f0, ql, qc, phi), "-", color=COLORS[0], label="notch fit")
687
+ a.axvline(f0, color="#888888", linestyle=":", linewidth=1.0)
688
+ a.set_xlabel("frequency (GHz)")
689
+ a.set_ylabel("$|S_{21}|$ (norm.)")
690
+ a.annotate(
691
+ f"$f_0$ = {f0:.4f} GHz\n$\\kappa_{{ext}}$ = {n['kappa_ext_MHz']:.3g} MHz\n$Q_i$ = {n['Q_internal']:.2g}",
692
+ (0.03, 0.05),
693
+ xycoords="axes fraction",
694
+ fontsize="small",
695
+ va="bottom",
696
+ )
697
+ a.set_title(tex(k) + ("" if trace is not None else " (fit only: trace not stored)"))
698
+ a.legend(frameon=False, fontsize="small", loc="lower right")
699
+ a.ticklabel_format(axis="x", useOffset=False)
700
+ return axs[0]
701
+
702
+
703
+ def s21_specs(results, f_GHz=None, s21=None, job_dir=None, tab: str = "plots", max_points: int = 400) -> list[dict]:
704
+ """Dashboard spec per |S21| notch: the data when a trace is available (decimated to ``max_points``), the fit
705
+ curve, and the fitted f0 / kappa_ext in the caption."""
706
+ import numpy as np # pylint: disable=import-outside-toplevel
707
+
708
+ res = _read_results(results)
709
+ trace = _s21_trace(results, f_GHz, s21, job_dir)
710
+ specs = []
711
+ for k, n in ((res.get("sparams") or {}).get("notch") or {}).items():
712
+ f0, ql, qc, phi, half, amp = _notch_window(n, trace)
713
+ fx = np.linspace(f0 - half, f0 + half, 200)
714
+ series = []
715
+ if trace is not None:
716
+ f, s = trace
717
+ sel = np.where(np.abs(f - f0) <= half)[0]
718
+ sel = sel[:: max(1, len(sel) // max_points)]
719
+ series.append(
720
+ {
721
+ "name": "data",
722
+ "x": [round(float(v), 6) for v in f[sel]],
723
+ "y": [round(float(v), 5) for v in np.abs(s[sel]) / amp],
724
+ "kind": "scatter",
725
+ }
726
+ )
727
+ series.append(
728
+ {
729
+ "name": "notch fit",
730
+ "x": [round(float(v), 6) for v in fx],
731
+ "y": [round(float(v), 5) for v in _notch_model(fx, f0, ql, qc, phi)],
732
+ "kind": "line",
733
+ }
734
+ )
735
+ specs.append(
736
+ xy_spec(
737
+ "s21_" + re.sub(r"[^A-Za-z0-9]+", "_", k).strip("_").lower(),
738
+ f"|S21| notch {k}",
739
+ tab,
740
+ series,
741
+ "Frequency (GHz)",
742
+ "|S21| (norm.)",
743
+ [{"axis": "x", "value": round(f0, 6), "label": f"f0 {f0:.4f} GHz"}],
744
+ caption=f"f0 {f0:.5f} GHz, kappa_ext {n['kappa_ext_MHz']:.3g} MHz, Q_i {n['Q_internal']:.3g}"
745
+ + ("" if trace is not None else "; fit only, the trace is not stored in results.json"),
746
+ )
747
+ )
748
+ return specs
749
+
750
+
751
+ def plot_epr(epr_result: dict, ax=None):
752
+ """Energy participation of an EPR result (:mod:`analysis.epr_lumped`): bars of p per mode, one colour per
753
+ junction (log scale: resonator modes sit near 1e-3), and without ``ax`` also the chi matrix of the modes that
754
+ touch a junction (signed, symmetric-log colour, values printed). Returns the first axis."""
755
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
756
+ import numpy as np # pylint: disable=import-outside-toplevel
757
+ from matplotlib.colors import SymLogNorm # pylint: disable=import-outside-toplevel
758
+
759
+ p = np.asarray(epr_result["p"], float)
760
+ modes = epr_result["modes"]
761
+ juncs = epr_result["junctions"]
762
+ own = ax is None
763
+ if own:
764
+ _, axes = figure("two", 1, 2)
765
+ ax, bx = list(axes.flat)
766
+ width = 0.8 / max(len(juncs), 1)
767
+ for j, name in enumerate(juncs):
768
+ xs = np.arange(len(modes)) + (j - (len(juncs) - 1) / 2) * width
769
+ ax.bar(xs, np.clip(p[:, j], 1e-6, None), width, label=tex(name), color=COLORS[j % len(COLORS)])
770
+ ax.set_yscale("log")
771
+ ax.set_ylim(1e-4, 30)
772
+ ax.set_xticks(range(len(modes)), [tex(f"{m['label']} {m['f_GHz']:.2f}") for m in modes], rotation=30, ha="right")
773
+ ax.tick_params(axis="x", which="minor", bottom=False, top=False)
774
+ ax.set_ylabel("participation $p_{mj}$")
775
+ ax.set_title(("(a) " if own else "") + "method: " + str(epr_result["method"]))
776
+ if len(juncs) > 1:
777
+ ax.legend(frameon=False, fontsize="small", ncols=2, loc="upper right")
778
+ if own:
779
+ act = [i for i in range(len(modes)) if p[i].max(initial=0.0) > 1e-4]
780
+ chi = np.asarray(epr_result["chi_MHz"], float)[np.ix_(act, act)] if act else np.zeros((1, 1))
781
+ top = max(float(np.abs(chi).max()), 1e-6)
782
+ im = bx.imshow(chi, cmap="RdBu_r", norm=SymLogNorm(linthresh=max(top * 1e-3, 1e-6), vmin=-top, vmax=top))
783
+ for (i, k), v in np.ndenumerate(chi):
784
+ bx.text(
785
+ k,
786
+ i,
787
+ f"{v:.2g}",
788
+ ha="center",
789
+ va="center",
790
+ fontsize="xx-small",
791
+ color="white" if abs(v) > 0.3 * top else "#111111",
792
+ )
793
+ names = [tex(modes[i]["label"]) for i in act]
794
+ bx.set_xticks(range(len(act)), names, rotation=30, ha="right")
795
+ bx.set_yticks(range(len(act)), names)
796
+ bx.minorticks_off()
797
+ bx.tick_params(length=0)
798
+ bx.set_title("(b) $\\chi$ matrix (MHz), diagonal $\\alpha$")
799
+ plt.colorbar(im, ax=bx, label="MHz")
800
+ return ax
801
+
802
+
803
+ def epr_specs(epr_result: dict, tab: str = "plots", prefix: str = "epr") -> list[dict]:
804
+ """Dashboard specs of an EPR result: participation bars (mode -> junction) and the chi matrix (diagonal alpha)."""
805
+ bars = [
806
+ {
807
+ "label": f"{m['label']} {m['f_GHz']:.2f} GHz",
808
+ "values": {j: round(float(v), 6) for j, v in zip(epr_result["junctions"], row)},
809
+ }
810
+ for m, row in zip(epr_result["modes"], epr_result["p"])
811
+ ]
812
+ act = [i for i, row in enumerate(epr_result["p"]) if max(row, default=0.0) > 1e-4]
813
+ names = [epr_result["modes"][i]["label"] for i in act]
814
+ vals = [[round(float(epr_result["chi_MHz"][i][k]), 4) for k in act] for i in act]
815
+ method = epr_result["method"]
816
+ return [
817
+ bar_spec(
818
+ f"{prefix}_p",
819
+ f"EPR participation ({method})",
820
+ tab,
821
+ bars,
822
+ "p_mj",
823
+ caption="energy participation of each junction in each mode",
824
+ ),
825
+ heatmap_spec(
826
+ f"{prefix}_chi",
827
+ f"EPR chi matrix ({method})",
828
+ tab,
829
+ names,
830
+ names,
831
+ vals,
832
+ "MHz",
833
+ caption="diagonal: self-Kerr alpha; off-diagonal: cross-Kerr chi",
834
+ ),
835
+ ]
836
+
837
+
838
+ def fem_specs(jobs, tab: str = "plots") -> list[dict]:
839
+ """All FEM-result plot specs for the dashboard. ``jobs``: results dicts or ``FilledCircuit.jobs`` entries (which
840
+ hold ``results``). Per job: its convergence set, the S21 notches of a driven job and the EPR of an eigenmode job
841
+ that recorded it."""
842
+ specs: list[dict] = []
843
+ seen: set[str] = set()
844
+ for j in jobs or []:
845
+ res = j.get("results") if isinstance(j, dict) and "results" in j and "convergence" not in j else j
846
+ if not isinstance(res, dict) or not res:
847
+ continue
848
+ group = res.get("group") or (j.get("group") if isinstance(j, dict) else "")
849
+ name = f"{res.get('analysis', 'job')} ({group})" if group else res.get("analysis", "job")
850
+ new = convergence_specs(res, name, tab) if (res.get("convergence") or {}).get("passes") else []
851
+ if (res.get("sparams") or {}).get("notch"):
852
+ new += s21_specs(res, tab=tab)
853
+ if (res.get("epr") or {}).get("p_mj"):
854
+ try:
855
+ from quantcore_circuits.analysis.epr_lumped import epr_from_job # pylint: disable=import-outside-toplevel
856
+
857
+ new += epr_specs(epr_from_job(res), tab)
858
+ except (KeyError, ValueError, ImportError): # a plot must not stop the analysis
859
+ pass
860
+ for s in new:
861
+ if s["id"] not in seen:
862
+ seen.add(s["id"])
863
+ specs.append(s)
864
+ return specs
865
+
866
+
867
+ def save(fig, path, formats=("pdf", "png")) -> list[Path]:
868
+ """Save ``fig`` next to ``path`` in each format (PDF for LaTeX, PNG for the dashboard/notebook)."""
869
+ path = Path(path)
870
+ path.parent.mkdir(parents=True, exist_ok=True)
871
+ out = []
872
+ for fmt in formats:
873
+ p = path.with_suffix(f".{fmt}")
874
+ fig.savefig(p)
875
+ out.append(p)
876
+ return out