# 6. Analyses

An analysis runs the simulator, or a frequency-domain method, and returns numbers. Open the **Analysis** menu, or press Cmd+K and type the command name. A form asks for the parameters, filled in from the scope (the first visible trace and the visible time window) and the circuit's first variable. **Advanced (JSON)** takes the JSON shown in this chapter. The result appears in a window as a table (and, for sweeps and frequency responses, a small plot); **Copy** copies it as CSV. Sensitivity, Worst Case and Optimize have no form yet and take JSON. The same command works from `powercraft-cli run --cmd <id> --params '<json>'`, and from an assistant.

![The Analysis menu, marked 1 to 5](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/analyses/01-menu.png)

1. Parameter Sweep.
2. AC Sweep.
3. Loop Gain.
4. Operating Point.
5. Losses, which stays grey until a run has finished.

Choose the right tool:

| You want to... | Use |
|---|---|
| See how a result changes as one value goes from A to B | `analysis.paramSweep` |
| Find which of several values matter, and how they interact | `analysis.doe` |
| See the spread caused by part tolerances (random) | `analysis.monteCarlo` |
| Plot gain and phase against frequency | `analysis.acSweep` |
| Measure an impedance (a filter's output impedance, a source's) | `analysis.impedance` |
| Check a control loop's phase margin and crossover | `analysis.loopGain` |
| Find the noise at a sense or reference output, and which part makes it | `analysis.noise` |
| Find the values that give the best result | `analysis.optimize` |
| Find which part matters most | `analysis.sensitivity` |
| Adjust values until the waveforms meet a spec, then stop | `analysis.tuneToSpec` |
| Guarantee a spec over all tolerances | `analysis.worstCase` |
| Get the losses of each switch and diode | `analysis.losses`, `analysis.thermal` |
| See harmonics | `analysis.fft` |
| Check each part's stress against its rating | `analysis.stress` |
| Check that each switch turns on at zero voltage, and size the dead time | `analysis.softSwitching` |
| Hold a line current to the grid harmonic limits of IEEE 519 | `analysis.gridHarmonics` |
| Check that an inverter rides through a grid sag or swell (IEEE 1547) | `analysis.rideThrough` |
| Check that an inverter stops within 2 s when the grid is lost (IEEE 1547) | `analysis.antiIslanding` |
| Check that an inverter rides through a grid frequency disturbance (IEEE 1547) | `analysis.frequencyRideThrough` |
| Check that an inverter follows the frequency-droop active power (IEEE 1547) | `analysis.frequencyDroop` |
| Check that an inverter follows the volt-var reactive power curve (IEEE 1547) | `analysis.voltVar` |
| Check that an inverter curtails its active power along the volt-watt curve (IEEE 1547) | `analysis.voltWatt` |
| Check that an inverter holds its power factor setting (IEEE 1547) | `analysis.constantPf` |
| Check that an inverter follows the watt-var reactive power curve (IEEE 1547) | `analysis.wattVar` |
| Measure a three-phase converter's dq and sequence impedance and check it against a weak grid (SCR) | `analysis.dqImpedance` |
| Check that an inverter holds its reactive power setting (IEEE 1547) | `analysis.constantQ` |
| Check that an inverter rides through a grid phase-angle jump (IEEE 1547) | `analysis.phaseJumpRideThrough` |
| Check that an inverter trips in time on an abnormal grid voltage (IEEE 1547) | `analysis.voltageTrip` |
| Check that an inverter trips in time on an abnormal grid frequency (IEEE 1547) | `analysis.frequencyTrip` |
| Check that an inverter returns to service only inside the enter-service ranges, after the delay (IEEE 1547) | `analysis.returnToService` |
| Estimate the conducted EMI and size an input filter | `emi.conducted` |

Run the simulation first for the commands that read a result (`analysis.fft`, `analysis.losses`, `analysis.thermal`, `analysis.stress`). The sweeps, the frequency analyses and the optimisers run their own simulations.

## Analyses saved with the project

An analysis can be kept in the project as a document of its own: its kind (transient, AC sweep, DC sweep, parameter sweep or operating point), its settings, the signals it shows and its latest result, saved in the file. `analysisDoc.add`, `analysisDoc.run`, `analysisDoc.update` and `analysisDoc.remove` make, run, change and remove one; each is one undo step. With **View › Studio Layout (Preview)** on, the project tree's **Simulation** folder lists them after its documents, in the project's order; hover a row for what it runs. A click on a transient that has run shows its waveforms in the **Transient** tab, with its run laid over the latest one when it is an earlier run. A click on an AC sweep, DC sweep, parameter sweep or operating point that has run opens its kept result in an **Analysis** tab named after the document: its plots, tables and summary, as the result window shows them, with **Run Analysis** beside its name to run it again. Each analysis document has a tab of its own, so several can be open at once: right-click one's tab for **Open to the Side** to compare two results side by side. A result with plots has a **Signals** panel beside them: clear a signal's box to hide it in every plot. Click a plot to put **Cursor A** there and right-click for **Cursor B**; the panel shows where each cursor is (the frequency on a frequency axis), and the table under the plots gives each shown signal at A and at B, the difference B − A, and its least and greatest value between the cursors (over the whole sweep until both are placed). **Clear cursors** removes them. Each analysis document starts with every signal shown and no cursors, keeps its own while its tab is open, and starts afresh once its tab is closed. A click on one that has not run runs it, and its result shows in that tab when the run ends. Right-click a row for **Run Analysis** and **Remove Analysis**. Right-click the **Simulation** folder for **New Analysis**, then pick a kind (**Transient**, **AC Sweep**, **DC Sweep**, **Parameter Sweep** or **Operating Point**): the new document gets the kind's name and the next free number (**AC Sweep 2**), shows in the folder without running, and is one undo step.

A field solve can be kept the same way. An extraction setup (`analysisDoc.add {kind: "extraction"}`) keeps `field.peec`'s settings by name (**Extraction Setup 1**), and a sweep object (`kind: "fieldSweep"`) keeps `field.sweep`'s; a sweep that names a setup with `setup` is attached to it and starts every point from the setup's settings as they are when it runs. `analysisDoc.duplicate` copies any analysis under the next number of its name (**Setup1** gives **Setup2**), without its result, as one undo step. They are listed in the **Simulation** folder with the others, and a click runs them; the **New Analysis** menu does not offer them.

## Parameter sweep

Change a circuit variable over a list or a range and measure one result each time. The sweep runs the points in parallel on all your cores.

```json
{"variable": "D", "values": [0.2, 0.25, 0.3],
 "measure": {"signal": "v(out)", "stat": "mean", "t0": "3m"}}
```

The **Tools > Parameter Sweep** form (chapter 13) fills in this command for you and shows the result as a table. Instead of `values`, give `start`, `stop` and `points`. `stat` is one of `mean`, `rms`, `max`, `min`, `pp`, `last`, `ripplePct` and `meanProduct` (the mean of `signal` times `signal2`, for power). The variable is a circuit variable (**Circuit > Variables**; the example buck has `Vin`, `D` and `fsw`) or a part's parameter written `Part.param`, such as `L1.l`.

To get several numbers from each run, give `measure` as a list; the reply adds a `table` with a column per measurement. To see the waveforms too, like LTspice's `.step`, add `keepWaveforms`: the scope then overlays each point's trace in its own colour, named with the point (`v(out) · L1.l = 47u`).

```json
{"variable": "L1.l", "values": [47e-6, 100e-6, 220e-6],
 "measure": [{"signal": "i(L1)", "stat": "pp", "t0": "3m", "name": "ripple"},
             {"signal": "v(out)", "stat": "mean", "t0": "3m"}],
 "keepWaveforms": ["v(out)"]}
```

The kept waveforms may hold 256 MB (64 MB in the browser): a sweep that would need more is refused before it runs, with what to change. They stay until the next sweep that keeps waveforms, or **Simulation > Clear Sweep Waveforms** (also **Clear sweep waveforms** under the Parameter Sweep window's results). **Show on scope** there puts the kept signals on the scope, one curve per run, after the circuit has been run once. `analysis.paramSweep2d` and `analysis.monteCarlo` take the same `measure` lists and `keepWaveforms`.

### Example: three inductors, two numbers each, one overlay

```sh
powercraft-cli run --cmd file.openExample --params '{"name":"buck"}' \
  --cmd analysis.paramSweep --params '{"variable":"L1.l","values":[47e-6,100e-6,220e-6],
    "measure":[{"signal":"i(L1)","stat":"pp","t0":"3m","name":"ripple"},{"signal":"v(out)","stat":"mean","t0":"3m"}],
    "keepWaveforms":["v(out)"]}' \
  --cmd sweep.list --params '{}' \
  --cmd sweep.waveforms --params '{"points":[0],"maxPoints":2000}'
```

The sweep's `table` has the columns `L1.l`, `ripple` and `mean(v(out))` (a measurement without a `name` is called `stat(signal)`):

| `L1.l` | `ripple` (A) | `mean(v(out))` (V) |
|---|---|---|
| 47 µH | 1.927 | 11.995 |
| 100 µH | 0.911 | 11.996 |
| 220 µH | 0.423 | 11.993 |

`kept` in the reply says what was kept: 3 points of `v(out)`, 2.9 MB of the 268 MB budget, none `dropped`. The scope overlays the three traces as `v(out) · L1.l = 47u`, `v(out) · L1.l = 100u` and `v(out) · L1.l = 220u`. Three commands reach the kept family without the scope:

- `sweep.list` gives the command that made it, what was moved, the signals and each point's `index`, `label` and values.
- `sweep.waveforms` gives the samples: `signals` (default: the kept ones), `points` (indexes from `sweep.list`, default every point, at most 200), `t0`, `t1` and `maxPoints` (samples per point and signal, default 2000, from 4 to 20000).
- `sweep.clear` (**Simulation > Clear Sweep Waveforms**) frees them.

With a `measure` list, `analysis.paramSweep2d` adds `zs`, one grid for each measurement, and `analysis.monteCarlo` adds `measureStats`, the count, mean, standard deviation, minimum and maximum of each. Their other figures (the heat map, the histogram, the yield) are those of the first measurement. A 2-D point is labelled `R1.r = 4.8, D = 250m` and a Monte Carlo run `#3 L1.l = …`.

In the app the scope overlays the kept family on the latest run (solid). With the Measurements panel folded, the legend names every point:

![The scope after the sweep, marked 1 to 3](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/sweep-overlay/01-overlay.png)

1. `v(out) · L1.l = 47u`, dashed.
2. `v(out) · L1.l = 100u`.
3. `v(out) · L1.l = 220u`.

### Limits of sweeps that keep waveforms

- At most 16 measurements and 16 kept signals per sweep, and at most 1000 runs.
- The kept waveforms hold at most 256 MB (64 MB in the browser). A sweep estimated to need more is refused before it runs, for example: "keeping 2 signal(s) for 1000 points takes about 1280 MB, over the 268 MB the kept sweep waveforms may hold; keep fewer signals or points, or record less per run". When the runs come out larger than the estimate, points are kept in order while they fit, and `dropped` and `note` say how many were not.
- One family is kept at a time: the next sweep that keeps waveforms replaces it. It is kept apart from the run history (so a large sweep does not push out your runs), it is not saved in the file and it is not part of undo.

## Two-variable sweep

`analysis.paramSweep2d` runs one simulation for each point of a grid of two targets and measures one number, or a list of them, at each point. Each target is a circuit variable or a part's parameter (`R1.r`), and the two must differ. The points run in parallel. Give `x` and `y`, each with a `variable` and either `values` or `start`, `stop` and `points`, and a `measure` as in the parameter sweep.

```json
{"x": {"variable": "Vin", "start": 36, "stop": 60, "points": 4},
 "y": {"variable": "D", "values": [0.2, 0.25, 0.3]},
 "measure": {"signal": "v(out)", "stat": "mean", "t0": "3m"}}
```

The reply is a matrix, and the result window draws it as a heat map. The command has no menu item. Run it from the console, a script or an assistant.

## Design of experiments

**Analysis > Design of Experiments** (`analysis.doe`) varies up to eight factors at once, each a circuit variable or a part's parameter (`L1.l`) between a `low` and a `high` value, runs one simulation for each point of the plan, and measures one number, or a list of them, at each point. The runs go in parallel on all your cores, a run starting only while the machine has memory for it, and the results come back in run order.

Three plans:

- **Full factorial** (`"design": "fullFactorial"`, the default): every combination of each factor's `levels` (2 by default, up to 10), the first factor changing fastest. Three or more levels let the model fit curvature.
- **Fractional factorial** (`"fractionalFactorial"`): a two-level `2^(k−p)` fraction for screening many factors in few runs. `fraction` sets `p` and uses the standard generators of the NIST/SEMATECH e-Handbook of Statistical Methods (§5.3.3.4.7); or give your own `generators`, such as `["D=ABC"]`, where A, B, C … are the factors in order. Some interactions are then aliased with main effects; the reply lists the generators so you can tell which.
- **Latin hypercube** (`"latinHypercube"`): `runs` points (10 per factor by default) that use every slice of each factor's range once, drawn from `seed`, so the same seed gives the same runs.

```json
{"factors": [{"name": "D", "low": 0.3, "high": 0.5, "levels": 3},
             {"name": "L1.l", "low": "80u", "high": "120u"}],
 "design": "fullFactorial",
 "measure": {"signal": "v(out)", "stat": "mean", "t0": "1m"}}
```

The result window shows what ran, the **main effects** (the change from each factor's low to its high value), the **fitted model** (least squares in coded units, −1 at low and +1 at high, with every factor, every two-factor interaction and, for factors set at three or more values, every square, as far as the runs can tell them apart) with its R², the **response surface** of the model over two factors as a heat map (`"surface": {"x": "D", "y": "L1.l"}`; the first two by default, the others held at the centre of their range), and the table of runs. **Copy CSV** copies the whole table. A good order: screen many factors with a fraction, then run a full factorial or a Latin hypercube on the two or three that matter.

## Monte Carlo

Random draws within part tolerances. It reports the mean, the standard deviation, and the smallest and largest value of the measurement.

```json
{"vars": [{"name": "L1.l", "tol": 0.2}, {"name": "C1.c", "tol": 0.1, "distribution": "gauss"}],
 "runs": 50, "seed": 1,
 "measure": {"signal": "v(out)", "stat": "pp", "t0": "3m"}}
```

The `seed` makes a run repeatable. Each entry of `vars` names a circuit variable or a part's parameter (`L1.l`) and its tolerance `tol` as a ratio (0.2 is ±20 %; for `gauss` it is three standard deviations). `distribution` is `uniform` (the default) or `gauss`. The older shape `{"variables": {"L1.l": {"tolerance": 0.2}}}` still works, and the reply then has a `deprecated` line that shows the new one.

The reply also has a histogram, the percentiles (1, 5, 25, 50, 75, 95 and 99) and the worst run. Add `limitMin`, `limitMax` or both, and each run passes when its value is inside the limits. The reply then has a yield: the share of runs that passed, with a Wilson score interval (`confidence`, 0.95 by default). A run that failed to simulate counts against the yield. `bins` sets the number of histogram bins.

## AC sweep, impedance and loop gain

Choose **Analysis > AC Sweep**. Name the source (here `Vin`), check the output, the sweep range (From, To) and the rest, and press **Run**.

![The AC Sweep form, marked 1 to 4](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/analyses/02-form.png)

1. Source.
2. Output.
3. From (the start frequency).
4. Run.

These give gain and phase against frequency for a power stage, an input filter or a control loop. Each takes a log-spaced sweep: `fStart` (default 10 Hz), `fStop` (default 100 kHz), `points` (default 50, from 2 to 1000).

```json
{"source": "V1", "output": "v(out)", "fStart": 10, "fStop": "100k", "points": 100}
```

- **`analysis.acSweep`** gives `output / stimulus`. The stimulus is an independent voltage or current source (`source`). Without `source` it takes the circuit's one DC voltage source, else its one sine or pulse voltage source, else its one DC current source, and the reply names it in `source` and `injection`; when there are several candidates, or none, it lists them and asks. The output is `v(node)`, `v(a,b)`, `i(element)` or a signal name.
- **`analysis.impedance`** injects a current into `node` and reports `Z = (v(node) - v(ref)) / I`. Example: `{"node": "out"}`.
- **`analysis.loopGain`** breaks a control signal (`signal`) and reports `T = -return / forward`. Read the crossover frequency where `magnitudeDb` crosses 0, and the phase margin as the distance of `phaseDeg` from -180 degrees at that frequency.

Three methods:

| `method` | How it works | Use it for |
|---|---|---|
| `linear` (default, except a loop gain of a switching circuit) | Complex nodal analysis at each frequency. Fast and exact for a linear circuit | Passive filters, analog stages, a converter averaged by hand |
| `perturbation` | Adds a small sinusoid to the running transient simulation and measures the response | Switching converters, where you want the real, sampled behaviour, delays and all |
| `periodic` (default for `analysis.loopGain` on a circuit that switches) | Finds the periodic steady state, then linearises one switching period about it and reads the response from that model | Switching converters: the same answer as `perturbation`, in two switching periods a frequency instead of a settled run |

The result holds arrays `frequency`, `magnitudeDb`, `phaseDeg`, `real` and `imag`, and `warnings`. For perturbation, extra keys report the periods, steps and amplitude used. For `linear` on a circuit with switches, `states` fixes each switch on or off (`{"S1": "on"}`), so you analyse one switch state. Perturbation takes longer, because every frequency needs its own settled run. Start with fewer points.

On a circuit that switches, `perturbation` moves the sweep's frequencies to whole fractions of the switching frequency (fsw/2, fsw/3 and so on), where the response repeats from one perturbation period to the next, and its solver steps land on the PWM's edges, so a small duty perturbation is resolved at the circuit's own `maxStep`. With `untilCrossover` it measures from the top down and stops once the loop gain has stayed at 1 or more for an octave below where it last rose through 1: an output filter's resonance can lift the gain above 1 again just above the crossover. A point that does not settle is left out and listed in `unsettled`. A frequency the step budget cannot measure is refused before the run starts.

**How `periodic` works.** It first finds the periodic steady state at the switching period, the way `simulation.steadyState` does. About that steady state it builds the sampled-data model of one period (G. C. Verghese, M. E. Elbuluk and J. G. Kassakian, "A general approach to sampled-data modeling for power electronic circuits", IEEE Trans. Power Electron. PE-1(2), 1986).
- The matrix that carries the state from one period boundary to the next takes one simulated period per state variable, each started from the steady state with that variable moved.
- Each frequency then takes two more periods: one with a cosine on the stimulus and one with a sine.

Every period is simulated with its switching instants found by the solver, so the model includes how each switching instant moves with the state and the stimulus. The reply is the response at the stimulus frequency, which is what `perturbation` measures (the zeroth harmonic transfer function; N. M. Wereley and S. R. Hall, Proc. 29th IEEE CDC, 1990). On the closed-loop buck and boost examples it matches a fine-step `perturbation` within 0.2 dB and 1° up to a third of the switching frequency, in about 1/100 of the solver steps.

**Which solver.** `solver` (`reference` or `fast`) picks the transient solver that runs the periods; without it the method uses the circuit's own (Simulation Settings). The fast solver lands its steps on every switching instant and locates each diode's and body diode's commutation inside its step, so each period has a step grid of its own; the method integrates every period over its own steps, and the two solvers agree within 0.2 dB and 1° on the buck and boost loops. The reference solver puts a commutation that is not on a PWM edge on its step grid, so use the fast solver for resonant and soft-switched circuits (an LLC, a phase-shifted full bridge) at their own `maxStep`. The reply names the solver in `solver`.

**Validated.** Against `perturbation` at a fine step (2 ns, 200 ns for the PFC), up to a third of the switching frequency: the LLC half bridge (`llcHalfBridge`, input to output), the phase-shifted full bridge (`psfb`, loop gain) and the boost PFC's voltage loop (`pfcBoost` broken at `ipk`, up to a third of the 50 Hz line), each within about 0.1 dB and 1.2° on the fast solver, with 1/25 (the PFC, whose period map spans the 20 ms line period) to 1/2000 of the solver steps of the fine-step perturbation. `docs/accuracy.md` lists every point.

It takes `amplitude` (default 1 % of the operating value), `tol` (the steady state's tolerance, default `1e-6`), `maxPeriods` (for the steady-state search, default 2000), `solver` and `frequencies`. At or above half the switching frequency a switching circuit's response also depends on the stimulus's phase, and the reply warns about it.

### Example: the loop gain of the closed-loop buck

```sh
powercraft-cli run --cmd file.openExample --params '{"name": "buckClosedLoop"}' \
  --cmd analysis.loopGain --params '{"signal": "duty", "fStart": 100, "fStop": "20k", "points": 12}'
```

The circuit switches, so `analysis.loopGain` takes `periodic` without being asked. The reply says `"method": "periodic"`, 2 `periods` at each of the 12 frequencies and 11211 solver `steps` in all, and the loop crosses over at 380 Hz with 115° of phase margin and 46 dB of gain margin. The same call with `"method": "perturbation"` needs more than 20 million solver steps and stops at the default `maxSteps`.

**Analysis > Loop Gain** with `Signal` set to `duty`, 100 Hz to 20 kHz and 12 points makes the same call. The circuit switches, so it takes the periodic method:

![The Loop Gain result for the closed-loop buck, marked 1 to 3](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/periodic-loop/01-form.png)

1. The sweep: 12 points, 100 Hz to 20 kHz.
2. The crossover: 380 Hz.
3. The phase margin: 115.0°.

The gain margin, 46.0 dB, follows on the same line.

To pick the signal on the schematic instead of typing it, press **Pick** beside the Signal field. The form steps aside, and dashed circles mark the control signals that a block or a meter drives, which are the places the loop can be broken. A click on a circle fills the field and brings the form back. A pick replaces a voltage injection set in the form. Esc stops picking and leaves the field as it was.

Twelve points step over the output filter's resonance at 1.59 kHz, where this loop's gain rises above 0 dB again. With 80 points over the same range the reply has `"crossings": 3` and a warning, and reads the margins where the gain falls through 0 dB last, at 1751 Hz: 45° of phase margin, the one that sets the damping (44.5° by hand). A loop that crosses 0 dB more than once is always read at its last fall, so sweep densely around a resonance: the phase turns fast there.

Give `pmMinDeg` and `gmMinDb` (or store a spec with them through `spec.set`, as `design.auto` does) and the reply judges the margins: `checks` lists each margin with its least value and `pass`, and the cards read PASS or FAIL with "needs at least 45°". A margin the sweep has no crossing for is not judged (`pass` null).

Under the cards one line says how the loop gain was measured: the method, the frequencies and the periods each took, the solver steps and the solver, as "Periodic method · 12 frequencies × 2 periods · 16659 solver steps · fast solver". In the Loop Gain form the line under Method says what the picked method does; left empty it reads "Automatic: periodic when the circuit switches, linear otherwise."

### Limits of the periodic method

- The circuit needs a periodic steady state at the switching period, found within `maxPeriods`. The period is the longest one among the PWM blocks, carriers, sine sources and sample-and-hold blocks.
- It takes at most 200 state variables.
- It refuses, and says why, where its answer would be wrong:
  - a PWM or carrier whose frequency is wired (variable-frequency control, as an LLC's oscillator): the switching period moves with the stimulus. Use `perturbation`.
  - a frequency at or above half the frequency of a line source (an AC source or sine reference) that moves the operating point while the circuit switches many times per line period: on the boost PFC its voltage loop, below 25 Hz, is measured, and its current loop is refused. Study a fast loop at a fixed operating point, the line replaced by a DC source, with `perturbation` at a fine `maxStep`.
  - a steady period that does not repeat from the steady state: a control block keeps state the method neither restores nor linearises. The integrals of `integrator` and `pi` blocks, the states of `tf` blocks (a Type II or Type III network) and the states of `ztf` blocks (a digital compensator) are covered. Use `perturbation` for anything else.
  - a steady state in which no switch changes state over the period: the converter is held off there (a soft start, an enable or a protection), so there is no operating point to linearise about.
  - an answer that changes by more than 4 % when the stimulus is halved: a switching instant moves in steps (the reference solver on the phase-shifted full bridge) or the stimulus is too large. Use the fast solver, a smaller `maxStep` or a smaller `amplitude`.
- At or above half the switching frequency the response also depends on the stimulus's phase. The reply warns, and the values there are the response to a cosine stimulus, not a transfer function.
- `tSettle`, `stepsPerPeriod`, `skipUnsettled` and `untilCrossover` belong to `perturbation` and are refused with `periodic`.

### When the periodic method refuses: the analyser fallback

When `analysis.loopGain` is called with no `method` on a circuit that switches and the periodic method refuses it (a block it does not linearise, or a converter held off at the steady state it finds), the loop is measured the way a frequency-response analyser measures the board: sinusoidal perturbation at whole fractions fsw/k up to fsw/4, at most 16 points, from the top of the sweep down until the gain has risen through 0 dB, 1 % agreement between periods and at most 80 periods a frequency, after `tSettle` (the circuit's `tEnd` unless the call gives one). The reply has `"method": "perturbation"` and a `fallback` object with `from`, `why` (the periodic method's refusal) and `how`. A refusal no method can get round, a loop that mixes with a line source's sidebands, is not covered: it is reported as an error. Naming `"method": "periodic"` turns the fallback off.

Every perturbation reply carries `sweep`, each frequency reached with `settled` true or false, so a plot can mark the points left out. When the step budget runs out part-way, the points measured until then are the answer: `partial` is true and `stopped` says where and why.

### Model against measurement

`design.voltageLoop` with its loop check measures the designed loop on the switching circuit and adds a `modelVsMeasured` line: the measured phase margin less the model's, with a note on the two things the averaged model treats differently. One is the output capacitor's ESR zero, 1/(2π·ESR·C), which the model leaves out and which adds atan(fc/fESR) of lead at the crossover. The other is the model's modulator delay of `delayTs`·Ts, 360·fc·`delayTs`/fsw degrees of lag, where the switching circuit has its own.

## Noise

Choose **Analysis > Noise**. `analysis.noise` gives the noise at an output over a log-spaced sweep, as SPICE's `.noise` does: it solves the DC operating point, linearises the circuit there (every switch and diode in its state at that point, unless `states` names one) and adds up the noise of every part at the output.

```json
{"output": "v(out)", "input": "V1", "fStart": 10, "fStop": "100k", "points": 50, "temperature": 27}
```

- `output` is `v(node)`, `v(a,b)` or a control signal. `outputDensity` is the noise density there in V/√Hz at each `frequency`, and `outputRms` the RMS noise over `fStart` to `fStop` (the density is integrated as a straight line on log-log axes between points, so a white or a 1/f² stretch is exact with few points).
- With `input` (an independent voltage or current source) the reply also has `gainDb`, the gain from that source, and `inputDensity` and `inputRms`, the noise referred to it (V/√Hz for a voltage source, A/√Hz for a current source).
- `sources` lists the parts that make noise, largest share first: each has its `kind`, its current noise `density` in A/√Hz and its `share` of the output noise power over the band.

What makes noise:

| Part | Noise |
|---|---|
| Resistor, and the series and parallel resistances of a part | thermal, 4kT/R at `temperature` (default 27 °C) |
| A switch or MOSFET channel that conducts | thermal noise of its on-resistance |
| A diode, body diode or bipolar junction that conducts, a bipolar transistor's collector current | shot, 2q·I at the operating point |
| A level-1 MOSFET | channel, 8kT·gm/3 |

Everything else is noiseless, and the reply's `notModelled` says what that leaves out in this circuit: controlled sources, behavioural sources and control blocks carry no noise, no part has an op-amp's input noise (en, in), and flicker (1/f) noise is not modelled. A junction's small-signal resistance uses the part's own temperature (its `tj` or 25 °C), not `temperature`.

Tests check the thermal noise of a resistive divider (4kT·(R1 ∥ R2)) and its value referred to the source, that an RC low-pass integrates to kT/C whatever R is, that a diode fed by a current source has 2qI·rd², and a diode bias network with an RC filter against ngspice's `.noise` (densities and the output total within 2e-7).

### Example: the noise of the RC example

```sh
powercraft-cli run --cmd file.openExample --params '{"name": "rc"}' \
  --cmd analysis.noise --params '{"output": "v(out)", "input": "V1", "fStart": 0.01, "fStop": "1g", "points": 400}'
```

`outputDensity` starts at 4.07 nV/√Hz (the 1 kΩ resistor, √(4kTR)) and falls above the 159 Hz corner; `outputRms` is 64.4 nV, √(kT/C) for 1 µF. Referred to `V1`, the noise is the resistor's 4.07 nV/√Hz at every frequency.

## DC operating point, DC sweep and transfer function

These three find the circuit at DC. A capacitor is open and an inductor is a short. They read the circuit and never change it.

`analysis.op` solves the operating point. It reports every node voltage as `v(node)`, every branch current as `i(element)`, the state of each switch and diode, and the power in each element. It also gives the power the sources deliver and the power the resistive parts take. Sources hold the value they have at time 0. Give `time` to use another moment. Give `states` to fix a switch, for example `{"S1": "on"}`. A switch you do not name follows its gate at that time. A node with no DC path to ground is named in `warnings`.

```json
{"states": {"D1": "off"}}
```

`analysis.dcSweep` solves the operating point once for each value of one source or one circuit variable. Give `source` or `variable`. Give the values as `values`, or as `start`, `stop` and `step`. Use `output` or `outputs` to choose the signals to return. Without them the reply holds every voltage and current. Each point starts from the switch states of the point before it.

```json
{"source": "V1", "start": 0, "stop": 5, "step": 0.5, "output": "i(D1)"}
```

`analysis.transfer` gives the small-signal gain from a source to an output at the operating point. It also gives the resistance the source sees and the resistance at the output with the sources off. A resistance of `null` means the circuit is open there.

```json
{"source": "V1", "output": "v(out)"}
```

Machines and mechanical parts are not solved at DC. Run a transient for them. The `.op`, `.dc` and `.tf` lines of an imported SPICE file run these commands through `analysis.runImported`: choose **Simulation > Run Imported Analyses**, which runs them with the file's `.tran`, `.step`, `.ac` and `.meas` lines and is greyed out while the circuit has none.

## Optimise, sensitivity and worst case

Three commands answer "how do I make the design better?". They share one way of describing **variables** (what to change) and **metrics** (what to measure).

```json
{"vars": [{"name": "D", "lo": 0.2, "hi": 0.45}],
 "metrics": {"vout": {"signal": "v(out)", "stat": "mean", "t0": "3m"}},
 "objective": {"expr": "vout", "sense": "max"},
 "constraints": [{"expr": "vout", "op": "<=", "value": 12}],
 "maxEvals": 60, "apply": false}
```

- **`analysis.optimize`** searches within bounds. It stops after `maxEvals` runs (at most 500) or when the search has converged. With `"apply": true` it writes the best values into the circuit as one undo step.
- **`analysis.sensitivity`** changes each variable by a small amount and ranks how much each metric moves. Start here when you do not know what to adjust. It costs two runs per variable plus one.
- **`analysis.worstCase`** takes a tolerance for each variable. With `"method": "corners"` it tries every combination of the extremes (up to 8 variables). With `"method": "sensitivity"` it uses a linear estimate plus a root-sum-square value.

For `analysis.worstCase` each entry of `vars` is either `{"name": "L1.l", "tol": 0.2}` (the value times 1 ± 0.2; `tol` strictly between 0 and 1) or `{"name": "Vin", "min": 36, "max": 60}` (an absolute range).

A variable is a circuit variable (`D`) or a parameter written `part.parameter` (`L1.l`). A good order of work is: sensitivity first, optimise the one to three variables that matter, then worst case. The full guide, with a buck walk-through and common traps, is [`docs/workflows/optimize.md`](https://voltecx-web.nguyenvanqui291.workers.dev/docs/workflows/optimize/).

### One way to name targets, tolerances and measurements

The sweeps, the 2-D sweep, Monte Carlo, optimise, sensitivity and worst case read their targets the same way: a circuit variable (`D`) or a part's parameter (`L1.l`). A part's parameter is written into each run's own copy of the circuit, so the open circuit does not change. Monte Carlo and worst case take the tolerances as the list `vars`, and every measurement takes the same `stat` list (`mean`, `rms`, `max`, `min`, `pp`, `last`, `ripplePct`, `meanProduct`). On the `buck` example:

```sh
powercraft-cli run --cmd file.openExample --params '{"name":"buck"}' \
  --cmd analysis.worstCase --params '{"vars":[{"name":"L1.l","tol":0.2},{"name":"Vin","min":36,"max":60}],
    "metrics":{"vout":{"signal":"v(out)","stat":"mean","t0":"3m"}}}'
```

The reply (`method` `corners`, 5 runs) gives `vout` 11.996 V at nominal, 8.995 V at its lowest (`Vin` 36 V, `L1.l` 120 µH) and 14.994 V at its highest (`Vin` 60 V, `L1.l` 80 µH).

**Limits.**
- A part's parameter must already be set on the part: `L1.x` is refused with the parameters `L1` has. A bare part name (`L1`) is refused with a hint to write `L1.l`, and a name listed twice is refused.
- At most 32 entries in `vars`. Monte Carlo takes `tol` from 0 to 1; worst case takes it strictly between 0 and 1, or `min` and `max` instead (Monte Carlo has no `min`/`max` form).
- The older Monte Carlo and worst-case shape `variables` still works and adds a `deprecated` line to the reply; giving both `vars` and `variables` is an error.

## Tune to a spec

`analysis.tuneToSpec` is the "simulate, look, adjust, repeat" loop as one command. You say which waveform measurements must meet which bound, and which values it may change. It searches until every target is met, or until a limit stops it.

```json
{"targets": [{"signal": "v(out)", "stat": "mean", "t0": "3m", "op": ">=", "value": 11.9},
             {"signal": "v(out)", "stat": "pp", "t0": "3m", "op": "<=", "value": 0.1}],
 "vars": [{"component": "R2", "key": "r", "min": 1, "max": 100}],
 "limits": {"maxIterations": 20, "maxSims": 60}}
```

The part names in this example (`R2`) are only an illustration. Use the names in your own circuit.

- A **target** is a measurement as in `analysis.optimize` (`signal`, `stat`, `t0`, `t1`) plus `op` (`<=`, `>=` or `=`) and `value`. For `=`, `tol` sets the tolerance (1 % of the value by default).
- A **variable** names a part and a parameter (`component`, `key`) that holds a plain number, with the range `min` to `max`. A range of ten times or more is searched on a log scale. Up to 16 targets and 16 variables.
- **Run settings.** `tEnd` and `solver` override the simulation settings for the search, as in `analysis.optimize`.
- **Limits.** `maxIterations` (default 20, at most 200), `maxSims` (default 60, at most 1000) and `maxSeconds` (desktop only). A run ends with `stopReason` `met`, `maxIterations`, `maxSims`, `maxSeconds`, `cancelled` or `failed`.
- The reply has `met`, the list of `iterations` with the values and measurements, `before`, `after`, and `ops`. `ops` are the best values found, written as `circuit.apply` edits.

Every simulation runs on a private copy, so the circuit does not change during the search. The circuit is edited only when you pass `"apply": true` **and** the spec is met, as one undo step labelled "Tune to spec". When a limit or a cancel stops the search, the circuit is untouched, and the best values are still returned in `ops`. The command runs as a background job, so you can watch its progress and cancel it. In the desktop app, the agent panel offers it as the **Tune** form (chapter 12).

## Losses, thermal and FFT

- `analysis.losses` returns the average conduction and switching loss of each switch and diode over a window: `{"t0": "3m", "t1": "4m"}`. It also lists the winding and core loss of each inductor (`dcr`, `rcore` or a linked core), coupled inductor (`rw1`, `rw2`, `rcore`) and transformer (`rw1`, `rw2`, `rcore` or a linked core).
- `analysis.lossChart` draws where the watts go at full load (see *The loss chart* below).
- `analysis.thermal` returns the temperatures of circuits that have a thermal network. A switch or diode junction with a limit also gets `limit` (°C), `limitFrom`, `marginK` (the limit minus the peak), `pass` and `crossedAt`; the result window shows the limit and margin columns, with a junction past its limit in red.

### The loss chart

**Analysis › Loss Chart** (`analysis.lossChart`) shows where the input power goes at full load. It runs `design.efficiency` itself (at half and full load, so you need no run first) and draws its full-load loss table in a window:

- **A Sankey.** The output runs straight across the top. The losses leave the input under it, one lane for each kind of loss (conduction, switching, gate drive, winding copper, core, capacitor ESR, and the rest that no part explains), then fan out to the parts.
- **One bar per part**, largest first, stacked by kind of loss in the Sankey's colours, with a legend. Hover over a bar to see its split.
- **Notes** under the chart when a loss is left out. On a soft-switched bridge the device tables price switching loss that the run does not draw, so the chart leaves the switching and gate drive out and keeps the run's own input.

![The loss chart of the buck example, marked 1 to 3](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/loss-chart/01-chart.png)

1. The chart, headed by the efficiency and the total loss.
2. **Copy CSV** copies the flow, one row per band: `from,to,category,watts`.
3. **Show data** holds the numbers (the reply without its pictures).

On the buck example 57.4 W goes in and 55 W comes out (95.7 %). Of the 2.47 W lost, D1 takes 2.43 W in conduction, S1 34.5 mW, C1 1.83 mW in its ESR, and 2.38 mW is not explained by any part.

A three-phase inverter needs no `bind` either. When the circuit is no converter `design.efficiency` knows, but its only DC source drives phases that each run through one resistor (and any series inductors) to a star point nothing else touches, those resistors are the load, and the output is what they dissipate together. On the `inverter3` example, Analysis › Loss Chart shows 7.39 kW in and 7.38 kW out (99.88 %). Of the 8.59 W lost, each of the six switches takes 1.23 W in conduction and 1.22 W is not explained by any part. With a second DC source, or a phase with no resistor or two, name the load in `bind` (below).

Every watt on the chart is a number of the loss table: nothing is scaled or rounded away. The chart is refused, with the reason, when the input differs from the output plus the losses by more than 0.5 % of the input, when a loss is not a finite number or is negative, or when there is no loss at all. You get an error, never an empty chart.

| Param | Meaning |
|---|---|
| `format` | `svg` (default), `png` or `json`. The PNG is 1920 px wide at 192 dpi, so it prints at the SVG's 10 in, and it is lettered in English whatever `lang` is. |
| `lang` | `en` (default) or `zh-Hant`, for the labels of the SVG. |
| `efficiency` | A `design.efficiency` reply you already have, charted instead of running it again. |
| `bind`, `tEnd` | Passed to `design.efficiency`: `bind {source, load, outNet, fsw?}` names the parts of a circuit it does not recognise by itself. |

The reply has `pinW`, `poutW`, `lossW`, `gapW`, `efficiency`, the `nodes` and `links` of the flow, `parts` (largest first, each with `byCategory`) and `notes`. The design summary folder (`report.designSummary`, chapter 16) has the same chart as `loss-chart.svg`.

```sh
powercraft-cli run --cmd file.openExample --params '{"name":"buck"}' \
  --cmd analysis.lossChart --params '{"format":"json"}'
```

### Over-temperature

A switch or diode's junction limit is its `tjMax` parameter (°C), else the `tjMax` of its device: the highest junction temperature of the data sheet, filled for the library devices whose data sheet states it and absent otherwise. A run watches every junction that heats a thermal network and has a limit. When one passes it, the run's warnings name the part, the peak, the limit and the time it first crossed; the reply lists it in `overTemperature`; and `circuit.problems` shows `thermal.overTemperature` for as long as the result belongs to the circuit as it is. With `simulation.settings {"stopOnOverTemperature": true}` the run ends at the first crossing instead, and `stoppedBy` says why.

### The thermal overlay

**View › Overlays › Thermal Overlay** draws the last run's temperatures on the schematic. It turns on by itself after a Real run that has temperatures (see *Temperatures after every run* below) and stays off once you turn it off. Each part with a junction temperature (a switch or diode on a thermal node: its `thermal` parameter, or a device with its own thermal chain) gets a plate beside it with its peak temperature, `112 °C`; while the scope's cursors are on, the plate shows the value at the first cursor instead. The part's body is tinted on a colour scale (viridis, which reads in grey and with every common colour-vision deficiency) from the coolest temperature of the run, the ambient, up to the lowest `tjMax`, or up to the hottest part when no part has a limit. A part past its own `tjMax` is drawn in the error colour, with a warning mark on its plate and an outline round it; the plate stands in for the over-temperature problem's own mark, and hovering it shows the problem's text. The scale sits in the corner of the canvas that covers the fewest parts and wires (bottom-left when it is free), with its two ends in °C and a tick at the `tjMax`; past the tick it runs on in the error colour. On a small canvas the bar is narrower, and a click on the scale folds it to its title (click again to show it). When you change the circuit after the run, the overlay dims and the scale's title says it is stale; run again to bring it up to date.

![The thermal overlay on the thermal buck with a heatsink too small for Q1, marked 1 to 2](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/thermal-overlay/01-overlay.png)

1. Q1 is past its 150 °C limit.
2. D1 sits on its own heatsink, below its limit.

The colour scale is in the bottom-left corner.

From automation the overlay is view state: `ui.set {"thermalOverlay": true}`, or `ui.menu.invoke {"id": "view.thermalOverlay"}` to toggle it.

### Temperatures after every run

Every Real run shows its temperatures, even when the circuit has no thermal network. `thermal.summary` gives each part that loses power a temperature:

| Source | Temperature |
|---|---|
| `simulated` | The circuit's thermal network, as the run recorded it (the peak). |
| `heatsink` | The part's `thermal` net carries a placed heatsink (`thermal.placeHeatsink`): ambient + loss × (Rth j-c of its library device + the heatsink's Rth). |
| `datasheet` | The RthJA its data sheet gives on the smallest board it names (`parts/heatsinks.json`, cited): ambient + loss × RthJA. |

A part with none of these shows `—` and **needs Rth**: nothing is guessed. The loss is the one `runs.compareFigures` reads (the second half of the run), so the Ideal against Real table and the temperatures agree. The ambient is the call's `ambient`, else the spec's hottest ambient, else the circuit's ambient part, else 40 °C (the reply's `ambientFrom` says which). A part that stands for `nParallel` devices puts each one's share through its own path.

The run card shows:

- a banner when some parts have no thermal model: *No thermal model on N parts. Temperatures use ambient + Rth from the data sheet.* **Add heatsinks** opens `Design › Design Steps › Thermal`, which picks a catalogue heatsink and pad (or board copper) for each device; apply it there in one undoable step;
- a chip with the hottest part, its temperature and its margin to `tjMax`: red over the limit, amber within 25 K, green beyond. A click turns the thermal overlay on;
- **Temperature per part**: each part's temperature with a bar of its rise against its `tjMax`, and its margin.

On the overlay an estimate's plate reads `≈ 85 °C`, and the scale starts at the ambient.

```json
{"cmd": "thermal.summary", "params": {"ambient": 40}}
```

returns `parts` (hottest first: `part`, `lossW`, `tC`, `source`, `rthKW`, `tjMax`, `marginK`, `over`, `cite`, `needs`), `hottest`, `unmodelled`, `estimated` and `needsRth`.
- `analysis.fft` returns the frequency and amplitude of each harmonic, the fundamental and the THD: `{"signal": "i(L1)", "t0": "3m", "t1": "4m", "harmonics": 20}`. Without `t0` and `t1` it reads the last 5 periods of the fundamental before the end of the run, or as many whole periods as a shorter run holds (a part of a period smears the fundamental into its neighbours): the period comes from `fundamental` when you give it, otherwise from the signal's crossings of its mean in the second half of the run (the whole run when that half has too few), and with no period found it reads the last 20 % of the run. The reply says which in `window` (the times read) and `windowFrom` (`given`, `fundamental`, `signal` or `last20pct`).

## Stress and part choice

`analysis.stress` measures each part's peak and RMS current, peak voltage, `di/dt`, `dv/dt` and loss, and compares them with the rating it should have (after derating). A diode whose device carries its data sheet's surge rating is also held, without derating, to IFSM (its peak current) and I²t (the largest ∫i²dt over the rating's 10 ms half sine): the `surge` entry of the row's `device` gives both with their margins and the sheet's table, and a shortfall is an issue that puts the part in `underRated`. Diodes without a rating, thyristors and capacitors (Voltecx has no surge-voltage data for them) are listed under `surgeNotChecked`. `library.search`, `device.recommend` and `device.validate` then find parts in the library that cover that stress at the lowest loss. The guide is [`docs/workflows/part-selection.md`](https://voltecx-web.nguyenvanqui291.workers.dev/docs/workflows/part-selection/).

## Soft switching and dead time

`analysis.softSwitching` reads every gate edge of every MOSFET, IGBT and switch. At each turn-on it takes the voltage across the switch and its current, and calls the edge ZVS (at most 5 % of the voltage the switch blocks, or its body diode conducting), partial, or hard (at least 90 %). At each turn-off it checks whether the current was near zero (ZCS). Per switch it gives the share of ZVS edges, the worst turn-on voltage and the energy lost to hard turn-ons, ½·Co(er)·V², from `coss`, `cossTable` or the Coss curve of the assigned device. For each leg it measures how long the switch node took to swing, compares that with the dead time the gates show, and says whether the dead time is too short (the switch turns on before its voltage is zero) or too long (a diode conducts afterwards), with a value to use. It reads the last result and runs the simulation when there is none. Set `coss` on the switches and use the variable step to see the transitions: with no capacitance the node swings within one step.

With `{"sweep": {"variable": "Rload", "values": [2, 5, 10, 20]}}` it runs a copy once per value and reports, per switch, where ZVS is kept and where it is lost: the ZVS boundary over load. `analysis.paramSweep` measures one signal statistic per run, so use the sweep of `analysis.softSwitching` for this.

## Grid harmonic limits (IEEE 519)

`analysis.gridHarmonics` holds a line current of the last run to the current distortion limits of IEEE Std 519-2014, Table 2 (systems of 120 V to 69 kV). Give the current (`signal`), the window on whole line cycles after the start-up (`t0`, `t1`, `fundamental`) and the short-circuit ratio Isc/IL at the point of common coupling (`iscRatio`, or `isc` with `il`). The ratio picks the row of the table; each odd order 3 to 50 is held to the limit of its band in percent of IL, each even order to a quarter of it, and the total demand distortion (TDD, the rms of the orders 2 to 50 over IL) to the row's TDD limit. IL is the maximum demand current; without `il` the measured fundamental is used, and the reply says so. For a converter of pulse number q above 6, `pulseNumber` raises the limits of the orders kq ± 1 by √(q/6) when every other order stays below 25 % of its limit (IEEE Std 519-1992, 10.4); `allowance` says whether it applied. The tables above 69 kV are not modelled. The standard assesses 10-minute and 3-second statistical values; a simulation gives one steady-state spectrum, compared with the limits as they stand.

On the example `electrolyzer12Pulse`, `{"signal": "ia", "t0": 0.08, "t1": 0.12, "fundamental": 50, "iscRatio": 1500, "pulseNumber": 12}` shows the 11th and 13th within their raised limits, but the 23rd (about 3.8 % of IL) above 2.5·√2 = 3.5 %: a bare twelve-pulse rectifier needs a filter or a higher pulse number to meet Table 2.

## Voltage ride-through (IEEE 1547)

`analysis.rideThrough` (**Analysis › Voltage Ride-Through Check**) checks a grid sag or swell in the last run against the voltage ride-through requirements of IEEE Std 1547-2018, clause 6.4.2. Sag the grid in the circuit first (the `grid3` source's `sagDepth`, `sagStart` and `sagEnd`; a negative `sagDepth` is a swell) and run on for at least half a second after it. Give the phase-to-neutral voltages at the inverter's connection (`voltages`, 1 or 3 signals), its phase currents in the same order with positive into the grid (`currents`), and its category (`category`, `I`, `II` or `III`); the nominal voltage and frequency come from the circuit's only `grid3` unless you give `vll` and `fundamental`.

Each phase voltage is a one-cycle rms value over the nominal. The disturbance is the first stretch outside continuous operation (0.88 to 1.10 p.u.) after the start-up. It is a sag when a phase is below 0.88 p.u. as it starts, and its applicable voltage is then the least phase voltage; otherwise it is a swell, and its applicable voltage is the greatest. The median applicable voltage picks the row of Table 14 (Category I), Table 15 (Category II) or Table 16 (Category III); the reply's `sag.kind` says which it was:

| Category | Voltage (p.u.) | Region | Minimum ride-through time |
|---|---|---|---|
| I and II | above 1.20 | cease to energize | none (may trip) |
| I and II | 1.175 to 1.20 | permissive operation | 0.2 s |
| I and II | 1.15 to 1.175 | permissive operation | 0.5 s |
| I and II | 1.10 to 1.15 | permissive operation | 1 s |
| I | 0.70 to 0.88 | mandatory operation | 0.7 s + 4 s/p.u. × (V − 0.70) |
| I | 0.50 to 0.70 | permissive operation | 0.16 s |
| I | below 0.50 | cease to energize | none (may trip) |
| II | 0.65 to 0.88 | mandatory operation | 3 s + 8.7 s/p.u. × (V − 0.65) |
| II | 0.45 to 0.65 | permissive operation | 0.32 s |
| II | 0.30 to 0.45 | permissive operation | 0.16 s |
| II | below 0.30 | cease to energize | none (may trip) |
| III | above 1.20 | cease to energize | none (may trip) |
| III | 1.10 to 1.20 | momentary cessation | 12 s |
| III | 0.70 to 0.88 | mandatory operation | 20 s |
| III | 0.50 to 0.70 | mandatory operation | 10 s |
| III | below 0.50 | momentary cessation | 1 s |

Three checks follow. `duration`: the sag or swell against the table's time. `current`, in mandatory operation of Category II or III only: the least apparent current in the sag must be at least 80 % of the pre-disturbance apparent current or active current, whichever is less (clause 6.4.2; the available active power is taken as the pre-disturbance power). `restore`: 0.4 s after the voltage returns, the active current must be back to at least 80 % of its pre-disturbance level (clause 6.4.2.7, a DER without dynamic voltage support). The `verdict` is `pass`, `fail`, `incomplete` when nothing failed but the sag was shorter than the table asks or the run ended too soon, or `notRequired` where the table asks no ride-through. Table 14's rows and every table's high-voltage rows were taken from reproductions of the tables, listed in the reply's `sources`: check them against the standard. Frequency ride-through (below) and consecutive disturbances are not checked yet.

On the example `microgridIslanding`, set `BrkGrid.topen` to 100 s so the grid stays connected, `G1.sagDepth` 0.3, `sagStart` 0.5 and `sagEnd` 5, run for 5.6 s, and check the PV inverter with `{"voltages": ["vba", "vbb", "vbc"], "currents": ["ipvra", "ipvrb", "ipvrc"]}`. The battery's droop holds the bus at about 0.74 p.u. (Category II asks 3.8 s), and the PV inverter's constant current reference keeps its current and is back at once: `pass`.

## Anti-islanding (IEEE 1547)

`analysis.antiIslanding` (**Analysis › Anti-Islanding Check**) checks an island in the last run against the unintentional-islanding requirement of IEEE Std 1547-2018, clause 8.1.2: the DER shall detect the island and cease to energize within 2 s of its formation. Open the grid's breaker in the circuit and run for at least 2 s after it. Give the phase-to-neutral voltages at the inverter's connection (`voltages`, 1 or 3 signals) and its phase currents in the same order (`currents`); the island time is the `topen` of the circuit's only breaker unless you give `islandAt`, and the nominal voltage and frequency come from the circuit's only `grid3` unless you give `vll` and `fundamental`.

The inverter counts as ceased once its one-cycle rms current falls to `ceaseShare` (1 % by default, a setting of the check, not a value of the standard) of its pre-island value and stays there to the end of the run. The `verdict` is `pass` when it ceased within 2 s, `fail` when it ceased later or still energizes 2 s after the island, and `incomplete` when the run ends sooner. The run-on time errs long by up to one cycle.

The hardest island for passive detection is a parallel RLC load matched to the inverter's power and tuned to the line frequency with a quality factor of 1.0 (IEEE Std 1547.1-2005 clause 5.7.1). The reply sizes it per phase (star) from the inverter's pre-island power as `testLoad` (R = V²/P, L = V²/(2π·f·P·Qf), C = Qf·P/(2π·f·V²); `qf` changes Qf). Build it in place of the circuit's loads, trim L or C until the grid carries no fundamental current before the island, and run again. The trip itself, the reconnection delay and the test's power and imbalance cases are not checked.

On the example `microgridIslanding`, run for 2.6 s and check the PV inverter with `{"voltages": ["vba", "vbb", "vbc"], "currents": ["ipvra", "ipvrb", "ipvrc"]}`: it follows the island the battery forms and still delivers 6 kW at the end, so it fails, as a grid-following inverter without islanding detection should. Give it a frequency trip that zeroes its current references and the check passes.


## Frequency ride-through (IEEE 1547)

`analysis.frequencyRideThrough` (**Analysis › Frequency Ride-Through Check**) checks a grid frequency disturbance in the last run against the frequency disturbance ride-through requirements of IEEE Std 1547-2018, clause 6.5.2. Move the grid's frequency in the circuit first: the `grid3` source's `fDev` (Hz, negative for an under-frequency), `fStart`, `fEnd` and `fRate` (Hz/s; `none` steps it). Give the phase-to-neutral voltages at the inverter's connection (`voltages`, 1 or 3 signals; the frequency is measured on the first, one value per cycle between rising zero crossings), its phase currents in the same order (`currents`) and its category (`category`, `I`, `II` or `III`). The disturbance starts at the grid's `fStart` unless you give `disturbanceAt`. Table 19 gives its frequencies in hertz for a 60 Hz system, so the check needs a 60 Hz fundamental.

Table 19 (the same for all three categories): 58.8 to 61.2 Hz is continuous operation; 57.0 to 58.8 Hz and 61.2 to 61.8 Hz are mandatory operation for at least 299 s; below 57.0 Hz and above 62.0 Hz no ride-through is required (the table lists no row from 61.8 to 62.0 Hz). Within these regions the DER rides through a rate of change of frequency up to Table 21's: 0.5 Hz/s for Category I, 2.0 Hz/s for II and 3.0 Hz/s for III (clause 6.5.2.5). The check reports three things: `rocof`, the largest RoCoF (the change of the frequency over `rocofWindow`, 0.1 s by default) against Table 21; `energized`, the least one-cycle rms current from the disturbance on against `ceaseShare` (1 % by default) of the pre-disturbance current; and, for an excursion into mandatory operation, `duration` against 299 s. `rocofWindow` and `ceaseShare` are settings of the check, not values of the standard. The frequency and its RoCoF count only up to the moment the inverter ceases, since after that its own loss of current moves the voltage they are measured on.

The `verdict` is `pass` when the inverter stayed energized (in mandatory operation, for at least 299 s), `fail` when it ceased while the standard asks it to ride through, `incomplete` when nothing failed but a mandatory excursion lasted less than 299 s, and `notRequired` when the frequency or the RoCoF went beyond what its category rides through. The table rows and limits were taken from reproductions of Tables 19 and 21 (listed in `sources`): check them against the standard. In continuous operation the `vPerHz` check reports the largest per-unit ratio of voltage (the highest phase over `vll`/√3) to frequency (over the fundamental) the inverter saw before it ceased: clause 6.5.2 asks it not to trip only up to 1.1 V/Hz, so above that the verdict is `notRequired` (the limit as quoted from clause 6.5.2 in NERC's 1547-2018 reliability guideline). The active power the inverter keeps or modulates (clause 6.5.2.7, Table 22: `analysis.frequencyDroop` below) and phase-angle jumps (clause 6.5.2.6: `analysis.phaseJumpRideThrough` below) are not checked here.

On the example `microgridIslanding`, set the variable `fline` to 60, `BrkGrid.topen` to 100 s so the grid stays connected, and on `G1` `fDev` −1, `fStart` 0.5, `fEnd` 100 and `fRate` 1.5. Run for 1.6 s and check the PV inverter with `{"voltages": ["vba", "vbb", "vbc"], "currents": ["ipvra", "ipvrb", "ipvrc"]}`: its phase-locked loop follows the grid down to 59 Hz at 1.5 Hz/s and it keeps its current, so Category II passes and Category I (0.5 Hz/s) asks nothing.

## Frequency-droop active power (IEEE 1547)

`analysis.frequencyDroop` (**Analysis › Frequency-Droop Check**) checks the active power an inverter delivers through a grid frequency excursion in the last run against the frequency-droop (frequency/power) operation of IEEE Std 1547-2018, clause 6.5.2.7 and Table 22. Move the grid's frequency as for the ride-through check, and give the phase-to-neutral voltages (`voltages`), the inverter's phase currents out of it in the same order (`currents`) and its rated active power (`ratedW`, the base of the per-unit droop; there is no default). The frequency and the power are one value per cycle of the first voltage. Outside the deadband the droop asks, from the pre-disturbance power p_pre in per unit: above 60 + `dbOf` Hz, p = max(p_pre − (f − (60 + `dbOf`)) / (60 · `kOf`), `pMinW`); below 60 − `dbUf` Hz, p = min(p_pre + ((60 − `dbUf`) − f) / (60 · `kUf`), `availableW`). The defaults are Table 22's: deadbands 0.036 Hz, droops 0.05 and a 5 s open-loop response time (`responseTime`), taken from EPRI OpenDER (listed in `sources`): check them against the standard. Without `availableW` the inverter is taken to have no headroom above its pre-disturbance power.

The check reports `power`, the last cycle's power against the droop at the last cycle's frequency, within `tolerancePct` (5 % of `ratedW` by default, a setting of the check, not a value of the standard), and `response`, the time from the frequency leaving the deadband to 90 % of the power change, against `responseTime`. For a frequency step that time is the open-loop response time; a ramp adds its own duration. The `verdict` is `pass`, `fail`, `incomplete` (the run ended before the response time and before the power reached 90 % of its change) or `notRequired` (the frequency stayed in the deadband).

On `microgridIslanding` set up as for the ride-through check, with `G1` `fDev` 0.5 and `fRate` 50, the PV inverter keeps its 6 kW and fails: the droop asks 0.155 pu less at 60.5 Hz. Scale its current references by the droop of the loop's frequency `wpv` (an `expr` block per phase) and it passes.

## Volt-var reactive power (IEEE 1547)

`analysis.voltVar` (**Analysis › Volt-VAR Check**) checks the reactive power an inverter delivers through a grid voltage change in the last run against the voltage-reactive power (volt-var) mode of IEEE Std 1547-2018, clause 5.3.3 and Table 8. Change the grid's voltage (`G1` `sagDepth`, `sagStart`, `sagEnd`; a negative depth is a swell), and give the phase-to-neutral voltages (`voltages`), the inverter's phase currents out of it in the same order (`currents`) and its nameplate apparent power (`ratedVA`, the base of the per-unit reactive power; there is no default). The voltage and the reactive power are one value per nominal cycle: the applicable voltage is the mean of the phases' rms over the nominal phase voltage (`vll`/√3), and the reactive power is positive when the inverter injects it (its current lags the voltage). The curve is piecewise linear through (V1, Q1) to (V4, Q4), flat outside, with its voltages shifted by `vRef` − 1. `category` picks Table 8's defaults: Category A 0.90, 1.00, 1.00, 1.10 p.u. with ±0.25 pu and a 10 s open-loop response time; Category B (the default) 0.92, 0.98, 1.02, 1.08 p.u. with ±0.44 pu and 5 s. They were taken from EPRI OpenDER (listed in `sources`): check them against the standard. `v1` to `v4`, `q1` to `q4` and `responseTime` replace them.

The check reports `reactive`, the last cycle's reactive power against the curve at the last cycle's voltage, within `tolerancePct` (5 % of `ratedVA` by default, a setting of the check, not a value of the standard), and `response`, the time from `disturbanceAt` (default the grid's `sagStart`) to 90 % of the reactive power change, against `responseTime`. The `verdict` is `pass`, `fail`, or `incomplete` when the change is still under way as the run ends before the response time.

On `microgridIslanding` at 60 Hz with its breaker kept closed and `G1` `sagDepth` 0.05 from 0.5 s, the bus settles near 0.95 p.u. and Category B asks about 0.2 pu of injection: the PV inverter as shipped injects none and fails. Drive its q-axis current from the bus voltage's d component through the curve (`srfPll`, `abc2dq`, an `expr` and `dq2abc` blocks) and it passes.

## Volt-watt active power (IEEE 1547)

`analysis.voltWatt` (**Analysis › Volt-Watt Check**) checks the active power an inverter delivers through a grid voltage rise in the last run against the voltage-active power (volt-watt) mode of IEEE Std 1547-2018, clause 5.4.2 and Table 10. Raise the grid's voltage (`G1` `sagDepth` negative, `sagStart`, `sagEnd`), and give the phase-to-neutral voltages (`voltages`), the inverter's phase currents out of it in the same order (`currents`) and its rated active power (`ratedW`, the base of the per-unit curve; there is no default). The voltage and the active power are one value per nominal cycle, as for the volt-var check. The curve is a power limit: P1 at V1 and below, P2 at V2 and above, linear between, and the inverter delivers the lesser of the limit and the power it has available (`availableW`, default its power before the change). Table 10's defaults, the same for Category A and B, are V1 1.06 p.u., P1 1.0, V2 1.10 p.u., P2 the lesser of 0.2 and the inverter's least active power over its rating (`pMinW`, default 0), and a 10 s open-loop response time. They were taken from EPRI OpenDER (listed in `sources`): check them against the standard. `v1`, `p1`, `v2`, `p2` and `responseTime` replace them.

The check reports `power`, the last cycle's active power against what the curve allows at the last cycle's voltage, within `tolerancePct` (5 % of `ratedW` by default, a setting of the check, not a value of the standard), and `response`, the time from `disturbanceAt` (default the grid's `sagStart`) to 90 % of the power change, against `responseTime`. The `verdict` is `pass`, `fail`, or `incomplete` when the change is still under way as the run ends before the response time.

On `microgridIslanding` at 60 Hz with its breaker kept closed and `G1` `sagDepth` −0.1 from 0.5 s, the bus settles between 1.06 and 1.10 p.u. and the curve limits the 6 kW PV inverter to part of its output: as shipped it keeps its current, so its power rises, and it fails. Limit its d-axis current through the curve from the bus voltage's d component (`srfPll`, `abc2dq`, an `expr` and `dq2abc` blocks) and it passes.

## Constant power factor (IEEE 1547)

`analysis.constantPf` (**Analysis › Constant Power Factor Check**) checks the reactive power an inverter exchanges in the last run against the constant power factor mode of IEEE Std 1547-2018, clause 5.3.2. Give the phase-to-neutral voltages (`voltages`), the inverter's phase currents out of it in the same order (`currents`), its rated apparent power (`ratedVA`, the base of the tolerance; there is no default), the power factor setting (`pf`, 0.1 to 1) and its excitation (`excitation`, `absorbing` or `injecting`). The active and reactive power are one value per nominal cycle, as for the volt-var check, and reactive power is positive when the inverter injects. At the setting the inverter's reactive power is ±P·√(1 − pf²)/pf of its active power P, negative when absorbing. The defaults, unity, absorbing and a 5 s response time, were taken from EPRI OpenDER (listed in `sources`): check them against the standard.

The check reports `reactive`, the last cycle's reactive power against the setting at the last cycle's active power, within `tolerancePct` (5 % of `ratedVA` by default, a setting of the check, not a value of the standard), and `response`, the time from `disturbanceAt` (when the setting or the active power changes; default the grid's `sagStart`) to 90 % of the reactive power change, against `responseTime`. Without a change the response is `notRun` and only the last cycle counts. The `verdict` is `pass`, `fail`, or `incomplete` when the change is still under way as the run ends before the response time.

On `microgridIslanding` at 60 Hz with its breaker kept closed and a setting of 0.9 absorbing from 0.5 s, the 6 kW PV inverter as shipped stays at unity and fails. Give it a q-axis current of √(1 − 0.9²)/0.9 of its d-axis current from 0.5 s (`srfPll`, `constant`, an `expr` of `time` and `dq2abc` blocks) and it absorbs about 2.9 kvar and passes.

## Watt-var (IEEE 1547)

`analysis.wattVar` (**Analysis › Watt-Var Check**) checks the reactive power an inverter exchanges in the last run against the active power-reactive power (watt-var) mode of IEEE Std 1547-2018, clause 5.3.4. Give the phase-to-neutral voltages (`voltages`), the inverter's phase currents out of it in the same order (`currents`), its rated active power (`ratedW`, the base of the curve's P) and its rated apparent power (`ratedVA`, the base of the curve's Q and of the tolerance); neither has a default. The curve has three points: `p1`, `p2`, `p3` per unit of `ratedW` and `q1`, `q2`, `q3` per unit of `ratedVA`, positive when the inverter injects. Below P1 it holds Q1, above P3 it holds Q3, and it is linear between. Table 9's defaults are P1 the greater of 0.2 and `pMinW`/`ratedW`, P2 0.5, P3 1, Q1 = Q2 = 0, and Q3 −0.25 for `category` A or −0.44 for B (the default), with a 5 s response time; they were taken from EPRI OpenDER (listed in `sources`): check them against the standard. When the last cycle takes active power (a battery charging), the curve's charging side applies: `p1Load`, `p2Load`, `p3Load` (P'1 to P'3, per unit of `ratedChargeW`, the rated charge power, from 0 down to −1) and `q1Load`, `q2Load`, `q3Load` (Q'1 to Q'3). Their defaults, from EPRI OpenDER too, are P'1 0, P'2 −0.5, P'3 −1, Q'1 equal to Q1, Q'2 0 and Q'3 0.44 (injecting); between P'1 and P1 the curve is linear, and below P'3 it holds Q'3. A charging last cycle without `ratedChargeW` is refused.

The check reports `reactive`, the last cycle's reactive power against the curve at the last cycle's active power, within `tolerancePct` (5 % of `ratedVA` by default, a setting of the check, not a value of the standard), and `response`, the time from `disturbanceAt` (when the mode is enabled or the active power changes; default the grid's `sagStart`) to 90 % of the reactive power change, against `responseTime`. Without a change the response is `notRun` and only the last cycle counts. The `verdict` is `pass`, `fail`, or `incomplete` when the change is still under way as the run ends before the response time.

On `microgridIslanding` at 60 Hz with its breaker kept closed and the mode enabled at 0.5 s (`ratedW` and `ratedVA` 6000), the 6 kW PV inverter runs near its rating, where the Category B curve asks it to absorb about 0.44 of 6 kVA. As shipped it stays at unity and fails. Give it a q-axis current of 0.44 of its d-axis current from 0.5 s (`srfPll`, `constant`, an `expr` of `time` and `dq2abc` blocks) and it passes.

## Constant reactive power (IEEE 1547)

`analysis.constantQ` (**Analysis › Constant Reactive Power Check**) checks the reactive power an inverter exchanges in the last run against the constant reactive power mode of IEEE Std 1547-2018, clause 5.3.5. Give the phase-to-neutral voltages (`voltages`), the inverter's phase currents out of it in the same order (`currents`), its rated apparent power (`ratedVA`, the base of the setting and of the tolerance; there is no default) and the setting (`qSet`, −1 to 1 per unit of `ratedVA`, positive when the inverter injects). The setting asks the same reactive power whatever the active power; keep it within the inverter's nameplate reactive power ratings, which the check does not know. The active and reactive power are one value per nominal cycle, as for the volt-var check. The defaults, 0 pu and a 5 s response time, were taken from EPRI OpenDER (listed in `sources`): check them against the standard.

The check reports `reactive`, the last cycle's reactive power against `qSet`·`ratedVA`, within `tolerancePct` (5 % of `ratedVA` by default, a setting of the check, not a value of the standard), and `response`, the time from `disturbanceAt` (when the mode is enabled or the setting changes; default the grid's `sagStart`) to 90 % of the reactive power change, against `responseTime`. Without a change the response is `notRun` and only the last cycle counts. The `verdict` is `pass`, `fail`, or `incomplete` when the change is still under way as the run ends before the response time.

On `microgridIslanding` at 60 Hz with its breaker kept closed and a setting of −0.25 pu (absorbing 1.5 kvar of 6 kVA) from 0.5 s, the 6 kW PV inverter as shipped stays at unity and fails. Give it a q-axis current of 0.25 of its rated d-axis current from 0.5 s (`srfPll`, `constant`, an `expr` of `time` and `dq2abc` blocks) and it passes.

## Phase-angle jump ride-through (IEEE 1547)

`analysis.phaseJumpRideThrough` (**Analysis › Phase-Jump Ride-Through Check**) checks whether an inverter rode through a jump of the grid's phase angle in the last run, as IEEE Std 1547-2018 clause 6.5.2.6 asks. Make the grid jump with the `grid3` parameters `jumpDeg` (degrees, positive leads), `jumpAt` (s) and `jumpPhases` (the phases it touches, `abc` by default), and give the phase-to-neutral voltages in the order a, b, c (`voltages`) and the inverter's phase currents in the same order (`currents`); `disturbanceAt` defaults to the grid's `jumpAt`. Each phase's angle change is that of its one-cycle fundamental phasor after the jump against the cycle before it, each an eighth of a cycle clear of it, and the positive-sequence change is that of (Va + a·Vb + a²·Vc)/3.

The clause asks a three-phase inverter to ride through positive-sequence changes of up to 20° while each phase changes by less than 60°, and a single-phase one changes of up to 60°; beyond them the `verdict` is `notRequired`. Positively damped current oscillations, or a momentary cessation of at most 0.5 s, are acceptable. The check reports `angle`, `cessation` (the longest stretch with the one-cycle rms current at or below `ceaseShare`, 1 % of the pre-jump current by default, against 0.5 s; it must end) and `damped` (the largest deviation of the current from its pre-jump value is smaller over the second half of the rest of the run than over the first, or within `settleShare`, 5 %). Both shares are settings of the check, not values of the standard, and the clause text was taken from a reproduction (listed in `sources`): check it against the standard. The `verdict` is `pass`, `fail` or `incomplete` (the run ended before the check could judge it).

On `microgridIslanding` set to 60 Hz with its breaker kept closed and `G1` `jumpDeg` 15 at `jumpAt` 0.5 s, the grid's terminals see the full 15° but the bus, behind the 1 mH feeder, sees about 12°, so measure where the inverter connects. The PV inverter re-locks and passes. Cut its current references one cycle after the jump (a `step` block times each reference) and it ceases for good and fails; a 30° jump asks nothing.

## Voltage trip (IEEE 1547)

`analysis.voltageTrip` (**Analysis › Voltage Trip Check**) checks whether an inverter ceased to energize and tripped in time on an abnormal grid voltage in the last run, as IEEE Std 1547-2018 clause 6.4.1 asks. Sag or swell the grid as for the ride-through check (`grid3` `sagDepth`, `sagStart`, `sagEnd`), give the phase-to-neutral voltages (`voltages`) and the inverter's phase currents in the same order (`currents`), and its category (`category`, `I`, `II` or `III`, Tables 11, 12 and 13).

Each of the four shall-trip functions has a threshold and a clearing time: OV2 (1.20 p.u., 0.16 s, fixed), OV1 (1.10 p.u.; 2 s, or 13 s in Category III), UV1 (0.70 p.u. for 2 s in Category I or 10 s in Category II; 0.88 p.u. for 21 s in Category III) and UV2 (0.45 p.u. for 0.16 s; 0.50 p.u. for 2 s in Category III). The Area EPS operator may set other values within the table's ranges of allowable settings: give them as `tripSettings`, for example `{"uv1": {"pu": 0.88, "s": 2}}`; a value outside the range is refused with the range. An undervoltage function reads the least one-cycle rms phase voltage and an overvoltage one the greatest. A function asks for the trip once its voltage has stayed beyond the threshold for the whole clearing time; of those, the earliest deadline decides (`trip`). The inverter counts as ceased once its one-cycle rms current stays at or below `ceaseShare` (1 % of the pre-disturbance current, a setting of the check, not of the standard).

The `verdict` is `pass` when it ceased within the clearing time, `fail` when it ceased later or still energizes at the deadline, `incomplete` when the run ends before the deadline (run longer), and `notRequired` when no voltage stayed beyond a threshold for its clearing time; whether it then had to ride through is `analysis.rideThrough`'s question. The table values were taken from a reproduction of Tables 11 to 13 (listed in `sources`): check them against the standard. Frequency tripping (Table 18) is `analysis.frequencyTrip`; reconnection is not checked.

On `microgridIslanding` with its breaker kept closed and `G1` sagging to 0.3 p.u. (`sagDepth` 0.7) at 0.5 s, UV2 asks the PV inverter to stop within 0.16 s. It has no voltage trip and keeps its current, so the check fails; a sag to 0.6 p.u. for 0.3 s asks no trip of a Category II inverter.

## Frequency trip (IEEE 1547)

`analysis.frequencyTrip` (**Analysis › Frequency Trip Check**) checks whether an inverter ceased to energize and tripped in time on an abnormal grid frequency in the last run, as IEEE Std 1547-2018 clause 6.5.1 asks. Move the grid frequency as for the frequency ride-through check (`grid3` `fDev`, `fStart`, `fEnd`, `fRate`) and give the phase-to-neutral voltages (`voltages`) and the inverter's phase currents in the same order (`currents`). Table 18 is the same for every category and is written in hertz for a 60 Hz system, so the fundamental must be 60 Hz.

The four shall-trip functions and their defaults are OF2 (62.0 Hz, 0.16 s), OF1 (61.2 Hz, 300 s), UF1 (58.5 Hz, 300 s) and UF2 (56.5 Hz, 0.16 s). The Area EPS operator may set other values within the table's ranges of allowable settings: give them as `tripSettings`, for example `{"uf1": {"hz": 59, "s": 180}}`; a value outside the range is refused with the range. The frequency is measured on the first voltage, one value per cycle, and the clause applies only while some phase is above 30 % of its nominal voltage. A function asks for the trip once the frequency has stayed beyond it for the whole clearing time; of those, the earliest deadline decides (`trip`). The inverter counts as ceased once its one-cycle rms current stays at or below `ceaseShare` (1 % of the pre-disturbance current, a setting of the check).

The `verdict` is `pass`, `fail`, `incomplete` or `notRequired`, as for the voltage trip check. The table values were taken from a reproduction of Table 18 (listed in `sources`): check them against the standard. Reconnection is `analysis.returnToService`'s.

On `microgridIslanding` at 60 Hz with its breaker kept closed and `G1` stepped to 62.5 Hz (`fDev` 2.5) at 0.5 s, OF2 asks the PV inverter to stop within 0.16 s. As shipped it keeps its current and fails; with a latched frequency trip on its phase-locked loop it ceases at once and passes. The same step back after 0.1 s (`fEnd` 0.6) asks no trip.

## Return to service (IEEE 1547)

`analysis.returnToService` (**Analysis › Return to Service Check**) checks how an inverter came back after a trip in the last run, as IEEE Std 1547-2018 clause 6.6 asks through clause 4.10.2: it may energize again only once the applicable voltage and the frequency are inside the enter-service ranges of Table 4, and after the return-to-service delay. Give the phase-to-neutral voltages (`voltages`) and the inverter's phase currents in the same order (`currents`). Table 4 is the same for every category and is written in hertz for a 60 Hz system, so the fundamental must be 60 Hz.

The default ranges are 0.917 to 1.05 p.u. and 59.5 to 60.1 Hz. The Area EPS operator may set others within the table's ranges of allowable settings: give them as `enterService`, for example `{"vMinPu": 0.88, "fMaxHz": 60.5}`; a value outside the range is refused with the range. The delay (`delayS`) defaults to 300 s and is counted from when the voltage and the frequency came back inside the ranges; a simulation seldom runs that long, so give the delay the inverter's logic uses. The inverter counts as ceased while its one-cycle rms current is at or below `ceaseShare` (1 % of the greatest in the five cycles before, a setting of the check) and as returned once it rises above that again.

The `verdict` is `pass` when it returned inside the ranges after the delay, `fail` when it returned outside them (`checks` `range`) or sooner (`checks` `delay`), `notReturned` when it stays ceased to the end of the run (`permittedAt` says when it could first have returned), and `notRequired` when it never ceased. The table values and the 300 s default were taken from a reproduction (listed in `sources`): check them against the standard. With `permitService: false` (the operator's permit service setting disabled) the inverter must stay ceased: staying ceased passes and any return fails (`checks` `permit`).

Give `ramp` to check the ramp-up after the return as well (clause 4.10.3 c): the active output must rise linearly or in a stepwise linear ramp to full output over `periodS` (default 300 s), with steps of no more than 20 % of the rating (`ratedVA`; without it the apparent output before the trip stands in, which is stricter when the inverter ran below its rating). `checks` `step` holds the greatest rise within a cycle, and `ramp` how far the output runs ahead of the straight line to full output, where one 20 % step is allowed. Either over 20 % fails the verdict. The 300 s and 20 % values were taken from a restatement of the clause (listed in `sources`). `ramp` is only checked when given.

A small inverter may instead enter service after a randomized delay (clause 4.10.3): once the ranges have held for the delay, it waits a further random time up to `maxS`. Give `randomDelay` `{"maxS": 120}` to check it: `maxS` is 1 to 1000 s, and the option is refused together with `ramp` or for an inverter of 500 kVA or more (`ratedVA`, or else the apparent output before the trip). A single run cannot check the random draw, so the check holds the return to its window: `checks` `random` holds how long past the delay it returned (`randomDelay.extraS`), which must be 0 to `maxS`, and `randomDelay.latestAt` says when it should have returned at the latest. These values were taken from an open implementation of the clause (EPRI OpenDER 2.2.0, listed in `sources`).

On `microgridIslanding` at 60 Hz with its breaker kept closed and `G1` at 62.5 Hz from 0.5 s to 0.8 s (`fDev` 2.5, `fEnd` 0.8), a latched frequency trip stops the PV inverter at once. Released at 1.1 s, about 0.25 s after the measured frequency is back inside the range, it passes a 0.2 s delay and fails a 0.4 s one; released at 0.65 s, while the grid is still at 62.5 Hz, it fails the range. Asked to ramp up, the instant return fails its full-power step (`stepPct` about 100); with its enable ramped over 0.15 s the output rises about 11 % per cycle, so it passes `{"ramp": {"periodS": 0.15}}` and fails a 0.3 s ramp for running about 42 % ahead of the line. With `delayS` 0 and `{"randomDelay": {"maxS": 1}}`, the release at 1.1 s passes, and one at 2.2 s, about 1.35 s after the frequency came back, fails as too late.

## dq impedance and the weak-grid check

`analysis.dqImpedance` (**Analysis › dq Impedance**) measures a three-phase converter's output impedance in the dq frame (Zdd, Zdq, Zqd, Zqq) and its positive- and negative-sequence impedance, from small-signal injections at its three terminals. The form starts on the circuit's three-phase grid (or the selected part with pins a, b and c) as **Three-phase part**, and at that grid's frequency as **Grid frequency**; give **Terminal nets** instead to name the three nets yourself. Under **Grid impedance**, give the grid inductance, or a **Short-circuit ratio** (one or several) with the **Rated line voltage** and **Rated power**, and the grid resistance or its X/R ratio: the check then reports, for each case, the margin of the eigenloci of Zgrid·Yconverter, whether the system is stable, and the critical SCR below which the margin turns negative. The linear method works at the converter's operating point, with its switches in the states you give, and leaves out the PLL's frequency coupling. The perturbation method measures the switched converter on the transient solver around its grid-periodic operating point, PLL and dq control included, so Zdd and Zqq differ. With it, **Three-phase part** names the grid source the converter hangs on. The result window draws Zdd, Zdq, Zqd and Zqq as a Bode plot (magnitude in ohms and phase). It writes one line per grid case, green when stable and red when not, with the margin and the frequency it is read at, then the critical SCR. Under them is the generalised Nyquist plot: the two eigenloci of Zgrid·Yconverter for each case, their mirrors for negative frequencies, the unit circle and −1. A stable system's loci never encircle −1.

## Conducted EMI and the input filter

`emi.conducted` (**Design › Automate › Conducted EMI**) is a pre-compliance estimate, not a compliance measurement. It puts a LISN (50 µH, 0.1 µF, 50 Ω) on a copy of the circuit on the input, runs it, and reads peak, quasi-peak and average through a 9 kHz receiver model against CISPR 32 class A or B (`limit`). When the supply's return is not the ground node, both lines get a LISN and the reply splits the result into differential mode (`before.dm`) and common mode (`before.cm`). The [conducted EMI tutorial](https://voltecx-web.nguyenvanqui291.workers.dev/docs/tutorials/09-conducted-emi/) walks through it.

The input is the circuit's DC voltage source, or, when it has none, its sine source: an AC mains input such as a diode bridge and PFC (`source` names it when there are several). On an AC input the LISN goes on L and N, the run settles for whole mains periods (`tSettle` is rounded up), and then reads 8 windows of whole switching periods at equal phases of the next mains period, since the switching changes over the mains cycle. The receiver envelopes of the 8 windows are joined: peak is the largest, average the mean and quasi-peak the detector's value over the mains period. Each window must fit in an eighth of the mains period (2.5 ms at 50 Hz). `before.inputVoltageV` and `inputCurrentA` are then RMS values (`inputRms`), the filter capacitors start uncharged, and the touch-current limit is held at the source's own frequency and voltage unless `mainsHz` and `mainsV` say otherwise. Each limit in `crates/engine/src/emi/limits.json` names its document, the artificial network it is measured with (`lisn`) and the receiver bandwidth (`rbwHz`), each with its source; the reply's `setup` repeats them. The limits are:

| `limit` | Standard | Port | Detectors | Network, receiver |
|---|---|---|---|---|
| `cispr32A`, `cispr32B` | CISPR 32:2015 Annex A | AC mains | quasi-peak, average | 50 µH / 50 Ω, 9 kHz |
| `cispr11A`, `cispr11B` | CISPR 11:2015+A2:2019 group 1 (class A up to 20 kVA) | AC mains | quasi-peak, average | 50 µH / 50 Ω, 9 kHz |
| `cispr25Class1` … `cispr25Class5` | CISPR 25 Ed. 5 (2021), voltage method | DC supply line | peak, average, quasi-peak | 5 µH + 1 Ω / 50 Ω, 9 kHz |

**The CISPR 11 and CISPR 25 values come from secondary sources** (articles that reproduce the standards' tables; `limit.source` names them) **and were not checked against the standards' text.** The reply marks them `"provenance": "secondary"` and a note says so; check them against the standard before relying on a margin. CISPR 11 class A above 20 kVA is not included (its values were not found). CISPR 25 applies only inside its broadcast bands (nothing between them); its quasi-peak line comes from one source only, and its bands above 30 MHz are in the file but not assessed, because the conducted measurement ends at 30 MHz. Its network's sources give no coupling capacitor, so Voltecx couples the receiver through a DC block (1 % of 50 Ω at 150 kHz) and says so. Where a limit gives a peak line, the peak reading is held to it; otherwise peak is only a screen against the quasi-peak line. MIL-STD-461G CE102 is not included: its limit is a figure whose breakpoints are not available. The limits are the mains-port tables, so an AC input is measured as they intend; a DC input held to them is a pre-compliance screen, and a note says so.

When the margin is below `targetMarginDb` (6 dB), it sizes a filter, measures again with it and, with `"apply": true`, inserts it in one undo step:

- **Differential mode:** one or two damped LC stages, held to Middlebrook's condition against the converter's input impedance (`zinOhm`, or the measured V/I).
- **Common mode** (two LISNs and a path to ground): a common-mode choke in both lines and a Y capacitor from each line to ground. The Y capacitors are limited by your product's safety standard, so Voltecx needs that limit and has no default: give `yCapMax` (farads per line), or `touchCurrent` with `mainsHz` and `mainsV` (it then allows `touchCurrent/(2π·mainsHz·mainsV)` per line). The choke is a catalogue part (`parts/common_mode_chokes.json`, each row read from its data sheet) whose worst-case common-mode inductance reaches the corner; the Y capacitor is the largest catalogue Y2 part under the limit. The choke's stray inductance stays in the differential path. With a common-mode stage the LC stages are sized from the differential readings only.

```json
{"limit": "cispr32B", "touchCurrent": "<from your standard>", "mainsHz": 50, "mainsV": 230, "apply": true}
```

The reply's `filter.commonMode` names the choke and Y capacitor with their data sheets, and `improvementCmDb` and `improvementDmDb` give the gain in each mode. Without a limit a note says so and only the LC stages are sized. When no catalogue choke reaches the inductance, the stage takes the rated choke with the most (`commonMode.reaches` is false) and the measurement shows what it falls short by.

**The filter is built from real parts.** The LC stages are not ideal values: each element is a catalogue part, chosen with the same rules `bom.export` uses, and the filter is sized again around it.

| Element | Catalogue | What the circuit gets |
|---|---|---|
| Series inductor | Coilcraft XAL and AGP4233 (the parts library's inductors, `crates/library/data/inductor.ndjson`), at or above the inductance, rated for the input current (RMS at a 40 K rise, peak under the saturation current, with `analysis.stress`'s derating) | the set's inductance, its typical DCR (`dcr`) and the part number (`part`, `2 × XAL7070-472MEC` for two in series) |
| Line capacitors on a DC input | `parts/capacitors.json`, as many in parallel as reach the capacitance left at the input voltage's DC bias; a part with a published self-resonant frequency first | the capacitance at the DC bias, the data-sheet ESR and the part number |
| Line capacitors on an AC input | X2 film from `parts/safety_capacitors.json` | the capacitance, the ESR from the data sheet's dissipation factor and the part number |
| Damping resistor | the nearest E96 value of a Vishay chip-resistor family | the E96 value |

With the real L and C the corner, the damping and Middlebrook's check are worked out again. `filter.catalogue` lists each part with its data sheet, its self-resonant frequency (`srfHz`) and the ESL or winding capacitance that follows from it; an element no catalogue part reaches stays ideal and is listed under `catalogue.missing` with the reason. `filter.insertionLoss` gives the LC stages' insertion loss from 1 to 30 MHz with ideal parts and with the parts' ESR, DCR, ESL and winding capacitance: above the parts' SRF the filter stops gaining, and the measurement with `parasitics` on (below) uses the same elements, so the margin in the upper bands is the parts' own.

**Sized until it meets the target.** The filter is measured, and while its margin misses `targetMarginDb` it is sized again for what it lacked (a second LC stage when one is not enough, a larger choke), up to four rounds; `rounds` lists each. `pass` is true only when the worst margin meets the target, Middlebrook's check passes and the loop keeps its phase margin. With `"apply": true` a filter that misses any of these is **not** applied: `applied` stays false and `applyRefused` says what fell short and what to change (raise `yCapMax` if the safety standard allows, relax the target, fix the coupling at the source).

**A DC input drawn with its return on ground** has no common-mode path, because the LISNs use ground as the chassis. Give `cChassis`, the switch node's (or heat sink's) capacitance to the chassis, and the measured copies are drawn as the board stands on the bench: the converter's return moves to its own net, `cChassis` joins `chassisNode` (default the switch node of `layout.hints`) to ground, both lines get a LISN, and the reply splits `before.cm` and `before.dm`. An AC input whose bridge sits on the ground node is lifted the same way; without `cChassis` a note says its common mode reads far too high. Your circuit is never changed by this. A common-mode stage cannot be drawn into a circuit whose return is the ground node, so `apply` is then refused with that reason: draw the return as its own net first.

```json
{"cChassis": "50p", "yCapMax": "4.7n", "apply": true}
```

**The loop with the filter.** With `apply` (or `pmMinDeg`) the command measures `analysis.loopGain` on copies of the circuit without and with the filter (whole fractions of fsw between fsw/200 and fsw/5) and runs a load step on each (the load resistor halved half-way through the run). `loopPmBefore` and `loopPmAfter` are the phase margins; below `pmMinDeg` (the call's, else the stored design spec's, else 45°) the filter is refused. `stability.zoCurve` is the filter's |Zo(f)| to hold against `stability.zinOhm`. A circuit without a pi or tf block driving its PWM has no loop to measure, and a note says so. `"loopCheck": false` skips the measurement.

**A measured scan.** `measured` overlays a receiver's or spectrum analyser's export on the limit and the prediction: `{"csv": "<text>"}` or `{"path": "scan.csv"}`, with the `detector` it was taken with (`peak`, `qp` or `av`). Each line holds a frequency (Hz, or MHz or kHz when the header says so) and a level in dBµV. `measured.bands` gives each band's measured and predicted worst margin and their difference (`deltaDb`, positive when the prediction was optimistic).

## Devices: vendor parts and your own datasheet tables

The device library holds two kinds of built-in parts. A generic device is an illustrative set of values for a class of part. A vendor part is a real part number whose values were read from the manufacturer's datasheet. `library.deviceModels` and `library.search` mark every device as `vendor`, `generic` or `user`. The library panel shows the manufacturer in front of a vendor part.

Every vendor part carries its source: the manufacturer, the datasheet URL, the revision, and the figures or tables the values came from. The curves were digitised coarsely, and the notes of the part say how and under which test conditions. Some datasheets give a curve at one temperature only. The notes then say so.

### IGBT power modules

The library also holds IGBT power modules: half bridges (Infineon EconoDUAL 3, 650 V to 1700 V, 300 A to 900 A) and six-packs (EconoPACK 3, EasyPACK 1B and 2B, 25 A to 100 A). A module is an `igbt` device with a `module` field: its `topology` (`halfBridge` or `sixPack`), its `package`, and its switch positions with the pins of each collector, emitter, gate and auxiliary emitter, as the data sheet's circuit diagram shows them. The loss tables are those of one IGBT and its diode, and every position of the case has them: the output characteristic at VGE = 15 V, Eon and Eoff over the collector current, the diode's forward characteristic and its Erec, each at the data sheet's temperatures, and the IGBT's Foster chain from the r/τ table of its transient thermal impedance figure. `rthCh` is the case-to-heat-sink resistance per IGBT with the data sheet's grease. A module without a baseplate (EasyPACK) is rated junction to heat sink, so its chain already ends at the heat sink: `chainToHeatsink` is true and it has no `rthCh`.

`library.search` with `"module": true` lists only modules, with `false` only discrete parts; each row has `module` (null for a discrete part). To use a module, give its id to the IGBTs of a leg or bridge, and to their anti-parallel diodes: a diode that names an IGBT device takes that device's diode tables. `design.parts` ranks modules with the discrete IGBTs and names the module it proposes in `module`.

The library has discrete IGBTs too (TRENCHSTOP 7 and 5, 650 V and 1200 V, TO-247). Their energies are given at one temperature (175 °C) as curves; the 25 °C energies are table values only, and the notes say so. Where a data sheet's curve and its table differ, the notes give both.

MOSFETs from Taiwanese makers cover synchronous rectification, point-of-load and PFC: Advanced Power Electronics (APEC) at 40, 60, 80, 100 and 650 V, PANJIT at 30, 100 and 650 V, and Excelliance MOS at 60 and 80 V, Niko-Sem at 40, 60, 80 and 100 V, and Sinopower at 30, 40, 60 and 100 V. Their data sheets give no switching energy, so these parts carry gate and output charges instead. SiC MOSFETs span 650 V to 3300 V: onsemi EliteSiC at 650 V, 1200 V and 1700 V, ROHM at 650 V (SCT3060AL), 1200 V (SCT4036KE) and 1700 V (SCT2H12NZ, a 1.15 Ω part for auxiliary supplies), and a GeneSiC 3300 V part. An onsemi part whose sheet gives its energies only in the table carries that one point at the table's voltage and current; the others carry the curves of their figures. The ROHM sheets print a three-stage Foster network, which the parts carry as printed, and say their Eon includes the body diode's recovery. The SCT2H12NZ carries no body-diode curve: its figure and its table disagree by 15 % at the table's current, and the notes say so.

To bring a part of your own, write its datasheet tables as CSV text and run `device.import`:

```json
{"command": "device.import", "params": {"format": "csv", "name": "mine/part-1", "text": "..."}}
```

`device.export` writes any library part in the same layout, which is the easiest way to see an example. `"format": "json"` takes the Voltecx device JSON instead. The import reads the text strictly. A bad table is refused with a message that names the line. The part then goes through the same checks as `device.validate`, and it is added to the open circuit, or to the session library when no circuit is open.

The text is a list of rows. Blank lines and lines that start with `#` are ignored. The rows about the part come first. Each one is a name, a comma and a value, and the value is the rest of the line, so it may hold commas: `id`, `kind` (`mosfet`, `igbt` or `diode`), `manufacturer`, `part`, `source`, `vMax` in volts, `iMax` in amperes, `notes` and, when the datasheet gives them, `tjMax`, the highest junction temperature in °C, `vgsMax`, the gate-source (gate-emitter) rating in volts, and `vgsMin`, its negative limit in volts (below zero, given only with `vgsMax`); `vgsOn`, the turn-on gate voltage the datasheet recommends, in volts (`design.gateDrive` then drives the switch at it unless the circuit sets `von`); `module`, a power module's case and pinout as one line of JSON (the `module` field of the device JSON); and `lineRectifier,true` for a standard-recovery mains rectifier, which `device.recommend` and `design.parts` give only to a diode reverse-biased at mains rate (a bridge diode), and take first there. The `source` row is required, and it should say which datasheet, revision and date the numbers come from. The tables come next. A row `section,<name>` starts a table, and the row after it names the columns. The unit is part of each column name, so a value in the wrong unit cannot be read as the right one.

| Section | Columns | One curve per |
|---|---|---|
| `conduction`, `diodeConduction` | `tj_c`, `i_a`, `v_v` (or `v_mv`) | temperature |
| `switching` | `tj_c`, `v_v`, `i_a`, and any of `eon_j`, `eoff_j`, `err_j` (or `_mj`, `_uj`) | test voltage and temperature, for each energy |
| `thermal` | `r_k_per_w`, `tau_s` (or `tau_ms`, `tau_us`) | one Foster stage per row |

In a `switching` table, leave a cell empty when a row has no value for that energy. A `thermal` table may instead have the single column `rth_jc_k_per_w` with one row. The import then assumes a time constant of 1 ms and adds a line to the notes that says so. Currents must rise along a curve. Values are plain numbers with no unit text. The limits are 256 KiB of text, 5000 data rows, 200 points per curve, 10 thermal stages and 16 temperatures.

Many low-voltage MOSFET datasheets give no switching energies. For such a part, add a `charges` section with one row and any of the columns `qg_c`, `qgs_c`, `qgd_c`, `qsw_c`, `qgth_c`, `qoss_c` (or `_nc`), `coss_pf` with `vcoss_v`, `vplateau_v`, `vth_v`, `gfs_s`, `rgint_ohm`, `qgvgs_v` (the gate voltage `qg` was measured at) and `qg2_c` (or `qg2_nc`) with `qg2vgs_v` (a second total charge at another gate voltage). With `qgvgs_v` and either the second charge or the plateau with `qgs` and `qgd`, Qg can be scaled to another drive voltage along the straight part of the gate-charge curve above the plateau. When `eOn` and `eOff` are both empty, the loss commands estimate them from these charges with the gate-charge method. The gate current is set by the driver voltage, the plateau and the gate resistance (external plus internal). The switching time is Qsw over that current, and the energy is V·I·t/2, plus Qoss·V at turn-on. The driver is the MOSFET's `von`, `voff`, `rgon` and `rgoff` when the circuit sets them, otherwise 10 V, 0 V and 2 Ω. Every loss report says when it used this estimate.

A vendor's PLECS thermal description file (`.xml`, the format PLECS reads for loss and thermal data) imports with `"format": "plecs-xml"`: its switching-energy and conduction tables and its Foster or Cauer junction-to-case chain become the device's tables (a Cauer ladder becomes the Foster chain with the same impedance). The file carries no voltage or current rating, so give `vMax` and `iMax` from the data sheet. The reply's `warnings` list what was not mapped: tables computed with a formula (kept as tabulated, the formula and its variables are not applied), curves at 0 V, points below 0 A, and any element the reader does not know. Details are in `docs/formats/plecs-thermal.md`.

```json
{"command": "device.import", "params": {"format": "plecs-xml", "text": "<?xml ...", "vMax": 1200, "iMax": 50}}
```

The numbers below only show the layout. They are not a real part:

```
id,mine/part-1
kind,mosfet
manufacturer,Example
part,EX-650-30
source,Example datasheet rev 1.0 2024-05-01, Fig 3 and Table 4
vMax,650
iMax,40

section,conduction
tj_c,i_a,v_v
25,0,0
25,20,0.8
150,0,0
150,20,1.3

section,switching
tj_c,v_v,i_a,eon_uj,eoff_uj
25,400,20,150,40
25,400,40,380,90

section,thermal
r_k_per_w,tau_ms
0.15,0.2
0.25,2
```

The workflow guide [`docs/workflows/part-selection.md`](https://voltecx-web.nguyenvanqui291.workers.dev/docs/workflows/part-selection/) has the full field list and the datasheet checks.

### Example: importing a thermal description

The repository's test file `crates/plecs-fmt/tests/fixtures/synthetic_igbt.xml` was written for the tests with round numbers of no real part: an IGBT with its diode, loss tables at two temperatures, a diode recovery energy given with a formula, and a four-stage Foster chain. With `jq` to put the file's text into the parameters:

```sh
powercraft-cli run --cmd file.new --params '{}' \
  --cmd device.import --params "$(jq -Rs '{format: "plecs-xml", text: ., vMax: 1200, iMax: 50}' synthetic_igbt.xml)"
```

The reply adds the device `plecs/syn-igbt-50` (kind `igbt`) to the circuit with 2 conduction curves, 2 turn-on, 2 turn-off and 2 recovery-energy curves and 4 thermal stages. Its 6 `warnings` say that the `CustomTables` element (line 96) is not read, that the curves at 0 V are not read for each of the three energies, that the recovery-energy table is kept as tabulated because the formula `E*(600/Rg)/60` is not applied, and that the formula variable `Rg = 10` is not applied.

### Limits of the PLECS thermal import

- The reader has been tested only on that synthetic file. Its element names have not yet been compared line by line with the published PLECS description of the format (see `docs/formats/plecs-thermal.md`), so check the warnings of a vendor's file.
- Only the first package and the first thermal branch are read; a warning names the others.
- Formulas and their variables are not applied, and a diode's turn-on energy is not mapped.
- Curves at 0 V and below, and points below 0 A, are left out.
- The file has no rating, so `vMax` and `iMax` are required. A class other than IGBT, MOSFET or diode (a thyristor, for example) is refused.
- `device.import` takes at most 8 MiB of text, and a document type declaration is refused. Voltecx never writes this format.

### Double-pulse test of a library device

`device.doublePulse {"device": "<library id>", "rgOn": 10, ...}` runs the double-pulse bench on one library MOSFET or GaN HEMT in a scratch circuit (the open circuit is never touched) and compares the simulated turn-on and turn-off energies with the data sheet's Eon and Eoff tables. The device needs gate data and those tables. Give the gate resistor `rgOn` (and `rgOff`), and the data sheet's test gate voltage `vgsOn`/`vgsOff` when the part states no recommended one; the command refuses to guess it (a GaN part with a 7 V gate rating does not get the 15 V default). `v`, `i` and `tj` default to the first Eon curve's voltage, current points (at most 8) and temperature. `lStray` is the power-loop inductance (default 0, the ideal-board limit), `lcs` the common-source inductance of the gate loop, and `qrr`/`trr` the body-diode recovery from its data sheet.

The reply holds, per current, `eOnSim`/`eOnTable`/`eOnErr` and `eOffSim`/`eOffTable`/`eOffErr` (joules; an error is a fraction, simulated minus table over table). Read the errors: a large one means the gate drive or the loop inductance you gave is not the one behind the table, not that the part is wrong. `sweep {"lStray": [...]}` or `{"rgOn": [...]}` (at most 8 values) repeats the run per value, which shows how much a board's loop inductance or a gate resistor costs in switching energy.

## Radiated EMI

**Design › Automate › Radiated EMI** (`emi.radiated`) is a pre-compliance estimate, not a measurement: use it to see how far you are from the limit and which layout change helps most, then measure. It estimates the field from 30 MHz to 1 GHz with Paul's formulas: the switch node driving its capacitance to the chassis and the cable as a common-mode antenna, and the hot loop as a small loop, against CISPR 32 class A or B. The form takes the limit, the distance (3 m or 10 m) and the board's numbers. Leave a field empty to take the circuit's value: the swing and the loop current come from the first hot loop of `layout.hints`, and the switch node's capacitance to the chassis is the sum of the capacitors drawn from the switch node to ground when the input's return is not ground (ground is then the chassis, as with two LISNs). The loop area (1 cm²), the capacitance to the chassis (10 pF) and the cable length (1 m) are typical values when nothing gives them.

**A switch on a heat sink.** A MOSFET, IGBT or diode whose tab pin is a hot loop's switch node (the tab is a MOSFET's drain, an IGBT's collector and a diode's cathode, as their data sheets draw it; a boost's diode, with its anode on the switch node, has its tab on the quiet output) and whose case sits on a heat sink through an insulating pad couples the switch node to the heat sink through its tab. Draw the thermal network (the switch's `thermal` net, an `rth` to the case, an `rth` for the pad with its library `part`, then a `heatsink`; `design.thermal {apply: true}` draws all of it, the pad's `part` being the interface it picked) and the estimate takes the tab's capacitance, ε0·εr·A/d: the pad's dielectric constant and thickness from its data sheet, and the package's largest exposed tab from its outline drawing (TO-247). `inputs.cSwSource` is `heatsink`, and `commonMode` has a row with `via: "tab"` naming the switch, the pad and the heat sink. With a routed board the tabs add to the chassis fills. The heat sink is taken as earthed; if it floats, give `cSw`. A grease, a pad the library does not hold, or a package with no tab size is named in a note and left out.

The result window shows the verdict first, then **Assumed values** in an amber box: each value the estimate did not get from you or the circuit, with a field. Type the board's value (`40u` for 40 mm², `22p`, `2`) and press **Run Again**. Below it, **Inputs** says where every number came from (given, layout hints, the circuit, the input source, assumed). With a routed board, **Hot loops at** the worst line lists each loop in the differential-mode sum (power and gate loops) with its area, peak current, where that current came from (**Current from**: given, layout hints, same as the first hot loop, or the run) and field, and a gate loop names the switch it drives, and **Common-mode paths at** that line lists each switch node's path to a chassis fill or, through a switch's tab, a heat sink, with its capacitance, swing and field; both tables are largest first, and a row the simulation left out of the sum says **Not in the sum**. **Cables and connectors** lists where each cable leaves the board, nearest the switch node first: the connector, its nets, its role (input, load or other), the board side and the distance from its nearest pad to the switch node's copper. It does not change the estimate, which still uses the cable length in **Inputs**. **Layout changes** lists the changes that raise the worst margin most.

### From the routed board

Give the routed board and the estimate reads it through `layout.extract`: `path` (a `.kicad_pcb` of this circuit), `text` (its text) or `board` (a Voltecx `.vxpcb` text). Then:

- **Every power loop counts.** The loop area is the sum of every complete power loop on the board, each weighted by its own current: `iLoop` when you give one, else that loop's own peak current from `layout.hints`, matched by the loop's name, else the first hot loop's current, with a note naming the loop. `loops` lists each loop with its area, its current and where that came from, and its own field at the worst line.
- **Gate loops, with the driver's current.** Give `iGate`, the gate driver's peak current from its data sheet, and every complete gate loop joins the sum as a loop of its own (kind `gate`). Without it, a current run whose switches have a modelled gate (a MOSFET at the dynamic level) gives each gate loop its own switch's peak gate current: the current the driver puts into the gate, `i(<switch>.cgs) − i(<switch>.cgd)`, at its peak over the run's second half (`currentSource` `run`, `inputs.iGateSource` `run`, and `switch` on the row). With the switches driven as signals, or with no current run, the gate loops are left out. The gate pulse is taken with the power loop's duty and edge, so the gate loops' share is an upper bound.
- **Common mode from the copper.** The switch node's capacitance to the chassis is the parallel-plate capacitance of every hot loop's switch-node copper to a chassis or heat-sink fill, summed. The fill is `chassisNet`, else any net named PE or starting with CHASSIS, EARTH, HEATSINK or SHIELD. `commonMode` has one row per switch node and fill: its capacitance, its swing, and its share of the common-mode current and field.
- **Each leg at its own timing.** When the last run recorded `v(<node>)` for each of those switch nodes, each node's frequency, phase and duty are read off the run (`inputs.cmTiming` is `simulated`; the duty is the time above half the swing, `legDuty`, and replaces the request's `duty` for that node's trapezoid): legs in antiphase cancel at the odd harmonics, complementary legs (one high while the other is low, as in a full bridge) cancel at every harmonic, and a leg that switches slowly, such as a totem-pole's line-frequency leg, adds no line at the switching harmonics. Without such a run the nodes are added in phase, the worst case (`inPhase`).
- **A slow leg's loop leaves the differential-mode sum.** The same run gives each power loop in `loops` its `switchNode`, `timing`, `legHz` and `inSum`. A loop whose switch node switches below half the switching frequency, or not at all, carries no current at the switching harmonics: it leaves the loop-area sum (`inSum: false`, no field of its own) and a note names it. The loops left in the sum add as phasors when the board and the run say how:
- **Loops with their phase and their direction.** Each power row also gets `phaseDeg`, its leg's phase, and `circulation` (+1 or −1): which way its current change goes round the board at the switch node's rising edge. The direction comes from the order of the loop's parts in `layout.extract`, the rails' mean voltages in the run and the inductor current's sign at every rising edge. When every loop in the sum has both, the loops add as phasors (`inputs.dmTiming` is `simulated`), each loop's current pulse at its own leg's duty (`legDuty`): two legs in antiphase whose loops are drawn as mirror images cancel at the even harmonics, and two drawn alike cancel at the odd ones. The cancellation shrinks as the frequency rises, since the loops sit apart on the board: the estimate adds k·Σ|z|ρ (k = 2πf/c, |z| each loop's weighted area, ρ its distance from the loops' common centre), so it is never below the field in any direction, and never above the amplitude sum (the array factor, Balanis, *Antenna Theory*, 3rd ed., chapter 6). Otherwise (no run, a loop with no inductor on its switch node, or an inverter leg whose current changes sign over the line period) the loops are added in amplitude, the worst case (`amplitude`).
- **Where the cables leave.** With a routed board (a KiCad board, or Voltecx's own `.vxpcb` given as `board` or by its `path`), `cables` lists each connector where a cable leaves the board, its role (input, load or other) and its distance to the switch node's copper, nearest first. It does not change the estimate: the board does not say how long the cable is, so `cableLength` stays yours or assumed.

### Near-field map of the board

`emi.nearField` maps the magnetic near field over the routed board, to see which loop to fix before you take a probe to it. The board window's **Near field** button draws the same map on the board (chapter 22).

- **The sources.** Each complete power loop from `layout.extract` is its own copper path carrying its own current: `iLoop`, else its peak current from `layout.hints`, matched by name. Gate loops carry `iGate`; without it, a current run whose switches have a modelled gate (a MOSFET at the dynamic level) gives each gate loop its own switch's peak gate current, as in `emi.radiated` (`currentSource` `run`, with a note that the gate loops' field is then an upper bound). With neither, the gate loops are listed in `skipped`.
- **The field.** The quasi-static Biot–Savart field of each loop's straight pieces (Griffiths, *Introduction to Electrodynamics*, example 5.5) on a plane `heightMm` above the top copper. The default 10 mm is an assumed probe height, not a standard's. The current is the loop's trapezoid at one switching harmonic (Paul, section 3.2): `fHz` takes the harmonic nearest it, by default the first at or above 30 MHz, where the CISPR 32 radiated scan starts.
- **Off a null of the spectrum.** The trapezoid's spectrum is zero at every harmonic n where n times the duty is a whole number (at 50 % duty, every even harmonic). When the default harmonic falls in such a null, the map moves to the strongest harmonic of the lobe it starts, and `steppedFromHarmonic` and a note give the harmonic it moved from. When the loops take their own legs' duties from the run (two or more add as phasors), the null is looked for in their spectra at those duties, each at its own peak current and added in amplitude: a harmonic is a null only where every loop's own spectrum is, and the note names the duties. A harmonic counts as a null when it is more than 20 dB below that strongest one: a threshold of Voltecx's own, not a standard's. A harmonic you ask for with `fHz` is kept; when it is in a null, a note names the strongest harmonic near it, since the map then shows far less than the board radiates around that frequency.
- **Loops with their phase and their direction.** With a current run, each power row in `loops` also gets `switchNode`, `timing`, `legHz`, `phaseDeg`, `circulation` and `legDuty`, read as for `emi.radiated` above, and `phasor` says whether it was added as a phasor. A power loop whose leg switches at the switching frequency and whose current's way round the board the run resolves adds as a phasor: each axis of the field sums the loops' fields turned by their phases at the map's harmonic, and the cell takes the length of that vector. Near the board, loops that share a part can add where their far fields cancel, so read this map, not `emi.radiated`, for where to probe. `dmTiming` is `simulated` when two or more loops add this way, and then each of those loops' current pulse takes its own leg's duty (`legDuty`) instead of the request's `duty`, as in `emi.radiated`: complementary legs (one high while the other is low) cancel at every harmonic, not only at the odd ones; `harmonicA` is each loop's own line. A loop whose leg switches below half the switching frequency, or not at all, carries no current at the map's harmonic and is listed in `skipped`.
- **An upper bound for the rest.** Gate loops, and power loops whose phase or direction the run does not resolve, add in amplitude on top of that sum: the worst case for them. Without a run every loop does, and `dmTiming` is `amplitude`.
- **The reply.** `levelsDbuam` is the map in dB(µA/m), `dominant` each cell's strongest loop, `hotSpots` the local maxima (strongest first, each with its loop and that loop's share), `loops` each loop with its own peak, its field straight above its centre and its far field at `distanceM` (Paul's small loop), `cables` each cable connector of the board (as `emi.radiated` lists them) with the map's field over it, its strongest loop there and how far it is under the map's strongest cell, strongest first, since a cable that leaves where the field is strong carries it off the board, and `skipped` the loops it could not map and why.

It is an estimate, not a scan, and it changes nothing.

## Debugging tools

`circuit.problems` (the list in **Problems**) checks the circuit for mistakes: a missing ground, floating or unconnected pins, undriven gates, a half bridge without dead time, each with its fixes. `{"compile": true}` adds the reference solver's compile report (nodes, unknowns, warnings). With `{"run": true}` it also runs a short simulation to look for shoot-through, ringing, growing oscillation, a saturated controller and parts over their rating. `circuit.diagnose` and `circuit.check` still answer for older scripts, as aliases of these two forms. `fault.*` inserts an open, a short, a stuck switch or a drifting value so you can see what a failure does. `waveform.compare` lines up your simulation with a measurement, and `debug.fitToMeasurement` moves the values you list (an inductance, an ESR, a dead time) until the simulation matches it. `debug.locateFault` takes the same measurement and ranks the faults that would explain it: it injects each candidate fault into a copy of the circuit, simulates it, and reports the best match only when it beats the circuit without a fault. The guide, organised by symptom, is [`docs/workflows/debugging.md`](https://voltecx-web.nguyenvanqui291.workers.dev/docs/workflows/debugging/).

## Faults at a time and fuse coordination

**Analysis › Faults › Inject Fault** (`fault.inject`) also places a fault that appears part-way through the run: give `at` in seconds and an open, short or ground fault becomes an ideal switch driven by a step block, so one run shows the circuit working, the fault and what the protection does about it. Besides a part (`component`, with `port` for the terminal), a fault can go on nets: `{"net": "a", "kind": "ground"}` shorts net `a` to ground (net `0`), and `{"between": ["a", "b"], "kind": "short"}` shorts two nets together. `value` is the fault's resistance (1 mΩ for a short or ground fault, 1 GΩ for an open). The fault parts are named `Fault_…`, show on the schematic and go away with one undo or **Clear Faults**, which takes a part or a net.

**Analysis › Faults › Fuse Coordination** (`protection.fuseCoordination`) checks two fuses in series: the one nearer the load must clear a fault before the one upstream of it melts. Name the two fuse parts (or give each fuse's melting I²t and minimum melting current). It sweeps the fault current and compares the two melting times of the fuse model (the overcurrent check), and compares the downstream fuse's operating I²t with the upstream fuse's melting I²t (the short-circuit check). The fuse model has no arc, so the operating I²t, pre-arcing plus arcing, comes from the downstream fuse's data sheet (`operatingI2t`); without it the result is **unchecked**, never a pass. Then prove it in simulation: inject a short at a time behind the downstream fuse and run; the warnings name the fuse that opened.

**Analysis › Faults › Protection Coordination** (`protection.coordination`) does the same check for any pair of fuses and circuit breakers. Each side is a fuse or breaker part (a breaker needs `itrip` and trips after `tdelay`), or figures: `{i2t, imin}` for a fuse, `{itrip, tdelay}` for a definite-time breaker, or `{curve, rating}` for a miniature breaker with curve B, C or D to IEC 60898-1 (Table 7, up to 125 A). The standard gives test points, not one curve, so the check uses bounds: at each fault current the upstream device's earliest operating time must come after the downstream device's latest. Set `iMax` to the prospective short-circuit current at the fault. Above an upstream miniature breaker's instantaneous range (5 In for C) the standard promises no selectivity; only the manufacturer's selectivity tables can. With an upstream fuse, give the downstream device's let-through I²t from its data sheet (`letThroughI2t`); without it the result is **unchecked**.

**Analysis › Faults › DESAT Short-Circuit Check** (`protection.desat`) says whether a gate driver's desaturation detector clears a hard short of a power switch before the switch's short-circuit withstand time runs out. Give the bus voltage `vdc`, the power-loop inductance `lLoop`, the detector threshold `vDesat`, the switch's on-state `ron` (and `vCe0` for an IGBT), the blanking time `tBlank`, `tFilter` and the turn-off delay `tOffDelay`; add `isc` (saturation current), `tScWithstand`, `tFall` and `vMax` from the switch data sheet to get the verdict. It returns the detection and short times, the peak current, an energy bound, the withstand margin and the turn-off spike against `vMax`. The loop current is a linear ramp (resistance ignored), so the peak is an upper bound; the model is the one in TI SLUA618A, and every figure is yours (none is assumed). It changes nothing in the circuit.

**Analysis › Faults › Active Short Circuit Check** (`protection.activeShort`) says what a permanent-magnet motor does when a drive fault makes the inverter short its three phases, and whether that or turning every switch off is the safe state. Give the machine's `rs`, `ld`, `lq`, `psif` and `poles` and the speed `rpm`; add the current before the fault (`id0`, `iq0`), the bus voltage `vdc`, the peak current the switches and the machine allow (`iMax`) and the d-axis current that starts demagnetising the magnets (`idDemag`). It returns the steady short current (which tends to `psif/ld` at speed), the braking torque and copper loss, the transient's peak current, its most negative d-axis current and the largest braking torque, and with `vdc` the line-to-line back EMF and the speed above which pulse-off charges the bus through the diodes (`safeState`). The speed is held constant and the inductances are linear (no saturation); the model is the dq one in Jahns and Caliskan (IEEE Trans. Ind. Appl., 1999). Every figure is yours (none is assumed). It changes nothing in the circuit.

**Analysis › Faults › DC Arc Fault** (`protection.arcFault`) says whether a series arc (a loose connector or a broken conductor in a PV string or a battery bus) keeps burning. Give the source voltage `vSource`, the loop resistance `rLoop`, the arc length `gap` and the Ayrton coefficients `ayrton: {a, b, c, d}` (V_arc = a + b·L + (c + d·L)/I, Ayrton 1902). The coefficients depend on the electrodes and the current range, so none is assumed: use the set from the source you trust. The reply gives the stable arc current, its voltage and power, the energy over `duration`, the lowest source voltage that sustains this gap (`minSourceVoltage`), and with `tripCurrent` whether the overcurrent protection would see it. The arc is quasi-static: it has no strike or extinction transient.

**Analysis › Battery Ageing** (`battery.age`) says how much capacity a lithium-ion cell has lost and how much its resistance has grown after `days` of storage and cycling: the cell temperature `temp` (0 to 55 °C), the depth of each cycle `dod`, `cyclesPerDay`, and the cell's average rest voltage `voc` (4.2 V for a cell stored full). The model is NREL's graphite/NMC life model (Smith et al., NREL/CP-5400-67102, 2017): calendar fade with the square root of time, lithium and electrode sites lost with cycles, and resistance growth. It answers as the battery's state of health `soh` (capacity left, a share of new) and resistance growth `rAge`; with `component` and `apply: true` it sets both on that battery, one undo step, so the next run sees the aged cell. Give `soc` (the charge the cell is stored at, or the top of each cycle, 0 to 1) and the negative electrode's potential follows it, from a graphite open-circuit curve (Safari and Delacourt, J. Electrochem. Soc. 158(5), A562, 2011): a cell kept at 65 % ages much slower than a full one, as in the paper's 45 °C storage tests. Without `soc` the state of charge acts only through `voc`, so a cell cycled about mid charge comes out more aged than it is; past the 300 days of the ageing tests the reply says the result is an extrapolation.

With `fromRun: true` and `component`, the stress comes from the last run instead (`simulation.run` or **Simulation › Long Battery Run**): the battery's state of charge is rainflow counted as one period of a repeating mission, so `dod` is its deepest swing and every swing counts as cycles of that depth in proportion to its own; `voc` is the time mean of its cell's rest voltage; `temp` is the mean temperature of its `thermal` net, or else its own `temp` (a `temp` in the call wins). `period` says how much calendar time one run stands for, at least the run's length: a 2 s test cycle that the product sees twice a day is `period: 43200`. Add `soc: "run"` and the negative electrode's potential follows the recorded state of charge, its effect averaged over the run's time: the same graphite curve as a hand `soc`, so a cell cycled about mid charge comes out less aged than with the full-charge reference. The reply's `fromRun` lists what was read (`deepest`, `cyclesPerDay`, `meanSoc`, `voc`, `temp` and where it came from, and `socFromRun`).

**Analysis › Fit Battery Impedance Spectrum** (`battery.fitImpedance`) turns a measured impedance spectrum (EIS) into the battery's cell model. Give the points as `points` (`[[Hz, Re Z, Im Z], ...]`, Im Z negative on the capacitive arc, the frequencies in sweep order) or a file: a CSV or whitespace table whose header names the frequency and the real and imaginary parts (`freq/Hz`, `Re(Z)/Ohm`, `-Im(Z)/Ohm` as EC-Lab writes them; `Zreal`, `Zimag`; `Z'`, `Z''`; in Ω or mΩ), or a one-port Touchstone file of Z or S parameters. It fits `r0`, `rcPairs` parallel RC pairs (1 to 3, default 2) and, with `inductance: true`, the lead inductance, by complex nonlinear least squares with each point weighted by its measured size (Macdonald and Garber, J. Electrochem. Soc. 124(7), 1977; Boukamp, Solid State Ionics 20, 1986). Every value stays positive and inside bounds set by the measured band. The reply gives the battery's `r0`, `r1`, `c1`, `r2`, `c2`, each pair's time constant and corner frequency, how far each value can move (`SpreadPct`), the error at every frequency, and the measured and fitted spectra to plot. `flags` names any value the spectrum does not pin down: a time constant at the edge of the band, or a pair the data does not need. With `component` and `apply: true` the values go on that battery, one undo step; `perCell: true` scales them when you measured one cell of an `ns`-cell battery. Too few points, a frequency out of order or a value that is not a finite number is refused, naming the point.

## Parasitic elements in the conducted EMI estimate

With ideal parts, the conducted estimate is optimistic from about 5 to 30 MHz: a real capacitor's ESL, an inductor's winding capacitance and a switch's Coss let noise through there. Tick **Parasitic elements** on the Conducted EMI form (`"parasitics": true`) to put them on the measured copy, never on your circuit. They come from your circuit's own `esr`, `esl` and `coss`, from **Parasitic values** (data-sheet values by part name, such as `{"Cin": {"esl": "2n"}, "L1": {"srf": "30Meg"}}`), from the capacitor catalogue's ESR (`{"Cin": {"mpn": "<part number>"}}`), from the self-resonant frequency of the catalogue part a capacitor or inductor names in its `part` (an ESL or a winding capacitance; Murata ceramic capacitors and the Coilcraft inductors publish one), or from the assigned device's Coss table. The filter's own parts take theirs the same way. Nothing is assumed: a part with no value is listed as skipped, with what to give. The notes compare the worst margin with and without the parasitics. Chapter 16 lists every key.

## Explain a circuit (beta)

`circuit.explain` reads a circuit you did not draw (imported from LTspice, for example) and says, without simulating, what it is: the topology (buck, boost, flyback, bridge, inverter, LLC, motor drive and more) with a confidence, the role of each part (`S1: high-side switch`), and the main loops and the operating point. Use `{"detail": "full"}` for the long form.
