> ## Documentation Index
> Fetch the complete documentation index at: https://docs.haiqu.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Variational Function Tomography

> Tomography method which fits the quantum state into a series of basis functions

#### 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 coefficients `c_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()`](../index.md#haiqu.sdk.quantum_haiqu.Haiqu.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 with
  `build_function(absolute=True)`.
* With the unrotated basis plus at least one basis that rotates a single qubit to `X`, the
  tomography will fit `f` considering its sign changes on the interval.
  The result is then determined up to one overall sign (global phase), which you can fix
  if you know `f` anywhere.

The overall magnitude of `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-`Z` basis;
    every other basis must measure exactly one qubit in `X` and the rest in `Z`.
    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_j` to fit, per axis, at most
    `2**num_qubits` of that axis. Required with a named family; defaults to the number of
    functions when `basis_functions` lists 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 polynomials `P_0, P_1, ...`, as in
      [scipy.special.eval\_legendre](https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_legendre.html).
    * `"chebyshev_t"`: the Chebyshev polynomials of the first kind `T_0, T_1, ...`, as in
      [scipy.special.eval\_chebyt](https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_chebyt.html).

    The families take `x` as is, without rescaling it to `interval`; `(-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 variable `x`, as in [`function_loading()`](../index.md#haiqu.sdk.quantum_haiqu.Haiqu.function_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 when `grid` is 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 coordinate `a` of the point whose index along
    each axis is `i_0, ..., i_k`, so one axis' coordinate may vary with the others' indices.
    With a single axis, a 1D array of `2**num_qubits` points is accepted too. Build a grid
    that is a product of per-axis points with `numpy.meshgrid(..., indexing="ij")`. The grid
    may hold at most `2**20` points. 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 to `None`, 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`](#haiqu.sdk.schemas.FunctionTomographyResult.coefficients): shape
    `(m_1, ..., m_dim)`, one entry per basis function on each axis. The coefficients of
    an earlier result with the same `m` and `basis_functions` can 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 to
    `None`, which adds no starting point.
  * **name** (*str* *|* *None*) -- Optional job name.
  * **description** (*str* *|* *None*) -- Optional job description.
* **Returns:**
  Job handle. Call `job.result()` for a
  : [`FunctionTomographyResult`](#haiqu.sdk.schemas.FunctionTomographyResult), whose `coefficients` are the
  `c_j` with one array dimension per axis and whose
  [`build_function()`](#haiqu.sdk.schemas.FunctionTomographyResult.build_function) returns `f` as a
  callable and [`build_expression()`](#haiqu.sdk.schemas.FunctionTomographyResult.build_expression) as a
  SymPy expression, or `job.progress()` for live updates.
* **Return type:**
  TomographyJobModel

#### Examples

Recover a distribution that [`distribution_loading()`](../index.md#haiqu.sdk.quantum_haiqu.Haiqu.distribution_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:

```python theme={null}
>>> from qiskit import QuantumCircuit
>>> dl_job = haiqu.distribution_loading(num_qubits=10, distribution_name="norm",
...                                     interval_start=-1, interval_end=1, scale=0.25)
>>> qc = QuantumCircuit(10)
>>> qc.append(dl_job.result(), range(10))
>>> qc.measure_all()
>>> run_job = haiqu.run(qc, shots=1024, device_id="aer_simulator")
>>> result = haiqu.variational_function_tomography(run_job.result_by_basis()[0], m=5).result()
```

`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()`](#haiqu.sdk.schemas.FunctionTomographyResult.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:

```python theme={null}
>>> import numpy as np
>>> x = np.linspace(-1, 1, 200)
>>> f_abs = result.build_function(absolute=True)
>>> f_abs(x)
```

With several axes the function takes one coordinate per axis, e.g. `f(x, y)` for a fit
with `num_qubits=[5, 5]`.

Any other basis is evaluated the same way:

```python theme={null}
>>> job = haiqu.variational_function_tomography(run_job.result_by_basis()[0], m=5, basis_functions="legendre")
>>> f_abs = job.result().build_function(absolute=True)
```

A normal density is positive everywhere, so the unrotated basis above determines it.
A function that changes sign needs rotated bases as well, and many more shots:

```python theme={null}
>>> bases = ["Z" * 10, "X" + "Z" * 9, "Z" + "X" + "Z" * 8]
>>> run_job = haiqu.run(qc, shots=100_000, device_id="aer_simulator",
...                     readout_bases=bases)
>>> job = haiqu.variational_function_tomography(run_job.result_by_basis()[0], m=8)
>>> f = job.result().build_function()  # signed, up to one overall sign
>>> f(x)
```

When the amplitudes were loaded on points other than the uniform bin midpoints, give
those points as `grid`. Here the 10-qubit register is split into two axes, with
Chebyshev nodes along the first and evenly spaced points along the second:

```python theme={null}
>>> xs = -np.cos(np.pi * (np.arange(32) + 0.5) / 32)
>>> ys = np.linspace(-1, 1, 32)
>>> grid = np.stack(np.meshgrid(xs, ys, indexing="ij"), axis=-1)  # shape (32, 32, 2)
>>> job = haiqu.variational_function_tomography(run_job.result_by_basis()[0], num_qubits=[5, 5],
...                                             m=[4, 4], basis_functions="legendre", grid=grid)
>>> f = job.result().build_function()
>>> amplitudes = f(grid[..., 0], grid[..., 1]).ravel()  # unit norm, in register order
```

### *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()`](#haiqu.sdk.schemas.FunctionTomographyResult.build_function) returns
`f` as a callable, and [`build_expression()`](#haiqu.sdk.schemas.FunctionTomographyResult.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 the `info` 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 function `f` 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()`](../index.md#haiqu.sdk.quantum_haiqu.Haiqu.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()`](#haiqu.sdk.schemas.FunctionTomographyResult.build_function)
at the grid points instead and pass the values to
[`vector_loading()`](../index.md#haiqu.sdk.quantum_haiqu.Haiqu.vector_loading).

* **Parameters:**
  * **scale** (*str* *|* *None*) -- Normalization of the expression, as in [`build_function()`](#haiqu.sdk.schemas.FunctionTomographyResult.build_function).
  * **absolute** (*bool*) -- Return `|f|`, as `Abs(...)`. Use it when the fit was given only the
    unrotated basis: those measurements determine `|f|` but not its sign.
* **Returns:**
  The fitted function.
* **Return type:**
  sympy.Expr

- **Raises:**
  **ValueError** -- As [`build_function()`](#haiqu.sdk.schemas.FunctionTomographyResult.build_function).

#### Examples

Load the state a one-axis fit describes:

```python theme={null}
>>> (low, high), = result.interval
>>> job = haiqu.function_loading(num_qubits=result.num_qubits[0],
...                              func=result.build_expression(absolute=True),
...                              interval_start=low, interval_end=high)
```

A two-axis fit on a custom `grid` is loaded from its values at the grid points instead:

```python theme={null}
>>> amplitudes = result.build_function()(grid[..., 0], grid[..., 1]).ravel()
>>> job = haiqu.vector_loading(amplitudes)
```

#### build\_function(\*, scale=None, absolute=False)

Return the fitted function `f` 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 of [`coefficients`](#haiqu.sdk.schemas.FunctionTomographyResult.coefficients), with the integral of `f**2` over
      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 with
      `n` qubits on `(lo, hi)` are the cell centres `lo + (i + 1/2) * (hi - lo) / 2**n`
      for `i = 0, ..., 2**n - 1`, not `numpy.linspace(lo, hi, 2**n)`. On a custom grid
      they are the points that were submitted, and this is the scale of
      [`coefficients`](#haiqu.sdk.schemas.FunctionTomographyResult.coefficients).

    Neither scale restores the magnitude of the loaded function: the measured state is
    normalized, so only the shape of `f` is recovered.
  * **absolute** (*bool*) -- Return `|f|`. Use it when the fit was given only the unrotated basis: those
    measurements determine `|f|` but not its sign.
* **Returns:**
  Callable `f(*coords) -> numpy.ndarray`.

- **Raises:**
  **ValueError** -- If `scale` is 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 raises `ValueError` if it is given the wrong number of coordinates, or
  coordinates that do not broadcast together.

* **Return type:**
  *Callable*\[\[...], *ndarray*]

#### Examples

```python theme={null}
>>> f = result.build_function()
>>> f(np.linspace(-1, 1, 200))  # one axis
>>> f2 = result_2d.build_function()
>>> xs, ys = np.meshgrid(np.linspace(-1, 1, 50), np.linspace(-1, 1, 50))
>>> f2(xs, ys)  # two axes, evaluated on a 50 x 50 grid
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.