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(
)[source]#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,
Simulate one kernel call on the quantum system it is compiled for.
simulate(kernel, *args)compiles the call askernel.lower(*args)does and simulates it, ascompile(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 asprogram.bind(values)does.- Parameters:
program (Kernel[...] | CompiledKernel[...] | ScheduledKernel) – A
@cudaq_pulse.kernelor theCompiledKernelof one, called with args; a module with run-time float parameters, such aslowered.generic, bound with args; or the module of one call, fromkernel.lower(*args)orbind, 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 aTransmonModel); 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 ofSimulationResult.density_matrix). By default each qudit starts in its thermal mixture: its excited level holds the quantum system’sthermal_populationp, 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
PulseWarningthat names that frequency and a step that resolves it. A step so coarse that the integrator diverges raisesExecutionError, naming the same and the line that calledsimulate, 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 (itsDispersiveReadout’serror_1to0anderror_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 (complexorlist[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 needsshots_count, and each shot from the call on is simulated as its own trajectory.quantum_system (Any) – A
QuantumSystemto 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 mostshots_countbranches, 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, andresult.branchesgives each one’s share of the shots. It needsshots_count. ABranchCoverageor 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 byshots_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:
-
class cudaq_pulse.SimulationResult(
)[source]#density_matrix,dims,qudits,measurements,branches,records=None,times_ns=(0.0, 0.0),acceptance=1.0,
Bases:
objectThe ensemble final state, and per-shot records if shots were taken.
The state spans the qudits the program uses,
qudits(quantum system indices, increasing), withdims[i]levels onqudits[i];density_matrixis indexed withqudits[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.measurementslists every measurement any path made, in the order of their end times;branchesholds oneBranchper path, with its measured levels (one per entry ofmeasurements, -1 where that path did not measure), its probability and its classical calls.recordsholds one row of levels per shot. Withbranches="sampled",branchesholds the branches the shots took, each with the fraction of shots that took it, and the state is their average.postselectgives the result over the branches a test keeps, andacceptancethe 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]#
- 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
postselectmade it.
- postselect(keep, /)[source]#
The result over the branches keep accepts, a test of a
Branch, aslambda b: b.levels[0] == 0orlambda b: b.answers("herald")[-1]: its state is theirs, normalized, each kept branch’s probability is divided by their total, which is the result’sacceptance(times this result’s), andrecordsholds the kept branches’ shots. Where branches of the same levels are both kept and not (calls that took IQ points, or timeouts withlatency_branching), a shot’s levels do not say which it took, andrecordsisNone.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 raisesUnsupportedError.- Parameters:
keep (Callable[[Branch], bool])
- Return type:
- 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]
- class cudaq_pulse.BranchCoverage(*values)[source]#
Bases:
StrEnumWhich measurement branches
simulatefollows; 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_countbranches.
- class cudaq_pulse.runtime.simulate.Measurement(readout, iteration, qudit, start_ns, end_ns)[source]#
Bases:
objectOne 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:
objectOne path of the ensemble: the levels its measurements gave, its probability, and the classical calls it made.
levelsholds one entry per entry ofSimulationResult.measurements, -1 where this branch did not measure. Withbranches="sampled",probabilityis 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.
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
spawnorforkservermultiprocessing method, or fork before the first GPU simulation.- Return type:
- class cudaq_pulse.runtime.GpuRuntime(library, path, device_count, cuda_major=None)[source]#
Bases:
objectA 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_LIBnames.
- 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
Noneonly whenCUDM_RUNTIME_LIBnames the library and neitherCUDAQ_PULSE_CUDAnor a single installed CUDA extra says which it is.