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
hash(self: qdk_chemistry.algorithms.ActiveSpaceSelector, wavefunction: qdk_chemistry.data.Wavefunction) str
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.CircuitExecutor

Bases: Algorithm

Abstract base class for circuit executor algorithms.

__init__()

Initialize the CircuitExecutor with default settings.

type_name()

Return the algorithm type name as circuit_executor.

Return type:

str

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

class qdk_chemistry.algorithms.ControlledCircuitMapper

Bases: Algorithm

Base class for circuit mapper for controlled-unitary in QDK/Chemistry algorithms.

__init__()

Initialize the ControlledCircuitMapper.

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

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 the total energy, a ket wavefunction, and optionally a bra wavefunction for non-Hermitian methods.

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, ket_wavefunction, bra_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)
hash(self: qdk_chemistry.algorithms.DynamicalCorrelationCalculator, ansatz: qdk_chemistry.data.Ansatz) str
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, qdk_chemistry.data.Wavefunction | None]

Perform reference-derived calculation.

Parameters:

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

Returns:

A tuple containing the total energy,

the ket wavefunction, and optionally a bra wavefunction for non-Hermitian methods

Return type:

tuple[float, Wavefunction, Optional[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.ExpectationEstimator

Bases: Algorithm

Abstract base class for expectation estimator algorithms.

__init__()

Initialize the ExpectationEstimator.

type_name()

Return expectation_estimator as the algorithm type name.

Return type:

str

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

class qdk_chemistry.algorithms.FiniteDifferenceNuclearDerivativeCalculator

Bases: NuclearDerivativeCalculator

Numeric nuclear derivative calculator using central finite differences.

__init__(self: qdk_chemistry.algorithms.FiniteDifferenceNuclearDerivativeCalculator) None

Create a finite-difference derivative calculator.

run(self: qdk_chemistry.algorithms.NuclearDerivativeCalculator, structure: qdk_chemistry.data.Structure, charge: SupportsInt | SupportsIndex, spin_multiplicity: SupportsInt | SupportsIndex, seed_or_basis: qdk_chemistry.data.Orbitals | qdk_chemistry.data.BasisSet | qdk_chemistry.data.Wavefunction | str, n_inactive_orbitals: SupportsInt | SupportsIndex = 0) tuple[float, qdk_chemistry.data.NuclearGradients, qdk_chemistry.data.NuclearHessian | None, qdk_chemistry.data.Wavefunction | None]

Compute nuclear derivatives for a molecular structure.

Parameters:
  • structure – Molecular structure to evaluate.

  • charge – Total molecular charge.

  • spin_multiplicity – Spin multiplicity of the molecular system.

  • seed_or_basis – Basis name, basis set, orbitals, or wavefunction seed.

  • n_inactive_orbitals – Number of doubly occupied orbitals excluded from multi-reference active spaces. This value is validated against the electron count even when the selected energy path does not use an active space (e.g., SCF).

Returns:

(energy, gradients, hessian, wavefunction).

Return type:

tuple

class qdk_chemistry.algorithms.HadamardTest(test_basis=HadamardTestBasis.X, circuit_executor=None, controlled_circuit_mapper=None)

Bases: Algorithm

Hadamard test generator.

Orchestrates the backend-agnostic Hadamard test workflow: it validates the inputs, delegates circuit construction (including mapping the target unitary into a controlled evolution circuit) to hadamard_test_circuit_builder (currently fixed to qdk), and executes the resulting circuit with the nested circuit_executor.

Parameters:
__init__(test_basis=HadamardTestBasis.X, circuit_executor=None, controlled_circuit_mapper=None)

Initialize a Hadamard test generator.

Parameters:
  • test_basis (HadamardTestBasis) – Measurement basis for the control qubit.

  • circuit_executor (AlgorithmRef | None) – Optional algorithm reference for circuit execution.

  • controlled_circuit_mapper (AlgorithmRef | None) – Optional algorithm reference for controlled circuit mapping.

type_name()

Return the algorithm type name as hadamard_test.

Return type:

str

name()

Return the name of the Hadamard test algorithm.

Return type:

str

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

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
hash(self: qdk_chemistry.algorithms.HamiltonianConstructor, orbitals: qdk_chemistry.data.Orbitals) str
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.HamiltonianUnitaryBuilder

Bases: Algorithm

Base class for Hamiltonian unitary builders in QDK/Chemistry algorithms.

__init__()

Initialize the HamiltonianUnitaryBuilder.

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

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
hash(self: qdk_chemistry.algorithms.MultiConfigurationCalculator, hamiltonian: qdk_chemistry.data.Hamiltonian, n_active_alpha_electrons: SupportsInt | SupportsIndex, n_active_beta_electrons: SupportsInt | SupportsIndex) str
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 | SupportsIndex, n_active_beta_electrons: SupportsInt | SupportsIndex) 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,
...                   n_active_alpha_electrons : int,
...                   n_active_beta_electrons : int) ->tuple[float, data.Wavefunction] :
...         # Custom MCSCF implementation
...         # Use self._create_nested("multi_configuration_calculator")
...         # to get the configurable nested algorithm exposed by these settings.
...         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
hash(self: qdk_chemistry.algorithms.MultiConfigurationScf, orbitals: qdk_chemistry.data.Orbitals, n_active_alpha_electrons: SupportsInt | SupportsIndex, n_active_beta_electrons: SupportsInt | SupportsIndex) str
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, n_active_alpha_electrons: SupportsInt | SupportsIndex, n_active_beta_electrons: SupportsInt | SupportsIndex) tuple[float, qdk_chemistry.data.Wavefunction]

Perform a MultiConfigurationScf calculation.

This method automatically locks settings before execution. The nested HamiltonianConstructor and MultiConfigurationCalculator are created from AlgorithmRef entries in settings.

Parameters:
  • orbitals (qdk_chemistry.data.Orbitals) – The initial molecular orbitals for the calculation

  • 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 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.NuclearDerivativeCalculator

Bases: pybind11_object

Base class for nuclear derivative algorithms.

Calculators return the total energy, nuclear gradients, an optional Hessian, and an optional wavefunction for a molecular structure.

__init__(self: qdk_chemistry.algorithms.NuclearDerivativeCalculator) None

Create a nuclear derivative calculator.

name(self: qdk_chemistry.algorithms.NuclearDerivativeCalculator) str

Return the implementation name.

run(self: qdk_chemistry.algorithms.NuclearDerivativeCalculator, structure: qdk_chemistry.data.Structure, charge: SupportsInt | SupportsIndex, spin_multiplicity: SupportsInt | SupportsIndex, seed_or_basis: qdk_chemistry.data.Orbitals | qdk_chemistry.data.BasisSet | qdk_chemistry.data.Wavefunction | str, n_inactive_orbitals: SupportsInt | SupportsIndex = 0) tuple[float, qdk_chemistry.data.NuclearGradients, qdk_chemistry.data.NuclearHessian | None, qdk_chemistry.data.Wavefunction | None]

Compute nuclear derivatives for a molecular structure.

Parameters:
  • structure – Molecular structure to evaluate.

  • charge – Total molecular charge.

  • spin_multiplicity – Spin multiplicity of the molecular system.

  • seed_or_basis – Basis name, basis set, orbitals, or wavefunction seed.

  • n_inactive_orbitals – Number of doubly occupied orbitals excluded from multi-reference active spaces. This value is validated against the electron count even when the selected energy path does not use an active space (e.g., SCF).

Returns:

(energy, gradients, hessian, wavefunction).

Return type:

tuple

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

Return the calculator settings.

type_name(self: qdk_chemistry.algorithms.NuclearDerivativeCalculator) str

Return the algorithm type name.

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
hash(self: qdk_chemistry.algorithms.OrbitalLocalizer, wavefunction: qdk_chemistry.data.Wavefunction, loc_indices_a: collections.abc.Sequence[SupportsInt | SupportsIndex], loc_indices_b: collections.abc.Sequence[SupportsInt | SupportsIndex]) str
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 | SupportsIndex], loc_indices_b: collections.abc.Sequence[SupportsInt | SupportsIndex]) 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

Bases: Algorithm

Abstract base class for phase estimation algorithms.

__init__()

Initialize the PhaseEstimation with default settings.

type_name()

Return the algorithm type name as phase_estimation.

Return type:

str

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

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
hash(self: qdk_chemistry.algorithms.ProjectedMultiConfigurationCalculator, hamiltonian: qdk_chemistry.data.Hamiltonian, configurations: collections.abc.Sequence[qdk_chemistry.data.Configuration]) str
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.

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

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.

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

class qdk_chemistry.algorithms.QdkExpectationEstimator

Bases: ExpectationEstimator

QDK implementation of the ExpectationEstimator.

__init__()

Initialize the QdkExpectationEstimator.

type_name()

Return expectation_estimator as the algorithm type name.

Return type:

str

name()

Get the name of the estimator for registry purposes.

Return type:

str

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

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.

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

class qdk_chemistry.algorithms.QdkMP2Calculator

Bases: DynamicalCorrelationCalculator

QDK implementation of the MP2 dynamical correlation calculator.

Computes the second-order Møller-Plesset (MP2) correlation energy and the T1/T2 amplitudes from a reference Ansatz, automatically selecting the restricted (RMP2) or unrestricted (UMP2) formulation from the reference wavefunction. The MP2 ket wavefunction is returned in an AmplitudeContainer.

Typical usage:

import qdk_chemistry.algorithms as alg

calculator = alg.create("dynamical_correlation_calculator", "qdk_mp2_calculator")
total_energy, ket_wavefunction, _ = calculator.run(ansatz)
__init__(self: qdk_chemistry.algorithms.QdkMP2Calculator) None

Default constructor.

Initializes an MP2 calculator with default settings.

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

Perform reference-derived calculation.

Parameters:

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

Returns:

A tuple containing the total energy,

the ket wavefunction, and optionally a bra wavefunction for non-Hermitian methods

Return type:

tuple[float, Wavefunction, Optional[Wavefunction]]

class qdk_chemistry.algorithms.QdkMP2NaturalOrbitalLocalizer

Bases: OrbitalLocalizer

QDK MP2 natural orbital transformer.

Deprecated since version 2.0.0: Use QdkNaturalOrbitalLocalizer (qdk_natural_orbitals) with a wavefunction that already contains the active-space one-particle reduced density matrix (1-RDM).

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.

run(self: qdk_chemistry.algorithms.OrbitalLocalizer, wavefunction: qdk_chemistry.data.Wavefunction, loc_indices_a: collections.abc.Sequence[SupportsInt | SupportsIndex], loc_indices_b: collections.abc.Sequence[SupportsInt | SupportsIndex]) 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

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("search_matel_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.

run(self: qdk_chemistry.algorithms.MultiConfigurationCalculator, hamiltonian: qdk_chemistry.data.Hamiltonian, n_active_alpha_electrons: SupportsInt | SupportsIndex, n_active_beta_electrons: SupportsInt | SupportsIndex) 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

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.

run(self: qdk_chemistry.algorithms.MultiConfigurationCalculator, hamiltonian: qdk_chemistry.data.Hamiltonian, n_active_alpha_electrons: SupportsInt | SupportsIndex, n_active_beta_electrons: SupportsInt | SupportsIndex) 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

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("ci_residual_tolerance", 1e-8)
pmc.settings().set("max_solver_iterations", 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.

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:
class qdk_chemistry.algorithms.QdkNaturalOrbitalLocalizer

Bases: OrbitalLocalizer

QDK natural orbital transformer.

This class provides a concrete implementation that transforms molecular orbitals into natural orbitals by diagonalizing the spin-traced one-particle reduced density matrix (1-RDM). Natural orbitals are eigenfunctions of the 1-RDM, and their eigenvalues are the occupation numbers.

Note

Requires loc_indices_a == loc_indices_b (natural orbitals are a single set). Requires loc_indices_a/loc_indices_b to match the orbitals’ active-space indices exactly. Requires a spin-traced 1-RDM and an active space in the wavefunction. For unrestricted Slaterdeterminant, the 1-RDM is expressed in the alpha MO basis and the output is always a restricted set of natural orbitals.

Typical usage:

import qdk_chemistry.algorithms as alg

# Create a natural orbital localizer
localizer = alg.QdkNaturalOrbitalLocalizer()

# Transform to natural orbitals
no_wfn = localizer.run(wavefunction, active_indices, active_indices)
__init__(self: qdk_chemistry.algorithms.QdkNaturalOrbitalLocalizer) None

Default constructor.

Initializes a natural orbital transformer with default settings.

run(self: qdk_chemistry.algorithms.OrbitalLocalizer, wavefunction: qdk_chemistry.data.Wavefunction, loc_indices_a: collections.abc.Sequence[SupportsInt | SupportsIndex], loc_indices_b: collections.abc.Sequence[SupportsInt | SupportsIndex]) 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

class qdk_chemistry.algorithms.QdkNuclearDerivativeCalculator

Bases: NuclearDerivativeCalculator

QDK nuclear derivative calculator using analytic internal SCF gradients.

__init__(self: qdk_chemistry.algorithms.QdkNuclearDerivativeCalculator) None

Create a QDK analytic nuclear derivative calculator.

run(self: qdk_chemistry.algorithms.NuclearDerivativeCalculator, structure: qdk_chemistry.data.Structure, charge: SupportsInt | SupportsIndex, spin_multiplicity: SupportsInt | SupportsIndex, seed_or_basis: qdk_chemistry.data.Orbitals | qdk_chemistry.data.BasisSet | qdk_chemistry.data.Wavefunction | str, n_inactive_orbitals: SupportsInt | SupportsIndex = 0) tuple[float, qdk_chemistry.data.NuclearGradients, qdk_chemistry.data.NuclearHessian | None, qdk_chemistry.data.Wavefunction | None]

Compute nuclear derivatives for a molecular structure.

Parameters:
  • structure – Molecular structure to evaluate.

  • charge – Total molecular charge.

  • spin_multiplicity – Spin multiplicity of the molecular system.

  • seed_or_basis – Basis name, basis set, orbitals, or wavefunction seed.

  • n_inactive_orbitals – Number of doubly occupied orbitals excluded from multi-reference active spaces. This value is validated against the electron count even when the selected energy path does not use an active space (e.g., SCF).

Returns:

(energy, gradients, hessian, wavefunction).

Return type:

tuple

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.

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

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.

run(self: qdk_chemistry.algorithms.OrbitalLocalizer, wavefunction: qdk_chemistry.data.Wavefunction, loc_indices_a: collections.abc.Sequence[SupportsInt | SupportsIndex], loc_indices_b: collections.abc.Sequence[SupportsInt | SupportsIndex]) 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

class qdk_chemistry.algorithms.QdkQubitMapper(threshold=1e-12, integral_threshold=1e-12)

Bases: QubitMapper

QDK native qubit mapper using Majorana-level C++ engine.

This is a table-driven backend: it reads the Pauli-string table from the MajoranaMapping and passes it directly to the C++ majorana_map_hamiltonian engine. Any valid MajoranaMapping works — built-in (Jordan-Wigner, Bravyi-Kitaev, parity, BK-tree, SCBK) or custom user-defined tables. The mapping’s name and base_encoding are used only for metadata on the output QubitOperator, not for dispatch.

Both restricted (RHF) and unrestricted (UHF) Hamiltonians are supported. For unrestricted systems, the engine handles all four spin-channel ERI blocks (aa, ab, ba, bb) independently.

The two-body integrals are consumed in the native storage format of the Hamiltonian’s container (the C++ engine dispatches on the container type):

  • SparseHamiltonianContainer: the engine iterates only the stored non-zero (p, q, r, s) entries, so both memory and runtime improve for the mostly-zero integrals of lattice / model Hamiltonians.

  • CholeskyHamiltonianContainer: the three-center factors are kept in their O(N**2 * naux) form and the auxiliary index is contracted one (pq|.) row at a time, so the dense N**4 tensor is never built and peak additional memory is a single N**2 row.

  • All other containers use the dense engine path.

In all cases the result is numerically equivalent (term-by-term, to within 1e-12) to the dense path.

The mapper uses canonical blocked spin-orbital ordering internally: qubits 0..N-1 for alpha spin, qubits N..2N-1 for beta spin (where N is the number of spatial orbitals). Use QubitOperator.to_interleaved() for alternative qubit orderings.

Examples

>>> from qdk_chemistry.algorithms import create
>>> from qdk_chemistry.data import MajoranaMapping
>>> mapper = create("qubit_mapper")
>>> mapping = MajoranaMapping.jordan_wigner(num_modes=n_spin_orbitals)
>>> qh = mapper.run(hamiltonian, mapping)
Parameters:
__init__(threshold=1e-12, integral_threshold=1e-12)

Initialize the QdkQubitMapper with default settings.

Parameters:
  • threshold (float) – Threshold for pruning small Pauli coefficients. Default: 1e-12.

  • integral_threshold (float) – Threshold for filtering small integrals. Default: 1e-12.

Return type:

None

name()

Return the algorithm name.

Return type:

str

run(hamiltonian, mapping)

Map a fermionic Hamiltonian to a qubit operator.

Delegates entirely to _run_impl. Each backend is responsible for handling tapering (if mapping.tapering is set).

Return type:

QubitOperator

Parameters:
  • hamiltonian (Hamiltonian) – The fermionic Hamiltonian.

  • mapping (MajoranaMapping) – The Majorana-to-Pauli encoding (may include tapering).

Returns:

QubitOperator with encoding and tapering metadata set.

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()

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

Default constructor.

Initializes an SCF solver with default settings.

run(self: qdk_chemistry.algorithms.ScfSolver, structure: qdk_chemistry.data.Structure, charge: SupportsInt | SupportsIndex, spin_multiplicity: SupportsInt | SupportsIndex, 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]

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.

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]

class qdk_chemistry.algorithms.QdkStabilizedScfSolver

Bases: ScfSolver

QDK implementation of an automated stabilized SCF workflow.

This solver runs a regular SCF calculation, checks wavefunction stability, rotates orbitals along detected instability directions, and reruns SCF until a stable wavefunction is found or the configured stability cycle limit is reached.

Typical usage:

import qdk_chemistry.algorithms as alg

scf_solver = alg.create("scf_solver", "qdk_stabilized")
energy, wavefunction = scf_solver.run(structure, 0, 1, "sto-3g")
__init__(self: qdk_chemistry.algorithms.QdkStabilizedScfSolver) None

Default constructor.

Initializes a stabilized SCF solver with default nested SCF and stability checker settings.

run(self: qdk_chemistry.algorithms.ScfSolver, structure: qdk_chemistry.data.Structure, charge: SupportsInt | SupportsIndex, spin_multiplicity: SupportsInt | SupportsIndex, 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]

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.

run(self: qdk_chemistry.algorithms.OrbitalLocalizer, wavefunction: qdk_chemistry.data.Wavefunction, loc_indices_a: collections.abc.Sequence[SupportsInt | SupportsIndex], loc_indices_b: collections.abc.Sequence[SupportsInt | SupportsIndex]) 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

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.

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

class qdk_chemistry.algorithms.QpeCircuitBuilder(num_bits=-1, unitary_builder=None, controlled_circuit_mapper=None)

Bases: Algorithm

Abstract base class for phase estimation circuit builders.

Parameters:
__init__(num_bits=-1, unitary_builder=None, controlled_circuit_mapper=None)

Initialize the QpeCircuitBuilder with default settings.

Parameters:
  • num_bits (int) – The number of phase bits to estimate. Default to -1; user needs to set a valid value.

  • unitary_builder (AlgorithmRef | None) – Optional algorithm reference for the unitary builder.

  • controlled_circuit_mapper (AlgorithmRef | None) – Optional algorithm reference for the controlled circuit mapper.

type_name()

Return the algorithm type name as qpe_circuit_builder.

Return type:

str

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

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

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

class qdk_chemistry.algorithms.QubitMapper

Bases: Algorithm

Abstract base class for mapping a Hamiltonian to a QubitOperator.

How backends use the MajoranaMapping

QubitMapper backends fall into two groups, and they use the MajoranaMapping argument differently:

  • Table-driven backends (e.g. QdkQubitMapper) read mapping.table — the Pauli strings that define the encoding — and feed them directly to the mapping engine. Any valid table works, including custom encodings with no standard name.

  • Third-party backends (e.g. OpenFermionQubitMapper, QiskitQubitMapper) ignore mapping.table. Instead they read mapping.base_encoding (a string like "jordan-wigner") and pass it to their own library to select the matching transform. The qubit operator is then built entirely by the third-party library’s own pipeline.

Third-party backends

Because third-party backends choose their transform by encoding name, the Pauli table in the MajoranaMapping is not used. Consistency between the table and the name is not checked at runtime. If a MajoranaMapping is manually built with a table that does not match its base_encoding name, a third-party backend will silently use the wrong transform.

Factory-produced mappings (MajoranaMapping.jordan_wigner(), .bravyi_kitaev(), etc.) always keep the table and name in sync. Cross-backend eigenvalue tests in the test suite verify this for every supported factory x backend combination. Custom or manually built mappings with non-standard names cannot be used with third-party backends.

Tapering

Each backend handles tapering in its own _run_impl(). The static helper _taper_result provides shared taper-then-relabel logic so backends don’t have to reimplement it. All shipped backends (QDK, OpenFermion, Qiskit) use this helper.

__init__()

Initialize the QubitMapper.

type_name()

Return qubit_mapper as the algorithm type name.

Return type:

str

run(hamiltonian, mapping)

Map a fermionic Hamiltonian to a qubit operator.

Delegates entirely to _run_impl. Each backend is responsible for handling tapering (if mapping.tapering is set).

Return type:

QubitOperator

Parameters:
  • hamiltonian (Hamiltonian) – The fermionic Hamiltonian.

  • mapping (MajoranaMapping) – The Majorana-to-Pauli encoding (may include tapering).

Returns:

QubitOperator with encoding and tapering metadata set.

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)
hash(self: qdk_chemistry.algorithms.ScfSolver, structure: qdk_chemistry.data.Structure, charge: SupportsInt | SupportsIndex, spin_multiplicity: SupportsInt | SupportsIndex, basis_or_guess: qdk_chemistry.data.Orbitals | qdk_chemistry.data.BasisSet | str) str
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 | SupportsIndex, spin_multiplicity: SupportsInt | SupportsIndex, 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)
hash(self: qdk_chemistry.algorithms.StabilityChecker, wavefunction: qdk_chemistry.data.Wavefunction) str
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.

Note

Current Limitation: All state preparation algorithms currently only support the Jordan-Wigner encoding for fermion-to-qubit mapping. The returned Circuit will have its encoding attribute set to "jordan-wigner".

If you use the state preparation circuit with a QubitOperator that uses a different encoding (e.g., "bravyi-kitaev" or "parity"), the encodings will be incompatible and may lead to incorrect results.

Recommended workflow:
  1. Create a QubitOperator using Jordan-Wigner encoding

  2. Use state preparation to create a Circuit

  3. Both will have encoding="jordan-wigner" and will be compatible

Support for additional encodings is planned for future releases.

__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: HamiltonianUnitaryBuilder

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

__init__()

Initialize the TimeEvolutionBuilder.

run(*args, **kwargs)

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

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.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