Classical Calls API#

See Call Classical Code During a Shot for how calls are scheduled, simulated and emulated.

Measurements and randomness#

class cudaq_pulse.classical.Bits(iterable=(), /)[source]#

Bases: list

Measurements read as bits (outcome != 0), bit-packed on the wire.

A kernel passes a list of measurements, fn.submit([m0, m1]); the body reads bits[0], len(bits) or iterates. As a result, the bits are answered as booleans a kernel can branch on. The length comes from the call, or is stated, pulse.Length[pulse.Bits, 8]. pulse.Bits() is an empty list, an external’s placeholder result.

cudaq_pulse.Length#

typing.Annotated, re-exported to state a fixed list length: pulse.Length[pulse.Bits, 8] takes or answers eight bits and pulse.Length[list[int], 8] eight numbers. The length is a positive whole number.

cudaq_pulse.classical.random_index(
n,
/,
*,
name='random_index',
max_latency_ns=0.0,
link=0,
**options,
)[source]#

An on-device random source: a classical function of no arguments whose answer is an integer drawn uniformly from 0 .. n - 1.

On hardware the controller’s random number generator answers it (the manifest marks it "random"). Simulation without shots follows every value, each with probability 1/n; with shots each shot draws one. Emulation draws from its own seeded generator. Use it to pick a randomized-benchmarking gate per shot, branching on the index.

Parameters:
  • n (int)

  • name (str)

  • max_latency_ns (float | Time)

  • link (int | str)

  • options (Any)

Return type:

ClassicalFunction[(), int]

Reports#

class cudaq_pulse.compiler.ClassicalCall(
function,
compiled_name,
dispatch_key,
link,
iteration,
submit_cycles,
submit_duration_cycles,
due_cycles,
taken_cycles,
first_use_cycles,
deadline_cycles,
segment,
link_name=None,
exposed_cycles=None,
controller=None,
)#

Bases: object

One execution of a call to a classical function, from classical_report().

Times are in clock cycles. The request is sent from submit_cycles for submit_duration_cycles; its answer is due at due_cycles (the budgeted latency after that) and taken at taken_cycles (None if the kernel never takes it). first_use_cycles is the earliest start of a pulse whose amplitude, tone or branch comes from the answer, and deadline_cycles the latest due time the function’s deadline_ns allows. segment is the segment it is submitted in. link_name is the link’s name in the control system, if it has one. controller is the controller whose instance of a per-controller link runs the call (Link(per_controller=True)), else None. function is the name the function is declared with and compiled_name the name it is compiled and served under: a version’s, such as "adaptive_t1__1", for a function whose list lengths come from its calls, else the same name. dispatch_key is the key its requests carry: the hash of compiled_name (classical.dispatch_key), or the key its controller’s firmware fixes (the dispatch_keys of the processor that runs it).

exposed_cycles is how long the first use waits for the answer beyond when it could start without the call: after its line is free and after the readout resonator of the last readout before the call has depleted (PhysicalQudit.depletion_ns), when pulses must wait anyway. The rest of the budget, hidden_cycles, overlaps that work. A latency within the depletion time is hidden entirely.

Parameters:
  • function (str)

  • compiled_name (str)

  • dispatch_key (int)

  • link (int)

  • iteration (tuple[int, ...])

  • submit_cycles (int)

  • submit_duration_cycles (int)

  • due_cycles (int)

  • taken_cycles (int | None)

  • first_use_cycles (int | None)

  • deadline_cycles (int | None)

  • segment (int)

  • link_name (str | None)

  • exposed_cycles (int | None)

  • controller (int | None)

controller: int | None = None#
property deadline_slack_cycles: int | None#

How far the due time is inside the deadline (negative: missed).

exposed_cycles: int | None = None#
property hidden_cycles: int | None#

The part of the budget that overlaps other work.

property slack_cycles: int | None#

How long the answer could arrive later without delaying a pulse.

function: str#
compiled_name: str#
dispatch_key: int#
iteration: tuple[int, ...]#
submit_cycles: int#
submit_duration_cycles: int#
due_cycles: int#
taken_cycles: int | None#
first_use_cycles: int | None#
deadline_cycles: int | None#
segment: int#
class cudaq_pulse.compiler.Segment(
index,
opened_by,
line,
start_cycles,
min_shift_cycles,
max_shift_cycles,
)[source]#

Bases: object

One segment of a compiled kernel, from ScheduledKernel.segments().

A variable wait (its length computed from a classical answer) or a blocking classical wait is a barrier for the lines that depend on it: those it waits on or whose pulses use its answer, and every line tied to them by a sync, a shared tone, a branch or a kernel with its own schedule=. They sync before it, and what follows on them shifts with its run-time length; other lines keep their time. Segment 0 starts the program; segment k starts when the k-th barrier, in program order, ends. start_cycles is the segment’s start in the static schedule, which places every barrier at its lowest length. At run time the segment starts shift_cycles later, with min_shift_cycles <= shift_cycles <= max_shift_cycles (None: unbounded); the bound adds up the barriers before it on the same lines. opened_by is "start", "wait" (a variable wait on line line) or "answer" (a blocking wait on link line).

Parameters:
  • index (int)

  • opened_by (str)

  • line (int)

  • start_cycles (int)

  • min_shift_cycles (int)

  • max_shift_cycles (int | None)

index: int#
opened_by: str#
line: int#
start_cycles: int#
min_shift_cycles: int#
max_shift_cycles: int | None#

Wire format#

The wire format of a call: what a request and an answer look like.

A request is a 24-byte header (magic 'CUQR', dispatch key, argument length, request id, timestamp) followed by the arguments, tightly packed and little-endian in the order of the function’s argument types; an answer is a 24-byte header (magic 'CUQS', status, result length, request id, timestamp) followed by the results. This is the layout of the CUDA-Q Realtime messaging protocol, declared here so cudaq-pulse needs nothing from CUDA-Q; core/mlir/include/cudaq-pulse/Runtime/WireFormat.h declares the same for C++.

native(library, symbol, function) wraps a host handler written in C with the signature void handler(const void *request, void *answer, size_t slot_bytes), the shape of a CUDA-Q Realtime host-call handler, as a Python handler for simulation.

cudaq_pulse.classical.wire.HEADER_BYTES = 24#

The size of a request or response header.

cudaq_pulse.classical.wire.REQUEST_MAGIC = 1129664850#

The first word of a request header, 'CUQR'.

cudaq_pulse.classical.wire.RESPONSE_MAGIC = 1129664851#

The first word of a response header, 'CUQS'.

cudaq_pulse.classical.wire.decode_answer(function, data)[source]#

(status, request id, answer) of an answer from function.

Parameters:
Return type:

tuple[int, int, Any]

cudaq_pulse.classical.wire.decode_request(function, data, dispatch_key=None)[source]#

(request id, timestamp, arguments) of a request to function at dispatch_key (as for encode_request).

Parameters:
Return type:

tuple[int, int, list[Any]]

cudaq_pulse.classical.wire.encode_answer(function, answer, request_id=0, timestamp=0, status=0)[source]#

The answer of function (as a handler returns it) to one request.

Parameters:
  • function (ClassicalFunction[..., Any])

  • answer (Any)

  • request_id (int)

  • timestamp (int)

  • status (int)

Return type:

bytes

cudaq_pulse.classical.wire.encode_request(
function,
args,
request_id=0,
timestamp=0,
dispatch_key=None,
)[source]#

A request to function with args (as a handler receives them), sent to dispatch_key: the program’s (call.dispatch_key), by default the hash of the function’s compiled name.

Parameters:
  • function (ClassicalFunction[..., Any])

  • args (Sequence[Any])

  • request_id (int)

  • timestamp (int)

  • dispatch_key (int | None)

Return type:

bytes

cudaq_pulse.classical.wire.native(library, symbol, function, slot_bytes=1024)[source]#

A handler for function that calls the C function symbol in the shared library library with a request and an answer slot.

Parameters:
Return type:

Any

cudaq_pulse.classical.wire.schema(function)[source]#

The function’s handler schema: per argument and result its payload type id, size in bytes and element count, as a dispatcher function table entry declares them. A function whose list lengths come from its calls has a schema per version: pass fn.specialize(...).

Parameters:

function (ClassicalFunction[..., Any])

Return type:

dict[str, Any]

CUDA-Q QEC decoders#

pulse.classical also takes CUDA-Q QEC’s real-time decoding functions, cudaq_qec.qec.enqueue_syndromes, get_corrections and reset_decoder, with the options above (max_latency_ns is 0 unless given for the calls that answer nothing); see the user guide.

Emulation#

Emulating a controller that calls classical services, in virtual time.

export(lowered) writes what a controller needs to run a compiled kernel: its static schedule with each event’s segment, the segment boundaries, its calls, and the manifest of the classical functions it calls (manifest): per function its dispatch key, link, handler schema and latency budget, which is what a CUDA-Q Realtime dispatcher’s function table holds.

emulate(lowered, ...) runs the program shot by shot in virtual time, without physics: measurement outcomes come from a source, each call is sent as a real request (wire) over a channel to a service, and the answer comes back after the modelled transport delay plus the service’s measured time. Its budget is what the compiled program allows: it is in time if it arrives the link’s feedback time before it is due. A late answer, or a decoder’s NOT_READY, takes the timeout arm of a wait with a timeout; a late answer is recorded as late otherwise. Answers are bound to the shot as in simulation, so variable waits get their real lengths and later segments shift accordingly.

class cudaq_pulse.classical.emulation.CallTrace(
function,
submit_ns,
latency_ns,
budget_ns,
in_time,
inputs,
answer,
)[source]#

Bases: object

One call in an emulated shot. Times in ns of the shot’s timeline.

budget_ns is how long after submit_ns the answer may arrive: until it is due, less the link’s feedback time. in_time is whether latency_ns is within it (false for a decoder’s NOT_READY).

Parameters:
  • function (str)

  • submit_ns (float)

  • latency_ns (float)

  • budget_ns (float)

  • in_time (bool)

  • inputs (tuple[Any, ...])

  • answer (Any)

function: str#
submit_ns: float#
latency_ns: float#
budget_ns: float#
in_time: bool#
inputs: tuple[Any, ...]#
answer: Any#
class cudaq_pulse.classical.emulation.RealtimeChannel(library, *args, **kwargs)[source]#

Bases: object

A channel through the CUDA-Q Realtime host library, which dispatches requests to registered GPU or host services. Not available yet: use InProcess (with wire.native handlers for compiled code) or UdpChannel. The requests and answers are already in its wire format, so a channel built on it drops in here.

Parameters:
  • library (str)

  • args (Any)

  • kwargs (Any)

cudaq_pulse.classical.emulation.device_call_text(lowered)[source]#

CUDA-Q kernel text that makes a compiled program’s calls as cc.device_call operations. Not available yet: export the program with export (or ScheduledKernel.export_to_emulator()), whose manifest holds each function’s dispatch key, payload types and link.

Parameters:

lowered (Any)

Return type:

str

class cudaq_pulse.classical.emulation.EmulationResult(outcomes=..., calls=..., ends_ns=..., wall_s=0.0)[source]#

Bases: object

Per shot, the measurement outcomes (in time order) and the calls.

Parameters:
  • outcomes (list[list[int]])

  • calls (list[list[CallTrace]])

  • ends_ns (list[float])

  • wall_s (float)

outcomes: list[list[int]]#
calls: list[list[CallTrace]]#
ends_ns: list[float]#
wall_s: float = 0.0#
property late_fraction: float#

The fraction of the answers the program waits on that came late (a decoder’s NOT_READY included). A call it sends without taking an answer, such as an enqueue of syndromes, counts in neither part, though its trace says whether it came back in time.

property calls_per_second: float#

The calls of every shot per second of the run’s wall-clock time; infinite when no wall time was measured.

class cudaq_pulse.classical.emulation.InProcess(functions, handlers, dispatch_keys=None)[source]#

Bases: object

A channel to services in this process: handlers by function name, called on the decoded request. A handler named for a function whose list lengths come from its calls serves each of its versions. dispatch_keys gives the program’s key per compiled name (emulate passes them); a function not in it is at the hash of its name.

Parameters:
  • functions (Sequence[ClassicalFunction[..., Any]])

  • handlers (Mapping[str, Callable[..., Any]])

  • dispatch_keys (Mapping[str, int] | None)

call(function, request)[source]#

Deliver request; returns the answer bytes and the service’s time in ns.

Parameters:
Return type:

tuple[bytes, float]

close()[source]#

Nothing to release: the services run in this process. It is here so that every channel can be closed alike.

Return type:

None

class cudaq_pulse.classical.emulation.Transport(fixed_ns=0.0, bytes_per_ns=0.0, jitter_ns=0.0)[source]#

Bases: object

The delay of one direction of a link: fixed_ns + bytes / bytes_per_ns plus a jitter drawn from an exponential with mean jitter_ns (0 for none).

Parameters:
  • fixed_ns (float)

  • bytes_per_ns (float)

  • jitter_ns (float)

fixed_ns: float = 0.0#
bytes_per_ns: float = 0.0#
jitter_ns: float = 0.0#
delay_ns(byte_count, rng)[source]#

The delay in ns of byte_count bytes in this direction: fixed_ns, plus byte_count / bytes_per_ns if bytes_per_ns is positive, plus a jitter drawn from rng if jitter_ns is.

Parameters:
  • byte_count (int)

  • rng (np.random.Generator)

Return type:

float

class cudaq_pulse.classical.emulation.UdpChannel(address, slot_bytes=65536, timeout_s=2.0)[source]#

Bases: object

A channel to a service reached over UDP: serve_udp, or any server that answers in the wire format, such as a CUDA-QX decoding server.

An answer ends where its header’s result length says; whatever follows, such as the padding of a server that sends whole slots, is not part of it. The service’s time is the one serve_udp sends after the answer, or, from a server that sends none, the round trip measured here.

Parameters:
  • address (tuple[str, int])

  • slot_bytes (int)

  • timeout_s (float)

call(function, request)[source]#

Send request and wait for the answer; returns the answer bytes and the service’s time in ns (the measured round trip if the server sends none). No answer within the channel’s timeout raises an error that names the function and the address.

Parameters:
Return type:

tuple[bytes, float]

close()[source]#

Close the channel’s socket.

Return type:

None

cudaq_pulse.classical.emulation.emulate(
lowered,
*,
shots_count=1,
channel=None,
handlers=None,
transport=None,
outcomes=None,
service_time='measured',
seed=None,
)[source]#

Run lowered for shots_count in virtual time against classical services.

channel reaches the services (InProcess of handlers by default, the functions’ bodies unless given). transport models each link’s delay in each direction, per link (name or id) or for all. outcomes gives the level a readout reports, from its qudit and the shot’s generator (uniform 0/1 by default); a call that takes IQ points gets them drawn at those levels from the quantum system’s dispersive readout model (IQModel). The answer’s latency is the request’s transport delay, plus the service’s time ("measured" wall-clock, or "none"), plus the answer’s transport delay. shots_count is a positive int.

Parameters:
  • lowered (Any)

  • shots_count (int)

  • channel (Any)

  • handlers (Mapping[str, Callable[..., Any]] | None)

  • transport (Transport | Mapping[int | str, Transport] | None)

  • outcomes (Callable[[int, int, np.random.Generator], int] | None)

  • service_time (str)

  • seed (int | None)

Return type:

EmulationResult

cudaq_pulse.classical.emulation.export(lowered, controller=None)#

A compiled kernel for a controller emulator: schedule, segments, calls, links and manifest, as JSON-serializable data. Times are in clock cycles of the controller, at clock_ghz (with program_clock_ghz when that is not the program clock, as in cudaq_pulse.controller); each event’s segment_start_cycles is the static start of its segment, which moves at run time by the lengths of the run-time waits before it on its lines. An segment’s shift adds to that of the segment it follows, the one before it unless it names another in after. On a control system of several controllers, the part of the one controller indexes, with only its events, calls, links and functions, and controller its index.

Parameters:
  • lowered (Any)

  • controller (int | None)

Return type:

dict[str, Any]

cudaq_pulse.classical.emulation.manifest(lowered)#

The classical functions a compiled kernel calls, for a dispatcher.

Parameters:

lowered (Any)

Return type:

dict[str, Any]

cudaq_pulse.classical.emulation.serve_udp(
functions,
handlers,
host='127.0.0.1',
port=0,
slot_bytes=65536,
dispatch_keys=None,
)[source]#

Serve handlers over UDP: one datagram per request and per answer, in the wire format. Returns the server thread, its address and a stop function. Each answer is followed by the service’s own time: the 4-byte tag 'CUQT' and the time in ns as 8 bytes, which UdpChannel reads. A request goes to the function at its dispatch key (dispatch_keys by compiled name, else the hash of the name). Built-in functions that share a key, such as QEC decoders, are told apart by their payload: its length, then its first argument (the decoder id).

Parameters:
  • functions (Sequence[ClassicalFunction[..., Any]])

  • handlers (Mapping[str, Callable[[...], Any]])

  • host (str)

  • port (int)

  • slot_bytes (int)

  • dispatch_keys (Mapping[str, int] | None)

Return type:

tuple[Thread, tuple[str, int], Callable[[], None]]

Calibration#

Estimators for calibrating while the QPU runs.

Each estimator is a plain function whose state goes in and comes back out, so the same code is the body of a classical function a kernel calls between measurements, runs between shots, and is tested on its own. Nothing is kept between calls.

  • t1_update and t1_wait: a gamma posterior over the decay rate 1/T1, updated from one shot of “excite, wait, measure”, and the next wait.

  • frequency_update and ramsey_setting: a Gaussian posterior over a qubit’s detuning, updated from one Ramsey shot, and the wait and phase of the next shot (a binary search: each shot says which side of the estimate the detuning is on).

  • survival_probability, ramsey_probability and rabi_probability: the outcome probabilities of those experiments with ideal pulses, for drawing shots without simulating them (rng.random() < p).

  • three_point_decay: the decay time of A exp(-t / T) + B from three equally spaced points.

  • three_point_phase: the phase error e of a - b cos(theta + e) from three equally spaced settings.

  • golden_section_step: one step of a golden-section search for a minimum; GoldenSection holds its state.

  • nelder_mead_step: one step of a Nelder-Mead simplex search; NelderMead holds its state.

The two searches are ask-and-tell: a step takes the cost measured at the point the last step asked for and returns the next point, and a flag that is true once the search has converged, for the converged pattern (see the user guide).

class cudaq_pulse.classical.calibration.GoldenSection(lo, hi, c, d, fc, fd, tolerance)[source]#

Bases: object

The state of a golden-section search on [lo, hi].

c and d are the interior points, fc and fd their costs (NaN until measured). as_floats/from_floats pack it into the 7 values of a list[float] argument.

Parameters:
  • lo (float)

  • hi (float)

  • c (float)

  • d (float)

  • fc (float)

  • fd (float)

  • tolerance (float)

lo: float#
hi: float#
c: float#
d: float#
fc: float#
fd: float#
tolerance: float#
classmethod start(lo, hi, tolerance)[source]#

A search for the minimum of a cost on [lo, hi], with no cost measured yet.

The interior points split the interval in the golden ratio. The search has converged once the interval is no wider than tolerance, which is in the units of lo and hi.

Parameters:
  • lo (float)

  • hi (float)

  • tolerance (float)

Return type:

GoldenSection

next_point()[source]#

The point whose cost the search needs next.

Return type:

float

converged()[source]#

Whether the interval is no wider than tolerance (hi - lo <= tolerance).

Return type:

bool

best()[source]#

The current estimate of the minimum.

Return type:

float

as_floats()[source]#

The state as 7 floats, in the order lo, hi, c, d, fc, fd, tolerance. A cost not measured yet is NaN.

Return type:

list[float]

classmethod from_floats(values)[source]#

The state that as_floats packed into values. Only the first 7 values are read.

Parameters:

values (Sequence[float])

Return type:

GoldenSection

class cudaq_pulse.classical.calibration.NelderMead(simplex, costs, stage, index, trial, trial_cost, tolerance)[source]#

Bases: object

The state of a Nelder-Mead search in dim dimensions.

simplex holds dim + 1 vertices and costs their costs (NaN until measured). stage says what the point asked for last is: a vertex of the start (index), the reflection, the expansion, the contraction, or a vertex of a shrink. trial and trial_cost keep the reflection while its expansion or contraction is measured. as_floats/from_floats pack it into a list[float] argument of NelderMead.size(dim) values.

Parameters:
  • simplex (tuple[tuple[float, ...], ...])

  • costs (tuple[float, ...])

  • stage (int)

  • index (int)

  • trial (tuple[float, ...])

  • trial_cost (float)

  • tolerance (float)

simplex: tuple[tuple[float, ...], ...]#
costs: tuple[float, ...]#
stage: int#
index: int#
trial: tuple[float, ...]#
trial_cost: float#
tolerance: float#
classmethod start(x0, step, tolerance)[source]#

A search that starts from the point x0, with no cost measured yet.

The first simplex is x0 and one vertex per coordinate, each x0 moved by step along that coordinate, so step sets the size of the first simplex. The search has converged once every vertex is within tolerance of the best in every coordinate. The first point asked for is x0.

Parameters:
  • x0 (Sequence[float])

  • step (float)

  • tolerance (float)

Return type:

NelderMead

property dim: int#

The number of coordinates of a point, len(x0) at the start.

static size(dim)[source]#

How many floats as_floats gives for dim dimensions.

Parameters:

dim (int)

Return type:

int

next_point()[source]#

The point whose cost the search needs next. That is a vertex while the start or a shrink is measured, and otherwise the reflection, expansion or contraction being tried.

Return type:

tuple[float, …]

converged()[source]#

Every vertex is within tolerance of the best, in every coordinate.

Return type:

bool

best()[source]#

The vertex with the lowest cost so far. A vertex whose cost is not measured yet is never preferred to one that has a cost.

Return type:

tuple[float, …]

as_floats()[source]#

The state as NelderMead.size(dim) floats, in this order: the dim + 1 vertices of the simplex, dim coordinates each, one vertex after the other; their dim + 1 costs; stage, index and tolerance; the dim coordinates of trial; and trial_cost. A cost not measured yet is NaN.

Return type:

list[float]

classmethod from_floats(values, dim)[source]#

The state that as_floats packed into values. The floats do not record the dimension, so dim must be the one the state was packed with.

Parameters:
  • values (Sequence[float])

  • dim (int)

Return type:

NelderMead

cudaq_pulse.classical.calibration.adaptive_t1_update(shape, rate, excited, wait, error_1to0, error_0to1)[source]#

The gamma posterior over Gamma = 1/T1 after one “excite, wait wait, measure” shot that read 1 (excited) or 0, through a readout that reads |1> as 0 with probability error_1to0 and |0> as 1 with error_0to1.

The prior is Gamma(shape k, rate theta), in the time unit of wait (ns when it is a time); the likelihood of reading 1 is error_0to1 + (1 - error_1to0 - error_0to1) exp(-Gamma wait). The posterior’s exact mean and variance give the new gamma distribution (moment matching), as in Berritta et al.; with r = theta / (theta + wait), E[Gamma^n exp(-Gamma wait)] is k (k + 1) … (k + n - 1) r^k / (theta + wait)^n.

Two outcomes have a posterior that is a gamma distribution, returned as it is. A 1 through a readout whose error_0to1 is 0 has the likelihood exp(-Gamma wait): (shape, rate + wait), for every wait. A 0 through a readout whose error_1to0 is 0 has 1 - exp(-Gamma wait), which a wait much shorter than the rate makes Gamma wait: the result tends to (shape + 1, rate) as the wait tends to 0, and is that when wait / rate rounds to 0.

The prior is returned unchanged, with no sign of it, where the shot says nothing or has no meaning: a wait of 0 (also of a 0 that such a readout cannot give then), an infinite, negative or NaN wait, a wait too long to compare with the rate, a rate or shape that is not positive, and an outcome the readout never reports. A caller cannot tell these from an update that changes nothing. The variance is kept at 1e-12 of the mean squared or more, so the shape returned is at most 1e12; the difference it is computed from keeps about 16 digits less those of the shape.

Limits: the result is not reliable where wait / rate, or a product of it with the shape or with an error probability, is in the denormal range (below about 1e-307), as for a wait of 1e-310 of the rate or a 1 read with error_1to0 = 1 and an error_0to1 of 1e-310 after a very short wait; it can then be far from the posterior, up to the shape of 1e12. An infinite or NaN shape or rate is outside the function’s domain: an infinite shape gives (nan, nan) for most shots.

Parameters:
  • shape (float)

  • rate (float)

  • excited (int)

  • wait (float | Time)

  • error_1to0 (float)

  • error_0to1 (float)

Return type:

tuple[float, float]

cudaq_pulse.classical.calibration.adaptive_t1_wait(shape, rate, scale=0.51)[source]#

The next wait: scale times the estimated T1 (rate / shape). The adaptive T1 tracker uses a fixed scale of 0.51.

Parameters:
  • shape (float)

  • rate (float)

  • scale (float)

Return type:

float

cudaq_pulse.classical.calibration.binary_search_phase(mean_hz, wait_ns)[source]#

The phase of a Ramsey shot (as for frequency_update: it reports 1 with probability (1 - cos(2 pi D t + phase)) / 2) that puts the estimate mean_hz on the fringe’s steepest point, so that a detuning above it makes 1 more likely: the Ramsey of detuning 1 / (4 t) + mean. The wait is a time, or a number of ns.

Parameters:
  • mean_hz (float)

  • wait_ns (float | Time)

Return type:

float

cudaq_pulse.classical.calibration.binary_search_update(
mean_hz,
sigma_hz,
outcome,
wait_ns,
offset=-0.02,
contrast=0.6,
coherence_ns=10000.0,
)[source]#

The Gaussian posterior over a detuning after one shot of the frequency binary search: a Ramsey shot of wait wait_ns set (by its phase, binary_search_phase) to the fringe’s steepest point at the estimate, reading outcome +1 or -1.

The likelihood of +1 is 1/2 + (offset + contrast exp(-t / T) sin(2 pi (D - mean) t)) / 2 with T = coherence_ns, and the posterior is the Gaussian of its exact moments (Berritta et al. 2025); a +1 moves the estimate up. The wait and T are times, or numbers of ns.

Parameters:
  • mean_hz (float)

  • sigma_hz (float)

  • outcome (int)

  • wait_ns (float | Time)

  • offset (float)

  • contrast (float)

  • coherence_ns (float | Time)

Return type:

tuple[float, float]

cudaq_pulse.classical.calibration.binary_search_wait(sigma_hz, coherence_ns=10000.0)[source]#

The wait (ns) of the next binary-search shot, from the posterior width: (sqrt(16 pi^2 s^2 + 1/T^2) - 1/T) / (8 pi^2 s^2), for T a time or a number of ns.

Parameters:
  • sigma_hz (float)

  • coherence_ns (float | Time)

Return type:

float

cudaq_pulse.classical.calibration.count_ones(bits)[source]#

How many of bits are 1. Measurement results arrive bit-packed, so a controller counts them a 32-bit word at a time.

Parameters:

bits (Sequence[int])

Return type:

int

cudaq_pulse.classical.calibration.decay_time(p0, p1, p3, spacing, shots_count)[source]#

The analytical decay estimator: the decay time T of A exp(-t / T) + C from its values at t0, t0 + spacing and t0 + 3 spacing, whatever A and C are (Marciniak et al., Eq. 1).

With c = (p3 - p0) / (p1 - p0) = x^2 + x + 1 and x = exp(-spacing / T), x = sqrt(c - 3/4) - 1/2. Returns T, its standard deviation from the binomial noise of shots_count shots per point (error propagation), and whether an estimate was formed (1 < c < 3, and not within rounding of 3). T is in the unit of spacing: ns when it is a time.

Parameters:
  • p0 (float)

  • p1 (float)

  • p3 (float)

  • spacing (float | Time)

  • shots_count (int)

Return type:

tuple[float, float, bool]

cudaq_pulse.classical.calibration.frequency_update(mean_hz, sigma_hz, outcome, wait_ns, phase)[source]#

The Gaussian posterior over a detuning after one Ramsey shot.

The shot waits wait_ns (a time, or a number of ns) between two pi/2 pulses, the second advanced by phase, and reports 1 with probability (1 - cos(2 pi D t + phase)) / 2 for detuning D. The posterior is the Gaussian with the exact mean and variance of prior times likelihood.

Parameters:
  • mean_hz (float)

  • sigma_hz (float)

  • outcome (int)

  • wait_ns (float | Time)

  • phase (float)

Return type:

tuple[float, float]

cudaq_pulse.classical.calibration.golden_section_step(state, cost)[source]#

Tell the search cost at state.next_point(); returns the new state, the point to measure next and whether the search has converged.

Parameters:
Return type:

tuple[GoldenSection, float, bool]

cudaq_pulse.classical.calibration.nelder_mead_step(state, cost)[source]#

Tell the search cost at state.next_point(); returns the new state, the point to measure next and whether the search has converged.

Standard coefficients: reflection 1, expansion 2, contraction 1/2, shrink 1/2.

Parameters:
Return type:

tuple[NelderMead, tuple[float, …], bool]

cudaq_pulse.classical.calibration.pi_train_amplitude(amplitude, theta, turns)[source]#

The corrected amplitude of a pulse from the sparse phase estimate theta of a train of its pulses that rotates by turns (odd) times pi when the amplitude is right, sampled at amplitude scales 1 - 1/(2 turns), 1 and 1 + 1/(2 turns) and read out as P(1).

P(1) = (1 - cos R) / 2 for the train’s rotation R, so theta = R + pi (mod 2 pi) and is 0 when R = turns pi. A pi pulse makes a train of turns pulses; a pi/2 pulse a train of 2 turns (Marciniak et al., Eq. 4, applying the pi/2 pulse twice).

Parameters:
  • amplitude (float)

  • theta (float)

  • turns (int)

Return type:

float

cudaq_pulse.classical.calibration.rabi_probability(angle, amplitude_scale)[source]#

P(1) after a resonant rotation meant to be angle (rad), on a qudit whose drive is amplitude_scale times the calibrated one: sin(scale x angle / 2) ** 2.

Parameters:
  • angle (float)

  • amplitude_scale (float)

Return type:

float

cudaq_pulse.classical.calibration.ramsey_detuning(mean_hz, theta, wait_ns)[source]#

The detuning from the sparse phase estimate theta of Ramsey shots of wait wait_ns at phases phi0 - pi/2, phi0 and phi0 + pi/2, with phi0 = -2 pi mean t (the convention of frequency_update: P(1) = (1 - cos(2 pi D t + phase)) / 2): D = mean + (theta - pi) / (2 pi t), the phase taken in (-pi, pi]. The wait is a time, or a number of ns.

Parameters:
  • mean_hz (float)

  • theta (float)

  • wait_ns (float | Time)

Return type:

float

cudaq_pulse.classical.calibration.ramsey_probability(wait_ns, phase, detuning_hz)[source]#

P(1) of a Ramsey shot that waits wait_ns (a time, or a number of ns) between two pi/2 pulses, the second advanced by phase, on a qudit detuning_hz off the drive: (1 - cos(2 pi D t + phase)) / 2, the likelihood frequency_update uses. Ideal pulses, no decay.

Parameters:
  • wait_ns (float | Time)

  • phase (float)

  • detuning_hz (float)

Return type:

float

cudaq_pulse.classical.calibration.ramsey_setting(mean_hz, sigma_hz, scale=0.1, max_wait_ns=None)[source]#

The wait (ns) and phase of the next Ramsey shot.

The phase puts the estimated detuning on the fringe’s steepest point, so the outcome says which side of the estimate the detuning is on. The wait is scale / sigma. Longer waits resolve the detuning more finely but wash out the fringe over the prior: 0.155 narrows the posterior most per shot (about 20%), but then one unlucky early shot can leave it confidently wrong; the default 0.1 narrows it by about 14% per shot and stays on the detuning in all but a few runs in a thousand. max_wait_ns caps the wait (a fraction of T2*, past which the fringe is gone; a time, or a number of ns); once it binds, every shot still narrows the posterior, more slowly.

Parameters:
  • mean_hz (float)

  • sigma_hz (float)

  • scale (float)

  • max_wait_ns (float | Time | None)

Return type:

tuple[float, float]

cudaq_pulse.classical.calibration.sparse_phase(p_minus, p_zero, p_plus, shots_count)[source]#

The sparse phase estimator: the phase theta0 of A cos(theta) + C from its values at theta0 - pi/2, theta0 and theta0 + pi/2, whatever A and C are: atan2(p- - p+, 2 (p0 - (p- + p+) / 2)) (Marciniak et al., Eq. 3; theta0 + pi for A < 0). Returns it and its standard deviation from the binomial noise of shots_count shots per point.

Parameters:
  • p_minus (float)

  • p_zero (float)

  • p_plus (float)

  • shots_count (int)

Return type:

tuple[float, float]

cudaq_pulse.classical.calibration.survival_probability(wait_ns, t1_us)[source]#

P(still excited) after exciting a qudit of t1_us and waiting wait_ns (a time, or a number of ns): exp(-wait / T1), the likelihood t1_update uses. A T1 of 0 is no decay.

Parameters:
  • wait_ns (float | Time)

  • t1_us (float)

Return type:

float

cudaq_pulse.classical.calibration.t1_update(alpha, beta, survived, wait_ns)[source]#

The posterior Gamma(alpha, beta) over Gamma = 1/T1 (per ns) after one shot that excited the qubit, waited wait_ns (a time, or a number of ns) and found it still excited (survived) or not.

Survival multiplies the prior by exp(-Gamma t), which keeps it a gamma distribution: beta grows by t. A decay multiplies it by 1 - exp(-Gamma t); the posterior is then the difference of two gamma distributions, and the result is the gamma distribution with its mean and variance.

Parameters:
  • alpha (float)

  • beta (float)

  • survived (bool)

  • wait_ns (float | Time)

Return type:

tuple[float, float]

cudaq_pulse.classical.calibration.t1_wait(alpha, beta, scale=1.0)[source]#

The next wait: scale times the estimated T1 (beta / alpha, in the units of beta).

Parameters:
  • alpha (float)

  • beta (float)

  • scale (float)

Return type:

float

cudaq_pulse.classical.calibration.three_point_decay(p0, p1, p2, spacing)[source]#

T in p(t) = A exp(-t / T) + B from p at t, t + spacing, t + 2 spacing.

The ratio (p1 - p2) / (p0 - p1) is exp(-spacing / T) whatever A and B are. Points that do not decay give inf. T is in the unit of spacing: ns when it is a time.

Parameters:
  • p0 (float)

  • p1 (float)

  • p2 (float)

  • spacing (float | Time)

Return type:

float

cudaq_pulse.classical.calibration.three_point_phase(p_minus, p_zero, p_plus, theta, delta)[source]#

The phase error e in p = a - b cos(theta + e), from p measured at theta - delta, theta and theta + delta (radians), whatever a and b are.

p+ - p- = 2 b sin(delta) sin(theta + e) and p+ + p- - 2 p0 = 2 b (1 - cos(delta)) cos(theta + e).

Parameters:
  • p_minus (float)

  • p_zero (float)

  • p_plus (float)

  • theta (float)

  • delta (float)

Return type:

float

Loops between shots#

Closed loops between shots: the parameters a program runs with, and the log of what was estimated.

A loop compiles its kernel once and runs it with the store’s current values each iteration, without compiling again. Amplitudes, phases and frequencies can be float parameters of the kernel, passed each iteration. A quantity that shapes the timeline, such as a wait, is read at run time instead: store.reader("wait_ns") is a classical function that answers with the store’s current value (on hardware, a read of a controller register), and a variable wait takes its length from the answer:

store = ParameterStore(amplitude=0.157, wait_ns=2000.0)
read_wait = store.reader("wait_ns", bounds=(0.0, 40000.0))

@pulse.kernel
def probe(q, amplitude: float):
    ...
    wait(d, read_wait.submit().result(), bounds=(0, 80000))

log = EstimateLog()
compiled = pulse.compile(probe, quantum_system=qs)
for i in range(10_000):
    scheduled = compiled.lower(q, store["amplitude"])
    outcome = ...  # run or simulate it
    estimate = update(...)  # the estimator, outside the kernel
    store.set("amplitude", estimate, iteration=i)
    log.record(i, "amplitude", estimate, uncertainty=..., truth=...)

The estimators of cudaq_pulse.classical.calibration serve both inside kernels (as the bodies of classical functions) and in such loops.

class cudaq_pulse.classical.loop.Estimate(
iteration,
name,
value,
uncertainty=None,
truth=None,
time_s=None,
)[source]#

Bases: object

One estimate of a quantity, with what was true if known.

Parameters:
  • iteration (int)

  • name (str)

  • value (float)

  • uncertainty (float | None)

  • truth (float | None)

  • time_s (float | None)

iteration: int#
name: str#
value: float#
uncertainty: float | None = None#
truth: float | None = None#
time_s: float | None = None#
class cudaq_pulse.classical.loop.EstimateLog[source]#

Bases: object

Every estimate a loop made, by quantity.

entries: list[Estimate]#
record(
iteration,
name,
value,
*,
uncertainty=None,
truth=None,
time_s=None,
)[source]#

Add an Estimate of name made at iteration, with its uncertainty, truth and time_s if given.

Parameters:
  • iteration (int)

  • name (str)

  • value (float)

  • uncertainty (float | None)

  • truth (float | None)

  • time_s (float | None)

Return type:

None

series(name)[source]#

The estimates of name, in the order they were recorded.

Parameters:

name (str)

Return type:

list[Estimate]

tracking_error(name)[source]#

The root-mean-square of estimate minus truth over the estimates of name that have a truth.

Parameters:

name (str)

Return type:

float

to_json()[source]#

The log as a JSON array with an object of fields per estimate, which from_json reads back.

Return type:

str

classmethod from_json(text)[source]#

A log of the estimates in text, a JSON array as to_json writes.

Parameters:

text (str)

Return type:

EstimateLog

extend(entries)[source]#

Add entries, such as another log’s, after the estimates already here.

Parameters:

entries (Iterable[Estimate])

Return type:

None

class cudaq_pulse.classical.loop.ParameterStore(values=None, /, **named)[source]#

Bases: object

Named calibration parameters, versioned on every change.

store[name] reads one; values(*names) reads several in order, for a kernel’s float arguments; set and update change them and bump version; history lists every change.

Parameters:
  • values (Mapping[str, float] | None)

  • named (float)

history: list[Update]#
values(*names)[source]#

The current values of names, in that order, as a kernel’s float arguments take them. A name the store does not have raises NotFoundError.

Parameters:

names (str)

Return type:

tuple[float, …]

set(name, value, *, iteration=None)[source]#

Set name to value, bump version and add the change, with the loop iteration that made it, to history. A non-finite value raises InvalidValueError and changes nothing.

Parameters:
  • name (str)

  • value (float)

  • iteration (int | None)

Return type:

None

update(values, *, iteration=None)[source]#

set each of values in turn, all with the same iteration; each bumps version. A non-finite value raises InvalidValueError, and the values before it stay set.

Parameters:
  • values (Mapping[str, float])

  • iteration (int | None)

Return type:

None

reader(
name,
*,
link=0,
max_latency_ns=0.0,
bounds=None,
)[source]#

A classical function of no arguments that answers with the current value of name (in clock cycles if it is a wait’s length), so a program compiled once reads each iteration’s value at run time. With bounds the value is clamped to them. On hardware it is a read of a controller register named like the function, read_<name>.

Parameters:
  • name (str)

  • link (int | str)

  • max_latency_ns (float | Time)

  • bounds (tuple[float, float] | None)

Return type:

ClassicalFunction[…, Any]

snapshot()[source]#

The current values (a copy).

Return type:

dict[str, float]

class cudaq_pulse.classical.loop.Update(name, value, version, iteration)[source]#

Bases: object

One change of a parameter: its new value, the store’s version after it, and the loop iteration that made it.

Parameters:
  • name (str)

  • value (float)

  • version (int)

  • iteration (int | None)

name: str#
value: float#
version: int#
iteration: int | None#