# Real-Time Classical Expressions (Qiskit fork) Some of the most useful QUA patterns rely on **classical data that is only known at run time**: a loop whose length is streamed in from the host, or a sequence of gate indices that changes from one shot to the next. Upstream Qiskit can express real-time scalar variables (`expr.Var`), but not dynamic loop bounds or arrays. To close that gap, the author maintains a Qiskit branch that extends the real-time classical expression system: > **Branch:** [`arthurostrauss/qiskit` @ `full_real_time_expr`](https://github.com/arthurostrauss/qiskit/tree/full_real_time_expr) These changes are **not merged upstream** and are not in any Qiskit release. This provider works with stock Qiskit 2.x; the features on this page **only switch on when the fork is installed**. ## What the branch adds | Feature | API | Typical use on QOP | |---|---|---| | **Dynamic `for`-loop ranges** | `expr.Range(start, stop, step)` as a `ForLoopOp` index set, with a real-time `expr.Var` loop counter | Noise amplification (gate folding), sweeps where the length comes from an input stream or OPNIC | | **1-D classical arrays** | `types.Array(element_type, size)`, indexed with `expr.index(array, i)` | Gate-index sequences (randomized benchmarking), lookup tables, `ParameterVector` streamed as one array | | **`for`-loop capture fix** | Loop bodies with a `Var` counter can read and write variables from the enclosing scope | Required by both features above: the loop body almost always reads an outer input | The branch also adds `Expr.substitute` / `QuantumCircuit.substitute_vars`, `UnrollForLoops` support for constant `expr.Range`, OpenQASM 3 export of ranges and arrays, and **QPY version 18** to serialize all of the above. The full list is in the branch's release notes under `releasenotes/notes/`. ## Installation The branch includes Rust code, so installing from source needs a [Rust toolchain](https://rustup.rs/) (the build takes several minutes): ```bash pip install "qiskit @ git+https://github.com/arthurostrauss/qiskit.git@full_real_time_expr" ``` For development, clone it and install it in editable mode: ```bash git clone -b full_real_time_expr https://github.com/arthurostrauss/qiskit.git pip install -e ./qiskit ``` The branch reports itself as a Qiskit `2.x` development version, so it meets this provider's `qiskit<3` requirement. Install it **after** `qiskit-qm-provider` so that pip does not replace it with the PyPI release. Check that the fork is active: ```python from qiskit.circuit.classical import expr, types assert hasattr(types, "Array") and hasattr(expr, "Range"), "full_real_time_expr is not installed" ``` ```{note} Circuits are lowered to QUA through OpenQASM 3 and **qm-qasm**. Array-typed `input` declarations need a qm-qasm build with input-array support (qm-qasm 1.10 or later). ``` ## Dynamic loop ranges with `expr.Range` A Python `range` is fixed when the circuit is built. An `expr.Range` takes **classical expressions** for `start`, `stop` and `step`, so its bounds can be real-time variables. The counter is a real-time `expr.Var`, generated automatically when you use `for_loop` as a context manager. A `Parameter` cannot be the counter, because it cannot hold a value that is only known at run time. `expr.Range` follows **OpenQASM 3** semantics, not Python's: **both `start` and `stop` are inclusive**, and `step` defaults to 1. `expr.Range(0, 5)` runs six times (`0, 1, …, 5`) and exports unchanged as `[0:1:5]`. A Python `range(0, 5)` runs five times and exports as `[0:4]`. Two idioms give exactly `n` iterations (literals shown bare for brevity; type them narrowly, as explained in the note below): - `expr.Range(1, n)`: the counter runs `1 … n`, and the loop is empty when `n = 0`. Use this when the counter value doesn't matter. - `expr.Range(0, expr.sub(n, 1))`: the counter runs `0 … n-1`, as needed for array indexing. Make sure `n ≥ 1`. In Qiskit's `Uint` semantics, `0 - 1` wraps around. QUA integers are signed, so on hardware the loop is simply empty, but the circuit should not depend on that. ```{important} The loop counter takes the range's type. A bare Python literal such as `0` is lifted to `Uint(64)`, but qm-qasm only compiles unsigned integers up to 31 bits wide. **Give the start value an explicit narrow type**, for example `expr.Range(expr.lift(0, types.Uint(16)), n)`, or build the range only from `Var`s of a narrow type. ``` ### Example: noise amplification by gate folding Zero-noise extrapolation amplifies noise by replacing a gate $G$ with $G (G^\dagger G)^n$. With a dynamic range, a **single compiled circuit** covers every fold count. The host (or an OPNIC-connected classical processor) chooses `n_fold` at run time, so there is no need to compile one program per noise level. ```python from qiskit.circuit import QuantumCircuit from qiskit.circuit.classical import expr, types zne = QuantumCircuit(2, name="zne_bell") n_fold = zne.add_input("n_fold", types.Uint(8)) zne.h(0) zne.cx(0, 1) with zne.for_loop(expr.Range(expr.lift(1, types.Uint(8)), n_fold)): # 1..n_fold inclusive: n_fold CX·CX pairs zne.cx(0, 1) zne.cx(0, 1) zne.measure_all() ``` The loop is exported to OpenQASM 3 as `for uint[8] _ in [1:1:n_fold]` and compiles to `for_(i, 1, i <= n_fold, i + 1)` in QUA. It runs exactly `n_fold` times, and not at all when `n_fold = 0`. ```{warning} At the default optimization level, `transpile` cancels each adjacent `CX·CX` pair, which leaves an empty loop and silently removes the noise amplification. Transpile folded circuits with `optimization_level=0`, or otherwise protect the folded gates from cancellation. ``` Bind `n_fold` like any other real-time input: ```python from qiskit_qm_provider import ParameterTable, InputType zne_inputs = ParameterTable.from_qiskit(zne, input_type=InputType.INPUT_STREAM, name="zne_inputs") ``` Use `InputType.OPNIC` instead to drive the fold count from an OAS/QUARC classical processor (see [Installation — OAS and QUARC](installation.md#open-acceleration-stack-oas-and-quarc)). ### Compile-time vs. run-time ranges An `expr.Range` is a dynamic classical object regardless of whether its bounds are currently constant. Materialization is implicit and belongs to the `UnrollForLoops` transpiler pass: the pass may unroll a range whose bounds can be resolved, while a range depending on a real-time `Var` remains a hardware loop. This separation also covers constant expressions whose values are not represented as literal `expr.Value` or `Cast` nodes. ## Classical arrays with `types.Array` `types.Array(element, size)` is a 1-D array of `Bool`, `Uint`, `Float` or `Duration`. You can declare one with `add_input` (streamed from the host) or `add_var` (local to the circuit). Read or write an element with `expr.index(array, i)`, where the index may be a real-time expression such as a loop counter. Writes go through `qc.store(expr.index(arr, i), value)`. When the fork is installed, two things change in this provider: - [`ParameterTable.from_qiskit`](apidocs/stubs/qiskit_qm_provider.parameter_table.ParameterTable.rst) maps an `Array` input to **one array-valued `Parameter`** (a QUA array of `int`, `bool` or `fixed`). - A `ParameterVector` is collapsed into **one** array `Parameter` named after the vector. With the backend option `export_vector_as_array=True` (the default), the backend's exporter enables the branch's `ExperimentalFeatures.PARAMETER_VECTORS_AS_ARRAYS` and emits a matching `input array[float[64], N]`; every element is exported even if only some are used, so the full vector is included whenever `filter_function` keeps any used element. With the option off, each used element is exported as a scalar input (as on stock Qiskit, and readable by Qiskit's OpenQASM 3 importer), and the array field binds those inputs through its cells. Sampler and estimator PUBs still supply values only for parameters used by the circuit, ordered as `circuit.parameters`. The circuit always sees the full-length vector array; unused entries hold zero and are never read, since gate parameters cannot index an array at run time. How a binding reaches it depends on `input_type`: - `INPUT_STREAM`, `IO1`, `IO2`: each binding travels as **one dense row** of `len(circuit.parameters)` floats on a per-PUB `