# 17. Python

`powercraft` Python 套件驅動的引擎，和桌面 app、命令列工具與 AI 助理是同一個。凡是能從選單、`powercraft-cli run` 或 AI 助理執行的指令，都能從 Python 執行；模擬的波形會以 numpy 陣列傳回，每一個取樣點都在。可以在腳本或 Jupyter 裡使用。

## 安裝

套件是一個對應你平台的 wheel 檔（同一個 wheel 適用 Python 3.9 以上）。用 pip 安裝：

```sh
pip install powercraft-0.9.0-cp39-abi3-macosx_11_0_arm64.whl   # 你拿到的那個檔案
pip install pandas matplotlib                                   # 選用：規格書與繪圖
```

要從原始碼建置 wheel，先安裝 [maturin](https://www.maturin.rs)，再執行 `cargo xtask python --wheel --release`；wheel 會寫到 `target/wheels/`。`cargo xtask python` 會建置開發用的版本並執行套件的測試。

## 第一個 session

```python
import powercraft

s = powercraft.Session()
s.execute("file.openExample", {"name": "buckIdeal"})
result = s.run(solver="fast")              # simulation.run
print(result["status"], result["samples"])

w = s.waveforms(["v(out)", "i(L1)"])       # numpy 陣列，每個取樣點都在
print(w["time"][-1], w["v(out)"].max())
```

- `Session.execute(command, params)` 依 id 執行任何引擎指令，結果以 Python 的 dict 與 list 傳回。`Session.commands("analysis")` 列出 id 或名稱符合的指令與它們的參數。
- `Session.run(**params)` 就是 `simulation.run`。
- `Session.waveforms(signals, t0, t1)` 傳回一個 dict：`"time"`（float64，單位秒）以及每個訊號一個 float32 陣列，和引擎儲存的格式相同。不給 `signals` 就傳回全部訊號；`t0` 與 `t1` 限定時間窗。陣列是唯讀的檢視，要修改請先 `.copy()`。`Session.signals()` 列出訊號名稱。
- `Session.dataframe(signals, t0, t1)` 以 pandas DataFrame 傳回同樣的資料，索引是時間。

CLI 與 AI 助理用的 `waveform.get` 預設每個訊號最多只給 2000 點的預覽；`waveforms` 則傳回完整的結果。

這些指令就是 app 執行的指令。在 app 的主控台（「檢視 > 主控台」，Cmd+Shift+Y）輸入同樣幾行，就能在寫腳本之前先試一次呼叫：

![在主控台執行第一個 session 的指令，標記 1 到 4](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/zh-Hant/python-console/01-console.png)

1. `file.openExample {"name": "buckIdeal"}`：就是 `s.execute("file.openExample", {"name": "buckIdeal"})` 執行的指令。
2. `simulation.run {"solver": "fast"}`：就是 `s.run(solver="fast")` 執行的指令。
3. `waveform.list`：這次模擬記錄的訊號。
4. 它的回覆：80800 個取樣點與訊號名稱。

## 錯誤

引擎拒絕或執行失敗的指令會丟出 `powercraft.CommandError`。訊息以指令 id 開頭，並說明哪裡有問題，和 app 的問題面板一樣。無法寫成 JSON 的參數會在執行任何東西之前丟出 `TypeError` 或 `ValueError`。Python 傳進來的任何內容都不會讓引擎崩潰。

## 檔案

`Session.open(path)` 與 `Session.save(path)` 讀寫你指定位置的 `.voltecx` 檔，和 CLI 的 `--in`、`--out` 相同。`file.*` 指令本身（`file.open`、`file.saveAs`、把波形匯出到路徑的 `file.exportWaveforms` 等）只能存取建立 session 時授權的資料夾裡的檔案：

```python
s = powercraft.Session(root="work")
s.execute("file.saveAs", {"path": "buck.voltecx"})   # 寫入 work/buck.voltecx
```

離開該資料夾的路徑（`../x.voltecx`）會被拒絕。沒有 `root` 的 session 不能透過指令存取檔案，規則和 `powercraft-cli run` 相同。

## 掃描

`Session.sweep` 把一個參數依序設成每個值、執行模擬、量測，最後復原它做的修改，所以電路會回到原來的樣子：

```python
rows = s.sweep("R1", "r", [1, 2, 4, 8], measure=("v(out)", "mean"), t0=2e-3, solver="fast")
for row in rows:
    print(row["value"], row["result"], row["error"])
```

`measure` 可以是訊號加上統計量（`mean`、`rms`、`max`、`min`、`pp`、`last`，在 `[t0, t1]` 區間內計算），也可以是一個接收 session 並傳回數值的函式，例如 `lambda s: s.waveforms("i(L1)")["i(L1)"].max()`。失敗的點會保留錯誤訊息，結果為 `None`，掃描繼續進行。要掃描電路變數並把工作分散到多個執行緒，請用引擎本身的 `analysis.paramSweep` 與 `analysis.paramSweep2d`。

## 場求解器（預覽功能）

場求解器是預覽功能：建立 session 時傳入 `preview=True`（等同 CLI 的 `preview.set`）。模型可以是 `magnetics.design` 的結果（畫成其磁芯的範本：含氣隙的 E 型磁芯對，或環形磁芯），也可以是你以毫米繪製的 `Sketch`：

```python
s = powercraft.Session(preview=True)
design = s.design_magnetics(l="100u", fsw="100k", idc=2, ripple=0.9, duty=0.25, top=1,
                            shape="E 25/13/7", wire="Round 0.5 - Grade 1")
solved = s.field_solve(design=design, field=True)     # magnetics.fieldSolve
print(solved.inductance() * 1e6, "µH", solved.model["nodes"], "nodes")

nodes, triangles, regions = solved.mesh()            # numpy：公尺、節點索引、每個元素的區域
b = solved.flux_density(current=2.0)                 # 每個元素的 (Bx, By)，單位 T

core = (powercraft.Sketch(depth_mm=10)
        .rectangle((-40, -40), (40, 40)).rectangle((-12, -8), (12, 8))
        .air("air", (0, 30)).core("core", (0, 6.5), mu_r=1e4))
```

- `Sketch` 提供 `point`、`segment`、`arc`（角度）、`polygon`、`rectangle` 與 `circle`，並以 `air`、`core`（線性材料及其 μr）或 `coil`（某電路的線圈邊及匝數，回程邊為負）標記每個區域。`Sketch.from_drawing(s.execute("geometry.get"))` 可接收用 `geometry.*` 指令畫的圖。錯誤的數值（NaN、半徑為零、掃角 360°）會引發指名該值的 `ValueError`；引擎無法網格化的圖會引發指名該點、邊或區域的 `CommandError`。
- `Session.field_solve(design | sketch, field, element_mm, mu_r, component, apply)` 傳回 `FieldSolution`：`values`（`l1`，兩個繞組時另有 `l2`、`m`、`k`、`lm`、`llk1`、`llk2`）、`inductance(circuit)`、`model`（網格大小、迭代次數、殘差、求解器版本與輸入雜湊）以及英文和繁體中文的 `notes`。加上 `field=True` 時另有 `mesh()`、`regions()`、`potential(circuit)` 與 `flux_density(circuit, current)`。`apply=True` 會以一個復原步驟把數值寫入 `component`。
- 每個場結果都帶有它的警告（平面模型、線性材料、超出材料資料、未收斂、網格太粗、超過飽和、舊版求解器）。`FieldSolution.warnings` 以 `{"code", "en", "zh-Hant", "data"}` 列出，`FieldSolution.warning(code)` 找出其中一個；`powercraft.field_warnings(reply)` 從其他場命令（例如 `field_core_loss`）的回覆讀出同樣的清單。
- `Session.field_line_profile(start, end, ...)` 以 numpy 陣列（`reply["arrays"]`）傳回沿線的 B 與 H、穿過該線的磁通，以及沿路徑的 ∫H·dl。`Session.field_region_table(...)` 傳回每個區域的能量、力與最大 |B|。兩者都接受各電路的 `currents`，並可用 `csv_path` 把 CSV 寫到 session 的 `root` 之下。
- `Session.field_core_loss(design | sketch, waveform=... | signals=[...])` 即 `magnetics.fieldCoreLoss`，損耗密度分布圖以 (n, 4) 陣列放在 `reply["map_array"]`。
- `Session.export_field_diagnostics(record, path)` 檢查一次求解的診斷紀錄，並寫成檔案供回報錯誤使用。

`apps/powercraft-python/examples/field_solve.py` 求解 E 25/13/7 設計，並掃描一個手繪磁芯的氣隙。數值與 `powercraft-cli run --cmd magnetics.fieldSolve` 對同一呼叫給出的相同。

## Jupyter

`apps/powercraft-python/examples/design_simulate_plot.ipynb` 用 `design.converter` 依輸出規格設計降壓轉換器的 L、C 與責任比，模擬結果，再用 matplotlib 畫出輸出電壓與電感電流。

## 授權

session 會使用桌面 app 儲存的授權（說明 › 授權），和 `powercraft-cli` 相同。傳入 `licensed=False` 則以免費版執行。
