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

# 3. The core of Rhyme

The core of Rhyme defines **quantum objects** and their behavior. You can use the quantum types provided by the library or build your own, for example, by subclassing the abstract `qobject` class.

A quantum object represents a superposition of **basis values**, each associated with an amplitude. The library's operations manipulate these amplitudes according to quantum mechanics.

## 3.1 `qobject`: the base class

```python theme={null}
from rhyme import qobject
```

`qobject[T]` is an abstract, generic base class to build quantum types. A quantum type is a type whose value set consists of quantum superpositions of reliably distinguishable values, called "basis values." `T` is the type of the basis values, such as `int` or `str`.

```python theme={null}
qobject(*t: T, name: str = "")
```

* Passing one basis value initializes the object to that value, with amplitude `1`.
* Passing multiple distinct basis values initializes a **uniform superposition** over them, with all their amplitudes positive and equal.
* Passing no basis values initializes the object to the value returned by `zero_value()`, with amplitude `1`.
* `name` is an optional name for the object.
* All supplied basis values must be **distinct** and **valid** for this object. Otherwise, the behavior is undefined. See also `is_valid_basis_value` below.

All instances of type `T` must be **immutable** and **hashable**.

### Creating your own quantum type

A subclass must implement two methods:

| Method | Purpose |
| - | - |
| `is_valid_basis_value(t: T) -> bool` | Return whether `t` is a valid basis value for this object. *The implementer must ensure that distinct valid basis values are **reliably distinguishable**. This is naturally the case when the basis values are classical. However, if instances of type `T` represent quantum values, those values must still be distinguishable with certainty using the public API of Rhyme. This requirement is not automatically enforced by the library.* |
| `zero_value -> T` | Return the canonical basis value used when the constructor receives no values. |

For example, we can define a quantum traffic light:

```python theme={null}
from rhyme import qobject

class qlight(qobject[str]):
    def is_valid_basis_value(self, value: str) -> bool:
        return isinstance(value, str) and value in {"red", "yellow", "green"}

    def zero_value(self) -> str:
        return "red"

light = qlight("red", "green")  # Uniform superposition
print(light.observe())  # Either "red" or "green"
```

**Important:** `is_valid_basis_value()` may be called while `qobject.__init__()` is running. If your implementation needs subclass-specific attributes, initialize them **before** calling `super().__init__()` in your subclass's constructor.

### All valid basis values

```python theme={null}
@classmethod
def all(cls, *, name: str = "") -> qobject[T]: ...
```

`all()` constructs a uniform superposition over all valid basis values. Since the base implementation in `qobject` raises `RhymeError`, subclasses must override this method if they want to support this operation. Several built-in types do so, in ways appropriate to their domains. For example:

```python theme={null}
from rhyme import qint

numbers = qint.all(size=8)  # Integers from -128 to 127 with equal amplitudes
```

## 3.2 Attributes for naming and debugging

All subclasses of `qobject` inherit the following attributes. The private attributes (starting with `_`) are intended for educational and debugging purposes. They expose the simulator's internal representation of quantum values, including their amplitudes and how quantum objects are grouped together.

| Attribute | Purpose |
| - | - |
| `name` | The name of the quantum object, specified using the optional `name` argument of its constructor. The default is an empty string. |
| `_amplitudes` | A dictionary mapping basis values to their amplitudes when the quantum object is treated separately. If the object is treated jointly with other quantum objects, this dictionary is empty. |
| `_joint_amplitudes` | A dictionary mapping tuples of basis values to their amplitudes when the quantum object is treated jointly with others. Otherwise, `None`. |
| `_joint_names` | A tuple containing the names of the jointly treated quantum objects, in the same order as their basis values appear in `_joint_amplitudes`. Otherwise, `None`. |

### Joint quantum values

Consider two ordinary Python variables:

```python theme={null}
i = 5
j = 10
```

Each has a value of its own, but we can also treat them as one entity whose value is `(5, 10)`. We are free to choose which point of view to take: the individual entities, or the joint entity. *(Similarly, we can consider our head, neck, arms, legs, and torso separately, or treat them together as one entity called our "body." It is our choice.)*

The same idea applies to quantum objects, except that their values may be superpositions:

```python theme={null}
from rhyme import qint, join

i = qint(5, 6, name="i")
j = qint(10, 12, name="j")

join(i, j)
```

Initially, `i` and `j` are treated separately. Then, the `join()` function instructs the simulator to treat them jointly, as parts of one entity. The resulting joint value is a superposition over all combinations (the Cartesian product) of the basis values participating in `i` and `j`, with the corresponding amplitudes multiplied together.

In this example, the joint value contains four participating combinations, each with amplitude $\frac{1}{2}=\frac{1}{\sqrt{2}}\cdot\frac{1}{\sqrt{2}}$:

```python theme={null}
{
    (5, 10):  0.5,
    (5, 12):  0.5,
    (6, 10):  0.5,
    (6, 12):  0.5,
}
```

You can inspect this dictionary through `_joint_amplitudes` in the debugger. Both `i` and `j` refer to the same joint value, and their `_joint_names` attributes contain `("i", "j")`, reflecting the names assigned when the objects were created.

The purpose of calling `join()` was to make the joint value visible in the debugger. We had the choice whether to treat `i` and `j` separately or jointly, and we chose the latter.

### No individual values?

However, as we will see in Section [6. Beyond individual quantum objects](https://docs.rhymeq.com/language-reference/06-beyond-individual.md), quantum objects may also become **entangled**, which means that they **only** have a joint value but no individual values of their own!

Here is an example of what the `_joint_amplitudes` may look like when `i` and `j` are entangled:

```python theme={null}
{
    (5, 10):  0.7071067812,  # 1 / sqrt(2)
    (6, 12):  0.7071067812,  # 1 / sqrt(2)
}
```

Convince yourself that it's impossible to assign separate superpositions to `i` and `j` whose combined amplitudes would reproduce the `_joint_amplitudes` above. *(Hint: If `5` and `6` participated in the superposition of `i`, and `10` and `12` in that of `j`, all with nonzero amplitudes, then combining them would necessarily produce all four combinations with nonzero amplitudes.)*

In the classical world, the whole is always the "sum of its parts." In the quantum world, there are situations where the parts, in a sense, don't exist individually, but only as a whole.

## 3.3 Operations inherited by quantum objects

All subclasses of `qobject` inherit the methods in the table below. In the formulas, $a$ and $b$ denote amplitudes. If they belong to paired basis values, $a$ is the "left" amplitude and $b$ is the "right" amplitude (see also the [pair() and lr()](#pair-and-lr) section).

In this section, we assume that the quantum object has a value of its own. Section [6. Beyond individual quantum objects](https://docs.rhymeq.com/language-reference/06-beyond-individual.md) explains what happens when these methods are called on `qobject` instances that are entangled with other quantum objects.

| Method | Effect |
| - | - |
| `observe() -> T` | Randomly collapse the object to one basis value and return that value as an instance of `T`. The probability of obtaining a particular basis value is the absolute square of its amplitude. The obtained basis value will have an amplitude of `1`. |
| `measure(label, *, destructive=False) -> L` | Randomly collapse to a single label, based on `label(value)`. The probability of obtaining a particular label is the sum of the absolute squares of the amplitudes of all basis values having that label. If `destructive=False`, only the basis values having the obtained label are kept in the superposition, with their amplitudes renormalized to ensure the absolute squares still add up to `1`. With `destructive=True`, the measured quantum object becomes inaccessible for further quantum operations. |
| `add_phase(rot_angle)` | Rotate each basis value's amplitude $a$ in the complex plane by the angle $\theta$ returned by `rot_angle(value)`. The amplitude changes to $a\cdot e^{i\theta}=a\cdot(\cos\theta + i\cdot\sin\theta)$, where $i$ is the imaginary unit. |
| `interfere(pair, lr)` | Mix the amplitudes of each basis value pair, by performing the canonical example of quantum interference: $a$ changes to $\frac{a+b}{\sqrt{2}}$, and $b$ changes to $\frac{a-b}{\sqrt{2}}$. |
| `flip(pair)` | Exchange the amplitudes of each basis value pair: $a$ changes to $b$, and $b$ changes to $a$. |
| `rotate(angle, pair, lr)` | Rotate the amplitudes of each basis value pair by `angle`: $a$ changes to $a\cdot\cos(\text{angle})-b\cdot\sin(\text{angle})$, and $b$ changes to $a\cdot\sin(\text{angle})+b\cdot\cos(\text{angle})$. |
| `combine(u11, u12, u21, u22, pair, lr)` | Mix the amplitudes of each basis value pair, by linear combination: $a$ changes to $u_{11}\cdot a+u_{12}\cdot b$, and $b$ changes to $u_{21}\cdot a+u_{22}\cdot b$. The four coefficients $u_{11}$, $u_{12}$, $u_{21}$, and $u_{22}$ are complex numbers, which must be chosen so that the sum of the absolute squares of the amplitudes is **preserved for any $a$ and $b$**. Otherwise, the behavior is undefined. |
| `discard()` | Make the quantum object inaccessible for further quantum operations. |

### Quantum parallelism

On a quantum computer, the runtime of all the methods above is independent of the number of basis values participating in the superposition of a quantum value. For example, `add_phase()` rotates the amplitude of every basis value at the same time, in a truly parallel fashion. Similarly, `measure()` evaluates labels and `interfere()` mixes amplitudes in parallel.

### Mathematical mappings, with no side effects

The functions `label()`, `rot_angle()`, `pair()`, and `lr()` represent **mathematical mappings** on the domain of valid basis values. The Python implementation serves as the **definition** of the mapping. During a single method call (e.g. `interfere(pair, lr)`), each mapping must be **well-defined** (the code must terminate normally on every valid input, and the same input must always produce the same output), and its implementation must have no **side effects**. Otherwise, the behavior of the method that takes the mapping function as an argument is undefined.

### `pair()` and `lr()`

The `pair()` function determines which basis values are paired. `lr()` determines which member of each pair is the "left" one, by returning `True` on those inputs. The following points apply:

* `pair()` must return a valid basis value, and `lr()` must return either `True` or `False`. Otherwise, the behavior of the method using these functions is undefined.
* If the basis value `x` has a non-zero amplitude and `pair(x) == y`, then `pair(y) == x` must hold. Otherwise, the behavior of the method using `pair()` is undefined.
* If the basis value `x` has a non-zero amplitude and `pair(x) == y`, where `y != x`, then `lr(x) != lr(y)` must hold whenever `lr()` is required. Otherwise, the behavior of the method using `lr()` is undefined.
* If `pair(x) == x`, the amplitude of `x` remains unchanged.
* If the quantum operation is symmetric with respect to exchanging the "left" and "right" members of a pair, regardless of their amplitudes, the `lr` argument is ignored and may be `None`.

### `rot_angle()`

The `rot_angle()` function passed to `add_phase()` must return a real number (`int` or `float`) for each basis value. Otherwise, the behavior of `add_phase()` is undefined.

### `label()`

The `label()` function passed to `measure()` assigns a label to each basis value. The returned value must be **classical** and **immutable**, but its type is otherwise unrestricted, though `str` is recommended. Otherwise, the behavior of `measure()` is undefined.

### Observation as side effect

Two familiar-looking Python operations call `observe()` under the hood:

* `str(obj)` (including `print(obj)`) observes the quantum object and collapses its value.
* `obj == other` observes `obj`, then compares the resulting basis value with `other`.

For example:

```python theme={null}
from rhyme import qint

value = qint(5, 6)
print(value)  # Observes and collapses value!
```

Do not use printing or equality comparisons merely to inspect a live superposition.

## 3.4 Binary helper functions

`qobject` defines three helpers for working with the canonical binary representations of basis values. Subclasses may override these methods; the base implementations in `qobject` raise `RhymeError`.

```python theme={null}
obj.bit_pair(bit_index, *ctrl_bit_index, ctrl_value=1)
obj.bit_lr(bit_index)
obj.bit_rot_angle(angle_0, angle_1, bit_index, *ctrl_bit_index, ctrl_value=1)
```

* **`bit_pair(...)`** returns a callable that pairs basis values by flipping the given bit. If control-bit indices are provided, the bit is flipped only when **all** control bits equal `ctrl_value`; otherwise, the value maps to itself.
* **`bit_lr(bit_index)`** returns a callable that identifies basis values whose specified bit is `0` as the left member of a pair.
* **`bit_rot_angle(...)`** returns a callable that selects `angle_0` or `angle_1`, depending on the specified bit; with controls, it returns `0.0` when the controls do not match.

All bit indices must be non-negative and **within the valid range** for the quantum type. For `bit_pair()` and `bit_rot_angle()`, the control-bit indices must be **distinct from** `bit_index` **and from one another**, and `ctrl_value` must be either `0` or `1`. Violating any of these requirements results in undefined behavior.

These helpers return functions: they **do not themselves change the quantum value**. You can pass the returned functions to operations such as `interfere()` and `add_phase()`:

```python theme={null}
from rhyme import quint

x = quint(0, size=3)  # Quantum unsigned integer
x.interfere(x.bit_pair(0), x.bit_lr(0))
x.add_phase(x.bit_rot_angle(0.0, 3.14159, 0))
```

Here, bit index `0` denotes the least-significant bit.

## 3.5 `RhymeError`

```python theme={null}
from rhyme import RhymeError
```

`RhymeError` is the **base exception class for Rhyme errors**. Catch it when you want to handle errors originating from the Rhyme library:

```python theme={null}
try:
    # Run Rhyme operations here.
    ...
except RhymeError as exc:
    print(f"Rhyme error: {exc}")
```

It is a subclass of Python's `Exception`.

## 3.6 `set_amplitude_precision()`

```python theme={null}
def set_amplitude_precision(decimal_places: int) -> None: ...
```

This debugging setting controls how many decimal places are used when **rounding newly calculated amplitudes** in the simulator. By default, amplitudes are rounded to **10 decimal places**.

```python theme={null}
from rhyme import set_amplitude_precision

set_amplitude_precision(8)  # Round new amplitudes to 8 decimal places
set_amplitude_precision(0)  # Disable rounding
```

* Values **less than or equal to zero** disable rounding, which can make simulation faster.
* Rounding may make debugger output easier to read and help prune near-zero amplitudes.
* It is a **debugging aid**, not a way to improve physical quantum-computer precision. Rounding can change simulation results, so avoid enabling it when you need maximum numerical fidelity.

## 3.7 Valid quantum programs

As explained above, Rhyme allows programmers to customize quantum operations by supplying functions such as `pair()`. The programmer is responsible for ensuring that these customizations do not result in undefined behavior. More generally, to ensure that instructions acting on quantum objects can be executed on a quantum computer, follow these rules:

* **Use only Rhyme's public API to access and manipulate quantum values.** In particular, code such as `if abs(j._amplitudes[0]) > 0.5: ...` cannot be executed on a quantum computer because, according to the laws of quantum mechanics, individual amplitudes cannot be read out.
* **No undefined behavior.** Follow the requirements described above when defining custom quantum types and operations. The Rhyme simulator detects many violations, but not all. For example, it does not verify whether a function such as `pair()` terminates normally on every possible valid input.

If you're new to Rhyme, we also recommend using only **classical values** as basis values.


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