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,397 @@
1
+ """Scripts that run *inside* AEDT (2024 R1/R2): batch ``ansysedt -ng -RunScriptAndExit``, a new window
2
+ ``ansysedt -RunScript``, or ``oDesktop.RunScriptWithArguments`` in an attached session (:mod:`.aedt_session`). The
3
+ status file ends with ``end`` (a window / attached session stays open, so the process does not end with the run).
4
+
5
+ One source, two file names in the job's ``scripts/`` folder:
6
+
7
+ * ``qcc_render.py`` — import the KQC simulation (KQC ``import_simulation_geometry.py``), fix the ports KQC leaves
8
+ unassigned, add the Q3D π-model and reports, save ``<sim>_project.aedt``. No solve.
9
+ * ``qcc_solve.py`` — the same, then ``AnalyzeAll``, KQC ``export_solution_data.py`` (C-matrix json, ``.eig``,
10
+ Touchstone) and ``<sim>_project_qcc.json`` (excitation order, variables, convergence, and for eigenmode jobs with
11
+ junction lines the pyEPR field integrals per mode).
12
+ * ``qcc_collect.py`` — no import, no solve: the exports of ``qcc_solve.py`` from the job's saved project as it is now
13
+ (e.g. after the user changed the setup in AEDT and solved again there). In the user's open AEDT: *Tools ▸ Run
14
+ Script…* ``scripts/qcc_collect.py`` (it finds the job from its own folder; the project open in that AEDT is used,
15
+ and nothing is saved). Headless: ``qcc hfss collect JOB`` opens the saved project in a new non-graphical AEDT.
16
+
17
+ Port fix-ups (KQC's importer handles only junction ports in eigenmode, and makes every port a terminal port in a
18
+ driven design):
19
+
20
+ * eigenmode: every non-junction port with a resistance (the 50 Ω edge / pad terminations the builder adds) becomes a
21
+ ``Lumped RLC`` boundary R = 50 Ω, so the eigenmode Q carries the external loss (κ);
22
+ * driven (HFSS terminal network): junction ports are deleted as excitations and become ``Lumped RLC`` L = ``Lj_<n>``,
23
+ C = ``Cj_<n>`` (design variables), so the S-matrix has only the real (pad / wave) ports.
24
+
25
+ EPR (``eigenmode_epr``; KQC draws a ``Junction<n>`` line over each junction): per mode, pyEPR's own calculator stack
26
+ (``DistributedAnalysis.calc_energy_electric/_magnetic`` and ``calc_current_using_line_voltage``): U_E = ∫Re(E·εE*),
27
+ U_H = ∫Re(H·μH*), U_E per substrate volume, and the junction line voltage (real and imaginary parts). The
28
+ participations and the Hamiltonian are computed afterwards outside AEDT (:mod:`quantcore_circuits.analysis.epr`).
29
+ This replaces KQC's ``run_pyepr_t1_estimate.py``, which attaches to a *running* AEDT over COM and ends with
30
+ ``QuitApplication()`` (it would close a user's open AEDT window).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ from pathlib import Path
36
+
37
+ RENDER_SCRIPT = "qcc_render.py"
38
+ SOLVE_SCRIPT = "qcc_solve.py"
39
+ COLLECT_SCRIPT = "qcc_collect.py"
40
+ STATUS_FILE = {"render": "qcc_render_status.txt", "solve": "qcc_solve_status.txt", "collect": "qcc_collect_status.txt"}
41
+ SCRIPT_MODE = {RENDER_SCRIPT: "render", SOLVE_SCRIPT: "solve", COLLECT_SCRIPT: "collect"}
42
+ EXTRAS_SUFFIX = "_project_qcc.json"
43
+
44
+ # IronPython 2.7 and CPython 3 compatible (AEDT's script engines): no f-strings, no keyword-only syntax.
45
+ AEDT_SOURCE = r'''# qcc: import a KQC simulation into AEDT; as qcc_solve.py also solve and export
46
+ # (quantcore_circuits.sim_tools.aedt_scripts). Sub-scripts are exec'd in-process so that their tracebacks
47
+ # land in the status file.
48
+ import json
49
+ import os
50
+ import sys
51
+ import time
52
+ import traceback
53
+
54
+ import ScriptEnv
55
+
56
+ ScriptEnv.Initialize("Ansoft.ElectronicsDesktop")
57
+ try:
58
+ jsonfile = ScriptArgument or ""
59
+ except NameError: # Tools > Run Script without arguments
60
+ jsonfile = ""
61
+ MODE = None
62
+ if "|" in jsonfile: # "<mode>|<sim json>" (optional; for script hosts that do not set __file__)
63
+ MODE, jsonfile = jsonfile.split("|", 1)
64
+ try:
65
+ scriptpath = os.path.dirname(os.path.abspath(__file__))
66
+ _own = os.path.basename(__file__)
67
+ MODE = MODE or ("solve" if _own.startswith("qcc_solve") else "collect" if _own.startswith("qcc_collect")
68
+ else "render")
69
+ except NameError:
70
+ scriptpath = os.path.join(os.path.dirname(os.path.abspath(jsonfile)), "scripts")
71
+ MODE = MODE or "solve"
72
+ if not jsonfile: # the job's simulation json, from job.json next to the scripts folder
73
+ with open(os.path.join(os.path.dirname(scriptpath), "job.json"), "r") as fp:
74
+ jsonfile = os.path.join(os.path.dirname(scriptpath), json.load(fp)["simulation_name"] + ".json")
75
+ elif not os.path.isabs(jsonfile) and not os.path.exists(jsonfile):
76
+ jsonfile = os.path.join(os.path.dirname(scriptpath), jsonfile)
77
+ path = os.path.abspath(os.path.dirname(jsonfile))
78
+ basename = os.path.splitext(os.path.basename(jsonfile))[0]
79
+ status = open(os.path.join(path, "qcc_%s_status.txt" % MODE), "w")
80
+
81
+
82
+ def log(msg):
83
+ status.write(msg + "\n")
84
+ status.flush()
85
+
86
+
87
+ def step(name, script, args=None):
88
+ log("step " + name)
89
+ t0 = time.time()
90
+ env = {"__file__": os.path.join(scriptpath, script), "__name__": "__main__", "oDesktop": oDesktop}
91
+ if args is not None:
92
+ env["ScriptArgument"] = args
93
+ with open(os.path.join(scriptpath, script)) as fp:
94
+ code = compile(fp.read(), os.path.join(scriptpath, script), "exec")
95
+ exec(code, env)
96
+ log("ok %s %.1f s" % (name, time.time() - t0))
97
+
98
+
99
+ def coords(p, units):
100
+ return ["%.32e%s" % (x, units) for x in p]
101
+
102
+
103
+ def add_variable(oDesign, name, value):
104
+ oDesign.ChangeProperty(
105
+ [
106
+ "NAME:AllTabs",
107
+ [
108
+ "NAME:LocalVariableTab",
109
+ ["NAME:PropServers", "LocalVariables"],
110
+ ["NAME:NewProps", ["NAME:" + name, "PropType:=", "VariableProp", "UserDef:=", True, "Value:=", value]],
111
+ ],
112
+ ]
113
+ )
114
+
115
+
116
+ def lumped_rlc(oDesign, port, units, name, r=None, l_var=None, c_var=None):
117
+ oEditor = oDesign.SetActiveEditor("3D Modeler")
118
+ poly = "Port%d" % port["number"]
119
+ args = [
120
+ "NAME:" + name,
121
+ "Objects:=",
122
+ [poly],
123
+ [
124
+ "NAME:CurrentLine",
125
+ "Coordinate System:=",
126
+ "Global",
127
+ "Start:=",
128
+ coords(port["signal_location"], units),
129
+ "End:=",
130
+ coords(port["ground_location"], units),
131
+ ],
132
+ "RLC Type:=",
133
+ "Parallel",
134
+ "UseResist:=",
135
+ r is not None,
136
+ ]
137
+ if r is not None:
138
+ args += ["Resistance:=", "%.12gohm" % r]
139
+ args += ["UseInduct:=", l_var is not None]
140
+ if l_var is not None:
141
+ args += ["Inductance:=", l_var]
142
+ args += ["UseCap:=", c_var is not None]
143
+ if c_var is not None:
144
+ args += ["Capacitance:=", c_var]
145
+ args += ["Faces:=", [int(oEditor.GetFaceIDs(poly)[0])]]
146
+ oDesign.GetModule("BoundarySetup").AssignLumpedRLC(args)
147
+
148
+
149
+ def boundaries(oDesign):
150
+ try:
151
+ return [str(b) for b in oDesign.GetModule("BoundarySetup").GetBoundaries()]
152
+ except Exception:
153
+ return []
154
+
155
+
156
+ def fix_ports(oDesign, data, tool, units):
157
+ """Eigenmode: 50 ohm terminations as Lumped RLC; driven: junction ports -> Lumped RLC L/C (see module doc)."""
158
+ oBoundary = oDesign.GetModule("BoundarySetup")
159
+ for port in sorted(data.get("ports", []), key=lambda p: p["number"]):
160
+ n = port["number"]
161
+ if "polygon" not in port:
162
+ continue
163
+ if tool == "eigenmode" and not port.get("junction") and port.get("resistance"):
164
+ lumped_rlc(oDesign, port, units, "LumpRLC_term_%d" % n, r=float(port["resistance"]))
165
+ log("fix Port%d: 50 ohm termination (Lumped RLC R=%g ohm)" % (n, float(port["resistance"])))
166
+ elif tool == "hfss" and port.get("junction"):
167
+ before = boundaries(oDesign)
168
+ try:
169
+ oBoundary.DeleteBoundaries([str(n)])
170
+ except Exception:
171
+ log("warn could not delete excitation %d\n%s" % (n, traceback.format_exc()))
172
+ add_variable(oDesign, "Lj_%d" % n, "%.32eH" % port["inductance"])
173
+ add_variable(oDesign, "Cj_%d" % n, "%.32efarad" % port["capacitance"])
174
+ lumped_rlc(oDesign, port, units, "LumpRLC_jj_%d" % n, l_var="Lj_%d" % n, c_var="Cj_%d" % n)
175
+ log("fix Port%d: junction excitation -> Lumped RLC L=Lj_%d C=Cj_%d (boundaries before: %s)"
176
+ % (n, n, n, ",".join(before)))
177
+
178
+
179
+ def variables(oDesign):
180
+ out = []
181
+ for v in oDesign.GetVariables():
182
+ out += [str(v) + ":=", str(oDesign.GetVariableValue(v))]
183
+ return out
184
+
185
+
186
+ def epr_energies(oDesign, data, setup="Setup1 : LastAdaptive"):
187
+ """pyEPR's calculator stack per eigenmode (field energies, junction line voltages)."""
188
+ calc = oDesign.GetModule("FieldsReporter")
189
+ sols = oDesign.GetModule("Solutions")
190
+ oEditor = oDesign.SetActiveEditor("3D Modeler")
191
+ n_modes = int(data["analysis_setup"]["n_modes"])
192
+ lv = variables(oDesign)
193
+ juncs = [p for p in data.get("ports", []) if p.get("junction")]
194
+ lines = [str(o) for o in oEditor.GetMatchedObjectName("Junction*")]
195
+ volumes = [str(o) for o in oEditor.GetMatchedObjectName("substrate*")]
196
+
197
+ def ev(stack):
198
+ calc.CalcStack("clear")
199
+ for fn, arg in stack:
200
+ f = getattr(calc, fn)
201
+ if isinstance(arg, (list, tuple)):
202
+ f(*arg)
203
+ else:
204
+ f(arg)
205
+ args = lv + ["Phase:=", "0deg"]
206
+ calc.ClcEval(setup, args)
207
+ val = float(calc.GetTopEntryValue(setup, args)[0])
208
+ calc.CalcStack("clear")
209
+ return val
210
+
211
+ def energy(qty, material, volume):
212
+ return ev([("EnterQty", qty), ("ClcMaterial", (material, "mult")), ("EnterQty", qty), ("CalcOp", "Conj"),
213
+ ("CalcOp", "Dot"), ("CalcOp", "Real"), ("EnterVol", volume), ("CalcOp", "Integrate")])
214
+
215
+ def line_voltage(part, line):
216
+ return ev([("EnterQty", "E"), ("CalcOp", part), ("EnterLine", line), ("CalcOp", "Tangent"),
217
+ ("CalcOp", "Dot"), ("EnterLine", line), ("CalcOp", "Integrate")])
218
+
219
+ modes = []
220
+ for m in range(1, n_modes + 1):
221
+ sols.EditSources(
222
+ [
223
+ ["FieldType:=", "EigenPeakElectricField"],
224
+ [
225
+ "Name:=",
226
+ "Modes",
227
+ "Magnitudes:=",
228
+ ["1" if i == m else "0" for i in range(1, n_modes + 1)],
229
+ "Phases:=",
230
+ ["0" for i in range(1, n_modes + 1)],
231
+ ],
232
+ ]
233
+ )
234
+ rec = {"mode": m, "junctions": {}, "U_E_volumes": {}}
235
+ try:
236
+ rec["freq_Hz"] = ev([("EnterOutputVar", ("Freq", "Complex")), ("CalcOp", "Real")])
237
+ except Exception:
238
+ log("warn mode %d: Freq output variable\n%s" % (m, traceback.format_exc()))
239
+ rec["U_E"] = energy("E", "Permittivity (epsi)", "AllObjects")
240
+ rec["U_H"] = energy("H", "Permeability (mu)", "AllObjects")
241
+ for v in volumes:
242
+ rec["U_E_volumes"][v] = energy("E", "Permittivity (epsi)", v)
243
+ for p in juncs:
244
+ line = "Junction%d" % p["number"]
245
+ if line not in lines:
246
+ continue
247
+ rec["junctions"][str(p["number"])] = {
248
+ "line": line,
249
+ "V_re": line_voltage("Real", line),
250
+ "V_im": line_voltage("Imag", line),
251
+ "Lj_H": p.get("inductance"),
252
+ "Cj_F": p.get("capacitance"),
253
+ }
254
+ modes.append(rec)
255
+ log("epr mode %d: U_E %.5g U_H %.5g (%d junction lines)" % (m, rec["U_E"], rec["U_H"], len(rec["junctions"])))
256
+ return {"setup": setup, "variables": lv, "lines": lines, "volumes": volumes, "modes": modes}
257
+
258
+
259
+ def export_convergence(oDesign, design_type, filename):
260
+ # Q3D wants the solution kind ("CG" = capacitance/conductance), as pyaedt's export_convergence does
261
+ tries = [("Setup1", "", filename)] if design_type == "HFSS" else [("Setup1", "", "CG", filename, True)]
262
+ for args in tries:
263
+ try:
264
+ oDesign.ExportConvergence(*args)
265
+ return True
266
+ except Exception:
267
+ continue
268
+ return False
269
+
270
+
271
+ def export_convergence_reports(oDesign, prefix):
272
+ """KQC's convergence reports (eigenmode: re(Mode(n)) per adaptive pass; driven: S per pass) as CSV files."""
273
+ import re
274
+
275
+ out = {}
276
+ rs = oDesign.GetModule("ReportSetup")
277
+ for name in rs.GetAllReportNames():
278
+ name = str(name)
279
+ if "onvergence" not in name:
280
+ continue
281
+ fn = os.path.join(path, prefix + "_" + re.sub("[^A-Za-z0-9]+", "_", name).strip("_") + ".csv")
282
+ try:
283
+ rs.ExportToFile(name, fn, False)
284
+ out[name] = os.path.basename(fn)
285
+ except Exception:
286
+ log("warn report %s\n%s" % (name, traceback.format_exc()))
287
+ return out
288
+
289
+
290
+ def messages(severity=1):
291
+ """AEDT message-window lines (warnings and errors by default): batch mode has no window to read them in."""
292
+ try:
293
+ return [str(m).strip() for m in oDesktop.GetMessages("", "", severity)]
294
+ except Exception:
295
+ return []
296
+
297
+
298
+ extras = {"mode": MODE}
299
+ try:
300
+ extras["python"] = sys.version.split()[0]
301
+ extras["aedt"] = str(oDesktop.GetVersion())
302
+ log("python %s | aedt %s | mode %s" % (extras["python"], extras["aedt"], MODE))
303
+ with open(jsonfile, "r") as fp:
304
+ data = json.load(fp)
305
+ tool = data.get("ansys_tool", "hfss")
306
+ units = data.get("units", "um")
307
+ extras["tool"] = tool
308
+ if MODE == "collect": # the saved project as it is now: no import, no solve, nothing saved
309
+ log("step open")
310
+ project_name = basename + "_project"
311
+ oProject = None
312
+ for p in oDesktop.GetProjects():
313
+ if str(p.GetName()) == project_name:
314
+ oProject = p
315
+ if oProject is None:
316
+ oProject = oDesktop.OpenProject(os.path.join(path, project_name + ".aedt"))
317
+ oDesktop.SetActiveProject(project_name)
318
+ oDesign = oProject.GetActiveDesign()
319
+ if oDesign is None:
320
+ oDesign = oProject.SetActiveDesign(str(oProject.GetChildNames()[0]))
321
+ log("ok open " + project_name)
322
+ extras["collected"] = time.strftime("%Y-%m-%dT%H:%M:%S")
323
+ else:
324
+ step("import", "import_simulation_geometry.py", jsonfile)
325
+ oProject = oDesktop.GetActiveProject()
326
+ oDesign = oProject.GetActiveDesign()
327
+ fix_ports(oDesign, data, tool, units)
328
+ if tool == "q3d" or data.get("capacitance_export", False):
329
+ step("pi_model", "create_capacitive_pi_model.py")
330
+ try:
331
+ step("reports", "create_reports.py")
332
+ except Exception: # reports are optional
333
+ log("warn reports\n" + traceback.format_exc())
334
+ oProject.SaveAs(os.path.join(path, basename + "_project.aedt"), True)
335
+ log("saved " + basename + "_project.aedt")
336
+ extras["boundaries"] = boundaries(oDesign)
337
+ if MODE in ("solve", "collect"):
338
+ if MODE == "solve":
339
+ log("step solve")
340
+ t0 = time.time()
341
+ try:
342
+ oDesign.AnalyzeAll()
343
+ log("ok solve %.1f s" % (time.time() - t0))
344
+ except Exception: # e.g. out of memory in a late pass: keep what the completed passes left
345
+ extras["solve_error"] = [m for m in messages(2)]
346
+ log("error solve %.1f s (exporting what exists)\n%s" % (time.time() - t0, traceback.format_exc()))
347
+ for line in extras["solve_error"]:
348
+ log("aedt: " + line)
349
+ extras["solve_seconds"] = round(time.time() - t0, 1)
350
+ oProject.Save()
351
+ try:
352
+ extras["convergence_reports"] = export_convergence_reports(oDesign, basename + "_project")
353
+ except Exception:
354
+ log("warn convergence reports\n" + traceback.format_exc())
355
+ step("export", "export_solution_data.py")
356
+ design_type = str(oDesign.GetDesignType())
357
+ extras["design_type"] = design_type
358
+ try:
359
+ extras["excitations"] = [str(x) for x in oDesign.GetModule("BoundarySetup").GetExcitations()]
360
+ except Exception:
361
+ log("warn excitations\n" + traceback.format_exc())
362
+ extras["variables"] = variables(oDesign)
363
+ conv = os.path.join(path, basename + "_project_convergence.txt")
364
+ extras["convergence_file"] = os.path.basename(conv) if export_convergence(oDesign, design_type, conv) else None
365
+ if tool == "eigenmode" and any(p.get("junction") for p in data.get("ports", [])):
366
+ if "pyepr" in data.get("simulation_flags", []):
367
+ try:
368
+ log("step epr")
369
+ t0 = time.time()
370
+ extras["epr"] = epr_energies(oDesign, data)
371
+ log("ok epr %.1f s" % (time.time() - t0))
372
+ except Exception:
373
+ log("error epr\n" + traceback.format_exc())
374
+ extras["messages"] = messages()
375
+ with open(os.path.join(path, basename + "_project_qcc.json"), "w") as fp:
376
+ json.dump(extras, fp, indent=1)
377
+ if MODE == "solve":
378
+ oProject.Save()
379
+ log("wrote " + basename + "_project_qcc.json")
380
+ log("done")
381
+ except Exception:
382
+ log("error\n" + traceback.format_exc())
383
+ for line in messages():
384
+ log("aedt: " + line)
385
+ log("end") # last line: a GUI / attached session stays open, so this marks the end of the run
386
+ status.close()
387
+ '''
388
+
389
+
390
+ def write_scripts(job_dir: str | Path) -> Path:
391
+ """Write ``qcc_render.py``, ``qcc_solve.py`` and ``qcc_collect.py`` into ``job_dir/scripts`` (next to KQC's AEDT
392
+ scripts)."""
393
+ scripts = Path(job_dir) / "scripts"
394
+ scripts.mkdir(parents=True, exist_ok=True)
395
+ for name in (RENDER_SCRIPT, SOLVE_SCRIPT, COLLECT_SCRIPT):
396
+ (scripts / name).write_text(AEDT_SOURCE, encoding="utf-8")
397
+ return scripts
@@ -0,0 +1,275 @@
1
+ """Where a qcc AEDT script runs: a new batch process, a new AEDT window, or an AEDT session that is already open.
2
+
3
+ ``aedt=`` (``hfss.render`` / ``hfss.solve_job`` / ``runner.run_job``, the tutorials' ``AEDT_MODE``; default from
4
+ ``QCC_AEDT_MODE``, else ``"batch"``):
5
+
6
+ * ``"batch"`` — a new non-graphical AEDT (``ansysedt -ng -RunScriptAndExit``), as before. Nothing to look at, but the
7
+ progress lines (pass, mesh, ΔF / ΔS / ΔC) are printed every ~30 s.
8
+ * ``"gui"`` — a new AEDT **window** (``ansysedt -RunScript``, no ``-ng``): you watch the import, the mesh, the
9
+ convergence plots and the results in it, and it stays open after the run (the project is saved). It is started
10
+ detached, so it survives a kernel restart.
11
+ * ``"attach"`` — run inside an AEDT 2024 R1+ window that is already open (the newest one, or ``aedt_pid=`` /
12
+ ``QCC_AEDT_PID``); if none is open, as ``"gui"``. The connection uses AEDT's own gRPC client
13
+ (``<AEDT>/PythonFiles/DesktopPlugin/PyDesktopPlugin.py``, shipped with AEDT 2024 R1; no extra Python package) in a
14
+ small helper process, which calls ``oDesktop.RunScriptWithArguments(qcc_solve.py, <sim>.json)`` and then only
15
+ releases the connection: the session, and every project in it (also the new one), stay open. The qcc script never
16
+ quits AEDT, and KQC's ``run_pyepr_t1_estimate.py`` (which does) is never run.
17
+
18
+ Rules: on a timeout only processes qcc started are killed (the batch AEDT, the ``gui`` window qcc opened, or the
19
+ attach helper — never an attached session; its solve then keeps running there). A project of the same job left open
20
+ by an earlier attached run is closed in that session before the new run (it would block the save).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import re
28
+ import subprocess
29
+ import sys
30
+ import time
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path
33
+
34
+ from quantcore_circuits.sim_tools.ansys import MIN_VERSION, aedt_version
35
+
36
+ AEDT_MODES = ("batch", "gui", "attach")
37
+ ENV_MODE = "QCC_AEDT_MODE"
38
+ ENV_PID = "QCC_AEDT_PID"
39
+ ENV_PROGRESS = "QCC_AEDT_PROGRESS"
40
+ ATTACH_HELPER = Path(__file__).with_name("aedt_attach.py")
41
+ GRPC_PORTS = range(50051, 50101) # where AEDT's gRPC server listens unless ``-grpcsrv`` says otherwise (as pyaedt)
42
+ _ALIASES = {"ng": "batch", "non-graphical": "batch", "nongraphical": "batch", "window": "gui", "new": "gui",
43
+ "graphical": "gui", "connect": "attach", "running": "attach"}
44
+
45
+ __all__ = [
46
+ "AEDT_MODES",
47
+ "AedtSession",
48
+ "find_sessions",
49
+ "launch_gui",
50
+ "pick_session",
51
+ "progress_interval",
52
+ "resolve_mode",
53
+ ]
54
+
55
+
56
+ def resolve_mode(aedt: str | None = None, graphical: bool = False) -> str:
57
+ """``aedt`` → one of :data:`AEDT_MODES`; None → ``graphical=True`` means ``"gui"``, else ``QCC_AEDT_MODE``, else
58
+ ``"batch"``."""
59
+ if aedt is None:
60
+ aedt = "gui" if graphical else (os.environ.get(ENV_MODE) or "batch")
61
+ mode = _ALIASES.get(str(aedt).strip().lower(), str(aedt).strip().lower())
62
+ if mode not in AEDT_MODES:
63
+ raise ValueError(f"aedt={aedt!r}: use one of {AEDT_MODES}")
64
+ return mode
65
+
66
+
67
+ def progress_interval(progress: float | None = None) -> float | None:
68
+ """Seconds between progress lines (``progress``, else ``QCC_AEDT_PROGRESS``, else 30); 0 / negative → None."""
69
+ if progress is None:
70
+ try:
71
+ progress = float(os.environ.get(ENV_PROGRESS, "30"))
72
+ except ValueError:
73
+ progress = 30.0
74
+ return float(progress) if progress and progress > 0 else None
75
+
76
+
77
+ # ---- running sessions ---------------------------------------------------------------------------------------------
78
+ @dataclass
79
+ class AedtSession:
80
+ pid: int
81
+ exe: Path | None
82
+ cmdline: list[str] = field(default_factory=list)
83
+ ports: list[int] = field(default_factory=list)
84
+ created: float | None = None
85
+
86
+ @property
87
+ def version(self) -> int | None:
88
+ return aedt_version(self.exe or (self.cmdline[0] if self.cmdline else ""))
89
+
90
+ @property
91
+ def graphical(self) -> bool:
92
+ return "-ng" not in [a.lower() for a in self.cmdline]
93
+
94
+ @property
95
+ def port(self) -> int | None:
96
+ """The gRPC port: ``-grpcsrv [host:]port`` on the command line, else a listening port in 50051–50100."""
97
+ args = [a.lower() for a in self.cmdline]
98
+ if "-grpcsrv" in args and args.index("-grpcsrv") + 1 < len(args):
99
+ try:
100
+ return int(self.cmdline[args.index("-grpcsrv") + 1].rsplit(":", 1)[-1])
101
+ except ValueError:
102
+ pass
103
+ grpc = sorted(p for p in self.ports if p in GRPC_PORTS)
104
+ return grpc[0] if grpc else None
105
+
106
+ @property
107
+ def plugin_dir(self) -> Path | None:
108
+ exe = self.exe or (Path(self.cmdline[0]) if self.cmdline else None)
109
+ return Path(exe).parent / "PythonFiles" / "DesktopPlugin" if exe else None
110
+
111
+ def describe(self) -> str:
112
+ v = self.version
113
+ name = f"20{v // 10} R{v % 10}" if v else "?"
114
+ return f"AEDT {name} pid {self.pid} (gRPC port {self.port})"
115
+
116
+
117
+ def parse_netstat(text: str) -> dict[int, list[int]]:
118
+ """``netstat -ano`` (Windows) → {pid: [listening TCP ports]}."""
119
+ out: dict[int, list[int]] = {}
120
+ for line in text.splitlines():
121
+ parts = line.split()
122
+ if len(parts) >= 5 and parts[0].upper() == "TCP" and parts[3].upper() == "LISTENING":
123
+ try:
124
+ port, pid = int(parts[1].rsplit(":", 1)[1]), int(parts[4])
125
+ except (ValueError, IndexError):
126
+ continue
127
+ out.setdefault(pid, [])
128
+ if port not in out[pid]:
129
+ out[pid].append(port)
130
+ return out
131
+
132
+
133
+ def _processes() -> list[dict]:
134
+ """``ansysedt`` processes: {pid, exe, cmdline, created}. psutil if installed, else CIM (Windows) / ps (POSIX)."""
135
+ try:
136
+ import psutil # pylint: disable=import-outside-toplevel
137
+ except ImportError:
138
+ psutil = None
139
+ out = []
140
+ if psutil is not None:
141
+ for p in psutil.process_iter(["pid", "name", "exe", "cmdline", "create_time"]):
142
+ if (p.info.get("name") or "").lower() in ("ansysedt.exe", "ansysedt"):
143
+ out.append({"pid": p.info["pid"], "exe": p.info.get("exe"), "cmdline": p.info.get("cmdline") or [],
144
+ "created": p.info.get("create_time")})
145
+ return out
146
+ if os.name == "nt":
147
+ ps = ("Get-CimInstance Win32_Process -Filter \"Name='ansysedt.exe'\" | Select-Object ProcessId,"
148
+ "ExecutablePath,CommandLine,@{n='Created';e={[double]($_.CreationDate.ToUniversalTime() - "
149
+ "[datetime]'1970-01-01').TotalSeconds}} | ConvertTo-Json -Compress")
150
+ r = subprocess.run(["powershell", "-NoProfile", "-Command", ps], capture_output=True, text=True, check=False)
151
+ try:
152
+ rows = json.loads(r.stdout or "[]")
153
+ except ValueError:
154
+ rows = []
155
+ for row in [rows] if isinstance(rows, dict) else rows:
156
+ out.append({"pid": row["ProcessId"], "exe": row.get("ExecutablePath"),
157
+ "cmdline": _split_cmdline(row.get("CommandLine") or ""), "created": row.get("Created")})
158
+ return out
159
+ r = subprocess.run(["ps", "-eo", "pid=,args="], capture_output=True, text=True, check=False)
160
+ for line in r.stdout.splitlines():
161
+ pid, _, args = line.strip().partition(" ")
162
+ if "ansysedt" in args.split(" ", 1)[0]:
163
+ out.append({"pid": int(pid), "exe": args.split(" ", 1)[0], "cmdline": args.split(), "created": None})
164
+ return out
165
+
166
+
167
+ def _split_cmdline(cmd: str) -> list[str]:
168
+ return [a.strip('"') for a in re.findall(r'"[^"]*"|\S+', cmd)]
169
+
170
+
171
+ def _listening_ports() -> dict[int, list[int]]:
172
+ try:
173
+ import psutil # pylint: disable=import-outside-toplevel
174
+
175
+ out: dict[int, list[int]] = {}
176
+ for c in psutil.net_connections(kind="tcp"):
177
+ if c.status == psutil.CONN_LISTEN and c.pid and c.laddr.port not in out.get(c.pid, []):
178
+ out.setdefault(c.pid, []).append(c.laddr.port) # IPv4 + IPv6 listeners: once
179
+ return out
180
+ except (ImportError, OSError, RuntimeError):
181
+ pass
182
+ if os.name == "nt":
183
+ r = subprocess.run(["netstat", "-ano", "-p", "TCP"], capture_output=True, text=True, check=False)
184
+ return parse_netstat(r.stdout)
185
+ return {}
186
+
187
+
188
+ def find_sessions(min_version: int = MIN_VERSION) -> list[AedtSession]:
189
+ """AEDT processes of version ≥ ``min_version`` (batch ones too; see :attr:`AedtSession.graphical`), newest first."""
190
+ procs = _processes()
191
+ ports = _listening_ports() if procs else {}
192
+ out = []
193
+ for p in procs:
194
+ s = AedtSession(p["pid"], Path(p["exe"]) if p.get("exe") else None, list(p["cmdline"]),
195
+ sorted(ports.get(p["pid"], [])), p.get("created"))
196
+ if s.version is None or s.version >= min_version:
197
+ out.append(s)
198
+ return sorted(out, key=lambda s: -(s.created or 0))
199
+
200
+
201
+ def pick_session(sessions: list[AedtSession], pid: int | None = None) -> AedtSession | None:
202
+ """The session to attach to: ``pid`` (or ``QCC_AEDT_PID``) if given, else the newest graphical session with a
203
+ gRPC port. Batch (``-ng``) processes are never picked: they belong to someone's running job."""
204
+ pid = pid or (int(os.environ[ENV_PID]) if os.environ.get(ENV_PID, "").isdigit() else None)
205
+ usable = [s for s in sessions if s.graphical and s.port]
206
+ if pid is not None:
207
+ hit = [s for s in sessions if s.pid == pid]
208
+ if not hit:
209
+ raise LookupError(f"no AEDT process with pid {pid} (running: {[s.pid for s in sessions]})")
210
+ if hit[0] not in usable:
211
+ raise LookupError(f"AEDT pid {pid} cannot be attached to (batch -ng process, or no gRPC port)")
212
+ return hit[0]
213
+ return usable[0] if usable else None
214
+
215
+
216
+ # ---- processes qcc starts -----------------------------------------------------------------------------------------
217
+ def gui_command(executable: Path, script: str, sim_json: str) -> list[str]:
218
+ """A new AEDT window that runs ``scripts/<script>`` and stays open (no ``-ng``, ``-RunScript``, not ...AndExit)."""
219
+ return [str(executable), "-RunScript", f"scripts/{script}", "-ScriptArgs", sim_json]
220
+
221
+
222
+ def spawn_detached(args: list[str], cwd: Path, log: Path | None = None) -> subprocess.Popen:
223
+ """Start a GUI process that outlives this one (also a Jupyter kernel restart, which on Windows kills the kernel's
224
+ process tree by parent PID): ``cmd /c start`` leaves no parent link. POSIX: a new session."""
225
+ if os.name != "nt":
226
+ out = log.open("w", encoding="utf-8") if log else subprocess.DEVNULL
227
+ return subprocess.Popen(args, cwd=cwd, stdout=out, stderr=subprocess.STDOUT, # noqa: S603
228
+ start_new_session=True, close_fds=True)
229
+ detached, new_group = 0x00000008, 0x00000200
230
+ return subprocess.Popen(["cmd", "/c", "start", "", "/D", str(cwd), *args], cwd=cwd, # noqa: S603
231
+ close_fds=True, creationflags=detached | new_group)
232
+
233
+
234
+ def launch_gui(executable: Path, job_dir: Path, script: str, sim_json: str, wait: float = 60.0,
235
+ log: Path | None = None) -> int | None:
236
+ """Open a new AEDT window running ``script`` on ``job_dir``; returns its pid (found by its command line)."""
237
+ before = {s.pid for s in find_sessions(0)}
238
+ t0 = time.time()
239
+ proc = spawn_detached(gui_command(executable, script, sim_json), job_dir, log)
240
+ if os.name != "nt":
241
+ return proc.pid
242
+ while time.time() - t0 < wait:
243
+ for s in find_sessions(0):
244
+ if s.pid not in before and sim_json in s.cmdline and f"scripts/{script}" in s.cmdline:
245
+ return s.pid
246
+ time.sleep(1.0)
247
+ return None
248
+
249
+
250
+ def attach_command(session: AedtSession, script: Path, script_arg: str, project: str) -> list[str]:
251
+ """The helper process (:mod:`.aedt_attach`, standard library only) that runs ``script`` inside ``session``."""
252
+ return [sys.executable, "-I", str(ATTACH_HELPER), "attach", "--port", str(session.port), "--pid",
253
+ str(session.pid), "--plugin", str(session.plugin_dir), "--script", str(script), "--arg", script_arg,
254
+ "--project", project]
255
+
256
+
257
+ def pid_alive(pid: int | None) -> bool:
258
+ if not pid:
259
+ return False
260
+ try:
261
+ import psutil # pylint: disable=import-outside-toplevel
262
+
263
+ return psutil.pid_exists(pid) and psutil.Process(pid).status() != "zombie"
264
+ except ImportError:
265
+ pass
266
+ except Exception: # noqa: BLE001 (gone between the two calls)
267
+ return False
268
+ if os.name == "nt":
269
+ r = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True, check=False)
270
+ return str(pid) in r.stdout
271
+ try:
272
+ os.kill(pid, 0)
273
+ return True
274
+ except OSError:
275
+ return False