## `eigenkit.orthogonal.blocks`

Circuit blocks for orthogonal networks: the RBS network, the unary loader and the unary readout.

An RBS gate is not in the gate vocabulary of the core, so each one is decomposed into gates every backend runs (Landman et al., Quantum 2022):

```math
\mathrm{RBS}_{ij}(\theta) =
H_i \, \mathrm{CNOT}_{ij} \, H_j \, R_Y^{(i)}(-\theta) \, R_Y^{(j)}(\theta) \,
H_j \, \mathrm{CNOT}_{ij} \, H_i
```

On the states `$|01\rangle$` and `$|10\rangle$` of the wires `$(i, j)$`, `$i < j$`, it is the Givens rotation of `orthogonal_matrix`, and every other basis state is left as it is. Each angle enters only plain `RY` rotations, so the two-term parameter-shift rule is exact for it, unlike a decomposition with `CRY`.

Qubit 0 is the most significant bit of the statevector, so the unary state `$e_k$`, with only wire `$k$` set, is the basis state `$2^{\,n-1-k}$`. Started in `$e_c$`, an `RBSNetwork` leaves the amplitude `$W_{rc}$` on `$e_r$`, where `W = orthogonal_matrix(topology, theta)`.

Example

```python
import numpy as np

from eigenkit import Circuit
from eigenkit.orthogonal import (
    RBSNetwork,
    UnaryLoader,
    butterfly,
    unary_loader_angles,
    unary_readout,
)

t = butterfly(4)
circuit = Circuit(
    [UnaryLoader(4, layout="parallel"), RBSNetwork(t)],
    observables=unary_readout(4),
)
x = np.array([0.5, -1.0, 2.0, 0.25])
z = circuit(np.zeros(t.n_angles), unary_loader_angles(x, layout="parallel"))
# (1 - z) / 2 == x**2 / |x|**2, because the zero angles give the identity.
```

### `RBSNetwork`

An orthogonal network of RBS gates, as a circuit block on the wires `0` to `topology.n - 1`.

The gates follow `topology.pairs()`, layer by layer, and gate `k` takes angle `k`. With `reflection=True` in the topology, a final Z gate acts on the last wire. Restricted to the unary basis the block is the matrix `orthogonal_matrix(topology, theta)`.

Without `angles` the block takes `topology.n_angles` trainable weights. With `angles` it takes none, and the angles are fixed `Constant`s, which is how classically trained angles become a circuit (see `to_block`).

Parameters:

| Name       | Type                | Description      | Default                                                                   |
| ---------- | ------------------- | ---------------- | ------------------------------------------------------------------------- |
| `topology` | `Topology`          | The gate layout. | *required*                                                                |
| `angles`   | \`tuple[float, ...] | None\`           | Fixed angles, one per gate, or None for trainable weights. Default: None. |

#### `build(n_qubits)`

Build the gates of this block for a circuit with `n_qubits` qubits.

Parameters:

| Name       | Type  | Description                                                                                            | Default    |
| ---------- | ----- | ------------------------------------------------------------------------------------------------------ | ---------- |
| `n_qubits` | `int` | The number of qubits of the circuit being assembled. The qubits from topology.n on are left unchanged. | *required* |

Returns:

| Name         | Type         | Description                                         |
| ------------ | ------------ | --------------------------------------------------- |
| `IRFragment` | `IRFragment` | The gates, with local weight indices starting at 0. |

#### `from_dict(d)`

Rebuild a block from the output of `to_dict()`.

Parameters:

| Name | Type   | Description                         | Default    |
| ---- | ------ | ----------------------------------- | ---------- |
| `d`  | `dict` | A dictionary returned by to_dict(). | *required* |

Returns:

| Name         | Type         | Description        |
| ------------ | ------------ | ------------------ |
| `RBSNetwork` | `RBSNetwork` | The rebuilt block. |

#### `required_qubits()`

Return `topology.n`, one qubit per wire.

#### `to_dict()`

Return a description of this block that can be saved as JSON.

Returns:

| Name   | Type   | Description                                            |
| ------ | ------ | ------------------------------------------------------ |
| `dict` | `dict` | The topology, the fixed angles (or None) and the type. |

### `UnaryLoader`

Load a vector `$x \in \mathbb{R}^n$` into the unary basis:

```math
|x\rangle = \sum_i \frac{x_i}{\lVert x \rVert} \, e_i
```

The loader of Johri et al. (2021): an X gate, then `$n - 1$` RBS gates whose angles depend on `$x$`. The three layouts are those of Cherrat et al., Fig. 14:

- `"parallel"`: a binary tree from wire 0, depth `$\log_2 n$`; `n` must be a power of two, and the gates act on distant wires;
- `"diagonal"`: a chain from wire 0 to wire `$n - 1$`, depth `$n - 1$`; any `n`, adjacent wires only;
- `"semi_diagonal"`: two chains from the middle, depth `$n / 2$`; `n` must be even, adjacent wires only.

The angles are non-linear functions of `$x$` that the `Parameter` tree cannot express, so the block takes them as `$n - 1$` inputs, computed by `unary_loader_angles(x, layout)`. It takes no weights.

The estimators `CustomQuantumClassifier` and `CustomQuantumRegressor` do not take this block yet: they read the number of circuit inputs from an `Encoding` or `Reuploading` block only, so a circuit that loads its inputs with a `UnaryLoader` raises a `ValueError` in `fit()`, even with `in_features` given. Run such a circuit with `Circuit` or `TorchCircuit`, or use the `OrthogonalQNN` layer, which computes the loader angles itself.

Parameters:

| Name     | Type           | Description                           | Default      |
| -------- | -------------- | ------------------------------------- | ------------ |
| `n`      | `int`          | The width, at least 2.                | *required*   |
| `layout` | `LoaderLayout` | The gate layout. Default: "diagonal". | `'diagonal'` |

#### `build(n_qubits)`

Build the gates of this block for a circuit with `n_qubits` qubits.

Parameters:

| Name       | Type  | Description                                                                                   | Default    |
| ---------- | ----- | --------------------------------------------------------------------------------------------- | ---------- |
| `n_qubits` | `int` | The number of qubits of the circuit being assembled. The qubits from n on are left unchanged. | *required* |

Returns:

| Name         | Type         | Description                                        |
| ------------ | ------------ | -------------------------------------------------- |
| `IRFragment` | `IRFragment` | The gates, with local input indices starting at 0. |

#### `from_dict(d)`

Rebuild a block from the output of `to_dict()`.

Parameters:

| Name | Type   | Description                         | Default    |
| ---- | ------ | ----------------------------------- | ---------- |
| `d`  | `dict` | A dictionary returned by to_dict(). | *required* |

Returns:

| Name          | Type          | Description        |
| ------------- | ------------- | ------------------ |
| `UnaryLoader` | `UnaryLoader` | The rebuilt block. |

#### `required_qubits()`

Return `n`, one qubit per component of `x`.

#### `to_dict()`

Return a description of this block that can be saved as JSON.

Returns:

| Name   | Type   | Description                         |
| ------ | ------ | ----------------------------------- |
| `dict` | `dict` | The width, the layout and the type. |

### `loader_depth(n, layout='diagonal')`

The number of layers of RBS gates of a unary loader, the X gate not counted.

It is `$\log_2 n$` for `"parallel"`, `$n - 1$` for `"diagonal"` and `$n / 2$` for `"semi_diagonal"` (Cherrat et al., Fig. 14, count the X gate too).

Parameters:

| Name     | Type           | Description                      | Default      |
| -------- | -------------- | -------------------------------- | ------------ |
| `n`      | `int`          | The width.                       | *required*   |
| `layout` | `LoaderLayout` | The layout. Default: "diagonal". | `'diagonal'` |

Returns:

| Name  | Type  | Description |
| ----- | ----- | ----------- |
| `int` | `int` | The depth.  |

### `unary_loader_angles(x, layout='diagonal')`

The input angles of `UnaryLoader` that load `$x / \lVert x \rVert$`.

Each gate splits the amplitude on its owner wire between the wires it keeps and the wires it passes on. With `$v_S$` the signed value `$x_s$` when `$S$` is one wire `$s$` and the norm `$\lVert x_S \rVert$` otherwise, the angle is `$\operatorname{atan2}(-v_{\mathrm{pass}}, v_{\mathrm{keep}})$` when the amplitude moves to a higher wire and `$\operatorname{atan2}(v_{\mathrm{pass}}, v_{\mathrm{keep}})$` when it moves to a lower one.

Parameters:

| Name     | Type           | Description                                                                                                                       | Default      |
| -------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------ |
| `x`      | `array - like` | One vector of shape (n,) or a batch of shape (B, n). It does not need to be normalised, and its scale does not change the angles. | *required*   |
| `layout` | `LoaderLayout` | The loader layout. Default: "diagonal".                                                                                           | `'diagonal'` |

Returns:

| Type      | Description                                              |
| --------- | -------------------------------------------------------- |
| `ndarray` | np.ndarray: The angles, of shape (n - 1,) or (B, n - 1). |

Raises:

| Type         | Description                                                                 |
| ------------ | --------------------------------------------------------------------------- |
| `ValueError` | If a vector is zero or not finite, or the layout does not accept the width. |

### `unary_probabilities(expectations)`

Convert the expectation values of `unary_readout` into probabilities.

Parameters:

| Name           | Type           | Description                                       | Default    |
| -------------- | -------------- | ------------------------------------------------- | ---------- |
| `expectations` | `array - like` | The values (\\langle Z_i \\rangle), of any shape. | *required* |

Returns:

| Type      | Description                                                       |
| --------- | ----------------------------------------------------------------- |
| `ndarray` | np.ndarray: ((1 - \\langle Z_i \\rangle) / 2), of the same shape. |

### `unary_readout(n)`

The observables `$Z_0, \dots, Z_{n-1}$` that read a unary state out.

On a unary state `$\sum_i a_i e_i$`, `$\langle Z_i \rangle = 1 - 2 a_i^2$`, so the probability of wire `$i$` is `$p_i = (1 - \langle Z_i \rangle) / 2$` (see `unary_probabilities`). After a `UnaryLoader` and an `RBSNetwork`, `$p_i = (Wx)_i^2 / \lVert x \rVert^2$`.

Parameters:

| Name | Type  | Description          | Default    |
| ---- | ----- | -------------------- | ---------- |
| `n`  | `int` | The number of wires. | *required* |

Returns:

| Type               | Description                                    |
| ------------------ | ---------------------------------------------- |
| `list[Observable]` | list\[Observable\]: One Z observable per wire. |
