QuantumProgram

class QuantumProgram(backend, seed=None, progress_queue=None, program_id=None, precision=8, suppress_performance_warnings=False, **kwargs)[source]

Bases: ABC

Abstract base class for quantum programs.

Subclasses must implement:
  • run(): Execute the quantum algorithm

Program-author extension hooks (override as needed):

  • _spec_stage() — Returns the SpecStage that converts the seed into a MetaCircuit batch. Default returns CircuitSpecStage; override with TrotterSpecStage for Hamiltonian-seeded programs (QAOA, TimeEvolution).

  • _initial_spec() — Returns the seed passed into _spec_stage(). The base raises NotImplementedError; any subclass that calls evaluate() must implement it. VariationalQuantumAlgorithm returns its cost ansatz; QAOA / TimeEvolution return their Hamiltonian. Programs that never call evaluate (e.g. those that assemble their own pipeline inside run) do not need to implement this method.

Note: _spec_stage and _initial_spec are intentionally not abstract — _spec_stage has a working default, and _initial_spec is only required by programs that use evaluate.

Variables:
  • backend – The quantum circuit execution backend.

  • _seed – Random seed for reproducible results.

  • _progress_queue – Queue for progress reporting.

Initialize the QuantumProgram.

Parameters:
  • backend (CircuitRunner) – Quantum circuit execution backend.

  • seed (int | None) – Random seed for reproducible results. Defaults to None.

  • progress_queue (Queue | None) – Queue for progress reporting. Defaults to None.

  • program_id (str | None) – Program identifier for progress reporting in batch operations. If provided along with progress_queue, enables queue-based progress reporting.

  • precision (int) – Decimal places for numeric parameter values in QASM emission. Higher values produce longer QASM strings; lower values shrink them at the cost of parameter resolution. Defaults to DEFAULT_PRECISION.

  • suppress_performance_warnings (bool) – Silence DiviPerformanceWarning from this program’s pipelines (e.g. exhaustive-QuEPP scaling or bind-before-mitigation hints). Defaults to False.

Attributes Summary

precision

Decimal places used for numeric parameter values in QASM emission.

total_circuit_count

Cumulative count of circuits submitted for execution across all runs of this program.

total_run_time

Cumulative backend execution time in seconds across all runs of this program.

Methods Summary

cancel_unfinished_job()

Cancel the currently running cloud job if one exists.

dry_run(*[, force_circuit_generation])

Run a forward pass on each exposed preprocessor and return a fan-out analysis.

evaluate(params, preprocessor, *[, shots, ...])

Measure this program's prepared state under preprocessor for params.

has_results()

Return True once the program has produced results.

run(**kwargs)

Execute the quantum algorithm.

Attributes Documentation

precision

Decimal places used for numeric parameter values in QASM emission.

total_circuit_count

Cumulative count of circuits submitted for execution across all runs of this program.

total_run_time

Cumulative backend execution time in seconds across all runs of this program.

Methods Documentation

cancel_unfinished_job()[source]

Cancel the currently running cloud job if one exists.

This method attempts to cancel the job associated with the current ExecutionResult. It is best-effort and will log warnings for any errors (e.g., job already completed, permission denied) without raising exceptions.

This is typically called by ProgramEnsemble when handling cancellation to ensure cloud jobs are cancelled before local threads terminate.

dry_run(*, force_circuit_generation=False)[source]

Run a forward pass on each exposed preprocessor and return a fan-out analysis.

Traverses each preprocessor’s pipeline without executing circuits and collects the fan-out factor, per-stage metadata, and total circuit count into a dict of DryRunReport objects keyed by preprocessor name (see _preprocessors()). Pass the returned dict to format_dry_run() for the pretty tree output.

Uses the analytic dry path by default; see the user guide for how that trades circuit generation for multiplicative-factor bookkeeping.

Parameters:

force_circuit_generation (bool) – If True, force every stage to run its full expand path so that the trace contains real DAGs and QASM strings. Useful when inspecting actual pipeline output (e.g. debugging a stage’s circuit transformation). Defaults to False.

Return type:

dict[str, DryRunReport]

Example

>>> from divi.pipeline import format_dry_run
>>> reports = program.dry_run()
>>> format_dry_run(reports)  # pretty-print to stdout
evaluate(params, preprocessor, *, shots=None, return_variance=False, preserve_keys=False, axes_to_preserve=())[source]

Measure this program’s prepared state under preprocessor for params.

The single entry point external callers (optimizers, metric estimators) use instead of assembling pipelines themselves. preprocessor supplies the post-spec MetaCircuit transform, the result format, and an optional custom terminal stage.

Parameters:
  • params (ndarray) – Parameter set(s) to evaluate; coerced to 2D (n_sets, n_params).

  • preprocessor (CircuitPreprocessor) – Selects the routine (cost / sample / metric / …).

  • shots (int | None) – Per-evaluation shot-count override. None (default) uses the backend’s own shot count; shot-adaptive optimizers (e.g. SPSA’s M_k schedule) pass an explicit budget the static backend cannot supply.

  • return_variance (bool) – Also return per-set shot-noise variance.

  • preserve_keys (bool) – Output control. When True, return the raw pipeline-result dict (keyed by full (axis, value) keys) instead of collapsing it to {param_set_idx: value}.

  • axes_to_preserve (tuple[str, ...]) – Pipeline-reduce control. Spec axes named here are kept in the result keys instead of being averaged away (e.g. the per-branch ham axis for the QDrift metric cohort). Operates on a different layer than preserve_keys and requires it: preserved axes would otherwise collide when the result is collapsed by param_set.

Return type:

dict[int, Any] | PipelineResult | tuple[dict[int, Any], dict[int, float]]

Returns:

{param_set_idx: value} (value shape per preprocessor.result_format), the raw pipeline-result dict when preserve_keys=True, or (values, shot_variances) when return_variance=True.

abstractmethod has_results()[source]

Return True once the program has produced results.

Return type:

bool

abstractmethod run(**kwargs)[source]

Execute the quantum algorithm.

Parameters:

**kwargs – Additional keyword arguments for subclasses.

Returns:

Returns self for method chaining.

Return type:

QuantumProgram