Skip to content

QuantumProgram

Bases: Displayable

A container for the main quantum program to be executed.

At its core, a QuantumProgram is an InstructionStack to run, a collection of all possible Instruction objects that could be run (either "global" or patch-based), and default noise model and RNG seeds. Once the run command has been used, it also contains a collection of History objects for each shot.

Examples:

>>> from loqs.core import QuantumProgram
>>> prog = QuantumProgram(instruction_stack=[], name="MyProgram")
>>> prog.name
'MyProgram'

QuantumProgram

QuantumProgram(instruction_stack: InstructionStackLike = None, initial_history: HistoryLike = None, default_noise_model: BaseNoiseModel | str | None = None, default_base_seed: int | None = None, expiring_state: bool = True, global_instructions: Mapping[str, Instruction] | None = None, state_type: type[BaseQuantumState] | None = None, patch_types: Mapping[str, QECCode] | None = None, override_global_instructions: bool = False, name: str = '(Unnamed quantum program)') -> None

Parameters:

Name Type Description Default
instruction_stack InstructionStackLike

A list of InstructionLabel castable objects that determine what operations get run during program execution. Defaults to None, in which case initial_history needs to be provided and contain a "stack" entry in the final Frame.

None
initial_history HistoryLike

An initial History to start num_shots from. Defaults to None, in which case an empty History is initialized and instruction_stack must be provided. Unless a History is passed, shots don't save the quantum state (it reads back as "NOT SERIALIZED"); passing a History, which saves everything by default, keeps it.

None
default_noise_model BaseNoiseModel | str | None

A noise model to pass to any Instruction that requests a model but does not have one provided in its [][](api:Instruction.data).

None
default_base_seed int | None

Base seed to use for RNG. Each shot will use a seed as default_base_seed + .

None
expiring_state bool

Whether to set "state" as an expiring key in the initial_history. Defaults to True, matching the default behavior of expiring_keys. A History initial history is then treated as if it had always expired "state": its earlier frames' state reads as expired, and the run's first new state expires the last one.

True
global_instructions Mapping[str, Instruction] | None

A list of Instruction objects that are not associated with a specific QECCodePatch.

None
state_type type[BaseQuantumState] | None

The state type to use when constructing the "Init State" global instruction. Defaults to None, in which case an initial_history needs to be provided and have "state" available in the final frame.

None
patch_types Mapping[str, QECCode] | None

A dict of name keys and QECCode values to use when constructing "Init Patch <key>" global instructions. If provided, then the "Remove Patch" global instruction is also created. Defaults to None, in which case the initial_history needs to be provided and have "patches" available in the final frame.

None
override_global_instructions bool

Whether or not to override "Init State", "Init Patch <key>", and "Remove Patch" instructions if they exist in global_instructions, and state_type and/or patch_types are provided. Defaults to False, which preserves the existing instructions.

False
name str

Name for logging

'(Unnamed quantum program)'

decode

Inherited static method from Serializable.decode().


display

Inherited method from Displayable.display().


dump

Inherited method from Serializable.dump().


encode

Inherited static method from Serializable.encode().


from_quantum_program classmethod

from_quantum_program(other: QuantumProgram, instruction_stack: InstructionStackLike = None, default_noise_model: BaseNoiseModel | str | None = None, default_base_seed: int | None = None, global_instructions: Mapping[str, Instruction] | None = None, state_type: type[BaseQuantumState] | None = None, patch_types: Mapping[str, QECCode] | None = None, name: str | None = None) -> QuantumProgram

Create a copy of a QuantumProgram with some options updated.

Parameters:

Name Type Description Default
other QuantumProgram

The base QuantumProgram to copy

required
instruction_stack InstructionStackLike

See instruction_stack in QuantumProgram

None
default_noise_model BaseNoiseModel | str | None

See default_noise_model in QuantumProgram

None
default_base_seed int | None

See default_base_seed in QuantumProgram

None
global_instructions Mapping[str, Instruction] | None

See global_instructions in QuantumProgram

None
state_type type[BaseQuantumState] | None

See state_type in QuantumProgram

None
patch_types Mapping[str, QECCode] | None

See patch_types in QuantumProgram

None
name str | None

See name in QuantumProgram

None

Returns:

Type Description
QuantumProgram

The copied and updated QuantumProgram


load

Inherited class method from Serializable.load().


read

Inherited class method from Serializable.read().


run

run(num_shots: int = 1, max_frame_limit: int | None = None, shot_executor: SubmitExecutor | None = None, verbose: bool = True, checkpoint: bool = False, resume: bool = False, checkpoint_batch_size: int | None = None, checkpoint_dir: str | Path | None = None, force_resume: bool = False, n_shot_batches: int | None = None, results_filename: str = 'results.h5', progress_callback: Callable[[int, int], None] | None = None) -> ProgramResults

Execute some shots of this QuantumProgram.

This returns a ProgramResults object containing the shot histories and wall-clock timing metadata.

Parameters:

Name Type Description Default
num_shots int

The number of shots to execute.

1
max_frame_limit int | None

A maximum number of frames to execute before terminating. The default None means no limit; with no limit, a program that never empties its stack runs until interrupted. An integer stops the shot after that many frames with a warning and a truncated history.

None
shot_executor SubmitExecutor | None

A SubmitExecutor (e.g. a loky.get_reusable_executor() instance, or an mpi4py.futures.MPIPoolExecutor) to parallelize shots across. Defaults to None, which runs shots in serial. Each worker pins its own thread pools to one thread before running, avoiding BLAS/OpenMP oversubscription regardless of how many workers shot_executor itself spawns. A ThreadPoolExecutor raises ValueError with checkpoint=True, since threads share one per-process progress ledger.

None
verbose bool

Whether to write a progress bar (True, default) or not (False) when running shots.

True
checkpoint bool

Whether to durably checkpoint shots to disk as they complete (False, default -- no checkpointing at all, checkpoint_dir/ checkpoint_batch_size/resume/force_resume are all ignored). The sole gate for whether any checkpoint file gets read or written -- checkpoint_batch_size/checkpoint_dir being set alone does not enable checkpointing. A checkpointed run evicts each shot from the returned ProgramResults's shot_histories once it's written, bounding this process's memory; shots read back via get_shot_history(), collect_shot_data() or load_checkpoint(). shot_wall_clock_times is not evicted and stays fully in memory.

False
resume bool

Whether this call continues a prior checkpoint-enabled call against the same checkpoint_dir, rather than starting fresh. Requires checkpoint=True (raises ValueError otherwise). Explicit by design, not inferred from on-disk state alone: with checkpoint=True, on-disk state already present at checkpoint_dir and resume=False raises ValueError (never silently overwrite or silently resume); resume=True with nothing on disk to resume from also raises ValueError (nothing to resume from -- also catches a caller pointing resume=True at the wrong checkpoint_dir). Only a genuine on-disk match with resume=True actually resumes, subject to the mismatch check below.

checkpoint_batch_size: Number of shots to accumulate, per writer, before durably flushing them to disk. Only meaningful when checkpoint=True; ignored otherwise. Mutually exclusive with n_shot_batches (providing both raises ValueError). If both n_shot_batches and checkpoint_batch_size are None, both default to max(1, ceil(num_shots / 20)). If shot_executor is given, each dispatched batch of this many shots is computed and checkpointed together inside its own worker process, keyed by that worker's own hostname_pid identity, so multiple workers never contend for the same file. Each worker writes a batch to its own payload file and marks it done in its own SWMR progress ledger; once every batch has returned, run() merges every payload into one final, bounded-memory-streamed results.h5 (see consolidate_checkpoints()). With no shot_executor (serial), there is only ever one writer, so shots are appended directly to that same results.h5 with no merge step. Set to 1 to checkpoint every single shot as soon as it completes (the finest possible granularity -- a crash loses at most one in-flight shot per writer); a larger value trades that granularity for fewer, larger writes.

False
checkpoint_dir str | Path | None

Directory to store checkpoint files. If None (default), checkpoints are stored in a ./checkpoints directory in the current working directory. Only relevant when checkpoint=True; ignored otherwise.

None
force_resume bool

When resuming a checkpoint-enabled call (rerunning against a checkpoint_dir with prior partial results), if this is False (default) and the stored num_shots/max_frame_limit/ default_base_seed differ from this call's own, raise ValueError naming the mismatches. Set to True to resume anyway, trusting the already-checkpointed data as-is. Has no effect when checkpoint is False.

False
n_shot_batches int | None

Number of batches to split shots into. A batch count, not a size (e.g. n_shot_batches=5 with num_shots=100 produces 5 batches of 20 shots each). Mutually exclusive with checkpoint_batch_size (providing both raises ValueError). None (default) means "auto": max(1, ceil(num_shots / 20)) when needed. If given explicitly, used as-is regardless of dispatch mode; if neither n_shot_batches nor checkpoint_batch_size is given, both default to the same auto formula applied independently to their own modes.

None
results_filename str

Filename to use for the canonical results checkpoint file. Defaults to "results.h5". Only relevant when checkpoint=True.

'results.h5'
progress_callback Callable[[int, int], None] | None

Optional callable invoked as progress_callback(shots_done, shots_total): once before the first shot, then each time the progress bar advances (after every serial shot, or as each parallel batch returns). shots_total is num_shots; shots_done is the absolute number of shots computed in this call's results, including shots loaded from a resumed checkpoint -- not the number durably checkpointed so far. It always runs in the calling process, never in a shot_executor worker, and is called regardless of verbose. Defaults to None (no callback).

None

Returns:

Type Description
ProgramResults

A ProgramResults object containing the shot histories and shot_wall_clock_times (wall-clock timing metadata for each shot).


serialize_function

Inherited static method from Serializable.serialize_function().


write

Inherited method from Serializable.write().