> ## 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.

# 6. Beyond individual quantum objects

This section describes Rhyme's **module-level functions** for operating on one or more quantum objects. They complement the methods of `qobject` introduced in [Section 3](https://docs.rhymeq.com/language-reference/03-core-of-rhyme.md).

These functions allow quantum operations to depend on the basis values of several objects simultaneously, without observing them. They can therefore create and manipulate quantum entanglement.

***General note on input arguments:** For all module-level functions that accept `*q` arguments, at least one quantum object must be supplied, except for `cswap()`, where `*q` may be empty. The quantum objects in `*q` must be distinct from one another, except for `join()`, which allows duplicates. Otherwise, the behavior is undefined.*

***Quantum parallelism:** The principle of [quantum parallelism](https://docs.rhymeq.com/language-reference/03-core-of-rhyme.md#quantum-parallelism) described in Section 3 also applies to module-level quantum operations. On a quantum computer, these operations act on all participating joint basis values in parallel, rather than processing one superposition branch after another.*

## 6.1 Operations on joint quantum values

When an operation involves multiple quantum objects, Rhyme treats them as having a **joint quantum value**. A joint basis value is a tuple containing one basis value for each object. For example, if `i` and `j` are quantum integers, a joint basis value might be `(2, 3)`.

In the simulator, quantum objects are automatically joined when an operation involves more than one of them. This does not necessarily mean they are entangled: independently prepared quantum objects may also be represented jointly. On a quantum computer, no explicit joining is needed: by the laws of quantum mechanics, operations involving multiple quantum objects act on their joint quantum value, whether or not the objects are entangled.

### Natural extension of functions

An important feature of Rhyme is that **functions supplied to quantum operations are automatically extended to larger joint quantum values when necessary**.

For example, consider the following setup:

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

i = qint(2, 3, name="i")
j = qint(0, 1, 2, 3, name="j")
k = qint(name="k")  # Holds 0 with amplitude 1

bfunc(lambda x, y: x ** y, i, j, ret=k)
```

The three objects now have a joint quantum value, and they are entangled.

Now suppose we want to exchange the amplitudes of basis values `2` and `-2` in `i`:

```python theme={null}
i.flip(
    lambda x: -2 if x == 2 else 2 if x == -2 else x
)
```

Although `i` is entangled with `j` and `k`, the supplied function only needs to describe the pairing of `i`'s basis values.

Rhyme automatically extends the pairing to the joint basis values:

* `(2, y, z)` is paired with `(-2, y, z)`.
* All other joint basis values are paired with themselves.

Notice that the basis values of `j` and `k` remain unchanged in the extended pairing. For example, `(2, 0, 1)` is paired with `(-2, 0, 1)`: the second and third components are identical in both tuples. Even if `(-2, 0, 1)` has amplitude zero, the operation exchanges the two amplitudes.

The same principle applies to other user-defined functions supplied to quantum operations. **Each function receives only the basis values of the quantum objects specified as its inputs**, even if those objects belong to a larger joint quantum value. For functions that return basis values, such as `pair()`, the remaining components of the joint basis value are left unchanged, as shown in the example above.

All user-defined functions supplied to quantum operations must satisfy the requirements described in [Section 3](https://docs.rhymeq.com/language-reference/03-core-of-rhyme.md), including those for pairing and left/right classification where applicable. Otherwise, the behavior of the operation is undefined.

### Single-object operations

When a module-level function receives only one quantum object `q`, it performs the equivalent of the corresponding object-level operation. For example:

```python theme={null}
observe(q)  # Equivalent to q.observe()
add_phase(f, q)  # Equivalent to q.add_phase(f)
flip(pair, q)  # Equivalent to q.flip(pair)
```

The same applies to `measure()`, `interfere()`, `rotate()`, `combine()`, and `discard()`.

This equivalence holds even if `q` belongs to a larger joint quantum value.

## 6.2 `observe()`: obtain basis values

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

observe(*q: qobject) -> Any
```

`observe()` collapses the quantum value and returns basis values.

* With one quantum object, it returns that object's observed basis value.
* With multiple quantum objects, it returns a tuple of their observed basis values, in the order supplied.

**The probability of an outcome is the sum of the squared magnitudes of the amplitudes of all joint basis values matching that outcome.** After observation, only those joint basis values continue to participate in the superposition, and their amplitudes are renormalized.

For example:

```python theme={null}
from rhyme import qbit, observe

a = qbit(0, 1)
b = qbit(0)

result = observe(a, b)  # Either (0, 0) or (1, 0), each with 50% probability
```

When the objects are entangled, observing some of them can also affect the quantum values of the others. For example:

```python theme={null}
from rhyme import qbit, bfunc, observe

a = qbit(0, 1)
b = qbit(0)

bfunc(lambda n: n, a, ret=b)
# Joint basis values: (0, 0) and (1, 1), each with an amplitude of 1 / sqrt(2)

result = observe(a)  # Either 0 or 1, each with 50% probability
```

Although only `a` was observed, `b` now holds the same basis value as `result`, with amplitude `1`. The observation of `a` has also collapsed the quantum value of `b`, as only the joint basis value `(result, result)` remains.

## 6.3 `measure()`: observe a label

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

measure(label, *q, destructive: bool = False)
```

`measure()` uses a user-defined `label()` function to assign a label to each basis value, or combination of basis values.

**The probability of observing a particular label is the sum of the squared magnitudes of the amplitudes of all joint basis values assigned that label.**

For example:

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

x = qint(1, 2, 3, 4)
parity = measure(lambda n: n % 2, x)  # Returns 0 or 1, each with 50% probability
```

Unlike `observe()`, this operation does not necessarily collapse the quantum value to a single basis value. Instead, only the basis values having the observed label continue to participate in the superposition, and their amplitudes are renormalized.

In the example above, if `parity` is `0`, the remaining basis values are `2` and `4`, each with an amplitude of $\frac{1}{\sqrt{2}}$. If `parity` is `1`, they are `1` and `3`, with the same amplitudes.

The label can also depend on multiple quantum objects:

```python theme={null}
x = qint(1, 2)
y = qint(3, 4)

parity = measure(lambda a, b: (a + b) % 2, x, y)
```

Here, `parity` is again `0` or `1`, each with 50% probability. If the result is `0`, only the joint basis values `(1, 3)` and `(2, 4)` remain in the superposition. If it is `1`, only `(1, 4)` and `(2, 3)` remain. In either case, `x` and `y` are now entangled.

The `label()` function must return a **classical, immutable** value, as described in [Section 3](https://docs.rhymeq.com/language-reference/03-core-of-rhyme.md#label).

By default, `destructive=False`. If `destructive=True`, the quantum objects being measured become inaccessible after the measurement for further quantum operations.

## 6.4 `add_phase()`: rotate amplitudes

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

add_phase(rot_angle, *q) -> None
```

`add_phase()` rotates the amplitude of each joint basis value by the angle returned by `rot_angle()`, measured in radians. The absolute values of the amplitudes remain unchanged.

For example:

```python theme={null}
from math import pi
from rhyme import qint, add_phase

x = qint(1, 2)
y = qint(1, 2)

add_phase(lambda a, b: pi if a == b else 0.0, x, y)
```

Here, the amplitudes of joint basis values `(1, 1)` and `(2, 2)` are rotated by `pi`, while the others remain unchanged.

The objects are not observed to evaluate the function. It defines the phase change for every joint basis value.

## 6.5 `interfere()`: mix paired amplitudes

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

interfere(pair, lr, *q) -> None
```

`interfere()` mixes amplitudes according to the pairing and left/right classification supplied by `pair()` and `lr()`, as explained in [Section 3](https://docs.rhymeq.com/language-reference/03-core-of-rhyme.md#pair-and-lr).

When multiple quantum objects are supplied, `pair()` takes one basis value argument per object and returns a tuple containing their paired values. Similarly, `lr()` takes one argument per object and returns a boolean.

For example:

```python theme={null}
from rhyme import qbit, interfere

a = qbit(0)
b = qbit(0)

interfere(
    lambda x, y: (x, 1 - y),  # Pair (x, 0) with (x, 1)
    lambda x, y: y == 0,  # Left if y is 0
    a, b
)
```

This mixes the amplitudes of the joint basis values `(0, 0)` and `(0, 1)`.

## 6.6 `flip()`: exchange paired amplitudes

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

flip(pair, *q) -> None
```

`flip()` exchanges the amplitudes of paired basis values. Because the operation is symmetric, no `lr()` function is required.

For example, we can flip the second bit conditionally on the first:

```python theme={null}
from rhyme import qbit, flip

control = qbit(0, 1)
target = qbit(0)

flip(
    lambda c, t: (c, 1 - t) if c == 1 else (c, t),
    control, target
)
```

The function pairs `(1, 0)` with `(1, 1)`, while leaving `(0, 0)` and `(0, 1)` unchanged.

Since `control` is in superposition, this operation creates entanglement between `control` and `target`.

## 6.7 `rotate()`: rotate paired amplitudes

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

rotate(angle, pair, lr, *q) -> None
```

`rotate()` mixes the amplitudes of each pair using a specified rotation angle, in radians.

For example:

```python theme={null}
from math import pi
from rhyme import qbit, rotate

bit = qbit(0)

rotate(
    pi / 4,
    lambda b: 1 - b,
    lambda b: b == 0,
    bit
)
```

This creates equal positive amplitudes for `0` and `1`.

The `lr` argument must be supplied, even though it may be `None` for operations that do not require a left/right distinction.

## 6.8 `combine()`: general mixing of paired amplitudes

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

combine(u11, u12, u21, u22, pair, lr, *q) -> None
```

`combine()` generalizes `interfere()`, `flip()`, and `rotate()`. It mixes each pair of amplitudes using four real or complex coefficients.

If the original "left" and "right" amplitudes are `a` and `b`, the new amplitudes will be:

* Left: `u11 * a + u12 * b`
* Right: `u21 * a + u22 * b`

The coefficients must be chosen so that the sum of the absolute squares of the amplitudes is preserved for any `a` and `b`. Otherwise, the behavior of `combine()` is undefined.

For example:

```python theme={null}
from math import sqrt
from rhyme import qbit, combine

bit = qbit(0)
s = 1 / sqrt(2)

combine(
    s, s, s, -s,
    lambda b: 1 - b,
    lambda b: b == 0,
    bit
)
```

This produces the same result as `bit.interfere()`.

The `lr` argument may be `None` when the operation is symmetric under exchanging the "left" and "right" members of each pair. In particular, this applies when `u11 == u22` and `u12 == u21`.

## 6.9 `swap()` and `cswap()`: exchange basis values

### `swap()`

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

swap(q1, q2) -> None
```

`swap()` exchanges the basis values of two quantum objects on every superposition branch of their joint quantum value.

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

left = qint(1, 2)
right = qint(9)

swap(left, right)
```

This operation works on superpositions without observing either object.

The two objects must be distinct, have the same quantum type and `size`, and each must accept the other's basis values as valid. Otherwise, the behavior of `swap()` is undefined.

### `cswap()`

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

cswap(q1, q2, include, *q) -> None
```

`cswap()` is a conditional version of `swap()`.

The `include()` function receives one basis value argument for each object in `q`. It determines whether the values of `q1` and `q2` are exchanged on a given superposition branch. It must define a mathematical mapping, and its Python implementation must have no side effects, as described in [Section 3](https://docs.rhymeq.com/language-reference/03-core-of-rhyme.md#mathematical-mappings-with-no-side-effects).

For example:

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

control = qbool(False, True)
a = qint(1)
b = qint(2)

cswap(a, b, lambda enabled: enabled, control)
```

Here, the values of `a` and `b` are exchanged only when the basis value of `control` is `True`.

`include()` must be consistent with the swap: it must return the same boolean result for two joint basis values that differ only by exchanging the basis values of `q1` and `q2`. Otherwise, the behavior of `cswap()` is undefined.

Passing `None` as `include` performs an unconditional swap.

## 6.10 `join()`: group quantum objects in the simulator

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

join(*q) -> None
```

`join()` instructs the **Rhyme simulator** to represent the supplied quantum objects jointly.

For example:

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

a = qbit(0, 1)
b = qbit(0)

join(a, b)
```

This can be useful for examining joint amplitudes in the debugger.

**Joining quantum objects does not necessarily entangle them.** In this example, `a` and `b` remain independent, even though the simulator represents them jointly.

`join()` has no impact on any outcome accessible through the public API of the Rhyme library. There is also no need to call it before a joint operation: the simulator automatically joins quantum objects when necessary.

## 6.11 `discard()`: make quantum values inaccessible

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

discard(*q) -> None
```

`discard()` makes the specified quantum objects inaccessible to subsequent quantum operations.

For example:

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

scratch = qint(0)
discard(scratch)
```

For a single quantum object, `discard(q)` is equivalent to `q.discard()`.

## 6.12 `bfunc()`: evaluate a function on basis values

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

bfunc(func, *q, ret) -> None
```

`bfunc()` allows a function to be applied to the basis values of quantum objects, **without observing them**.

The `func()` function receives one basis value argument for each input quantum object in `q`. Its result is used to modify the quantum object supplied as `ret`. It must define a mathematical mapping, and its Python implementation must have no side effects, as described in [Section 3](https://docs.rhymeq.com/language-reference/03-core-of-rhyme.md#mathematical-mappings-with-no-side-effects).

On each superposition branch, the behavior of `bfunc()` is specified when the basis value of `ret` equals either:

* Its canonical zero value, returned by `ret.zero_value()`.
* The actual result of `func()` on that given branch.

If these values are different, `bfunc()` exchanges them. If they are equal, the basis value of `ret` remains unchanged.

For other initial basis values of `ret`, the result is **unspecified**. This does not mean that the behavior of `bfunc()` is undefined; the resulting value may depend on the compiler or simulator implementation.

For example:

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

x = quint(1, 2, size=3)
y = quint(size=3)  # Holds 0 with amplitude 1

bfunc(lambda n: (n + 1) % 8, x, ret=y)
```

The joint basis values are now `(1, 2)` and `(2, 3)`, each with equal amplitude. The two quantum objects are entangled, and neither has been observed.

Calling the same function again exchanges the values back:

```python theme={null}
bfunc(lambda n: (n + 1) % 8, x, ret=y)
# y again holds 0 with amplitude 1
```

This is a useful technique for **uncomputing** intermediate results in quantum algorithms.

The following requirements apply:

* `ret` must be distinct from all input objects.
* `func()` must return a valid basis value of `ret` for every valid combination of input basis values. Otherwise, the behavior of `bfunc()` is undefined.

## 6.13 Putting joint operations together

The following example demonstrates how joint operations can create entanglement:

```python theme={null}
from rhyme import qbit, flip, observe

control = qbit(0)
target = qbit(0)

control.interfere()

flip(
    lambda c, t: (c, 1 - t) if c == 1 else (c, t),
    control, target
)

print(observe(control, target))  # Either (0, 0) or (1, 1)
```

The first operation creates an equal superposition of `0` and `1` in `control`.

The second operation flips `target` only when `control` has basis value `1`. As a result, the two objects become entangled, with equal amplitudes for joint basis values `(0, 0)` and `(1, 1)`.

Finally, `observe()` returns either outcome with probability `50%`.


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