QuantumProgram¶
- class QuantumProgram(backend, seed=None, progress_queue=None, program_id=None, precision=8, suppress_performance_warnings=False, **kwargs)[source]¶
Bases:
ABCAbstract base class for quantum programs.
- Subclasses must implement:
run(): Execute the quantum algorithm
Program-author extension hooks (override as needed):
_spec_stage()— Returns theSpecStagethat converts the seed into aMetaCircuitbatch. Default returnsCircuitSpecStage; override withTrotterSpecStagefor Hamiltonian-seeded programs (QAOA, TimeEvolution)._initial_spec()— Returns the seed passed into_spec_stage(). The base raisesNotImplementedError; any subclass that callsevaluate()must implement it.VariationalQuantumAlgorithmreturns its cost ansatz; QAOA / TimeEvolution return their Hamiltonian. Programs that never callevaluate(e.g. those that assemble their own pipeline insiderun) do not need to implement this method.
Note:
_spec_stageand_initial_specare intentionally not abstract —_spec_stagehas a working default, and_initial_specis only required by programs that useevaluate.- 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 toDEFAULT_PRECISION.suppress_performance_warnings (
bool) – SilenceDiviPerformanceWarningfrom this program’s pipelines (e.g. exhaustive-QuEPP scaling or bind-before-mitigation hints). Defaults to False.
Attributes Summary
Decimal places used for numeric parameter values in QASM emission.
Cumulative count of circuits submitted for execution across all runs of this program.
Cumulative backend execution time in seconds across all runs of this program.
Methods Summary
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
preprocessorforparams.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
DryRunReportobjects keyed by preprocessor name (see_preprocessors()). Pass the returned dict toformat_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) – IfTrue, force every stage to run its fullexpandpath 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 toFalse.- Return type:
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
preprocessorforparams.The single entry point external callers (optimizers, metric estimators) use instead of assembling pipelines themselves.
preprocessorsupplies the post-specMetaCircuittransform, 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’sM_kschedule) pass an explicit budget the static backend cannot supply.return_variance (
bool) – Also return per-set shot-noise variance.preserve_keys (
bool) – Output control. WhenTrue, 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-branchhamaxis for the QDrift metric cohort). Operates on a different layer thanpreserve_keysand requires it: preserved axes would otherwise collide when the result is collapsed byparam_set.
- Return type:
dict[int,Any] |PipelineResult|tuple[dict[int,Any],dict[int,float]]- Returns:
{param_set_idx: value}(value shape perpreprocessor.result_format), the raw pipeline-result dict whenpreserve_keys=True, or(values, shot_variances)whenreturn_variance=True.
- abstractmethod has_results()[source]¶
Return True once the program has produced results.
- Return type: