qdk_chemistry.algorithms package

A package for algorithms in the quantum applications toolkit.

This module is primarily intended for developers who want to implement custom algorithms that can be registered and used within the QDK/Chemistry framework.

class qdk_chemistry.algorithms.ActiveSpaceSelector

Bases: pybind11_object

Abstract base class for active space selector algorithms.

This class defines the interface for selecting active spaces from a set of orbitals. Active space selection is a critical step in many quantum chemistry methods, particularly for multireference calculations. Concrete implementations should inherit from this class and implement the select_active_space method.

Return value semantics

Implementations return a new Wavefunction object with active-space data populated. Some selectors (e.g., occupation/valence) return a copy with only metadata updated. Others (e.g., AVAS) may rotate/canonicalize orbitals and recompute occupations, so the returned coefficients/occupations can differ from the input. The input Wavefunction object is never modified.

Examples

To create a custom active space selector, inherit from this class.:

>>> import qdk_chemistry.algorithms as alg
>>> import qdk_chemistry.data as data
>>> class MyActiveSpaceSelector(alg.ActiveSpaceSelector):
...     def __init__(self):
...         super().__init__()  # Call the base class constructor
...     # Implement the _run_impl method (called by run())
...     def _run_impl(self, wavefunction: data.Wavefunction) -> data.Wavefunction:
...         # Custom active space selection implementation that returns orbitals with active space populated.
...         # For selectors that only annotate, return a copied object with metadata set; for others,
...         # you may also rotate/transform the coefficients as needed.
...         act_orbitals = data.Orbitals(wavefunction.get_orbitals()) # Copy base data by default
...         act_orbitals.set_active_space_indices([0, 1, 2, 3])
...         act_orbitals.set_num_active_electrons(2)
...         ... # Additional logic to modify orbitals if needed
...         act_wavefunction = data.Wavefunction(...)
...         return act_wavefunction # Return modified wavefunction object
__init__(self: qdk_chemistry.algorithms.ActiveSpaceSelector) None

Create an ActiveSpaceSelector instance.

Default constructor for the abstract base class. This should typically be called from derived class constructors.

Examples

>>> # In a derived class:
>>> class MySelector(alg.ActiveSpaceSelector):
...     def __init__(self):
...         super().__init__()  # Calls parent constructor
name(self: qdk_chemistry.algorithms.ActiveSpaceSelector) str

The algorithm’s name.

Returns:

The name of the algorithm

Return type:

str

run(self: qdk_chemistry.algorithms.ActiveSpaceSelector, wavefunction: qdk_chemistry.data.Wavefunction) qdk_chemistry.data.Wavefunction

Select active space orbitals from the given wavefunction.

This method automatically locks settings before execution to prevent modifications during selection.

Parameters:

wavefunction (qdk_chemistry.data.Wavefunction) – The wavefunction from which to select the active space

Returns:

Wavefunction with active space data populated

Return type:

qdk_chemistry.data.Wavefunction

Raises:

SettingsAreLocked – If attempting to modify settings after run() is called

settings(self: qdk_chemistry.algorithms.ActiveSpaceSelector) qdk_chemistry.data.Settings

Access the selector’s configuration settings.

Returns:

Reference to the settings object for configuring the active space selector

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.ActiveSpaceSelector) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.ControlledEvolutionCircuitMapper

Bases: Algorithm

Base class for controlled time evolution circuit mapper in QDK/Chemistry algorithms.

__init__()

Initialize the ControlledEvolutionCircuitMapper.

class qdk_chemistry.algorithms.DynamicalCorrelationCalculator

Bases: pybind11_object

Abstract base class for reference-derived quantum chemistry methods.

This class provides a unified interface for quantum chemistry methods that derive corrections from a reference wavefunction, such as Møller-Plesset perturbation theory (MP2) and Coupled Cluster (CC) methods.

The calculator takes an Ansatz (containing both Hamiltonian and reference wavefunction) as input and returns both the total energy and an updated wavefunction that may contain correlation information.

Examples

>>> import qdk
>>> # Create ansatz from hamiltonian and wavefunction
>>> ansatz = qdk_chemistry.data.Ansatz(hamiltonian, wavefunction)
>>>
>>> # Create calculator (e.g., MP2) using the registry
>>> calculator = qdk_chemistry.algorithms.create("dynamical_correlation_calculator", "qdk_mp2_calculator")
>>>
>>> # Run calculation
>>> total_energy, result_wavefunction = calculator.run(ansatz)
__init__(self: qdk_chemistry.algorithms.DynamicalCorrelationCalculator) None

Create a DynamicalCorrelationCalculator instance.

Initializes a new reference-derived calculator with default settings. Configuration options can be modified through the settings() method.

Examples

>>> calc = alg.DynamicalCorrelationCalculator()
>>> calc.settings().set("max_iterations", 100)
>>> calc.settings().set("convergence_threshold", 1e-8)
name(self: qdk_chemistry.algorithms.DynamicalCorrelationCalculator) str

Get the algorithm name

run(self: qdk_chemistry.algorithms.DynamicalCorrelationCalculator, ansatz: qdk_chemistry.data.Ansatz) tuple[float, qdk_chemistry.data.Wavefunction]

Perform reference-derived calculation.

Parameters:

ansatz (Ansatz) – The Ansatz (Wavefunction and Hamiltonian) describing the quantum system

Returns:

A tuple containing the total energy and the resulting wavefunction

Return type:

tuple[float, Wavefunction]

settings(self: qdk_chemistry.algorithms.DynamicalCorrelationCalculator) qdk_chemistry.data.Settings

Access the calculator’s configuration settings.

Returns:

Reference to the settings object for configuring the calculator

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.DynamicalCorrelationCalculator) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.EnergyEstimator

Bases: Algorithm

Abstract base class for energy estimator algorithms.

__init__()

Initialize the EnergyEstimator.

type_name()

Return energy_estimator as the algorithm type name.

Return type:

str

run(circuit, qubit_hamiltonians, total_shots, noise_model=None, classical_coeffs=None)

Estimate the expectation value and variance of Hamiltonians.

Return type:

EnergyExpectationResult

Parameters:
  • circuit (Circuit) – Circuit that provides an OpenQASM3 string of the quantum circuit to be evaluated.

  • qubit_hamiltonians (list[QubitHamiltonian]) – List of QubitHamiltonian to estimate.

  • total_shots (int) – Total number of shots to allocate across the observable terms.

  • noise_model (Any | None) – Optional noise model to simulate noise in the quantum circuit.

  • classical_coeffs (list | None) – Optional list of coefficients for classical Pauli terms to calculate energy offset.

Returns:

EnergyExpectationResult containing the energy expectation value and variance.

Note

  • Measurement circuits are generated for each QubitHamiltonian term.

  • Parameterized circuits are not supported.

  • Only one circuit is supported per run.

class qdk_chemistry.algorithms.HamiltonianConstructor

Bases: pybind11_object

Abstract base class for Hamiltonian constructors.

This class defines the interface for constructing Hamiltonian matrices from orbital data. Concrete implementations should inherit from this class and implement the construct method.

Examples

To create a custom Hamiltonian constructor, inherit from this class:

>>> import qdk_chemistry.algorithms as alg
>>> import qdk_chemistry.data as data
>>> class MyHamiltonianConstructor(alg.HamiltonianConstructor):
...     def __init__(self):
...         super().__init__()  # Call the base class constructor
...     # Implement the _run_impl method
...     def _run_impl(self, orbitals: data.Orbitals) -> data.Hamiltonian:
...         # Custom Hamiltonian construction implementation
...         return hamiltonian
__init__(self: qdk_chemistry.algorithms.HamiltonianConstructor) None

Create a HamiltonianConstructor instance.

Default constructor for the abstract base class. This should typically be called from derived class constructors.

Examples

>>> # In a derived class:
>>> class MyConstructor(alg.HamiltonianConstructor):
...     def __init__(self):
...         super().__init__()  # Calls this constructor
name(self: qdk_chemistry.algorithms.HamiltonianConstructor) str

The algorithm’s name.

Returns:

The name of the algorithm

Return type:

str

run(self: qdk_chemistry.algorithms.HamiltonianConstructor, orbitals: qdk_chemistry.data.Orbitals) qdk_chemistry.data.Hamiltonian

Construct a Hamiltonian from the given orbitals.

This method automatically locks settings before execution to prevent modifications during construction.

Parameters:

orbitals (qdk_chemistry.data.Orbitals) – The orbital data to construct the Hamiltonian from

Returns:

The constructed Hamiltonian matrix

Return type:

qdk_chemistry.data.Hamiltonian

Raises:

SettingsAreLocked – If attempting to modify settings after run() is called

settings(self: qdk_chemistry.algorithms.HamiltonianConstructor) qdk_chemistry.data.Settings

Access the constructor’s configuration settings.

Returns:

Reference to the settings object for configuring the constructor

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.HamiltonianConstructor) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.IterativePhaseEstimation(hamiltonian, evolution_time)

Bases: PhaseEstimation

Most-significant-bit-first iterative phase estimation (Kitaev style [Kit95]).

Parameters:
algorithm: PhaseEstimationAlgorithm | None = 'iterative'
__init__(hamiltonian, evolution_time)

Configure iterative QPE for hamiltonian evolved for evolution_time.

Parameters:
  • hamiltonian (QubitHamiltonian) – The target Hamiltonian whose eigenvalues will be estimated.

  • evolution_time (float) – Time parameter t used in the time-evolution unitary U = exp(-i H t).

create_iteration_circuit(state_prep, *, iteration, total_iterations, phase_correction=0.0, measurement_register=None, iteration_name=None, circuit_folding=True)

Construct a single IQPE iteration circuit.

Return type:

QuantumCircuit

Parameters:
  • state_prep (QuantumCircuit) – Trial-state preparation circuit that prepares the initial quantum state on the system qubits.

  • iteration (int) –

    Current iteration index (0-based), where 0 corresponds to the

    most-significant bit.

  • total_iterations (int) – Total number of phase bits to measure across all iterations.

  • phase_correction (float) –

    Feedback phase angle to apply before controlled evolution.

    Defaults to 0.0 for the first iteration.

  • measurement_register (ClassicalRegister | None) –

    Optional classical register for storing the measurement

    result. If None, a new register named c{iteration} is created.

  • iteration_name (str | None) –

    Optional custom name for the circuit. If None, no specific

    name is assigned.

  • circuit_folding (bool) – Whether to apply circuit folding for visualization. Defaults to True.

Returns:

A quantum circuit implementing one IQPE iteration with an ancilla qubit, system qubits, and classical measurement register.

create_iteration(state_prep, *, iteration, total_iterations, phase_correction=0.0, measurement_register=None, iteration_name=None, circuit_folding=True)

Build an iteration and return contextual metadata.

Return type:

IterativePhaseEstimationIteration

Parameters:
  • state_prep (QuantumCircuit) –

    Trial-state preparation circuit that prepares the initial

    quantum state on the system qubits.

  • iteration (int) – Current iteration index (0-based), where 0 corresponds to the most-significant bit.

  • total_iterations (int) – Total number of phase bits to measure across all iterations.

  • phase_correction (float) –

    Feedback phase angle to apply before controlled evolution.

    Defaults to 0.0 for the first iteration.

  • measurement_register (ClassicalRegister | None) –

    Optional classical register for storing the measurement result.

    If None, a new register named c{iteration} is created.

  • iteration_name (str | None) – Optional custom name for the circuit. If None, no specific name is assigned.

  • circuit_folding (bool) – Whether to apply circuit folding for visualization. Defaults to True.

Returns:

An IterativePhaseEstimationIteration object containing the circuit and metadata including iteration number, total iterations, power of evolution, and phase correction.

create_iterations(state_prep, *, num_bits, phase_corrections=None, measurement_registers=None, iteration_names=None, circuit_folding=True)

Generate num_bits iteration circuits with optional phase feedback.

Return type:

list[IterativePhaseEstimationIteration]

Parameters:
  • state_prep (QuantumCircuit) – Trial-state preparation circuit that prepares the initial quantum state on the system qubits.

  • num_bits (int) – Total number of IQPE iterations to generate. Must be a positive integer.

  • phase_corrections (Sequence[float] | None) –

    Optional list of feedback phases Φ(k+1) to apply before each iteration.

    Must have length equal to num_bits if provided. Defaults to zeros if not specified.

  • measurement_registers (Sequence[ClassicalRegister] | None) –

    Optional collection of classical registers, one per iteration.

    Must have length equal to num_bits if provided.

  • iteration_names (Sequence[str | None] | None) –

    Optional custom names for the per-iteration circuits.

    Must have length equal to num_bits if provided.

  • circuit_folding (bool) – Whether to apply circuit folding for visualization. Defaults to True.

Returns:

A list of IterativePhaseEstimationIteration objects, one for each iteration, containing circuits and metadata.

Raises:

ValueError – If num_bits is not positive, or if the length of phase_corrections, measurement_registers, or iteration_names does not match num_bits.

static update_phase_feedback(current_phase, measured_bit)

Update the feedback angle after measuring an iteration.

Return type:

float

Parameters:
  • current_phase (float) – The accumulated phase feedback from previous iterations.

  • measured_bit (int) – The measurement result (0 or 1) from the current iteration.

Returns:

The updated phase feedback to be used in the next iteration.

static phase_fraction_from_feedback(phase_feedback)

Compute the phase fraction φ from the final feedback phase.

Return type:

float

Parameters:

phase_feedback (float) – The accumulated phase feedback after all iterations.

Returns:

The phase fraction φ in the range [0, 1), representing the fractional part of the eigenphase.

static phase_feedback_from_bits(bits_msb_first)

Convenience helper that wraps accumulated_phase_from_bits().

Return type:

float

Parameters:

bits_msb_first (Sequence[int]) – Sequence of measured bits ordered from most-significant to least-significant.

Returns:

The accumulated phase feedback computed from the bit sequence.

class qdk_chemistry.algorithms.IterativePhaseEstimationIteration(circuit, iteration, total_iterations, power, phase_correction)

Bases: object

Container describing a single iteration circuit.

Parameters:
circuit: QuantumCircuit
iteration: int
total_iterations: int
power: int
phase_correction: float
__init__(circuit, iteration, total_iterations, power, phase_correction)
Parameters:
Return type:

None

class qdk_chemistry.algorithms.MultiConfigurationCalculator

Bases: pybind11_object

Abstract base class for multi-configuration calculators.

This class defines the interface for multi configuration-based quantum chemistry calculations. Concrete implementations should inherit from this class and implement the calculate method.

Examples

>>> # To create a custom multi-configuration calculator, inherit from this class.
>>> import qdk_chemistry.algorithms as alg
>>> import qdk_chemistry.data as data
>>> class MyMultiConfigurationCalculator(alg.MultiConfigurationCalculator):
...     def __init__(self):
...         super().__init__()  # Call the base class constructor
...     # Implement the _run_impl method (called by run())
...     def _run_impl(self, hamiltonian: data.Hamiltonian, n_active_alpha_electrons: int, n_active_beta_electrons: int) -> tuple[float, data.Wavefunction]:
...         # Custom MC implementation
...         return energy, wavefunction
__init__(self: qdk_chemistry.algorithms.MultiConfigurationCalculator) None

Create a MultiConfigurationCalculator instance.

Default constructor for the abstract base class. This should typically be called from derived class constructors.

Examples

>>> # In a derived class:
>>> class MyCalculator(alg.MultiConfigurationCalculator):
...     def __init__(self):
...         super().__init__()  # Calls this constructor
name(self: qdk_chemistry.algorithms.MultiConfigurationCalculator) str

The algorithm’s name.

Returns:

The name of the algorithm

Return type:

str

run(self: qdk_chemistry.algorithms.MultiConfigurationCalculator, hamiltonian: qdk_chemistry.data.Hamiltonian, n_active_alpha_electrons: SupportsInt, n_active_beta_electrons: SupportsInt) tuple[float, qdk_chemistry.data.Wavefunction]

Perform multi-configuration calculation on the given Hamiltonian.

Parameters:
  • hamiltonian (qdk_chemistry.data.Hamiltonian) – The Hamiltonian to perform the calculation on

  • n_active_alpha_electrons (int) – The number of alpha electrons in the active space

  • n_active_beta_electrons (int) – The number of beta electrons in the active space

Returns:

A tuple containing the computed total energy (active + core) and wavefunction

Return type:

tuple[float, qdk_chemistry.data.Wavefunction]

Raises:

SettingsAreLocked – If attempting to modify settings after run() is called

settings(self: qdk_chemistry.algorithms.MultiConfigurationCalculator) qdk_chemistry.data.Settings

Access the calculator’s configuration settings.

Returns:

Reference to the settings object for configuring the calculator

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.MultiConfigurationCalculator) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.MultiConfigurationScf

Bases: pybind11_object

Abstract base class for multi-configurational Self-Consistent Field (MultiConfigurationScf) algorithms.

This class defines the interface for MultiConfigurationScf calculations that simultaneously optimize both molecular orbital coefficients and configuration interaction coefficients. Concrete implementations should inherit from this class and implement the solve method.

Examples

>>> # To create a custom MultiConfigurationScf algorithm, inherit from this class.
>>> import qdk_chemistry.algorithms as alg
>>> import qdk_chemistry.data as data
>>> class MyMCSCF(alg.MultiConfigurationScf):
...     def __init__(self):
...         super().__init__()  # Call the base class constructor
...     def _run_impl(self,
...                   orbitals : data.Orbitals,
...                   ham_ctor : alg.HamiltonianConstructor,
...                   mc_calculator : alg.MultiConfigurationCalculator,
...                   n_active_alpha_electrons : int,
...                   n_active_beta_electrons : int) ->tuple[float, data.Wavefunction] :
...         # Custom MCSCF implementation
...         return -1.0, data.Wavefunction()
__init__(self: qdk_chemistry.algorithms.MultiConfigurationScf) None

Create a MultiConfigurationScf instance.

Default constructor for the abstract base class. This should typically be called from derived class constructors.

Examples

>>> # In a derived class:
>>> class MyMCSCF(alg.MultiConfigurationScf):
...     def __init__(self):
...         super().__init__()  # Calls this constructor
name(self: qdk_chemistry.algorithms.MultiConfigurationScf) str

The algorithm’s name.

Returns:

The name of the algorithm

Return type:

str

run(self: qdk_chemistry.algorithms.MultiConfigurationScf, orbitals: qdk_chemistry.data.Orbitals, ham_ctor: qdk::chemistry::algorithms::HamiltonianConstructor, mc_calculator: qdk_chemistry.algorithms.MultiConfigurationCalculator, n_active_alpha_electrons: SupportsInt, n_active_beta_electrons: SupportsInt) tuple[float, qdk_chemistry.data.Wavefunction]

Perform a MultiConfigurationScf calculation.

This method automatically locks settings before execution.

Parameters:
Returns:

A tuple containing the calculated energy and the resulting wavefunction

Return type:

tuple[float, qdk_chemistry.data.Wavefunction]

settings(self: qdk_chemistry.algorithms.MultiConfigurationScf) qdk_chemistry.data.Settings

Access the MultiConfigurationScf calculation settings.

Returns:

Reference to the settings object for configuring the MultiConfigurationScf calculation

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.MultiConfigurationScf) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.OrbitalLocalizer

Bases: pybind11_object

Abstract base class for orbital localizers.

This class defines the interface for localizing molecular orbitals. Localization transforms canonical molecular orbitals into localized orbitals that are spatially confined to specific regions or bonds. Concrete implementations should inherit from this class and implement the localize method.

Examples

>>> # To create a custom orbital localizer, inherit from this class.
>>> import qdk_chemistry.algorithms as alg
>>> import qdk_chemistry.data as data
>>> class MyLocalizer(alg.Localizer):
...     def __init__(self):
...         super().__init__()  # Call the base class constructor
...     # Implement the _run_impl method
...     def _run_impl(self, wavefunction: data.Wavefunction, loc_indices_a: list, loc_indices_b: list) -> data.Wavefunction:
...         # Custom localization implementation
...         return localized_wavefunction
__init__(self: qdk_chemistry.algorithms.OrbitalLocalizer) None

Create a Localizer instance.

Default constructor for the abstract base class. This should typically be called from derived class constructors.

Examples

>>> # In a derived class:
>>> class MyLocalizer(alg.Localizer):
...     def __init__(self):
...         super().__init__()  # Calls this constructor
name(self: qdk_chemistry.algorithms.OrbitalLocalizer) str

The algorithm’s name.

Returns:

The name of the algorithm

Return type:

str

run(self: qdk_chemistry.algorithms.OrbitalLocalizer, wavefunction: qdk_chemistry.data.Wavefunction, loc_indices_a: collections.abc.Sequence[SupportsInt], loc_indices_b: collections.abc.Sequence[SupportsInt]) qdk_chemistry.data.Wavefunction

Localize molecular orbitals in the given wavefunction.

Parameters:
  • wavefunction (qdk_chemistry.data.Wavefunction) – The canonical molecular wavefunction to localize

  • loc_indices_a (list[int]) – Indices of alpha orbitals to localize (empty for no localization)

  • loc_indices_b (list[int]) – Indices of beta orbitals to localize (empty for no localization)

Notes

For restricted orbitals, loc_indices_b must match loc_indices_a.

Returns:

The localized molecular wavefunction

Return type:

qdk_chemistry.data.Wavefunction

Raises:
  • ValueError – If orbital indices are invalid or inconsistent

  • RuntimeError – If localization fails due to numerical issues

settings(self: qdk_chemistry.algorithms.OrbitalLocalizer) qdk_chemistry.data.Settings

Access the localizer’s configuration settings.

Returns:

Reference to the settings object for configuring the localizer

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.OrbitalLocalizer) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.PhaseEstimation(hamiltonian, evolution_time)

Bases: ABC

Abstract interface for phase estimation strategies.

Parameters:
algorithm: PhaseEstimationAlgorithm | None = None
__init__(hamiltonian, evolution_time)

Store common data for phase estimation routines.

Parameters:
  • hamiltonian (QubitHamiltonian) – Target Hamiltonian whose eigenvalues are estimated.

  • evolution_time (float) – Time parameter t used in the time-evolution unitary U = exp(-i H t).

property hamiltonian: QubitHamiltonian

Return the Hamiltonian used by the algorithm.

property evolution_time: float

Return the evolution time used for U = exp(-i H t).

classmethod from_algorithm(algorithm, *, hamiltonian, evolution_time, **kwargs)

Factory method returning the requested phase estimation strategy.

Return type:

TypeVar(AlgorithmT, bound= PhaseEstimation)

Parameters:
Raises:

ValueError – If the requested algorithm is not registered.

class qdk_chemistry.algorithms.PhaseEstimationAlgorithm(*values)

Bases: StrEnum

Enumeration of supported phase estimation routines.

References

  • Iterative QPE: Kitaev, A. (1995). arXiv:quant-ph/9511026. [Kit95]

  • Traditional QPE: Nielsen, M. A., & Chuang, I. L. (2010). [NC10]

ITERATIVE = 'iterative'
TRADITIONAL = 'traditional'
class qdk_chemistry.algorithms.ProjectedMultiConfigurationCalculator

Bases: pybind11_object

Abstract base class for projected multi-configurational (PMC) calculations in quantum chemistry.

This class provides the interface for projected multi-configurational-based quantum chemistry calculations. This contrasts the MultiConfigurationCalculator in that the space of determinants upon which the Hamiltonian is projected is taken to be a free parameter and must be specified. In this manner, the high-performance solvers which underly other MC algorithms can be interfaced with external methods for selecting important determinants.

The calculator takes a Hamiltonian and a set of configurations as input and returns both the calculated total energy and the corresponding multi-configurational wavefunction.

To create a custom PMC calculator, inherit from this class.

Examples

>>> import qdk_chemistry.algorithms as alg
>>> import qdk_chemistry.data as data
>>> class MyProjectedMultiConfigurationCalculator(alg.ProjectedMultiConfigurationCalculator):
...     def __init__(self):
...         super().__init__()  # Call the base class constructor
...     def _run_impl(self, hamiltonian: data.Hamiltonian, configurations: list[data.Configuration]) -> tuple[float, data.Wavefunction]:
...         # Custom PMC implementation
...         return energy, wavefunction
__init__(self: qdk_chemistry.algorithms.ProjectedMultiConfigurationCalculator) None

Create a ProjectedMultiConfigurationCalculator instance.

Default constructor for the abstract base class. This should typically be called from derived class constructors.

Examples

>>> # In a derived class:
>>> class MyPMC(alg.ProjectedMultiConfigurationCalculator):
...     def __init__(self):
...         super().__init__()  # Calls this constructor
name(self: qdk_chemistry.algorithms.ProjectedMultiConfigurationCalculator) str

The algorithm’s name.

Returns:

The name of the algorithm

Return type:

str

run(self: qdk_chemistry.algorithms.ProjectedMultiConfigurationCalculator, hamiltonian: qdk_chemistry.data.Hamiltonian, configurations: collections.abc.Sequence[qdk_chemistry.data.Configuration]) tuple[float, qdk_chemistry.data.Wavefunction]

Perform projected multi-configurational calculation.

This method automatically locks settings before execution.

This method takes a Hamiltonian describing the quantum system and a set of configurations/determinants to project the Hamiltonian onto, and returns both the calculated energy and the optimized multi-configurational wavefunction.

Parameters:
Returns:

A tuple containing the calculated total energy (active + core) and the resulting multi-configurational wavefunction

Return type:

tuple[float, qdk_chemistry.data.Wavefunction]

Raises:
settings(self: qdk_chemistry.algorithms.ProjectedMultiConfigurationCalculator) qdk_chemistry.data.Settings

Access the calculator’s configuration settings.

Returns:

Reference to the settings object for configuring the calculator

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.ProjectedMultiConfigurationCalculator) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.QdkAutocasActiveSpaceSelector

Bases: ActiveSpaceSelector

QDK Automated Complete Active Space (AutoCAS) selector.

This class provides an automated approach to selecting active space orbitals based on various criteria including occupation numbers, orbital energies, and other chemical information [SR19].

Typical usage:

import qdk_chemistry.algorithms as alg

# Create an AutoCAS selector
selector = alg.QdkAutocasActiveSpaceSelector()

# Select active space automatically
active_wfn = selector.run(wavefunction)
__init__(self: qdk_chemistry.algorithms.QdkAutocasActiveSpaceSelector) None

Default constructor.

Initializes an AutoCAS selector with default settings.

class qdk_chemistry.algorithms.QdkAutocasEosActiveSpaceSelector

Bases: ActiveSpaceSelector

QDK entropy-based active space selector.

This class selects active space orbitals based on orbital entropy measures. It identifies orbitals with high entropy, which indicates strong electron correlation and multi-reference character. This method is a variant of the AutoCAS method that uses entropy as the primary criterion for selecting active orbitals [SR19].

Typical usage:

import qdk_chemistry.algorithms as alg

# Create an entropy-based selector
selector = alg.QdkAutocasEosActiveSpaceSelector()

# Configure entropy threshold
selector.settings().set("entropy_threshold", 0.1)

# Select active space
active_wfn = selector.run(wavefunction)
__init__(self: qdk_chemistry.algorithms.QdkAutocasEosActiveSpaceSelector) None

Default constructor.

Initializes an entropy-based active space selector with default settings.

class qdk_chemistry.algorithms.QdkHamiltonianConstructor

Bases: HamiltonianConstructor

QDK implementation of the Hamiltonian constructor.

This class provides a concrete implementation of the Hamiltonian constructor using the internal backend. It constructs molecular Hamiltonian matrices from orbital data, computing the necessary one- and two-electron integrals.

Typical usage:

import qdk_chemistry.algorithms as alg
import qdk_chemistry.data as data

# Assuming you have orbitals from an SCF calculation
constructor = alg.QdkHamiltonianConstructor()

# Configure settings if needed
constructor.settings().set("eri_method", "direct")

# Construct Hamiltonian
hamiltonian = constructor.run(orbitals)
__init__(self: qdk_chemistry.algorithms.QdkHamiltonianConstructor) None

Default constructor.

Initializes a Hamiltonian constructor with default settings.

class qdk_chemistry.algorithms.QdkMP2NaturalOrbitalLocalizer

Bases: OrbitalLocalizer

QDK MP2 natural orbital transformer.

This class provides a concrete implementation that transforms canonical molecular orbitals into natural orbitals derived from second-order Møller-Plesset perturbation theory (MP2). Natural orbitals are eigenfunctions of the first-order reduced density matrix.

MP2 natural orbitals often provide a more compact representation of the electronic wavefunction, which can improve computational efficiency in correlation methods.

Note

Only supports restricted orbitals and closed-shell systems.

Typical usage:

import qdk_chemistry.algorithms as alg

# Create an MP2 natural orbital localizer
localizer = alg.QdkMP2NaturalOrbitalLocalizer()

# Transform to MP2 natural orbitals
no_wfn = localizer.run(wavefunction, loc_indices_a, loc_indices_b)
__init__(self: qdk_chemistry.algorithms.QdkMP2NaturalOrbitalLocalizer) None

Default constructor.

Initializes an MP2 natural orbital transformer with default settings.

class qdk_chemistry.algorithms.QdkMacisAsci

Bases: MultiConfigurationCalculator

QDK MACIS-based Adaptive Sampling Configuration Interaction (ASCI) calculator.

This class provides a concrete implementation of the multi-configuration calculator using the MACIS library for Adaptive Sampling Configuration Interaction (ASCI) calculations, which adaptively selects the most important configurations.

Typical usage:

import qdk_chemistry.algorithms as alg

# Create an ASCI calculator
asci = alg.QdkMacisAsci()

# Configure ASCI-specific settings
asci.settings().set("ntdets_max", 1000)
asci.settings().set("h_el_tol", 1e-6)

# Run calculation
energy, wavefunction = asci.run(hamiltonian, n_alpha, n_beta)
__init__(self: qdk_chemistry.algorithms.QdkMacisAsci) None

Default constructor.

Initializes a MACIS ASCI calculator with default settings.

class qdk_chemistry.algorithms.QdkMacisCas

Bases: MultiConfigurationCalculator

QDK MACIS-based Complete Active Space (CAS) calculator.

This class provides a concrete implementation of the multi-configuration calculator using the MACIS library for Complete Active Space Configuration Interaction (CASCI) calculations.

Typical usage:

import qdk_chemistry.algorithms as alg

# Create a CASCI calculator
casci = alg.QdkMacisCas()

# Configure settings if needed
casci.settings().set("max_iterations", 100)

# Run calculation
energy, wavefunction = casci.run(hamiltonian, n_alpha, n_beta)
__init__(self: qdk_chemistry.algorithms.QdkMacisCas) None

Default constructor.

Initializes a MACIS CAS calculator with default settings.

class qdk_chemistry.algorithms.QdkMacisPmc

Bases: ProjectedMultiConfigurationCalculator

QDK MACIS-based Projected Multi-Configuration (PMC) calculator.

This class provides a concrete implementation of the projected multi-configuration calculator using the MACIS library. It performs projections of the Hamiltonian onto a specified set of determinants to compute energies and wavefunctions for strongly correlated molecular systems.

The calculator inherits from ProjectedMultiConfigurationCalculator and uses MACIS library routines to perform the actual projected calculations where the determinant space is provided as input rather than generated adaptively.

Typical usage:

import qdk_chemistry.algorithms as alg
import qdk_chemistry.data as data

# Create a PMC calculator
pmc = alg.QdkMacisPmc()

# Configure PMC-specific settings
pmc.settings().set("davidson_res_tol", 1e-8)
pmc.settings().set("davidson_max_m", 200)

# Prepare configurations
configurations = [...]  # Your list of Configuration objects

# Run calculation
energy, wavefunction = pmc.run(hamiltonian, configurations)
__init__(self: qdk_chemistry.algorithms.QdkMacisPmc) None

Default constructor.

Initializes a MACIS PMC calculator with default settings.

class qdk_chemistry.algorithms.QdkOccupationActiveSpaceSelector

Bases: ActiveSpaceSelector

QDK occupation-based active space selector.

This class selects active space orbitals based on their occupation numbers. It identifies orbitals that have partial occupations (not close to 0 or 2 electrons), which typically indicates significant multi-reference character and strong electron correlation.

Typical usage:

import qdk_chemistry.algorithms as alg

# Create an occupation-based selector
selector = alg.QdkOccupationActiveSpaceSelector()

# Configure occupation threshold
selector.settings().set("occupation_threshold", 0.1)

# Select active space
active_wfn = selector.run(wavefunction)
__init__(self: qdk_chemistry.algorithms.QdkOccupationActiveSpaceSelector) None

Default constructor.

Initializes an occupation-based active space selector with default settings.

class qdk_chemistry.algorithms.QdkPipekMezeyLocalizer

Bases: OrbitalLocalizer

QDK Pipek-Mezey orbital localizer.

This class provides a concrete implementation of the orbital localizer using the Pipek-Mezey localization algorithm. The Pipek-Mezey algorithm maximizes the sum of squares of atomic orbital populations on atoms, resulting in orbitals that are more localized to individual atoms or bonds.

This implementation separately localizes occupied and virtual orbitals to maintain the occupied-virtual separation.

Typical usage:

import qdk_chemistry.algorithms as alg

# Create a Pipek-Mezey localizer
localizer = alg.QdkPipekMezeyLocalizer()

# Configure settings if needed
localizer.settings().set("max_iterations", 100)
localizer.settings().set("convergence_tolerance", 1e-8)

# Localize orbitals
localized_wfn = localizer.run(wavefunction, loc_indices_a, loc_indices_b)
__init__(self: qdk_chemistry.algorithms.QdkPipekMezeyLocalizer) None

Default constructor.

Initializes a Pipek-Mezey localizer with default settings.

class qdk_chemistry.algorithms.QdkScfSolver

Bases: ScfSolver

QDK implementation of the SCF solver.

This class provides a concrete implementation of the SCF (Self-Consistent Field) solver using the internal backend. It inherits from the base ScfSolver class and implements the solve method to perform self-consistent field calculations on molecular structures.

Typical usage:

import qdk_chemistry.algorithms as alg
import qdk_chemistry.data as data

# Create a molecular structure
water = data.Structure(
    positions=[[0.0, 0.0, 0.0], [0.0, 0.76, 0.59], [0.0, -0.76, 0.59]],
    elements=[data.Element.O, data.Element.H, data.Element.H]
)

# Create an SCF solver instance
scf_solver = alg.QdkScfSolver()

# Configure settings if needed
scf_solver.settings().set("basis_set", "sto-3g")

# Perform SCF calculation
energy, wavefunction = scf_solver.run(water, 0, 1)
__init__(self: qdk_chemistry.algorithms.QdkScfSolver) None

Default constructor.

Initializes an SCF solver with default settings.

class qdk_chemistry.algorithms.QdkStabilityChecker

Bases: StabilityChecker

QDK implementation of the stability checker.

This class provides a concrete implementation of the stability checker using the backend. It inherits from the base StabilityChecker class and implements the run method to perform stability analysis on wavefunctions.

Typical usage:

import qdk_chemistry.algorithms as alg
import qdk_chemistry.data as data

# Assume you have a wavefunction from an SCF calculation
scf_solver = algorithms.create("scf_solver", backend)
energy, wavefunction = scf_solver.run(structure, 0, 1, "basis_set")

# Create a stability checker instance
stability_checker = algorithms.create("stability_checker", backend)

# Configure settings if needed
stability_checker.settings().set("internal", True)
stability_checker.settings().set("external", True)

# Perform stability analysis
is_stable, result = stability_checker.run(wavefunction)
__init__(self: qdk_chemistry.algorithms.QdkStabilityChecker) None

Default constructor.

Initializes a stability checker with default settings.

class qdk_chemistry.algorithms.QdkVVHVLocalizer

Bases: OrbitalLocalizer

QDK Valence Virtual - Hard Virtual (VV-HV) orbital localizer.

This class provides a concrete implementation of the orbital localizer using the VV-HV localization algorithm. The VV-HV algorithm partitions virtual orbitals into valence virtuals (VVs) and hard virtuals (HVs) based on projection onto a minimal basis, then localizes each space separately.

The algorithm is particularly useful for post-Hartree-Fock methods where separate treatment of valence and Rydberg-like virtual orbitals improves computational efficiency and accuracy.

Implementation based on:

Subotnik et al. JCP 123, 114108 (2005) Wang et al. JCTC 21, 1163 (2025)

Note

This localizer requires all orbital indices to be covered in the localization call.

Typical usage:

import qdk_chemistry.algorithms as alg

# Create a VV-HV localizer
localizer = alg.QdkVVHVLocalizer()

# Configure settings if needed
localizer.settings().set("minimal_basis", "sto-3g")
localizer.settings().set("weighted_orthogonalization", True)
localizer.settings().set("max_iterations", 100)
localizer.settings().set("convergence_tolerance", 1e-8)

# Localize orbitals (must include all orbital indices)
localized_wfn = localizer.run(wavefunction, loc_indices_a, loc_indices_b)
__init__(self: qdk_chemistry.algorithms.QdkVVHVLocalizer) None

Default constructor.

Initializes a VV-HV localizer with default settings.

class qdk_chemistry.algorithms.QdkValenceActiveSpaceSelector

Bases: ActiveSpaceSelector

QDK valence-based active space selector.

This class selects active space orbitals based on valence orbital criteria. It identifies valence orbitals that are chemically significant for the molecular system under study.

Typical usage:

import qdk_chemistry.algorithms as alg

# Create a valence-based selector
selector = alg.QdkValenceActiveSpaceSelector()

# Select active space
active_wfn = selector.run(wavefunction)
__init__(self: qdk_chemistry.algorithms.QdkValenceActiveSpaceSelector) None

Default constructor.

Initializes a valence-based active space selector with default settings.

class qdk_chemistry.algorithms.QubitHamiltonianSolver

Bases: Algorithm

Abstract base class for solving a qubit Hamiltonian.

__init__()

Initialize the QubitHamiltonianSolver.

type_name()

Return qubit_hamiltonian_solver as the algorithm type name.

Return type:

str

class qdk_chemistry.algorithms.QubitMapper

Bases: Algorithm

Abstract base class for mapping a Hamiltonian to a QubitHamiltonian.

__init__()

Initialize the QubitMapper.

type_name()

Return qubit_mapper as the algorithm type name.

Return type:

str

class qdk_chemistry.algorithms.ScfSolver

Bases: pybind11_object

Abstract base class for Self-Consistent Field (SCF) solvers.

This class defines the interface for SCF calculations that compute molecular orbitals from a molecular structure. Concrete implementations should inherit from this class and implement the solve method.

Examples

>>> # To create a custom SCF solver, inherit from this class:
>>> import qdk_chemistry.algorithms as alg
>>> import qdk_chemistry.data as data
>>> class MyScfSolver(alg.ScfSolver):
...     def __init__(self):
...         super().__init__()  # Call the base class constructor
...     # Implement the _run_impl method
...     def _run_impl(self, structure: data.Structure, charge: int, spin_multiplicity: int, initial_guess=None) -> tuple[float, data.Wavefunction]:
...         # Custom SCF implementation
...         return energy, wavefunction
__init__(self: qdk_chemistry.algorithms.ScfSolver) None

Create an ScfSolver instance.

Initializes a new Self-Consistent Field (SCF) solver with default settings. Configuration options can be modified through the settings() method.

Examples

>>> scf = alg.ScfSolver()
>>> scf.settings().set("max_iterations", 100)
>>> scf.settings().set("convergence_threshold", 1e-8)
name(self: qdk_chemistry.algorithms.ScfSolver) str

The algorithm’s name.

Returns:

The name of the algorithm

Return type:

str

run(self: qdk_chemistry.algorithms.ScfSolver, structure: qdk_chemistry.data.Structure, charge: SupportsInt, spin_multiplicity: SupportsInt, basis_or_guess: qdk_chemistry.data.Orbitals | qdk_chemistry.data.BasisSet | str) tuple[float, qdk_chemistry.data.Wavefunction]

Perform SCF calculation on the given molecular structure.

This method automatically locks settings before execution.

Parameters:
  • structure (qdk_chemistry.data.Structure) – The molecular structure to solve

  • charge (int) – The molecular charge

  • spin_multiplicity (int) – The spin multiplicity of the molecular system

  • basis_or_guess (Union[qdk_chemistry.data.Orbitals, qdk_chemistry.data.BasisSet, str]) –

    Basis set information, which can be provided as:

    • A qdk_chemistry.data.BasisSet object

    • A string specifying the name of a standard basis set (e.g., “sto-3g”)

    • A qdk_chemistry.data.Orbitals object to be used as an initial guess

Returns:

Converged total energy (nuclear + electronic) and the resulting wavefunction.

Return type:

tuple[float, qdk_chemistry.data.Wavefunction]

settings(self: qdk_chemistry.algorithms.ScfSolver) qdk_chemistry.data.Settings

Access the solver’s configuration settings.

Returns:

Reference to the settings object for configuring the solver

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.ScfSolver) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.StabilityChecker

Bases: pybind11_object

Abstract base class for wavefunction stability checkers.

This class defines the interface for checking the stability of wavefunctions in quantum chemistry calculations. Stability checking examines the second-order response of a wavefunction to determine if it corresponds to a true minimum or if there are directions in which the energy can be lowered.

Examples

>>> # To create a custom stability checker, inherit from this class.
>>> import qdk_chemistry.algorithms as alg
>>> import qdk_chemistry.data as data
>>> class MyStabilityChecker(alg.StabilityChecker):
...     def __init__(self):
...         super().__init__()  # Call the base class constructor
...     # Implement the _run_impl method
...     def _run_impl(self, wavefunction: data.Wavefunction) -> tuple[bool, data.StabilityResult]:
...         # Custom stability checking implementation
...         import numpy as np
...         internal_eigenvalues = np.array([1.0, 2.0, 3.0])
...         external_eigenvalues = np.array([0.5, 1.5])
...         internal_eigenvectors = np.eye(3)
...         external_eigenvectors = np.eye(2)
...         internal_stable = np.all(internal_eigenvalues > 0)
...         external_stable = np.all(external_eigenvalues > 0)
...         result = data.StabilityResult(internal_stable, external_stable,
...                                       internal_eigenvalues, internal_eigenvectors,
...                                       external_eigenvalues, external_eigenvectors)
...         return (result.is_stable(), result)
__init__(self: qdk_chemistry.algorithms.StabilityChecker) None

Create a StabilityChecker instance.

Initializes a new stability checker with default settings. Configuration options can be modified through the settings() method.

Examples

>>> checker = alg.StabilityChecker()
>>> checker.settings().set("nroots", 5)
>>> checker.settings().set("convergence_threshold", 1e-6)
name(self: qdk_chemistry.algorithms.StabilityChecker) str

The algorithm’s name.

Returns:

The name of the algorithm

Return type:

str

run(self: qdk_chemistry.algorithms.StabilityChecker, wavefunction: qdk_chemistry.data.Wavefunction) tuple[bool, qdk_chemistry.data.StabilityResult]

Check the stability of the given wavefunction.

This method automatically locks settings before execution and performs stability analysis on the input wavefunction by examining the eigenvalues of the electronic Hessian matrix. A stable wavefunction should have all positive eigenvalues for both internal and external stability.

Parameters:

wavefunction (qdk_chemistry.data.Wavefunction) – The wavefunction to analyze for stability

Returns:

Tuple of the overall stability flag and the detailed stability information (eigenvalues, eigenvectors, and helper accessors).

Return type:

tuple[bool, qdk_chemistry.data.StabilityResult]

settings(self: qdk_chemistry.algorithms.StabilityChecker) qdk_chemistry.data.Settings

Access the stability checker’s configuration settings.

Returns:

Reference to the settings object for configuring the stability checker

Return type:

qdk_chemistry.data.Settings

type_name(self: qdk_chemistry.algorithms.StabilityChecker) str

The algorithm’s type name.

Returns:

The type name of the algorithm

Return type:

str

class qdk_chemistry.algorithms.StatePreparation

Bases: Algorithm

Abstract base class for state preparation algorithms.

__init__()

Initialize the StatePreparation with default settings.

type_name()

Return the algorithm type name as state_prep.

Return type:

str

run(wavefunction)

Prepare a quantum circuit that encodes the given wavefunction.

Return type:

Circuit

Parameters:

wavefunction (Wavefunction) – The target wavefunction to prepare.

Returns:

A Circuit object containing an OpenQASM3 string of the quantum circuit that prepares the wavefunction.

class qdk_chemistry.algorithms.TimeEvolutionBuilder

Bases: Algorithm

Base class for time evolution Builders in QDK/Chemistry algorithms.

__init__()

Initialize the TimeEvolutionBuilder.

class qdk_chemistry.algorithms.TraditionalPhaseEstimation(hamiltonian, evolution_time, *, qft_do_swaps=True)

Bases: PhaseEstimation

Standard QFT-based (non-iterative) phase estimation.

Parameters:
algorithm: PhaseEstimationAlgorithm | None = 'traditional'
__init__(hamiltonian, evolution_time, *, qft_do_swaps=True)

Initialize the traditional phase estimation routine.

Parameters:
  • hamiltonian (QubitHamiltonian) – Target Hamiltonian.

  • evolution_time (float) – Time parameter t for U = exp(-i H t).

  • qft_do_swaps (bool) –

    Whether to include the final swap layer in the inverse

    QFT. Defaults to True so that the measured bit string is ordered from most-significant to least-significant bit.

create_circuit(state_prep, *, num_bits, measurement_register=None, include_measurement=True)

Build the traditional QPE circuit.

Return type:

QuantumCircuit

Parameters:
qdk_chemistry.algorithms.available(algorithm_type=None)

List all available algorithms by type.

This function returns information about available algorithms in the registry. When called without arguments, it returns a dictionary mapping all algorithm types to their available implementations. When called with a specific algorithm type, it returns only the list of available algorithms for that type.

Return type:

dict[str, list[str]] | list[str]

Parameters:

algorithm_type (str | None) –

If provided, only list algorithms of this type.

If None, list all algorithms across all types.

Returns:

Information on available algorithms.

When algorithm_type is None, returns a dictionary where keys are algorithm type names and values are lists of available algorithm names for that type. When algorithm_type is specified, returns a list of available algorithm names for that specific type (empty list if type not found or no algorithms are available).

Return type:

dict[str, list[str]] | list[str]

Examples

>>> from qdk_chemistry.algorithms import registry
>>> # List all available algorithms across all types
>>> all_algorithms = registry.available()
>>> print(all_algorithms)
{'scf_solver': ['pyscf', 'qdk'], 'active_space_selector': ['pyscf_avas', 'qdk_occupation', ...], ...}
>>> # List only SCF solvers
>>> scf_solvers = registry.available("scf_solver")
>>> print(scf_solvers)
['pyscf', 'qdk']
>>> # Check what active space selectors are available
>>> selectors = registry.available("active_space_selector")
>>> print(selectors)
['pyscf_avas', 'qdk_occupation', 'qdk_autocas_eos', 'qdk_autocas', 'qdk_valence']
qdk_chemistry.algorithms.create(algorithm_type, algorithm_name=None, **kwargs)

Create an algorithm instance by type and name.

This function creates an algorithm instance from the registry using the specified algorithm type and name. If no name is provided, the default implementation for that type is created.

Available algorithm types depend on the installed plugins and any user-registered algorithms. Use available() to inspect what is currently loaded before calling create().

Return type:

Algorithm

Parameters:
  • algorithm_type (str) –

    The type of algorithm to create.

    (e.g., “scf_solver”, “active_space_selector”, “coupled_cluster_calculator”).

  • algorithm_name (str | None) –

    The specific name of the algorithm implementation to create.

    If None or empty string, creates the default algorithm for that type.

  • kwargs

    Optional keyword arguments (passed via **kwargs).

    These configure the algorithm’s settings. These are forwarded directly to the algorithm’s settings via settings().update(). Available settings depend on the specific algorithm type and implementation and can be looked up with inspect_settings() or print_settings().

Returns:

The created algorithm instance.

Return type:

Algorithm

Raises:

KeyError – If the specified algorithm type is not registered in the system.

Examples

>>> from qdk_chemistry.algorithms import registry
>>> # Create the default SCF solver
>>> scf = registry.create("scf_solver")
>>> # Create a specific SCF solver by name
>>> pyscf_solver = registry.create("scf_solver", "pyscf")
>>> # Create an SCF solver with custom settings
>>> scf = registry.create("scf_solver", "pyscf", max_iterations=100, convergence_threshold=1e-8)
>>> # Create an MP2 calculator
>>> mp2_calc = registry.create("dynamical_correlation_calculator", "qdk_mp2_calculator")
>>> # Create the default reference-derived calculator (MP2)
>>> default_calc = registry.create("dynamical_correlation_calculator")
qdk_chemistry.algorithms.energy_from_phase(phase_fraction, *, evolution_time)

Convert a measured phase fraction to energy using E = angle / t.

Return type:

float

Parameters:
  • phase_fraction (float) – Fractional phase obtained from the phase register.

  • evolution_time (float) – Evolution time t used in U = exp(-i H t).

Returns:

Energy estimate corresponding to phase_fraction.

qdk_chemistry.algorithms.inspect_settings(algorithm_type, algorithm_name)

Inspect the settings schema for a specific algorithm.

This function retrieves the settings schema for a given algorithm type and name. The settings schema provides information about configurable parameters for the algorithm, including their names, expected Python types, default values, descriptions, and allowed values/ranges.

Return type:

list[tuple[str, str, Any, str | None, Any | None]]

Parameters:
  • algorithm_type (str) –

    The type of algorithm.

    (e.g., “scf_solver”, “active_space_selector”, “coupled_cluster_calculator”).

  • algorithm_name (str) – The specific name of the algorithm implementation.

Returns:

A list of tuples where each tuple contains:
  • Setting name (str): The name/key of the setting

  • Expected Python type (str): The Python type expected for this setting (e.g., int, float, str, bool, list[int], list[float])

  • Default value (Any): The default value for this setting

  • Description (str | None): Human-readable description of the setting, or None if not available

  • Limits (Any | None): Allowed values or range, or None if not constrained. For numeric types: tuple of (min, max). For strings/lists: list of allowed values.

Return type:

list[tuple[str, str, Any, str | None, Any | None]]

Raises:

KeyError – If the specified algorithm type is not registered in the system.

Examples

>>> from qdk_chemistry.algorithms import registry
>>> # Show settings for the PySCF SCF solver
>>> settings_info = registry.inspect_settings("scf_solver", "pyscf")
>>> for name, python_type, default, description, limits in settings_info:
...     limit_str = f" (allowed: {limits})" if limits else ""
...     desc_str = f"  # {description}" if description else ""
...     print(f"{name}: {python_type} = {default}{limit_str}{desc_str}")
method: str = hf (allowed: ['hf', 'dft'])  # SCF method to use
basis_set: str = def2-svp  # Basis set for the calculation
charge: int = 0  # Total molecular charge
spin_multiplicity: int = 1 (allowed: (1, 10))  # Spin multiplicity (2S+1)
tolerance: float = 1e-06 (allowed: (1e-12, 0.01))  # Convergence threshold
max_iterations: int = 50 (allowed: (1, 1000))  # Maximum SCF iterations
force_restricted: bool = False  # Force restricted calculation
qdk_chemistry.algorithms.print_settings(algorithm_type, algorithm_name, characters=120)

Print the settings table for a specific algorithm.

This function retrieves and prints the settings schema for a given algorithm type and name as a formatted table. The table displays configurable parameters including their names, current values, allowed values/ranges, and descriptions.

Return type:

None

Parameters:
  • algorithm_type (str) –

    The type of algorithm.

    (e.g., “scf_solver”, “active_space_selector”, “coupled_cluster_calculator”).

  • algorithm_name (str) – The specific name of the algorithm implementation.

  • characters (int) – Maximum width of the table in characters (default: 120).

Raises:

KeyError – If the specified algorithm type is not registered in the system.

Examples

>>> from qdk_chemistry.algorithms import registry
>>> # Print settings table for the PySCF SCF solver
>>> registry.print_settings("scf_solver", "pyscf")
------------------------------------------------------------------------------------------------------------------------
Key                  | Value           | Allowed              | Description
------------------------------------------------------------------------------------------------------------------------
charge               | 0               | -                    | Total molecular charge
convergence_thresh...| 1.00e-06        | 1.00e-12 <= x        | Energy convergence threshold
                     |                 | x <= 1.00e-02        |
force_restricted     | false           | -                    | Force restricted calculation
max_iterations       | 50              | 1 <= x <= 1000       | Maximum SCF iterations
method               | "hf"            | ["hf", "dft"]        | SCF method to use
spin_multiplicity    | 1               | 1 <= x <= 10         | Spin multiplicity (2S+1)
------------------------------------------------------------------------------------------------------------------------
>>> # Print with custom width
>>> registry.print_settings("scf_solver", "pyscf", characters=100)
qdk_chemistry.algorithms.register(generator)

Register a custom algorithm implementation.

This function registers a custom algorithm implementation (typically written in Python) into the registry system. The generator function should return a new instance of the algorithm each time it’s called. The algorithm’s type is automatically detected from the returned instance.

Return type:

None

Parameters:

generator (Callable[[], Algorithm]) –

A callable that returns a new instance.

Need to return an instance of the custom algorithm. This will be called each time the algorithm is created from the factory.

Raises:

KeyError – If the algorithm’s type is not a recognized algorithm type in the system.

Examples

>>> from qdk_chemistry.algorithms import registry
>>> from qdk_chemistry.algorithms import ScfSolver
>>> class MyCustomScf(ScfSolver):
...     def name(self):
...         return "my_custom_scf"
...     def _run_impl(self, structure, charge, spin_multiplicity):
...         # Custom implementation
...         pass
>>> # Register the custom algorithm
>>> registry.register(lambda: MyCustomScf())
>>> # Now it can be created from the registry
>>> scf = registry.create("scf_solver", "my_custom_scf")
qdk_chemistry.algorithms.show_default(algorithm_type=None)

List the default algorithm by type.

This function returns information about the default algorithms configured for each algorithm type. When called without arguments, it returns a dictionary mapping all algorithm types to their default algorithm names. When called with a specific algorithm type, it returns only the default algorithm name for that type.

Return type:

dict[str, str] | str

Parameters:

algorithm_type (str | None) – If provided, only return the default algorithm for this type. If None, return default algorithms for all types.

Returns:

When algorithm_type is None, returns a dictionary where

keys are algorithm type names and values are the default algorithm names for each type. When algorithm_type is specified, returns the default algorithm name for that specific type (empty string if type not found).

Return type:

dict[str, str] | str

Examples

>>> from qdk_chemistry.algorithms import registry
>>> # List the default algorithms across all types
>>> default_algorithms = registry.show_default()
>>> print(default_algorithms)
{'scf_solver': 'qdk', 'active_space_selector': 'qdk_autocas_eos', ...}
>>> # Get the default SCF solver
>>> default_scf = registry.show_default("scf_solver")
>>> print(default_scf)
'qdk'
qdk_chemistry.algorithms.unregister(algorithm_type, algorithm_name)

Unregister a custom algorithm implementation.

This function removes a previously registered algorithm from the registry.

Return type:

None

Parameters:
  • algorithm_type (str) –

    The type of algorithm to unregister.

    (e.g., “scf_solver”, “active_space_selector”).

  • algorithm_name (str) – The name of the specific algorithm implementation to unregister.

Raises:

KeyError – If the specified algorithm type is not registered in the system.

Examples

>>> from qdk_chemistry.algorithms import registry
>>> # Assuming you previously registered a custom algorithm
>>> registry.unregister("scf_solver", "my_custom_scf")

Subpackages

Submodules