# 17. Python

The `powercraft` Python package drives the same engine as the app, the command-line tool and the assistant. Every command
you can run from a menu, `powercraft-cli run` or an assistant, you can run from Python, and a simulation's
waveforms come back as numpy arrays with every sample. Use it from a script or from Jupyter.

## Install

The package is a wheel for your platform (one wheel works with Python 3.9 and later). Install it with pip:

```sh
pip install powercraft-0.9.0-cp39-abi3-macosx_11_0_arm64.whl   # the file you were given
pip install pandas matplotlib                                   # optional: data frames and plots
```

To build the wheel from the source tree, install [maturin](https://www.maturin.rs) and run
`cargo xtask python --wheel --release`; the wheel is written to `target/wheels/`. `cargo xtask python` builds a
development copy and runs the package's tests.

## A first 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 arrays, every sample
print(w["time"][-1], w["v(out)"].max())
```

- `Session.execute(command, params)` runs any engine command by its id and returns its result as Python dicts and
  lists. `Session.commands("analysis")` lists the commands whose id or label matches, with their parameters.
- `Session.run(**params)` is `simulation.run`.
- `Session.waveforms(signals, t0, t1)` returns a dict: `"time"` (float64 seconds) and one float32 array per signal,
  as the engine stores them. Without `signals` you get every signal; `t0` and `t1` limit the window. The arrays are
  read-only views; use `.copy()` to change one. `Session.signals()` lists the names.
- `Session.dataframe(signals, t0, t1)` gives the same data as a pandas DataFrame indexed by time.

`waveform.get`, which the CLI and the assistant use, returns a preview of at most 2000 points per signal unless you ask for
more. `waveforms` returns the full result instead.

The commands are the ones the app runs. Type the same lines in its console (**View > Console**, Cmd+Shift+Y) to try a call before you script it:

![The console running the first session's commands, marked 1 to 4](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/python-console/01-console.png)

1. `file.openExample {"name": "buckIdeal"}`: what `s.execute("file.openExample", {"name": "buckIdeal"})` runs.
2. `simulation.run {"solver": "fast"}`: what `s.run(solver="fast")` runs.
3. `waveform.list`: the signals the run recorded.
4. Its reply: 80800 samples and the signal names.

## Errors

A command the engine refuses or that fails raises `powercraft.CommandError`. Its message starts with the command id
and says what is wrong, as in the app's Problems panel. Parameters that cannot be written as JSON raise `TypeError`
or `ValueError` before anything runs. Nothing a Python caller sends can crash the engine.

## Files

`Session.open(path)` and `Session.save(path)` read and write `.voltecx` files anywhere you point them, like the CLI's
`--in` and `--out`. The `file.*` commands themselves (`file.open`, `file.saveAs`, `file.exportWaveforms` to a path,
...) reach files only inside a folder you grant when you create the session:

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

Paths that leave the folder (`../x.voltecx`) are refused. A session without `root` has no file access through
commands, the same rule as `powercraft-cli run`.

## Sweeps

`Session.sweep` sets one parameter to each value, runs the simulation, measures, and then undoes its changes, so the
circuit is as it was:

```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` is a signal and a statistic (`mean`, `rms`, `max`, `min`, `pp`, `last`) over `[t0, t1]`, or a function
that takes the session and returns a value, for example `lambda s: s.waveforms("i(L1)")["i(L1)"].max()`. A point
that fails keeps its error message and `None` as its result; the sweep goes on. For sweeps over circuit variables,
with the work spread over threads, use the engine's own `analysis.paramSweep` and `analysis.paramSweep2d`.

## Field solver (Preview)

The field solver is a Preview feature: start the session with `preview=True` (the same as `preview.set` in the
CLI). A model is a `magnetics.design` result, drawn as its core's template (an E pair with its gap, or a ring
core), or a `Sketch` you draw in millimetres:

```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: m, node indices, region per element
b = solved.flux_density(current=2.0)                 # (Bx, By) per element, 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` has `point`, `segment`, `arc` (degrees), `polygon`, `rectangle` and `circle`, and labels each region with
  `air`, `core` (a linear material with its μr) or `coil` (a circuit's coil side and its turns, negative for the
  return side). `Sketch.from_drawing(s.execute("geometry.get"))` takes a drawing made with the `geometry.*`
  commands. A wrong number (NaN, a zero radius, a sweep of 360°) raises `ValueError` naming it; a drawing the
  engine cannot mesh raises `CommandError` naming the point, edge or region.
- `Session.field_solve(design | sketch, field, element_mm, mu_r, component, apply)` returns a `FieldSolution`:
  `values` (`l1`, and with two windings `l2`, `m`, `k`, `lm`, `llk1`, `llk2`), `inductance(circuit)`, `model` (mesh
  size, iterations, residual, solver version and input hashes) and `notes` in English and Traditional Chinese. With
  `field=True` it also has `mesh()`, `regions()`, `potential(circuit)` and `flux_density(circuit, current)`.
  `apply=True` writes the values to `component` in one undo step.
- Every field result carries its warnings (planar model, linear material, outside the material data, not converged,
  mesh too coarse, above saturation, older solver version). `FieldSolution.warnings` lists them as
  `{"code", "en", "zh-Hant", "data"}` and `FieldSolution.warning(code)` finds one;
  `powercraft.field_warnings(reply)` reads the same list from any other field command's reply, such as
  `field_core_loss`.
- `Session.field_line_profile(start, end, ...)` gives B and H along a line as numpy arrays (`reply["arrays"]`),
  the flux across it and ∫H·dl along a path. `Session.field_region_table(...)` gives each region's energy, force
  and peak |B|. Both take `currents` per circuit and write a CSV with `csv_path` under the session's `root`.
- `Session.field_core_loss(design | sketch, waveform=... | signals=[...])` is `magnetics.fieldCoreLoss`, with the
  loss-density map as an (n, 4) array in `reply["map_array"]`.
- `Session.export_field_diagnostics(record, path)` checks a solve's diagnostics record and writes it for a bug
  report.

`apps/powercraft-python/examples/field_solve.py` solves the E 25/13/7 design and sweeps the gap of a hand-drawn
core. The numbers are the same as `powercraft-cli run --cmd magnetics.fieldSolve` gives for the same call.

## Jupyter

`apps/powercraft-python/examples/design_simulate_plot.ipynb` designs a buck converter's output filter with
`design.converter` (L, C and the duty cycle from the output spec), simulates the result and plots the output voltage and inductor current with matplotlib.

## Licence

A session uses the licence stored by the desktop app (Help › Licence), like `powercraft-cli`. Pass
`licensed=False` to run as Free.
