Simulation API#

Warning

Simulation is a research-preview interface with no stability or numerical-accuracy guarantee. See Simulation for the physical model and GPU Simulation Reference for unsupported features.

cudaq_pulse.simulate(
program,
/,
*args,
levels=None,
initial_state=None,
shots_count=None,
seed=None,
backend='cpu',
t_end=None,
dt_ns=None,
integrator='rk4',
dephasing='t2_star',
handlers=None,
readout='ideal',
latency_branching=False,
quantum_system=None,
branches=BranchCoverage.ALL,
reset_time=None,
)[source]#

Simulate one kernel call on the quantum system it is compiled for.

simulate(kernel, *args) compiles the call as kernel.lower(*args) does and simulates it, as compile(kernel) takes the kernel first and its options by keyword. A program compiled already is simulated without compiling it again, such as one a worker process receives pickled: simulate(program, *values) binds the values of its run-time float parameters as program.bind(values) does.

Parameters:
  • program (Kernel[...] | CompiledKernel[...] | ScheduledKernel) – A @cudaq_pulse.kernel or the CompiledKernel of one, called with args; a module with run-time float parameters, such as lowered.generic, bound with args; or the module of one call, from kernel.lower(*args) or bind, with no args.

  • args (Any) – For a kernel, its arguments by position: the qudit handles, then its other parameters. For a module with run-time parameters, their values, in the order of program.parameters.

  • levels (int | dict[int, int] | None) – Levels per qudit. By default each qudit has the levels its quantum system’s simulation model declares for it (QuantumSystem.model; 3 for a TransmonModel); an int sets every qudit’s, and a dict by quantum system qudit index sets those it names. A transmon with three or more levels includes its anharmonicity.

  • initial_state (npt.ArrayLike | None) – A state vector or density matrix over lowered.qudits, the qudits the program uses, with the first the least significant digit (the layout of SimulationResult.density_matrix). By default each qudit starts in its thermal mixture: its excited level holds the quantum system’s thermal_population p, and higher levels follow the same Boltzmann ratio p / (1 - p) per level (|0...0> when every p is 0). T1 then relaxes it back there, with downward and upward rates (1 - p) / T1 and p / T1, whatever the initial state.

  • shots_count (int | None) – Sample this many per-shot measurement records: a positive int. None (the default) samples none.

  • seed (int | None) – Seed for sampling the records.

  • backend (str) – "cpu" for the NumPy reference integrator (RK4), "gpu" for the cuDensityMat runtime.

  • t_end (float | Time | None) – End of the simulation: a time (40 * pulse.ns) or a number of ns; the end of the schedule by default.

  • dt_ns (float | Time | None) – Integration step: a time or a number of ns. By default 0.05 ns, or shorter when the simulation holds a faster frequency: a coupling turns at its qudits’ detuning, and a qudit’s levels at the spread of their energies in its frame (of four or more transmon levels, a multiple of its anharmonicity). The step resolves it with 20 steps per period (0.024 ns at 2.1 GHz), a whole fraction of a clock cycle. A step passed here that takes fewer than 20 steps per period of the fastest frequency the simulation holds, a qudit’s anharmonicity with three or more levels or the detuning of coupled qudits, warns with a PulseWarning that names that frequency and a step that resolves it. A step so coarse that the integrator diverges raises ExecutionError, naming the same and the line that called simulate, rather than returning a state that is not finite.

  • integrator (str) – cuDensityMat integrator for the GPU backend: "rk1", "rk2", "rk4", "magnus" or "crank_nicolson".

  • dephasing (str) – Dephase at each qudit’s Ramsey T2* ("t2_star", the default) or its Hahn-echo T2 ("t2_echo"), which every simulated qudit must have.

  • handlers (Mapping[str, Callable[..., Any]] | None) – For a program that calls classical functions, what answers each call, by function name: a Python callable taking the call’s arguments (bits and levels as lists of ints, numbers as floats), by default the function’s own body. Each call’s answer is bound to its path, and the path is scheduled again, so answers that set amplitudes, frequencies, branches or wait lengths take effect exactly.

  • readout (str) – "ideal" (the default) reports the measured level. "model" reports through each qubit’s assignment errors (its DispersiveReadout’s error_1to0 and error_0to1) and "model_with_decay" adds relaxation during the readout window; branches and calls see the reported outcome, and the state is projected on the true one. A call that takes IQ points (complex or list[complex]) gets points synthesized per shot at each readout’s true level, from its tone’s frequency and its pulse’s amplitude (IQModel; with "model_with_decay", relaxation during the window too); it needs shots_count, and each shot from the call on is simulated as its own trajectory.

  • quantum_system (Any) – A QuantumSystem to simulate instead of the one the program was compiled for: its qudits’ frequencies, T1, T2, thermal populations, drive strength and readout parameters apply, while the program (its tones and pulses) stays as compiled. A system with parameter drift (cudaq_pulse.quantum_systems.drift) plays its true values, true_qudits, whether it is this one or the one the program is compiled for, and the call advances its drift time.

  • latency_branching (bool) – With a timeout, branch on whether the answer came in time with the probability of the function’s latency model; by default, without shots, the answer is in time when the nominal latency is within the timeout. With shots the in-time outcome is always sampled.

  • branches (BranchCoverage | str) – "all" (the default) follows every outcome of every measurement, so the state is the exact ensemble. "sampled" follows only the outcomes the shots draw: at most shots_count branches, so a program that measures many times inside one shot (an adaptive loop of readouts and calls) does not cost time exponential in its measurements. A loop that waits each round on a variable or blocking wait costs the same host time per round at any length; other programs with calls are scheduled again whole after each answer, so their host time per interval grows with the rounds before it. The state is then the average over the shots’ branches, and result.branches gives each one’s share of the shots. It needs shots_count. A BranchCoverage or its string.

  • reset_time (Time | None) – The time between shots, after each run of the program, as 200 * pulse.us: a system with parameter drift advances its drift time by shots_count (or one) times the program’s duration plus this. By default 5 times the longest calibrated T1 of the program’s qudits, a passive reset. It changes nothing else, and nothing for a system without drift. A call whose shots take longer than the shortest correlation time of the drift models is split into chunks of whole shots, each at least that long, and each plays the true values at its start; the result merges them, weighted by shots, with the records in shot order.

Return type:

SimulationResult

class cudaq_pulse.SimulationResult(
density_matrix,
dims,
qudits,
measurements,
branches,
records=None,
times_ns=(0.0, 0.0),
acceptance=1.0,
)[source]#

Bases: object

The ensemble final state, and per-shot records if shots were taken.

The state spans the qudits the program uses, qudits (quantum system indices, increasing), with dims[i] levels on qudits[i]; density_matrix is indexed with qudits[0] as the least significant digit. Qudits the program does not use are left out, with their couplings, as classical spectators in their ground state. measurements lists every measurement any path made, in the order of their end times; branches holds one Branch per path, with its measured levels (one per entry of measurements, -1 where that path did not measure), its probability and its classical calls. records holds one row of levels per shot. With branches="sampled", branches holds the branches the shots took, each with the fraction of shots that took it, and the state is their average. postselect gives the result over the branches a test keeps, and acceptance the fraction of the ensemble it kept.

Parameters:
  • density_matrix (npt.NDArray[np.complex128])

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

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

  • measurements (list[Measurement])

  • branches (list[Branch])

  • records (npt.NDArray[np.int64] | None)

  • times_ns (tuple[float, float])

  • acceptance (float)

density_matrix: npt.NDArray[np.complex128]#
dims: tuple[int, ...]#
qudits: tuple[int, ...]#
measurements: list[Measurement]#
branches: list[Branch]#
records: npt.NDArray[np.int64] | None = None#
times_ns: tuple[float, float] = (0.0, 0.0)#
acceptance: float = 1.0#

The probability of the branches this result keeps: 1.0 unless postselect made it.

postselect(keep, /)[source]#

The result over the branches keep accepts, a test of a Branch, as lambda b: b.levels[0] == 0 or lambda b: b.answers("herald")[-1]: its state is theirs, normalized, each kept branch’s probability is divided by their total, which is the result’s acceptance (times this result’s), and records holds the kept branches’ shots. Where branches of the same levels are both kept and not (calls that took IQ points, or timeouts with latency_branching), a shot’s levels do not say which it took, and records is None.

A test that keeps no branch raises InvalidValueError. A result merged from the shot chunks of a quantum system with parameter drift holds no state per branch, and raises UnsupportedError.

Parameters:

keep (Callable[[Branch], bool])

Return type:

SimulationResult

level_populations(qudit=None)[source]#

The probability of each level of qudit, from level 0 up: the diagonal of its reduced density matrix, summing to 1.

qudit is a quantum system qudit index or a qudit handle, one of qudits; it may be left out when the result models one qudit.

Parameters:

qudit (int | Qudit | None)

Return type:

list[float]

level_population(level, qudit=None)[source]#

The probability that qudit is in level, as in level_populations(qudit)[level].

Parameters:
  • level (int)

  • qudit (int | Qudit | None)

Return type:

float

class cudaq_pulse.BranchCoverage(*values)[source]#

Bases: StrEnum

Which measurement branches simulate follows; the strings "all" and "sampled" mean the same.

ALL = 'all'#

Every outcome of every measurement: the exact ensemble.

SAMPLED = 'sampled'#

Only the outcomes the shots draw, at most shots_count branches.

class cudaq_pulse.runtime.simulate.Measurement(readout, iteration, qudit, start_ns, end_ns)[source]#

Bases: object

One execution of a readout: which one, on which (quantum system) qudit, and when.

Parameters:
  • readout (int)

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

  • qudit (int)

  • start_ns (float)

  • end_ns (float)

readout: int#
iteration: tuple[int, ...]#
qudit: int#
start_ns: float#
end_ns: float#
class cudaq_pulse.runtime.simulate.Branch(levels, probability, calls=())[source]#

Bases: object

One path of the ensemble: the levels its measurements gave, its probability, and the classical calls it made.

levels holds one entry per entry of SimulationResult.measurements, -1 where this branch did not measure. With branches="sampled", probability is the fraction of the shots that took the branch.

Parameters:
  • levels (tuple[int, ...])

  • probability (float)

  • calls (tuple[CallRecord, ...])

levels: tuple[int, ...]#
probability: float#
calls: tuple[CallRecord, ...] = ()#

The classical calls this branch made, in time order.

answers(function)[source]#

The answers of this branch’s calls to function (its name), in call order. A function it did not call is a KeyError listing those it called.

Parameters:

function (str)

Return type:

list[Any]

GPU runtime#

The GPU runtime is loaded on first use; its errors are on Errors.

cudaq_pulse.runtime.require_gpu_runtime()[source]#

Return the loaded GPU runtime, or raise a specific GpuRuntimeError.

A process forked after its parent used the GPU cannot use it: start GPU workers with the spawn or forkserver multiprocessing method, or fork before the first GPU simulation.

Return type:

GpuRuntime

class cudaq_pulse.runtime.GpuRuntime(library, path, device_count, cuda_major=None)[source]#

Bases: object

A loaded cuDensityMat runtime with at least one usable device.

Parameters:
  • library (CDLL)

  • path (Path)

  • device_count (int)

  • cuda_major (int | None)

library: CDLL#

The cudaq-pulse GPU runtime library, loaded from path. It is the project’s own library, not cuDensityMat itself.

path: Path#

The file the library was loaded from: the bundled runtime for the selected CUDA major version, or the file CUDM_RUNTIME_LIB names.

device_count: int#

The number of GPU devices CUDA reports. It is never 0 in a runtime that require_gpu_runtime() returns, which raises instead.

cuda_major: int | None = None#

The CUDA major version of the runtime, 12 or 13. It is None only when CUDM_RUNTIME_LIB names the library and neither CUDAQ_PULSE_CUDA nor a single installed CUDA extra says which it is.