Metadata-Version: 2.4
Name: qtool-py
Version: 0.4.3
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Dist: numpy>=1.22
Summary: Python bindings for qtool: superconducting-qubit calibration fits and interactive plotly reports.
Author-email: xncz <xncz@outlook.com>
License-Expression: PolyForm-Noncommercial-1.0.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/xncz/qtool

# qtool-py

Python bindings for **[qtool](https://github.com/xncz/qtool)** — superconducting-qubit
calibration analysis: fit the standard spectroscopy / Rabi / Ramsey / T1 / T2-echo /
DRAG sweeps, render each one as an interactive plotly report, and assemble whole
**chip reports** (the chip board plus one page per qubit and per layer/part group).

The fitting core, the plotting and the HTML generation all run in Rust — no part of a fit
enters the interpreter, and `fit_batch` uses every core; Python only holds the API.

That second half is the point. Using 32 cores *from Python* means a `multiprocessing` pool
you have to construct (**1.0–1.5 s** on Windows, 2.7–3.4 s cold), a chunk size you have to
guess, and a pickle per chunk across a pipe — and at 3000 lines it still ends up slower than
a single-threaded scipy fit that was merely handed the analytic Jacobian. `fit_batch` spreads
the same work over the same cores from inside the call, at **17.9×** the serial rate. Numbers
below; method and caveats in the
[main README](https://github.com/xncz/qtool#performance).

## Install

```bash
pip install qtool-py          # or: uv add qtool-py
```

## Quick start

```python
import qtool

# a T1 relaxation sweep: taus (s), iq = complex readout, states = calibrated centres
states = qtool.StateCenters([0.30 + 0.10j, 0.42 + 0.30j])
fit = qtool.t1.fit(taus, iq, states=states)

print(fit.model.t1, dict(fit.params)["t1"])   # value and stderr
qtool.t1.plot(taus, iq, states=states, fit=fit)   # last line of a cell → the report shows up
```

**Nothing has to be loaded by hand.** The returned object is an `Html` (a `str`
subclass): in a notebook it renders itself (the page carries its own plotly.js tag
inside a `srcdoc` iframe), in a script it is just a string, and to save a standalone
page:

```python
from pathlib import Path

qtool.t1.plot(taus, iq, states=states, fit=fit).persist(Path("reports/q0"))
# → reports/q0/t1.html, self-contained
```

## Chip reports

A chip report is **one self-contained HTML file** holding the chip board and one page per
report entity: a qubit page per `Qubit`, a section page per `Part`. The board is
interactive — every device click opens its page, and the header carries a **Layer**
selector and a per-scope **Data** menu that tints the board by any measured parameter.
Selecting a metric also opens a distribution card next to the board: CDF, histogram and a
statistics table for that metric across all qubits (default scope) or all parts of the
selected layer.

```python
import qtool

states = qtool.StateCenters([g0, g1])          # calibrated readout centres
chip = qtool.Chip("chipA")

# topology: names placed on (row, col) of a lattice, 0-based
chip.qubit("q1", 0, 0).qubit("q2", 0, 1).qubit("q3", 1, 1)
chip.coupler("c1", "q1", "q2").coupler("c2", "q2", "q3")

# layers and parts: a part only references names, the part name is the members joined by "-"
# layer.metric(..) declares that layer's default colouring; without it the layer opens on
# "Default" (uncoloured), like the qubit scope without chip.metric(..)
chip.layer("L1").metric(qtool.t1.Param.T1).part(["q1", "c1", "q2"]).part(["q3"])
chip.layer("L2").part(["q1", "c1", "q2"])      # layers may overlap; a layer may not

# entities: build, stack figures, then hand them to the chip
q1 = qtool.Qubit("q1")                         # alive=True by default; alive=False → red on the board
q1 += qtool.t1.plot(taus, iq1, states=states, div_id="q1-t1", frame="T1")
q2 = qtool.Qubit("q2")
q2 += qtool.t1.plot(taus, iq2, states=states, div_id="q2-t1")
chip += q1
chip += q2
chip += qtool.Part("L1", "q1-c1-q2")           # the name must match the declared part

# default: pick the initial board colouring (optional; without it the board is unpainted)
chip.metric(qtool.t1.Param.T1)

chip.persist("plt/chipA.html")
```

### The chip takes live handles, not snapshots

`chip += entity` stores the *object*. Everything you do to it afterwards shows up at the next
render — no re-adding, no syncing:

```python
q1 = qtool.Qubit("q1")
q1 += qtool.t1.plot(taus, iq, states=states, div_id="q1-t1")
chip += q1

q1 += qtool.ramsey.plot(taus2, iq2, states=states, div_id="q1-ramsey")
chip.persist("plt/chipA.html")                 # q1's page already has both cards

# when the reference is gone — or you want the chip to be the source of truth:
again = chip.entity("q1")                      # the very same object: again is q1 → True
again += qtool.t2_echo.plot(taus3, iq3, states=states, div_id="q1-t2echo")
chip.persist("plt/chipA.html")                 # now three cards

# cards come off the same way: with the Html or with its div_id
q1 -= "q1-t2echo"                              # unknown div_id → QtoolError
```

`chip.entity(name)` returns a qubit entity by name, or a part entity when you also pass
`layer=`. The only hard rule is that one entity must not be added twice; both `q1 += card`
before and after `chip += q1` are equivalent, because rendering reads the entities at the
moment of `html()` / `persist()`.

### Parameters, run-time and layout rules

| item | rule |
| --- | --- |
| part name | the member names joined by `-`, in declaration order (`["q1", "c1", "q2"]` → `"q1-c1-q2"`) |
| layer name | free-form; a layer is created on first use, order = first appearance |
| within a layer | a device may belong to **one** part only (disjoint parts) |
| across layers | overlap allowed — the same qubit may head different layers' parts |
| layer parts | a part may omit its couplers: the outline then shows separate blocks |
| diagonal links | a part must not contain a diagonal coupler, nor both ends of one (not supported yet) |
| default colouring | `chip.metric(..)` for the qubit scope, `layer.metric(..)` per layer; each is optional — a scope without one opens on "Default" (unpainted) |
| removed entities | there is no removal API; `Entity` and `Chip` only ever grow |

### Errors

| call | on failure |
| --- | --- |
| `layer.part([...])`, `entity += fig` | `QtoolError`, raised right away (empty part, unknown device, duplicate in the layer, clashing part name, diagonal link) |
| `chip.html()`, `chip.persist(...)` | `QtoolError` — every cross-cutting check runs here: duplicate names/sites, unknown coupler ends, self-loops, a report for a qubit that is not on the chip, a part page without a declared part, the same entity added twice, clashing `div_id`s, a metric no card carries |
| `chip.entity(name)` | `KeyError` when the chip holds no such entity |

`QtoolError` subclasses `Exception`, so `except Exception` catches it. Everything listed as a
run-time check is deliberately deferred to the render call, which means declaration order
never matters and `+=` never fails.

### Saving

* `Html.persist(path)` writes `path/<name>.html` — the argument is a **directory** (`name`
  is the plot's display name: `t1`, `s21_power`, …).
* `Qubit.persist(path)`, `Part.persist(path)` and `Chip.persist(path)` write a single file —
  the argument is the **file path**; missing parent directories are created.

## What is in the box

| Module | Fit |
| --- | --- |
| `qtool.s21` | resonator `S21(f)` (11-parameter complex model), plus the power-sweep report |
| `qtool.qspec` | qubit spectroscopy (Lorentzian), single line and vs. flux |
| `qtool.rabi` | Rabi amplitude (cosine, anchored at `P1(0)=0`) |
| `qtool.iq` | readout IQ clouds: per-state density regions, pairwise separability |
| `qtool.ramsey` / `qtool.t1` / `qtool.t2_echo` | damped cosine and exponentials |
| `qtool.drag.{amplitude,coeff,detuning}` | the DRAG calibration chain (first order and the valley fits) |
| `qtool.bloch` | three-basis readout → Bloch-vector trajectory (3D report) |
| `qtool.jazz` / `qtool.idle_point` | residual ZZ fringe and the idle-point scan over coupler bias |
| `qtool.jazzn` | the jazz-N order chain (`factor_zero` wide window, `factor_k` narrow fit) |
| `qtool.tomography` | three-basis tomography → a single-qubit state in four representations |
| `qtool.virtual_z` | compensation angle from per-tier phases (fed by `qtool.tomography`) |

Every module with a model exposes the same shape: `fit(...)` (raises on failure),
`fit_batch(...)` (one result per line, failures come back as exception **instances**),
and `plot(...)` returning an `Html`. `qtool.iq` and `qtool.bloch` are analysis plus plot —
their entry points are `iq.stats` / `iq.discriminants` and `bloch.bloch_vector`.
Array-valued results cross the boundary as numpy arrays; `params` is a list of
`(name, (value, stderr))` tuples, so `dict(fit.params)["t1"]` is how you look one up.

**Every per-line argument of `fit_batch` takes one entry per line** — the axis, the IQ and the
σ alike: either a 2-D array (its rows are the lines) or a sequence of 1-D arrays. A shared axis
is written `[freqs] * n`, which costs n pointers rather than n copies; a ragged batch, where
each line swept its own window, is just a list:

```python
freqs = np.linspace(6.88e9, 6.92e9, 201)
iqs = np.asarray(traces)                              # (12, 201)

# rectangular — one entry per line, shared axis by repetition
qtool.qspec.fit_batch([freqs] * 12, iqs, states=[centers] * 12)

# ragged — three lines, three different windows, three different lengths
axes = [np.linspace(6.80e9, 6.84e9, 201),
        np.linspace(6.88e9, 6.92e9,  51),
        np.linspace(6.95e9, 6.97e9, 101)]
qtool.qspec.fit_batch(axes, [iq0, iq1, iq2], states=[c0, c1, c2])
```

Nothing is copied on the way in. The arrays are borrowed through the buffer protocol and split
into row views, so a batch that arrives as numpy stays numpy — at 3000 lines × 51 points the
conversion is **0.016 ms** against **5.8 ms** for reading the same numbers element by element.
Pass `np.ascontiguousarray(x)` if a view you built is not C-contiguous.

## What the reports look like

Screenshots of the live figures — hover, legend toggles, zoom, and the Bloch sphere's orbit
controls all work in the page `plot(...)` returns:

**s21** — resonator spectroscopy, 11-parameter complex model

![s21 fit](https://raw.githubusercontent.com/xncz/qtool/master/docs/s21.png)

**s21 vs power** — the same fit swept over drive power

![s21 vs power](https://raw.githubusercontent.com/xncz/qtool/master/docs/s21_power.png)

**qspec** — qubit spectroscopy (Lorentzian)

![qspec](https://raw.githubusercontent.com/xncz/qtool/master/docs/qspec.png)

**qspec vs Z** — the flux sweep

![qspec vs Z](https://raw.githubusercontent.com/xncz/qtool/master/docs/qspec_z.png)

**rabi** — Rabi amplitude, cosine anchored at `P1(0)=0`

![rabi](https://raw.githubusercontent.com/xncz/qtool/master/docs/rabi.png)

**iq** — readout clouds: density regions and pairwise separability

![iq](https://raw.githubusercontent.com/xncz/qtool/master/docs/iq.png)

**ramsey** — T2* from a damped cosine

![ramsey](https://raw.githubusercontent.com/xncz/qtool/master/docs/ramsey.png)

**t1** — energy relaxation

![t1](https://raw.githubusercontent.com/xncz/qtool/master/docs/t1.png)

**t2_echo** — echo dephasing

![t2_echo](https://raw.githubusercontent.com/xncz/qtool/master/docs/t2_echo.png)

**drag — amplitude** — first order and the escalated valley fits

![drag amplitude](https://raw.githubusercontent.com/xncz/qtool/master/docs/drag_amplitude.png)

**drag — coefficient**

![drag coeff](https://raw.githubusercontent.com/xncz/qtool/master/docs/drag_coeff.png)

**drag — detuning** — carrier residual

![drag detuning](https://raw.githubusercontent.com/xncz/qtool/master/docs/drag_detuning.png)

**bloch** — three-basis readout → Bloch trajectory (orbit-rotatable, hover cross-highlights
the three projections)

![bloch](https://raw.githubusercontent.com/xncz/qtool/master/docs/bloch.gif)

## API reference

All physical quantities are in **SI units** (seconds, hertz, volts, radians); ratios are
plain numbers. Axes and IQ data are sequences or numpy arrays; IQ is complex. Every `plot`
function returns an `Html`; every `fit` raises on failure; every `fit_batch` returns one
result per line and never raises (failures are exception *instances*).

### Top level

| name | meaning |
| --- | --- |
| `qtool.Html` | `str` subclass holding one self-contained report fragment — see below |
| `qtool.StateCenters(centers)` | readout centres, one complex number per prepared state; `.centers` |
| `qtool.QtoolError` | `Exception` subclass — every fit/validation failure that is raised |
| `qtool.assets(kind)` | the browser asset tags (`"inline"` or `"cdn"`) a page carries |
| `qtool.p1(iq, states=None)` | IQ → excited-state probability |
| `qtool.p1_sigma(iq, states, sigma)` | the σ of `p1`, propagated from the IQ σ |
| `qtool.direction(iq)` | one direction (and its spread) from an IQ cloud |
| `qtool.__version__` | the installed version |

**`Html`** — `Html(fragment, name="plot", div_id=None, frame=None, assets="inline")`.

| member | meaning |
| --- | --- |
| `.name` | display name (file stem for `persist`, page `<title>`) |
| `.div_id` | the div id inside the fragment; unique per chip report |
| `.frame` | the card's outer title (the `frame=` argument of `plot`) |
| `.page(title=None)` | the full HTML document as a string |
| `.persist(path, title=None)` | write `path/<name>.html`, self-contained; returns the path |

### `qtool.t1`

Model `Decay(offset, amplitude, t1)`; fit result `T1Fit`.

| call | returns |
| --- | --- |
| `fit(taus, iq, states=None, sigma=None)` | `T1Fit` |
| `fit_batch(taus, iqs, states=None, sigmas=None)` | list of `T1Fit` / `T1Error` |
| `plot(taus, iq, states=None, sigma=None, fit=None, div_id="t1", frame=None)` | `Html` |

`Param`: `T1`, `OFFSET`, `AMPLITUDE`.

### `qtool.t2_echo`

Model `EchoDecay(offset, amplitude, t2_echo)`; fit result `T2EchoFit`.

| call | returns |
| --- | --- |
| `fit(taus, iq, states=None, sigma=None)` | `T2EchoFit` |
| `fit_batch(taus, iqs, states=None, sigmas=None)` | list of `T2EchoFit` / `T2EchoError` |
| `plot(taus, iq, states=None, sigma=None, fit=None, div_id="t2-echo", frame=None)` | `Html` |

`Param`: `T2_ECHO`, `OFFSET`, `AMPLITUDE`.

### `qtool.ramsey`

Model `CosDamp(offset, amplitude, frequency, phase, decay)`; fit result `RamseyFit`.

| call | returns |
| --- | --- |
| `fit(taus, iq, states=None, sigma=None)` | `RamseyFit` |
| `fit_batch(taus, iqs, states=None, sigmas=None)` | list of `RamseyFit` / `RamseyError` |
| `plot(taus, iq, states=None, sigma=None, fit=None, div_id="ramsey", frame=None)` | `Html` |

`Param`: `T2_STAR`, `FREQUENCY`, `PHASE`, `OFFSET`, `AMPLITUDE`.

### `qtool.rabi`

Model `Cos(freq, amp)` — a cosine anchored at `P1(0)=0`; fit result `RabiFit`.

| call | returns |
| --- | --- |
| `fit(amps, iq, states=None, sigma=None)` | `RabiFit` |
| `fit_batch(amps, iqs, states=None, sigmas=None)` | list of `RabiFit` / `RabiError` |
| `plot(amps, iq, states=None, sigma=None, fit=None, div_id="rabi", frame=None)` | `Html` |

`Param`: `A_PI`, `FREQ`, `AMP`.

### `qtool.s21`

Model `S21Model(fr, ql, qc, theta, ap, tau, a, b, phi, zc_re, zc_im)` — the full
11-parameter complex resonator model; fit result `S21Fit`.

| call | returns |
| --- | --- |
| `fit(freqs, iq, sigma=None)` | `S21Fit` |
| `fit_batch(freqs, iqs, sigmas=None)` | list of `S21Fit` / `S21Error` |
| `plot(freqs, iq, sigma=None, fit=None, div_id="s21", frame=None)` | `Html` |
| `power_plot(freqs, lines, div_id="s21-power", frame=None)` | `Html` — power sweep |
| `PowerLine(power, iq, sigma=None, fit=None)` | one line of the power sweep |

`Param`: `FR`, `QL`, `QC`, `THETA`, `AP`, `TAU`, `A`, `B`, `PHI`, `ZC_RE`, `ZC_IM`,
`QI`, `KAPPA_EX` (the last two are derived).

### `qtool.qspec`

Models `Lorentz(fq, fwhm, amp, offset)` and `Flux()` (SQUID tuning); fit results
`QspecFit` and `FluxFit`.

| call | returns |
| --- | --- |
| `fit(freqs, iq, states=None, sigma=None)` | `QspecFit` — one spectroscopy line |
| `fit_batch(freqs, iqs, states=None, sigmas=None)` | list of `QspecFit` / `QspecError` |
| `fit_flux(zs, peaks, eta, asymmetry=0.0)` | `FluxFit` — peak positions vs flux |
| `fit_flux_batch(lines)` | list of `FluxFit` / `QspecError`; `FluxLine(zs, peaks, eta, asymmetry=0.0)` is one input |
| `plot(freqs, iq, states=None, sigma=None, fit=None, div_id="qspec", frame=None)` | `Html` |
| `z_plot(freqs, lines, states=None, div_id="qspec-z", frame=None, flux=None)` | `Html` — the flux sweep |
| `QspecZLine(z, iq, fit=None, freqs=None)` | one line of the flux sweep |

`Param`: `FQ`, `FWHM`, `AMP`, `OFFSET` (single line) and `F_MAX`, `ETA`, `ASYMMETRY`,
`Z_OFFSET`, `Z_PERIOD` (flux).

### `qtool.iq`

Readout analysis: per-state centres, spreads and pairwise separability, plus three
discriminators (`which` is one of `"naive"`, `"kmeans"`, `"custom"`).

| call | returns |
| --- | --- |
| `stats(iqs, which)` | `IqStats` — one IQ cloud per state |
| `discriminants(clouds, states, which)` | `Discriminant` — train one (state numbers need not start at 0) |
| `batch_discriminants(clouds, states, which)` | one `Discriminant`-ish result per qubit, failures as instances |
| `batch_judge(discriminants, shots)` | one `Verdict` per qubit (paired with its shots; the longer side is truncated) |
| `plot(iqs, which, div_id="iq", frame=None)` | `Html` — clouds + the chosen overlay |
| `Param` | a namespace of metric names: `.center`, `.centroid`, `.separation`, `.snr`, `.threshold`, `.error_rate`, `.auc` |

Result classes: `IqStats`, `StateStats` (centre & spread), `PairStats` (separability),
`Discriminant`, `Verdict`.

### `qtool.qpt`

CZ process tomography.

| call | returns |
| --- | --- |
| `fit(dataset, ideal=None)` | `QptFit`; raises `QptError` when it does not converge |
| `fit_batch(datasets, ideal=None)` | one result per dataset, failures as `QptError` instances |
| `plot(fit, div_id="qpt", frame=None)` | `Html` — PTM heat map + fidelity table |

Inputs: `Dataset(experiments=None)` with `.push(...)`, `Experiment(state, basis,
expectation)`, `QuantumState(qubits)`, `PauliBase(ops)`, and the constants
`SingleQubitState.PLUS_X / MINUS_X / PLUS_Y / MINUS_Y / PLUS_Z / MINUS_Z`,
`Pauli.I / X / Y / Z`. Results: `QptFit` with `.ptm`, `.f_proc`, `.f_avg`,
`.iterations`, `.solve_time_ms`; `PtmMatrix` has `.mat`, `.basis_order`,
`.from_unitary`, `.identity()`, `.process_fidelity(...)`, `.average_fidelity(...)`.

`Param`: `F_PROC`, `F_AVG`.

### `qtool.bloch`

| call | returns |
| --- | --- |
| `bloch_vector(trajectory, states=None)` | `BlochVector` — `(⟨X⟩, ⟨Y⟩, ⟨Z⟩)` along the scan |
| `plot(vector, x_title, div_id="bloch", frame=None)` | `Html` — the 3D report |
| `Trajectory(axis, x, y, z)` | one input: the scan axis and the three basis IQ traces |

### `qtool.jazz`

| call | returns |
| --- | --- |
| `fit(taus, iq, base_hz, states=None, sigma=None)` | `JazzFit` — `Fringe(offset, amplitude, zeta, phase, decay, base_hz)` is the model |
| `plot(taus, iq, states=None, sigma=None, fit=None, div_id="jazz", frame=None)` | `Html` |
| `Param`: `ZETA_ZZ`, `T2_STAR`, `OFFSET`, `AMPLITUDE`, `PHASE` | |

`taus` must be equidistant (the initial ζ comes from an FFT); `base_hz` is the experiment's
reference frequency (an input, not fitted); `sigma` is in the **IQ domain** (`std(shots)/√n`,
same convention as `qtool.s21`). There is no `fit_batch` — one fringe at a time.

### `qtool.idle_point`

| call | returns |
| --- | --- |
| `jazz_at_z(v, iq, sigma=None, fit=None)` | `JazzAtZ` — one coupler-bias tier: the bias, that tier's IQ, and its `JazzFit` (or none) |
| `fit(volts, zetas, stderrs=None)` | `IdlePointFit` — three kinds of minimum in one call: the parabola `\|ζ\|(V) ≈ a·(V−v0)² + c` fit (`.parabola_fit_idle_v`, `.parabola_fit_zeta_min`), the grid argmin (`.zeta_argmin`, `.zeta_min`) and the ζ zero crossing (`.zero_v`, `None` when the curve does not cross zero); `.model`, `.params` |
| `plot(taus, lines, states=None, div_id="idle-point", frame=None)` | `Html` — two line plots (`\|ζ_ZZ\|` in purple, with the red parabola fit and the fitted idle point marked; `ζ_ZZ` in teal, with the zero crossing marked) plus the summary table |
| `Param`: `PARABOLA_FIT_IDLE_V`, `PARABOLA_FIT_ZETA_MIN`, `ZETA_ARGMIN`, `ZETA_MIN`, `ZERO_V` (kind `idle_point`) | the scan's own readings |

The scan is the same row-wise shape as `s21.power_plot` / `qspec.z_plot`: you fit each tier
with `qtool.jazz.fit` and assemble the lines yourself (ascending `v`; a `fit=None` tier
still draws its data). `JazzAtZ` is only created by `jazz_at_z`. In `fit`, NaN tiers are
skipped and the per-tier σ weights the parabola. The card's parameter table — and the
chip's `idle_point` colouring vocabulary — is the **scan summary**: the fitted vertex and
its `|ζ|`, the grid argmin point and its measured `|ζ|`, and the signed-ζ **zero crossing**
(a linear interpolation between the adjacent tiers; the entry is simply absent when the
curve does not cross zero). The per-tier jazz parameters stay in the downloadable data
(`fits` and one sub-table per tier).

### `qtool.jazzn`

| call | returns |
| --- | --- |
| `factor_zero(volts, iqs, states)` | `FactorZeroFit` — wide window: `peak` is the grid index, `fwhm` a grid difference |
| `factor_k(volts, iqs, states)` | `FactorKFit` — narrow fit: `LorentzPeak(centre, fwhm, amp, offset)` with stderr |
| `Stage(pairs, volts, fit)` | one order of the chain: its `pairs` label, its voltage window and its fit |
| `plot(stages, chosen, states, div_id="jazzn", frame=None)` | `Html`; stages are sorted by `pairs` internally |
| `Param`: `chosen_v()`, `peak_v(pairs)`, `peak_p1(pairs)`, `fwhm(pairs)` | |

`iqs` is **per-shot**: one ragged IQ array per voltage point (P1 is counted per shot).
`states` is required. The window recursion (each stage's window comes from the previous
stage's reading) stays in your code — the library only gives the per-stage primitives.

### `qtool.tomography`

| call | returns |
| --- | --- |
| `tomography(x_iqs, y_iqs, z_iqs, states=None)` | `QubitState` — one measurement point |
| `tomography_batch(x, y, z, states=None)` | one `QubitState` per point (failures as instances) |
| `QubitState.bloch() / .spherical() / .density() / .ket()` | `Bloch(x, y, z)`, `Spherical(r, theta, phi)`, `Density(matrix)`, `Ket(alpha, beta, mixing)` — each with a `covariance` (3×3 or `None`) |

`states=None` means uncalibrated: the IQ axis is estimated from the data itself (same path
as `qtool.p1`). In `tomography_batch` you may also pass one entry per point — a
`StateCenters` or `None` — to calibrate some points and not others. `spherical().phi` is the
**phase** the virtual-Z chain runs on. The Pauli-coordinates view is named `Bloch` here
(the Rust name is `Pauli`; `qtool.qpt.Pauli` is the basis enum).

### `qtool.virtual_z`

| call | returns |
| --- | --- |
| `fit(ns, phases)` | `VirtualZFit` — `slope` (rad/tier), `intercept`, `compensation` (∈ [0, 2π)), `residual`, `shift` |
| `fit_batch(ns, phases)` | one `VirtualZFit` per line (failures as instances) |
| `plot(ns, states, fit, div_id="virtual_z", frame=None)` | `Html` — `states` are the per-tier `QubitState`s, `fit` is required |
| `Param`: `SLOPE`, `COMPENSATION`, `INTERCEPT`, `RESIDUAL` | |

`ns` are the gate counts, integers (identifiability is mod `2π/gcd(counts)`); `phases` come
from `[state.spherical().phi for state in states]`. No stderr — the fit has no covariance.

### `qtool.drag`

Three scans, one shape each. `amplitude` has two entry points: `fit` (first-order
chevron) and `valley_fit` (the escalated valley scan).

| call | returns |
| --- | --- |
| `amplitude.fit(amps, iq, states, sigma=None)` | `FactorOneFit` — one lowest-order (`pairs = 1`) chevron |
| `amplitude.fit_batch(amps, iqs, states, sigmas=None)` | one `FactorOneFit` per line (failures as instances) |
| `amplitude.valley_fit(amps, iq, states, sigma=None)` | `FactorNFit` — an escalated valley scan (`pairs ≥ 2`) |
| `amplitude.valley_fit_batch(amps, iqs, states, sigmas=None)` | one `FactorNFit` per line |
| `amplitude.window_half_width(a_pi, pairs)` | half-width of the next scan's window |
| `amplitude.plot(orders, chosen, states, div_id="drag-amplitude", frame=None)` | `Html`; `OrderScan(pairs, amps, iq, fit=None)` is one line |
| `coeff.fit(coeffs, iq, states, sigma=None)` | `ValleyFit` |
| `coeff.fit_batch(coeffs, iqs, states, sigmas=None)` | one result per line |
| `coeff.plot(orders, chosen, states, div_id="drag-coeff", frame=None)` | `Html`; `OrderScan(pairs, coeffs, iq, fit=None)` |
| `detuning.fit(detunings_hz, iq, states, sigma=None)` | `ValleyFit` |
| `detuning.fit_batch(detunings_hz, iqs, states, sigmas=None)` | one result per line |
| `detuning.plot(orders, chosen, states, div_id="drag-detuning", frame=None)` | `Html`; `OrderScan(pairs, detunings_hz, iq, fit=None)` |

Note `states` is required (no default) for all of `qtool.drag`. `Valley(centre, fwhm,
amp, offset)` and `CosWave(freq, amp)` are the models; `Param`: `A_PI`, `FREQ`, `AMP`
(amplitude scan) and `CENTRE`, `FWHM`, `AMP`, `OFFSET` (the valley scans).

### Fit results

Every fit result carries:

| member | meaning |
| --- | --- |
| `.model` | the fitted parameters as a named record (`fit.model.t1`, `fit.model.fq`, …) |
| `.params` | `[(name, (value, stderr)), …]` — what the report's parameter table shows |
| `.p1` | the model evaluated at the data points (projected to probability) |
| `.chisqr`, `.redchi` | χ² and reduced χ² |
| `.nfev`, `.success` | solver statistics |

Failure instances (from `fit_batch`) are the module's `*Error` class: test them with
`isinstance`, read the message with `str`.

## Performance

3000 S21 lines (51 frequency points each) on a 32-thread Ryzen 9 9950X, best of three runs.
Both sides solve the identical problems, and the same-task rows are given the same start
point *and* a hand-written analytic Jacobian, so what is left on the Python side is the
interpreter:

| path | 3000 fits | per fit |
| --- | --- | --- |
| `scipy.optimize.curve_fit`, serial — **scipy's default** (finite differences) | 2.28 s | 0.760 ms |
| `scipy.optimize.curve_fit`, serial — analytic Jacobian | 0.96 s | 0.321 ms |
| **`qtool` core (Rust), serial** — Jacobian ships with the crate | **0.157 s** | **0.052 ms** |
| `scipy.optimize.curve_fit`, 32-process pool — analytic | 0.09 s | 0.030 ms |
| **`qtool` core (Rust), `rayon` 32 threads** | **0.011 s** | **0.0037 ms** |

The whole pipeline, no start point given — `fit_batch` estimates the initial values from the
data, fits up to eight candidates per line and keeps the best:

| path | 3000 lines | per line |
| --- | --- | --- |
| `qtool.s21.fit`, one line at a time — estimation + up to 8 fits | 95.0 s | 31.7 ms |
| `qtool.s21.fit_batch` (32 threads), the same work | 5.3 s | 1.78 ms (**17.9×**, 0 failures) |

From a realistic (estimator-grade) start a single scipy fit costs 15.3 ms and **3.7% of the
lines never converge**; the core takes 6.7 ms and loses none. Machine, method, controls and
caveats are in the [main README](https://github.com/xncz/qtool#performance).

## The Rust API

Everything here has a direct Rust counterpart — the same chip report model
(`Chip::layer(..).part(..)`, `Entity::qubit/part`, `entity_mut`, `metric`, `persist`), the
same fitting modules. Usage examples for both languages and the complete reference live in
the [main README](https://github.com/xncz/qtool).

## License

PolyForm Noncommercial 1.0.0 — free for noncommercial use; commercial use requires a
separate paid license (contact xncz@outlook.com). See the
[LICENSE](https://github.com/xncz/qtool/blob/master/LICENSE) in the main repository.

