GenericIQAE
The implementation is based on Algorithm 1 & Algorithm 2 in [1], with the intent of demistifying variables names and simplifying the code flow. Moreover, we separated the algorithm flow from quantum execution to allow migrating this code to any execution interface and to improve its testability. Methods:iterations
iterations: list[IterationInfo] = []
run
run(
self:
) -> float
Execute the estimation algorithm.
See Algorithm 1, [1].
Parameters:
find_next_K
find_next_K(
K: int,
is_upper_plane: bool,
confidence_interval: np.ndarray,
r: int = 2
) -> tuple[int, bool]
We want to find the largest K (with some lower and upper bounds) such that the K-scaled confidence interval
lies completely in the upper or lower half planes.
See Algorithm 2, [1].
Parameters:
IQAEIterationData
Handles the data storage for a single iteration of the Iterative Quantum Amplitude Estimation algorithm. This class is intended to represent the results and state of a single Grover iteration of the IQAE process. Attributes:grover_iterations
grover_iterations: int
sample_results
sample_results: ExecutionDetails
IQAEResult
Represents the result of an Iterative Quantum Amplitude Estimation (IQAE) process. This class encapsulates the output of the IQAE algorithm, including the estimated value, confidence interval, intermediate iteration data, and any warnings generated during the computation. Attributes:estimation
estimation: float
confidence_interval
confidence_interval: list[float] = Field(min_length=2, max_length=2)
iterations_data
iterations_data: list[IQAEIterationData]
warnings
warnings: list[str]
ExecutionPreferences
Represents the execution settings for running a quantum program. Execution preferences for running a quantum program. For more details, refer to: ExecutionPreferences example: ExecutionPreferences.. Attributes:noise_properties
noise_properties: NoiseProperties | None = pydantic.Field(default=None, description='Properties of the noise in the circuit')
random_seed
random_seed: int = pydantic.Field(default_factory=create_random_seed, description='The random seed used for the execution')
backend_preferences
backend_preferences: BackendPreferencesTypes = backend_preferences_field(backend_name=(ClassiqSimulatorBackendNames.SIMULATOR))
num_shots
num_shots: pydantic.PositiveInt | None = pydantic.Field(default=None)
transpile_to_hardware
transpile_to_hardware: TranspilationOption = pydantic.Field(default=(TranspilationOption.DECOMPOSE), description='Transpile the circuit to the hardware basis gates before execution', title='Transpilation Option')
job_name
job_name: str | None = pydantic.Field(min_length=1, description='The job name', default=None)
include_zero_amplitude_outputs
include_zero_amplitude_outputs: bool = pydantic.Field(default=False, description='In state vector simulation, whether to include zero-amplitude states in the result. When True, overrides amplitude_threshold.')
amplitude_threshold
amplitude_threshold: float = pydantic.Field(default=0.0, ge=0, description='In state vector simulation, only states with amplitude magnitude strictly greater than this threshold are included in the result. Defaults to 0 (filters exactly zero-amplitude states). Overridden by include_zero_amplitude_outputs=True.')
Constraints
Constraints for the quantum circuit synthesis engine. This class is used to specify constraints such as maximum width, depth, gate count, and optimization parameters for the synthesis engine, guiding the generation of quantum circuits that satisfy these constraints. Attributes:max_width
max_width: pydantic.PositiveInt | None = pydantic.Field(default=None, description='Maximum number of qubits in generated quantum circuit')
optimization_parameter
optimization_parameter: OptimizationParameterType = pydantic.Field(default=(OptimizationParameter.NO_OPTIMIZATION), description='If set, the synthesis engine optimizes the solution according to that chosen parameter')
Preferences
Preferences for synthesizing a quantum circuit. Methods:
Attributes:
machine_precision
machine_precision: PydanticMachinePrecision = DEFAULT_MACHINE_PRECISION
backend_service_provider
backend_service_provider: Provider | ProviderVendor | str | None = pydantic.Field(default=None, description='Provider company or cloud for the requested backend.')
backend_name
backend_name: PydanticBackendName | AllBackendsNameByVendor | None = pydantic.Field(default=None, description='Name of the requested backend or target.')
custom_hardware_settings
custom_hardware_settings: CustomHardwareSettings = pydantic.Field(default_factory=CustomHardwareSettings, description='Custom hardware settings which will be used during optimization. This field is ignored if backend preferences are given.')
debug_mode
debug_mode: bool = pydantic.Field(default=True, description='Add debug information to the synthesized result. Setting this option to False can potentially speed up the synthesis, and is recommended for executing iterative algorithms.')
synthesize_all_separately
synthesize_all_separately: bool = pydantic.Field(default=False, description='If true, a heuristic is used to determine if a function should be synthesized separately', deprecated=True)
optimization_level
optimization_level: OptimizationLevel = pydantic.Field(default=(OptimizationLevel.LIGHT), description='The optimization level used during synthesis; determines the trade-off between synthesis speed and the quality of the results')
output_format
output_format: PydanticConstrainedQuantumFormatList = pydantic.Field(default=[QuantumFormat.QASM], description='The quantum circuit output format(s). ')
qasm3
qasm3: bool | None = pydantic.Field(None, description='Output OpenQASM 3.0 instead of OpenQASM 2.0. Relevant only for the qasmandtranspiled_circuit.qasmattributes ofGeneratedCircuit.')
transpilation_option
transpilation_option: TranspilationOption = pydantic.Field(default=(TranspilationOption.AUTO_OPTIMIZE), description='If true, the returned result will contain a transpiled circuit and its depth')
solovay_kitaev_max_iterations
solovay_kitaev_max_iterations: pydantic.PositiveInt | None = pydantic.Field(None, description='Maximum iterations for the Solovay-Kitaev algorithm (if applied).')
timeout_seconds
timeout_seconds: pydantic.PositiveInt = pydantic.Field(default=300, description='Generation timeout in seconds')
optimization_timeout_seconds
optimization_timeout_seconds: pydantic.PositiveInt | None = pydantic.Field(default=None, description='Optimization timeout in seconds, or None for no optimization timeout (will still timeout when the generation timeout is over)')
random_seed
random_seed: int = pydantic.Field(default_factory=create_random_seed, description='The random seed used for the generation')
symbolic_loops
symbolic_loops: bool = pydantic.Field(default=False)
compatibility_mode
compatibility_mode: bool = pydantic.Field(default=False)
backend_preferences
backend_preferences: BackendPreferences | None
ExecutionSession
A session for executing a quantum program or OpenQASM source text.ExecutionSession allows to execute the quantum program with different parameters and operations without the need to re-synthesize the model.
The session must be closed in order to ensure resources are properly cleaned up. It’s recommended to use ExecutionSession as a context manager for this purpose. Alternatively, you can directly use the close method.
Methods:
Attributes:
program
program = _openqasm_session_placeholder_program()
close
close(
self:
) -> None
Close the session and clean up its resources.
Parameters:
update_execution_preferences
update_execution_preferences(
self: ,
execution_preferences: ExecutionPreferences | None
) -> None
Update the execution preferences for the session.
Parameters:
Returns:
- Type:
None
sample
sample(
self: ,
parameters: ExecutionParams | list[ExecutionParams] | None = None,
num_shots: int | None = None,
run_via_classiq: bool | None = None
) -> ExecutionDetails | list[ExecutionDetails]
Samples the quantum program with the given parameters, if any.
Parameters:
Returns:
- Type:
ExecutionDetails \| list[ExecutionDetails] - The result of the sampling, or a list of results when
parametersis a list.
submit_sample
submit_sample(
self: ,
parameters: ExecutionParams | list[ExecutionParams] | None = None,
num_shots: int | None = None,
run_via_classiq: bool | None = None
) -> ExecutionJob
Initiates an execution job with the sample primitive.
This is a non-blocking version of sample: it gets the same parameters and initiates the same execution job, but instead
of waiting for the result, it returns the job object immediately.
Parameters:
Returns:
- Type:
ExecutionJob - The execution job.
calculate_state_vector
calculate_state_vector(
self: ,
parameters: ExecutionParams | list[ExecutionParams] | None = None,
filters: dict[str, Any] | None = None,
amplitude_threshold: float = 0.0
) -> DataFrame | list[DataFrame]
Calculate the state vector of the quantum program.
The session must be configured with a Classiq simulator
("classiq/simulator", "classiq/nvidia_simulator") or
"google/cuquantum". The corresponding statevector variant is
selected automatically; callers do not need to know about the
_statevector backend names.
Parameters:
Returns:
- Type:
DataFrame \| list[DataFrame] - A dataframe containing the state vector, or a list of dataframes when
parametersis a list.
submit_calculate_state_vector
submit_calculate_state_vector(
self: ,
parameters: ExecutionParams | list[ExecutionParams] | None = None,
filters: dict[str, Any] | None = None,
amplitude_threshold: float = 0.0
) -> ExecutionJob
Initiates an execution job with the calculate_state_vector primitive.
This is a non-blocking version of :meth:calculate_state_vector: it gets
the same parameters and initiates the same execution job, but instead of
waiting for the result, it returns the job object immediately.
Parameters:
Returns:
- Type:
ExecutionJob - The execution job.
batch_sample
batch_sample(
self: ,
parameters: list[ExecutionParams]
) -> list[ExecutionDetails]
Samples the quantum program multiple times with the given parameters for each iteration. The number of samples is determined by the length of the parameters list.
.. deprecated::
Pass a list of parameter dicts to :meth:sample instead.
Parameters:
Returns:
- Type:
list[ExecutionDetails] - List[ExecutionDetails]: The results of all the sampling iterations.
submit_batch_sample
submit_batch_sample(
self: ,
parameters: list[ExecutionParams]
) -> ExecutionJob
Initiates an execution job with the batch_sample primitive.
.. deprecated::
Pass a list of parameter dicts to :meth:submit_sample instead.
Parameters:
Returns:
- Type:
ExecutionJob - The execution job.
observe
observe(
self: ,
hamiltonian: Hamiltonian,
parameters: ExecutionParams | list[ExecutionParams] | None = None,
num_shots: int | None = None,
run_via_classiq: bool | None = None
) -> EstimationResult | list[EstimationResult]
Estimates the expectation value of the given Hamiltonian using the quantum program.
Parameters:
Returns:
- Type:
EstimationResult \| list[EstimationResult] - The estimation result, or a list of results when
parameters - is a list.
submit_observe
submit_observe(
self: ,
hamiltonian: Hamiltonian,
parameters: ExecutionParams | list[ExecutionParams] | None = None,
num_shots: int | None = None,
run_via_classiq: bool | None = None,
_check_deprecation: bool = True
) -> ExecutionJob
Initiates an execution job with the observe primitive.
This is a non-blocking version of :meth:observe: it gets the same
parameters and initiates the same execution job, but instead of waiting
for the result, it returns the job object immediately.
Parameters:
Returns:
- Type:
ExecutionJob - The execution job.
estimate
estimate(
self: ,
hamiltonian: Hamiltonian,
parameters: ExecutionParams | list[ExecutionParams] | None = None,
num_shots: int | None = None,
run_via_classiq: bool | None = None
) -> EstimationResult | list[EstimationResult]
Estimates the expectation value of the given Hamiltonian using the quantum program.
.. deprecated::
estimate is deprecated and will no longer be supported starting
on 2026-06-22. Use :meth:observe instead.
Parameters:
submit_estimate
submit_estimate(
self: ,
hamiltonian: Hamiltonian,
parameters: ExecutionParams | list[ExecutionParams] | None = None,
num_shots: int | None = None,
run_via_classiq: bool | None = None,
_check_deprecation: bool = True
) -> ExecutionJob
Initiates an execution job with the estimate primitive.
.. deprecated::
submit_estimate is deprecated and will no longer be supported
starting on 2026-06-22. Use :meth:submit_observe instead.
Parameters:
batch_estimate
batch_estimate(
self: ,
hamiltonian: Hamiltonian,
parameters: list[ExecutionParams]
) -> list[EstimationResult]
Estimates the expectation value of the given Hamiltonian multiple times using the quantum program, with the given parameters for each iteration. The number of estimations is determined by the length of the parameters list.
.. deprecated::
Pass a list of parameter dicts to :meth:observe instead.
Parameters:
Returns:
- Type:
list[EstimationResult] - List[EstimationResult]: The results of all the estimation iterations.
submit_batch_estimate
submit_batch_estimate(
self: ,
hamiltonian: Hamiltonian,
parameters: list[ExecutionParams],
_check_deprecation: bool = True
) -> ExecutionJob
Initiates an execution job with the batch_estimate primitive.
.. deprecated::
Pass a list of parameter dicts to :meth:submit_observe instead.
Parameters:
Returns:
- Type:
ExecutionJob - The execution job.
variational_minimize
variational_minimize(
self: ,
cost_function: Hamiltonian | QmodExpressionCreator,
initial_params: ExecutionParams,
max_iteration: int,
quantile: float = 1.0,
tolerance: float | None = None,
hosted: bool = False,
num_shots: int | None = None,
run_via_classiq: bool | None = None
) -> list[tuple[float, ExecutionParams]]
Variationally minimizes the given cost function using the quantum program.
Parameters:
Returns:
- Type:
list[tuple[float, ExecutionParams]] - A list of tuples, each containing the estimated cost and the corresponding parameters for that iteration.
costis a float, andparametersis a dictionary matching the execution parameter format.
minimize
minimize(
self: ,
cost_function: Hamiltonian | QmodExpressionCreator,
initial_params: ExecutionParams,
max_iteration: int,
quantile: float = 1.0,
tolerance: float | None = None,
num_shots: int | None = None,
run_via_classiq: bool | None = None
) -> list[tuple[float, ExecutionParams]]
.. deprecated::
Use :meth:variational_minimize instead.
This name is kept for backward compatibility and will be removed in a future release.
Parameters:
submit_variational_minimize
submit_variational_minimize(
self: ,
cost_function: Hamiltonian | QmodExpressionCreator,
initial_params: ExecutionParams,
max_iteration: int,
quantile: float = 1.0,
tolerance: float | None = None,
hosted: bool = False,
num_shots: int | None = None,
run_via_classiq: bool | None = None,
_check_deprecation: bool = True
) -> ExecutionJob
Initiates an execution job with the variational minimization primitive.
Non-blocking counterpart of :meth:variational_minimize: same parameters and job,
but returns the :class:~classiq.execution.jobs.ExecutionJob immediately.
Parameters:
Returns:
- Type:
ExecutionJob - The execution job. When
hosted=Trueon an IonQ backend, the backend - worker submits and polls IonQ Hosted Hybrid while this job tracks
- progress through the standard Classiq execution API.
submit_minimize
submit_minimize(
self: ,
cost_function: Hamiltonian | QmodExpressionCreator,
initial_params: ExecutionParams,
max_iteration: int,
quantile: float = 1.0,
tolerance: float | None = None,
num_shots: int | None = None,
run_via_classiq: bool | None = None,
_check_deprecation: bool = True
) -> ExecutionJob
.. deprecated::
Use :meth:submit_variational_minimize instead.
This name is kept for backward compatibility and will be removed in a future release.
Parameters:
estimate_cost
estimate_cost(
self: ,
cost_func: Callable[[ParsedState], float],
parameters: ExecutionParams | None = None,
quantile: float = 1.0,
num_shots: int | None = None,
run_via_classiq: bool | None = None
) -> float
Estimates circuit cost using a classical cost function.
Parameters:
Returns:
- Type:
float - cost estimation
set_measured_state_filter
set_measured_state_filter(
self: ,
output_name: str,
condition: Callable
) -> None
When simulating on a statevector simulator, emulate the behavior of postprocessing
by discarding amplitudes for which their states are “undesirable”.
Parameters:
QBit
A type representing a single qubit.QBit serves both as a placeholder for a temporary, non-allocated qubit
and as the type of an allocated physical or logical qubit.
Conceptually, a qubit is a two-level quantum system, described by the
superposition of the computational basis states:
Therefore, a qubit state is a linear combination:
where ( \alpha ) and ( \beta ) are complex numbers satisfying:
Typical usage includes:
- Representing an unallocated qubit before its allocation.
- Acting as the output type for a qubit or an allocated qubit in the main function after calling an allocation function.
Z
Z(
target: Const[QBit]
) -> None
[Qmod core-library function]
Performs the Pauli-Z gate on a qubit.
This operation is represented by the following matrix:
Parameters:
allocate
allocate(
args: Any = (),
kwargs: Any =
) -> None
Initialize a quantum variable to a new quantum object in the zero state:
\left|\text{out}\right\rangle = \left|0\right\rangle^{\otimes \text{num_qubits}}
If ‘num_qubits’ is not specified, it will be inferred according to the type of ‘out’.
In case the quantum variable is of type QNum, its numeric attributes can be specified as
well.
Parameters:
bind
bind(
source: Input[QVar] | list[Input[QVar]],
destination: Output[QVar] | list[Output[QVar]]
) -> None
Reassign qubit or arrays of qubits by redirecting their logical identifiers.
This operation rewires the logical identity of the source qubits to new objects given in destination.
For example, an array of two qubits X can be mapped to individual qubits Y and Z.
Parameters:
within_apply
within_apply(
within: Callable[[], Statements],
apply: Callable[[], Statements]
) -> None
Given two operations and , performs the composition of operations .
This operation is used to represent a sequence where the operation U is applied, followed by another operation V, and then U^{-1} is applied to uncompute. This pattern is common in reversible
computation and quantum subroutines.
Parameters:
drop
drop(
in_: Input[QArray[QBit]]
) -> None
[Qmod core-library function]
Discards the qubits allocated to a quantum variable which may be in any state,
preventing their further use.
Parameters:
create_model
create_model(
entry_point: QFunc | GenerativeQFunc,
constraints: Constraints | None = None,
execution_preferences: ExecutionPreferences | None = None,
preferences: Preferences | None = None,
classical_execution_function: CFunc | None = None,
out_file: str | None = None
) -> SerializedModel
Create a serialized model from a given Qmod entry function and additional parameters.
Parameters:
Returns:
- Type:
SerializedModel - A serialized model.
synthesize
synthesize(
model: SerializedModel | BaseQFunc,
auto_show: bool = False,
constraints: Constraints | None = None,
preferences: Preferences | None = None
) -> QuantumProgram
Synthesize a model with the Classiq engine to receive a quantum program.
More details
Parameters:
Returns:
- Type:
QuantumProgram - Quantum program. (See: QuantumProgram)
IQAE
Implementation of Iterative Quantum Amplitude Estimation [1]. Given s.t. , the algorithm estimates by iteratively sampling , where , and is an integer variable. For estimating , The algorithm estimates which is defined by , so it starts with a confidence interval and narrows down this interval on each iteration according to the sample results. Methods:get_model
get_model(
self:
) -> SerializedModel
Implement the quantum part of IQAE in terms of the Qmod Model
Parameters:
Returns:
- Type:
SerializedModel - A serialized model.
get_qprog
get_qprog(
self:
) -> QuantumProgram
Create an executable quantum Program for IQAE.
Parameters:
Returns:
- Type:
QuantumProgram - Quantum program. See QuantumProgram.
run
run(
self: ,
epsilon: float,
alpha: float,
execution_preferences: ExecutionPreferences | None = None
) -> IQAEResult
Executes IQAE’s quantum program with the provided epsilon, alpha, and execution
preferences.
If execution_preferences has been proved, or if it does not contain num_shot, then num_shot is set to 2048.
Parameters:
IQAEIterationData
Handles the data storage for a single iteration of the Iterative Quantum Amplitude Estimation algorithm. This class is intended to represent the results and state of a single Grover iteration of the IQAE process. Attributes:grover_iterations
grover_iterations: int
sample_results
sample_results: ExecutionDetails
IQAEResult
Represents the result of an Iterative Quantum Amplitude Estimation (IQAE) process. This class encapsulates the output of the IQAE algorithm, including the estimated value, confidence interval, intermediate iteration data, and any warnings generated during the computation. Attributes:estimation
estimation: float
confidence_interval
confidence_interval: list[float] = Field(min_length=2, max_length=2)
iterations_data
iterations_data: list[IQAEIterationData]
warnings
warnings: list[str]