Haiqu.variational_function_tomography(distributions, *, m=None, basis_functions=‘fourier’, interval=None, grid=None, num_qubits=None, num_restarts=3, initial_coefficients=None, name=None, description=None)
Recover a real-valued function encoded in a quantum state amplitudes from measurements of this state. Finds the unknown coefficientsc_j of f(x) = sum_j c_j g_j(x), where the g_j are the first
m functions of basis_functions, such that f on the register’s grid matches the state measured in
distributions. The grid is the one function_loading() uses: interval is divided into
2**num_qubits equal bins, and amplitude index i holds f at the midpoint x of bin i. With
several axes, each axis is discretized this way and each g_j is a product of one basis function per axis.
When the amplitudes hold f at other points, pass their coordinates as grid instead of interval.
What can be recovered depends on which bases were measured:
- With only the unrotated (all-
Z) basis, the fit identifies|f|. The coefficients describe some function whose magnitude matches, so evaluate it withbuild_function(absolute=True). - With the unrotated basis plus at least one basis that rotates a single qubit to
X, the tomography will fitfconsidering its sign changes on the interval. The result is then determined up to one overall sign (global phase), which you can fix if you knowfanywhere.
f is not recoverable in either case: the register holds a
normalized state, so the coefficients are scaled so that the integral of f**2 over
interval is 1. On a custom grid they are scaled so that the sum of f**2 over the
grid points is 1.
For sign recovery, rotate the most significant qubits of each axis first (the highest qubit
indices); sign flips rarely show at the scale of low-order qubits. As a rule of thumb, if f
may change sign up to 2**r times along an axis, measure r+1 rotated bases, one for each
of that axis’ r+1 most significant qubits.
- Parameters:
-
distributions (dict) — Measured distributions keyed by per-qubit Pauli readout basis, as
returned by
run_job.result_by_basis(). Must contain the unrotated all-Zbasis; every other basis must measure exactly one qubit inXand the rest inZ. Values map bitstring to a non-negative weight, such as a probability or a shot count; each basis is normalized before the fit, so its values may sum to any positive total. Basis strings and bitstrings follow Qiskit little-endian order: the rightmost character is qubit 0. -
m (int | Sequence *[*int ] | None) — Number of basis functions
g_jto fit, per axis, at most2**num_qubitsof that axis. Required with a named family; defaults to the number of functions whenbasis_functionslists them. Choose it against your shot budget: too large overfits at low shot counts. -
basis_functions (str | Sequence) —
The basis to fit against. A family name, or one entry per
axis, each a family name or a list of that axis’ basis functions:
"fourier"(the default):1, cos(pi*x), sin(pi*x), cos(2*pi*x), sin(2*pi*x), ...."legendre": the Legendre polynomialsP_0, P_1, ..., as in scipy.special.eval_legendre."chebyshev_t": the Chebyshev polynomials of the first kindT_0, T_1, ..., as in scipy.special.eval_chebyt.
xas is, without rescaling it tointerval;(-1, 1)is the recommended interval for all three. A basis function may be a real-valued string or SymPy expression in the single real variablex, as infunction_loading(). A flat list of basis functions applies to every axis; nest per axis to mix, e.g.[["1", "x"], "fourier"]. -
interval (Sequence | None) —
(lo, hi)shared by every axis, or one pair per axis. Defaults to(-1, 1). Leave it out whengridis given. -
grid (ArrayLike | None) — Coordinates of every register point, replacing the uniform grid
derived from
interval. Its shape is(2**num_qubits[0], ..., 2**num_qubits[-1], num_axes):grid[i_0, ..., i_k, a]is coordinateaof the point whose index along each axis isi_0, ..., i_k, so one axis’ coordinate may vary with the others’ indices. With a single axis, a 1D array of2**num_qubitspoints is accepted too. Build a grid that is a product of per-axis points withnumpy.meshgrid(..., indexing="ij"). The grid may hold at most2**20points. The coordinates are used as given, so with a named family keep them inside[-1, 1]. Fits on a custom grid take longer than on a uniform one. -
num_qubits (int | Sequence *[*int ] | None) — Qubits per axis, summing to the number of qubits
in
distributions. An integer declares a single axis of that many qubits; a list declares one axis per entry, e.g.[5, 5]splits a 10-qubit register into two axes. Defaults toNone, a single axis spanning every measured qubit. Axis 0 takes the leading (most significant) qubits of each bitstring. - num_restarts (int) — Random restarts in addition to the deterministic start, from 0 to 100. Each one is another optimizer run, lowering the risk of a poor local optimum.
-
initial_coefficients (ArrayLike | None) — An additional starting point for the fit, in the
format of
coefficients: shape(m_1, ..., m_dim), one entry per basis function on each axis. The coefficients of an earlier result with the samemandbasis_functionscan be passed as they are; their overall scale does not matter. The fit still runs its usual starts and returns the best one, so this costs about as much as one more restart. Defaults toNone, which adds no starting point. - name (str | None) — Optional job name.
- description (str | None) — Optional job description.
-
distributions (dict) — Measured distributions keyed by per-qubit Pauli readout basis, as
returned by
- Returns:
Job handle. Call
job.result()for a :FunctionTomographyResult, whosecoefficientsare thec_jwith one array dimension per axis and whosebuild_function()returnsfas a callable andbuild_expression()as a SymPy expression, orjob.progress()for live updates. - Return type: TomographyJobModel
Examples
Recover a distribution thatdistribution_loading() encoded. A run without
readout_bases is read out in the computational basis, which is the unrotated basis
the fit needs; result_by_basis()[0] holds it for the run’s one circuit. The fit
interval has to be the one the state was loaded on:
distribution_loading puts sqrt(pdf) in the amplitudes by default, so sqrt
of the normal density is what comes back. Five Fourier terms recover it to a few
percent from those 1024 shots, thinly spread over a 1024-point grid; raising m
past that starts fitting the shot noise rather than the distribution.
build_function() turns the coefficients
into a function that can be evaluated anywhere on the interval. The unrotated basis
determines only |f|, so ask for that:
f(x, y) for a fit
with num_qubits=[5, 5].
Any other basis is evaluated the same way:
grid. Here the 10-qubit register is split into two axes, with
Chebyshev nodes along the first and evenly spaced points along the second:
class haiqu.sdk.schemas.FunctionTomographyResult(*, coefficients, basis_functions, interval, num_qubits, loss, converged, basis_condition)
The outcome of a function-tomography fit.coefficients
Fitted coefficients, shape(m_1, ..., m_dim). These are the
coefficients of f(x) = sum_j c_j g_j(x) in the basis named by
basis_functions, normalized so that the integral of f**2 over interval
is 1, or, for a fit on a custom grid, so that the sum of f**2 over the grid
points is 1. Nothing else is needed to evaluate f. Axis 0 takes the leading
(most significant) qubits of each bitstring. build_function() returns
f as a callable, and build_expression() as a SymPy expression.
basis_functions
The basis family, or the expressions, used on each axis. Expressions in the result of a completed job have been validated, but expressions from any other source, such as theinfo of a failed job, are parsed by SymPy as Python code, so
only use ones you trust.
interval
(lo, hi) per axis, or None for a fit on a custom grid.
num_qubits
Register qubits per axis.loss
Final value of the fit’s objective. Smaller is a closer fit to the measured distributions.converged
Whether the optimizer reported convergence.basis_condition
Condition number of the basis on the register’s grid. Large values mean the coefficients are poorly determined there, typically because the chosen basis functions are nearly linearly dependent;None if it could not
be computed.
build_expression(*, scale=None, absolute=False)
Return the fitted functionf as a SymPy expression.
The expression is f = sum_j c_j g_j written out in full. It depends on x for a fit
with one axis, and on x_0, x_1, ..., one variable per axis in axis order, for a fit with
several. The polynomial families are written out as explicit polynomials, and the Fourier
family as 1, cos(pi*x), sin(pi*x), cos(2*pi*x), ....
A one-axis expression can be passed as is to function_loading(),
which samples it at the midpoints of the same bins the fit used. To prepare the state the fit
describes, load it on the fit’s num_qubits and interval. Function loading normalizes
the state it prepares, so scale makes no difference there.
The expression of a fit on a custom grid is valid at any point, but function loading would
sample it on a uniform grid. To prepare the state of such a fit, evaluate build_function()
at the grid points instead and pass the values to
vector_loading().
- Parameters:
- scale (str | None) — Normalization of the expression, as in
build_function(). - absolute (bool) — Return
|f|, asAbs(...). Use it when the fit was given only the unrotated basis: those measurements determine|f|but not its sign.
- scale (str | None) — Normalization of the expression, as in
- Returns: The fitted function.
- Return type: sympy.Expr
- Raises:
ValueError — As
build_function().
Examples
Load the state a one-axis fit describes:grid is loaded from its values at the grid points instead:
build_function(*, scale=None, absolute=False)
Return the fitted functionf as a callable, evaluable anywhere on the interval or grid.
The callable takes one coordinate per axis, in axis order: f(x) for one axis,
f(x, y) for two, and so on. It evaluates f = sum_j c_j g_j there. Coordinates may
be scalars or arrays of any shape that broadcast together, such as the output of
numpy.meshgrid; the result has their broadcast shape. Coordinates are used as given,
without mapping the interval onto the basis family’s own domain.
- Parameters:
-
scale (str | None) —
Normalization of the returned values. Defaults to
"interval", or to"grid"for a fit on a custom grid."interval": the scale ofcoefficients, with the integral off**2over the interval equal to 1. It does not depend on the number of qubits, so fits on registers of different sizes can be compared directly. Not available for a fit on a custom grid, which has no interval."grid": the amplitude scale of the register. Evaluated at the register’s grid points, the values form a unit-norm state vector. The grid points of an axis withnqubits on(lo, hi)are the cell centreslo + (i + 1/2) * (hi - lo) / 2**nfori = 0, ..., 2**n - 1, notnumpy.linspace(lo, hi, 2**n). On a custom grid they are the points that were submitted, and this is the scale ofcoefficients.
fis recovered. -
absolute (bool) — Return
|f|. Use it when the fit was given only the unrotated basis: those measurements determine|f|but not its sign.
-
scale (str | None) —
Normalization of the returned values. Defaults to
- Returns:
Callable
f(*coords) -> numpy.ndarray.
- Raises:
ValueError — If
scaleis unknown, if it is"interval"for a fit on a custom grid, or if this result’s per-axis fields disagree on the number of axes. The returned callable raisesValueErrorif it is given the wrong number of coordinates, or coordinates that do not broadcast together.
- Return type: Callable[[…], ndarray]