Namespace qdk

namespace qdk
namespace chemistry
namespace algorithms

Typedefs

using BasisOrGuessType = std::variant<std::shared_ptr<data::Orbitals>, std::shared_ptr<data::BasisSet>, std::string>

Type alias for basis set specification or initial guess.

Can be one of:

  • A shared pointer to Orbitals for initial guess

  • A shared pointer to BasisSet for custom basis

  • A string for standard basis set name (e.g., “sto-3g”)

using DynamicalCorrelationResult = std::tuple<double, std::shared_ptr<data::Wavefunction>, std::optional<std::shared_ptr<data::Wavefunction>>>

Return type for dynamical correlation calculations.

A tuple containing:

  • double: Total energy (reference + correlation)

  • shared_ptr<Wavefunction>: The ket (right) wavefunction

  • optional<shared_ptr<Wavefunction>>: Optional bra (left) wavefunction for non-Hermitian methods

using NuclearDerivativeResult = std::tuple<double, std::shared_ptr<data::NuclearGradients>, std::optional<std::shared_ptr<data::NuclearHessian>>, std::optional<std::shared_ptr<data::Wavefunction>>>

Energy, gradients, optional Hessian, and optional wavefunction.

using NuclearDerivativeSeedType = std::variant<std::shared_ptr<data::Orbitals>, std::shared_ptr<data::BasisSet>, std::shared_ptr<data::Wavefunction>, std::string>

Initial basis-set name, basis, orbitals, or wavefunction seed for a derivative run.

A string seed is interpreted as the basis-set name, such as “sto-3g”, to use for SCF calculations.

class ActiveSpaceSelector : public qdk::chemistry::algorithms::Algorithm<ActiveSpaceSelector, std::shared_ptr<data::Wavefunction>, std::shared_ptr<data::Wavefunction>>
#include <qdk/chemistry/algorithms/active_space.hpp>

Abstract base class for selecting active spaces in quantum chemistry calculations.

The ActiveSpaceSelector class defines an interface for algorithms that identify and select important orbitals to include in active space calculations. Active space methods are crucial for reducing the computational complexity of many-body calculations by focusing on the most chemically relevant orbitals while treating the rest as either fully occupied or empty.

Different active space selection algorithms can be implemented by deriving from this class and providing implementations for the pure virtual methods. The class works with the Factory pattern through ActiveSpaceSelectorFactory to allow runtime selection of different implementations.

Typical usage:

auto selector =
  qdk::chemistry::algorithms::ActiveSpaceSelectorFactory::create("algorithm_name");
selector->settings().set("parameter_name", value);
data::Orbitals orbitals_with_active_space =
  selector->run(wavefunction);

See also

ActiveSpaceSelectorFactory for creating instances of active space selectors

See also

data::Wavefunction for the wavefunction data structure used as input

See also

data::Settings for configuration parameters

Public Functions

ActiveSpaceSelector() = default

Default constructor for ActiveSpaceSelector.

This constructor initializes the ActiveSpaceSelector object.

virtual ~ActiveSpaceSelector() = default

Default destructor for ActiveSpaceSelector.

This destructor cleans up any resources used by the ActiveSpaceSelector.

virtual std::string name() const = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline ReturnType run(Args... args) const

Selects the active space from the given orbitals.

Note

Settings are automatically locked when this method is called and cannot be modified during or after execution.

Note

The specific criteria and side effects (such as unitary rotations) for selecting the active space may vary between implementations. See the documentation for the specific active space selector being used (docstring).

Throws:
  • std::runtime_error – if the active space selection fails or if the input orbitals already have an active space defined.

  • qdk::chemistry::data::SettingsAreLocked – if attempting to modify settings after run) is called

Returns:

Orbitals with active space data populated. Depending on the implementation, the returned orbitals may be a copy with only metadata added (e.g., occupation/valence selectors), or they may include transformations to the underlying coefficients/energies (e.g., AVAS may rotate/canonicalize orbitals). The input orbitals are not modified.

inline std::string type_name() const final

Access the algorithm’s type name.

Returns:

The algorithm’s type name

struct ActiveSpaceSelectorFactory : public qdk::chemistry::algorithms::AlgorithmFactory<ActiveSpaceSelector, ActiveSpaceSelectorFactory>
#include <qdk/chemistry/algorithms/active_space.hpp>

Factory class for creating active space selector instances.

This class provides a mechanism to create active space selector instances based on a string key. It allows for easy extension and registration of different active space selection implementations.

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static void register_default_instances()
template<typename Derived, typename ReturnType, typename ...Args>
class Algorithm
#include <qdk/chemistry/algorithms/algorithm.hpp>

Base class for algorithms.

This class automatically generates a run() method that locks settings and delegates to _run_impl().

Usage:

class ScfSolver : public Algorithm<ScfSolver,
                  std::pair<double, std::shared_ptr<Wavefunction>>,
                  std::shared_ptr<Structure>, int, int> {
 protected:
  std::pair<double, std::shared_ptr<Wavefunction>> _run_impl(
    std::shared_ptr<Structure> structure, int charge, int spin) const
override;
};

Template Parameters:
  • Derived – The derived algorithm class such as ScfSolver

  • ReturnType – The return type of the algorithm’s run() and _run_impl() methods

  • Args – Parameter pack containing the types of input arguments required by the algorithm

Public Functions

Algorithm() = default
virtual ~Algorithm() = default
inline virtual std::vector<std::string> aliases() const

Access the algorithm’s aliases.

The name aliases for this algorithm, including the primary name. By default, returns a vector containing only the primary name.

Returns:

A vector of name aliases

inline virtual std::string hash(Args... args) const

Compute a deterministic content hash for a run with these inputs.

Hashes the algorithm type, algorithm name, current settings, and arguments that would be passed to run(). The result identifies a run for cache and checkpoint/restart workflows among compatible builds.

Parameters:

args – Arguments that would be forwarded to run()

Returns:

16-character hex content hash

virtual std::string name() const = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline virtual ReturnType run(Args... args) const

Auto-generated run() method.

Automatically locks settings and delegates to _run_impl()

Parameters:

args – Arguments forwarded to _run_impl() - types specified by the Args parameter pack

Returns:

ReturnType The result from executing _run_impl()

inline data::Settings &settings()

Access the algorithm’s settings.

Returns:

Reference to the algorithm’s Settings object

virtual std::string type_name() const = 0

Access the algorithm’s type name.

Returns:

The algorithm’s type name

Friends

friend struct detail::DeprecationAccess
template<typename BaseAlgorithmType, typename Derived>
class AlgorithmFactory
#include <qdk/chemistry/algorithms/algorithm.hpp>

Base class template for algorithm factories.

This class provides a generic factory pattern for creating algorithm instances based on string keys. It allows for easy extension and registration of different algorithm implementations.

Template parameters:

Usage:

// Define a concrete factory for ScfSolver
struct ScfSolverFactory : public AlgorithmFactory<ScfSolver> {
  // Optional: override default_key() for custom default behavior
};

// Register implementations
ScfSolverFactory::register_instance("hf", []() {
  return std::make_unique<HartreeFockSolver>();
});

// Create instances
auto solver = ScfSolverFactory::create("hf");

Template Parameters:
  • BaseAlgorithmType – The base algorithm type that every registered implementation inherits from and whose run() signature is enforced.

  • Derived – The factory type that implements algorithm-specific registration helpers (default names, etc.).

Public Types

using functor_type = std::function<return_type(void)>
using return_type = std::unique_ptr<BaseAlgorithmType>

Public Static Functions

static inline std::vector<std::string> available()

Get a list of all available algorithm keys.

This method returns a vector containing all registered keys for algorithm implementations.

Returns:

A vector of strings representing the available algorithm keys.

static inline void clear()

Clear all registered implementations.

This method removes all entries from the registry. Use with caution.

static inline return_type create(const std::string &name = "")

Create an algorithm instance.

This method creates an algorithm based on the provided key. If no key is provided or the key is empty, it defaults to the first registered implementation. To check any returned implementations, for its name use the name() method of the created instance. To list all available implementations, use the available() method of the factory.

Parameters:

name – The name to identify the desired algorithm implementation.

Throws:

std::runtime_error – if the name is not found in the registry.

Returns:

A unique pointer to the created algorithm instance.

static inline bool has(const std::string &key)

Check if a key exists in the registry.

Parameters:

key – The key to check.

Returns:

true if the key exists, false otherwise.

static inline void register_instance(functor_type func)

Register a new algorithm implementation.

This method allows the registration of a new algorithm implementation with a unique key. If the key already exists, an exception is thrown. The algorithm is registered under its primary name and all its aliases.

Parameters:

func – The function that creates the algorithm instance.

Throws:

std::runtime_error – if the key already exists or if type mismatch.

static inline bool unregister_instance(const std::string &key)

Unregister an algorithm implementation.

This method removes a previously registered algorithm implementation from the registry.

Parameters:

key – The key identifying the algorithm implementation to remove.

Returns:

true if the key was found and removed, false otherwise.

class DynamicalCorrelationCalculator : public qdk::chemistry::algorithms::Algorithm<DynamicalCorrelationCalculator, DynamicalCorrelationResult, std::shared_ptr<data::Ansatz>>
#include <qdk/chemistry/algorithms/dynamical_correlation_calculator.hpp>

Base class for reference-derived quantum chemistry methods.

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

See also

data::Ansatz

See also

MP2Calculator

Public Functions

DynamicalCorrelationCalculator() = default

Default constructor.

virtual ~DynamicalCorrelationCalculator() = default

Virtual destructor.

virtual std::string name() const override = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline ReturnType run(Args... args) const

Run main calculation.

This method performs the calculation using the provided ansatz and returns the total energy, the ket wavefunction, and optionally a bra wavefunction for non-Hermitian methods.

Parameters:

args – Arguments to pass to the underlying algorithm, typically an Ansatz (Wavefunction and Hamiltonian) describing the system of interest

Throws:
  • std::runtime_error – if the calculation fails

  • std::invalid_argument – if the Ansatz is invalid

Returns:

A DynamicalCorrelationResult containing the energy, ket wavefunction, and optionally a bra wavefunction

inline std::string type_name() const override

Access the algorithm’s type name.

Returns:

The algorithm’s type name

struct DynamicalCorrelationCalculatorFactory : public qdk::chemistry::algorithms::AlgorithmFactory<DynamicalCorrelationCalculator, DynamicalCorrelationCalculatorFactory>
#include <qdk/chemistry/algorithms/dynamical_correlation_calculator.hpp>

Factory class for creating reference-derived calculator instances.

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static void register_default_instances()
class ElectronicStructureSettings : public qdk::chemistry::data::Settings
#include <qdk/chemistry/algorithms/scf.hpp>

Base class for electronic structure algorithms.

Contains common settings for algorithms that work with electronic structure like basis sets, molecular charge, spin multiplicity.

Public Functions

inline ElectronicStructureSettings()
class HamiltonianConstructor : public qdk::chemistry::algorithms::Algorithm<HamiltonianConstructor, std::shared_ptr<data::Hamiltonian>, std::shared_ptr<data::Orbitals>>
#include <qdk/chemistry/algorithms/hamiltonian.hpp>

Abstract base class for constructing Hamiltonian operators.

This class provides the interface for constructing Hamiltonian operators from orbital data in quantum chemistry calculations. It serves as a base for various Hamiltonian construction methods.

The constructor takes orbital information as input and produces a complete Hamiltonian operator that can be used in subsequent quantum chemistry calculations.

See also

data::Orbitals

See also

data::Settings

Public Functions

HamiltonianConstructor() = default

Default constructor.

Creates a Hamiltonian constructor with default settings.

virtual ~HamiltonianConstructor() = default

Virtual destructor.

Ensures proper cleanup of derived classes.

virtual std::string name() const = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline ReturnType run(Args... args) const

Construct Hamiltonian operator from orbital data.

See also

data::Orbitals

Note

Settings are automatically locked when this method is called and cannot be modified during or after execution.

Throws:
  • std::runtime_error – if Hamiltonian construction fails

  • std::invalid_argument – if orbital data is incomplete or invalid

  • qdk::chemistry::data::SettingsAreLocked – if attempting to modify settings after run) is called

Returns:

The constructed Hamiltonian operator ready for use in quantum chemistry calculations

inline std::string type_name() const final

Access the algorithm’s type name.

Returns:

The algorithm’s type name

struct HamiltonianConstructorFactory : public qdk::chemistry::algorithms::AlgorithmFactory<HamiltonianConstructor, HamiltonianConstructorFactory>
#include <qdk/chemistry/algorithms/hamiltonian.hpp>

Factory class for creating Hamiltonian constructor instances.

The HamiltonianConstructorFactory implements the Factory design pattern to dynamically create and manage different implementations of Hamiltonian constructors. This allows the library to support multiple Hamiltonian construction methods while providing a unified interface for clients.

The factory maintains a registry of constructor implementations identified by string keys. New implementations can be registered at runtime using the register_instance method, and instances can be created using the create method.

Typical usage:

// Register a custom implementation
HamiltonianConstructorFactory::register_instance("my_method", []() {
    return std::make_unique<MyHamiltonianConstructor>();
});

// Create an instance
auto constructor = HamiltonianConstructorFactory::create("my_method");

// Get available implementations
auto available = HamiltonianConstructorFactory::available();

See also

HamiltonianConstructor for the interface implemented by concrete constructors

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static void register_default_instances()
class Localizer : public qdk::chemistry::algorithms::Algorithm<Localizer, std::shared_ptr<data::Wavefunction>, std::shared_ptr<data::Wavefunction>, const std::vector<size_t>&, const std::vector<size_t>&>
#include <qdk/chemistry/algorithms/localization.hpp>

Abstract base class for orbital localization algorithms.

The Localizer class provides a common interface for various orbital localization methods used in quantum chemistry. Orbital localization transforms canonical molecular orbitals (which are typically delocalized across the entire molecule) into localized orbitals that are confined subject to some metric (spatial, bond, etc.).

This class uses the Factory design pattern through LocalizerFactory to allow dynamic creation of different localization algorithms at runtime.

Example usage:

// Create a concrete localizer (e.g., PipekMezeyLocalizer)
auto localizer =
qdk::chemistry::algorithms::LocalizerFactory::create_localizer(
  "qdk_pipek_mezey");
// Create indices for all orbitals
auto all_indices = wavefunction->orbitals->get_all_mo_indices();
auto localized_orbital_wavefunction = localizer->run(wavefunction,
  all_indices, all_indices);

Public Functions

Localizer() = default

Default constructor.

virtual ~Localizer() = default

Virtual destructor for proper inheritance.

virtual std::string name() const = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline ReturnType run(Args... args) const

Localize the given molecular orbitals.

Note

Settings are automatically locked when this method is called and cannot be modified during or after execution.

Note

The specific requirements for the inputs and settings affecting this method may vary by implementation. See the documentation for the specific localizer being used (docstring).

Note

Localizers return a single Aufbau determinant wavefunction with updated orbitals. Localizers may attach derived RDM payloads when their algorithm naturally produces them.

Note

The number of electrons is an input for the MP2NaturalOrbitalLocalizer and VVHVLocalizer. Orbital indices < n_alpha_electrons/n_beta_electrons are treated as occupied, indices >= n_alpha_electrons/n_beta_electrons are treated as virtual.

Note

For restricted orbitals, loc_indices_a and loc_indices_b must be identical

Note

All localizer implementations require sorted index arrays for performance and consistency reasons

Throws:
  • std::runtime_error – If localization fails

  • std::invalid_argument – If the input orbitals are invalid for the specified instance of the localizer

  • qdk::chemistry::data::SettingsAreLocked – if attempting to modify settings after run() is called

  • std::invalid_argument – If loc_indices_a or loc_indices_b are not sorted

  • qdk::chemistry::data::SettingsAreLocked – if attempting to modify settings after run() is called

Returns:

The localized molecular orbitals with updated coefficients.

inline std::string type_name() const final

Access the algorithm’s type name.

Returns:

The algorithm’s type name

struct LocalizerFactory : public qdk::chemistry::algorithms::AlgorithmFactory<Localizer, LocalizerFactory>
#include <qdk/chemistry/algorithms/localization.hpp>

Factory class for creating localizer instances.

This class provides a mechanism to create localizer instances based on a string key. It allows for easy extension and registration of different localization implementations.

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static void register_default_instances()
class MultiConfigurationCalculator : public qdk::chemistry::algorithms::Algorithm<MultiConfigurationCalculator, std::pair<double, std::shared_ptr<data::Wavefunction>>, std::shared_ptr<data::Hamiltonian>, unsigned int, unsigned int>
#include <qdk/chemistry/algorithms/mc.hpp>

Abstract base class for multi-configurational calculations in quantum chemistry.

This class provides the interface for multi-configurational-based quantum chemistry calculations. It serves as a base for various multi-configurational methods, such as Complete Active Space CI (CAS-CI), and other multi-reference quantum mechanical algorithms.

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

See also

data::Settings

Public Functions

MultiConfigurationCalculator() = default

Default constructor.

Creates a multi-configurational calculator with default settings.

virtual ~MultiConfigurationCalculator() = default

Virtual destructor.

Ensures proper cleanup of derived classes.

virtual std::string name() const = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline ReturnType run(Args... args) const

Perform multi-configurational calculation.

This method is auto-generated by the Algorithm base class and automatically locks settings before execution, then delegates to _run_impl().

Note

Settings are automatically locked when this method is called and cannot be modified during or after execution.

Throws:
  • std::runtime_error – if the calculation fails

  • std::invalid_argument – if hamiltonian is invalid

  • qdk::chemistry::data::SettingsAreLocked – if attempting to modify settings after run() is called

Returns:

A pair containing the calculated energy (first) and the resulting multi-configurational wavefunction (second)

inline std::string type_name() const final

Access the algorithm’s type name.

Returns:

The algorithm’s type name

struct MultiConfigurationCalculatorFactory : public qdk::chemistry::algorithms::AlgorithmFactory<MultiConfigurationCalculator, MultiConfigurationCalculatorFactory>
#include <qdk/chemistry/algorithms/mc.hpp>

Factory class for creating multi-configurational calculator instances.

The MultiConfigurationCalculatorFactory implements the Factory design pattern to dynamically create and manage different implementations of multi-configurational calculators. This allows the library to support multiple MC calculation methods while providing a unified interface for clients.

The factory maintains a registry of calculator implementations identified by string keys. New implementations can be registered at runtime using the register_builder method, and instances can be created using the create method.

Typical usage:

// Register a custom implementation
MultiConfigurationCalculatorFactory::register_instance("my_method", []() {
    return std::make_unique<MyMultiConfigurationCalculator>();
});

// Create an instance
auto calculator = MultiConfigurationCalculatorFactory::create("my_method");

// Get available implementations
auto available = MultiConfigurationCalculatorFactory::available();

See also

MultiConfigurationCalculator for the interface implemented by concrete calculators

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static void register_default_instances()
class MultiConfigurationScf : public qdk::chemistry::algorithms::Algorithm<MultiConfigurationScf, std::pair<double, std::shared_ptr<data::Wavefunction>>, std::shared_ptr<data::Orbitals>, unsigned int, unsigned int>
#include <qdk/chemistry/algorithms/mcscf.hpp>

Abstract base class for multi-configurational Self-Consistent Field (MCSCF) calculations.

The MultiConfigurationScf class provides an interface for multi-configurational Self-Consistent Field methods that simultaneously optimize both the molecular orbital coefficients and the configuration interaction coefficients.

The solver takes a Hamiltonian as input and produces the optimized energy and multi-configurational wavefunction.

See also

data::Settings

Public Functions

inline MultiConfigurationScf()

Default constructor.

Creates an MultiConfigurationScf solver with default settings that include an AlgorithmRef entry for multi_configuration_calculator.

virtual ~MultiConfigurationScf() = default

Virtual destructor.

Ensures proper cleanup of derived classes.

virtual std::string name() const = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline ReturnType run(Args... args) const

Perform an MultiConfigurationScf calculation.

The nested HamiltonianConstructor and MultiConfigurationCalculator are created from AlgorithmRef settings automatically.

Note

This method is const as it should not modify the solver’s state

Throws:
  • std::runtime_error – if calculation fails to converge

  • std::invalid_argument – if hamiltonian is invalid

Returns:

A pair containing the calculated energy (first) and the resulting multi-configurational wavefunction (second)

inline std::string type_name() const final

Access the algorithm’s type name.

Returns:

The algorithm’s type name

struct MultiConfigurationScfFactory : public qdk::chemistry::algorithms::AlgorithmFactory<MultiConfigurationScf, MultiConfigurationScfFactory>
#include <qdk/chemistry/algorithms/mcscf.hpp>

Factory class for creating MultiConfigurationScf solver instances.

The MultiConfigurationScfFactory implements the Factory design pattern to dynamically create and manage different implementations of MultiConfigurationScf solvers. This allows the library to support multiple MultiConfigurationScf methods while providing a unified interface for clients.

The factory maintains a registry of solver implementations identified by string keys. New implementations can be registered at runtime using the register_builder method, and instances can be created using the create method.

Typical usage:

// Register a custom implementation
MultiConfigurationScfFactory::register_instance("my_mcscf", []() {
    return std::make_unique<MyMultiConfigurationScf>();
});

// Create an instance
auto mcscf = MultiConfigurationScfFactory::create("my_mcscf");

See also

MultiConfigurationScf for the interface implemented by concrete solvers

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static inline void register_default_instances()
class MultiConfigurationScfSettings : public qdk::chemistry::data::Settings
#include <qdk/chemistry/algorithms/mcscf.hpp>

Settings for MCSCF calculations with nested algorithm references.

Public Functions

inline MultiConfigurationScfSettings()
virtual ~MultiConfigurationScfSettings() = default
class MultiConfigurationSettings : public qdk::chemistry::data::Settings
#include <qdk/chemistry/algorithms/mc.hpp>

Settings class specific to multi-configurational calculations.

This class extends the base Settings class with parameters specific to multi-configurational calculations. It provides default values for commonly used settings in MC calculations such as reduced density matrix generation and convergence thresholds.

See also

data::Settings

Subclassed by qdk::chemistry::algorithms::ProjectedMultiConfigurationSettings

Public Functions

inline MultiConfigurationSettings()

Default constructor.

Creates a multi-configurational settings object with default parameter values.

virtual ~MultiConfigurationSettings() = default

Virtual destructor.

class NuclearDerivativeCalculator : public qdk::chemistry::algorithms::Algorithm<NuclearDerivativeCalculator, NuclearDerivativeResult, std::shared_ptr<data::Structure>, int, int, NuclearDerivativeSeedType, unsigned int>
#include <qdk/chemistry/algorithms/nuclear_derivative.hpp>

Base class for nuclear derivative algorithms.

Implementations compute a total energy and nuclear gradients for a molecular structure. Hessians are returned when requested by settings, and a wavefunction is returned when the selected energy path naturally produces one.

Public Functions

inline NuclearDerivativeCalculator()

Construct a calculator with nuclear derivative settings.

virtual ~NuclearDerivativeCalculator() = default
virtual std::string name() const = 0
inline ReturnType run(Args... args) const

Compute nuclear derivatives for a molecular structure.

This method is auto-generated by the Algorithm base class and automatically locks settings before execution, then delegates to _run_impl().

Note

Settings are automatically locked when this method is called and cannot be modified during or after execution.

Throws:
  • std::invalid_argument – If the molecular charge, spin multiplicity, electron count, or inactive-orbital count is inconsistent

  • qdk::chemistry::data::SettingsAreLocked – If attempting to modify settings after run() is called

Returns:

Energy, gradients, optional Hessian, and optional wavefunction.

inline std::string type_name() const final

Return the factory type name for nuclear derivative calculators.

struct NuclearDerivativeCalculatorFactory : public qdk::chemistry::algorithms::AlgorithmFactory<NuclearDerivativeCalculator, NuclearDerivativeCalculatorFactory>
#include <qdk/chemistry/algorithms/nuclear_derivative.hpp>

Factory for nuclear derivative calculator implementations.

Public Static Functions

static inline std::string algorithm_type_name()

Return the algorithm type name managed by this factory.

static inline std::string default_algorithm_name()

Return the default nuclear derivative implementation name.

static void register_default_instances()

Register built-in nuclear derivative calculator implementations.

class NuclearDerivativeSettings : public qdk::chemistry::data::Settings
#include <qdk/chemistry/algorithms/nuclear_derivative.hpp>

Settings for nuclear derivative calculations.

Public Functions

inline NuclearDerivativeSettings()

Construct settings with shared nuclear derivative defaults.

class ProjectedMultiConfigurationCalculator : public qdk::chemistry::algorithms::Algorithm<ProjectedMultiConfigurationCalculator, std::pair<double, std::shared_ptr<data::Wavefunction>>, std::shared_ptr<data::Hamiltonian>, const std::vector<data::Configuration>&>
#include <qdk/chemistry/algorithms/pmc.hpp>

Abstract base class for projected multi-configurational 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 energy and the corresponding multi-configurational wavefunction.

See also

data::Settings

Public Functions

ProjectedMultiConfigurationCalculator() = default

Default constructor.

Creates a projected multi-configurational calculator with default settings.

virtual ~ProjectedMultiConfigurationCalculator() = default

Virtual destructor.

Ensures proper cleanup of derived classes.

virtual std::string name() const = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline ReturnType run(Args... args) const

Perform projected multi-configurational calculation.

Note

Settings are automatically locked when this method is called and cannot be modified during or after execution.

Throws:
  • std::runtime_error – if the calculation fails

  • std::invalid_argument – if hamiltonian is invalid

  • std::invalid_argument – if configurations is invalid

  • qdk::chemistry::data::SettingsAreLocked – if attempting to modify settings after run() is called

Returns:

A pair containing the calculated energy (first) and the resulting multi-configurational wavefunction (second)

inline std::string type_name() const final

Access the algorithm’s type name.

Returns:

The algorithm’s type name

struct ProjectedMultiConfigurationCalculatorFactory : public qdk::chemistry::algorithms::AlgorithmFactory<ProjectedMultiConfigurationCalculator, ProjectedMultiConfigurationCalculatorFactory>
#include <qdk/chemistry/algorithms/pmc.hpp>

Factory class for creating projected multi-configurational calculator instances.

The ProjectedMultiConfigurationCalculatorFactory implements the Factory design pattern to dynamically create and manage different implementations of projected multi-configurational calculators. This allows the library to support multiple PMC calculation methods while providing a unified interface for clients.

The factory maintains a registry of calculator implementations identified by string keys. New implementations can be registered at runtime using the register_builder method, and instances can be created using the create method.

Typical usage:

// Register a custom implementation
ProjectedMultiConfigurationCalculatorFactory::register_instance("my_method",
[]() { return std::make_unique<MyProjectedMultiConfigurationCalculator>();
});

// Create an instance
auto calculator =
ProjectedMultiConfigurationCalculatorFactory::create("my_method");

// Get available implementations
auto available = ProjectedMultiConfigurationCalculatorFactory::available();

See also

ProjectedMultiConfigurationCalculator for the interface implemented by concrete calculators

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static void register_default_instances()
class ProjectedMultiConfigurationSettings : public qdk::chemistry::algorithms::MultiConfigurationSettings
#include <qdk/chemistry/algorithms/pmc.hpp>

Settings class specific to multi-configurational calculations.

This class extends the base Settings class with parameters specific to projected multi-configurational calculations. It provides default values for commonly used settings in PMC calculations such as reduced density matrix generation and convergence thresholds.

See also

data::Settings

Public Functions

inline ProjectedMultiConfigurationSettings()

Default constructor.

Creates a multi-configurational settings object with default parameter values. It inherits default settings from MultiConfigurationSettings.

virtual ~ProjectedMultiConfigurationSettings() = default

Virtual destructor.

class ScfSolver : public qdk::chemistry::algorithms::Algorithm<ScfSolver, std::pair<double, std::shared_ptr<data::Wavefunction>>, std::shared_ptr<data::Structure>, int, int, BasisOrGuessType>
#include <qdk/chemistry/algorithms/scf.hpp>

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

The ScfSolver class provides a common interface for various SCF algorithms used in quantum chemistry calculations. This class uses the Factory design pattern to enable the dynamic creation of different SCF solver implementations.

The solver takes a molecular structure as input and produces the converged total energy (electronic + nuclear repulsion) and corresponding molecular orbitals and single determinant wavefunction.

Example usage:

// Create a concrete SCF solver (e.g., HartreeFockSolver)
auto scf_solver = qdk::chemistry::ScfSolver::create("default");

// Configure solver settings
scf_solver->settings().set("max_iterations", 100);

// Perform SCF calculation
auto [energy, wavefunction] = scf_solver->run(molecular_structure, 0, 1,
"cc-pvdz");

std::cout << "SCF Total Energy: " << energy << " Hartree" << std::endl;

Public Functions

inline ScfSolver()

Default constructor.

virtual ~ScfSolver() = default

Virtual destructor for proper inheritance.

virtual std::string name() const = 0

Access the algorithm’s name.

Returns:

The algorithm’s name

inline ReturnType run(Args... args) const

Solve the SCF equations for a given molecular structure.

This method performs the iterative SCF procedure to find the self-consistent molecular orbitals and total energy.

The specific algorithm (HF, DFT, etc.) is determined by the concrete implementation.

Note

Settings are automatically locked when this method is called and cannot be modified during or after execution.

Note

The specific requirements for the inputs and settings affecting the SCF calculation may vary by implementation. See the documentation for the specific SCF solver being used.

Throws:
  • std::runtime_error – If SCF fails to converge

  • std::invalid_argument – If the input structure is invalid

  • qdk::chemistry::data::SettingsAreLocked – If attempting to modify settings after run() is called

Returns:

A pair containing:

  • double: The converged total energy in Hartree

  • data::Wavefunction: The converged wavefunction, including orbitals, their energies, coefficients, and occupancies

inline std::string type_name() const final

Access the algorithm’s type name.

Returns:

The algorithm’s type name

struct ScfSolverFactory : public qdk::chemistry::algorithms::AlgorithmFactory<ScfSolver, ScfSolverFactory>
#include <qdk/chemistry/algorithms/scf.hpp>

Factory class for creating SCF solvers.

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static void register_default_instances()
class StabilityChecker : public qdk::chemistry::algorithms::Algorithm<StabilityChecker, std::pair<bool, std::shared_ptr<data::StabilityResult>>, std::shared_ptr<data::Wavefunction>>
#include <qdk/chemistry/algorithms/stability.hpp>

Abstract base class for wavefunction stability checking algorithms with respect to orbital rotation.

The StabilityChecker class provides a common interface for various stability checking methods used in quantum chemistry. 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.

This class uses the Factory design pattern through StabilityCheckerFactory to allow dynamic creation of different stability checking algorithms at runtime.

Example usage:

// Create a concrete stability checker
auto checker =
qdk::chemistry::algorithms::StabilityCheckerFactory::create("pyscf");

// Configure checker settings
checker->settings().set("nroots", 5);

// Perform stability check
auto [is_stable, result] = checker->run(wavefunction);

if (is_stable) {
  std::cout << "Wavefunction is stable" << std::endl;
} else {
  std::cout << "Wavefunction is unstable" << std::endl;
}
auto smallest_eigenvalue = result->get_smallest_eigenvalue();
std::cout << "Smallest eigenvalue: " << smallest_eigenvalue << std::endl;

Public Functions

StabilityChecker() = default

Default constructor.

virtual ~StabilityChecker() = default

Virtual destructor for proper inheritance.

virtual std::string name() const override = 0
inline ReturnType run(Args... args) const

Check the stability of the given wavefunction with respect to orbital rotation.

This method performs stability analysis on the input wavefunction by examining the eigenvalues of the electronic Hessian matrix. A stable wavefunction should have all non-negative eigenvalues. Near-zero eigenvalues may indicate orbital degeneracy.

The specific algorithm (PySCF-based, etc.) is determined by the concrete implementation.

Note

Settings are automatically locked when this method is called and cannot be modified during or after execution.

Note

The specific requirements for the inputs and settings affecting the stability check may vary by implementation. See the documentation for the specific stability checker being used.

Throws:
  • std::runtime_error – If stability analysis fails

  • std::invalid_argument – If the input wavefunction is invalid for the specified instance of the stability checker

  • qdk::chemistry::data::SettingsAreLocked – If attempting to modify settings after run() is called

Returns:

A pair containing:

  • bool: Overall stability status (true if stable, false if unstable)

  • data::StabilityResult: Detailed stability information including eigenvalues and eigenvectors of the stability matrix, which can be used to start a new SCF calculation if an instability is detected.

inline std::string type_name() const override
struct StabilityCheckerFactory : public qdk::chemistry::algorithms::AlgorithmFactory<StabilityChecker, StabilityCheckerFactory>
#include <qdk/chemistry/algorithms/stability.hpp>

Factory class for creating stability checker instances.

This class provides a mechanism to create stability checker instances based on a string key. It allows for easy extension and registration of different stability checking implementations.

Public Static Functions

static inline std::string algorithm_type_name()
static inline std::string default_algorithm_name()
static void register_default_instances()
namespace detail

Functions

std::vector<size_t> _get_inactive_space_indices(size_t nelec, const std::vector<size_t> &active_space_indices)

Helper function to determine inactive space indices for restricted orbitals.

Parameters:
  • nelec – Number of electrons

  • active_space_indices – Active space orbital indices

Returns:

Vector of inactive space orbital indices

std::pair<std::vector<size_t>, std::vector<size_t>> _get_inactive_space_indices(size_t nelec_a, size_t nelec_b, const std::vector<size_t> &active_space_indices_a, const std::vector<size_t> &active_space_indices_b)

Helper function to determine inactive space indices for unrestricted orbitals.

Parameters:
  • nelec_a – Number of alpha electrons

  • nelec_b – Number of beta electrons

  • active_space_indices_a – Alpha active space orbital indices

  • active_space_indices_b – Beta active space orbital indices

Returns:

Pair of vectors containing (alpha_inactive_space_indices, beta_inactive_space_indices)

std::tuple<double, std::vector<size_t>, Eigen::VectorXd> _sort_entropies_and_indices(std::shared_ptr<data::Wavefunction> wavefunction, bool normalize_entropies)

Helper function to sort entropies and their corresponding orbital indices in descending order.

Parameters:
  • wavefunction – The wavefunction containing orbital entropies and indices.

  • normalize_entropies – If true, normalize entropies by the maximum entropy value.

Throws:

std::runtime_error – if the wavefunction does not have single orbital entropies.

Returns:

A pair containing a vector of sorted orbital indices and a vector of sorted entropies.

bool is_aufbau_determinant_wavefunction(std::shared_ptr<data::Wavefunction> wavefunction)

Check whether a wavefunction is exactly the Aufbau determinant.

An Aufbau determinant wavefunction contains a single determinant with the canonical Aufbau occupation implied by its electron counts.

Parameters:

wavefunction – The wavefunction to check.

Returns:

True if the wavefunction is exactly the Aufbau determinant.

std::shared_ptr<data::Wavefunction> new_aufbau_determinant_wavefunction(std::shared_ptr<data::Wavefunction> wavefunction, std::shared_ptr<data::Orbitals> new_orbitals, std::optional<data::ContainerTypes::MatrixVariant> one_rdm_spin_traced = std::nullopt)

Create an Aufbau determinant wavefunction with updated orbitals.

The returned wavefunction contains the canonical Aufbau determinant with a new set of orbitals.

Parameters:
  • wavefunction – The original wavefunction providing electron counts.

  • new_orbitals – The orbitals to attach to the output wavefunction.

  • one_rdm_spin_traced – Optional spin-traced active-space 1-RDM payload.

Returns:

An Aufbau determinant wavefunction with the updated orbitals.

std::shared_ptr<data::Orbitals> new_orbitals(std::shared_ptr<data::Wavefunction> wavefunction, const std::vector<size_t> &active_space_indices_a, const std::optional<std::vector<size_t>> &active_space_indices_b = std::nullopt)

Create a new Orbitals object with the specified active space indices.

Parameters:
  • wavefunction – The wavefunction containing the orbitals.

  • active_space_indices_a – The active space orbital indices for alpha electrons.

  • active_space_indices_b – The active space orbital indices for beta electrons (optional for restricted orbitals).

Returns:

A new Orbitals object with the specified active space indices.

std::shared_ptr<data::Wavefunction> new_wavefunction(std::shared_ptr<data::Wavefunction> wavefunction, std::shared_ptr<data::Orbitals> new_orbitals)

Create a new Wavefunction object with updated orbitals.

Generate a new Wavefunction by replacing the orbitals of the given wavefunction with the provided new orbitals, keeping the identical total, determinants.

Parameters:
  • wavefunction – The original wavefunction.

  • new_orbitals – The new orbitals to set in the wavefunction.

Returns:

A new Wavefunction object with the updated orbitals.

std::shared_ptr<data::Settings> resolve_algorithm_defaults(const std::string &type, const std::string &name)

Resolve default settings for a given algorithm type and name using the C++ factory dispatch.

void warn_if_not_aufbau_determinant_wavefunction(std::shared_ptr<data::Wavefunction> wavefunction, const std::string &localizer_name)

Log a warning when a localizer receives a non-Aufbau wavefunction.

Localizers transform orbitals and return an Aufbau determinant wavefunction; correlated-state coefficients from a multi-determinant input are not carried through the transformation.

Parameters:
  • wavefunction – The wavefunction to check.

  • localizer_name – Name of the localizer issuing the warning.

struct DeprecationAccess
#include <qdk/chemistry/algorithms/algorithm.hpp>

Internal reader for protected deprecation-warning hooks.

This is intentionally the only non-derived access path to Algorithm::_deprecation_message(). It lets factories and language bindings emit the same construction-time warnings without exposing deprecation metadata as part of the public Algorithm API.

Public Static Functions

template<typename Derived, typename ReturnType, typename ...Args>
static inline std::optional<std::string> message(const Algorithm<Derived, ReturnType, Args...> &algorithm)
namespace constants

Functions

inline std::unordered_map<std::string, ConstantInfo> get_constants_info()

Get documentation information for all constants in the current namespace.

This function returns documentation for constants using the currently active CODATA version (determined by the using namespace directive below).

Returns:

Map of constant names to their documentation

constexpr const char *get_current_codata_version()

Variables

static constexpr std::array<std::array<size_t, 4>, 119> ATOMIC_CONFIGURATION

Non-relativistic spin-restricted spherical HF configurations.

Each entry corresponds to an element with atomic number Z and contains the number of electrons in each subshell: s, p, d, f

Reference: Lehtola, S. (2020). “Fully numerical calculations on atoms with

fractional occupations and range-separated functionals” Phys. Rev. A. 10.1103/physreva.101.012516

struct ConstantInfo
#include <qdk/chemistry/constants.hpp>

Documentation metadata for physical constants.

Public Members

std::string description
std::string name
std::string source
std::string symbol
std::string units
double value
namespace codata_2014

CODATA 2014 recommended values for fundamental physical constants.

Constants from the 2014 CODATA recommended values of the fundamental physical constants: https://physics.nist.gov/cuu/Constants/. [MNT16]

Variables

static constexpr double angstrom_to_bohr = 1.0 / bohr_to_angstrom
static constexpr double atomic_mass_constant = 1.660539040e-27
static constexpr double avogadro_constant = 6.022140857e23
static constexpr double bohr_to_angstrom = 0.52917721067
static constexpr double boltzmann_constant = 1.38064852e-23
static constexpr double electron_mass = 9.10938356e-31
static constexpr double elementary_charge = 1.6021766208e-19
static constexpr double ev_to_hartree = 1.0 / hartree_to_ev
static constexpr double fine_structure_constant = 7.2973525664e-3
static constexpr double hartree_to_ev = 27.21138602
static constexpr double hartree_to_kcal_per_mol = 627.509474
static constexpr double hartree_to_kj_per_mol = 2625.49964
static constexpr double kcal_per_mol_to_hartree = 1.0 / hartree_to_kcal_per_mol
static constexpr double kj_per_mol_to_hartree = 1.0 / hartree_to_kj_per_mol
static constexpr double neutron_mass = 1.674927471e-27
static constexpr double planck_constant = 6.626070040e-34
static constexpr double proton_mass = 1.672621898e-27
static constexpr double reduced_planck_constant = planck_constant / (2.0 * 3.14159265358979323846)
static constexpr double speed_of_light = 299792458.0
namespace codata_2018

CODATA 2018 recommended values for fundamental physical constants.

Constants from the 2018 CODATA recommended values of the fundamental physical constants: https://physics.nist.gov/cuu/Constants/. [TMNT21]

Variables

static constexpr double angstrom_to_bohr = 1.0 / bohr_to_angstrom
static constexpr double atomic_mass_constant = 1.66053906660e-27
static constexpr double avogadro_constant = 6.02214076e23
static constexpr double bohr_to_angstrom = 0.529177210903
static constexpr double boltzmann_constant = 1.380649e-23
static constexpr double electron_mass = 9.1093837015e-31
static constexpr double elementary_charge = 1.602176634e-19
static constexpr double ev_to_hartree = 1.0 / hartree_to_ev
static constexpr double fine_structure_constant = 7.2973525693e-3
static constexpr double hartree_to_ev = 27.211386245988
static constexpr double hartree_to_kcal_per_mol = 627.5094736
static constexpr double hartree_to_kj_per_mol = 2625.4996395
static constexpr double kcal_per_mol_to_hartree = 1.0 / hartree_to_kcal_per_mol
static constexpr double kj_per_mol_to_hartree = 1.0 / hartree_to_kj_per_mol
static constexpr double neutron_mass = 1.67492749804e-27
static constexpr double planck_constant = 6.62607015e-34
static constexpr double proton_mass = 1.67262192369e-27
static constexpr double reduced_planck_constant = planck_constant / (2.0 * 3.14159265358979323846)
static constexpr double speed_of_light = 299792458.0
namespace codata_2022

CODATA 2022 recommended values for fundamental physical constants.

Constants from the 2022 CODATA recommended values of the fundamental physical constants: https://physics.nist.gov/cuu/Constants/. [MNT25]

Variables

static constexpr double angstrom_to_bohr = 1.0 / bohr_to_angstrom
static constexpr double atomic_mass_constant = 1.66053906892e-27
static constexpr double avogadro_constant = 6.02214076e23
static constexpr double bohr_to_angstrom = 0.529177210544
static constexpr double boltzmann_constant = 1.380649e-23
static constexpr double electron_mass = 9.1093837139e-31
static constexpr double elementary_charge = 1.602176634e-19
static constexpr double ev_to_hartree = 1.0 / hartree_to_ev
static constexpr double fine_structure_constant = 7.2973525643e-3
static constexpr double hartree_to_ev = 27.211386245981
static constexpr double hartree_to_kcal_per_mol = hartree_to_kj_per_mol / 4.184
static constexpr double hartree_to_kj_per_mol = hartree_to_ev * 1.602176634 * 6.02214076 * 10
static constexpr double kcal_per_mol_to_hartree = 1.0 / hartree_to_kcal_per_mol
static constexpr double kj_per_mol_to_hartree = 1.0 / hartree_to_kj_per_mol
static constexpr double neutron_mass = 1.67492750056e-27
static constexpr double planck_constant = 6.62607015e-34
static constexpr double proton_mass = 1.67262192595e-27
static constexpr double reduced_planck_constant = planck_constant / (2.0 * 3.14159265358979323846)
static constexpr double speed_of_light = 299792458.0
namespace data

Typedefs

using Constraint = std::variant<BoundConstraint<int64_t>, ListConstraint<int64_t>, BoundConstraint<double>, ListConstraint<std::string>>

Type for specifying limits on setting values.

using EdgeColoring = std::map<std::pair<std::uint64_t, std::uint64_t>, int>

Edge coloring as a map from ordered (i, j) (with i < j) to a non-negative integer color label.

Two edges sharing the same color have disjoint vertex sets.

using SettingValue = std::variant<bool, int64_t, double, std::string, std::vector<int64_t>, std::vector<double>, std::vector<std::string>, AlgorithmRef>

Type-safe variant for storing different setting value types.

This variant can hold common types used in settings configurations. Note: All integer types are stored internally as int64_t (signed). Other integer types can be requested via get() with automatic conversion.

template<std::size_t Rank, class Scalar = double>
using SparseMapBlock = std::map<std::array<unsigned, Rank>, Scalar>

Per-block sparse storage: maps an index tuple to a scalar value.

Each key is an std::array<unsigned, Rank> of per-slot local indices (offsets within the block’s declared extents).

Template Parameters:
  • Rank – Number of index slots.

  • Scalar – Element type (default double).

using SparsePauliWord = std::vector<std::pair<std::uint64_t, std::uint8_t>>

A sparse representation of a Pauli string (tensor product of Pauli operators).

Each element is a (qubit_index, operator_type) pair where operator_type is:

  • 0: Identity (I) - typically not stored in sparse representation

  • 1: Pauli X

  • 2: Pauli Y

  • 3: Pauli Z

The vector is kept sorted by qubit_index for efficient comparison and hashing. An empty SparsePauliWord represents the identity operator.

Example: X(0) * Z(2) * Y(5) would be represented as: [(0, 1), (2, 3), (5, 2)]

template<std::size_t Rank>
using SymmetryBlockedTensorVariant = std::variant<SymmetryBlockedTensor<Rank, double>, SymmetryBlockedTensor<Rank, std::complex<double>>>

Variant of real- and complex-valued SymmetryBlockedTensor at a fixed rank.

Mirrors the ContainerTypes::MatrixVariant / ContainerTypes::VectorVariant pattern: API surfaces that need to expose either a real or a complex symmetry-blocked tensor (e.g. spin-dependent RDMs from a complex wavefunction) return this alias and let consumers dispatch with std::visit or std::holds_alternative.

Template Parameters:

Rank – Tensor rank (1, 2, 3, or 4 are instantiated).

template<std::size_t Rank, class Scalar = double>
using Tensor = std::conditional_t<(Rank == 1 || Rank == 4), Eigen::Matrix<Scalar, Eigen::Dynamic, 1>, Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>>

Storage type for one block of a rank-Rank tensor over Scalar.

Rank-1 and rank-4 blocks are stored as (flat) dense column vectors; rank-2 and rank-3 blocks are stored as dense matrices. (Rank-3 blocks are typically packed as [outer*outer, inner] for two paired index slots plus one trailing index, e.g. a Cholesky three-center factor \(L^{Q}_{ij}\) stored as \([ij,\,Q]\); the size is validated against the product of the per-slot extents and the precise row/column split is producer-chosen.) Only ranks 1–4 are supported; SymmetryBlockedTensor rejects other ranks.

Enums

enum class AmplitudeType

Identifies the correlated method that produced an amplitude wavefunction.

Because all amplitude-based wavefunctions share a single container type, this tag lets downstream consumers know how to interpret the stored amplitudes (for example, first-order perturbative doubles versus an exponential coupled-cluster ansatz).

Values:

enumerator MollerPlesset

Moller-Plesset perturbation theory.

enumerator CoupledCluster

Coupled cluster theory.

enumerator Unspecified

Producer did not record a type (e.g. legacy data)

enum class AOType

Enumeration for atomic orbital types (spherical vs cartesian)

Values:

enumerator Spherical

Spherical harmonics (2l+1 functions per shell)

enumerator Cartesian

Cartesian coordinates (more functions for l>=2)

enum class AxisName

Symmetry axis identifier.

Values:

enumerator Spin

The spin ( \(S_z\)) axis carrying SpinValue labels.

enum class Element : unsigned

Enumeration for chemical elements in the periodic table (1-118)

Values:

enumerator H
enumerator He
enumerator Li
enumerator Be
enumerator B
enumerator C
enumerator N
enumerator O
enumerator F
enumerator Ne
enumerator Na
enumerator Mg
enumerator Al
enumerator Si
enumerator P
enumerator S
enumerator Cl
enumerator Ar
enumerator K
enumerator Ca
enumerator Sc
enumerator Ti
enumerator V
enumerator Cr
enumerator Mn
enumerator Fe
enumerator Co
enumerator Ni
enumerator Cu
enumerator Zn
enumerator Ga
enumerator Ge
enumerator As
enumerator Se
enumerator Br
enumerator Kr
enumerator Rb
enumerator Sr
enumerator Y
enumerator Zr
enumerator Nb
enumerator Mo
enumerator Tc
enumerator Ru
enumerator Rh
enumerator Pd
enumerator Ag
enumerator Cd
enumerator In
enumerator Sn
enumerator Sb
enumerator Te
enumerator I
enumerator Xe
enumerator Cs
enumerator Ba
enumerator La
enumerator Ce
enumerator Pr
enumerator Nd
enumerator Pm
enumerator Sm
enumerator Eu
enumerator Gd
enumerator Tb
enumerator Dy
enumerator Ho
enumerator Er
enumerator Tm
enumerator Yb
enumerator Lu
enumerator Hf
enumerator Ta
enumerator W
enumerator Re
enumerator Os
enumerator Ir
enumerator Pt
enumerator Au
enumerator Hg
enumerator Tl
enumerator Pb
enumerator Bi
enumerator Po
enumerator At
enumerator Rn
enumerator Fr
enumerator Ra
enumerator Ac
enumerator Th
enumerator Pa
enumerator U
enumerator Np
enumerator Pu
enumerator Am
enumerator Cm
enumerator Bk
enumerator Cf
enumerator Es
enumerator Fm
enumerator Md
enumerator No
enumerator Lr
enumerator Rf
enumerator Db
enumerator Sg
enumerator Bh
enumerator Hs
enumerator Mt
enumerator Ds
enumerator Rg
enumerator Cn
enumerator Nh
enumerator Fl
enumerator Mc
enumerator Lv
enumerator Ts
enumerator Og
enum class HamiltonianType

Types of Hamiltonians supported.

Values:

enumerator Hermitian
enumerator NonHermitian
enum class OrbitalType

Enumeration for different types of atomic orbitals.

Values:

enumerator UL

ECP local potential (l=-1)

enumerator S

S orbital (angular momentum l=0)

enumerator P

P orbital (angular momentum l=1)

enumerator D

D orbital (angular momentum l=2)

enumerator F

F orbital (angular momentum l=3)

enumerator G

G orbital (angular momentum l=4)

enumerator H

H orbital (angular momentum l=5)

enumerator I

I orbital (angular momentum l=6)

enum class SpinChannel

Spin channels for one and two-electron integrals.

Values:

enumerator aa
enumerator bb
enumerator aaaa
enumerator aabb
enumerator bbbb
enum class WavefunctionType

Enum to distinguish between different wavefunction representations.

This enum allows tagging wavefunctions based on their mathematical role:

  • SelfDual: Wavefunctions that can be used as both bra and ket

  • NotSelfDual: Wavefunctions that are strictly bra or ket

This distinction maps to the use of hermitian or non-hermitian operators.

Values:

enumerator SelfDual
enumerator NotSelfDual

Functions

AmplitudeType amplitude_type_from_string(const std::string &s)

Parse an AmplitudeType from its serialization string.

Parameters:

s – String identifier (“moller_plesset”, “coupled_cluster”, or “unspecified”; legacy aliases “mp2” and “ccsd” are also accepted)

Returns:

Corresponding AmplitudeType; unrecognized strings map to Unspecified

std::string amplitude_type_to_string(AmplitudeType type)

Convert an AmplitudeType to its serialization string.

Parameters:

type – Amplitude type

Returns:

Lowercase string identifier (“moller_plesset”, “coupled_cluster”, or “unspecified”)

EdgeColoring chain_coloring(std::int64_t n, bool periodic)

Deterministic optimal edge coloring for a chain (path / ring).

Parameters:
  • n – Number of sites in the chain.

  • periodic – Whether the chain wraps around (ring topology).

Returns:

Edge coloring using 2 colours (open or even-periodic) or 3 colours (odd-periodic).

constexpr const char *get_current_ciaaw_version()
EdgeColoring greedy_edge_coloring(const Eigen::SparseMatrix<double> &adj, int seed = 0, int trials = 1)

Greedy randomised edge coloring of an arbitrary graph.

Shuffles the edge order and assigns each edge the lowest colour not incident to either endpoint. Repeats for trials shuffles (with deterministic PRNG seeded by seed) and returns the result with the fewest colours.

Parameters:
  • adj – Sparse adjacency matrix of the graph.

  • seed – Random seed. Default: 0.

  • trials – Number of random-order trials. Default: 1.

Returns:

Edge coloring with the fewest distinct colours found.

inline void hash_value(qdk::chemistry::utils::HashContext &ctx, const DataClass &value)

Hash a DataClass by its content hash.

Parameters:
  • ctx – Hash context to update

  • value – Data object to hash

void hash_value(qdk::chemistry::utils::HashContext &ctx, const SymmetryAxisValue &value)

Hash a symmetry axis value without routing through JSON.

Parameters:
  • ctx – Hash context to update.

  • value – Axis value to hash.

void hash_value(qdk::chemistry::utils::HashContext &ctx, const SymmetryLabel &label)

Hash a symmetry label without routing through JSON.

Parameters:
  • ctx – Hash context to update.

  • label – Label to hash.

EdgeColoring honeycomb_coloring(std::int64_t nx, std::int64_t ny, bool periodic_x, bool periodic_y)

Deterministic optimal 3-coloring for a honeycomb lattice.

Parameters:
  • nx – Number of unit cells along x.

  • ny – Number of unit cells along y.

  • periodic_x – Whether periodic boundary conditions are applied along x.

  • periodic_y – Whether periodic boundary conditions are applied along y.

Returns:

Edge coloring using exactly 3 colours (one per bond type).

SparsePauliWord label_to_sparse_pauli_word(const std::string &label)

Convert a QubitOperator label to a sparse Pauli word.

The input label uses the QubitOperator convention: qubit 0 is the rightmost character. Identity characters are omitted from the output.

Parameters:

label – Dense Pauli-string label (e.g. “XIZZ”).

Throws:

std::invalid_argument – If the label contains invalid characters.

Returns:

Sparse Pauli word sorted by qubit index.

MajoranaMapResult majorana_map_hamiltonian(const MajoranaMapping &mapping, const Hamiltonian &hamiltonian, bool spin_symmetric, double threshold, double integral_threshold)

Map a fermionic Hamiltonian to qubit Pauli terms.

Dispatches to the dense, Cholesky, or sparse engine entry point based on the Hamiltonian’s container type, without materializing a dense N^4 two-body tensor when a specialized container is present. One-body integrals are flattened to row-major layout internally.

The constant energy shift (nuclear repulsion / frozen core) is excluded from the mapped operator (core_energy = 0), matching the buffer-based overload as invoked by QdkQubitMapper.

Parameters:
  • mapping – The Majorana-to-Pauli encoding.

  • hamiltonian – The fermionic Hamiltonian.

  • spin_symmetric – Use the spin-summed restricted fast path when true.

  • threshold – Pauli terms with |coeff| < threshold are dropped.

  • integral_threshold – Integrals with |value| < this are skipped.

Returns:

MajoranaMapResult with Pauli words and coefficients.

MajoranaMapResult majorana_map_hamiltonian(const MajoranaMapping &mapping, double core_energy, const double *h1_alpha, const double *h1_beta, const double *eri_aaaa, const double *eri_aabb, const double *eri_bbbb, std::size_t n_spatial, bool spin_symmetric, double threshold, double integral_threshold)

Map a fermionic Hamiltonian to qubit Pauli terms via Majorana loops.

Decomposes each fermionic operator into Majorana products, looks up each gamma_k in the mapping, and accumulates the resulting Pauli words.

Parameters:
  • mapping – The Majorana-to-Pauli encoding.

  • core_energy – Core (nuclear repulsion + frozen core) energy.

  • h1_alpha – One-body integrals, alpha spin (n_spatial x n_spatial).

  • h1_beta – One-body integrals, beta spin (n_spatial x n_spatial).

  • eri_aaaa – Flattened two-body integrals (aa|aa), chemist notation.

  • eri_aabb – Flattened two-body integrals (aa|bb), chemist notation.

  • eri_bbbb – Flattened two-body integrals (bb|bb), chemist notation.

  • n_spatial – Number of spatial orbitals.

  • spin_symmetric – If true, use the spin-summed fast path. This assumes identical integrals across all spin channels (h_alpha == h_beta, eri_aaaa == eri_bbbb == eri_aabb), as produced by restricted orbitals. For unrestricted orbital sets, pass false — the engine handles each spin channel independently.

  • threshold – Pauli terms with |coeff| < threshold are dropped.

  • integral_threshold – Integrals with |value| < this are skipped.

Returns:

MajoranaMapResult with Pauli words and coefficients.

MajoranaMapResult majorana_map_hamiltonian_cholesky(const MajoranaMapping &mapping, double core_energy, const double *h1_alpha, const double *h1_beta, const double *three_center_aa, const double *three_center_bb, std::size_t n_spatial, std::size_t naux, bool spin_symmetric, double threshold, double integral_threshold)

Map a fermionic Hamiltonian to qubit Pauli terms directly from three-center (Cholesky/density-fitted) two-body factors.

Equivalent to majorana_map_hamiltonian but consumes the low-rank factors instead of a dense N^4 tensor. The auxiliary index is contracted in integral space one (pq|.) row at a time — a vectorized matrix-vector product per orbital pair — so the dense four-center tensor is never materialized and peak additional memory is a single N^2 row. The result is numerically equivalent to the dense path for the same integrals.

Parameters:
  • mapping – The Majorana-to-Pauli encoding.

  • core_energy – Core (nuclear repulsion + frozen core) energy.

  • h1_alpha – One-body integrals, alpha spin (n_spatial x n_spatial), row-major.

  • h1_beta – One-body integrals, beta spin (row-major).

  • three_center_aa – Alpha three-center factors, column-major [n_spatial^2 x naux] with the orbital pair index in row-major order.

  • three_center_bb – Beta three-center factors (same layout). For restricted inputs this may alias three_center_aa.

  • n_spatial – Number of spatial orbitals.

  • naux – Number of auxiliary (Cholesky) vectors.

  • spin_symmetric – If true, use the spin-summed restricted fast path.

  • threshold – Pauli terms with |coeff| < threshold are dropped.

  • integral_threshold – Integrals with |value| < this are skipped.

Returns:

MajoranaMapResult with Pauli words and coefficients.

MajoranaMapResult majorana_map_hamiltonian_sparse(const MajoranaMapping &mapping, double core_energy, const double *h1_alpha, const double *h1_beta, const int *two_body_indices, const double *two_body_values, std::size_t num_entries, std::size_t n_spatial, bool spin_symmetric, double threshold, double integral_threshold)

Map a fermionic Hamiltonian to qubit Pauli terms directly from a sparse two-body integral list.

Equivalent to majorana_map_hamiltonian but consumes the stored non-zero (p,q,r,s) integrals instead of a dense N^4 tensor, which is never materialized. Missing entries are treated as zero, exactly as in the dense layout.

Stored entries are canonicalized under the 8-fold ERI symmetry and symmetry-expanded before mapping. The dense reference path for SparseHamiltonianContainer materializes each stored tuple at its exact index with no symmetry expansion, so the two paths agree when stored integrals are canonical or symmetry-complete (as for in-repo model builders), while this entry point is more robust when a container stores only non-canonical symmetry representatives.

Entries are canonicalized under the 8-fold ERI symmetry at ingestion (p<=q, r<=s, (p,q)<=(r,s)) and deduplicated deterministically, so the mapped operator does not depend on which symmetry-related permutation(s) of an integral the caller stored, nor on the order of the entry list. Duplicate entries for the same position must agree exactly (bitwise floating-point equality); conflicting duplicates are rejected rather than resolved in encounter order.

Parameters:
  • mapping – The Majorana-to-Pauli encoding.

  • core_energy – Core (nuclear repulsion + frozen core) energy.

  • h1_alpha – One-body integrals, alpha spin (row-major).

  • h1_beta – One-body integrals, beta spin (row-major).

  • two_body_indices – Flattened (p,q,r,s) indices, 4 ints per entry; each index must lie in [0, n_spatial).

  • two_body_values – Integral values, one per entry.

  • num_entries – Number of stored non-zero two-body integrals.

  • n_spatial – Number of spatial orbitals.

  • spin_symmetric – Must be true: the sparse fast path is spin-summed (SparseHamiltonianContainer is restricted-only). Unrestricted Hamiltonians must use majorana_map_hamiltonian.

  • threshold – Pauli terms with |coeff| < threshold are dropped.

  • integral_threshold – Integrals with |value| < this are skipped.

Throws:

std::invalid_argument – If spin_symmetric is false, any two-body index is outside [0, n_spatial), or duplicate entries for the same position carry conflicting values.

Returns:

MajoranaMapResult with Pauli words and coefficients.

template<class Derived>
std::shared_ptr<const SymmetryBlockedTensor<2, typename Derived::Scalar>> make_spin_diagonal_rank2_sbt(const Eigen::MatrixBase<Derived> &aa, const Eigen::MatrixBase<Derived> &bb)

Dense-matrix overload of make_spin_diagonal_rank2_sbt that treats an empty matrix as “absent” (the std::optional analog).

Returns nullptr when aa has zero size; otherwise builds the rank-2 spin-diagonal SBT. The spin axis is restricted iff bb has zero size. Use this overload to lift v1 dense APIs (which encode absence as an empty matrix) into the SBT-native construction path without optional boilerplate at the call site.

Template Parameters:

Derived – Any Eigen::MatrixBase expression; the block scalar is taken from Derived::Scalar.

Parameters:
  • aa – Alpha-alpha block (empty matrix means “no data supplied”).

  • bb – Beta-beta block (empty matrix means restricted).

Returns:

Shared pointer to the SBT, or nullptr if aa is empty.

template<class Derived>
SymmetryBlockedTensor<2, typename Derived::Scalar> make_spin_diagonal_rank2_sbt(const Eigen::MatrixBase<Derived> &aa, const Eigen::MatrixBase<Derived> &bb, bool restricted)

Build a rank-2 spin-diagonal SymmetryBlockedTensor whose two slots both carry a single-particle spin axis.

Used by one-body integrals, inactive Fock matrices, and rank-2 1-RDMs; those all have [n,n] alpha and beta blocks indexed by an MO axis.

Template Parameters:

Derived – Any Eigen::MatrixBase expression; the block scalar is taken from Derived::Scalar.

Parameters:
  • aa – Alpha-alpha block (square [n,n] matrix expression).

  • bb – Beta-beta block; ignored when restricted is true (the restricted axis aliases the beta partner to aa).

  • restricted – Whether the spin axis is restricted (alpha and beta share storage).

Returns:

Constructed rank-2 SBT.

template<class Scalar>
std::shared_ptr<const SymmetryBlockedTensor<2, Scalar>> make_spin_diagonal_rank2_sbt(const std::optional<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>> &aa, const std::optional<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>> &bb)

Optional overload of make_spin_diagonal_rank2_sbt.

Returns nullptr when aa is empty (no data supplied); otherwise builds the rank-2 spin-diagonal SBT and returns a shared pointer. The spin axis is restricted iff bb is nullopt.

Template Parameters:

Scalar – Block scalar type.

Parameters:
  • aa – Alpha-alpha block (or empty optional to indicate no data).

  • bb – Beta-beta block (or empty optional for restricted).

Returns:

Shared pointer to the SBT, or nullptr if aa is unset.

inline std::shared_ptr<const SymmetryBlockedTensorVariant<2>> make_spin_diagonal_rank2_sbt_variant(const std::optional<std::variant<Eigen::MatrixXd, Eigen::MatrixXcd>> &aa, const std::optional<std::variant<Eigen::MatrixXd, Eigen::MatrixXcd>> &bb)

Optional overload of make_spin_diagonal_rank2_sbt_variant.

Returns nullptr when neither spin channel is supplied. Restrictedness is inferred from whether bb is supplied (restricted iff bb is unset and the resulting axis aliases the alpha block).

Parameters:
  • aa – Alpha-alpha block as an optional matrix variant.

  • bb – Beta-beta block as an optional matrix variant.

Returns:

Shared pointer to the constructed variant tensor, or nullptr when both channels are unset.

inline std::shared_ptr<const SymmetryBlockedTensorVariant<2>> make_spin_diagonal_rank2_sbt_variant(const std::variant<Eigen::MatrixXd, Eigen::MatrixXcd> &aa, const std::variant<Eigen::MatrixXd, Eigen::MatrixXcd> &bb, bool restricted)

Variant overload of make_spin_diagonal_rank2_sbt — dispatches to the scalar-typed builder by visiting aa.

Parameters:
  • aa – Alpha-alpha block as a real/complex matrix variant.

  • bb – Beta-beta block (must hold the same scalar alternative as aa); ignored when restricted is true.

  • restricted – Whether the spin axis is restricted.

Returns:

Shared pointer to the constructed variant tensor.

template<class Scalar>
std::shared_ptr<const SymmetryBlockedSparseMap<4, Scalar>> make_spin_diagonal_rank4_sbsm(SparseMapBlock<4, Scalar> block, std::size_t n_active)

Build a single-channel restricted rank-4 SymmetryBlockedSparseMap whose alpha-alpha-alpha-alpha block is aliased into the alpha-alpha-beta-beta key (orbit aliasing on the restricted spin axis fills bbbb from aaaa and bbaa from aabb, so all four equivalent spin patterns share a single underlying block).

Use for spin-restricted sparse two-electron integrals where \((\alpha\alpha|\alpha\alpha) = (\alpha\alpha|\beta\beta) = (\beta\beta|\beta\beta)\) holds physically. Mirrors the single-channel dense overload make_spin_diagonal_rank4_sbt(constEigen::MatrixBase<Derived>&).

Template Parameters:

Scalar – Map value type.

Parameters:
  • block – Sparse entries for the single channel; keys are per-slot local indices, values are the integral magnitudes. Moved into the resulting map.

  • n_active – Per-spin extent. The alpha and beta extents both equal n_active on every slot.

Returns:

Shared pointer to the constructed sparse map, or nullptr when block is empty.

template<class Derived>
SymmetryBlockedTensor<4, typename Derived::Scalar> make_spin_diagonal_rank4_sbt(const Eigen::MatrixBase<Derived> &aaaa)

Single-channel restricted overload of make_spin_diagonal_rank4_sbt.

Use when only one channel of rank-4 data is supplied and all four equivalent spin patterns (aaaa, aabb, bbbb, bbaa) share that single block. This applies to spin-restricted two-electron integrals where \((\alpha\alpha|\alpha\alpha) = (\alpha\alpha|\beta\beta) = (\beta\beta|\beta\beta)\) holds physically, but does not apply to 2-RDMs (whose spin channels are independent quantities even in restricted spin states).

The alpha-alpha-alpha-alpha and alpha-alpha-beta-beta keys are both pointed at the single supplied block; orbit aliasing on the restricted spin axis then fills bbbb (from aaaa) and bbaa (from aabb) with the same block pointer.

Template Parameters:

Derived – Any Eigen::MatrixBase expression; the block scalar is taken from Derived::Scalar.

Parameters:

aaaa – The single channel of rank-4 data (flat n_active^4 vector). Validated to be a perfect fourth power in size.

Throws:

std::invalid_argument – if aaaa.size() is not a perfect fourth power.

Returns:

Constructed rank-4 SBT with one underlying block, aliased to four spin keys.

template<class Derived>
std::shared_ptr<const SymmetryBlockedTensor<4, typename Derived::Scalar>> make_spin_diagonal_rank4_sbt(const Eigen::MatrixBase<Derived> &aaaa, const Eigen::MatrixBase<Derived> &aabb, const Eigen::MatrixBase<Derived> &bbbb)

Dense-vector overload of make_spin_diagonal_rank4_sbt that treats an empty vector as “absent” (the std::optional analog).

Returns nullptr when all three channels are empty; otherwise builds the rank-4 spin-diagonal SBT from whichever channels are supplied. The spin axis is restricted iff bbbb is empty, in which case unspecified channels are aliased to aaaa.

Template Parameters:

Derived – Any Eigen::MatrixBase expression; the block scalar is taken from Derived::Scalar.

Parameters:
  • aaaa – Alpha-alpha-alpha-alpha channel (empty means “absent”).

  • aabb – Alpha-alpha-beta-beta channel (empty means “absent”).

  • bbbb – Beta-beta-beta-beta channel (empty means restricted).

Returns:

Shared pointer to the SBT, or nullptr if all three channels are empty.

template<class Derived>
SymmetryBlockedTensor<4, typename Derived::Scalar> make_spin_diagonal_rank4_sbt(const Eigen::MatrixBase<Derived> &aaaa, const Eigen::MatrixBase<Derived> &aabb, const Eigen::MatrixBase<Derived> &bbbb, bool restricted)

Build a rank-4 spin-diagonal SymmetryBlockedTensor.

Used by two-body integrals and 2-RDMs that store n_active^4 flat vectors per independent spin sector (aaaa, aabb, bbbb).

Template Parameters:

Derived – Any Eigen::MatrixBase expression (a flat n_active^4 column-vector-like block); the block scalar is taken from Derived::Scalar.

Parameters:
  • aaaa – Alpha-alpha-alpha-alpha channel (flat n_active^4 vector).

  • aabb – Alpha-alpha-beta-beta channel.

  • bbbb – Beta-beta-beta-beta channel; ignored when restricted is true.

  • restricted – Whether the spin axis is restricted.

Throws:

std::invalid_argument – if aaaa.size() is not a perfect fourth power.

Returns:

Constructed rank-4 SBT.

template<class Scalar>
std::shared_ptr<const SymmetryBlockedTensor<4, Scalar>> make_spin_diagonal_rank4_sbt(const std::optional<Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> &aaaa, const std::optional<Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> &aabb, const std::optional<Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> &bbbb)

Optional overload of make_spin_diagonal_rank4_sbt.

Returns nullptr when all three channels are unset. Builds the rank-4 spin-diagonal SBT from whichever channels are supplied, with the restrictedness of the resulting spin axis determined by whether bbbb is supplied: when nullopt, the axis is restricted and unspecified channels are aliased to aaaa.

Template Parameters:

Scalar – Block scalar type.

Parameters:
  • aaaa – Alpha-alpha-alpha-alpha channel (or empty optional).

  • aabb – Alpha-alpha-beta-beta channel (or empty optional).

  • bbbb – Beta-beta-beta-beta channel (or empty optional). When unset the spin axis is restricted.

Returns:

Shared pointer to the SBT, or nullptr if all three channels are unset.

inline std::shared_ptr<const SymmetryBlockedTensorVariant<4>> make_spin_diagonal_rank4_sbt_variant(const std::optional<std::variant<Eigen::VectorXd, Eigen::VectorXcd>> &aaaa, const std::optional<std::variant<Eigen::VectorXd, Eigen::VectorXcd>> &aabb, const std::optional<std::variant<Eigen::VectorXd, Eigen::VectorXcd>> &bbbb)

Optional overload of make_spin_diagonal_rank4_sbt_variant.

Returns nullptr when none of the three spin channels are supplied. The spin axis is restricted iff bbbb is unset; in that case unspecified channels alias the supplied alpha-like block.

Parameters:
  • aaaa – Alpha-alpha-alpha-alpha channel as an optional vector variant.

  • aabb – Alpha-alpha-beta-beta channel as an optional vector variant.

  • bbbb – Beta-beta-beta-beta channel as an optional vector variant.

Returns:

Shared pointer to the constructed variant tensor, or nullptr when all three channels are unset.

inline std::shared_ptr<const SymmetryBlockedTensorVariant<4>> make_spin_diagonal_rank4_sbt_variant(const std::variant<Eigen::VectorXd, Eigen::VectorXcd> &aaaa, const std::variant<Eigen::VectorXd, Eigen::VectorXcd> &aabb, const std::variant<Eigen::VectorXd, Eigen::VectorXcd> &bbbb, bool restricted)

Variant overload of make_spin_diagonal_rank4_sbt — dispatches to the scalar-typed builder by visiting aaaa.

Parameters:
  • aaaa – Alpha-alpha-alpha-alpha block as a real/complex vector variant.

  • aabb – Alpha-alpha-beta-beta block (same scalar alternative).

  • bbbb – Beta-beta-beta-beta block (same scalar alternative); ignored when restricted is true.

  • restricted – Whether the spin axis is restricted.

Returns:

Shared pointer to the constructed variant tensor.

std::string sparse_pauli_word_to_label(const SparsePauliWord &word, std::uint64_t num_qubits)

Convert a sparse Pauli word to a QubitOperator label.

The returned label uses the QubitOperator convention: qubit 0 is the rightmost character.

EdgeColoring square_coloring(std::int64_t nx, std::int64_t ny, bool periodic_x, bool periodic_y)

Deterministic optimal edge coloring for a square lattice.

Parameters:
  • nx – Number of sites along x.

  • ny – Number of sites along y.

  • periodic_x – Whether periodic boundary conditions are applied along x.

  • periodic_y – Whether periodic boundary conditions are applied along y.

Returns:

Edge coloring using 2–4 colours depending on periodicity and parity.

std::shared_ptr<const SymmetryAxisValue> symmetry_axis_value_from_json(const nlohmann::json &j)

Reconstruct a SymmetryAxisValue from JSON by dispatching on its kind tag.

Parameters:

j – JSON object produced by a prior to_json call on a concrete SymmetryAxisValue subclass.

Throws:

std::runtime_error – if the kind tag is missing or not recognized.

Returns:

Shared pointer to the deserialized value typed as the polymorphic base.

std::string to_string(AxisName axis)

Human-readable name for an AxisName (used in messages and serialization metadata).

Parameters:

axis – Axis identifier to render.

Returns:

A stable lower-case string (e.g. "spin" for AxisName::Spin).

EdgeColoring trivial_edge_coloring(const Eigen::SparseMatrix<double> &adj)

Trivial edge coloring where every edge receives a unique color.

Useful as a fallback when no topology-aware coloring is available.

Parameters:

adj – Sparse adjacency matrix of the graph.

Returns:

Edge coloring mapping each undirected edge to a distinct colour label 0, 1, 2, … in iteration order.

Variables

const std::unordered_map<unsigned, std::string> CHARGE_TO_SYMBOL
template<typename T>
constexpr bool is_non_bool_integral_v = NonBoolIntegral<T>

Helper variable template for non-bool integral (for backward compatibility)

Template Parameters:

T – The type to check

template<typename T>
constexpr bool is_non_bool_integral_vector_v = NonBoolIntegralVector<T>

Helper variable template for non-bool integral vector (for backward compatibility)

Template Parameters:

T – The type to check

template<typename T, typename Variant>
constexpr bool is_variant_member_v = VariantMember<T, Variant>

Helper variable template for variant member check.

Template Parameters:
  • T – The type to check

  • Variant – The variant type to check against

template<typename T>
constexpr bool is_vector_v = Vector<T>

Helper variable template for is_vector (for backward compatibility)

Template Parameters:

T – The type to check

static constexpr size_t MAX_ORBITAL_ANGULAR_MOMENTUM = 6

Maximum angular momentum for atomic orbitals supported in QDK/Chemistry.

std::unordered_map<std::string, unsigned> SYMBOL_TO_CHARGE
class AlgorithmRef
#include <qdk/chemistry/data/settings.hpp>

Declarative reference to a nested algorithm to be created via the registry.

An AlgorithmRef is stored inside a parent algorithm’s Settings to describe a child algorithm that will be instantiated at run-time.

Public Functions

AlgorithmRef() = default

Default constructor.

AlgorithmRef(std::string type, std::string name, std::shared_ptr<Settings> settings_ptr = nullptr)

Construct an AlgorithmRef with a given type, name, and optional settings.

If settings_ptr is nullptr the constructor attempts to auto-resolve the algorithm’s default settings via create_default_settings.

Parameters:
  • type – Registry type key (e.g. “circuit_executor”).

  • name – Registry name key (e.g. “qdk_sparse_state_simulator”).

  • settings_ptr – Optional pre-built settings; nullptr triggers auto-resolution.

inline const std::string &get_algorithm_name() const

Get the registry name key.

inline const std::string &get_algorithm_type() const

Get the registry type key (immutable after construction).

inline const std::shared_ptr<Settings> &get_settings() const

Get the nested settings for the algorithm.

inline bool operator==(const AlgorithmRef &other) const

Equality comparison (compares type and name only).

Parameters:

other – The AlgorithmRef to compare against.

Returns:

true if both algorithm_type and algorithm_name match.

template<typename V>
void set(const std::string &key, const V &value)

Set a field or nested setting on this AlgorithmRef.

Enforce inheritance from base class and presence of required methods.

Special keys:

  • "algorithm_name" – changes the name and re-resolves default settings (any previous overrides are lost).

  • "algorithm_type" – always throws (immutable after construction).

  • Anything else – forwarded to settings->set(key, value).

This checks the presence of key methods (serialization, deserialization) and get_summary. AlgorithmRef::set / update — deferred definitions. These are templates so they can be declared inside AlgorithmRef (before SettingValue exists) but defined here where Settings, SettingValue, SettingNotFound, and SettingTypeMismatch are all complete.

Note

Declared as a template to break the circular dependency with SettingValue. Defined after the SettingValue alias below.

Parameters:
  • key – The setting key.

  • value – The new value (must be SettingValue).

Throws:
  • std::invalid_argument – if key is "algorithm_type".

  • SettingTypeMismatch – if key is "algorithm_name" and value is not a string.

  • SettingNotFound – if settings is nullptr or does not contain key.

template<typename V>
void update(const std::map<std::string, V> &overrides)

Bulk-update nested settings without resetting defaults.

Applies each entry in overrides to the current settings via set().

Note

Declared as a template to break the circular dependency with SettingValue. Defined after the SettingValue alias below.

Parameters:

overrides – Map of setting keys to new values.

Throws:

SettingNotFound – if settings is nullptr or a key does not exist.

Public Static Attributes

static std::function<std::shared_ptr<Settings>(const std::string &type, const std::string &name)> create_default_settings

Global create function used to auto-resolve default settings.

Signature: (algorithm_type, algorithm_name) → default Settings copy, or nullptr if the algorithm is not found.

Set once by the algorithm / Python layer so that AlgorithmRef constructors can populate the settings member automatically.

class AmplitudeContainer : public qdk::chemistry::data::WavefunctionContainer
#include <qdk/chemistry/data/wavefunction_containers/amplitude_container.hpp>

Wavefunction container representing an amplitude-based correlated wavefunction (e.g.

coupled cluster or MP2).

This is the single container type for wavefunctions parameterized by excitation amplitudes relative to a reference. It stores the reference wavefunction together with T1/T2 amplitude blocks and subsumes the previous coupled-cluster and MP2 containers.

The container is pure storage: it does not expand the amplitudes into a determinant/coefficient (CI) representation and does not compute reduced density matrices. Determinant- and RDM-based accessors therefore throw. Amplitudes are supplied by the producing algorithm; they are not computed lazily.

Public Types

using DeterminantVector = ContainerTypes::DeterminantVector
using MatrixVariant = ContainerTypes::MatrixVariant
using ScalarVariant = ContainerTypes::ScalarVariant
using VectorVariant = ContainerTypes::VectorVariant

Public Functions

AmplitudeContainer(std::shared_ptr<Orbitals> orbitals, std::shared_ptr<Wavefunction> wavefunction, AmplitudeType amplitude_type, const std::optional<VectorVariant> &t1_amplitudes, const std::optional<VectorVariant> &t2_amplitudes, std::string sector = Wavefunction::DEFAULT_SECTOR)

Constructs an amplitude wavefunction with spatial (restricted) amplitudes.

T1/T2 amplitudes are stored if provided.

Parameters:
  • orbitals – Shared pointer to orbitals

  • sector – Name of the single-particle sector the orbitals belong to

  • wavefunction – Shared pointer to the reference wavefunction

  • amplitude_type – Correlated method that produced the amplitudes

  • t1_amplitudes – T1 amplitudes (optional)

  • t2_amplitudes – T2 amplitudes (optional)

AmplitudeContainer(std::shared_ptr<Orbitals> orbitals, std::shared_ptr<Wavefunction> wavefunction, AmplitudeType amplitude_type, const std::optional<VectorVariant> &t1_amplitudes_aa, const std::optional<VectorVariant> &t1_amplitudes_bb, const std::optional<VectorVariant> &t2_amplitudes_abab, const std::optional<VectorVariant> &t2_amplitudes_aaaa, const std::optional<VectorVariant> &t2_amplitudes_bbbb, std::string sector = Wavefunction::DEFAULT_SECTOR)

Constructs an amplitude wavefunction with spin-separated amplitudes.

T1/T2 amplitudes are stored if provided.

Parameters:
  • orbitals – Shared pointer to orbitals

  • sector – Name of the single-particle sector the orbitals belong to

  • wavefunction – Shared pointer to the reference wavefunction

  • amplitude_type – Correlated method that produced the amplitudes

  • t1_amplitudes_aa – Alpha T1 amplitudes (optional)

  • t1_amplitudes_bb – Beta T1 amplitudes (optional)

  • t2_amplitudes_abab – Alpha-beta T2 amplitudes (optional)

  • t2_amplitudes_aaaa – Alpha-alpha T2 amplitudes (optional)

  • t2_amplitudes_bbbb – Beta-beta T2 amplitudes (optional)

~AmplitudeContainer() override = default

Destructor.

virtual std::shared_ptr<const SymmetryBlockedScalar<std::size_t>> active_num_particles() const override

Number of active-space particles as a symmetry-blocked scalar.

Returns:

Shared pointer to the symmetry-blocked active particle count.

virtual std::shared_ptr<const SymmetryBlockedTensor<1>> active_orbital_occupations() const override

Not supported: orbital occupations require reduced density matrices, which are not stored by amplitude wavefunctions.

Throws:

std::runtime_error – Always.

virtual void clear_caches() const override

Clear cached data to release memory.

virtual std::unique_ptr<WavefunctionContainer> clone() const override

Create a deep copy of this container.

Returns:

Unique pointer to cloned container

bool contains_determinant(const Configuration &det) const

Check if a determinant is in the reference wavefunction.

Parameters:

det – Configuration/determinant to check

Returns:

True if determinant matches any reference determinant

bool contains_reference(const Configuration &det) const

Check if a determinant is in the reference wavefunction.

Parameters:

det – Configuration/determinant to check

Returns:

True if determinant matches any reference determinant

AmplitudeType get_amplitude_type() const

Get the correlated method that produced these amplitudes.

Returns:

The amplitude expansion type (MollerPlesset, CoupledCluster, or Unspecified)

virtual std::string get_container_type() const override

Get container type identifier for serialization.

Returns:

String “amplitude”

virtual std::shared_ptr<Orbitals> get_orbitals() const override

Get reference to orbitals.

Returns:

Shared pointer to orbitals

std::pair<const VectorVariant&, const VectorVariant&> get_t1_amplitudes() const

Get T1 amplitudes.

Throws:

std::runtime_error – if T1 amplitudes are not available

Returns:

Pair of (alpha, beta) T1 amplitudes

std::tuple<const VectorVariant&, const VectorVariant&, const VectorVariant&> get_t2_amplitudes() const

Get T2 amplitudes.

Throws:

std::runtime_error – if T2 amplitudes are not available

Returns:

Tuple of (alpha-beta, alpha-alpha, beta-beta) T2 amplitudes

std::shared_ptr<Wavefunction> get_wavefunction() const

Get the reference wavefunction.

Returns:

Shared pointer to the reference wavefunction

bool has_t1_amplitudes() const

Check if T1 amplitudes are available.

Returns:

True if T1 amplitudes are available

bool has_t2_amplitudes() const

Check if T2 amplitudes are available.

Returns:

True if T2 amplitudes are available

virtual void hash_update(qdk::chemistry::utils::HashContext &ctx) const override

Feed identifying data into a hash context.

virtual bool is_complex() const override

Check if the wavefunction is complex-valued.

Returns:

True if amplitudes contain complex values

virtual double norm() const override

Not supported for amplitude wavefunctions.

Throws:

std::runtime_error – Always.

virtual ScalarVariant overlap(const WavefunctionContainer &other) const override

Not supported for amplitude wavefunctions.

Throws:

std::runtime_error – Always.

virtual std::shared_ptr<const Orbitals> sector_basis(const std::string &name) const override

Single-particle basis bound to a sector.

Parameters:

name – Sector name to resolve.

Throws:

std::out_of_range – if this container has no sector named name.

Returns:

Shared pointer to the Orbitals bound to name.

virtual std::vector<std::string> sectors() const override

Names of the single-particle sectors this container spans.

Returns:

The container’s sector names (the sector supplied at construction).

virtual void to_hdf5(H5::Group &group) const override

Convert container to HDF5 group.

Parameters:

group – HDF5 group to write container data to

Throws:

std::runtime_error – if HDF5 I/O error occurs

virtual nlohmann::json to_json() const override

Convert container to JSON format.

Returns:

JSON object containing container data

virtual std::shared_ptr<const SymmetryBlockedScalar<std::size_t>> total_num_particles() const override

Number of particles (active + inactive) as a symmetry-blocked scalar.

Returns:

Shared pointer to the symmetry-blocked total particle count.

virtual std::shared_ptr<const SymmetryBlockedTensor<1>> total_orbital_occupations() const override

Not supported: orbital occupations require reduced density matrices, which are not stored by amplitude wavefunctions.

Throws:

std::runtime_error – Always.

Public Static Functions

static std::unique_ptr<AmplitudeContainer> from_hdf5(H5::Group &group)

Load container from HDF5 group.

Reads the current “amplitude” format as well as the legacy “coupled_cluster” and “mp2” formats (read-only backward compatibility). Legacy “mp2” files did not store amplitudes, so the resulting container has none.

Parameters:

group – HDF5 group containing container data

Throws:

std::runtime_error – if HDF5 data is malformed or I/O error occurs

Returns:

Unique pointer to the container created from HDF5 group

static std::unique_ptr<AmplitudeContainer> from_json(const nlohmann::json &j)

Load container from JSON format.

Reads the current “amplitude” format as well as the legacy “coupled_cluster” and “mp2” formats (read-only backward compatibility). Legacy “mp2” files did not store amplitudes, so the resulting container has none.

Parameters:

j – JSON object containing container data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Unique pointer to the container created from JSON data

class Ansatz : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<Ansatz>
#include <qdk/chemistry/data/ansatz.hpp>

Represents a quantum chemical ansatz combining a Hamiltonian and wavefunction.

This class represents a complete quantum chemical ansatz, which consists of:

  • A Hamiltonian operator describing the system’s energy

  • A wavefunction describing the quantum state

The class is immutable after construction, meaning all data must be provided during construction and cannot be modified afterwards. This ensures consistency between the Hamiltonian and wavefunction throughout the calculation.

Common use cases:

  • Configuration interaction (CI) methods

  • Multi-configuration self-consistent field (MultiConfigurationScf) calculations

  • Coupled cluster calculations

  • Energy expectation value computations

Public Functions

Ansatz(Ansatz &&other) noexcept = default

Move constructor.

Ansatz(const Ansatz &other)

Copy constructor.

Ansatz(const Hamiltonian &hamiltonian, const Wavefunction &wavefunction)

Constructor with Hamiltonian and Wavefunction objects.

Parameters:
  • hamiltonian – The Hamiltonian operator for the system

  • wavefunction – The wavefunction describing the quantum state

Throws:

std::invalid_argument – if orbital dimensions are inconsistent between Hamiltonian and wavefunction

Ansatz(std::shared_ptr<Hamiltonian> hamiltonian, std::shared_ptr<Wavefunction> wavefunction)

Constructor with shared pointers to Hamiltonian and Wavefunction.

Parameters:
  • hamiltonian – Shared pointer to the Hamiltonian operator

  • wavefunction – Shared pointer to the wavefunction

Throws:

std::invalid_argument – if pointers are nullptr or orbital dimensions are inconsistent

virtual ~Ansatz() = default

Destructor.

double calculate_energy() const

Calculate the energy expectation value ⟨ψ|H|ψ⟩

Note

This method will be implemented once energy calculation algorithms are available

Throws:

std::runtime_error – if calculation cannot be performed

Returns:

Energy expectation value in atomic units

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“ansatz”

std::shared_ptr<Hamiltonian> get_hamiltonian() const

Get shared pointer to the Hamiltonian.

Throws:

std::runtime_error – if Hamiltonian is not set

Returns:

Shared pointer to the Hamiltonian object

std::shared_ptr<Orbitals> get_orbitals() const

Get shared pointer to the orbital basis set from the Hamiltonian.

Throws:

std::runtime_error – if orbitals are not available

Returns:

Shared pointer to the Orbitals object

virtual std::string get_summary() const override

Get a summary string describing the Ansatz.

Returns:

Human-readable summary of the Ansatz

std::shared_ptr<Wavefunction> get_wavefunction() const

Get shared pointer to the wavefunction.

Throws:

std::runtime_error – if wavefunction is not set

Returns:

Shared pointer to the Wavefunction object

bool has_hamiltonian() const

Check if Hamiltonian is available.

Returns:

True if Hamiltonian is set

bool has_orbitals() const

Check if orbital data is available.

Returns:

True if orbitals are set in both Hamiltonian and wavefunction

bool has_wavefunction() const

Check if wavefunction is available.

Returns:

True if wavefunction is set

Ansatz &operator=(Ansatz &&other) noexcept = default

Move assignment operator.

Ansatz &operator=(const Ansatz &other)

Copy assignment operator.

virtual void to_file(const std::string &filename, const std::string &type) const override

Generic file I/O - save to file based on type parameter.

Parameters:
  • filename – Path to file to create/overwrite

  • type – File format type (“json” or “hdf5”)

Throws:

std::runtime_error – if unsupported type or I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Serialize Ansatz to HDF5 group.

Parameters:

group – HDF5 group to write data to

Throws:

std::runtime_error – if I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save Ansatz to HDF5 file (with validation)

Parameters:

filename – Path to HDF5 file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert Ansatz to JSON.

Returns:

JSON object containing Ansatz data

virtual void to_json_file(const std::string &filename) const override

Save Ansatz to JSON file (with validation)

Parameters:

filename – Path to JSON file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

void validate_orbital_consistency() const

Validate orbital consistency between Hamiltonian and wavefunction.

Throws:

std::runtime_error – if orbital dimensions are inconsistent

Public Static Functions

static std::shared_ptr<Ansatz> from_file(const std::string &filename, const std::string &type)

Generic file I/O - load from file based on type parameter.

Parameters:
  • filename – Path to file to read

  • type – File format type (“json” or “hdf5”)

Throws:

std::runtime_error – if file doesn’t exist, unsupported type, or I/O error occurs

Returns:

New Ansatz loaded from file

static std::shared_ptr<Ansatz> from_hdf5(H5::Group &group)

Load Ansatz from HDF5 group.

Parameters:

group – HDF5 group to read data from

Throws:

std::runtime_error – if I/O error occurs

Returns:

Shared pointer to const Ansatz loaded from group

static std::shared_ptr<Ansatz> from_hdf5_file(const std::string &filename)

Load Ansatz from HDF5 file (with validation)

Parameters:

filename – Path to HDF5 file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const Ansatz loaded from file

static std::shared_ptr<Ansatz> from_json(const nlohmann::json &j)

Load Ansatz from JSON.

Parameters:

j – JSON object containing Ansatz data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Shared pointer to const Ansatz loaded from JSON

static std::shared_ptr<Ansatz> from_json_file(const std::string &filename)

Load Ansatz from JSON file (with validation)

Parameters:

filename – Path to JSON file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const Ansatz loaded from file

class BasisSet : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<BasisSet>
#include <qdk/chemistry/data/basis_set.hpp>

Represents an atomic orbital basis set using shell-based organization.

This class stores and manages atomic orbital basis set information using shells as the primary organizational unit. A shell represents a group of atomic orbitals with the same atom, angular momentum, and primitives. The class is designed to be immutable after construction, ensuring data integrity.

Features:

  • Shell-based storage for memory efficiency

  • Support for spherical or cartesian atomic orbitals

  • Mapping between shells/atomic orbitals and atoms

  • Mapping between shells/atomic orbitals and orbital types

  • Basis set metadata (name, parameters, references)

  • Integration with molecular structure information

  • On-demand expansion of shells to individual atomic orbitals

The shell-based approach matches standard quantum chemistry practices and provides efficient storage and computation.

Public Functions

BasisSet(BasisSet &&other) noexcept = default

Move constructor.

BasisSet(const BasisSet &other)

Copy constructor.

Note: this function generates a deep copy of the basis set.

BasisSet(const std::string &name, const std::vector<Shell> &shells, AOType atomic_orbital_type = AOType::Spherical)

Constructor with shells.

Parameters:
  • name – Name of the basis set

  • shells – Vector of shells to initialize the basis set with

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

BasisSet(const std::string &name, const std::vector<Shell> &shells, const std::string &ecp_name, const std::vector<Shell> &ecp_shells, const std::vector<size_t> &ecp_electrons, const Structure &structure, AOType basis_type = AOType::Spherical)

Constructor with shells, ECP shells, ECP name, ECP electrons, and structure.

Parameters:
  • name – Name of the basis set

  • shells – Vector of shells to initialize the basis set with

  • ecp_name – Name of the ECP basis set

  • ecp_shells – Vector of ECP shells to initialize the basis set with

  • ecp_electrons – Vector containing numbers of ECP electrons for each atom

  • structure – The molecular structure

  • basis_type – Whether to use spherical or cartesian atomic orbitals

BasisSet(const std::string &name, const std::vector<Shell> &shells, const std::string &ecp_name, const std::vector<Shell> &ecp_shells, const std::vector<size_t> &ecp_electrons, std::shared_ptr<Structure> structure, AOType basis_type = AOType::Spherical)

Constructor with shells, ECP shells, ECP name, ECP electrons, and structure shared pointer.

Parameters:
  • name – Name of the basis set

  • shells – Vector of shells to initialize the basis set with

  • ecp_shells – Vector of ECP shells to initialize the basis set with

  • ecp_name – Name of the ECP basis set

  • ecp_electrons – Vector containing numbers of ECP electrons for each atom

  • structure – Shared pointer to the molecular structure

  • basis_type – Whether to use spherical or cartesian atomic orbitals

BasisSet(const std::string &name, const std::vector<Shell> &shells, const std::vector<Shell> &ecp_shells, const Structure &structure, AOType basis_type = AOType::Spherical)

Constructor with shells, ECP shells, and structure.

Parameters:
  • name – Name of the basis set

  • shells – Vector of shells to initialize the basis set with

  • ecp_shells – Vector of ECP shells to initialize the basis set with

  • structure – The molecular structure

  • basis_type – Whether to use spherical or cartesian atomic orbitals

BasisSet(const std::string &name, const std::vector<Shell> &shells, const std::vector<Shell> &ecp_shells, std::shared_ptr<Structure> structure, AOType basis_type = AOType::Spherical)

Constructor with shells, ECP shells, and structure shared pointer.

Parameters:
  • name – Name of the basis set

  • shells – Vector of shells to initialize the basis set with

  • ecp_shells – Vector of ECP shells to initialize the basis set with

  • structure – Shared pointer to the molecular structure

  • basis_type – Whether to use spherical or cartesian atomic orbitals

BasisSet(const std::string &name, const std::vector<Shell> &shells, const Structure &structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with shells and structure.

Parameters:
  • name – Name of the basis set

  • shells – Vector of shells to initialize the basis set with

  • structure – The molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

BasisSet(const std::string &name, const std::vector<Shell> &shells, std::shared_ptr<Structure> structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with shells and structure shared pointer.

Parameters:
  • name – Name of the basis set

  • shells – Vector of shells to initialize the basis set with

  • structure – Shared pointer to the molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

BasisSet(const std::string &name, const std::vector<Shell> &shells, std::shared_ptr<Structure> structure, std::shared_ptr<const SymmetryProduct> ao_symmetries, std::unordered_map<SymmetryLabel, std::size_t> ao_extents = {}, AOType atomic_orbital_type = AOType::Spherical)

Constructor with explicit atomic-orbital (AO) symmetries.

Use this overload to block the AO basis under a non-default SymmetryProduct. The default (used by every other constructor) is a restricted spin axis (axes::spin(1, true)) whose \(\alpha\)/ \(\beta\) labels each carry an extent equal to get_num_atomic_orbitals().

Parameters:
  • name – Name of the basis set

  • shells – Vector of shells to initialize the basis set with

  • structure – The molecular structure

  • ao_symmetries – Symmetry definitions the AO basis is blocked under

  • ao_extents – Per-label AO extents; if empty, defaults to get_num_atomic_orbitals() for every admissible label

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

Throws:

std::invalid_argument – if extents are inadmissible or violate symmetry aliasing

BasisSet(const std::string &name, const Structure &structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with basis set name and structure.

Parameters:
  • name – Name of the basis set (e.g., “6-31G”, “cc-pVDZ”)

  • structure – The molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

BasisSet(const std::string &name, std::shared_ptr<Structure> structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with basis set name and structure shared pointer.

Parameters:
  • name – Name of the basis set (e.g., “6-31G”, “cc-pVDZ”)

  • structure – Shared pointer to the molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

virtual ~BasisSet() = default

Default destructor.

const std::unordered_map<SymmetryLabel, std::size_t> &ao_extents() const

Per-label extents of the atomic-orbital basis.

Maps each admissible SymmetryLabel to the number of atomic orbitals it carries.

Returns:

Map from AO symmetry label to extent

std::shared_ptr<const SymmetryProduct> ao_symmetries() const

Symmetry definitions the atomic-orbital basis is blocked under.

Returns the AO-basis symmetries. This is distinct from Orbitals::symmetries(), which returns the MO-basis symmetries — AOs and MOs live in different single-particle bases and may carry different SymmetryProduct instances (e.g. an intertwiner stored on Orbitals carries AO symmetries on one slot and MO symmetries on the other). The ao_ prefix exists to keep this distinction explicit on classes that touch both bases.

Defaults to a restricted spin axis (axes::spin(1, true)). Override at construction with the AO-symmetries constructor overload.

Returns:

Shared pointer to the AO SymmetryProduct

std::pair<size_t, int> basis_to_shell_index(size_t atomic_orbital_index) const

Convert atomic orbital index to shell index and magnetic quantum number.

Parameters:

atomic_orbital_index – Global atomic orbital index

Returns:

Pair of (shell_index, magnetic_quantum_number)

size_t get_atom_index_for_atomic_orbital(size_t contracted_atomic_orbital_index) const

Get the atom index for a atomic orbital.

Parameters:

contracted_atomic_orbital_index – Index of the atomic orbital

Throws:

std::out_of_range – if atomic_orbital_index is invalid

Returns:

Index of the atom this atomic orbital belongs to

std::vector<size_t> get_atomic_orbital_indices_for_atom(size_t atom_index) const

Get all atomic orbital indices for a specific atom.

Parameters:

atom_index – Index of the atom

Returns:

Vector of atomic orbital indices for this atom

std::pair<size_t, int> get_atomic_orbital_info(size_t atomic_orbital_index) const

Get the shell index and magnetic quantum number for a atomic orbital index.

Parameters:

atomic_orbital_index – Index of the atomic orbital

Throws:

std::out_of_range – if index is invalid

Returns:

Pair containing (shell_index, magnetic_quantum_number)

AOType get_atomic_orbital_type() const

Get the basis type.

Returns:

Current basis type (spherical or cartesian)

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“basis_set”

const std::vector<size_t> &get_ecp_electrons() const

Get the ECP electrons vector.

Returns:

Vector containing numbers of ECP electrons for each atom

const std::string &get_ecp_name() const

Get the ECP name.

Returns:

Name of the ECP

const Shell &get_ecp_shell(size_t shell_index) const

Get a specific ECP shell by global index.

Parameters:

shell_index – Global index of the ECP shell

Throws:

std::out_of_range – if index is invalid

Returns:

Reference to the ECP shell

std::vector<size_t> get_ecp_shell_indices_for_atom(size_t atom_index) const

Get ECP shell indices for a specific atom.

Parameters:

atom_index – Index of the atom

Returns:

Vector of ECP shell indices for this atom

std::vector<size_t> get_ecp_shell_indices_for_atom_and_orbital_type(size_t atom_index, OrbitalType orbital_type) const

Get ECP shell indices for a specific atom and orbital type.

Parameters:
  • atom_index – Index of the atom

  • orbital_type – Type of orbital

Returns:

Vector of ECP shell indices matching both criteria

std::vector<size_t> get_ecp_shell_indices_for_orbital_type(OrbitalType orbital_type) const

Get ECP shell indices for a specific orbital type.

Parameters:

orbital_type – Type of orbital

Returns:

Vector of ECP shell indices of this type

std::vector<Shell> get_ecp_shells() const

Get all ECP shells (flattened from per-atom storage)

Returns:

Vector of all ECP shells

const std::vector<Shell> &get_ecp_shells_for_atom(size_t atom_index) const

Get ECP shells for a specific atom.

Parameters:

atom_index – Index of the atom

Returns:

Vector of ECP shells for this atom

const std::string &get_name() const

Get the basis set name.

Returns:

Name of the basis set

size_t get_num_atomic_orbitals() const

Get number of atomic orbitals (total from all shells)

Returns:

Total number of atomic orbitals

size_t get_num_atomic_orbitals_for_atom(size_t atom_index) const

Get number of atomic orbitals for a specific atom.

Parameters:

atom_index – Index of the atom

Returns:

Number of atomic orbitals for this atom

size_t get_num_atomic_orbitals_for_orbital_type(OrbitalType orbital_type) const

Get number of atomic orbitals for a specific orbital type.

Parameters:

orbital_type – Type of orbital

Returns:

Number of atomic orbitals of this type

size_t get_num_atoms() const

Get number of atoms that have shells.

Returns:

Number of atoms with shells

size_t get_num_ecp_shells() const

Get total number of ECP shells across all atoms.

Returns:

Total number of ECP shells

size_t get_num_shells() const

Get total number of shells across all atoms.

Returns:

Total number of shells

const Shell &get_shell(size_t shell_index) const

Get a specific shell by global index.

Parameters:

shell_index – Global index of the shell

Throws:

std::out_of_range – if index is invalid

Returns:

Reference to the shell

std::vector<size_t> get_shell_indices_for_atom(size_t atom_index) const

Get shell indices for a specific atom.

Parameters:

atom_index – Index of the atom

Returns:

Vector of shell indices for this atom

std::vector<size_t> get_shell_indices_for_atom_and_orbital_type(size_t atom_index, OrbitalType orbital_type) const

Get shell indices for a specific atom and orbital type.

Parameters:
  • atom_index – Index of the atom

  • orbital_type – Type of orbital

Returns:

Vector of shell indices matching both criteria

std::vector<size_t> get_shell_indices_for_orbital_type(OrbitalType orbital_type) const

Get shell indices for a specific orbital type.

Parameters:

orbital_type – Type of orbital

Returns:

Vector of shell indices of this type

std::vector<Shell> get_shells() const

Get all shells (flattened from per-atom storage)

Returns:

Vector of all shells

const std::vector<Shell> &get_shells_for_atom(size_t atom_index) const

Get shells for a specific atom.

Parameters:

atom_index – Index of the atom

Returns:

Vector of shells for this atom

const std::shared_ptr<Structure> get_structure() const

Get the molecular structure.

Throws:

std::runtime_error – if no structure is set

Returns:

Pointer to the molecular structure

virtual std::string get_summary() const override

Get summary string of basis set information.

Returns:

String describing the basis set

bool has_ecp_electrons() const

Check if ECP electrons are present.

Returns:

True if ECP electrons are present

bool has_ecp_shells() const

Check if this basis set has ECP shells.

Returns:

True if there are any ECP shells

bool has_structure() const

Check if a structure is associated with this basis set.

Returns:

True if structure is set

BasisSet &operator=(BasisSet &&other) noexcept = default

Move assignment operator.

BasisSet &operator=(const BasisSet &other)

Copy assignment operator.

Note: this function generates a deep copy of the basis set.

virtual void to_file(const std::string &filename, const std::string &type) const override

Generic file I/O - save to file based on type parameter.

Parameters:
  • filename – Path to file to create/overwrite

  • type – File format type (“json” or “hdf5”)

Throws:

std::runtime_error – if unsupported type or I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Serialize basis set to HDF5 group.

Parameters:

group – HDF5 group to write data to

Throws:

std::runtime_error – if I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save basis set to HDF5 file (with validation)

Parameters:

filename – Path to HDF5 file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert basis set to JSON.

Returns:

JSON object containing basis set data

virtual void to_json_file(const std::string &filename) const override

Save basis set to JSON file (with validation)

Parameters:

filename – Path to JSON file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

Public Static Functions

static std::string atomic_orbital_type_to_string(AOType atomic_orbital_type)

Convert basis type to string.

Parameters:

atomic_orbital_type – The basis type to convert

Returns:

String representation (“spherical” or “cartesian”)

static std::shared_ptr<BasisSet> from_basis_name(const std::string &basis_name, const Structure &structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with basis set name and structure.

Parameters:
  • basis_name – Name of the basis set (e.g., “6-31G”, “cc-pVDZ”)

  • structure – The molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

Returns:

Shared pointer to the created BasisSet

static std::shared_ptr<BasisSet> from_basis_name(std::string basis_name, std::shared_ptr<Structure> structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with basis set name and structure.

Parameters:
  • basis_name – Name of the basis set (e.g., “6-31G”, “cc-pVDZ”)

  • structure – Shared pointer to the molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

Returns:

Shared pointer to the created BasisSet

static std::shared_ptr<BasisSet> from_element_map(const std::map<std::string, std::string> &element_to_basis_map, const Structure &structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with basis set name and structure.

Parameters:
  • element_to_basis_map – Mapping from element symbols to basis set names

  • structure – The molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

Returns:

Shared pointer to the created BasisSet

static std::shared_ptr<BasisSet> from_element_map(const std::map<std::string, std::string> &element_to_basis_map, std::shared_ptr<Structure> structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with basis set name and structure.

Parameters:
  • element_to_basis_map – Mapping from element symbols to basis set names

  • structure – Shared pointer to the molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

Returns:

Shared pointer to the created BasisSet

static std::shared_ptr<BasisSet> from_file(const std::string &filename, const std::string &type)

Generic file I/O - load from file based on type parameter.

Parameters:
  • filename – Path to file to read

  • type – File format type (“json” or “hdf5”)

Throws:

std::runtime_error – if file doesn’t exist, unsupported type, or I/O error occurs

Returns:

New BasisSet instance loaded from file

static std::shared_ptr<BasisSet> from_hdf5(H5::Group &group)

Load basis set from HDF5 group.

Parameters:

group – HDF5 group to read data from

Throws:

std::runtime_error – if I/O error occurs

Returns:

Shared pointer to const BasisSet instance loaded from group

static std::shared_ptr<BasisSet> from_hdf5_file(const std::string &filename)

Load basis set from HDF5 file (with validation)

Parameters:

filename – Path to HDF5 file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const BasisSet instance loaded from file

static std::shared_ptr<BasisSet> from_index_map(const std::map<size_t, std::string> &index_to_basis_map, const Structure &structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with basis set name and structure.

Parameters:
  • index_to_basis_map – Mapping from atom indices (as strings) to basis set names

  • structure – The molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

Returns:

Shared pointer to the created BasisSet

static std::shared_ptr<BasisSet> from_index_map(const std::map<size_t, std::string> &index_to_basis_map, std::shared_ptr<Structure> structure, AOType atomic_orbital_type = AOType::Spherical)

Constructor with basis set name and structure.

Parameters:
  • index_to_basis_map – Mapping from atom indices (as strings) to basis set names

  • structure – Shared pointer to the molecular structure

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

Returns:

Shared pointer to the created BasisSet

static std::shared_ptr<BasisSet> from_json(const nlohmann::json &j)

Load basis set from JSON.

Parameters:

j – JSON object containing basis set data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Shared pointer to const BasisSet instance loaded from JSON

static std::shared_ptr<BasisSet> from_json_file(const std::string &filename)

Load basis set from JSON file (with validation)

Parameters:

filename – Path to JSON file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const BasisSet instance loaded from file

static int get_angular_momentum(OrbitalType orbital_type)

Get angular momentum quantum number for orbital type.

Parameters:

orbital_type – Type of orbital

Returns:

Angular momentum quantum number (l)

static int get_num_orbitals_for_l(int l, AOType atomic_orbital_type = AOType::Spherical)

Get number of orbitals for given angular momentum.

Parameters:
  • l – Angular momentum quantum number

  • atomic_orbital_type – Whether to use spherical or cartesian atomic orbitals

Returns:

Number of orbitals

static inline int get_orbital_size(OrbitalType orbital_type)
static std::vector<std::string> get_supported_basis_set_names()

Get supported basis set names.

Returns:

Vector of supported basis set names

static std::vector<Element> get_supported_elements_for_basis_set(std::string basis_name)

Get supported elements for a given basis set.

Parameters:

basis_name – Name of the basis set

Returns:

Vector of supported elements as enum

static OrbitalType l_to_orbital_type(int l)

Convert an integer orbital angular momentum quantum number to orbital type.

Parameters:

l – Angular momentum quantum number

Throws:

std::invalid_argument – if l is out of range

Returns:

Orbital type enumeration

static std::string orbital_type_to_string(OrbitalType orbital_type)

Convert orbital type to string.

Parameters:

orbital_type – Type of orbital

Returns:

String representation (e.g., “s”, “p”, “d”)

static AOType string_to_atomic_orbital_type(const std::string &basis_string)

Convert string to basis type.

Parameters:

basis_string – String representation (“spherical” or “cartesian”)

Throws:

std::invalid_argument – if string is invalid

Returns:

Basis type enumeration

static OrbitalType string_to_orbital_type(const std::string &orbital_string)

Convert string to orbital type.

Parameters:

orbital_string – String representation (e.g., “s”, “p”, “d”)

Throws:

std::invalid_argument – if string is invalid

Returns:

Orbital type enumeration

Public Static Attributes

static constexpr std::string_view custom_ecp_name = "custom_ecp"

Name for custom ecps.

static constexpr std::string_view custom_name = "custom_basis_set"

Name for custom basis sets.

template<typename T>
struct BoundConstraint
#include <qdk/chemistry/data/settings.hpp>

Constraint specifying minimum and maximum bounds for a setting value.

This constraint type defines inclusive bounds [min, max] for numeric settings. By default, min and max are set to the type’s limits.

Template Parameters:

T – The type of the bounded value (int64_t or double)

Public Members

T max = std::numeric_limits<T>::max()

Maximum allowed value (inclusive)

T min = std::numeric_limits<T>::min()

Minimum allowed value (inclusive)

class CanonicalFourCenterHamiltonianContainer : public qdk::chemistry::data::HamiltonianContainer
#include <qdk/chemistry/data/hamiltonian_containers/canonical_four_center.hpp>

Contains a molecular Hamiltonian using canonical four center integrals, implemented as a subclass of HamiltonianContainer.

This class stores molecular Hamiltonian data for quantum chemistry calculations, specifically designed for active space methods. It contains:

  • One-electron integrals (kinetic + nuclear attraction) in MO representation

  • Two-electron integrals (electron-electron repulsion) in MO representation

  • Molecular orbital information for the active space

  • Core energy contributions from inactive orbitals and nuclear repulsion

This class implies that all inactive orbitals are fully occupied for the purpose of computing the core energy and inactive Fock matrix.

The Hamiltonian is immutable after construction, meaning all data must be provided during construction and cannot be modified afterwards. The Hamiltonian supports both restricted and unrestricted calculations and integrates with the broader quantum chemistry framework for active space methods.

Public Functions

CanonicalFourCenterHamiltonianContainer(const Eigen::MatrixXd &one_body_integrals, const Eigen::VectorXd &two_body_integrals, std::shared_ptr<Orbitals> orbitals, double core_energy, const Eigen::MatrixXd &inactive_fock_matrix, HamiltonianType type = HamiltonianType::Hermitian)

Constructor for restricted active space Hamiltonian with four center integrals.

CanonicalFourCenterHamiltonianContainer(const Eigen::MatrixXd &one_body_integrals_alpha, const Eigen::MatrixXd &one_body_integrals_beta, const Eigen::VectorXd &two_body_integrals_aaaa, const Eigen::VectorXd &two_body_integrals_aabb, const Eigen::VectorXd &two_body_integrals_bbbb, std::shared_ptr<Orbitals> orbitals, double core_energy, const Eigen::MatrixXd &inactive_fock_matrix_alpha, const Eigen::MatrixXd &inactive_fock_matrix_beta, HamiltonianType type = HamiltonianType::Hermitian)

Constructor for unrestricted active space Hamiltonian with four center integrals using separate spin components.

CanonicalFourCenterHamiltonianContainer(SymmetryBlockedTensor<2> one_body, SymmetryBlockedTensor<4> two_body, std::shared_ptr<Orbitals> orbitals, double core_energy, std::shared_ptr<const SymmetryBlockedTensor<2>> inactive_fock, HamiltonianType type = HamiltonianType::Hermitian)

SymmetryBlockedTensor constructor.

Parameters:
~CanonicalFourCenterHamiltonianContainer() = default

Destructor.

virtual std::unique_ptr<HamiltonianContainer> clone() const override

Create a deep copy of this container.

Returns:

Unique pointer to a cloned container

virtual std::string get_container_type() const override

Get the type of the underlying container.

Returns:

String identifying the container type (e.g., “canonical_four_center”, “density_fitted”)

virtual double get_two_body_element(unsigned i, unsigned j, unsigned k, unsigned l, SpinChannel channel = SpinChannel::aaaa) const final override

Get specific two-electron integral element.

Parameters:
  • i – First orbital index

  • j – Second orbital index

  • k – Third orbital index

  • l – Fourth orbital index

  • channel – Spin channel to query (aaaa, aabb, or bbbb), defaults to aaaa

Throws:

std::out_of_range – if indices are invalid

Returns:

Two-electron integral (ij|kl)

virtual std::tuple<const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&> get_two_body_integrals() const final override

Get two-electron integrals in MO basis for all spin channels.

virtual bool has_two_body_integrals() const final override

Check if two-body integrals are available.

Returns:

True if two-body integrals are set

virtual bool is_restricted() const final override

Check if the Hamiltonian is restricted.

Returns:

True if alpha and beta integrals are identical

virtual bool is_valid() const final override

Check if the Hamiltonian data is complete and consistent.

Returns:

True if all required data is set and dimensions are consistent

virtual void to_hdf5(H5::Group &group) const override

Serialize Hamiltonian data to HDF5 group.

Parameters:

group – HDF5 group to write data to

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert Hamiltonian to JSON.

Returns:

JSON object containing Hamiltonian data

const SymmetryBlockedTensor<4> &two_body_integrals() const

Two-body integrals as a rank-4 symmetry-blocked tensor.

Throws:

std::runtime_error – if two-body integrals are not set.

Returns:

Const reference to the two-body SymmetryBlockedTensor.

const Eigen::VectorXd &two_body_integrals_block(const SymmetryLabel &p, const SymmetryLabel &q, const SymmetryLabel &r, const SymmetryLabel &s) const

Two-body integral block for the given symmetry labels.

Parameters:
  • p – First slot’s symmetry label.

  • q – Second slot’s symmetry label.

  • r – Third slot’s symmetry label.

  • s – Fourth slot’s symmetry label.

Throws:
  • std::runtime_error – if two-body integrals are not set.

  • std::invalid_argument – if no block is stored for the requested label tuple.

Returns:

Const reference to the flat-packed vector block stored for {p, q, r, s}.

Public Static Functions

static std::unique_ptr<CanonicalFourCenterHamiltonianContainer> from_hdf5(H5::Group &group)

Deserialize Hamiltonian data from HDF5 group.

Parameters:

group – HDF5 group to read data from

Throws:

std::runtime_error – if I/O error occurs

Returns:

Unique pointer to Hamiltonian loaded from group

static std::unique_ptr<CanonicalFourCenterHamiltonianContainer> from_json(const nlohmann::json &j)

Load Hamiltonian from JSON.

Parameters:

j – JSON object containing Hamiltonian data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Shared pointer to Hamiltonian loaded from JSON

class CholeskyHamiltonianContainer : public qdk::chemistry::data::HamiltonianContainer
#include <qdk/chemistry/data/hamiltonian_containers/cholesky.hpp>

Contains a molecular Hamiltonian expressed using three-center integrals.

In addition to those contained in HamiltonianContainer, this subclass also contains:

  • Three-center two-electron integrals (electron-electron repulsion) in MO representation.

  • Optionally, AO Cholesky vectors for potential reuse in further transformations.

Public Functions

CholeskyHamiltonianContainer(const Eigen::MatrixXd &one_body_integrals, const Eigen::MatrixXd &three_center_integrals, std::shared_ptr<Orbitals> orbitals, double core_energy, const Eigen::MatrixXd &inactive_fock_matrix, std::optional<Eigen::MatrixXd> ao_cholesky_vectors = std::nullopt, HamiltonianType type = HamiltonianType::Hermitian)

Constructor for restricted Cholesky Hamiltonian.

CholeskyHamiltonianContainer(const Eigen::MatrixXd &one_body_integrals_alpha, const Eigen::MatrixXd &one_body_integrals_beta, const Eigen::MatrixXd &three_center_integrals_aa, const Eigen::MatrixXd &three_center_integrals_bb, std::shared_ptr<Orbitals> orbitals, double core_energy, const Eigen::MatrixXd &inactive_fock_matrix_alpha, const Eigen::MatrixXd &inactive_fock_matrix_beta, std::optional<Eigen::MatrixXd> ao_cholesky_vectors = std::nullopt, HamiltonianType type = HamiltonianType::Hermitian)

Constructor for unrestricted Cholesky Hamiltonian.

CholeskyHamiltonianContainer(SymmetryBlockedTensor<2> one_body, SymmetryBlockedTensor<3> three_center, std::shared_ptr<Orbitals> orbitals, double core_energy, std::shared_ptr<const SymmetryBlockedTensor<2>> inactive_fock, std::optional<Eigen::MatrixXd> ao_cholesky_vectors = std::nullopt, HamiltonianType type = HamiltonianType::Hermitian)

SymmetryBlockedTensor constructor for Cholesky Hamiltonian.

Parameters:
  • one_body – One-body integrals as rank-2 SymmetryBlockedTensor.

  • three_center – Three-center integrals as a rank-3 SymmetryBlockedTensor with slots [MO_row, MO_col, auxiliary]. Each block is a dense [norb_row*norb_col, naux] MatrixXd.

  • orbitals – Shared pointer to molecular orbital data.

  • core_energy – Core energy.

  • inactive_fock – Inactive Fock matrix as rank-2 SymmetryBlockedTensor.

  • ao_cholesky_vectors – Optional AO Cholesky vectors.

  • typeHamiltonian type.

~CholeskyHamiltonianContainer() override = default

Destructor.

virtual std::unique_ptr<HamiltonianContainer> clone() const final override

Create a deep copy of this container.

Returns:

Unique pointer to a cloned container

const std::optional<Eigen::MatrixXd> &get_ao_cholesky_vectors() const

Get the optional AO Cholesky vectors.

Returns:

Const reference to the optional AO Cholesky vectors matrix [nao^2 x nchol]. Contains std::nullopt if AO Cholesky vectors were not provided at construction.

virtual std::string get_container_type() const final override

Get the type of the underlying container.

Returns:

String identifying the container type (e.g., “cholesky”)

std::pair<const Eigen::MatrixXd&, const Eigen::MatrixXd&> get_three_center_integrals() const

Get three-center integrals in MO basis for all spin channels.

Returns:

Pair of dense [norb^2, naux] MatrixXd for (alpha, beta).

virtual double get_two_body_element(unsigned i, unsigned j, unsigned k, unsigned l, SpinChannel channel = SpinChannel::aaaa) const override

Get specific four-center two-electron integral element.

Parameters:
  • i – First orbital index

  • j – Second orbital index

  • k – Third orbital index

  • l – Fourth orbital index

  • channel – Spin channel to query (aaaa, aabb, or bbbb), defaults to aaaa

Throws:

std::out_of_range – if indices are invalid

Returns:

Four-center two-electron integral (ij|kl)

virtual std::tuple<const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&> get_two_body_integrals() const override

Get four-center two-electron integrals in MO basis for all spin channels.

Throws:

std::runtime_error – if integrals are not set

Returns:

Tuple of references to (aaaa, aabb, bbbb) four-center two-electron integrals vectors

virtual bool has_two_body_integrals() const override

Check if two-body integrals are available.

Returns:

True if two-body integrals are set

virtual bool is_restricted() const final override

Check if the Hamiltonian is restricted.

Returns:

True if alpha and beta integrals are identical

virtual bool is_valid() const final override

Check if the Hamiltonian data is complete and consistent.

Returns:

True if all required data is set and dimensions are consistent

const SymmetryBlockedTensor<3> &three_center() const

Three-center integrals as a rank-3 symmetry-blocked tensor.

Slots are [MO_row, MO_col, auxiliary]; each block is a dense [norb_row*norb_col, naux] MatrixXd.

virtual void to_hdf5(H5::Group &group) const final override

Serialize Hamiltonian data to HDF5 group.

Parameters:

group – HDF5 group to write data to

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const final override

Convert Hamiltonian to JSON.

Returns:

JSON object containing Hamiltonian data

Public Static Functions

static std::unique_ptr<CholeskyHamiltonianContainer> from_hdf5(H5::Group &group)

Deserialize Hamiltonian data from HDF5 group.

Parameters:

group – HDF5 group to read data from

Throws:

std::runtime_error – if I/O error occurs

Returns:

Unique pointer to const CholeskyHamiltonianContainer loaded from group

static std::unique_ptr<CholeskyHamiltonianContainer> from_json(const nlohmann::json &j)

Load Hamiltonian from JSON.

Parameters:

j – JSON object containing Hamiltonian data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Unique pointer to const CholeskyHamiltonianContainer loaded from JSON

class Configuration : public qdk::chemistry::data::DataClass
#include <qdk/chemistry/data/configuration.hpp>

Represents a configuration (or occupation number vector) with efficient bit-packing.

The Configuration class provides a memory-efficient representation of single-particle mode occupations. For spin-½ systems (2 bits per mode), each mode can be unoccupied, alpha-occupied, beta-occupied, or doubly occupied. For generic systems (1 bit per mode), each mode is simply occupied or unoccupied.

Public Functions

Configuration() = default

Default constructor.

Creates an empty spin-½ configuration with 0 modes.

uint8_t bits_per_mode() const

Bits used to encode each mode (1 for spinless, 2 for spin-½).

Returns:

Bits per mode.

size_t capacity() const

Number of single-particle modes in the configuration.

Returns:

Number of modes (same as get_orbital_capacity).

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“configuration”

uint8_t get_mode_state(size_t idx) const

Raw state value for mode idx (range 0 to 2^bits_per_mode - 1).

Parameters:

idx – Mode index (0-indexed).

Throws:

std::out_of_range – if idx >= capacity().

Returns:

Packed state value for the mode.

std::tuple<size_t, size_t> get_n_electrons() const

Get the number of alpha and beta electrons in the configuration.

Throws:

std::runtime_error – if bits_per_mode() != 2

Returns:

A tuple containing (number of alpha electrons, number of beta electrons)

size_t get_orbital_capacity() const

Get the max orbital capacity of the configuration.

Returns:

Number of modes the configuration can represent.

virtual std::string get_summary() const override

Get a summary string describing the configuration.

Returns:

String containing configuration summary information

bool has_alpha_electron(size_t orbital_idx) const

Check if a specific orbital has an alpha electron (spin-½ only).

Parameters:

orbital_idx – The orbital index (0-indexed)

Throws:

std::runtime_error – if bits_per_mode() != 2

Returns:

true if the orbital has an alpha electron, false otherwise

bool has_beta_electron(size_t orbital_idx) const

Check if a specific orbital has a beta electron (spin-½ only).

Parameters:

orbital_idx – The orbital index (0-indexed)

Throws:

std::runtime_error – if bits_per_mode() != 2

Returns:

true if the orbital has a beta electron, false otherwise

bool is_closed_shell() const

Whether the configuration is closed-shell (spin-½ only).

Closed-shell means every spatial orbital is either unoccupied or doubly occupied — there are no singly-occupied (open-shell) orbitals. The resulting alpha and beta occupation patterns are identical.

Returns:

true iff no orbital is singly occupied.

bool operator!=(const Configuration &other) const

Inequality comparison operator.

Parameters:

other – The configuration to compare with

Returns:

true if the configurations differ, false if they are identical

bool operator==(const Configuration &other) const

Equality comparison operator.

Note

Used for std::find and other algorithms

Parameters:

other – The configuration to compare with

Returns:

true if the configurations are identical, false otherwise

const std::vector<uint8_t> &packed_data() const

Return a const reference to the raw packed byte storage.

Each byte packs (8 / bits_per_mode) modes. Use bits_per_mode() and the true mode count from the owning container to interpret the data.

Returns:

Const reference to the internal packed byte vector.

std::pair<std::string, std::string> to_binary_strings(size_t num_orbitals) const

Convert configuration to separate alpha and beta binary strings in little-endian format (spin-½ only).

Parameters:

num_orbitals – How many orbitals to extract

Throws:

std::runtime_error – If bits_per_mode() != 2 or num_orbitals exceeds capacity

Returns:

Pair of binary strings (alpha, beta)

template<size_t N>
inline std::bitset<N> to_bitset() const

Convert to a bitset representation.

For spin-½ (2 bits/mode): N must be even; alpha occupations fill the low half, beta the high half. For bitstring (1 bit/mode): one bit per mode in the low capacity() positions.

Template Parameters:

N – Size of the returned bitset.

Throws:

std::invalid_argument – If the configuration doesn’t fit in N bits.

Returns:

Bitset representation of the configuration.

virtual void to_file(const std::string &filename, const std::string &type) const override

Save configuration to file in the specified format.

Parameters:
  • filename – Path to the output file

  • type – Format type (“json” or “hdf5”)

Throws:
  • std::invalid_argument – if format type is not supported

  • std::runtime_error – if I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Save configuration to HDF5 group.

Parameters:

group – HDF5 group to save data to

Throws:

std::runtime_error – if I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save configuration to HDF5 file.

Parameters:

filename – Path to the output HDF5 file

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert configuration to JSON representation.

Returns:

JSON object containing the serialized data

virtual void to_json_file(const std::string &filename) const override

Save configuration to JSON file.

Parameters:

filename – Path to the output JSON file

Throws:

std::runtime_error – if I/O error occurs

std::string to_string() const

Convert the configuration to a string representation.

Returns:

For spin-½ (2 bits/mode): '0'/ bitstring (1 bit/mode): '0'/.

size_t total_occupation() const

Total occupation summed over all modes.

For spin-½ modes the per-mode occupation is the popcount of the 2-bit state (0, 1, 1, or 2). For spinless modes it is the 1-bit value itself.

Returns:

Sum of per-mode occupations.

Public Static Functions

static Configuration canonical_hf_configuration(size_t n_alpha, size_t n_beta, size_t n_orbitals)

Create a canonical Hartree-Fock configuration using the Aufbau principle (spin-½ only).

Parameters:
  • n_alpha – Number of alpha electrons

  • n_beta – Number of beta electrons

  • n_orbitals – Total number of orbitals

Returns:

Configuration representing the HF ground state (2 bits/mode)

static Configuration from_binary_strings(std::string alpha_string, std::string beta_string)

Convert separate alpha and beta binary strings to a spin-½ Configuration (2 bits/mode).

Parameters:
  • alpha_string – Alpha occupation string (‘0’/’1’)

  • beta_string – Beta occupation string (‘0’/’1’)

Returns:

Configuration object with bits_per_mode() == 2

static Configuration from_bitstring(const std::string &str)

Construct from a bitstring (1 bit per mode).

Parameters:

str – String with alphabet '0'/.

Throws:

std::invalid_argument – If the string contains invalid characters.

Returns:

Configuration with bits_per_mode() == 1.

template<size_t N>
static inline Configuration from_bitstring_bitset(const std::bitset<N> &orbs, size_t num_modes)

Construct from a flat bitset (1 bit per mode).

Template Parameters:

N – Size of the bitset.

Parameters:
  • orbs – Bitset with one bit per mode.

  • num_modes – Number of modes to extract.

Throws:

std::invalid_argument – If num_modes exceeds N.

Returns:

Configuration with bits_per_mode() == 1.

static Configuration from_file(const std::string &filename, const std::string &type)

Load configuration from file in specified format.

Parameters:
  • filename – Path to file to read

  • type – Format type (“json” or “hdf5”)

Throws:
  • std::invalid_argument – if unknown type

  • std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

New Configuration instance loaded from file

static Configuration from_hdf5(H5::Group &group)

Load configuration from HDF5 group.

Parameters:

group – HDF5 group to read from

Throws:

std::runtime_error – if I/O error occurs

Returns:

New Configuration instance created from HDF5 data

static Configuration from_hdf5_file(const std::string &filename)

Load configuration from HDF5 file.

Parameters:

filename – Path to HDF5 file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

New Configuration instance loaded from file

static Configuration from_json(const nlohmann::json &j)

Load configuration from JSON.

Parameters:

j – JSON object containing configuration data

Throws:

std::runtime_error – if JSON is malformed

Returns:

New Configuration instance created from JSON

static Configuration from_json_file(const std::string &filename)

Load configuration from JSON file.

Parameters:

filename – Path to JSON file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

New Configuration instance loaded from file

template<size_t N>
static inline Configuration from_spin_half_bitset(const std::bitset<N> &orbs, size_t num_orbitals)

Construct from an alpha/beta bitset (spin-½).

Template Parameters:

N – Size of the bitset (must be even).

Parameters:
  • orbs – Bitset with alpha in the low half and beta in the high half.

  • num_orbitals – Number of spatial orbitals to extract.

Throws:

std::invalid_argument – If num_orbitals exceeds N/2.

Returns:

Configuration with bits_per_mode() == 2.

static Configuration from_spin_half_string(const std::string &str)

Construct from a spin-½ string representation.

Parameters:

str – String with alphabet '0'/ Configuration with bits_per_mode() == 2.

Throws:

std::invalid_argument – If the string contains invalid characters.

class ConfigurationSet : public qdk::chemistry::data::DataClass
#include <qdk/chemistry/data/configuration_set.hpp>

Associates a collection of Configuration objects with orbital information.

This class manages a set of configurations that share the same single-particle basis, specifically the active space of an Orbitals object. By storing the orbital information at the set level rather than in each configuration, we eliminate redundant storage of the number of orbitals.

Key design points:

  • Configurations represent only the active space, not the full orbital set

  • Inactive and virtual orbitals are not included in the configuration representation

  • All configurations in the set must be consistent with the active space size

  • Provides iteration and access methods similar to std::vector

  • Immutable after construction to ensure consistency

Public Functions

ConfigurationSet(const std::vector<Configuration> &configurations, std::shared_ptr<Orbitals> orbitals, std::string sector)

Construct a ConfigurationSet from configurations and orbital information.

Note

All configurations must have the same number of orbitals and sufficient capacity to represent the active space defined in the orbitals object. Configurations only represent the active space; inactive and virtual orbitals are not included in the configuration representation.

Parameters:
  • configurations – Vector of configurations (representing active space only)

  • orbitals – Shared pointer to orbital basis set

  • sector – Name of the single-particle sector the orbitals belong to

Throws:

std::invalid_argument – if configurations are inconsistent with active space or if orbitals pointer is null

ConfigurationSet(std::vector<Configuration> &&configurations, std::shared_ptr<Orbitals> orbitals, std::string sector)
const Configuration &at(size_t idx) const

Access configuration by index with bounds checking.

Parameters:

idx – Index

Throws:

std::out_of_range – if index is invalid

Returns:

Const reference to configuration

std::vector<Configuration>::const_iterator begin() const
std::vector<Configuration>::const_iterator cbegin() const
std::vector<Configuration>::const_iterator cend() const
bool empty() const

Check if the set is empty.

Returns:

True if empty

std::vector<Configuration>::const_iterator end() const
const std::vector<Configuration> &get_configurations() const

Get the configurations.

Returns:

Const reference to vector of configurations

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“configuration_set”

std::shared_ptr<Orbitals> get_orbitals() const

Get the orbital information.

Returns:

Shared pointer to orbitals

virtual std::string get_summary() const override

Get a summary string describing the configuration set.

Returns:

String containing object summary information

size_t num_modes() const

Get the actual number of single-particle modes represented by each configuration (not byte-padded).

This is derived from the orbital basis: the active-space size if an active space is defined, otherwise the total number of molecular orbitals.

Returns:

Non-padded mode count.

bool operator!=(const ConfigurationSet &other) const

Check inequality with another ConfigurationSet.

Parameters:

other – Other set

Returns:

True if not equal

bool operator==(const ConfigurationSet &other) const

Check equality with another ConfigurationSet.

Parameters:

other – Other set

Returns:

True if equal (same configurations and orbitals point to same object)

const Configuration &operator[](size_t idx) const

Access configuration by index.

Parameters:

idx – Index

Returns:

Const reference to configuration

const std::vector<std::pair<std::string, std::shared_ptr<Orbitals>>> &sector_layout() const

Get the sector layout: the ordered partition of a configuration’s slots across named single-particle sectors.

Each entry pairs a sector name with the single-particle basis whose modes occupy that segment. Today this is a single entry (the sector name supplied at construction, backed by get_orbitals); mixed-statistics systems will return several entries.

Returns:

Reference to the ordered sector layout.

size_t size() const

Get the number of configurations in the set.

Returns:

Number of configurations

virtual void to_file(const std::string &filename, const std::string &type) const override

Save object to file in the specified format.

Parameters:
  • filename – Path to the output file

  • type – Format type (e.g., “json”, “hdf5”)

Throws:
  • std::invalid_argument – if format type is not supported

  • std::runtime_error – if I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Serialize configuration set to HDF5.

Note

This serializes both configurations and orbitals recursively

Parameters:

group – HDF5 group to write to

virtual void to_hdf5_file(const std::string &filename) const override

Save object to HDF5 file.

Parameters:

filename – Path to the output HDF5 file

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Serialize configuration set to JSON.

Note

This serializes both configurations and orbitals recursively

Returns:

JSON representation (includes configurations and orbitals)

virtual void to_json_file(const std::string &filename) const override

Save object to JSON file.

Parameters:

filename – Path to the output JSON file

Throws:

std::runtime_error – if I/O error occurs

Public Static Functions

static ConfigurationSet from_file(const std::string &filename, const std::string &type)

Load configuration set from file in the specified format.

Parameters:
  • filename – Path to the input file

  • type – Format type (e.g., “json”, “hdf5”)

Throws:
  • std::invalid_argument – if format type is not supported

  • std::runtime_error – if I/O error occurs

Returns:

ConfigurationSet object

static ConfigurationSet from_hdf5(H5::Group &group)

Deserialize configuration set from HDF5.

Note

Orbitals are deserialized from the HDF5 “orbitals” subgroup

Parameters:

group – HDF5 group to read from

Returns:

ConfigurationSet object

static ConfigurationSet from_hdf5_file(const std::string &filename)

Load configuration set from HDF5 file.

Parameters:

filename – Path to the input HDF5 file

Throws:

std::runtime_error – if I/O error occurs

Returns:

ConfigurationSet object

static ConfigurationSet from_json(const nlohmann::json &j)

Deserialize configuration set from JSON.

Note

Orbitals are deserialized from the JSON “orbitals” field

Parameters:

j – JSON object containing configuration and orbital data

Returns:

ConfigurationSet object

static ConfigurationSet from_json_file(const std::string &filename)

Load configuration set from JSON file.

Parameters:

filename – Path to the input JSON file

Throws:

std::runtime_error – if I/O error occurs

Returns:

ConfigurationSet object

class DataClass
#include <qdk/chemistry/data/data_class.hpp>

Base interface class providing common methods for data classes.

This class defines a common interface that all QDK chemistry data classes should implement.

Subclassed by qdk::chemistry::data::SymmetryBlocked< 1, std::vector< std::uint32_t > >, qdk::chemistry::data::SymmetryBlocked< 1, std::size_t >, qdk::chemistry::data::SymmetryBlocked< Rank, SparseMapBlock< Rank, double > >, qdk::chemistry::data::SymmetryBlocked< Rank, Tensor< Rank, double > >, qdk::chemistry::data::Ansatz, qdk::chemistry::data::BasisSet, qdk::chemistry::data::Configuration, qdk::chemistry::data::ConfigurationSet, qdk::chemistry::data::Hamiltonian, qdk::chemistry::data::LatticeGraph, qdk::chemistry::data::MajoranaMapping, qdk::chemistry::data::NuclearGradients, qdk::chemistry::data::NuclearHessian, qdk::chemistry::data::Orbitals, qdk::chemistry::data::Settings, qdk::chemistry::data::StabilityResult, qdk::chemistry::data::Structure, qdk::chemistry::data::SymmetryAxis, qdk::chemistry::data::SymmetryBlocked< Rank, Block >, qdk::chemistry::data::SymmetryProduct, qdk::chemistry::data::TaperingSpecification, qdk::chemistry::data::Wavefunction

Public Functions

virtual ~DataClass() = default
inline virtual std::string content_hash(size_t truncate_chars = 16) const

Compute a deterministic content hash of this object’s identifying data.

Returns a truncated hex digest (16 hex chars = 64 bits by default). Two objects with identical defining data will produce identical hashes within a compatible build. Lazy/cached data is excluded; only constructor-supplied data participates. Content hashes are cache keys for checkpoint/restart workflows, not stable archival identifiers across releases.

Parameters:

truncate_chars – Number of hex characters in the result (default 16)

Returns:

Hex string content hash

virtual std::string get_data_type_name() const = 0

Get the data type name for this class.

This is used for file naming conventions and serialization. Derived classes must override this to return their specific type name.

Returns:

String containing the data type name (e.g., “structure”, “wavefunction”)

virtual std::string get_summary() const = 0

Get a summary string describing the object.

Returns:

String containing object summary information

virtual void to_file(const std::string &filename, const std::string &type) const = 0

Save object to file in the specified format.

Parameters:
  • filename – Path to the output file

  • type – Format type (e.g., “json”, “hdf5”, “xyz”)

Throws:
  • std::invalid_argument – if format type is not supported

  • std::runtime_error – if I/O error occurs

virtual void to_hdf5(H5::Group &group) const = 0

Save object to HDF5 group.

Parameters:

group – HDF5 group to save data to

Throws:

std::runtime_error – if I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const = 0

Save object to HDF5 file.

Parameters:

filename – Path to the output HDF5 file

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const = 0

Convert object to JSON representation.

Returns:

JSON object containing the serialized data

virtual void to_json_file(const std::string &filename) const = 0

Save object to JSON file.

Parameters:

filename – Path to the output JSON file

Throws:

std::runtime_error – if I/O error occurs

class Hamiltonian : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<Hamiltonian>
#include <qdk/chemistry/data/hamiltonian.hpp>

Provides an interface to a molecular Hamiltonian in the molecular orbital basis by wrapping an implementation from HamiltonianContainer.

This class provides an interface to molecular Hamiltonian data for quantum chemistry calculations, specifically designed for active space methods. It interfaces with a HamiltonianContainer that stores:

  • One-electron integrals (kinetic + nuclear attraction) in MO representation

  • Two-electron integrals (electron-electron repulsion) in MO representation

  • Molecular orbital information for the active space

  • Core energy contributions from inactive orbitals and nuclear repulsion

Public Functions

Hamiltonian(const Hamiltonian &other)

Copy constructor.

Hamiltonian(Hamiltonian &&other) noexcept = default

Move constructor.

Hamiltonian(std::unique_ptr<HamiltonianContainer> container)

Constructor for Hamiltonian with a HamiltonianContainer.

Parameters:

container – Unique pointer to HamiltonianContainer holding the data

~Hamiltonian() = default

Destructor.

template<typename T>
inline const T &get_container() const

Get typed reference to the underlying container.

Template Parameters:

T – Container type to cast to

Throws:

std::bad_cast – if container is not of type T

Returns:

Reference to container as type T

std::string get_container_type() const

Get the type of the underlying container.

Returns:

String identifying the container type (e.g., “canonical_four_center”, “density_fitted”)

double get_core_energy() const

Get core energy.

Returns:

Core energy in atomic units

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“hamiltonian”

std::pair<const Eigen::MatrixXd&, const Eigen::MatrixXd&> get_inactive_fock_matrix() const

Get tuple of inactive Fock matrices (alpha, beta) for the selected active space.

Throws:

std::runtime_error – if inactive Fock matrix is not set

Returns:

Reference to the inactive Fock matrix

double get_one_body_element(unsigned i, unsigned j, SpinChannel channel = SpinChannel::aa) const

Get specific one-electron integral element.

Parameters:
  • i – First orbital index

  • j – Second orbital index

  • channel – Spin channel to query (aa, or bb), defaults to aa

Throws:

std::out_of_range – if indices are invalid

Returns:

One-electron integral (i|h|j);

std::tuple<const Eigen::MatrixXd&, const Eigen::MatrixXd&> get_one_body_integrals() const

Get tuple of alpha, beta one-electron integrals in MO basis.

Throws:

std::runtime_error – if integrals are not set

Returns:

Reference to alpha, beta one-electron integrals matrices

const std::shared_ptr<Orbitals> get_orbitals() const

Get molecular orbital data.

Throws:

std::runtime_error – if orbitals are not set

Returns:

Reference to the orbitals object

virtual std::string get_summary() const override

Get summary string of Hamiltonian information.

Returns:

String describing the Hamiltonian

double get_two_body_element(unsigned i, unsigned j, unsigned k, unsigned l, SpinChannel channel = SpinChannel::aaaa) const

Get specific two-electron integral element.

Parameters:
  • i – First orbital index

  • j – Second orbital index

  • k – Third orbital index

  • l – Fourth orbital index

  • channel – Spin channel to query (aaaa, aabb, or bbbb), defaults to aaaa

Throws:

std::out_of_range – if indices are invalid

Returns:

Two-electron integral (ij|kl)

std::tuple<const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&> get_two_body_integrals() const

Get two-electron integrals in MO basis for all spin channels.

Throws:

std::runtime_error – if integrals are not set

Returns:

Tuple of references to (aaaa, aabb, bbbb) two-electron integrals vectors

HamiltonianType get_type() const

Get the type of Hamiltonian (Hermitian or NonHermitian)

Returns:

HamiltonianType enum value

template<typename T>
inline bool has_container_type() const

Check if container is of specific type.

Template Parameters:

T – Container type to check

Returns:

True if container is of type T

bool has_inactive_fock_matrix() const

Check if inactive Fock matrix is available.

Returns:

True if inactive Fock matrix is set

bool has_one_body_integrals() const

Check if one-body integrals are available.

Returns:

True if one-body integrals are set

bool has_orbitals() const

Check if orbital data is available.

Returns:

True if orbitals are set

bool has_two_body_integrals() const

Check if two-body integrals are available.

Returns:

True if two-body integrals are set

bool is_hermitian() const

Check if the Hamiltonian is Hermitian.

Returns:

True if the Hamiltonian type is Hermitian

bool is_restricted() const

Check if the Hamiltonian is restricted.

Returns:

True if alpha and beta integrals are identical

bool is_unrestricted() const

Check if the Hamiltonian is unrestricted.

Returns:

True if alpha and beta integrals are different

Hamiltonian &operator=(const Hamiltonian &other)

Copy assignment operator.

Hamiltonian &operator=(Hamiltonian &&other) noexcept = default

Move assignment operator.

void to_fcidump_file(const std::string &filename, size_t nalpha, size_t nbeta) const

Save Hamiltonian to an FCIDUMP file.

Parameters:
  • filename – Path to FCIDUMP file to create/overwrite

  • nalpha – Number of alpha electrons

  • nbeta – Number of beta electrons

Throws:

std::runtime_error – if I/O error occurs

virtual void to_file(const std::string &filename, const std::string &type) const override

Generic file I/O - save to file based on type parameter.

Parameters:
  • filename – Path to file to create/overwrite

  • type – File format type (“json” or “hdf5”)

Throws:

std::runtime_error – if unsupported type or I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Serialize Hamiltonian data to HDF5 group.

Parameters:

group – HDF5 group to write data to

Throws:

std::runtime_error – if I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save Hamiltonian to HDF5 file (with validation)

Parameters:

filename – Path to HDF5 file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert Hamiltonian to JSON.

Returns:

JSON object containing Hamiltonian data

virtual void to_json_file(const std::string &filename) const override

Save Hamiltonian to JSON file (with validation)

Parameters:

filename – Path to JSON file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

Public Static Functions

static std::shared_ptr<Hamiltonian> from_file(const std::string &filename, const std::string &type)

Generic file I/O - load from file based on type parameter.

Parameters:
  • filename – Path to file to read

  • type – File format type (“json” or “hdf5”)

Throws:

std::runtime_error – if file doesn’t exist, unsupported type, or I/O error occurs

Returns:

Shared pointer to const Hamiltonian loaded from file

static std::shared_ptr<Hamiltonian> from_hdf5(H5::Group &group)

Deserialize Hamiltonian data from HDF5 group.

Parameters:

group – HDF5 group to read data from

Throws:

std::runtime_error – if I/O error occurs

Returns:

Shared pointer to const Hamiltonian loaded from group

static std::shared_ptr<Hamiltonian> from_hdf5_file(const std::string &filename)

Load Hamiltonian from HDF5 file (with validation)

Parameters:

filename – Path to HDF5 file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const Hamiltonian loaded from file

static std::shared_ptr<Hamiltonian> from_json(const nlohmann::json &j)

Load Hamiltonian from JSON.

Parameters:

j – JSON object containing Hamiltonian data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Shared pointer to const Hamiltonian loaded from JSON

static std::shared_ptr<Hamiltonian> from_json_file(const std::string &filename)

Load Hamiltonian from JSON file (with validation)

Parameters:

filename – Path to JSON file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const Hamiltonian loaded from file

class HamiltonianContainer
#include <qdk/chemistry/data/hamiltonian.hpp>

Pure virtual base class for a molecular Hamiltonian implementation in the molecular orbital basis.

Concrete subclasses must provide an implementation that defines the underlying storage and/or computation mechanism for two-electron integrals.

This class stores molecular Hamiltonian data for quantum chemistry calculations, specifically designed for active space methods. It contains:

  • One-electron integrals (kinetic + nuclear attraction) in MO representation

  • Molecular orbital information for the active space

  • Core energy contributions from inactive orbitals and nuclear repulsion

Note that this class does not store two-electron integrals; derived classes are expected to implement storage and access for these integrals.

This class implies that all inactive orbitals are fully occupied for the purpose of computing the core energy and inactive Fock matrix.

The Hamiltonian is immutable after construction, meaning all data must be provided during construction and cannot be modified afterwards. The Hamiltonian supports both restricted and unrestricted calculations and integrates with the broader quantum chemistry framework for active space methods.

Subclassed by qdk::chemistry::data::CanonicalFourCenterHamiltonianContainer, qdk::chemistry::data::CholeskyHamiltonianContainer, qdk::chemistry::data::SparseHamiltonianContainer

Public Functions

HamiltonianContainer(const Eigen::MatrixXd &one_body_integrals, std::shared_ptr<Orbitals> orbitals, double core_energy, const Eigen::MatrixXd &inactive_fock_matrix, HamiltonianType type = HamiltonianType::Hermitian)

Constructor for active space Hamiltonian with shared_ptr orbitals and inactive Fock matrix (restricted).

HamiltonianContainer(const Eigen::MatrixXd &one_body_integrals_alpha, const Eigen::MatrixXd &one_body_integrals_beta, std::shared_ptr<Orbitals> orbitals, double core_energy, const Eigen::MatrixXd &inactive_fock_matrix_alpha, const Eigen::MatrixXd &inactive_fock_matrix_beta, HamiltonianType type = HamiltonianType::Hermitian)

Constructor for unrestricted active space Hamiltonian with separate spin components.

HamiltonianContainer(SymmetryBlockedTensor<2> one_body, std::shared_ptr<Orbitals> orbitals, double core_energy, std::shared_ptr<const SymmetryBlockedTensor<2>> inactive_fock, HamiltonianType type = HamiltonianType::Hermitian)

SymmetryBlockedTensor constructor for active space Hamiltonian.

Parameters:
  • one_body – One-body integrals as a rank-2 symmetry-blocked tensor.

  • orbitals – Shared pointer to molecular orbital data.

  • core_energy – Core energy.

  • inactive_fock – Inactive Fock matrix as a rank-2 symmetry-blocked tensor.

  • type – Type of Hamiltonian (Hermitian by default).

Throws:

std::invalid_argument – if orbitals pointer is nullptr

virtual ~HamiltonianContainer() = default

Destructor.

virtual std::unique_ptr<HamiltonianContainer> clone() const = 0

Create a deep copy of this container.

Returns:

Unique pointer to a cloned container

virtual std::string get_container_type() const = 0

Get the type of the underlying container.

Returns:

String identifying the container type (e.g., “canonical_four_center”, “density_fitted”)

double get_core_energy() const

Get core energy.

Returns:

Core energy in atomic units

std::pair<const Eigen::MatrixXd&, const Eigen::MatrixXd&> get_inactive_fock_matrix() const

Get inactive Fock matrix for the selected active space.

double get_one_body_element(unsigned i, unsigned j, SpinChannel channel = SpinChannel::aa) const

Get specific one-electron integral element.

Parameters:
  • i – First orbital index

  • j – Second orbital index

  • channel – Spin channel to query (aa, or bb), defaults to aa

Throws:

std::out_of_range – if indices are invalid

Returns:

One-electron integral (i|h|j)

std::tuple<const Eigen::MatrixXd&, const Eigen::MatrixXd&> get_one_body_integrals() const

Get tuple of alpha, beta one-electron integrals in MO basis.

const std::shared_ptr<Orbitals> get_orbitals() const

Get molecular orbital data.

Throws:

std::runtime_error – if orbitals are not set

Returns:

Reference to the orbitals object

virtual double get_two_body_element(unsigned i, unsigned j, unsigned k, unsigned l, SpinChannel channel = SpinChannel::aaaa) const = 0

Get specific two-electron integral element.

Parameters:
  • i – First orbital index

  • j – Second orbital index

  • k – Third orbital index

  • l – Fourth orbital index

  • channel – Spin channel to query (aaaa, aabb, or bbbb), defaults to aaaa

Throws:

std::out_of_range – if indices are invalid

Returns:

Two-electron integral (ij|kl)

virtual std::tuple<const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&> get_two_body_integrals() const = 0

Get two-electron integrals in MO basis for all spin channels.

Throws:

std::runtime_error – if integrals are not set

Returns:

Tuple of references to (aaaa, aabb, bbbb) two-electron integrals vectors

HamiltonianType get_type() const

Get the type of Hamiltonian (Hermitian or NonHermitian)

Returns:

HamiltonianType enum value

bool has_inactive_fock_matrix() const

Check if inactive Fock matrix is available.

Returns:

True if inactive Fock matrix is set

bool has_one_body_integrals() const

Check if one-body integrals are available.

Returns:

True if one-body integrals are set

bool has_orbitals() const

Check if orbital data is available.

Returns:

True if orbitals are set

virtual bool has_two_body_integrals() const = 0

Check if two-body integrals are available.

Returns:

True if two-body integrals are set

virtual void hash_update(qdk::chemistry::utils::HashContext &ctx) const

Feed identifying data into a hash context.

Subclasses override to add their container-specific data.

const SymmetryBlockedTensor<2> &inactive_fock() const

Inactive Fock matrix as a rank-2 symmetry-blocked tensor.

Throws:

std::runtime_error – if not set.

Returns:

Const reference to the inactive Fock SymmetryBlockedTensor.

const Eigen::MatrixXd &inactive_fock_block(const SymmetryLabel &row, const SymmetryLabel &col) const

Inactive Fock block for the given row/column symmetry labels.

Parameters:
  • row – Row-slot symmetry label.

  • col – Column-slot symmetry label.

Throws:
  • std::runtime_error – if the inactive Fock matrix is not set.

  • std::invalid_argument – if no block is stored for the requested label pair.

Returns:

Const reference to the matrix block stored for {row, col}.

bool is_hermitian() const

Check if the Hamiltonian is Hermitian.

Returns:

True if the Hamiltonian type is Hermitian

virtual bool is_restricted() const = 0

Check if the Hamiltonian is restricted.

Returns:

True if alpha and beta integrals are identical

bool is_unrestricted() const

Check if the Hamiltonian is unrestricted.

Returns:

True if alpha and beta integrals are different

virtual bool is_valid() const = 0

Check if the Hamiltonian data is complete and consistent.

Returns:

True if all required data is set and dimensions are consistent

const SymmetryBlockedTensor<2> &one_body_integrals() const

One-body integrals as a rank-2 symmetry-blocked tensor.

Throws:

std::runtime_error – if one-body integrals are not set.

Returns:

Const reference to the one-body SymmetryBlockedTensor.

const Eigen::MatrixXd &one_body_integrals_block(const SymmetryLabel &row, const SymmetryLabel &col) const

One-body integral block for the given row/column symmetry labels.

Parameters:
  • row – Row-slot symmetry label.

  • col – Column-slot symmetry label.

Throws:
  • std::runtime_error – if one-body integrals are not set.

  • std::invalid_argument – if no block is stored for the requested label pair.

Returns:

Const reference to the matrix block stored for {row, col}.

virtual void to_fcidump_file(const std::string &filename, size_t nalpha, size_t nbeta) const

Save Hamiltonian to an FCIDUMP file.

Parameters:
  • filename – Path to FCIDUMP file to create/overwrite

  • nalpha – Number of alpha electrons

  • nbeta – Number of beta electrons

Throws:

std::runtime_error – if I/O error occurs or Hamiltonian is unrestricted

virtual void to_hdf5(H5::Group &group) const = 0

Serialize Hamiltonian data to HDF5 group.

Parameters:

group – HDF5 group to write data to

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const = 0

Convert Hamiltonian to JSON.

Returns:

JSON object containing Hamiltonian data

Public Static Functions

static std::unique_ptr<HamiltonianContainer> from_hdf5(H5::Group &group)

Deserialize Hamiltonian data from HDF5 group.

Parameters:

group – HDF5 group to read data from

Throws:

std::runtime_error – if I/O error occurs

Returns:

Unique pointer to Hamiltonian loaded from group

static std::unique_ptr<HamiltonianContainer> from_json(const nlohmann::json &j)

Load Hamiltonian from JSON.

Parameters:

j – JSON object containing Hamiltonian data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Unique pointer to Hamiltonian loaded from JSON

template<typename T, typename Variant>
struct is_variant_member_impl

Concept to check if a type is a member of a std::variant.

Template Parameters:
  • T – The type to check

  • Variant – The variant type to check against

template<typename T>
struct is_vector_impl : public std::false_type
#include <qdk/chemistry/data/settings.hpp>

Concept to detect if a type is a std::vector.

Template Parameters:

T – The type to check

template<std::size_t Rank>
struct LabelsHash
#include <qdk/chemistry/data/symmetry/symmetry_blocked.hpp>

Hash of an array of SymmetryLabel used to key blocks by their per-slot symmetry labels.

Template Parameters:

Rank – Number of label slots.

Public Functions

inline std::size_t operator()(const std::array<SymmetryLabel, Rank> &labels) const noexcept

Combine the per-slot SymmetryLabel hashes into a single hash suitable for use as an unordered_map key.

Parameters:

labels – Per-slot symmetry labels keying one block.

Returns:

Hash value derived from the concatenation of per-slot label hashes via qdk::chemistry::utils::hash_combine.

class LatticeGraph : public qdk::chemistry::data::DataClass
#include <qdk/chemistry/data/lattice_graph.hpp>

Weighted graph representing a lattice connectivity structure.

Stores the lattice topology as a sparse adjacency matrix and provides static factory methods for common lattice geometries. Used by model Hamiltonian builders to define site connectivity and hopping integrals.

Public Functions

LatticeGraph(const std::map<std::pair<std::uint64_t, std::uint64_t>, double> &edge_weights, std::uint64_t num_sites = 0)

Construct a lattice graph from an edge-weight map.

Each key is a pair (i, j) of site indices and each value is the corresponding edge weight. Edges are stored exactly as given; use make_bidirectional() to add reverse edges from one-directional input.

Parameters:
  • edge_weights – Map of (source, target) -> weight.

  • num_sites – Total number of sites. If 0, inferred from the largest index in edge_weights.

~LatticeGraph() = default
Eigen::MatrixXd adjacency_matrix() const

Return a dense copy of the adjacency matrix.

bool are_connected(std::uint64_t i, std::uint64_t j) const

Check whether sites i and j are connected.

Equivalent to weight(i, j) != 0.0.

Parameters:
  • i – First site index.

  • j – Second site index.

Returns:

True if the edge weight is non-zero.

const std::optional<EdgeColoring> &edge_coloring() const

Edge coloring stored at construction time, if any.

Factory methods for recognised topologies pre-populate this field. Returns std::nullopt for lattices constructed without a coloring.

Returns:

Reference to the optional edge coloring.

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“lattice_graph”

virtual std::string get_summary() const override

Get a human-readable summary of the lattice graph.

Returns:

Multi-line string with site/edge counts and symmetry info.

bool is_symmetric() const

Return whether the adjacency matrix is symmetric.

std::uint64_t num_edges() const

Return the number of undirected edges.

Counts only upper-triangular entries (row < col) so that each undirected edge is counted once.

std::uint64_t num_nonzeros() const

Return the total number of stored non-zero entries in the sparse adjacency matrix.

For a symmetric undirected graph this is twice the number of edges (each edge is stored in both directions).

std::uint64_t num_sites() const

Return the number of sites (vertices) in the lattice.

const Eigen::SparseMatrix<double> &sparse_adjacency_matrix() const

Return a const reference to the internal sparse adjacency matrix.

virtual void to_file(const std::string &filename, const std::string &type) const override

Save lattice graph to file in the specified format.

Parameters:
  • filename – Path to the output file.

  • type – Format type (“json” or “hdf5”).

Throws:

std::invalid_argument – If format type is not supported.

virtual void to_hdf5(H5::Group &group) const override

Save lattice graph to an HDF5 group.

virtual void to_hdf5_file(const std::string &filename) const override

Save lattice graph to an HDF5 file.

virtual nlohmann::json to_json() const override

Convert lattice graph to JSON representation.

Stores the sparse adjacency matrix (row-major) and the symmetry flag.

Returns:

JSON object containing the serialised data.

virtual void to_json_file(const std::string &filename) const override

Save lattice graph to a JSON file.

double weight(std::uint64_t i, std::uint64_t j) const

Return the edge weight between sites i and j.

Returns 0.0 when the sites are not connected.

Parameters:
  • i – Source site index.

  • j – Target site index.

Public Static Functions

static LatticeGraph chain(std::uint64_t n, bool periodic = false, double t = 1.0, bool dfs_ordering = false)

Create a one-dimensional chain lattice.

Sites are labelled 0 … n-1 with nearest-neighbour edges.

Example: chain (n=4)

  0 --- 1 --- 2 --- 3

With periodic boundary condition:

  • Wrap bond: (n-1) &#8212; 0 e.g. 3 &#8212; 0

Parameters:
  • n – Number of sites.

  • periodic – If true, add an edge between the first and last site (ring topology). Requires n > 2. Default: false.

  • t – Uniform hopping weight for every edge. Default: 1.0.

Throws:

std::invalid_argument – If n == 0.

static LatticeGraph from_dense_matrix(const Eigen::MatrixXd &adjacency_matrix)

Create a lattice graph from a dense adjacency matrix.

Parameters:

adjacency_matrix – Square dense matrix of edge weights.

Throws:

std::invalid_argument – If the matrix is not square.

Returns:

LatticeGraph with the given adjacency.

static LatticeGraph from_file(const std::string &filename, const std::string &type)

Load a lattice graph from file.

Parameters:
  • filename – Path to the input file.

  • type – Format type (“json” or “hdf5”).

Returns:

New LatticeGraph instance.

static LatticeGraph from_hdf5(H5::Group &group)

Load a lattice graph from an HDF5 group.

Parameters:

group – HDF5 group to read from.

Returns:

New LatticeGraph instance.

static LatticeGraph from_hdf5_file(const std::string &filename)

Load a lattice graph from an HDF5 file.

static LatticeGraph from_json(const nlohmann::json &j)

Load a lattice graph from a JSON object.

Parameters:

j – JSON object (must contain “adjacency_matrix” and “is_symmetric”).

Returns:

New LatticeGraph instance.

static LatticeGraph from_json_file(const std::string &filename)

Load a lattice graph from a JSON file.

static LatticeGraph from_sparse_matrix(const Eigen::SparseMatrix<double> &sparse)

Create a lattice graph from a sparse adjacency matrix.

Parameters:

sparse – Sparse square matrix of edge weights.

Throws:

std::invalid_argument – If the matrix is not square.

Returns:

LatticeGraph with the given adjacency.

static LatticeGraph honeycomb(std::uint64_t nx, std::uint64_t ny, bool periodic_x = false, bool periodic_y = false, double t = 1.0, bool dfs_ordering = false)

Create a two-dimensional honeycomb lattice.

The honeycomb lattice has two sites per unit cell (A and B sublattices). Unit cells are arranged on a rectangular grid of size nx x ny, giving a total of 2 * nx * ny sites. Sites are indexed as:

  • A-sublattice: 2 * (y * nx + x)

  • B-sublattice: 2 * (y * nx + x) + 1

Example: 3x4 honeycomb

            18-19-20-21-22-23
             |     |     |
         12-13-14-15-16-17
          |     |     |
       6--7--8--9-10-11
       |     |     |
    0--1--2--3--4--5

With periodic boundary conditions (using the 3x4 example above):

  • periodic_x wraps right to left: 5 &#8212; 0, 11 &#8212; 6, 17 &#8212; 12, 23 &#8212; 18

  • periodic_y wraps top to bottom: 19 &#8212; 0, 15 &#8212; 2, 17 &#8212; 4

Parameters:
  • nx – Number of unit cells along the x-axis.

  • ny – Number of unit cells along the y-axis.

  • periodic_x – If true, apply periodic boundary conditions along x. Requires nx >= 2. Default: false.

  • periodic_y – If true, apply periodic boundary conditions along y. Requires ny >= 2. Default: false.

  • t – Uniform hopping weight. Default: 1.0.

Throws:

std::invalid_argument – If nx or ny is 0.

static LatticeGraph kagome(std::uint64_t nx, std::uint64_t ny, bool periodic_x = false, bool periodic_y = false, double t = 1.0, int coloring_seed = 0, bool dfs_ordering = false)

Create a two-dimensional kagome lattice.

The kagome lattice has three sites per unit cell, arranged as corner-sharing triangles. Unit cells are on a rectangular grid of size nx x ny, giving a total of 3 * nx * ny sites. Sites are indexed as:

  • site 0: 3 * (y * nx + x)

  • site 1: 3 * (y * nx + x) + 1

  • site 2: 3 * (y * nx + x) + 2

Unit cell (up-triangle):

        2
       / \
      0---1

Example: 3x2 kagome

      11       14       17
     /  \     /  \     /  \
    9---10--12---13--15---16
   /     \  /     \  /
  2       5        8
 / \     / \      / \
0---1---3---4----6---7

With periodic boundary conditions (using the 3x2 example above):

  • periodic_x wraps right to left: 0 &#8212; 7, 9 &#8212; 16, 2 &#8212; 16

  • periodic_y wraps top to bottom: 0 &#8212; 11, 3 &#8212; 14, 6 &#8212; 17, 1 &#8212; 14, 4 &#8212; 17

  • Diagonal wraps (require both periodic_x and periodic_y): 7 &#8212; 11

Parameters:
  • nx – Number of unit cells along the x-axis.

  • ny – Number of unit cells along the y-axis.

  • periodic_x – If true, apply periodic boundary conditions along x. Requires nx >= 2. Default: false.

  • periodic_y – If true, apply periodic boundary conditions along y. Requires ny >= 2. Default: false.

  • t – Uniform hopping weight. Default: 1.0.

  • coloring_seed – PRNG seed for greedy edge coloring. Default: 0.

Throws:

std::invalid_argument – If nx or ny is 0.

static LatticeGraph make_bidirectional(const LatticeGraph &graph)

Return a new lattice graph with reverse edges added.

For each directed edge (i,j) with weight w, ensures (j,i) also exists with the same weight. Computes A_out = A + A^T.

Parameters:

graph – The (possibly directed) lattice graph.

Returns:

A new LatticeGraph with bidirectional edges.

static LatticeGraph permute(const LatticeGraph &graph, const std::vector<std::uint64_t> &path)

Permutes the vertices of the lattice graph according to the given path.

Reorders the sparse adjacency matrix using Eigen’s permutation operations and updates the edge coloring to align with the new vertex indexing.

Parameters:
  • graph – The source lattice graph to permute.

  • path – The sequence of original vertex indices representing the target permutation.

Returns:

A new LatticeGraph with the permuted adjacency matrix and edge coloring.

static LatticeGraph square(std::uint64_t nx, std::uint64_t ny, bool periodic_x = false, bool periodic_y = false, double t = 1.0, bool dfs_ordering = false)

Create a two-dimensional square lattice.

Sites are indexed in row-major order: site index = y * nx + x. Total sites: nx * ny.

Example: 4x3 square lattice

  8 --- 9 ---10 ---11
  |     |     |     |
  4 --- 5 --- 6 --- 7
  |     |     |     |
  0 --- 1 --- 2 --- 3

With periodic boundary conditions (using the 4x3 example above):

  • periodic_x wraps right to left: 3 &#8212; 0, 7 &#8212; 4, 11 &#8212; 8

  • periodic_y wraps top to bottom: 8 &#8212; 0, 9 &#8212; 1, 10 &#8212; 2, 11 &#8212; 3

Parameters:
  • nx – Number of sites along the x-axis.

  • ny – Number of sites along the y-axis.

  • periodic_x – If true, apply periodic boundary conditions along x. Requires nx >= 2. Default: false.

  • periodic_y – If true, apply periodic boundary conditions along y. Requires ny >= 2. Default: false.

  • t – Uniform hopping weight. Default: 1.0.

Throws:

std::invalid_argument – If nx or ny is 0.

static LatticeGraph triangular(std::uint64_t nx, std::uint64_t ny, bool periodic_x = false, bool periodic_y = false, double t = 1.0, int coloring_seed = 0, bool dfs_ordering = false)

Create a two-dimensional triangular lattice.

Sites are indexed in row-major order: site index = y * nx + x. Total sites: nx * ny. Each site connects to its right and upper square-lattice neighbours plus the upper-right diagonal neighbour, forming a triangulation of the plane.

Example: 3x3 triangular lattice

   6 --- 7 --- 8
   |  /  |  /  |
   3 --- 4 --- 5
   |  /  |  /  |
   0 --- 1 --- 2

With periodic boundary conditions (using the 3x3 example above):

  • periodic_x wraps right to left: 2 &#8212; 0, 5 &#8212; 3, 8 &#8212; 6

  • periodic_y wraps top to bottom: 6 &#8212; 0, 7 &#8212; 1, 8 &#8212; 2

  • Diagonal wraps require both periodic_x and periodic_y: 8 &#8212; 0

Parameters:
  • nx – Number of sites along the x-axis.

  • ny – Number of sites along the y-axis.

  • periodic_x – If true, apply periodic boundary conditions along x. Requires nx >= 2. Default: false.

  • periodic_y – If true, apply periodic boundary conditions along y. Requires ny >= 2. Default: false.

  • t – Uniform hopping weight. Default: 1.0.

  • coloring_seed – PRNG seed for greedy edge coloring. Default: 0.

Throws:

std::invalid_argument – If nx or ny is 0.

template<typename T>
struct ListConstraint
#include <qdk/chemistry/data/settings.hpp>

Constraint specifying a list of allowed values for a setting.

This constraint type defines an explicit set of allowed values for a setting. The setting value must match one of the values in the allowed_values vector.

Template Parameters:

T – The type of the allowed values (int64_t or std::string)

Public Members

std::vector<T> allowed_values

Vector of allowed values for the setting.

class MajoranaMapping : public qdk::chemistry::data::DataClass
#include <qdk/chemistry/data/majorana_mapping.hpp>

Data class describing a fermion-to-qubit encoding.

Majorana-atomic mappings store a 2N-entry Pauli table for individual gamma_k; bilinear-only mappings (via from_bilinears) store the bilinear images directly. bilinear(j, k) is available on both forms.

Public Functions

inline const std::string &base_encoding() const

Encoding name used by third-party plugin backends to select their own transform.

std::pair<std::complex<double>, const SparsePauliWord&> bilinear(std::size_t j, std::size_t k) const

Pauli image of the bilinear i*gamma_j*gamma_k.

O(1) lookup. For Majorana-atomic mappings the coefficient is real (+/-1); for bilinear-only mappings it is whatever was provided at construction.

Throws:
  • std::out_of_range – if j or k >= 2N.

  • std::invalid_argument – if j == k.

inline virtual std::string get_data_type_name() const override

Get the data type name for serialization.

virtual std::string get_summary() const override

Get a human-readable summary of the mapping.

inline bool is_majorana_atomic() const

Whether individual Majoranas have a Pauli image.

inline const SparsePauliWord &majorana(std::size_t k) const

Named alias for operator()(k).

inline const std::string &name() const

Encoding name (may be empty for custom encodings).

inline std::size_t num_modes() const

Number of fermionic modes.

inline std::size_t num_qubits() const

Number of qubits in the encoding table.

const SparsePauliWord &operator()(std::size_t k) const

Pauli word for Majorana operator gamma_k.

Throws:
  • std::out_of_range – if k >= 2N.

  • std::logic_error – if the mapping is not Majorana-atomic.

inline const std::vector<std::pair<std::complex<double>, SparsePauliWord>> &stabilizers() const

Stabilizer terms carried by this mapping.

Returns:

Reference to the vector of stabilizers.

inline const std::vector<SparsePauliWord> &table() const

The full Majorana-to-Pauli table (empty for bilinear-only mappings).

inline const std::optional<TaperingSpecification> &tapering() const

Optional post-mapping tapering specification.

virtual void to_file(const std::string &filename, const std::string &type) const override

Save to file in the specified format.

Parameters:
  • filename – Path to the output file.

  • type – Format type (“json”, “hdf5”, or “h5”).

virtual void to_hdf5(H5::Group &group) const override

Save to an HDF5 group.

virtual void to_hdf5_file(const std::string &filename) const override

Save to an HDF5 file.

virtual nlohmann::json to_json() const override

Serialize to JSON.

virtual void to_json_file(const std::string &filename) const override

Save to a JSON file.

MajoranaMapping without_tapering() const

Return a copy with tapering removed and the base encoding name restored.

The returned mapping has the same Pauli table and bilinears as the original, but tapering() is std::nullopt and name() equals base_encoding().

Returns:

An untapered copy of this mapping.

Public Static Functions

static MajoranaMapping bravyi_kitaev(std::size_t num_modes)

Bravyi-Kitaev (Fenwick-tree) encoding.

Uses the Fenwick-tree construction to balance parity and occupation information across qubits.

Parameters:

num_modes – Number of fermionic modes (= number of qubits).

Throws:

std::invalid_argument – If num_modes == 0.

Returns:

MajoranaMapping with name "bravyi-kitaev".

static MajoranaMapping bravyi_kitaev_tree(std::size_t num_modes)

Balanced binary-tree Bravyi-Kitaev encoding.

Recursive balanced binary-tree construction. Produces shorter Pauli strings than the Fenwick variant for non-power-of-two mode counts.

Parameters:

num_modes – Number of fermionic modes (= number of qubits).

Throws:

std::invalid_argument – If num_modes == 0.

Returns:

MajoranaMapping with name "bravyi-kitaev-tree".

static MajoranaMapping from_bilinears(std::size_t num_modes, std::vector<std::pair<std::complex<double>, SparsePauliWord>> upper_triangle, std::string name = "")

Construct a bilinear-only mapping from pre-computed bilinears.

The upper_triangle vector stores (coeff, word) for each pair (j, k) with j < k, in row-major order: (0,1), (0,2), …, (0,M-1), (1,2), …, (M-2,M-1) where M = 2*num_modes. Size must be M*(M-1)/2.

Parameters:
  • num_modes – Number of fermionic modes (N).

  • upper_triangle – Bilinear entries for all j < k.

  • name – Optional encoding label.

Throws:

std::invalid_argument – If sizes are inconsistent or num_modes == 0.

static MajoranaMapping from_file(const std::string &filename, const std::string &type)

Load from file in the specified format.

Parameters:
  • filename – Path to the input file.

  • type – Format type (“json”, “hdf5”, or “h5”).

static MajoranaMapping from_hdf5(H5::Group &group)

Load from an HDF5 group.

static MajoranaMapping from_hdf5_file(const std::string &filename)

Load from an HDF5 file.

static MajoranaMapping from_json(const nlohmann::json &data)

Deserialize from JSON.

static MajoranaMapping from_json_file(const std::string &filename)

Load from a JSON file.

static MajoranaMapping from_table(std::vector<SparsePauliWord> table, std::string name = "")

Construct a Majorana-atomic mapping from a 2N-entry table.

Parameters:
  • table – 2N SparsePauliWord entries (gamma_0, …, gamma_{2N-1}).

  • name – Optional encoding label.

Throws:

std::invalid_argument – If the table is empty or its size is odd.

static MajoranaMapping jordan_wigner(std::size_t num_modes)

Jordan-Wigner encoding.

Maps fermionic modes to qubits using the Jordan-Wigner transform. Each mode maps to one qubit; the Pauli-Z string encodes parity.

Parameters:

num_modes – Number of fermionic modes (= number of qubits).

Throws:

std::invalid_argument – If num_modes == 0.

Returns:

MajoranaMapping with name "jordan-wigner".

static MajoranaMapping parity(std::size_t num_modes)

Parity encoding.

Each qubit stores the parity (cumulative occupation) up to its corresponding mode, rather than the occupation itself.

Parameters:

num_modes – Number of fermionic modes (= number of qubits).

Throws:

std::invalid_argument – If num_modes == 0.

Returns:

MajoranaMapping with name "parity".

static MajoranaMapping parity(std::size_t num_modes, std::size_t n_alpha, std::size_t n_beta)

Parity encoding with two-qubit reduction.

Attaches TaperingSpecification metadata for post-mapping removal of two symmetry qubits (alpha-parity and total-parity).

Parameters:
  • num_modes – Number of fermionic modes.

  • n_alpha – Number of alpha electrons.

  • n_beta – Number of beta electrons.

Throws:

std::invalid_argument – If num_modes is odd, < 4, or electron counts exceed spatial orbitals.

Returns:

MajoranaMapping with name "parity-2q-reduced" and tapering.

static MajoranaMapping symmetry_conserving_bravyi_kitaev(std::size_t num_modes, std::size_t n_alpha, std::size_t n_beta)

Symmetry-conserving Bravyi-Kitaev (SCBK) encoding.

Combines a balanced BK-tree base mapping with tapering metadata that removes two symmetry qubits. Post-mapping tapering is applied by the qubit mapper backends.

Parameters:
  • num_modes – Number of fermionic modes.

  • n_alpha – Number of alpha electrons.

  • n_beta – Number of beta electrons.

Throws:

std::invalid_argument – If num_modes is odd, < 4, or electron counts exceed spatial orbitals.

Returns:

MajoranaMapping with name "symmetry-conserving-bravyi-kitaev" and tapering.

static MajoranaMapping verstraete_cirac(const LatticeGraph &lattice)

Verstraete-Cirac encoding.

Maps fermionic modes on a LatticeGraph to qubits.

Parameters:

lattice – The LatticeGraph connectivity.

Returns:

MajoranaMapping with name "verstraete-cirac".

struct MajoranaMapResult
#include <qdk/chemistry/data/majorana_mapping.hpp>

Result of a Majorana-loop fermion-to-qubit mapping.

Parallel arrays of Pauli words and their complex coefficients.

Public Members

std::vector<std::complex<double>> coefficients

Complex coefficients (parallel to words).

std::vector<SparsePauliWord> words

Pauli words (one per non-zero term).

class ModelOrbitals : public qdk::chemistry::data::Orbitals
#include <qdk/chemistry/data/orbitals.hpp>

Simple subclass of Orbitals for model systems without basis set information.

This class allows creating Orbitals objects with a specified basis size and whether the calculation is restricted or unrestricted, without needing to provide full coefficient or energy data. The class allows for model Hamiltonians and Wavefunctions to be fully specified without explicit basis set details.

Calls to any functions requiring actual data (e.g. get_coefficients, get_energies, calculate_ao_density_matrix, etc.) will throw runtime errors.

Public Functions

ModelOrbitals(const ModelOrbitals &other)
ModelOrbitals(size_t basis_size, const std::tuple<std::vector<size_t>, std::vector<size_t>> &indices)

(v1) Construct restricted model orbitals from legacy CAS index tuples.

Convenience overload accepting the legacy (active, inactive) index tuple, plumbed through the v2 SymmetryBlockedIndexSet path with an equivalent spin ( \(S_z\)) axis. The same indices apply to both spin channels.

Parameters:
  • basis_size – Number of single-particle modes.

  • indices – (active, inactive) mode-index tuple.

ModelOrbitals(size_t basis_size, const std::tuple<std::vector<size_t>, std::vector<size_t>, std::vector<size_t>, std::vector<size_t>> &indices)

(v1) Construct unrestricted model orbitals from legacy CAS index tuples.

Convenience overload accepting the legacy (active_alpha, active_beta, inactive_alpha, inactive_beta) index tuple, plumbed through the v2 SymmetryBlockedIndexSet path with a (non-equivalent) spin ( \(S_z\)) axis.

Parameters:
  • basis_size – Number of single-particle modes.

  • indices – (active_alpha, active_beta, inactive_alpha, inactive_beta) mode-index tuple.

explicit ModelOrbitals(size_t basis_size, std::shared_ptr<const SymmetryProduct> symmetries = nullptr)

Construct model orbitals over a full active space.

Restricted-ness is inferred from symmetries (a spin axis whose labels are equivalent is restricted); the default is no symmetry, i.e. a single statistics-generic mode block.

Parameters:
  • basis_size – Number of single-particle modes.

  • symmetries – Explicit single-particle symmetries (default: none). For spin-resolved ( \(S_z\)) quantities pass a spin symmetry, e.g. std::make_shared<SymmetryProduct>(SymmetryProduct

    ({axes::spin(1,

    true)})).

explicit ModelOrbitals(std::shared_ptr<const SymmetryBlockedIndexSet> active_indices, std::shared_ptr<const SymmetryBlockedIndexSet> inactive_indices = nullptr)

Construct model orbitals from symmetry-blocked active/inactive index sets.

The single-particle symmetries, per-mode extents, and restricted-ness are taken from the index sets; no spin convention is assumed.

Parameters:
  • active_indices – Active-space index set (must not be null).

  • inactive_indices – Inactive-space index set (default: none).

virtual ~ModelOrbitals() = default
virtual Eigen::MatrixXd calculate_ao_density_matrix(const Eigen::VectorXd &occupations) const override

Calculate atomic orbital (AO) density matrix from restricted occupation vector.

Parameters:

occupations – Occupation vector (size must match number of MOs)

Throws:

std::runtime_error – if occupation vector size doesn’t match number of MOs

Returns:

AO density matrix (total alpha + beta)

virtual std::pair<Eigen::MatrixXd, Eigen::MatrixXd> calculate_ao_density_matrix(const Eigen::VectorXd &occupations_alpha, const Eigen::VectorXd &occupations_beta) const override

Calculate AO density matrix from occupation vectors.

Parameters:
  • occupations_alpha – Alpha spin occupation vector (size must match number of MOs)

  • occupations_beta – Beta spin occupation vector (size must match number of MOs)

Throws:

std::runtime_error – if occupation vector sizes don’t match number of MOs

Returns:

Pair of (alpha, beta) AO density matrices

virtual Eigen::MatrixXd calculate_ao_density_matrix_from_rdm(const Eigen::MatrixXd &rdm) const override

Calculate atomic orbital (AO) density matrix from 1RDM in molecular orbital (MO) space (restricted)

Parameters:

rdm – 1RDM in MO basis (size must match number of MOs x MOs)

Throws:

std::runtime_error – if 1RDM matrix size doesn’t match number of MOs

Returns:

AO density matrix (total alpha + beta)

virtual std::pair<Eigen::MatrixXd, Eigen::MatrixXd> calculate_ao_density_matrix_from_rdm(const Eigen::MatrixXd &rdm_alpha, const Eigen::MatrixXd &rdm_beta) const override

Calculate atomic orbital (AO) density matrix from 1RDM in molecular orbital (MO) space.

Parameters:
  • rdm_alpha – Alpha 1RDM in MO basis (size must match number of MOs x MOs)

  • rdm_beta – Beta 1RDM in MO basis (size must match number of MOs x MOs)

Throws:

std::runtime_error – if 1RDM matrix sizes don’t match number of MOs

Returns:

Pair of (alpha, beta) AO density matrices

virtual std::vector<size_t> get_all_mo_indices() const override

Get all molecular orbital indices as a vector.

Returns:

Vector containing indices [0, 1, 2, …, num_molecular_orbitals-1]

virtual std::shared_ptr<BasisSet> get_basis_set() const override

Get basis set information.

Throws:

std::runtime_error – if basis set is not set

Returns:

Reference to the basis set object

virtual std::pair<const Eigen::MatrixXd&, const Eigen::MatrixXd&> get_coefficients() const override

Get orbital coefficients.

Throws:

std::runtime_error – if coefficients are not set

Returns:

Pair of references to (alpha, beta) coefficient matrices

virtual const Eigen::MatrixXd &get_coefficients_alpha() const override

Get alpha orbital coefficients.

Returns:

Reference to alpha coefficient matrix

virtual const Eigen::MatrixXd &get_coefficients_beta() const override

Get beta orbital coefficients.

Returns:

Reference to beta coefficient matrix

virtual std::pair<const Eigen::VectorXd&, const Eigen::VectorXd&> get_energies() const override

Get orbital energies.

Throws:

std::runtime_error – if energies are not set

Returns:

Pair of references to (alpha, beta) energy vectors

virtual const Eigen::VectorXd &get_energies_alpha() const override

Get alpha orbital energies.

Returns:

Reference to alpha energy vector

virtual const Eigen::VectorXd &get_energies_beta() const override

Get beta orbital energies.

Returns:

Reference to beta energy vector

virtual std::tuple<Eigen::MatrixXd, Eigen::MatrixXd, Eigen::MatrixXd> get_mo_overlap() const override

Get all molecular orbital (MO) overlap matrices.

Computes the overlap matrices between molecular orbitals by transforming the atomic orbital overlap matrix to the molecular orbital basis:

  • S_MO^αα = C_α^T * S_AO * C_α (alpha-alpha overlap)

  • S_MO^αβ = C_α^T * S_AO * C_β (alpha-beta overlap)

  • S_MO^ββ = C_β^T * S_AO * C_β (beta-beta overlap)

For restricted calculations, alpha-alpha = beta-beta and alpha-beta = alpha-alpha. For orthonormal MOs, alpha-alpha and beta-beta should be identity matrices.

Throws:

std::runtime_error – if atomic orbital (AO) overlap matrix or coefficients are not set

Returns:

Tuple of (alpha-alpha, alpha-beta, beta-beta) MO overlap matrices

virtual Eigen::MatrixXd get_mo_overlap_alpha_alpha() const override

Get alpha-alpha molecular orbital (MO) overlap matrix.

Computes the overlap matrix between alpha molecular orbitals by transforming the atomic orbital overlap matrix using the alpha MO coefficients. For orthonormal alpha MOs, this should be the identity matrix.

Throws:

std::runtime_error – if AO overlap matrix or alpha coefficients are not set

Returns:

MO overlap matrix S_MO^αα = C_α^T * S_AO * C_α

virtual Eigen::MatrixXd get_mo_overlap_alpha_beta() const override

Get alpha-beta molecular orbital (MO) overlap matrix.

Computes the overlap matrix between alpha and beta molecular orbitals. For restricted calculations, this equals the alpha-alpha overlap matrix.

Throws:

std::runtime_error – if AO overlap matrix or coefficients are not set

Returns:

MO overlap matrix S_MO^αβ = C_α^T * S_AO * C_β

virtual Eigen::MatrixXd get_mo_overlap_beta_beta() const override

Get beta-beta molecular orbital (MO) overlap matrix.

Computes the overlap matrix between beta molecular orbitals by transforming the atomic orbital overlap matrix using the beta MO coefficients. For orthonormal beta MOs, this should be the identity matrix. For restricted calculations, this equals the alpha-alpha overlap matrix.

Throws:

std::runtime_error – if AO overlap matrix or beta coefficients are not set

Returns:

MO overlap matrix S_MO^ββ = C_β^T * S_AO * C_β

inline virtual size_t get_num_atomic_orbitals() const override

Get number of atomic orbitals.

Returns:

Number of AOs (rows in coefficient matrix)

inline virtual size_t get_num_molecular_orbitals() const override

Get number of molecular orbitals.

Returns:

Number of molecular orbitals (columns in coefficient matrix)

virtual const Eigen::MatrixXd &get_overlap_matrix() const override

Get overlap matrix.

Returns:

Reference to overlap matrix

virtual bool is_restricted() const override

Check if calculation is restricted (RHF/RKS/ROHF/ROKS)

Returns:

True if orbitals are restricted

virtual bool is_unrestricted() const override

Check if calculation is unrestricted (UHF/UKS)

Returns:

True if orbitals are unrestricted

ModelOrbitals &operator=(const ModelOrbitals &other)
virtual void to_hdf5(H5::Group &group) const override

Serialize ModelOrbitals to HDF5 group.

Parameters:

group – HDF5 group to write data to

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert orbital data to JSON.

Throws:

std::runtime_error – if data is invalid

Returns:

JSON object containing orbital data

Public Static Functions

static std::shared_ptr<ModelOrbitals> from_hdf5(H5::Group &group)

Load ModelOrbitals from HDF5 group.

Parameters:

group – HDF5 group containing ModelOrbitals data

Throws:

std::runtime_error – if HDF5 data is malformed or I/O error occurs

Returns:

Shared pointer to ModelOrbitals object loaded from group

static std::shared_ptr<ModelOrbitals> from_json(const nlohmann::json &j)
class NuclearGradients : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<NuclearGradients>
#include <qdk/chemistry/data/nuclear_gradients.hpp>

Nuclear energy gradients for a specific molecular structure.

Stores the Cartesian derivative of the total energy with respect to nuclear coordinates. Values are stored atom-major as x, y, z components for each atom and are associated with the structure for which they were computed.

Public Functions

NuclearGradients(std::shared_ptr<Structure> structure, const Eigen::VectorXd &gradient_values)

Construct nuclear gradients for a structure.

Parameters:
  • structure – Molecular structure used to compute the gradients.

  • gradient_values – Atom-major gradient vector with length 3 * number of atoms.

Throws:

std::invalid_argument – If the structure is null or the vector size does not match the structure.

Eigen::MatrixXd as_matrix() const

Return gradients as a num_atoms by 3 matrix.

Eigen::Vector3d get_atom_gradient(size_t atom_index) const

Get the x, y, z gradient components for one atom.

Parameters:

atom_index – Zero-based atom index.

Throws:

std::out_of_range – If atom_index is not in the associated structure.

inline virtual std::string get_data_type_name() const override

Return the serialized data type name.

const std::shared_ptr<Structure> get_structure() const

Get the molecular structure associated with these gradients.

virtual std::string get_summary() const override

Return a short summary of the gradient data.

inline const Eigen::VectorXd &get_values() const

Get the atom-major gradient vector in Hartree/Bohr.

virtual void to_file(const std::string &filename, const std::string &type) const override

Save gradients to a JSON or HDF5 file.

virtual void to_hdf5(H5::Group &group) const override

Save gradients to an HDF5 group.

virtual void to_hdf5_file(const std::string &filename) const override

Save gradients to an HDF5 file.

virtual nlohmann::json to_json() const override

Convert gradients to JSON.

virtual void to_json_file(const std::string &filename) const override

Save gradients to a JSON file.

Public Static Functions

static std::shared_ptr<NuclearGradients> from_file(const std::string &filename, const std::string &type)

Load gradients from a JSON or HDF5 file.

static std::shared_ptr<NuclearGradients> from_hdf5(H5::Group &group)

Load gradients from an HDF5 group.

static std::shared_ptr<NuclearGradients> from_hdf5_file(const std::string &filename)

Load gradients from an HDF5 file.

static std::shared_ptr<NuclearGradients> from_json(const nlohmann::json &j)

Load gradients from JSON.

static std::shared_ptr<NuclearGradients> from_json_file(const std::string &filename)

Load gradients from a JSON file.

class NuclearHessian : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<NuclearHessian>
#include <qdk/chemistry/data/nuclear_hessian.hpp>

Nuclear second derivatives for a specific molecular structure.

Stores the Cartesian Hessian of the total energy with respect to nuclear coordinates. The matrix is ordered atom-major by x, y, z components and is associated with the structure for which it was computed.

Public Functions

NuclearHessian(std::shared_ptr<Structure> structure, const Eigen::MatrixXd &hessian_matrix)

Construct a nuclear Hessian for a structure.

Parameters:
  • structure – Molecular structure used to compute the Hessian.

  • hessian_matrix – Square 3N by 3N Hessian matrix in Hartree/Bohr^2.

Throws:

std::invalid_argument – If the structure is null or the matrix shape does not match the structure.

Eigen::Matrix3d get_atom_pair_block(size_t row_atom_index, size_t column_atom_index) const

Get the 3 by 3 Hessian block coupling two atoms.

Parameters:
  • row_atom_index – Zero-based atom index for the row coordinate block.

  • column_atom_index – Zero-based atom index for the column coordinate block.

Throws:

std::out_of_range – If either atom index is not in the associated structure.

inline virtual std::string get_data_type_name() const override

Return the serialized data type name.

inline const Eigen::MatrixXd &get_matrix() const

Get the Hessian matrix in Hartree/Bohr^2.

const std::shared_ptr<Structure> get_structure() const

Get the molecular structure associated with this Hessian.

virtual std::string get_summary() const override

Return a short summary of the Hessian data.

virtual void to_file(const std::string &filename, const std::string &type) const override

Save the Hessian to a JSON or HDF5 file.

virtual void to_hdf5(H5::Group &group) const override

Save the Hessian to an HDF5 group.

virtual void to_hdf5_file(const std::string &filename) const override

Save the Hessian to an HDF5 file.

virtual nlohmann::json to_json() const override

Convert the Hessian to JSON.

virtual void to_json_file(const std::string &filename) const override

Save the Hessian to a JSON file.

Public Static Functions

static std::shared_ptr<NuclearHessian> from_file(const std::string &filename, const std::string &type)

Load the Hessian from a JSON or HDF5 file.

static std::shared_ptr<NuclearHessian> from_hdf5(H5::Group &group)

Load the Hessian from an HDF5 group.

static std::shared_ptr<NuclearHessian> from_hdf5_file(const std::string &filename)

Load the Hessian from an HDF5 file.

static std::shared_ptr<NuclearHessian> from_json(const nlohmann::json &j)

Load the Hessian from JSON.

static std::shared_ptr<NuclearHessian> from_json_file(const std::string &filename)

Load the Hessian from a JSON file.

struct OrbitalEntropies
#include <qdk/chemistry/data/wavefunction.hpp>

Container for orbital entropy data.

Groups single-orbital entropies, two-orbital entropies, and mutual information into a single struct for cleaner constructor interfaces.

Public Functions

inline bool has_any() const

Check if any entropy data is present.

Public Members

std::optional<Eigen::MatrixXd> mutual_information
std::optional<Eigen::VectorXd> single_orbital
std::optional<Eigen::MatrixXd> two_orbital
class Orbitals : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<Orbitals>
#include <qdk/chemistry/data/orbitals.hpp>

Represents molecular orbitals with coefficients and energies.

This class stores molecular orbital data including:

  • Orbital coefficients (alpha/beta spin channels)

  • Orbital energies (alpha/beta spin channels)

  • Atomic orbital (AO) overlap matrix

  • Basis set information

Supports both restricted (RHF/RKS) and unrestricted (UHF/UKS) calculations.

This class is immutable after construction - all data must be provided during construction and cannot be modified afterward.

Subclassed by qdk::chemistry::data::ModelOrbitals

Public Types

using RestrictedCASIndices = std::tuple<std::vector<size_t>, std::vector<size_t>>

Legacy (v1) active/inactive index tuple for restricted spaces: (active_indices, inactive_indices), applied to both spin channels.

using UnrestrictedCASIndices = std::tuple<std::vector<size_t>, std::vector<size_t>, std::vector<size_t>, std::vector<size_t>>

Legacy (v1) active/inactive index tuple for unrestricted spaces: (active_alpha, active_beta, inactive_alpha, inactive_beta).

Public Functions

Orbitals(const Eigen::MatrixXd &coefficients, const std::optional<Eigen::VectorXd> &energies, const std::optional<Eigen::MatrixXd> &ao_overlap, std::shared_ptr<BasisSet> basis_set, const std::optional<std::tuple<std::vector<size_t>, std::vector<size_t>>> &indices)

(v1) Construct restricted orbitals from legacy CAS index tuples.

Convenience overload accepting the legacy RestrictedCASIndices tuple of (active, inactive) molecular-orbital indices. The indices are plumbed through the v2 SymmetryBlockedIndexSet construction path and applied to both spin channels.

Parameters:
  • coefficients – The molecular orbital coefficients matrix

  • energies – The orbital energies (optional)

  • ao_overlap – The atomic orbital overlap matrix (optional)

  • basis_set – The basis set as shared pointer

  • indices – (active, inactive) indices; std::nullopt selects the full active space.

Orbitals(const Eigen::MatrixXd &coefficients, const std::optional<Eigen::VectorXd> &energies, const std::optional<Eigen::MatrixXd> &ao_overlap, std::shared_ptr<BasisSet> basis_set, std::shared_ptr<const SymmetryBlockedIndexSet> active_indices = nullptr, std::shared_ptr<const SymmetryBlockedIndexSet> inactive_indices = nullptr)

Constructor for restricted orbitals with shared pointer to basis set.

Parameters:
  • coefficients – The molecular orbital coefficients matrix

  • energies – The orbital energies (optional)

  • ao_overlap – The atomic orbital overlap matrix (optional)

  • basis_set – The basis set as shared pointer

  • active_indices – Active-space index set (default: all orbitals)

  • inactive_indices – Inactive-space index set (default: empty)

Orbitals(const Eigen::MatrixXd &coefficients_alpha, const Eigen::MatrixXd &coefficients_beta, const std::optional<Eigen::VectorXd> &energies_alpha, const std::optional<Eigen::VectorXd> &energies_beta, const std::optional<Eigen::MatrixXd> &ao_overlap, std::shared_ptr<BasisSet> basis_set, const std::optional<std::tuple<std::vector<size_t>, std::vector<size_t>, std::vector<size_t>, std::vector<size_t>>> &indices)

(v1) Construct unrestricted orbitals from legacy CAS index tuples.

Convenience overload accepting the legacy UnrestrictedCASIndices tuple of (active_alpha, active_beta, inactive_alpha, inactive_beta) molecular-orbital indices. The indices are plumbed through the v2 SymmetryBlockedIndexSet construction path.

Parameters:
  • coefficients_alpha – The alpha molecular orbital coefficients matrix

  • coefficients_beta – The beta molecular orbital coefficients matrix

  • energies_alpha – The alpha orbital energies (optional)

  • energies_beta – The beta orbital energies (optional)

  • ao_overlap – The atomic orbital overlap matrix (optional)

  • basis_set – The basis set as shared pointer

  • indices – (active_alpha, active_beta, inactive_alpha, inactive_beta) indices; std::nullopt selects the full active space.

Orbitals(const Eigen::MatrixXd &coefficients_alpha, const Eigen::MatrixXd &coefficients_beta, const std::optional<Eigen::VectorXd> &energies_alpha, const std::optional<Eigen::VectorXd> &energies_beta, const std::optional<Eigen::MatrixXd> &ao_overlap, std::shared_ptr<BasisSet> basis_set, std::shared_ptr<const SymmetryBlockedIndexSet> active_indices = nullptr, std::shared_ptr<const SymmetryBlockedIndexSet> inactive_indices = nullptr)

Constructor for unrestricted orbitals with shared pointer to basis set.

Parameters:
  • coefficients_alpha – The alpha molecular orbital coefficients matrix

  • coefficients_beta – The beta molecular orbital coefficients matrix

  • energies_alpha – The alpha orbital energies (optional)

  • energies_beta – The beta orbital energies (optional)

  • ao_overlap – The atomic orbital overlap matrix (optional)

  • basis_set – The basis set as shared pointer

  • active_indices – Active-space index set (default: all orbitals)

  • inactive_indices – Inactive-space index set (default: empty)

Orbitals(const Orbitals &other)

Copy constructor.

Parameters:

other – The orbitals object to copy from

Orbitals(std::shared_ptr<const SymmetryBlockedTensor<2>> coefficients, std::shared_ptr<const SymmetryBlockedTensor<1>> energies, const std::optional<Eigen::MatrixXd> &ao_overlap, std::shared_ptr<BasisSet> basis_set, std::shared_ptr<const SymmetryBlockedIndexSet> active_indices = nullptr, std::shared_ptr<const SymmetryBlockedIndexSet> inactive_indices = nullptr)

Constructor from symmetry-blocked storage primitives (SymmetryBlockedTensor).

This is the preferred construction path: it builds an Orbitals object directly from the symmetry-blocked containers, without going through the dense (deprecated) v1 inputs. It emits no deprecation warnings.

Parameters:
  • coefficients – Basis coefficient tensor (AO x MO blocks)

  • energies – Orbital energy tensor (may be nullptr if unavailable)

  • ao_overlap – The atomic orbital overlap matrix (optional)

  • basis_set – The basis set as shared pointer (may be nullptr)

  • active_indices – Active-space index set (default: all orbitals)

  • inactive_indices – Inactive-space index set (default: empty)

Throws:

std::runtime_error – if the containers are inconsistent

virtual ~Orbitals()

Destructor.

std::shared_ptr<const SymmetryBlockedIndexSet> active_indices() const

Get active-space indices as a symmetry-blocked index set.

Returns:

Shared pointer to the active-space index set, or null if unset

virtual Eigen::MatrixXd calculate_ao_density_matrix(const Eigen::VectorXd &occupations) const

Calculate atomic orbital (AO) density matrix from restricted occupation vector.

Parameters:

occupations – Occupation vector (size must match number of MOs)

Throws:

std::runtime_error – if occupation vector size doesn’t match number of MOs

Returns:

AO density matrix (total alpha + beta)

virtual std::pair<Eigen::MatrixXd, Eigen::MatrixXd> calculate_ao_density_matrix(const Eigen::VectorXd &occupations_alpha, const Eigen::VectorXd &occupations_beta) const

Calculate AO density matrix from occupation vectors.

Parameters:
  • occupations_alpha – Alpha spin occupation vector (size must match number of MOs)

  • occupations_beta – Beta spin occupation vector (size must match number of MOs)

Throws:

std::runtime_error – if occupation vector sizes don’t match number of MOs

Returns:

Pair of (alpha, beta) AO density matrices

virtual Eigen::MatrixXd calculate_ao_density_matrix_from_rdm(const Eigen::MatrixXd &rdm) const

Calculate atomic orbital (AO) density matrix from 1RDM in molecular orbital (MO) space (restricted)

Parameters:

rdm – 1RDM in MO basis (size must match number of MOs x MOs)

Throws:

std::runtime_error – if 1RDM matrix size doesn’t match number of MOs

Returns:

AO density matrix (total alpha + beta)

virtual std::pair<Eigen::MatrixXd, Eigen::MatrixXd> calculate_ao_density_matrix_from_rdm(const Eigen::MatrixXd &rdm_alpha, const Eigen::MatrixXd &rdm_beta) const

Calculate atomic orbital (AO) density matrix from 1RDM in molecular orbital (MO) space.

Parameters:
  • rdm_alpha – Alpha 1RDM in MO basis (size must match number of MOs x MOs)

  • rdm_beta – Beta 1RDM in MO basis (size must match number of MOs x MOs)

Throws:

std::runtime_error – if 1RDM matrix sizes don’t match number of MOs

Returns:

Pair of (alpha, beta) AO density matrices

std::shared_ptr<const SymmetryBlockedTensor<2>> coefficients() const

Get the molecular-orbital basis coefficients as a symmetry-blocked container.

Throws:

std::runtime_error – if coefficients are not set

Returns:

Shared pointer to the basis-coefficient tensor

std::shared_ptr<const SymmetryBlockedTensor<1>> energies() const

Get the orbital energies as a symmetry-blocked container.

Throws:

std::runtime_error – if energies are not set

Returns:

Shared pointer to the orbital-energy tensor

virtual std::pair<const std::vector<size_t>&, const std::vector<size_t>&> get_active_space_indices() const

Get active space information.

Returns:

Pair of (alpha, beta) active space indices

virtual std::vector<size_t> get_all_mo_indices() const

Get all molecular orbital indices as a vector.

Returns:

Vector containing indices [0, 1, 2, …, num_molecular_orbitals-1]

virtual std::shared_ptr<BasisSet> get_basis_set() const

Get basis set information.

Throws:

std::runtime_error – if basis set is not set

Returns:

Reference to the basis set object

virtual std::pair<const Eigen::MatrixXd&, const Eigen::MatrixXd&> get_coefficients() const

Get orbital coefficients.

Throws:

std::runtime_error – if coefficients are not set

Returns:

Pair of references to (alpha, beta) coefficient matrices

virtual const Eigen::MatrixXd &get_coefficients_alpha() const

Get alpha orbital coefficients.

Returns:

Reference to alpha coefficient matrix

virtual const Eigen::MatrixXd &get_coefficients_beta() const

Get beta orbital coefficients.

Returns:

Reference to beta coefficient matrix

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“orbitals”

virtual std::pair<const Eigen::VectorXd&, const Eigen::VectorXd&> get_energies() const

Get orbital energies.

Throws:

std::runtime_error – if energies are not set

Returns:

Pair of references to (alpha, beta) energy vectors

virtual const Eigen::VectorXd &get_energies_alpha() const

Get alpha orbital energies.

Returns:

Reference to alpha energy vector

virtual const Eigen::VectorXd &get_energies_beta() const

Get beta orbital energies.

Returns:

Reference to beta energy vector

std::pair<const std::vector<size_t>&, const std::vector<size_t>&> get_inactive_space_indices() const

Get inactive space information.

Returns:

Pair of (alpha, beta) inactive space indices

virtual std::tuple<Eigen::MatrixXd, Eigen::MatrixXd, Eigen::MatrixXd> get_mo_overlap() const

Get all molecular orbital (MO) overlap matrices.

Computes the overlap matrices between molecular orbitals by transforming the atomic orbital overlap matrix to the molecular orbital basis:

  • S_MO^αα = C_α^T * S_AO * C_α (alpha-alpha overlap)

  • S_MO^αβ = C_α^T * S_AO * C_β (alpha-beta overlap)

  • S_MO^ββ = C_β^T * S_AO * C_β (beta-beta overlap)

For restricted calculations, alpha-alpha = beta-beta and alpha-beta = alpha-alpha. For orthonormal MOs, alpha-alpha and beta-beta should be identity matrices.

Throws:

std::runtime_error – if atomic orbital (AO) overlap matrix or coefficients are not set

Returns:

Tuple of (alpha-alpha, alpha-beta, beta-beta) MO overlap matrices

virtual Eigen::MatrixXd get_mo_overlap_alpha_alpha() const

Get alpha-alpha molecular orbital (MO) overlap matrix.

Computes the overlap matrix between alpha molecular orbitals by transforming the atomic orbital overlap matrix using the alpha MO coefficients. For orthonormal alpha MOs, this should be the identity matrix.

Throws:

std::runtime_error – if AO overlap matrix or alpha coefficients are not set

Returns:

MO overlap matrix S_MO^αα = C_α^T * S_AO * C_α

virtual Eigen::MatrixXd get_mo_overlap_alpha_beta() const

Get alpha-beta molecular orbital (MO) overlap matrix.

Computes the overlap matrix between alpha and beta molecular orbitals. For restricted calculations, this equals the alpha-alpha overlap matrix.

Throws:

std::runtime_error – if AO overlap matrix or coefficients are not set

Returns:

MO overlap matrix S_MO^αβ = C_α^T * S_AO * C_β

virtual Eigen::MatrixXd get_mo_overlap_beta_beta() const

Get beta-beta molecular orbital (MO) overlap matrix.

Computes the overlap matrix between beta molecular orbitals by transforming the atomic orbital overlap matrix using the beta MO coefficients. For orthonormal beta MOs, this should be the identity matrix. For restricted calculations, this equals the alpha-alpha overlap matrix.

Throws:

std::runtime_error – if AO overlap matrix or beta coefficients are not set

Returns:

MO overlap matrix S_MO^ββ = C_β^T * S_AO * C_β

virtual size_t get_num_atomic_orbitals() const

Get number of atomic orbitals.

Returns:

Number of AOs (rows in coefficient matrix)

virtual size_t get_num_molecular_orbitals() const

Get number of molecular orbitals.

Returns:

Number of molecular orbitals (columns in coefficient matrix)

virtual const Eigen::MatrixXd &get_overlap_matrix() const

Get overlap matrix.

Returns:

Reference to overlap matrix

virtual std::string get_summary() const override

Get summary string of orbital information.

Returns:

String describing the orbital data

std::pair<std::vector<size_t>, std::vector<size_t>> get_virtual_space_indices() const

Get virtual space information (orbitals not in active or inactive)

Returns:

Pair of (alpha, beta) virtual space indices

bool has_active_space() const

Check if calculation has an active space.

Returns:

True if active space is set

bool has_basis_set() const

Check if basis set information is available.

Returns:

True if basis set is set

bool has_energies() const

Check if energies are set.

Returns:

True if energies are set

bool has_inactive_space() const

Check if calculation has an inactive space.

Returns:

True if inactive space is set

bool has_overlap_matrix() const

Check if instance has an overlap matrix.

Returns:

True if overlap matrix is set

std::shared_ptr<const SymmetryBlockedIndexSet> inactive_indices() const

Get inactive-space indices as a symmetry-blocked index set.

Returns:

Shared pointer to the inactive-space index set, or null if unset

virtual bool is_restricted() const

Check if calculation is restricted (RHF/RKS/ROHF/ROKS)

Returns:

True if orbitals are restricted

virtual bool is_unrestricted() const

Check if calculation is unrestricted (UHF/UKS)

Returns:

True if orbitals are unrestricted

std::unordered_map<SymmetryLabel, std::size_t> mo_extents() const

Molecular-orbital extents keyed by symmetry label.

Returns:

Map from symmetry label to number of molecular orbitals

std::size_t num_modes() const

Number of single-particle modes (molecular orbitals).

Returns:

Number of molecular orbitals

Orbitals &operator=(const Orbitals &other)

Copy assignment operator.

Parameters:

other – The orbitals object to copy from

Returns:

Reference to this object

std::shared_ptr<const SymmetryProduct> symmetries() const

Single-particle symmetries over the molecular-orbital modes.

Returns:

Shared pointer to the molecular-orbital symmetries

virtual void to_file(const std::string &filename, const std::string &type) const override

Save orbital data to file based on type parameter.

Parameters:
  • filename – Path to file to create/overwrite

  • type – File format type (“json” or “hdf5”)

Throws:

std::runtime_error – if data is invalid, unsupported type, or I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Serialize orbital data to HDF5 group.

Parameters:

group – HDF5 group to write data to

Throws:

std::runtime_error – if I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save orbital data to HDF5 file (with validation)

Parameters:

filename – Path to HDF5 file to create/overwrite

Throws:

std::runtime_error – if data is invalid or I/O error occurs

virtual nlohmann::json to_json() const override

Convert orbital data to JSON.

Throws:

std::runtime_error – if data is invalid

Returns:

JSON object containing orbital data

virtual void to_json_file(const std::string &filename) const override

Save orbital data to JSON file (with validation)

Parameters:

filename – Path to JSON file to create/overwrite

Throws:

std::runtime_error – if data is invalid or I/O error occurs

Public Static Functions

static std::shared_ptr<Orbitals> from_file(const std::string &filename, const std::string &type)

Load orbital data from file based on type parameter.

Parameters:
  • filename – Path to file to read

  • type – File format type (“json” or “hdf5”)

Throws:

std::runtime_error – if file doesn’t exist, unsupported type, or I/O error occurs

Returns:

New Orbitals object loaded from file

static std::shared_ptr<Orbitals> from_hdf5(H5::Group &group)

Load orbital data from HDF5 group.

Parameters:

group – HDF5 group containing orbital data

Throws:

std::runtime_error – if HDF5 data is malformed or I/O error occurs

Returns:

Shared pointer to Orbitals object loaded from group

static std::shared_ptr<Orbitals> from_hdf5_file(const std::string &filename)

Load orbital data from HDF5 file.

Parameters:

filename – Path to HDF5 file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const Orbitals object loaded from file

static std::shared_ptr<Orbitals> from_json(const nlohmann::json &j)

Load orbital data from JSON.

Parameters:

j – JSON object containing orbital data

Throws:

std::runtime_error – if JSON is malformed or missing required data

Returns:

Shared pointer to const Orbitals object loaded from JSON

static std::shared_ptr<Orbitals> from_json_file(const std::string &filename)

Load orbital data from JSON file.

Parameters:

filename – Path to JSON file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const Orbitals object loaded from file

class PauliOperator : public qdk::chemistry::data::PauliOperatorExpression
#include <qdk/chemistry/data/pauli_operator.hpp>

A PauliOperatorExpression representing a single Pauli operator acting on a qubit.

This class serves as the leaf node in the expression tree for PauliOperatorExpression trees. It represents one of the four Pauli operators:

  • Identity (I)

  • Pauli-X (X)

  • Pauli-Y (Y)

  • Pauli-Z (Z)

Public Functions

PauliOperator(std::uint8_t operator_type, std::uint64_t qubit_index)

Constructs a PauliOperator with the specified type and qubit index.

Parameters:
  • operator_type – The type of Pauli operator (0=I, 1=X, 2=Y, 3=Z).

  • qubit_index – The index of the qubit this operator acts on.

virtual std::unique_ptr<PauliOperatorExpression> clone() const override

Creates a deep copy of this Pauli operator.

Returns:

A unique_ptr to the cloned Pauli operator.

virtual std::unique_ptr<SumPauliOperatorExpression> distribute() const override

Distributes this Pauli operator.

Since a single Pauli operator is already in simplest form, this method simply returns a new SumPauliOperatorExpression containing this operator.

Returns:

A new SumPauliOperatorExpression containing this operator.

inline std::uint8_t get_operator_type() const

Returns the type of this Pauli operator.

Returns:

The operator type (0=I, 1=X, 2=Y, 3=Z).

inline std::uint64_t get_qubit_index() const

Returns the qubit index this Pauli operator acts on.

Returns:

The qubit index.

virtual std::uint64_t max_qubit_index() const override

Returns the maximum qubit index referenced in this operator.

Since this operator acts on a single qubit, it simply returns that index.

Returns:

The qubit index this operator acts on.

virtual std::uint64_t min_qubit_index() const override

Returns the minimum qubit index referenced in this operator.

Since this operator acts on a single qubit, it simply returns that index.

Returns:

The qubit index this operator acts on.

virtual std::uint64_t num_qubits() const override

Returns the number of qubits spanned by this operator.

Since this operator acts on a single qubit, it always returns 1.

Returns:

1

virtual std::unique_ptr<SumPauliOperatorExpression> prune_threshold(double epsilon) const override

Returns a sum containing this operator if it meets the threshold.

Single Pauli operators have an implicit coefficient of 1.0.

Parameters:

epsilon – Terms with |coefficient| < epsilon are excluded.

Returns:

A SumPauliOperatorExpression containing this operator if epsilon <= 1.0, or an empty sum otherwise.

virtual std::unique_ptr<PauliOperatorExpression> simplify() const override

Simplifies this Pauli operator.

Since a single Pauli operator is already in simplest form, this method simply returns a clone of this operator.

Returns:

A clone of this Pauli operator.

virtual std::string to_canonical_string(std::uint64_t min_qubit, std::uint64_t max_qubit) const override

Returns the canonical string representation for a qubit range.

See PauliOperatorExpression::to_canonical_string() for more details.

Parameters:
  • min_qubit – The minimum qubit index to include.

  • max_qubit – The maximum qubit index to include (inclusive).

Returns:

A string of length (max_qubit - min_qubit + 1).

virtual std::string to_canonical_string(std::uint64_t num_qubits) const override

Returns the canonical string representation of this Pauli operator.

Wraps to_canonical_string(0, max_qubit_index()+1).

Parameters:

num_qubits – The total number of qubits to represent.

Returns:

A string of length num_qubits.

virtual std::vector<std::pair<std::complex<double>, std::string>> to_canonical_terms() const override

Returns a vector of (coefficient, canonical_string) pairs.

Wraps to_canonical_terms(max_qubit_index()+1).

Returns:

Vector of pairs where each pair contains the coefficient and canonical string for each term.

virtual std::vector<std::pair<std::complex<double>, std::string>> to_canonical_terms(std::uint64_t num_qubits) const override

Returns a vector of (coefficient, canonical_string) pairs.

For a single Pauli operator, this returns a single pair with coefficient 1.0 and the canonical string representation if the requested num_qubits includes the qubit this operator acts on. Otherwise, it returns a single pair with coefficient 1.0 and a string of all identities.

Parameters:

num_qubits – The total number of qubits to represent.

Returns:

Vector of pairs where each pair contains the coefficient and canonical string for each term.

char to_char() const

Returns the character representation of this Pauli operator.

Throws:

std::runtime_error – If the operator type is invalid (not 0-3).

Returns:

‘I’, ‘X’, ‘Y’, or ‘Z’.

virtual std::string to_string() const override

Returns a string representation of this Pauli operator.

For example, “X(0)” for a Pauli-X operator on qubit 0.

See PauliOperatorExpression::to_string() for more details.

Returns:

A string representing this Pauli operator.

Public Static Functions

static inline PauliOperator I(std::uint64_t qubit_index)

Factory method to create an Identity operator on a specified qubit.

Parameters:

qubit_index – The index of the qubit.

Returns:

PauliOperator representing the Identity operator on the specified qubit.

static inline PauliOperator X(std::uint64_t qubit_index)

Factory method to create a Pauli-X operator on a specified qubit.

Parameters:

qubit_index – The index of the qubit.

Returns:

PauliOperator representing the Pauli-X operator on the specified qubit.

static inline PauliOperator Y(std::uint64_t qubit_index)

Factory method to create a Pauli-Y operator on a specified qubit.

Parameters:

qubit_index – The index of the qubit.

Returns:

PauliOperator representing the Pauli-Y operator on the specified qubit.

static inline PauliOperator Z(std::uint64_t qubit_index)

Factory method to create a Pauli-Z operator on a specified qubit.

Parameters:

qubit_index – The index of the qubit.

Returns:

PauliOperator representing the Pauli-Z operator on the specified qubit.

class PauliOperatorExpression
#include <qdk/chemistry/data/pauli_operator.hpp>

Base interface for Pauli operator expressions.

Subclassed by qdk::chemistry::data::PauliOperator, qdk::chemistry::data::ProductPauliOperatorExpression, qdk::chemistry::data::SumPauliOperatorExpression

Public Functions

virtual ~PauliOperatorExpression() = default
inline PauliOperator *as_pauli_operator()

Attempts to dynamically cast this expression to a PauliOperator.

Returns:

Pointer to PauliOperator if successful, nullptr otherwise.

inline const PauliOperator *as_pauli_operator() const

Attempts to dynamically cast this expression to a PauliOperator.

Returns:

Pointer to PauliOperator if successful, nullptr otherwise.

inline ProductPauliOperatorExpression *as_product_expression()

Attempts to dynamically cast this expression to a ProductPauliOperatorExpression.

Returns:

Pointer to ProductPauliOperatorExpression if successful, nullptr otherwise.

inline const ProductPauliOperatorExpression *as_product_expression() const

Attempts to dynamically cast this expression to a ProductPauliOperatorExpression.

Returns:

Pointer to ProductPauliOperatorExpression if successful, nullptr otherwise.

inline SumPauliOperatorExpression *as_sum_expression()

Attempts to dynamically cast this expression to a SumPauliOperatorExpression.

Returns:

Pointer to SumPauliOperatorExpression if successful, nullptr otherwise.

inline const SumPauliOperatorExpression *as_sum_expression() const

Attempts to dynamically cast this expression to a SumPauliOperatorExpression.

Returns:

Pointer to SumPauliOperatorExpression if successful, nullptr otherwise.

virtual std::unique_ptr<PauliOperatorExpression> clone() const = 0

Creates a deep copy of this expression.

Returns:

A unique_ptr to the cloned expression.

virtual std::unique_ptr<SumPauliOperatorExpression> distribute() const = 0

Distributes nested expressions to create a flat sum of products.

For example, it transforms expressions like (A + B) * (C - D) into A*C - A*D + B*C - B*D.

Returns:

A new SumPauliOperatorExpression in distributed form.

bool is_distributed() const

Returns whether this expression is in distributed form.

An expression is in distributed form when it contains no nested sums inside products. Specifically:

Distributed form is required by to_canonical_string() and to_canonical_terms(). Use distribute() to convert an expression to distributed form.

See also

distribute()

Returns:

true if this expression is in distributed form, false otherwise.

inline bool is_pauli_operator() const

Returns whether this expression is a Pauli operator.

Returns:

true if this is a PauliOperator, false otherwise.

inline bool is_product_expression() const

Returns whether this expression is a product expression.

Returns:

true if this is a ProductPauliOperatorExpression, false otherwise.

inline bool is_sum_expression() const

Returns whether this expression is a sum expression.

Returns:

true if this is a SumPauliOperatorExpression, false otherwise.

virtual std::uint64_t max_qubit_index() const = 0

Returns the maximum qubit index referenced in this expression.

Throws:

std::logic_error – If the expression is empty.

Returns:

The maximum qubit index.

virtual std::uint64_t min_qubit_index() const = 0

Returns the minimum qubit index referenced in this expression.

Throws:

std::logic_error – If the expression is empty.

Returns:

The minimum qubit index.

virtual std::uint64_t num_qubits() const = 0

Returns the number of qubits spanned by this expression.

Returns:

max_qubit_index() - min_qubit_index() + 1, or 0 if empty.

virtual std::unique_ptr<SumPauliOperatorExpression> prune_threshold(double epsilon) const = 0

Returns a new expression with small-magnitude terms removed.

Parameters:

epsilon – Terms with |coefficient| < epsilon are excluded.

Returns:

A new SumPauliOperatorExpression with small terms filtered out.

virtual std::unique_ptr<PauliOperatorExpression> simplify() const = 0

Simplifies the expression by combining like terms and carrying out qubit-wise multiplications.

For example, it combines terms like 2*X(0)*Y(1) + 3*X(0)*Y(1) into 5*X(0)*Y(1), and simplifies products like X(0)*X(0) into I(0).

This function will also reorder terms into a canonical form. e.g. X(1)*Y(0) will be reordered to Y(0)*X(1).

By convention, distribute will be called internally before simplify to ensure the expression is in a suitable form for simplification.

Returns:

A new simplified PauliOperatorExpression.

virtual std::string to_canonical_string(std::uint64_t min_qubit, std::uint64_t max_qubit) const = 0

Returns the canonical string representation for a qubit range.

The canonical string is a sequence of characters representing the Pauli operators on each qubit, in little-endian order (qubit 0 is leftmost). Identity operators are represented as ‘I’.

For example, for min_qubit=1 and max_qubit=3 for the expression

X(0) * Y(1) * Z(3) * X(4)

the returned string would be “YIZ”.

Parameters:
  • min_qubit – The minimum qubit index to include.

  • max_qubit – The maximum qubit index to include (inclusive).

Returns:

A canonical string representation.

virtual std::string to_canonical_string(std::uint64_t num_qubits) const = 0

Returns the canonical string representation of this expression.

Wraps to_canonical_string(0, max_qubit_index()+1).

Parameters:

num_qubits – The total number of qubits to represent.

Returns:

A canonical string representation.

virtual std::vector<std::pair<std::complex<double>, std::string>> to_canonical_terms() const = 0

Returns a vector of (coefficient, canonical_string) pairs.

Wraps to_canonical_terms(max_qubit_index()+1).

Returns:

Vector of pairs where each pair contains the coefficient and canonical string for each term.

virtual std::vector<std::pair<std::complex<double>, std::string>> to_canonical_terms(std::uint64_t num_qubits) const = 0

Returns a vector of (coefficient, canonical_string) pairs.

For example, the expression 2*X(0)*Z(2) + 3i*Y(1) on 4 qubits would return: [ (2, “XIZI”), (3i, “IYII”) ]

Parameters:

num_qubits – The total number of qubits to represent.

Returns:

Vector of pairs where each pair contains the coefficient and canonical string for each term.

virtual std::string to_string() const = 0

Returns a string representation of this expression.

Returns a human-readable string showing the structure of the arithmetic expression. For example, a product of two Pauli operators might be represented as “(X(0) * Z(1))”.

For the canonical string representation consistent with other frameworks, use to_canonical_string().

Returns:

A string representing this expression.

class PauliTermAccumulator
#include <qdk/chemistry/data/pauli_operator.hpp>

High-performance accumulator for Pauli terms with coefficient combining.

This class provides efficient accumulation of Pauli terms represented in sparse format, with automatic coefficient combination for identical terms. It is optimized for use cases like fermion-to-qubit mappings where many term products are accumulated.

Example usage:

PauliTermAccumulator acc;
SparsePauliWord x0 = {{0, 1}};  // X(0)
SparsePauliWord z1 = {{1, 3}};  // Z(1)
acc.accumulate(x0, 0.5);         // Add 0.5 * X(0)
acc.accumulate_product(x0, z1, 1.0);  // Add 1.0 * X(0) * Z(1)
auto terms = acc.get_terms(1e-12);

Public Functions

PauliTermAccumulator() = default

Constructs an empty accumulator.

void accumulate(const SparsePauliWord &word, std::complex<double> coeff)

Accumulate a single term with the given coefficient.

If a term with the same SparsePauliWord already exists, the coefficients are added together.

Parameters:
  • word – The sparse Pauli word to accumulate.

  • coeff – The coefficient to add.

void accumulate_product(const SparsePauliWord &word1, const SparsePauliWord &word2, std::complex<double> scale)

Accumulate the product of two terms with a scale factor.

Computes word1 * word2 using Pauli algebra (with cached multiplication), then accumulates the result scaled by the given factor.

Parameters:
  • word1 – The first sparse Pauli word.

  • word2 – The second sparse Pauli word.

  • scale – The scale factor to apply to the product.

std::size_t cache_size() const

Get the current number of entries in the multiplication cache.

Returns:

The number of cached multiplications.

void clear()

Clear all accumulated terms.

void clear_cache()

Clear the multiplication cache.

std::vector<std::pair<std::complex<double>, SparsePauliWord>> get_terms(double threshold = 0.0) const

Get all accumulated terms with coefficients above threshold.

Parameters:

threshold – Terms with |coefficient| < threshold are excluded.

Returns:

Vector of (coefficient, SparsePauliWord) pairs.

std::vector<std::pair<std::complex<double>, std::string>> get_terms_as_strings(std::uint64_t num_qubits, double threshold = 0.0) const

Get accumulated terms as canonical strings.

Parameters:
  • num_qubits – The total number of qubits for string representation.

  • threshold – Terms with |coefficient| < threshold are excluded.

Returns:

Vector of (coefficient, canonical_string) pairs.

std::pair<std::complex<double>, SparsePauliWord> multiply(const SparsePauliWord &word1, const SparsePauliWord &word2)

Multiply two SparsePauliWords using Pauli algebra.

Computes word1 * word2, returning the phase factor and resulting word. This method uses the instance cache for efficiency.

Parameters:
  • word1 – The first sparse Pauli word.

  • word2 – The second sparse Pauli word.

Returns:

A pair of (phase, result_word) where phase is the complex phase from Pauli multiplication rules.

void set_cache_capacity(std::size_t capacity)

Set the capacity of the multiplication cache.

The cache stores results of SparsePauliWord multiplications to avoid redundant computation. When the cache exceeds capacity, oldest entries are evicted (LRU policy).

Parameters:

capacity – Maximum number of entries in the cache.

inline std::size_t size() const

Get the number of unique terms currently accumulated.

Returns:

The number of terms in the accumulator.

Public Static Functions

static std::unordered_map<std::pair<std::uint64_t, std::uint64_t>, std::vector<std::pair<std::complex<double>, SparsePauliWord>>, std::function<std::size_t(const std::pair<std::uint64_t, std::uint64_t>&)>> compute_all_bk_excitation_terms(std::uint64_t n_spin_orbitals, const std::unordered_map<std::uint64_t, std::vector<std::uint64_t>> &parity_sets, const std::unordered_map<std::uint64_t, std::vector<std::uint64_t>> &update_sets, const std::unordered_map<std::uint64_t, std::vector<std::uint64_t>> &remainder_sets)

Compute all Bravyi-Kitaev excitation operator terms.

Computes E_pq = a†_p a_q for all (p, q) pairs in sparse format. Uses the provided BK index sets (parity, update, remainder) for each orbital.

Parameters:
  • n_spin_orbitals – Total number of spin orbitals (N).

  • parity_sets – Map from orbital index to parity set P(j).

  • update_sets – Map from orbital index to update set U(j).

  • remainder_sets – Map from orbital index to remainder set R(j).

Returns:

Map from (p, q) indices to list of (coefficient, SparsePauliWord) terms.

static std::unordered_map<std::pair<std::uint64_t, std::uint64_t>, std::vector<std::pair<std::complex<double>, SparsePauliWord>>, std::function<std::size_t(const std::pair<std::uint64_t, std::uint64_t>&)>> compute_all_jw_excitation_terms(std::uint64_t n_spin_orbitals)

Compute all Jordan-Wigner excitation operator terms.

Computes E_pq = a†_p a_q for all (p, q) pairs in sparse format. This is optimized to compute all N² terms in one call, avoiding repeated pybind11 boundary crossings when invoked from Python.

Parameters:

n_spin_orbitals – Total number of spin orbitals (N).

Returns:

Map from (p, q) indices to list of (coefficient, SparsePauliWord) terms.

static std::pair<std::complex<double>, SparsePauliWord> multiply_uncached(const SparsePauliWord &word1, const SparsePauliWord &word2)

Multiply two SparsePauliWords without caching.

This is the core Pauli algebra implementation.

Parameters:
  • word1 – The first sparse Pauli word.

  • word2 – The second sparse Pauli word.

Returns:

A pair of (phase, result_word).

Public Static Attributes

static constexpr std::size_t kDefaultCacheCapacity = 10000

Default cache capacity.

class ProductPauliOperatorExpression : public qdk::chemistry::data::PauliOperatorExpression
#include <qdk/chemistry/data/pauli_operator.hpp>

A PauliOperatorExpression representing Kronecker products of multiple PauliOperatorExpression instances.

For example, the expression X(0) * Y(1) represents the Pauli-X operator on qubit 0 tensor product with the Pauli-Y operator on qubit 1, with an implicit coefficient of 1.0.

The class also supports nesting of expressions, e.g., 2.0 * (X(0) + Z(2)) * Y(1)

where the left factor is SumPauliOperatorExpression and the right factor is a PauliOperator.

The product expression follows standard arithmetic rules for Kronecker products:

  • Distributive: A*(B + C) = A*B + A*C

  • Associative: (A*B)*C = A*(B*C)

  • Non-commutative: A*B != B*A in general for expressions acting on overlapping qubits.

Public Functions

ProductPauliOperatorExpression()

Constructs an empty ProductPauliOperatorExpression with coefficient 1.0.

ProductPauliOperatorExpression(const PauliOperatorExpression &left, const PauliOperatorExpression &right)

Constructs a ProductPauliOperatorExpression representing the product of two PauliOperatorExpression instances.

For example: auto left = PauliOperator::X(0); auto right = SumPauliOperatorExpression(PauliOperator::Y(1), PauliOperator::Z(2)); auto product = ProductPauliOperatorExpression(left, right);

Parameters:
ProductPauliOperatorExpression(const ProductPauliOperatorExpression &other)

Copy constructor.

Deep copies all factors.

Parameters:

other – The ProductPauliOperatorExpression to copy.

ProductPauliOperatorExpression(std::complex<double> coefficient)

Constructs a ProductPauliOperatorExpression with the specified coefficient and no expression factors.

Parameters:

coefficient – The scalar coefficient for this product expression.

ProductPauliOperatorExpression(std::complex<double> coefficient, const PauliOperatorExpression &expr)

Constructs a ProductPauliOperatorExpression with the specified coefficient and a single PauliOperatorExpression factor.

Parameters:
void add_factor(std::unique_ptr<PauliOperatorExpression> factor)

Appends a factor to this product.

The factor is added to the end of the factor list. Ownership is transferred to this expression.

Parameters:

factor – The expression to append.

virtual std::unique_ptr<PauliOperatorExpression> clone() const override

Creates a deep copy of this product expression.

Returns:

A unique_ptr to a new ProductPauliOperatorExpression.

virtual std::unique_ptr<SumPauliOperatorExpression> distribute() const override

Expands this product into a flat sum of products.

Recursively distributes multiplication over addition for all factors. For example, (X(0) + Y(0)) * Z(1) becomes X(0)*Z(1) + Y(0)*Z(1).

The result is always a SumPauliOperatorExpression where each term is a ProductPauliOperatorExpression containing only PauliOperator factors (no nested sums).

Returns:

A new SumPauliOperatorExpression in distributed form.

std::complex<double> get_coefficient() const

Returns the scalar coefficient of this product.

Returns:

The complex coefficient.

const std::vector<std::unique_ptr<PauliOperatorExpression>> &get_factors() const

Returns a const reference to the internal factor list.

Returns:

Vector of expression factors in multiplication order.

virtual std::uint64_t max_qubit_index() const override

Returns the maximum qubit index referenced in this expression.

Throws:

std::logic_error – If the expression has no factors.

Returns:

The maximum qubit index.

virtual std::uint64_t min_qubit_index() const override

Returns the minimum qubit index referenced in this expression.

Throws:

std::logic_error – If the expression has no factors.

Returns:

The minimum qubit index.

void multiply_coefficient(std::complex<double> c)

Multiplies the coefficient by the given scalar.

Parameters:

c – The scalar to multiply by.

virtual std::uint64_t num_qubits() const override

Returns the number of qubits spanned by this expression.

Returns:

max_qubit_index() - min_qubit_index() + 1, or 0 if empty.

virtual std::unique_ptr<SumPauliOperatorExpression> prune_threshold(double epsilon) const override

Returns a sum containing this product if it meets the threshold.

Parameters:

epsilon – Terms with |coefficient| < epsilon are excluded.

Returns:

A SumPauliOperatorExpression containing this product, or an empty sum if excluded.

void reserve_capacity(std::size_t capacity)

Pre-allocates capacity for the factor list.

Parameters:

capacity – The number of factors to reserve space for.

void set_coefficient(std::complex<double> c)

Sets the scalar coefficient of this product.

Parameters:

c – The new coefficient value.

virtual std::unique_ptr<PauliOperatorExpression> simplify() const override

Simplifies this product by applying Pauli algebra rules.

If the expression is not already distributed, distribute() is called first.

Simplification performs the following steps:

  1. Unrolls nested products into a flat list of PauliOperators

  2. Sorts factors by qubit index (stable sort)

  3. Combines operators on the same qubit using Pauli multiplication:

    • P * P = I for any Pauli P

    • X * Y = iZ, Y * Z = iX, Z * X = iY (cyclic)

    • Y * X = -iZ, Z * Y = -iX, X * Z = -iY (anti-cyclic)

  4. Strips identity operators from the result

  5. Accumulates phase factors into the coefficient

Returns:

A simplified ProductPauliOperatorExpression with sorted, non-identity factors and updated coefficient.

virtual std::string to_canonical_string(std::uint64_t min_qubit, std::uint64_t max_qubit) const override

Returns the canonical string representation for a qubit range.

Parameters:
  • min_qubit – The minimum qubit index to include.

  • max_qubit – The maximum qubit index to include (inclusive).

Throws:

std::logic_error – If the expression is not in distributed form.

Returns:

A string of length (max_qubit - min_qubit + 1).

virtual std::string to_canonical_string(std::uint64_t num_qubits) const override

Returns the canonical string representation of this product.

The canonical string is a sequence of characters representing the Pauli operators on each qubit, in little-endian order (qubit 0 is leftmost). Identity operators are represented as ‘I’. The expression is simplified internally before generating the string.

Parameters:

num_qubits – The total number of qubits to represent.

Throws:

std::logic_error – If the expression is not in distributed form. Call distribute() first.

Returns:

A string of length num_qubits, e.g., “XIZI” for X(0)*Z(2) on 4 qubits.

virtual std::vector<std::pair<std::complex<double>, std::string>> to_canonical_terms() const override

Returns this product as a single (coefficient, canonical_string) pair.

Uses max_qubit_index() + 1 as the qubit count. An empty product returns a single term with coefficient and “I”.

Throws:

std::logic_error – If the expression is not in distributed form.

Returns:

A vector containing one pair.

virtual std::vector<std::pair<std::complex<double>, std::string>> to_canonical_terms(std::uint64_t num_qubits) const override

Returns this product as a single (coefficient, canonical_string) pair.

Parameters:

num_qubits – The total number of qubits to represent.

Throws:

std::logic_error – If the expression is not in distributed form.

Returns:

A vector containing one pair.

virtual std::string to_string() const override

Returns a human-readable string representation of this product.

Renders the coefficient (if not 1) followed by factors joined with “ * “. Sum factors are wrapped in parentheses. An empty product returns “1” or the coefficient string.

To improve readability, coefficients sufficiently close (within fp64 epsilon: ~2.22e-16) to {-1, 1, i, -i} are rendered as “-”, “”, “i”, or “-i” respectively.

Returns:

A string like “2 * X(0) * Y(1)” or “(X(0) + Z(1)) * Y(2)”.

class SettingNotFound : public std::runtime_error
#include <qdk/chemistry/data/settings.hpp>

Exception thrown when a setting is not found.

Public Functions

inline explicit SettingNotFound(const std::string &key)
class Settings : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<Settings>
#include <qdk/chemistry/data/settings.hpp>

Base class for extensible settings objects.

This class provides a flexible settings system that can:

  • Store arbitrary typed values using a variant system

  • Be easily extended by derived classes during construction only

  • Map seamlessly to Python dictionaries via pybind11

  • Provide type-safe access to settings with default values

  • Support nested settings structures

  • Prevent extension of the settings map after class initialization

The settings map can only be populated during construction using the protected set_default methods. This design ensures that the available settings are fixed at initialization time and cannot be extended later.

Usage:

class MySettings : public Settings {
public:
    MySettings() {
        // Can only call set_default during construction
        set_default("max_iterations", 100);
        set_default("convergence_threshold", 1e-6);
        set_default("method", std::string("default"));
    }

    // Convenience getters with validation (optional)
    int32_t get_max_iterations() const { return
get<int32_t>("max_iterations"); } double get_convergence_threshold() const {
return get<double>("convergence_threshold"); } std::string get_method() const
{ return get<std::string>("method"); }

    // After construction, only existing settings can be modified
    void set_max_iterations(int32_t value) { set("max_iterations", value); }
    void set_convergence_threshold(double value) {
set("convergence_threshold", value); }
};

Subclassed by qdk::chemistry::algorithms::ElectronicStructureSettings, qdk::chemistry::algorithms::MultiConfigurationScfSettings, qdk::chemistry::algorithms::MultiConfigurationSettings, qdk::chemistry::algorithms::NuclearDerivativeSettings

Public Functions

Settings() = default

Default constructor.

Settings(const Settings &other) = default

Copy constructor.

Settings(Settings &&other) noexcept = default

Move constructor.

virtual ~Settings() = default

Virtual destructor for proper inheritance.

std::string as_table(size_t max_width = 120, bool show_undocumented = false) const

Print settings as a formatted table.

Prints all documented settings in a table format with columns: Key, Value, Limits, Description

The table fits within the specified width with multi-line descriptions as needed. Non-integer numeric values are displayed in scientific notation.

Parameters:
  • max_width – Maximum total width of the table (default: 120)

  • show_undocumented – Whether to show undocumented settings (default: false)

Returns:

Formatted table string

bool empty() const

Check if settings are empty.

Returns:

true if no settings are stored

SettingValue get(const std::string &key) const

Get a setting value as variant.

Parameters:

key – The setting key

Throws:

SettingNotFound – if key doesn’t exist

Returns:

The setting value as SettingValue variant

template<typename T>
inline T get(const std::string &key) const

Get a setting value with type checking.

Parameters:

key – The setting key

Throws:
Returns:

The setting value

const std::map<std::string, SettingValue> &get_all_settings() const

Get all settings as a map for Python interoperability.

Returns:

Map of setting keys to their SettingValue variants

std::string get_as_string(const std::string &key) const

Get a setting value as a string representation.

Parameters:

key – The setting key

Throws:

SettingNotFound – if key doesn’t exist

Returns:

String representation of the value

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“settings”

std::string get_description(const std::string &key) const

Get the description of a setting.

Parameters:

key – The setting key

Throws:

SettingNotFound – if key doesn’t exist or has no description

Returns:

The description string

Constraint get_limits(const std::string &key) const

Get the limits of a setting.

Parameters:

key – The setting key

Throws:

SettingNotFound – if key doesn’t exist or has no limits

Returns:

The limit value (can be range or enumeration)

SettingValue get_or_default(const std::string &key, const SettingValue &default_value) const

Get a setting value with a default if not found (variant version)

Parameters:
  • key – The setting key

  • default_value – The default value to return if key not found

Returns:

The setting value or default

template<typename T>
inline T get_or_default(const std::string &key, const T &default_value) const

Get a setting value with a default if not found (template version)

Parameters:
  • key – The setting key

  • default_value – The default value to return if key not found

Returns:

The setting value or default

virtual std::string get_summary() const override

Get a summary string describing the settings.

Returns:

String containing settings summary information

std::string get_type_name(const std::string &key) const

Get the type name of a setting value.

Parameters:

key – The setting key

Returns:

String representation of the type, or “not_found” if key doesn’t exist

bool has(const std::string &key) const

Check if a setting exists.

Parameters:

key – The setting key

Returns:

true if the setting exists

bool has_description(const std::string &key) const

Check if a setting has a description.

Parameters:

key – The setting key

Returns:

true if the setting has a description

bool has_limits(const std::string &key) const

Check if a setting has defined limits.

Parameters:

key – The setting key

Returns:

true if the setting has limits defined

template<typename T>
inline bool has_type(const std::string &key) const

Check if a setting exists and has the expected type.

Parameters:

key – The setting key

Returns:

true if the setting exists and has the correct type

bool is_documented(const std::string &key) const

Check if a setting is documented.

Parameters:

key – The setting key

Throws:

SettingNotFound – if key doesn’t exist

Returns:

true if the setting is marked as documented

std::vector<std::string> keys() const

Get all setting keys.

Returns:

Vector of all setting keys

void lock() const

Lock the settings to prevent further modifications.

Settings &operator=(const Settings &other) = delete

Copy assignment operator.

Settings &operator=(Settings &&other) noexcept = default

Move assignment operator.

void set(const std::string &key, const char *value)

Sets the value for a given key in the settings.

This overload allows setting the value using a C-style string. Internally, the value is converted to a std::string and passed to the main set function.

Parameters:
  • key – The key to associate with the value.

  • value – The C-style string value to set.

void set(const std::string &key, const SettingValue &value)

Set a setting value.

Parameters:
  • key – The setting key

  • value – The setting value

Throws:
  • SettingsAreLocked – if the settings have been locked

  • SettingNotFound – if key does not exist

  • SettingTypeMismatch – if value type does not match the existing type for key

  • std::invalid_argument – if an AlgorithmRef’s algorithm_type is changed for a setting that is not marked as a cross-type dispatch setting, or if a constrained value is out of range / not in the allowed set

template<NonIntegralBool T>
inline void set(const std::string &key, const T &value)

Set a setting value (template version for convenience)

Note

This template is disabled for non-int64_t integers to avoid ambiguity

Parameters:
  • key – The setting key

  • value – The setting value

template<typename Integer>
inline void set(const std::string &key, Integer value)
size_t size() const

Get the number of settings.

Returns:

Number of settings

virtual void to_file(const std::string &filename, const std::string &type) const override

Save settings to file in specified format.

Parameters:
  • filename – Path to file to create/overwrite

  • type – Format type (“json” or “hdf5”)

Throws:
  • std::invalid_argument – if unknown type

  • std::runtime_error – if I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Save settings to HDF5 group.

Parameters:

group – HDF5 group to save data to

Throws:

std::runtime_error – if I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save settings to HDF5 file.

Parameters:

filename – Path to HDF5 file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert settings to JSON.

Returns:

JSON object containing all settings

virtual void to_json_file(const std::string &filename) const override

Save settings to JSON file.

Parameters:

filename – Path to JSON file to write

Throws:

std::runtime_error – if file cannot be opened or written

template<typename T>
inline std::optional<T> try_get(const std::string &key) const

Try to get a setting value with type checking, returns optional.

Parameters:

key – The setting key

Returns:

Optional containing the value if found and correct type, empty otherwise

void update(const Settings &other_settings)

Apply settings from another Settings object.

This method performs a bulk update of settings from another Settings object. Only keys that exist in both this object and the other_settings object will be updated. All keys in other_settings must already exist in this settings object. If any key is missing, the entire operation fails and no settings are modified. This ensures atomicity of the bulk update.

Parameters:

other_settings – The Settings object to copy values from

Throws:
void update(const std::map<std::string, SettingValue> &updates_map)

Apply multiple settings from a map.

This method performs a bulk update of settings. All keys in the map must already exist in the settings. If any key is missing, the entire operation fails and no settings are modified. This ensures atomicity of the bulk update.

Parameters:

updates_map – Map of setting keys to their new values

Throws:
void update(const std::map<std::string, std::string> &updates_map)

Apply multiple settings from a string-to-string map.

This method performs a bulk update of settings from string representations. The string values are parsed based on the current type of each setting. All keys in the map must already exist in the settings. If any key is missing or any value cannot be parsed, the entire operation fails and no settings are modified. This ensures atomicity of the bulk update.

Supported string formats:

  • bool: “true”/”false”, “1”/”0”, “yes”/”no”, “on”/”off” (case-insensitive)

  • integers: Standard integer format (e.g., “123”, “-456”)

  • floating-point: Standard float format (e.g., “3.14”, “1e-6”)

  • string: Direct string value

  • vectors: JSON array format (e.g., “[1,2,3]” or “[“a”,”b”,”c”]”)

Parameters:

updates_map – Map of setting keys to their new values as strings

Throws:
  • SettingNotFound – if any key doesn’t exist

  • std::runtime_error – if any string value cannot be parsed to the expected type

void update(const std::string &key, const SettingValue &value)

Update a setting value (variant version), throwing if key doesn’t exist.

Parameters:
  • key – The setting key

  • value – The new value

Throws:

SettingNotFound – if key doesn’t exist

template<typename T>
inline void update(const std::string &key, const T &value)

Update a setting value, throwing if key doesn’t exist.

Parameters:
  • key – The setting key

  • value – The new value

Throws:

SettingNotFound – if key doesn’t exist

void validate_required(const std::vector<std::string> &required_keys) const

Validate that all required settings are present.

Parameters:

required_keys – Vector of required setting keys

Throws:

SettingNotFound – if any required setting is missing

Public Static Functions

static std::shared_ptr<Settings> from_file(const std::string &filename, const std::string &type)

Create settings from file in specified format (static factory method)

Parameters:
  • filename – Path to file to read

  • type – Format type (“json” or “hdf5”)

Throws:
  • std::invalid_argument – if unknown type

  • std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to new Settings instance

static std::shared_ptr<Settings> from_hdf5(H5::Group &group)

Create settings from HDF5 group (static factory method)

Parameters:

group – HDF5 group to read

Throws:

std::runtime_error – if I/O error occurs

Returns:

Shared pointer to new Settings instance

static std::shared_ptr<Settings> from_hdf5_file(const std::string &filename)

Create settings from HDF5 file (static factory method)

Parameters:

filename – Path to HDF5 file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to new Settings instance

static std::shared_ptr<Settings> from_json(const nlohmann::json &json_obj)

Create settings from JSON (static factory method)

Parameters:

json_obj – JSON object containing settings data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Shared pointer to new Settings instance

static std::shared_ptr<Settings> from_json_file(const std::string &filename)

Create settings from JSON file (static factory method)

Parameters:

filename – Path to JSON file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to new Settings instance

class SettingsAreLocked : public std::runtime_error
#include <qdk/chemistry/data/settings.hpp>

Exception thrown when modification of locked settings is requested.

Public Functions

inline explicit SettingsAreLocked()
class SettingTypeMismatch : public std::runtime_error
#include <qdk/chemistry/data/settings.hpp>

Exception thrown when a setting type conversion fails.

Public Functions

inline explicit SettingTypeMismatch(const std::string &key, const std::string &expected_type)
struct Shell
#include <qdk/chemistry/data/basis_set.hpp>

Information about a shell of atomic orbitals.

A shell represents a group of atomic orbitals that share the same atom, angular momentum, and primitive functions, but differ in magnetic quantum numbers. For example, a p-shell contains px, py, pz functions.

Primitive data is stored as raw vectors instead of Primitive objects for better performance and simpler data handling.

By convention, the coefficients are stored as the raw, unnormalized contraction coefficients for the primitives. This convention is adopted to facilitate compatibility with various quantum chemistry software packages and libraries, which often use raw coefficients in their basis set definitions. The normalization of these coefficients is typically handled during the computation of integrals or other operations, rather than being stored in the basis set itself.

Public Functions

inline Shell(size_t atom_idx, OrbitalType orb_type, const Eigen::VectorXd &exp, const Eigen::VectorXd &coeff)

Constructor with primitive data.

inline Shell(size_t atom_idx, OrbitalType orb_type, const Eigen::VectorXd &exp, const Eigen::VectorXd &coeff, const Eigen::VectorXi &rpow)

Constructor with primitive data and radial powers (for ECP shells)

Shell(size_t atom_idx, OrbitalType orb_type, const std::vector<double> &exp_list, const std::vector<double> &coeff_list)

Constructor with vectors for primitives.

Shell(size_t atom_idx, OrbitalType orb_type, const std::vector<double> &exp_list, const std::vector<double> &coeff_list, const std::vector<int> &rpow_list)

Constructor with vectors for primitives and radial powers (for ECP shells)

inline int get_angular_momentum() const

Get angular momentum quantum number.

inline size_t get_num_atomic_orbitals(AOType atomic_orbital_type = AOType::Spherical) const

Get number of atomic orbitals in this shell.

Parameters:

atomic_orbital_type – Whether to use spherical or cartesian atomic

inline size_t get_num_primitives() const

Get number of primitives in this shell.

inline bool has_radial_powers() const

Check if this shell has radial powers (i.e., is an ECP shell)

Public Members

size_t atom_index = 0ul

Index of the atom this shell belongs to.

Eigen::VectorXd coefficients

Contraction coefficients for primitives.

Eigen::VectorXd exponents

Orbital exponents for primitive Gaussians.

OrbitalType orbital_type = OrbitalType::S

Type of orbital (s, p, d, f, etc.)

Eigen::VectorXi rpowers

Radial powers for ECP shells (r^n terms)

class SparseHamiltonianContainer : public qdk::chemistry::data::HamiltonianContainer
#include <qdk/chemistry/data/hamiltonian_containers/sparse.hpp>

Hamiltonian container for lattice model Hamiltonians (Hückel, Hubbard, PPP, etc.) with sparse internal storage.

Stores one-body integrals as a sparse matrix and two-body integrals as a sparse map of (p,q,r,s) indices. Provides lazy materialization of dense two-body integrals for the base class interface.

Uses ModelOrbitals internally so that the full HamiltonianContainer base class interface works.

In addition to the standard interface, this container exposes sparse-specific accessors (sparse_one_body_integrals, sparse_two_body_integrals, one_body_element, two_body_element) that are only available when working directly with the concrete container type.

Public Types

using TwoBodyIndex = std::tuple<int, int, int, int>

Sparse index type for two-body integrals (p,q,r,s).

using TwoBodyMap = std::map<TwoBodyIndex, double>

Sparse two-body integral storage: maps (p,q,r,s) to value.

Public Functions

SparseHamiltonianContainer(const Eigen::MatrixXd &one_body_integrals, const Eigen::VectorXd &two_body_integrals, double core_energy = 0.0, HamiltonianType type = HamiltonianType::Hermitian)

Construct from dense one-body and dense two-body integrals.

Parameters:
  • one_body_integrals – Dense one-body integral matrix [n x n]

  • two_body_integrals – Dense two-body integrals [n^4]

  • core_energy – Scalar energy offset (default 0.0)

  • typeHamiltonian type (default Hermitian)

explicit SparseHamiltonianContainer(const Eigen::MatrixXd &one_body_integrals, double core_energy = 0.0, HamiltonianType type = HamiltonianType::Hermitian)

Construct from dense one-body integrals only.

Parameters:
  • one_body_integrals – Dense one-body integral matrix [n x n]

  • core_energy – Scalar energy offset (default 0.0)

  • typeHamiltonian type (default Hermitian)

explicit SparseHamiltonianContainer(Eigen::SparseMatrix<double> one_body_integrals, double core_energy = 0.0, HamiltonianType type = HamiltonianType::Hermitian)

Construct with sparse one-body integrals only (no two-body).

Parameters:
  • one_body_integrals – Sparse one-body integral matrix [n x n]

  • core_energy – Scalar energy offset (default 0.0)

  • typeHamiltonian type (default Hermitian)

SparseHamiltonianContainer(Eigen::SparseMatrix<double> one_body_integrals, std::shared_ptr<const SymmetryBlockedSparseMap<4>> two_body, double core_energy = 0.0, HamiltonianType type = HamiltonianType::Hermitian)

Construct from a sparse one-body matrix and a preconstructed SymmetryBlockedSparseMap two-body container.

Used by the serialization layer to hand a deserialized sparse map to the container without going through the TwoBodyMap conversion path.

Parameters:
  • one_body_integrals – Sparse one-body integral matrix [n x n].

  • two_body – Preconstructed sparse two-body container (may be nullptr to indicate no two-body integrals).

  • core_energy – Scalar energy offset.

  • typeHamiltonian type.

SparseHamiltonianContainer(Eigen::SparseMatrix<double> one_body_integrals, TwoBodyMap two_body_integrals, double core_energy = 0.0, HamiltonianType type = HamiltonianType::Hermitian)

Construct from sparse one-body integrals and sparse two-body map.

Parameters:
  • one_body_integrals – Sparse one-body integral matrix [n x n]

  • two_body_integrals – Sparse two-body integral map

  • core_energy – Scalar energy offset (default 0.0)

  • typeHamiltonian type (default Hermitian)

~SparseHamiltonianContainer() = default

Destructor.

virtual std::unique_ptr<HamiltonianContainer> clone() const override

Create a deep copy of this container.

Returns:

Unique pointer to a cloned container

virtual std::string get_container_type() const override

Get the type of the underlying container.

Returns:

“sparse”

virtual double get_two_body_element(unsigned i, unsigned j, unsigned k, unsigned l, SpinChannel channel = SpinChannel::aaaa) const final override

Get a specific two-electron integral element.

Parameters:
  • i – First orbital index

  • j – Second orbital index

  • k – Third orbital index

  • l – Fourth orbital index

  • channel – Spin channel (ignored; model Hamiltonians are restricted)

Returns:

Two-electron integral (ij|kl), or 0 if not stored

virtual std::tuple<const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&> get_two_body_integrals() const final override

Get two-electron integrals as dense vectors for all spin channels.

Materializes the sparse two-body map into a dense n^4 vector on first call (cached). Model Hamiltonians are restricted, so all three channels reference the same vector.

Throws:

std::runtime_error – if no two-body integrals are stored

Returns:

Tuple of references to (aaaa, aabb, bbbb) two-electron integrals

virtual bool has_two_body_integrals() const final override

Check if two-body integrals are available.

Returns:

True if the two-body map is non-empty

virtual bool is_restricted() const final override

Model Hamiltonians are always restricted.

Returns:

true

virtual bool is_valid() const final override

Check if the container data is consistent.

Returns:

True if the one-body matrix is square and non-empty

double one_body_element(int i, int j) const

Access a single one-body integral element.

Parameters:
  • i – Row index

  • j – Column index

Returns:

Value of one-body integral (i,j)

const Eigen::SparseMatrix<double> &sparse_one_body_integrals() const

Direct access to the sparse one-body integral matrix.

Returns:

Const reference to the internal sparse matrix

TwoBodyMap sparse_two_body_integrals() const

Direct access to the sparse two-body integral map.

Returns:

Const reference to the internal two-body map

virtual void to_fcidump_file(const std::string &filename, size_t nalpha, size_t nbeta) const override

Save Hamiltonian to an FCIDUMP file.

Parameters:
  • filename – Path to FCIDUMP file to create/overwrite

  • nalpha – Number of alpha electrons

  • nbeta – Number of beta electrons

Throws:

std::runtime_error – if the Hamiltonian is unrestricted or the file cannot be opened

virtual void to_hdf5(H5::Group &group) const override

Serialize Hamiltonian data to HDF5 group.

Parameters:

group – HDF5 group to write data to

virtual nlohmann::json to_json() const override

Convert Hamiltonian to JSON.

Returns:

JSON object containing Hamiltonian data

const SymmetryBlockedSparseMap<4> &two_body_integrals_sparse() const

Two-body integrals as a rank-4 symmetry-blocked sparse map.

Throws:

std::runtime_error – if not set.

Returns:

Const reference to the two-body sparse map.

Public Static Functions

static std::unique_ptr<SparseHamiltonianContainer> from_hdf5(H5::Group &group)

Deserialize Hamiltonian data from HDF5 group.

Parameters:

group – HDF5 group to read data from

Returns:

Unique pointer to Hamiltonian loaded from group

static std::unique_ptr<SparseHamiltonianContainer> from_json(const nlohmann::json &j)

Load Hamiltonian from JSON.

Parameters:

j – JSON object containing Hamiltonian data

Returns:

Unique pointer to Hamiltonian loaded from JSON

struct SparsePauliWordHash
#include <qdk/chemistry/data/pauli_operator.hpp>

Hash function for SparsePauliWord.

Uses hash_combine for unordered-map lookup performance. This is a local table hash, not a deterministic content digest.

Public Functions

inline std::size_t operator()(const SparsePauliWord &word) const noexcept
struct SparsePauliWordPairHash
#include <qdk/chemistry/data/pauli_operator.hpp>

Hash function for pairs of SparsePauliWord (used for multiplication caching).

Combines the two SparsePauliWordHash results for fast unordered-map lookup. This is a local table hash, not a deterministic content digest.

Public Functions

inline std::size_t operator()(const std::pair<SparsePauliWord, SparsePauliWord> &pair) const noexcept
class SpinValue : public qdk::chemistry::data::SymmetryAxisValue
#include <qdk/chemistry/data/symmetry/symmetry.hpp>

Concrete spin-½ axis value.

The stored value is \(2 M_s\): +1 for an \(\alpha\) label and -1 for a \(\beta\) label.

Public Functions

inline explicit constexpr SpinValue(int two_ms)

Construct from \(2 M_s\) (e.g.

+1 for alpha, -1 for beta).

Parameters:

two_ms – Twice the spin projection of the represented label.

inline virtual AxisName axis() const override

The axis this value belongs to.

Returns:

Always AxisName::Spin.

virtual bool equals(const SymmetryAxisValue &other) const override

Value-equality against another axis value.

Parameters:

other – Axis value to compare against.

Returns:

true iff other is a SpinValue carrying the same \(2 M_s\) value.

virtual std::size_t hash() const override

Hash consistent with equals.

Returns:

Hash value derived from the stored \(2 M_s\).

virtual nlohmann::json to_json() const override

Serialize this value (subclass payload only).

Returns:

JSON object carrying the \(2 M_s\) value under a stable key.

inline constexpr int value() const

The stored \(2 M_s\) value.

Returns:

+1 for \(\alpha\), -1 for \(\beta\), or any other value carried at construction.

Public Static Functions

static std::shared_ptr<const SymmetryAxisValue> from_json(const nlohmann::json &j)

Reconstruct a SpinValue from its JSON payload.

Parameters:

j – JSON object produced by a prior SpinValue::to_json call.

Throws:

std::runtime_error – if j is missing the \(2 M_s\) payload or it is of the wrong type.

Returns:

Shared pointer to the deserialized value typed as the polymorphic SymmetryAxisValue base.

class StabilityResult : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<StabilityResult>
#include <qdk/chemistry/data/stability_result.hpp>

Result structure for wavefunction stability analysis.

The StabilityResult class encapsulates the results of a stability check performed on a wavefunction. It contains information about whether the wavefunction is stable, along with the eigenvalues and eigenvectors of the stability matrix for both internal and external stability. (See J. Chem. Phys. 66, 3045–3050 (1977) for classification of stability types.)

This class provides:

  • Internal and external stability status

  • Overall stability status (stable only if both internal and external are stable)

  • Internal and external eigenvalues of the stability matrices

  • Internal and external eigenvectors of the stability matrices

  • Convenient access methods for stability analysis results

Eigenvector Format

The eigenvectors encode orbital rotation parameters between occupied and virtual orbitals. The required size depends on the orbital type:

RHF (Restricted Hartree-Fock):

  • Size: num_occupied_orbitals * num_virtual_orbitals

  • Where: num_virtual_orbitals = num_molecular_orbitals - num_occupied_orbitals

  • Elements represent rotations between occupied and virtual spatial orbitals

  • Both spins rotate together (spin symmetry preserved)

UHF (Unrestricted Hartree-Fock):

  • Size: num_alpha_occupied_orbitals * num_alpha_virtual_orbitals + num_beta_occupied_orbitals * num_beta_virtual_orbitals

  • Where: num_alpha_virtual_orbitals = num_molecular_orbitals - num_alpha_occupied_orbitals num_beta_virtual_orbitals = num_molecular_orbitals - num_beta_occupied_orbitals

  • First num_alpha_occupied_orbitals * num_alpha_virtual_orbitals elements: alpha rotations

  • Last num_beta_occupied_orbitals * num_beta_virtual_orbitals elements: beta rotations

  • Alpha and beta orbitals rotate independently

ROHF (Restricted Open-shell Hartree-Fock):

  • The rotation mask is the union of two rectangular blocks:

    1. Alpha block: num_alpha_occupied_orbitals * num_alpha_virtual_orbitals

    2. Beta block: num_beta_occupied_orbitals * num_beta_virtual_orbitals

  • Size calculation for union (assuming num_alpha_occupied >= num_beta_occupied): num_alpha_occupied_orbitals * (num_molecular_orbitals - num_alpha_occupied_orbitals) + (num_alpha_occupied_orbitals - num_beta_occupied_orbitals) * num_beta_occupied_orbitals

  • This equals the virtual-occupied block plus the additional doubly-occupied to singly-occupied block

Indexing Convention: The occupied orbital index varies fastest. For the element corresponding to occupied orbital i and virtual orbital a, the index is computed as: index = i + a * num_occupied. This convention is from row-major eigenvector (num_virtual, num_occupied).

Note

Internal stability typically refers to stability against perturbations within the same method (e.g. RHF -> RHF), while external stability refers to stability against perturbations between different methods (e.g. RHF -> UHF).

Public Functions

StabilityResult() = default

Default constructor.

inline StabilityResult(bool internal_stable, bool external_stable, const Eigen::VectorXd &internal_eigenvalues, const Eigen::MatrixXd &internal_eigenvectors, const Eigen::VectorXd &external_eigenvalues, const Eigen::MatrixXd &external_eigenvectors)

Construct a StabilityResult with specific values.

Parameters:
  • internal_stable – True if internal stability is satisfied

  • external_stable – True if external stability is satisfied

  • internal_eigenvalues – Eigenvalues of the internal stability matrix

  • internal_eigenvectors – Eigenvectors of the internal stability matrix

  • external_eigenvalues – Eigenvalues of the external stability matrix

  • external_eigenvectors – Eigenvectors of the external stability matrix

StabilityResult(const StabilityResult&) = default

Copy constructor.

StabilityResult(StabilityResult&&) noexcept = default

Move constructor.

virtual ~StabilityResult() = default

Destructor.

bool empty() const

Check if the stability result is empty.

Returns:

true if no eigenvalues/eigenvectors are present for internal or external

inline size_t external_size() const

Get the number of external eigenvalues.

Returns:

Number of external eigenvalues in the stability matrix

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“stability_result”

inline const Eigen::VectorXd &get_external_eigenvalues() const

Get the external eigenvalues of the stability matrix.

Returns:

Reference to the external eigenvalues vector

inline const Eigen::MatrixXd &get_external_eigenvectors() const

Get the external eigenvectors of the stability matrix.

Returns:

Reference to the external eigenvectors matrix

inline const Eigen::VectorXd &get_internal_eigenvalues() const

Get the internal eigenvalues of the stability matrix.

Returns:

Reference to the internal eigenvalues vector

inline const Eigen::MatrixXd &get_internal_eigenvectors() const

Get the internal eigenvectors of the stability matrix.

Returns:

Reference to the internal eigenvectors matrix

double get_smallest_eigenvalue() const

Get the smallest eigenvalue across both internal and external.

Throws:

std::runtime_error – if no eigenvalues are present

Returns:

Smallest eigenvalue overall (most negative for unstable systems)

std::pair<double, Eigen::VectorXd> get_smallest_eigenvalue_and_vector() const

Get the smallest eigenvalue and its corresponding eigenvector across both internal and external.

Throws:

std::runtime_error – if no eigenvalues are present

Returns:

Pair of (eigenvalue, eigenvector) for the smallest eigenvalue overall

double get_smallest_external_eigenvalue() const

Get the smallest external eigenvalue.

Throws:

std::runtime_error – if no external eigenvalues are present

Returns:

Smallest external eigenvalue (most negative for unstable systems)

std::pair<double, Eigen::VectorXd> get_smallest_external_eigenvalue_and_vector() const

Get the smallest external eigenvalue and its corresponding eigenvector.

Throws:

std::runtime_error – if no external eigenvalues are present

Returns:

Pair of (eigenvalue, eigenvector) for the smallest external eigenvalue

double get_smallest_internal_eigenvalue() const

Get the smallest internal eigenvalue.

Throws:

std::runtime_error – if no internal eigenvalues are present

Returns:

Smallest internal eigenvalue (most negative for unstable systems)

std::pair<double, Eigen::VectorXd> get_smallest_internal_eigenvalue_and_vector() const

Get the smallest internal eigenvalue and its corresponding eigenvector.

Throws:

std::runtime_error – if no internal eigenvalues are present

Returns:

Pair of (eigenvalue, eigenvector) for the smallest internal eigenvalue

virtual std::string get_summary() const override

Get summary string of stability result information.

Returns:

String describing the stability result

bool has_external_result() const

Check if external stability data is present.

Returns:

true if external eigenvalues are present

bool has_internal_result() const

Check if internal stability data is present.

Returns:

true if internal eigenvalues are present

inline size_t internal_size() const

Get the number of internal eigenvalues.

Returns:

Number of internal eigenvalues in the stability matrix

inline bool is_external_stable() const

Check if external stability is satisfied.

Returns:

True if external stability is satisfied

inline bool is_internal_stable() const

Check if internal stability is satisfied.

Returns:

True if internal stability is satisfied

inline bool is_stable() const

Check if the wavefunction is stable overall.

Returns:

True if both internal and external stability are satisfied

StabilityResult &operator=(const StabilityResult&) = default

Copy assignment operator.

StabilityResult &operator=(StabilityResult&&) noexcept = default

Move assignment operator.

inline void set_external_eigenvalues(const Eigen::VectorXd &external_eigenvalues)

Set the external eigenvalues.

Parameters:

external_eigenvalues – The external eigenvalues of the stability matrix

inline void set_external_eigenvectors(const Eigen::MatrixXd &external_eigenvectors)

Set the external eigenvectors.

Parameters:

external_eigenvectors – The external eigenvectors of the stability matrix

inline void set_external_stable(bool external_stable)

Set the external stability status.

Parameters:

external_stable – True if external stability is satisfied

inline void set_internal_eigenvalues(const Eigen::VectorXd &internal_eigenvalues)

Set the internal eigenvalues.

Parameters:

internal_eigenvalues – The internal eigenvalues of the stability matrix

inline void set_internal_eigenvectors(const Eigen::MatrixXd &internal_eigenvectors)

Set the internal eigenvectors.

Parameters:

internal_eigenvectors – The internal eigenvectors of the stability matrix

inline void set_internal_stable(bool internal_stable)

Set the internal stability status.

Parameters:

internal_stable – True if internal stability is satisfied

virtual void to_file(const std::string &filename, const std::string &type) const override

Save object to file in the specified format.

Parameters:
  • filename – Path to the output file

  • type – Format type (e.g., “json”, “hdf5”)

Throws:
  • std::invalid_argument – if format type is not supported

  • std::runtime_error – if I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Save object to HDF5 group.

Parameters:

group – HDF5 group to save data to

Throws:

std::runtime_error – if I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save object to HDF5 file.

Parameters:

filename – Path to the output HDF5 file

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert object to JSON representation.

Returns:

JSON object containing the serialized data

virtual void to_json_file(const std::string &filename) const override

Save object to JSON file.

Parameters:

filename – Path to the output JSON file

Throws:

std::runtime_error – if I/O error occurs

Public Static Functions

static std::shared_ptr<StabilityResult> from_file(const std::string &filename, const std::string &type)

Load object from file in the specified format.

Parameters:
  • filename – Path to the input file

  • type – Format type (e.g., “json”, “hdf5”)

Throws:
  • std::invalid_argument – if format type is not supported

  • std::runtime_error – if I/O error occurs

Returns:

Shared pointer to the loaded StabilityResult

static std::shared_ptr<StabilityResult> from_hdf5(H5::Group &group)

Load object from HDF5 group.

Parameters:

group – HDF5 group to load data from

Throws:

std::runtime_error – if I/O error occurs

Returns:

Shared pointer to the loaded StabilityResult

static std::shared_ptr<StabilityResult> from_hdf5_file(const std::string &filename)

Load object from HDF5 file.

Parameters:

filename – Path to the input HDF5 file

Throws:

std::runtime_error – if I/O error occurs

Returns:

Shared pointer to the loaded StabilityResult

static std::shared_ptr<StabilityResult> from_json(const nlohmann::json &j)

Load object from JSON data.

Parameters:

j – JSON object containing the serialized data

Throws:

std::runtime_error – if JSON data is invalid

Returns:

Shared pointer to the loaded StabilityResult

static std::shared_ptr<StabilityResult> from_json_file(const std::string &filename)

Load object from JSON file.

Parameters:

filename – Path to the input JSON file

Throws:

std::runtime_error – if I/O error occurs

Returns:

Shared pointer to the loaded StabilityResult

class StateVectorContainer : public qdk::chemistry::data::WavefunctionContainer
#include <qdk/chemistry/data/wavefunction_containers/state_vector.hpp>

Wavefunction container for a state expressed as a linear combination of Slater determinants.

This is the single container type for determinant-expansion wavefunctions. It stores a coefficient vector together with the corresponding determinants (as a ConfigurationSet) and subsumes the previous single-determinant (Slater determinant), complete-active-space (CAS), and selected-configuration-interaction (SCI) containers, which were structurally identical apart from a type tag.

A single Slater determinant is simply the special case of a one-determinant expansion with coefficient 1.0; use the single-determinant convenience constructor for that case. When the expansion contains exactly one determinant and no reduced density matrices (RDMs) were supplied, the active-space RDMs, orbital occupations, and single-orbital entropies are generated on the fly from the determinant occupations.

Public Types

using CoeffContainer = ContainerTypes::VectorVariant
using DeterminantVector = ContainerTypes::DeterminantVector
using MatrixVariant = ContainerTypes::MatrixVariant
using ScalarVariant = ContainerTypes::ScalarVariant
using VectorVariant = ContainerTypes::VectorVariant

Public Functions

StateVectorContainer(const Configuration &det, std::shared_ptr<Orbitals> orbitals, const std::string &sector = Wavefunction::DEFAULT_SECTOR, WavefunctionType type = WavefunctionType::SelfDual)

Constructs a single Slater-determinant state vector.

Convenience constructor for the one-determinant, coefficient-1.0 case (e.g. a Hartree-Fock reference). Validates that the configuration has sufficient orbital capacity for the active space and that any orbitals beyond the active space are unoccupied.

Note: Configurations only represent the active space, not the full orbital space. Inactive and virtual orbitals are not included in the configuration representation.

Parameters:
  • det – The single determinant configuration (active space only)

  • orbitals – Shared pointer to orbital basis set

  • sector – Name of the single-particle sector the orbitals belong to

  • type – Type of wavefunction (default: SelfDual)

Throws:

std::invalid_argument – If validation fails

StateVectorContainer(const VectorVariant &coeffs, const DeterminantVector &dets, std::shared_ptr<Orbitals> orbitals, const std::optional<MatrixVariant> &one_rdm_spin_traced, const std::optional<MatrixVariant> &one_rdm_aa, const std::optional<MatrixVariant> &one_rdm_bb, const std::optional<VectorVariant> &two_rdm_spin_traced, const std::optional<VectorVariant> &two_rdm_aaaa, const std::optional<VectorVariant> &two_rdm_aabb, const std::optional<VectorVariant> &two_rdm_bbbb, const std::string &sector = Wavefunction::DEFAULT_SECTOR, const OrbitalEntropies &entropies = OrbitalEntropies{}, WavefunctionType type = WavefunctionType::SelfDual)

Constructs a state vector with full reduced density matrix (RDM) data.

Parameters:
  • coeffs – The vector of CI coefficients (can be real or complex)

  • dets – The vector of determinants

  • orbitals – Shared pointer to orbital basis set

  • sector – Name of the single-particle sector the orbitals belong to

  • one_rdm_spin_traced – Spin-traced 1-RDM for active orbitals (optional)

  • one_rdm_aa – Alpha-alpha block of 1-RDM for active orbitals (optional)

  • one_rdm_bb – Beta-beta block of 1-RDM for active orbitals (optional)

  • two_rdm_spin_traced – Spin-traced 2-RDM for active orbitals (optional)

  • two_rdm_aaaa – Alpha-alpha-alpha-alpha block of 2-RDM for active orbitals (optional)

  • two_rdm_aabb – Alpha-alpha-beta-beta block of 2-RDM for active orbitals (optional)

  • two_rdm_bbbb – Beta-beta-beta-beta block of 2-RDM for active orbitals (optional)

  • entropies – Orbital entropies, with optional keys “single_orbital” (1-D), “two_orbital” (2-D), and “mutual_information” (2-D) (optional)

  • typeWavefunction type (SelfDual or NotSelfDual)

StateVectorContainer(const VectorVariant &coeffs, const DeterminantVector &dets, std::shared_ptr<Orbitals> orbitals, const std::optional<MatrixVariant> &one_rdm_spin_traced, const std::optional<VectorVariant> &two_rdm_spin_traced, const std::string &sector = Wavefunction::DEFAULT_SECTOR, const OrbitalEntropies &entropies = OrbitalEntropies{}, WavefunctionType type = WavefunctionType::SelfDual)

Constructs a state vector with spin-traced reduced density matrix (RDM) data.

Parameters:
  • coeffs – The vector of CI coefficients (can be real or complex)

  • dets – The vector of determinants

  • orbitals – Shared pointer to orbital basis set

  • sector – Name of the single-particle sector the orbitals belong to

  • one_rdm_spin_traced – Spin-traced 1-RDM for active orbitals (optional)

  • two_rdm_spin_traced – Spin-traced 2-RDM for active orbitals (optional)

  • entropies – Orbital entropies, with optional keys “single_orbital” (1-D), “two_orbital” (2-D), and “mutual_information” (2-D) (optional)

  • typeWavefunction type (SelfDual or NotSelfDual)

StateVectorContainer(const VectorVariant &coeffs, const DeterminantVector &dets, std::shared_ptr<Orbitals> orbitals, const std::string &sector = Wavefunction::DEFAULT_SECTOR, WavefunctionType type = WavefunctionType::SelfDual)

Constructs a state-vector wavefunction without reduced density matrices (RDMs)

Parameters:
  • coeffs – The vector of CI coefficients (can be real or complex)

  • dets – The vector of determinants

  • orbitals – Shared pointer to orbital basis set

  • sector – Name of the single-particle sector the orbitals belong to

  • typeWavefunction type (SelfDual or NotSelfDual)

StateVectorContainer(const VectorVariant &coeffs, const DeterminantVector &dets, std::shared_ptr<Orbitals> orbitals, std::shared_ptr<MatrixVariant> one_rdm_spin_traced, std::shared_ptr<VectorVariant> two_rdm_spin_traced, std::shared_ptr<const SymmetryBlockedTensorVariant<2>> active_one_rdm, std::shared_ptr<const SymmetryBlockedTensorVariant<4>> active_two_rdm, const std::string &sector = Wavefunction::DEFAULT_SECTOR, const OrbitalEntropies &entropies = OrbitalEntropies{}, WavefunctionType type = WavefunctionType::SelfDual)

Constructs a state vector from preconstructed RDM storage.

Used by the serialization layer to hand reconstructed SymmetryBlockedTensorVariant objects to the container without going through the per-block construction path.

Parameters:
  • coeffs – The vector of CI coefficients (real or complex).

  • dets – The vector of determinants.

  • orbitals – Shared pointer to orbital basis set.

  • sector – Name of the single-particle sector the orbitals belong to.

  • one_rdm_spin_traced – Spin-traced 1-RDM (may be nullptr).

  • two_rdm_spin_traced – Spin-traced 2-RDM (may be nullptr).

  • active_one_rdm – Spin-dependent active-space 1-RDM (may be nullptr).

  • active_two_rdm – Spin-dependent active-space 2-RDM (may be nullptr).

  • entropies – Orbital entropies.

  • typeWavefunction type (SelfDual or NotSelfDual).

~StateVectorContainer() override = default

Destructor.

virtual std::shared_ptr<const SymmetryBlockedScalar<std::size_t>> active_num_particles() const override

Number of active-space particles as a symmetry-blocked scalar.

Returns:

Shared pointer to the symmetry-blocked active particle count.

virtual const SymmetryBlockedTensorVariant<2> &active_one_rdm() const override

Active-space spin-dependent one-particle RDM as an SBT.

Returns stored data when available; for a single-determinant expansion the RDM is generated lazily from the determinant occupations.

virtual std::shared_ptr<const SymmetryBlockedTensor<1>> active_orbital_occupations() const override

Orbital occupations for active orbitals only as a rank-1 symmetry-blocked tensor.

Returns:

Shared pointer to the symmetry-blocked active orbital occupations.

virtual const SymmetryBlockedTensorVariant<4> &active_two_rdm() const override

Active-space spin-dependent two-particle RDM as an SBT.

Returns stored data when available; for a single-determinant expansion the RDM is generated lazily from the determinant occupations.

virtual void clear_caches() const override

Clear cached data to release memory.

Clears the cached active-space RDMs (spin-traced and spin-dependent).

virtual std::unique_ptr<WavefunctionContainer> clone() const override

Clone method for deep copying.

bool contains_determinant(const Configuration &det) const

Check if a determinant is present in the expansion.

Parameters:

det – Configuration/determinant to check for

Returns:

True if the determinant is present

virtual const DeterminantVector &get_active_determinants() const override

Get all determinants in the wavefunction.

Returns:

Vector of all configurations/determinants

virtual const MatrixVariant &get_active_one_rdm_spin_traced() const override

Get spin-traced one-particle RDM for active orbitals only.

virtual const VectorVariant &get_active_two_rdm_spin_traced() const override

Get spin-traced two-particle RDM for active orbitals only.

virtual ScalarVariant get_coefficient(const Configuration &det) const override

Get coefficient for a specific determinant.

The configuration is expected to be a determinant describing only the wavefunction’s active space.

Parameters:

det – Configuration/determinant to get coefficient for

Returns:

Coefficient of the determinant

virtual const VectorVariant &get_coefficients() const override

Get all coefficients in the wavefunction.

Returns:

Vector of all coefficients (real or complex)

virtual const ConfigurationSet &get_configuration_set() const override

Get the configuration set for this wavefunction.

Returns:

Reference to the configuration set containing determinants and orbitals

virtual std::string get_container_type() const override

Get container type identifier for serialization.

Returns:

String “state_vector”

virtual std::shared_ptr<Orbitals> get_orbitals() const override

Get reference to orbital basis set.

Returns:

Shared pointer to orbitals

virtual Eigen::VectorXd get_single_orbital_entropies() const override

Calculate single orbital entropies for active orbitals only.

virtual bool has_coefficients() const override

Check if this container has coefficients data.

Returns:

True if coefficients are available, false otherwise

virtual bool has_configuration_set() const override

Check if this container has configuration set data.

Returns:

True if configuration set is available, false otherwise

virtual bool has_one_rdm_spin_dependent() const override

Check if spin-dependent one-particle RDMs for active orbitals are available.

Returns:

True if available

virtual bool has_one_rdm_spin_traced() const override

Check if spin-traced one-particle RDM for active orbitals is available.

Returns:

True if available

virtual bool has_two_rdm_spin_dependent() const override

Check if spin-dependent two-particle RDMs for active orbitals are available.

Returns:

True if available

virtual bool has_two_rdm_spin_traced() const override

Check if spin-traced two-particle RDM for active orbitals is available.

Returns:

True if available

virtual void hash_update(qdk::chemistry::utils::HashContext &ctx) const override

Feed identifying data into a hash context.

virtual bool is_complex() const override

Check if the wavefunction is complex-valued.

Returns:

True if coefficients are complex, false if real

virtual double norm() const override

Calculate norm of the wavefunction.

Returns:

Norm

virtual ScalarVariant overlap(const WavefunctionContainer &other) const override

Calculate overlap with another wavefunction.

Parameters:

other – Other wavefunction

Returns:

Overlap value

virtual std::shared_ptr<const Orbitals> sector_basis(const std::string &name) const override

Single-particle basis bound to a sector.

Parameters:

name – Sector name to resolve.

Throws:

std::out_of_range – if this container has no sector named name.

Returns:

Shared pointer to the Orbitals bound to name.

virtual std::vector<std::string> sectors() const override

Names of the single-particle sectors, from the configuration set’s sector layout.

Returns:

Names of the container’s sectors.

virtual size_t size() const override

Get number of determinants.

Returns:

Number of determinants in the wavefunction

virtual nlohmann::json to_json() const override

Convert container to JSON format.

Returns:

JSON object containing container data

virtual std::shared_ptr<const SymmetryBlockedScalar<std::size_t>> total_num_particles() const override

Number of particles (active + inactive) as a symmetry-blocked scalar.

Returns:

Shared pointer to the symmetry-blocked total particle count.

virtual std::shared_ptr<const SymmetryBlockedTensor<1>> total_orbital_occupations() const override

Orbital occupations for all orbitals (total = active + inactive + virtual) as a rank-1 symmetry-blocked tensor.

Returns:

Shared pointer to the symmetry-blocked total orbital occupations.

Public Static Functions

static std::unique_ptr<WavefunctionContainer> from_hdf5(H5::Group &group)

Load container from HDF5 group.

Reads the current “state_vector” format as well as the legacy “cas”, “sci”, and “sd” formats (read-only backward compatibility).

Parameters:

group – HDF5 group containing container data

Throws:

std::runtime_error – if HDF5 data is malformed or I/O error occurs

Returns:

Unique pointer to the container created from HDF5 group

static std::unique_ptr<WavefunctionContainer> from_json(const nlohmann::json &j)

Load container from JSON format.

Reads the current “state_vector” format as well as the legacy “cas”, “sci”, and “sd” formats (read-only backward compatibility).

Parameters:

j – JSON object containing container data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Unique pointer to the container created from JSON data

class Structure : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<Structure>
#include <qdk/chemistry/data/structure.hpp>

Represents a molecular structure with atomic coordinates, elements, masses, and nuclear charges.

This class stores and manipulates molecular structure data including:

  • Atomic coordinates in 3D space

  • Atomic element identifiers using Element enum

  • Atomic masses (in atomic mass units)

  • Nuclear charges (atomic numbers) for each atom

  • Serialization to/from JSON and XYZ formats

  • Basic geometric operations and validation

The structure can be constructed from various input formats and provides convenient access to atomic properties and molecular geometry. Standard atomic masses and nuclear charges are used by default unless otherwise specified. The class is designed to be immutable after construction, ensuring data integrity.

Public Functions

Structure(const Eigen::MatrixXd &coordinates, const std::vector<Element> &elements, const Eigen::VectorXd &masses = {}, const Eigen::VectorXd &nuclear_charges = {})

Constructor with coordinates, elements, masses, and nuclear charges.

Parameters:
  • coordinates – Matrix of atomic coordinates (N x 3) in Bohr

  • elements – Vector of atomic elements using enum

  • masses – Vector of atomic masses in AMU (default: use default masses)

  • nuclear_charges – Vector of nuclear charges (default: use default charges)

Throws:

std::invalid_argument – if dimensions don’t match

Structure(const Eigen::MatrixXd &coordinates, const std::vector<std::string> &symbols, const Eigen::VectorXd &masses = {}, const Eigen::VectorXd &nuclear_charges = {})

Constructor from atomic symbols and coordinates.

Parameters:
  • coordinates – Matrix of atomic coordinates (N x 3) in Bohr

  • symbols – Vector of atomic symbols (e.g., “H”, “C”, “O”)

  • masses – Vector of atomic masses in AMU (default: use default masses)

  • nuclear_charges – Vector of nuclear charges (default: use default charges)

Throws:

std::invalid_argument – if dimensions don’t match or unknown symbols

Structure(const std::vector<Eigen::Vector3d> &coordinates, const std::vector<Element> &elements, const std::vector<double> &masses = {}, const std::vector<double> &nuclear_charges = {})

Constructor from atomic elements and coordinates as vector.

Parameters:
  • coordinates – Vector of atomic coordinates (N x 3) in Bohr

  • elements – Vector of atomic elements using enum

  • masses – Vector of atomic masses in AMU (default: use default masses)

  • nuclear_charges – Vector of nuclear charges (default: use default charges)

Throws:

std::invalid_argument – if dimensions don’t match

Structure(const std::vector<Eigen::Vector3d> &coordinates, const std::vector<std::string> &symbols, const std::vector<double> &masses = {}, const std::vector<double> &nuclear_charges = {})

Constructor from atomic symbols and coordinates as vector.

Parameters:
  • coordinates – Vector of atomic coordinates (N x 3) in Bohr

  • symbols – Vector of atomic symbols (e.g., “H”, “C”, “O”)

  • masses – Vector of atomic masses in AMU (default: use default masses)

  • nuclear_charges – Vector of nuclear charges (default: use default charges)

Throws:

std::invalid_argument – if dimensions don’t match or unknown symbols

Structure(const Structure &other) = default

Copy constructor.

Structure(Structure &&other) noexcept = default

Move constructor.

virtual ~Structure() = default

Destructor.

double calculate_nuclear_repulsion_energy() const

Calculate nuclear-nuclear repulsion energy.

This function calculates the Coulombic repulsion energy between all nuclei in the structure using the formula: E_nn = sum_{i<j} Z_i * Z_j / |R_i - R_j| where Z_i is the nuclear charge of atom i and R_i is its position vector.

Returns:

Nuclear repulsion energy in atomic units (Hartree)

Eigen::Vector3d get_atom_coordinates(size_t atom_index) const

Get coordinates for a specific atom.

Parameters:

atom_index – Index of the atom (0-based)

Throws:

std::out_of_range – if atom_index is invalid

Returns:

3D coordinates as Eigen::Vector3d

Element get_atom_element(size_t atom_index) const

Get element for a specific atom.

Parameters:

atom_index – Index of the atom (0-based)

Throws:

std::out_of_range – if atom_index is invalid

Returns:

Atomic element enum

double get_atom_mass(size_t atom_index) const

Get mass for a specific atom.

Parameters:

atom_index – Index of the atom (0-based)

Throws:

std::out_of_range – if atom_index is invalid

Returns:

Atomic mass in AMU

double get_atom_nuclear_charge(size_t atom_index) const

Get nuclear charge for a specific atom.

Parameters:

atom_index – Index of the atom (0-based)

Throws:

std::out_of_range – if atom_index is invalid

Returns:

Nuclear charge (atomic number)

std::string get_atom_symbol(size_t atom_index) const

Get atomic symbol for a specific atom.

Parameters:

atom_index – Index of the atom (0-based)

Throws:

std::out_of_range – if atom_index is invalid

Returns:

Atomic symbol (e.g., “H”, “C”, “O”)

std::vector<std::string> get_atomic_symbols() const

Get all atomic symbols.

Returns:

Vector of atomic symbols

inline const Eigen::MatrixXd &get_coordinates() const

Get the atomic coordinates matrix.

Returns:

Matrix of coordinates (N x 3) in Bohr

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“structure”

inline const std::vector<Element> &get_elements() const

Get the atomic elements vector.

Returns:

Vector of atomic elements

inline const Eigen::VectorXd &get_masses() const

Get the atomic masses vector.

Returns:

Vector of atomic masses in AMU

inline const Eigen::VectorXd &get_nuclear_charges() const

Get the nuclear charges vector.

Returns:

Vector of nuclear charges (atomic numbers)

inline size_t get_num_atoms() const

Get the number of atoms in the structure.

Returns:

Number of atoms

virtual std::string get_summary() const override

Get summary string of structure information.

Returns:

String describing the structure

double get_total_mass() const

Calculate the total molecular mass.

Returns:

Total mass in AMU

inline bool is_empty() const

Check if the structure is empty.

Returns:

True if no atoms are present

Structure &operator=(const Structure&) = delete

Copy assignment operator.

Structure &operator=(Structure&&) = delete

Move assignment operator.

virtual void to_file(const std::string &filename, const std::string &type) const override

Save structure to file in specified format.

Parameters:
  • filename – Path to file to create/overwrite

  • type – Format type (“json”, “xyz”, or “hdf5”)

Throws:
  • std::invalid_argument – if unknown type

  • std::runtime_error – if I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Convert structure to HDF5 group.

Parameters:

group – HDF5 group to write structure data to

Throws:

std::runtime_error – if HDF5 I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save structure to HDF5 file.

Parameters:

filename – Path to HDF5 file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert structure to JSON format.

Returns:

JSON object containing structure data with coordinates in Bohr

virtual void to_json_file(const std::string &filename) const override

Save structure to JSON file.

Parameters:

filename – Path to JSON file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

std::string to_xyz(const std::string &comment = "") const

Convert structure to XYZ format string.

Parameters:

comment – Optional comment line (default: empty)

Returns:

XYZ format string with coordinates in Angstrom

void to_xyz_file(const std::string &filename, const std::string &comment = "") const

Save structure to XYZ file.

Parameters:
  • filename – Path to XYZ file to create/overwrite

  • comment – Optional comment line (default: empty)

Throws:

std::runtime_error – if I/O error occurs

Public Static Functions

static unsigned element_to_nuclear_charge(Element element)

Convert element enum to nuclear charge.

Parameters:

element – Atomic element enum

Returns:

Nuclear charge (atomic number)

static std::string element_to_symbol(Element element)

Convert element enum to atomic symbol.

Parameters:

element – Atomic element enum

Returns:

Atomic symbol (e.g., “H”, “C”, “O”)

static std::shared_ptr<Structure> from_file(const std::string &filename, const std::string &type)

Load structure from file in specified format.

Parameters:
  • filename – Path to file to create/overwrite

  • type – Format type (“json”, “xyz”, or “hdf5”)

Throws:
  • std::invalid_argument – if unknown type

  • std::runtime_error – if I/O error occurs

Returns:

Structure object created from file

static std::shared_ptr<Structure> from_hdf5(H5::Group &group)

Load structure from HDF5 group.

Parameters:

group – HDF5 group containing structure data

Throws:

std::runtime_error – if HDF5 data is malformed or I/O error occurs

Returns:

Shared pointer to Structure object created from HDF5 group

static std::shared_ptr<Structure> from_hdf5_file(const std::string &filename)

Load structure from HDF5 file.

Parameters:

filename – Path to HDF5 file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to Structure object created from HDF5 file

static std::shared_ptr<Structure> from_json(const nlohmann::json &j)

Load structure from JSON format.

Parameters:

j – JSON object containing structure data with coordinates in Bohr

Throws:

std::runtime_error – if JSON is malformed

Returns:

Shared pointer to const Structure object created from JSON data

static std::shared_ptr<Structure> from_json_file(const std::string &filename)

Load structure from JSON file.

Parameters:

filename – Path to JSON file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to const Structure object created from JSON file

static std::shared_ptr<Structure> from_xyz(const std::string &xyz_string)

Load structure from XYZ format string.

Parameters:

xyz_string – XYZ format string with coordinates in Angstrom

Throws:

std::runtime_error – if XYZ format is invalid

Returns:

Structure object created from XYZ string

static std::shared_ptr<Structure> from_xyz_file(const std::string &filename)

Load structure from XYZ file.

Parameters:

filename – Path to XYZ file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to a Structure object created from XYZ file

static double get_default_atomic_mass(Element element)

Get standard atomic mass for an element.

Parameters:

element – Atomic element enum

Returns:

Standard atomic mass in AMU

static double get_default_atomic_mass(std::string symbol)

Get atomic mass for an element symbol string.

Parameters:

symbol – Element symbol (e.g., “H”, “H2”, “C”, “C12”, “C13”) Using an element symbol string without a mass number returns the standard atomic weight. “D” (deuterium) can be used as alias for “H2”. “T” (tritium) can be used as alias for “H3”.

Returns:

Atomic mass in AMU

static unsigned get_default_nuclear_charge(Element element)

Get nuclear charge for an element.

Parameters:

element – Atomic element enum

Returns:

Nuclear charge (atomic number)

static Element nuclear_charge_to_element(unsigned nuclear_charge)

Convert nuclear charge to element enum.

Parameters:

nuclear_charge – Nuclear charge (atomic number)

Throws:

std::invalid_argument – if unknown nuclear charge

Returns:

Atomic element enum

static std::string nuclear_charge_to_symbol(unsigned nuclear_charge)

Convert nuclear charge to atomic symbol.

Parameters:

nuclear_charge – Nuclear charge (atomic number)

Throws:

std::invalid_argument – if unknown nuclear charge

Returns:

Atomic symbol (e.g., “H”, “C”, “O”)

static Element symbol_to_element(const std::string &symbol)

Convert atomic symbol to element enum.

Parameters:

symbol – Atomic symbol (e.g., “H”, “C”, “O”)

Throws:

std::invalid_argument – if unknown symbol

Returns:

Atomic element enum

static unsigned symbol_to_nuclear_charge(const std::string &symbol)

Convert atomic symbol to nuclear charge.

Parameters:

symbol – Atomic symbol (e.g., “H”, “C”, “O”)

Throws:

std::invalid_argument – if unknown symbol

Returns:

Nuclear charge (atomic number)

class SumPauliOperatorExpression : public qdk::chemistry::data::PauliOperatorExpression
#include <qdk/chemistry/data/pauli_operator.hpp>

A PauliOperatorExpression representing a sum of expressions.

This class represents linear combinations of Pauli operator expressions. For example, 2*X(0) + 3*Y(1)*Z(2) represents a sum of two terms.

Terms can be any PauliOperatorExpression type, including nested sums and products. The distribute() and simplify() methods can be used to flatten and combine terms.

Public Functions

SumPauliOperatorExpression()

Constructs an empty sum (represents zero).

SumPauliOperatorExpression(const PauliOperatorExpression &left, const PauliOperatorExpression &right)

Constructs a sum of two expressions.

Parameters:
  • left – The first term.

  • right – The second term.

SumPauliOperatorExpression(const SumPauliOperatorExpression &other)

Copy constructor.

Deep copies all terms.

Parameters:

other – The SumPauliOperatorExpression to copy.

void add_term(std::unique_ptr<PauliOperatorExpression> term)

Appends a term to this sum.

Ownership is transferred.

Parameters:

term – The expression to add.

virtual std::unique_ptr<PauliOperatorExpression> clone() const override

Creates a deep copy of this sum expression.

Returns:

A unique_ptr to a new SumPauliOperatorExpression.

virtual std::unique_ptr<SumPauliOperatorExpression> distribute() const override

Distributes all terms and returns a flat sum of products.

Calls distribute() on each term and collects all resulting products. The result contains only ProductPauliOperatorExpression terms, each containing only PauliOperator factors.

Returns:

A new SumPauliOperatorExpression in distributed form.

const std::vector<std::unique_ptr<PauliOperatorExpression>> &get_terms() const

Returns a const reference to the internal term list.

Returns:

Vector of expression terms in addition order.

virtual std::uint64_t max_qubit_index() const override

Returns the maximum qubit index referenced in this expression.

Throws:

std::logic_error – If the expression has no terms.

Returns:

The maximum qubit index.

virtual std::uint64_t min_qubit_index() const override

Returns the minimum qubit index referenced in this expression.

Throws:

std::logic_error – If the expression has no terms.

Returns:

The minimum qubit index.

virtual std::uint64_t num_qubits() const override

Returns the number of qubits spanned by this expression.

Returns:

max_qubit_index() - min_qubit_index() + 1, or 0 if empty.

virtual std::unique_ptr<SumPauliOperatorExpression> prune_threshold(double epsilon) const override

Returns a sum with small-magnitude terms removed.

Recursively processes nested sums. Bare PauliOperators have an implicit coefficient of 1.0.

Parameters:

epsilon – Terms with |coefficient| < epsilon are excluded.

Returns:

A new SumPauliOperatorExpression with small terms filtered out.

void reserve_capacity(std::size_t capacity)

Pre-allocates capacity for the term list.

Parameters:

capacity – The number of terms to reserve space for.

virtual std::unique_ptr<PauliOperatorExpression> simplify() const override

Simplifies this sum by combining like terms.

Simplification performs the following steps:

  1. Distributes the expression to flatten nested sums/products

  2. Simplifies each term individually (applying Pauli algebra)

  3. Collects like terms: terms with identical Pauli strings have their coefficients added together

  4. Removes terms with exactly zero coefficients

Term ordering is preserved for non-duplicate terms.

Returns:

A simplified SumPauliOperatorExpression.

virtual std::string to_canonical_string(std::uint64_t min_qubit, std::uint64_t max_qubit) const override

Returns the canonical string for a single-term sum.

Parameters:
  • min_qubit – The minimum qubit index to include.

  • max_qubit – The maximum qubit index to include (inclusive).

Throws:

std::logic_error – If the sum has more than one term after simplification.

Returns:

The canonical string, or “0” if empty.

virtual std::string to_canonical_string(std::uint64_t num_qubits) const override

Returns the canonical string for a single-term sum.

This method simplifies the sum first. It is intended for sums that reduce to a single term after simplification.

Parameters:

num_qubits – The total number of qubits to represent.

Throws:

std::logic_error – If the sum has more than one term after simplification. Use to_canonical_terms() for multi-term sums.

Returns:

The canonical string of the single term, or “0” if empty.

virtual std::vector<std::pair<std::complex<double>, std::string>> to_canonical_terms() const override

Returns each term as a (coefficient, canonical_string) pair.

Uses the range [0, max_qubit_index()] for the canonical strings. Returns an empty vector for an empty sum.

Throws:

std::logic_error – If any term is not in distributed form.

Returns:

Vector of (coefficient, canonical_string) pairs.

virtual std::vector<std::pair<std::complex<double>, std::string>> to_canonical_terms(std::uint64_t num_qubits) const override

Returns each term as a (coefficient, canonical_string) pair.

Each term in the sum produces one entry. This method does not simplify or combine like terms; call simplify() first if that is desired.

Parameters:

num_qubits – The total number of qubits to represent.

Throws:

std::logic_error – If any term is not in distributed form.

Returns:

Vector of (coefficient, canonical_string) pairs.

virtual std::string to_string() const override

Returns a human-readable string representation of this sum.

Terms are joined with “ + “ or “ - “ depending on sign. An empty sum returns “0”.

Returns:

A string like “X(0) + 2 * Y(1) - Z(2)”.

class SymmetryAxis : public qdk::chemistry::data::DataClass
#include <qdk/chemistry/data/symmetry/symmetry.hpp>

One named symmetry partition a tensor may be blocked under.

Holds the axis name, the ordered set of admissible labels, and an equivalent flag indicating whether the labels under this axis share storage or are stored independently.

Public Functions

SymmetryAxis(AxisName name, std::vector<std::shared_ptr<const SymmetryAxisValue>> labels, bool equivalent)

Construct a symmetry axis with the given name, admissible labels, and equivalence flag.

Parameters:
  • name – Identifier of the axis (see AxisName).

  • labels – Ordered set of admissible SymmetryAxisValue labels carried by this axis.

  • equivalenttrue if the labels under this axis share storage (e.g. restricted spin where \(\alpha\) and \(\beta\) alias the same MO coefficients).

bool admits(const SymmetryAxisValue &value) const

True iff value is one of this axis’s admissible labels.

Parameters:

value – Candidate axis value to test.

Returns:

true if value is admissible under this axis.

bool equivalent() const

Whether labels under this axis share storage (i.e.

the restricted-spin alias).

Returns:

true if labels alias the same storage; false otherwise.

inline virtual std::string get_data_type_name() const override

DataClass type identifier.

Returns:

The string "symmetry_axis".

virtual std::string get_summary() const override

Single-line human-readable summary.

Returns:

A string of the form SymmetryAxis(name=..., equivalent=..., labels=...).

std::size_t hash() const

Hash consistent with operator==.

Returns:

Hash value suitable for use with std::hash.

const std::vector<std::shared_ptr<const SymmetryAxisValue>> &labels() const

The ordered list of admissible labels for this axis.

Returns:

Reference to the labels supplied at construction.

AxisName name() const

The identifier of this axis.

Returns:

The axis name (see AxisName).

inline bool operator!=(const SymmetryAxis &other) const

Inverse of operator==.

Parameters:

other – Right-hand axis to compare against.

Returns:

true if any of name, labels, or equivalence flag differs.

bool operator==(const SymmetryAxis &other) const

Value-equality against another axis.

Parameters:

other – Right-hand axis to compare against.

Returns:

true if name, labels, and equivalence flag all match.

virtual void to_file(const std::string &filename, const std::string &type) const override

Dispatch to JSON or HDF5 serialization based on type.

Parameters:
  • filename – Path to the output file.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if an I/O error occurs.

virtual void to_hdf5(H5::Group &group) const override

Serialize this axis into an HDF5 group.

The implementation writes the JSON form (see to_json) as a single string dataset within group, mirroring the HDF5 layout used by SymmetryBlockedIndexSet.

Parameters:

group – HDF5 group to write data to.

Throws:

std::runtime_error – if an HDF5 I/O error occurs.

virtual void to_hdf5_file(const std::string &filename) const override

Serialize this axis to an HDF5 file.

Parameters:

filename – Path to the output HDF5 file (created or truncated).

Throws:

std::runtime_error – if an HDF5 I/O error occurs.

virtual nlohmann::json to_json() const override

Serialize this axis to JSON.

Returns:

JSON object with "name", "equivalent", and "labels" fields. Each label is the verbatim to_json fragment of a SymmetryAxisValue (whose polymorphic "kind" tag is preserved).

virtual void to_json_file(const std::string &filename) const override

Serialize this axis to a JSON file.

Parameters:

filename – Path to the output JSON file.

Throws:

std::runtime_error – if filename cannot be opened for writing.

Public Static Functions

static std::shared_ptr<SymmetryAxis> from_file(const std::string &filename, const std::string &type)

Dispatch to JSON or HDF5 deserialization based on type.

Parameters:
  • filename – Path to the input file.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if filename cannot be read or its contents are malformed.

Returns:

Shared pointer to the deserialized SymmetryAxis.

static std::shared_ptr<SymmetryAxis> from_hdf5(H5::Group &group)

Load a SymmetryAxis from an HDF5 group produced by to_hdf5.

Parameters:

group – HDF5 group to read data from.

Throws:

std::runtime_error – if the expected dataset is missing or the payload is malformed.

Returns:

Shared pointer to the deserialized SymmetryAxis.

static std::shared_ptr<SymmetryAxis> from_hdf5_file(const std::string &filename)

Load a SymmetryAxis from an HDF5 file produced by to_hdf5_file.

Parameters:

filename – Path to the input HDF5 file.

Throws:

std::runtime_error – if filename cannot be read or its contents are malformed.

Returns:

Shared pointer to the deserialized SymmetryAxis.

static std::shared_ptr<SymmetryAxis> from_json(const nlohmann::json &j)

Reconstruct a SymmetryAxis from JSON produced by to_json.

Parameters:

j – JSON object containing axis data.

Throws:

std::runtime_error – if j is missing required fields or contains an unknown axis name.

Returns:

Shared pointer to the deserialized SymmetryAxis.

static std::shared_ptr<SymmetryAxis> from_json_file(const std::string &filename)

Load a SymmetryAxis from a JSON file produced by to_json_file.

Parameters:

filename – Path to the input JSON file.

Throws:

std::runtime_error – if filename cannot be read or its contents are malformed.

Returns:

Shared pointer to the deserialized SymmetryAxis.

class SymmetryAxisValue
#include <qdk/chemistry/data/symmetry/symmetry.hpp>

Abstract value carried by a single symmetry axis.

Concrete subclasses (e.g. SpinValue) represent one label of one axis. Instances are shared via shared_ptr<const> so that symmetry-equivalent uses can be interned.

Subclassed by qdk::chemistry::data::SpinValue

Public Functions

virtual ~SymmetryAxisValue() = default

Defaulted virtual destructor.

Declared virtual so that derived axis values can be safely deleted through a SymmetryAxisValue pointer.

virtual AxisName axis() const = 0

The axis this value belongs to.

Returns:

The AxisName identifying the owning axis.

virtual bool equals(const SymmetryAxisValue &other) const = 0

Value-equality against another axis value.

Parameters:

other – Right-hand axis value to compare against.

Returns:

true iff other is the same concrete subclass and carries the same payload.

virtual std::size_t hash() const = 0

Hash consistent with equals.

Returns:

Hash value derived from the subclass payload.

inline bool operator!=(const SymmetryAxisValue &other) const

Negation of operator==.

Parameters:

other – Axis value to compare against.

Returns:

true iff equals returns false for other.

inline bool operator==(const SymmetryAxisValue &other) const

Convenience wrapper around equals for symmetry with sibling types (SymmetryAxis, SymmetryProduct, SymmetryLabel).

Parameters:

other – Axis value to compare against.

Returns:

true iff equals returns true for other.

virtual nlohmann::json to_json() const = 0

Serialize this value (subclass payload only).

The polymorphic "kind" tag is written by the enclosing SymmetryLabel / SymmetryAxis so subclasses need only emit their own state.

Returns:

JSON object carrying the subclass payload.

template<std::size_t Rank, typename Block>
class SymmetryBlocked : public qdk::chemistry::data::DataClass
#include <qdk/chemistry/data/symmetry/symmetry_blocked.hpp>

Symmetry-addressed container of per-block storage.

A SymmetryBlocked stores a sparse map from per-slot SymmetryLabel arrays to opaque block values of type Block. Each slot carries its own SymmetryProduct and a per-label extent. Blocks are held via shared_ptr<const Block> so that symmetry-equivalent sectors can alias the same storage.

Symmetry aliasing is defined on the spin axis: a simultaneous \(\alpha \leftrightarrow \beta\) swap across all slots. When every slot shares the same SymmetryProduct instance and the spin axis is marked equivalent, the constructor auto-aliases each partner block to the supplied representative. Aliasing can also be achieved by the producer supplying the same shared_ptr for both spin partners (e.g. restricted basis coefficients share the same MO matrix for both spins).

The full block map is supplied at construction.

Derived classes (e.g. SymmetryBlockedTensor) add block-type-specific validation and serialization.

Template Parameters:
  • Rank – Number of label slots (1, 2, or 4 are typical).

  • Block – The per-block storage type (e.g. Eigen::MatrixXd, std::map, std::vector).

Subclassed by qdk::chemistry::data::SymmetryBlockedScalar< Scalar >, qdk::chemistry::data::SymmetryBlockedSparseMap< Rank, Scalar >, qdk::chemistry::data::SymmetryBlockedTensor< Rank, Scalar >

Public Types

using BlockMap = std::unordered_map<Labels, BlockPtr, LabelsHash<Rank>>

Sparse map from per-slot label tuples to block storage.

Aliased sectors (e.g. restricted-spin partners) map to the same BlockPtr. Keys are hashed via LabelsHash.

using BlockPtr = std::shared_ptr<const Block>

Shared pointer to immutable per-block storage.

Held as shared_ptr<const Block> so that symmetry-equivalent sectors can alias the same underlying storage.

using ExtentsArray = std::array<std::unordered_map<SymmetryLabel, std::size_t>, Rank>

Per-slot per-label extents.

For each index slot, maps every admissible SymmetryLabel to the universe size (number of basis vectors) carried under that label.

using Labels = std::array<SymmetryLabel, Rank>

Per-slot block label tuple: one SymmetryLabel per index slot.

Used as the key type of BlockMap so that blocks are addressed by the full tuple of per-slot symmetry labels.

using SymmetriesArray = std::array<std::shared_ptr<const SymmetryProduct>, Rank>

Per-slot symmetry definitions.

One SymmetryProduct per index slot; supplied at construction and used to validate block labels and apply orbit aliasing.

Public Functions

inline SymmetryBlocked(SymmetriesArray symmetries, ExtentsArray extents, BlockMap blocks)

Construct from per-slot symmetries, per-slot extents, and a block map.

Validates symmetries and extents, checks block label admissibility and null pointers, then applies orbit aliasing. Derived classes should call their own block-shape validation after this constructor returns.

Parameters:
  • symmetries – Per-slot SymmetryProduct definitions. None of the pointers may be null.

  • extents – Per-slot per-label universe sizes; every declared label must be admissible under its slot’s symmetries.

  • blocks – Block storage keyed by per-slot SymmetryLabel tuples; pointers must be non-null and labels admissible.

Throws:

std::invalid_argument – if a block or extent label is not admissible under the matching slot’s SymmetryProduct, if a block pointer is null, if restricted orbit partners have unequal extents, or if both orbit partners are supplied but do not share storage.

inline bool all_aliased(const std::vector<Labels> &keys) const

Whether every stored key in keys aliases the same block.

Keys absent from the container are skipped (they do not break aliasing). Returns true when zero or one of keys is stored, or when all stored keys map to the same underlying block pointer.

Parameters:

keys – Per-slot label tuples to compare.

Returns:

true iff the stored keys all share storage; false if any two stored keys point at different blocks.

inline const Block &block(const Labels &labels) const

Reference to the block stored for labels.

If all labels in the key are trivial (empty), returns the sole block when exactly one unique block exists.

Parameters:

labels – Per-slot label tuple identifying the block.

Throws:

std::invalid_argument – if no such block exists or the trivial key is ambiguous.

Returns:

Const reference to the requested block storage.

inline BlockPtr block_ptr(const Labels &labels) const

Shared pointer to the block stored for labels.

If all labels in the key are trivial (empty), returns the sole block when exactly one unique block exists.

Parameters:

labels – Per-slot label tuple identifying the block.

Throws:

std::invalid_argument – if no such block exists or the trivial key is ambiguous.

Returns:

Shared pointer to the requested block storage; same instance is returned for every key that aliases the same storage.

inline const ExtentsArray &extents() const

Per-slot per-label extents.

Returns:

Reference to the ExtentsArray supplied at construction.

inline bool has_block(const Labels &labels) const

True iff a block is stored for labels.

If all labels in the key are trivial (empty), returns true when exactly one unique block exists.

Parameters:

labels – Per-slot label tuple to look up.

Returns:

true if labels (or the unambiguous trivial-key shortcut) maps to a stored block.

inline std::size_t num_blocks() const

Total number of stored blocks (including aliases).

Returns:

Size of the underlying BlockMap; counts each key independently even if multiple keys alias the same storage.

inline const SymmetriesArray &symmetries() const

Per-slot symmetry definitions.

Returns:

Reference to the SymmetriesArray supplied at construction.

class SymmetryBlockedIndexSet : public qdk::chemistry::data::SymmetryBlocked<1, std::vector<std::uint32_t>>
#include <qdk/chemistry/data/symmetry/symmetry_blocked_index_set.hpp>

Sorted-unique integer index subset, blocked by symmetry.

A SymmetryBlockedIndexSet describes, for each admissible SymmetryLabel of a single SymmetryProduct, a sorted set of unique indices drawn from [0, extent) for that label. The extent is the universe size for that label (e.g. the total number of α MOs) and is stored separately from the indices subset, so the universe boundary survives serialization even when the subset is sparse or empty.

Typical use: carving out symmetry-respecting subspaces (core / active / virtual orbital partitions) of a SymmetryBlockedTensor.

Example — active α = {2,3,4} drawn from 10 α MOs:

std::unordered_map<SymmetryLabel, std::size_t> extents;
extents[SymmetryLabel({axes::alpha()})] = 10;           // universe size

std::unordered_map<SymmetryLabel, std::vector<std::uint32_t>> indices;
indices[SymmetryLabel({axes::alpha()})] = {2u, 3u, 4u}; // chosen subset

SymmetryBlockedIndexSet active(symmetries, extents, indices);

Public Functions

SymmetryBlockedIndexSet(std::shared_ptr<const SymmetryProduct> symmetries, std::unordered_map<SymmetryLabel, std::size_t> extents, std::unordered_map<SymmetryLabel, std::vector<std::uint32_t>> indices)

Construct from symmetry definitions, per-label extents, and per-label index lists.

Parameters:
  • symmetries – The symmetry definitions this index set is blocked under. Determines the admissible SymmetryLabel keys for extents and indices.

  • extents – Per-label universe size. extents[label] is the upper bound (exclusive) of the index range from which the indices entries for that label are drawn. The extent is not derived from indices[label].size() because the subset may be strictly smaller than (or sparser than, or empty within) its universe, and the universe boundary must survive serialization independently of the chosen subset.

  • indices – Per-label chosen subset, sorted strictly increasing. Every index must satisfy 0 <= idx < extents[label].

Throws:
  • std::invalid_argument – if a label is not admissible under symmetries, lacks a declared extent, or an index list is not strictly increasing.

  • std::out_of_range – if an index is >= its label’s extent.

inline const std::unordered_map<SymmetryLabel, std::size_t> &extents() const

Per-label extents.

Returns:

Reference to the map from admissible SymmetryLabel to its universe size.

inline virtual std::string get_data_type_name() const override

DataClass type identifier.

Returns:

The stable string "symmetry_blocked_index_set".

virtual std::string get_summary() const override

Single-line human-readable summary of the contained labels.

Returns:

A short diagnostic string suitable for logging.

inline bool has(const SymmetryLabel &label) const

True iff indices are stored for label.

Parameters:

label – Symmetry label to look up.

Returns:

true iff indices(label) would succeed.

std::span<const std::uint32_t> indices(const SymmetryLabel &label) const

View of the (sorted, unique) indices stored for label.

Parameters:

label – Symmetry label whose index list is requested.

Throws:

std::invalid_argument – if no indices are stored for label.

Returns:

Non-owning span over the stored indices for label.

std::vector<SymmetryLabel> labels() const

The labels for which indices are stored.

Returns:

Vector of every SymmetryLabel keyed in this index set.

inline std::shared_ptr<const SymmetryProduct> symmetries() const

The symmetry definitions this index set is blocked under.

Returns:

Shared pointer to the single-slot SymmetryProduct.

virtual void to_file(const std::string &filename, const std::string &type) const override

Dispatch to JSON or HDF5 serialization based on type.

Parameters:
  • filename – Target file path.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if the underlying I/O operation fails.

virtual void to_hdf5(H5::Group &group) const override

Serialize this index set into an HDF5 group.

Parameters:

group – HDF5 group to write into; receives a version attribute and a string data dataset carrying the JSON payload.

Throws:

std::runtime_error – on HDF5 I/O failure.

virtual void to_hdf5_file(const std::string &filename) const override

Serialize this index set to an HDF5 file.

Parameters:

filename – Path to the HDF5 file to create or overwrite.

Throws:

std::runtime_error – on HDF5 I/O failure.

virtual nlohmann::json to_json() const override

Serialize this index set to JSON.

Returns:

JSON object carrying the serialization version, the per-label extents, and the per-label indices.

virtual void to_json_file(const std::string &filename) const override

Serialize this index set to a JSON file.

Parameters:

filename – Path to the JSON file to create or overwrite.

Throws:

std::runtime_error – if the file cannot be opened for writing.

Public Static Functions

static std::shared_ptr<SymmetryBlockedIndexSet> from_file(const std::string &filename, const std::string &type)

Dispatch to JSON or HDF5 deserialization based on type.

Parameters:
  • filename – Source file path.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if the underlying I/O operation fails or the serialization version is incompatible.

Returns:

Shared pointer to the reconstructed index set.

static std::shared_ptr<SymmetryBlockedIndexSet> from_hdf5(H5::Group &group)

Reconstruct a SymmetryBlockedIndexSet from an HDF5 group produced by to_hdf5.

Validates the version attribute against SERIALIZATION_VERSION before reconstructing.

Parameters:

group – HDF5 group to read from.

Throws:

std::runtime_error – if the version attribute is missing or incompatible, or on HDF5 I/O failure.

Returns:

Shared pointer to the reconstructed index set.

static std::shared_ptr<SymmetryBlockedIndexSet> from_hdf5_file(const std::string &filename)

Reconstruct a SymmetryBlockedIndexSet from an HDF5 file produced by to_hdf5_file.

Parameters:

filename – Path to the HDF5 file to read.

Throws:

std::runtime_error – if the file cannot be opened, or the serialization version is incompatible.

Returns:

Shared pointer to the reconstructed index set.

static std::shared_ptr<SymmetryBlockedIndexSet> from_json(const nlohmann::json &j)

Reconstruct a SymmetryBlockedIndexSet from a JSON object produced by to_json.

Validates the serialization version recorded in j against SERIALIZATION_VERSION before reconstructing.

Parameters:

j – JSON object produced by a prior to_json call.

Throws:

std::runtime_error – if the "version" field is missing or incompatible, or if j is otherwise malformed.

Returns:

Shared pointer to the reconstructed index set.

static std::shared_ptr<SymmetryBlockedIndexSet> from_json_file(const std::string &filename)

Reconstruct a SymmetryBlockedIndexSet from a JSON file produced by to_json_file.

Parameters:

filename – Path to the JSON file to read.

Throws:

std::runtime_error – if the file cannot be opened, parsed, or the serialization version is incompatible.

Returns:

Shared pointer to the reconstructed index set.

template<class Scalar = std::size_t>
class SymmetryBlockedScalar : public qdk::chemistry::data::SymmetryBlocked<1, std::size_t>
#include <qdk/chemistry/data/symmetry/symmetry_blocked_scalar.hpp>

Symmetry-blocked scalar quantity.

A SymmetryBlockedScalar stores one scalar value per symmetry sector of a single-slot (rank-1) partition: a sparse map from a per-slot SymmetryLabel to a scalar Scalar. The slot carries its own SymmetryProduct. A SymmetryBlockedScalar is the scalar analogue of SymmetryBlockedTensor and is used for any symmetry-resolved scalar quantity whose block structure is induced by the single-particle basis.

Example: when the slot carries a spin axis, the stored labels can be the spin labels ( \(\alpha\), \(\beta\)) and the value under each label is that channel’s quantity. When the slot carries no axes (trivial SymmetryProduct), a single block keyed by the trivial label holds the aggregate quantity.

Blocks are held via shared_ptr<const Scalar> so that symmetry-equivalent sectors can alias the same storage when the axis is marked SymmetryAxis::equivalent. Scalar quantities whose sectors are independent should use non-equivalent axes so that no aliasing is applied (for example, open-shell \(\alpha\) and \(\beta\) electron counts).

Template Parameters:

Scalar – The per-block scalar type (defaults to std::size_t for count-like quantities).

Public Types

using BlockMap = std::unordered_map<Labels, BlockPtr, LabelsHash<1>>

Sparse map from a single-slot label tuple to scalar storage.

Aliased sectors map to the same BlockPtr; keys are hashed via LabelsHash.

using BlockPtr = std::shared_ptr<const Scalar>

Shared pointer to immutable per-block scalar storage.

Held as shared_ptr<const Scalar> so that symmetry-equivalent sectors can alias the same storage.

using Labels = std::array<SymmetryLabel, 1>

Single-slot label tuple: one SymmetryLabel.

The key type of BlockMap. Equivalent to the rank-1 Labels of the SymmetryBlocked base.

using SymmetriesArray = std::array<std::shared_ptr<const SymmetryProduct>, 1>

Per-slot symmetry definition.

One SymmetryProduct for the single index slot, supplied at construction.

Public Functions

inline SymmetryBlockedScalar(SymmetriesArray symmetries, BlockMap blocks)

Construct from the per-slot symmetry and a block map.

See the class description for the validation rules.

A scalar block is a single number, so extents are meaningless and are not part of this constructor: the base-class extents (every label present in blocks mapped to 1) are computed automatically.

Parameters:
  • symmetries – Single-slot SymmetryProduct definition.

  • blocks – Scalar storage keyed by the per-slot label.

Throws:

std::invalid_argument – if a block label is not admissible under the slot’s SymmetryProduct, if a block pointer is null, or if restricted orbit partners are supplied with distinct backing storage.

inline virtual std::string get_data_type_name() const override

DataClass type identifier.

Returns:

The stable string "symmetry_blocked_scalar".

inline virtual std::string get_summary() const override

Single-line summary including scalar type and per-block label/value pairs.

Returns:

A short diagnostic string suitable for logging.

inline virtual void to_file(const std::string &filename, const std::string &type) const override

Dispatch to JSON or HDF5 serialization based on type.

Parameters:
  • filename – Target file path.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if the underlying I/O operation fails.

virtual void to_hdf5(H5::Group &group) const override

Serialize this scalar container into an HDF5 group.

Writes the JSON form (see to_json) as a single string dataset within group, mirroring the HDF5 layout used by SymmetryProduct.

Parameters:

group – HDF5 group to write into.

Throws:

std::runtime_error – on HDF5 I/O failure.

virtual void to_hdf5_file(const std::string &filename) const override

Save object to HDF5 file.

Parameters:

filename – Path to the output HDF5 file

Throws:

std::runtime_error – if I/O error occurs

inline virtual nlohmann::json to_json() const override

Serialize this scalar container to JSON.

Returns:

JSON object carrying the serialization version, scalar type, per-slot symmetries and extents, and the per-block payload.

inline virtual void to_json_file(const std::string &filename) const override

Serialize this scalar container to a JSON file.

Parameters:

filename – Path to the JSON file to create or overwrite.

Throws:

std::runtime_error – if the file cannot be opened for writing.

inline Scalar value(const SymmetryLabel &label) const

The scalar value stored for label.

Convenience wrapper around SymmetryBlocked::block for the single-slot case. When the container holds a single block, the trivial (empty) label also resolves to it.

Parameters:

label – The symmetry label identifying the block.

Throws:

std::invalid_argument – if no block exists for label.

Returns:

The stored scalar value.

Public Static Functions

static inline std::shared_ptr<SymmetryBlockedScalar> from_file(const std::string &filename, const std::string &type)

Dispatch to JSON or HDF5 deserialization based on type.

Parameters:
  • filename – Source file path.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if the underlying I/O operation fails or the serialization version is incompatible.

Returns:

Shared pointer to the reconstructed scalar container.

static std::shared_ptr<SymmetryBlockedScalar> from_hdf5(H5::Group &group)

Reconstruct from an HDF5 group produced by to_hdf5.

Validates the "version" field in the HDF5 metadata payload against SERIALIZATION_VERSION before reconstructing.

Parameters:

group – HDF5 group to read from.

Throws:
  • std::runtime_error – if the metadata dataset or its "version" field is missing or the version is incompatible, or on HDF5 I/O failure.

  • std::invalid_argument – if the encoded scalar type does not match the requested instantiation.

Returns:

Shared pointer to the reconstructed scalar container.

static std::shared_ptr<SymmetryBlockedScalar> from_hdf5_file(const std::string &filename)
static std::shared_ptr<SymmetryBlockedScalar> from_json(const nlohmann::json &j)

Reconstruct from a JSON object produced by to_json.

Validates the serialization version recorded in j against SERIALIZATION_VERSION before reconstructing. Any "extents" field is accepted but ignored: scalar extents are always 1 and are recomputed from the blocks.

Parameters:

j – JSON object produced by a prior to_json call.

Throws:
  • std::runtime_error – if j is missing the "version" field or its version is incompatible with SERIALIZATION_VERSION.

  • nlohmann::json::exception – if j is otherwise malformed.

Returns:

Shared pointer to the reconstructed scalar container.

static inline std::shared_ptr<SymmetryBlockedScalar> from_json_file(const std::string &filename)

Reconstruct a SymmetryBlockedScalar from a JSON file produced by to_json_file.

Parameters:

filename – Path to the JSON file to read.

Throws:

std::runtime_error – if the file cannot be opened, parsed, or carries an incompatible serialization version.

Returns:

Shared pointer to the reconstructed scalar container.

template<std::size_t Rank, class Scalar = double>
class SymmetryBlockedSparseMap : public qdk::chemistry::data::SymmetryBlocked<Rank, SparseMapBlock<Rank, double>>
#include <qdk/chemistry/data/symmetry/symmetry_blocked_sparse_map.hpp>

Symmetry-blocked sparse map.

A SymmetryBlockedSparseMap stores the non-zero symmetry sectors of a rank-Rank sparse index-value map. Each block is a SparseMapBlock — a sorted map from per-slot local-index tuples to scalar values. The block map, SymmetryProduct instances, and orbit aliasing are inherited from SymmetryBlocked.

Template Parameters:
  • Rank – Number of label slots (typically 4 for two-body integrals).

  • Scalar – Element type (double).

Public Types

using BlockMap = std::unordered_map<Labels, BlockPtr, LabelsHash<Rank>>

Sparse map from per-slot label tuples to block storage.

Aliased sectors (e.g. restricted-spin partners) map to the same BlockPtr. Keys are hashed via LabelsHash.

using BlockPtr = std::shared_ptr<const SparseMapBlock<Rank, Scalar>>

Shared pointer to immutable per-block sparse storage.

Equivalent to the base SymmetryBlocked BlockPtr with the block type resolved to SparseMapBlock. Held as shared_ptr<const SparseMapBlock> so that symmetry-equivalent sectors can alias the same storage.

using ExtentsArray = std::array<std::unordered_map<SymmetryLabel, std::size_t>, Rank>

Per-slot per-label extents.

For each index slot, maps every admissible SymmetryLabel to the universe size (number of basis vectors) carried under that label.

using IndexTuple = std::array<unsigned, Rank>

Per-slot local-index tuple keying a single sparse entry within one block.

using Labels = std::array<SymmetryLabel, Rank>

Per-slot block label tuple: one SymmetryLabel per index slot.

Used as the key type of BlockMap so that blocks are addressed by the full tuple of per-slot symmetry labels.

using SparseBlock = SparseMapBlock<Rank, Scalar>

Per-block sparse storage: a sorted map from per-slot local-index tuples to scalar values.

using SymmetriesArray = std::array<std::shared_ptr<const SymmetryProduct>, Rank>

Per-slot symmetry definitions.

One SymmetryProduct per index slot; supplied at construction and used to validate block labels and apply orbit aliasing.

Public Functions

inline SymmetryBlockedSparseMap(SymmetriesArray symmetries, ExtentsArray extents, BlockMap blocks)

Construct from per-slot symmetries, per-slot extents, and a block map of sparse blocks.

Parameters:
  • symmetries – Per-slot SymmetryProduct definitions.

  • extents – Per-slot per-label universe sizes.

  • blocks – Block storage keyed by per-slot label tuples; entries of each block carry per-slot local indices.

Throws:

std::invalid_argument – if a label is not admissible, if restricted orbit partners have unequal extents, if a sparse entry index exceeds the extent, or if orbit partners do not share storage.

inline Scalar get(const Labels &labels, const IndexTuple &idx) const

Look up a single entry by labels and index tuple.

Parameters:
  • labels – Per-slot symmetry label tuple identifying the block.

  • idx – Per-slot local index tuple within the block.

Returns:

The stored value if present, or Scalar{} (zero) otherwise.

inline virtual std::string get_data_type_name() const override

DataClass type identifier.

Returns:

The stable string "symmetry_blocked_sparse_map".

inline virtual std::string get_summary() const override

Single-line summary including rank, number of stored blocks, and total number of non-zero entries.

Returns:

A short diagnostic string suitable for logging.

inline std::size_t num_entries() const

Total number of stored (non-zero) entries across all blocks.

Returns:

Sum of the sparse-entry counts of every stored block.

inline virtual void to_file(const std::string &filename, const std::string &type) const override

Dispatch to JSON or HDF5 serialization based on type.

Parameters:
  • filename – Target file path.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if the underlying I/O operation fails.

virtual void to_hdf5(H5::Group &group) const override

Serialize this sparse map into an HDF5 group.

Writes the JSON form (see to_json) as a single string dataset within group, mirroring the HDF5 layout used by SymmetryBlockedScalar.

Parameters:

group – HDF5 group to write into.

Throws:

std::runtime_error – on HDF5 I/O failure.

virtual void to_hdf5_file(const std::string &filename) const override

Serialize this sparse map to an HDF5 file.

Parameters:

filename – Path to the HDF5 file to create or overwrite.

Throws:

std::runtime_error – on HDF5 I/O failure.

inline virtual nlohmann::json to_json() const override

Serialize this sparse map to JSON.

One entry per group of pointer-equivalent blocks; each entry lists the canonical key, the aliased keys, and the sparse-entry payload as [idx0, idx1, …, value] tuples.

Returns:

JSON object carrying rank, scalar type, per-slot symmetries and extents, and the sparse-entry payload.

inline virtual void to_json_file(const std::string &filename) const override

Serialize this sparse map to a JSON file.

Parameters:

filename – Path to the JSON file to create or overwrite.

Throws:

std::runtime_error – if the file cannot be opened for writing.

Public Static Functions

static inline std::shared_ptr<SymmetryBlockedSparseMap> from_file(const std::string &filename, const std::string &type)

Dispatch to JSON or HDF5 deserialization based on type.

Parameters:
  • filename – Source file path.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if the underlying I/O operation fails or the serialization version is incompatible.

Returns:

Shared pointer to the reconstructed sparse map.

static std::shared_ptr<SymmetryBlockedSparseMap> from_hdf5(H5::Group &group)

Reconstruct from an HDF5 group produced by to_hdf5.

Parameters:

group – HDF5 group to read from.

Throws:

std::runtime_error – if the metadata dataset or its "version" field is missing or the version is incompatible, or on HDF5 I/O failure.

Returns:

Shared pointer to the reconstructed sparse map.

static std::shared_ptr<SymmetryBlockedSparseMap> from_hdf5_file(const std::string &filename)

Reconstruct from an HDF5 file produced by to_hdf5_file.

Parameters:

filename – Path to the HDF5 file to read.

Throws:

std::runtime_error – if the file cannot be opened or carries an incompatible serialization version.

Returns:

Shared pointer to the reconstructed sparse map.

static std::shared_ptr<SymmetryBlockedSparseMap> from_json(const nlohmann::json &j)

Reconstruct a SymmetryBlockedSparseMap from a JSON object produced by to_json.

Validates the serialization version recorded in j against SERIALIZATION_VERSION before reconstructing.

Parameters:

j – JSON object produced by a prior to_json call.

Throws:
  • std::runtime_error – if j is missing the "version" field or its version is incompatible with SERIALIZATION_VERSION.

  • std::invalid_argument – if a block label is not admissible or a sparse entry index exceeds the declared extent.

  • nlohmann::json::exception – if j is otherwise malformed.

Returns:

Shared pointer to the reconstructed sparse map.

static std::shared_ptr<SymmetryBlockedSparseMap> from_json_file(const std::string &filename)

Reconstruct a SymmetryBlockedSparseMap from a JSON file produced by to_json_file.

Parameters:

filename – Path to the JSON file to read.

Throws:

std::runtime_error – if the file cannot be opened, parsed, or carries an incompatible serialization version.

Returns:

Shared pointer to the reconstructed sparse map.

template<std::size_t Rank, class Scalar = double>
class SymmetryBlockedTensor : public qdk::chemistry::data::SymmetryBlocked<Rank, Tensor<Rank, double>>
#include <qdk/chemistry/data/symmetry/symmetry_blocked_tensor.hpp>

Symmetry-blocked dense tensor.

A SymmetryBlockedTensor stores the non-zero symmetry sectors of a rank-Rank tensor as a sparse map from per-slot SymmetryLabel arrays to dense Eigen blocks. Each slot carries its own SymmetryProduct and a per-label extent. Blocks are held via shared_ptr<const Tensor> so that symmetry-equivalent sectors can alias the same storage.

Symmetry aliasing is defined on the spin axis: a simultaneous \(\alpha \leftrightarrow \beta\) swap across all slots. When every slot shares the same SymmetryProduct instance and the spin axis is marked equivalent, the constructor auto-aliases each partner block to the supplied representative. When the slots carry distinct SymmetryProduct (intertwiner storage such as basis coefficients), no auto-aliasing is performed.

The full block map is supplied at construction.

Template Parameters:
  • Rank – Tensor rank (1, 2, 3, or 4 are instantiated).

  • Scalar – Element type (double or std::complex<double>).

Public Types

using BlockMap = std::unordered_map<Labels, BlockPtr, LabelsHash<Rank>>

Sparse map from per-slot label tuples to block storage.

Aliased sectors (e.g. restricted-spin partners) map to the same BlockPtr. Keys are hashed via LabelsHash.

using BlockPtr = std::shared_ptr<const Tensor<Rank, Scalar>>

Shared pointer to immutable per-block dense storage.

Equivalent to the base SymmetryBlocked BlockPtr with the block type resolved to Tensor. Held as shared_ptr<const Tensor> so that symmetry-equivalent sectors can alias the same storage.

using ExtentsArray = std::array<std::unordered_map<SymmetryLabel, std::size_t>, Rank>

Per-slot per-label extents.

For each index slot, maps every admissible SymmetryLabel to the universe size (number of basis vectors) carried under that label.

using Labels = std::array<SymmetryLabel, Rank>

Per-slot block label tuple: one SymmetryLabel per index slot.

Used as the key type of BlockMap so that blocks are addressed by the full tuple of per-slot symmetry labels.

using SymmetriesArray = std::array<std::shared_ptr<const SymmetryProduct>, Rank>

Per-slot symmetry definitions.

One SymmetryProduct per index slot; supplied at construction and used to validate block labels and apply orbit aliasing.

Public Functions

inline SymmetryBlockedTensor(SymmetriesArray symmetries, ExtentsArray extents, BlockMap blocks)

Construct from per-slot symmetries, per-slot extents, and a block map.

See the class description for the validation rules.

Parameters:
  • symmetries – Per-slot SymmetryProduct definitions.

  • extents – Per-slot per-label universe sizes.

  • blocks – Block storage keyed by per-slot label tuples; block shapes must match the declared extents per slot.

Throws:

std::invalid_argument – if a block or extent label is not admissible under the matching slot’s SymmetryProduct, if a block’s shape does not match the declared extents, if restricted orbit partners have unequal extents, or if both orbit partners are supplied but do not share storage.

inline virtual std::string get_data_type_name() const override

DataClass type identifier.

Returns:

The stable string "symmetry_blocked_tensor".

inline virtual std::string get_summary() const override

Single-line summary including rank, scalar type, number of stored blocks, and number of independent (non-aliased) blocks.

Returns:

A short diagnostic string suitable for logging.

inline virtual void to_file(const std::string &filename, const std::string &type) const override

Dispatch to JSON or HDF5 serialization based on type.

Parameters:
  • filename – Target file path.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if the underlying I/O operation fails.

virtual void to_hdf5(H5::Group &group) const override

Serialize this tensor into an HDF5 group.

Writes one numeric dataset per independent block plus a JSON metadata payload (carrying the serialization version, per-slot symmetries and extents, and the block keys).

Parameters:

group – HDF5 group to write into.

Throws:

std::runtime_error – on HDF5 I/O failure.

virtual void to_hdf5_file(const std::string &filename) const override

Serialize this tensor to an HDF5 file.

Parameters:

filename – Path to the HDF5 file to create or overwrite.

Throws:

std::runtime_error – on HDF5 I/O failure.

inline virtual nlohmann::json to_json() const override

Serialize this tensor to JSON, with one entry per group of pointer-equivalent blocks (a canonical key, the aliased keys, and the block payload).

Returns:

JSON object carrying the serialization version, rank, scalar type, per-slot symmetries and extents, and the per-block payload.

inline virtual void to_json_file(const std::string &filename) const override

Serialize this tensor to a JSON file.

Parameters:

filename – Path to the JSON file to create or overwrite.

Throws:

std::runtime_error – if the file cannot be opened for writing.

Public Static Functions

static inline std::shared_ptr<SymmetryBlockedTensor> from_file(const std::string &filename, const std::string &type)

Dispatch to JSON or HDF5 deserialization based on type.

Parameters:
  • filename – Source file path.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if the underlying I/O operation fails or the serialization version is incompatible.

Returns:

Shared pointer to the reconstructed tensor.

static std::shared_ptr<SymmetryBlockedTensor> from_hdf5(H5::Group &group)

Reconstruct from an HDF5 group produced by to_hdf5.

Validates the "version" field in the HDF5 metadata payload against SERIALIZATION_VERSION before reconstructing.

Parameters:

group – HDF5 group to read from.

Throws:
  • std::runtime_error – if the metadata dataset or its "version" field is missing or the version is incompatible, or on HDF5 I/O failure.

  • std::invalid_argument – if the encoded rank or scalar type does not match the requested instantiation.

Returns:

Shared pointer to the reconstructed tensor.

static std::shared_ptr<SymmetryBlockedTensor> from_hdf5_file(const std::string &filename)

Reconstruct from an HDF5 file produced by to_hdf5_file.

Parameters:

filename – Path to the HDF5 file to read.

Throws:

std::runtime_error – if the file cannot be opened or carries an incompatible serialization version.

Returns:

Shared pointer to the reconstructed tensor.

static std::shared_ptr<SymmetryBlockedTensor> from_json(const nlohmann::json &j)

Reconstruct from a JSON object produced by to_json.

Validates the serialization version recorded in j against SERIALIZATION_VERSION before reconstructing.

Parameters:

j – JSON object produced by a prior to_json call.

Throws:
  • std::runtime_error – if j is missing the "version" field or its version is incompatible with SERIALIZATION_VERSION.

  • nlohmann::json::exception – if j is otherwise malformed.

Returns:

Shared pointer to the reconstructed tensor.

static inline std::shared_ptr<SymmetryBlockedTensor> from_json_file(const std::string &filename)

Reconstruct a SymmetryBlockedTensor from a JSON file produced by to_json_file.

Parameters:

filename – Path to the JSON file to read.

Throws:

std::runtime_error – if the file cannot be opened, parsed, or carries an incompatible serialization version.

Returns:

Shared pointer to the reconstructed tensor.

class SymmetryLabel
#include <qdk/chemistry/data/symmetry/symmetry.hpp>

A composite addressing key: one SymmetryAxisValue per axis.

Used to address a single block of a SymmetryBlockedTensor or a single label set of a SymmetryBlockedIndexSet. The hash is precomputed at construction so the label can be used as an unordered-map key cheaply.

Public Functions

inline SymmetryLabel()

Construct a trivial (empty) label with no axis values.

SymmetryLabel(std::initializer_list<std::shared_ptr<const SymmetryAxisValue>> values)

Construct from a brace-enclosed list of axis values.

Convenience overload for the common interned-shared-ptr pattern:

SymmetryLabel alpha({axes::alpha()});

Parameters:

values – Axis values carried by this label; each axis name must appear at most once.

template<std::derived_from<SymmetryAxisValue> Derived>
inline SymmetryLabel(std::shared_ptr<const Derived> value)

Construct from a single axis value (implicit conversion).

Lets call sites write block({axes::alpha(), axes::beta()}) without naming SymmetryLabel explicitly — each axis-value shared pointer is wrapped into a label carrying just that one value. Accepts a shared pointer to any SymmetryAxisValue subclass (e.g. SpinValue).

Template Parameters:

Derived – Any SymmetryAxisValue subclass.

Parameters:

value – Axis value carried by this label.

explicit SymmetryLabel(std::vector<std::shared_ptr<const SymmetryAxisValue>> values)

Construct from an explicit vector of axis values.

Parameters:

values – Axis values carried by this label; each axis name must appear at most once.

inline bool empty() const

True iff this label carries no axis values (trivial label).

Returns:

true iff values() is empty.

std::shared_ptr<const SymmetryAxisValue> get(AxisName axis) const

The value carried for axis axis.

Parameters:

axis – Axis identifier to look up.

Throws:

std::runtime_error – if the label carries no value for axis.

Returns:

Shared pointer to the value carried for axis.

bool has(AxisName axis) const

True iff this label carries a value for axis.

Parameters:

axis – Axis identifier to look up.

Returns:

true if get(axis) would succeed.

inline std::size_t hash() const

Hash consistent with operator==.

Precomputed in the constructor so the label can be used as an unordered_map key without recomputing the hash on each lookup.

Returns:

Cached hash value of this label.

inline bool operator!=(const SymmetryLabel &other) const

Negation of operator==.

Parameters:

other – Label to compare against.

Returns:

true iff other differs from *this on any axis.

bool operator==(const SymmetryLabel &other) const

Value-equality (same axes carrying equal-valued axis values).

Parameters:

other – Label to compare against.

Returns:

true iff other carries the same set of axes and each per-axis value compares equal via SymmetryAxisValue::equals.

nlohmann::json to_json() const

Serialize this label to JSON.

Returns:

JSON object enumerating each per-axis value (with its polymorphic "kind" tag).

inline const std::map<AxisName, std::shared_ptr<const SymmetryAxisValue>> &values() const

The axes addressed by this label.

Returns:

Reference to the underlying ordered map from axis name to value.

Public Static Functions

static SymmetryLabel from_json(const nlohmann::json &j)

Reconstruct a SymmetryLabel from JSON produced by to_json.

Parameters:

j – JSON object produced by a prior to_json call.

Throws:

std::runtime_error – if j is malformed or names an unknown axis kind.

Returns:

The deserialized label.

class SymmetryProduct : public qdk::chemistry::data::DataClass
#include <qdk/chemistry/data/symmetry/symmetry.hpp>

The ordered set of symmetry axes a tensor is blocked under, together with their admissible labels and equivalence flags.

Public Functions

explicit SymmetryProduct(std::vector<SymmetryAxis> axes)

Construct from an ordered list of symmetry axes.

Parameters:

axes – The axes this symmetry set is composed of. The order is preserved and observable via axes(); axis names must be unique.

const std::vector<SymmetryAxis> &axes() const

The ordered list of axes carried by this symmetry set.

Returns:

Reference to the axes supplied at construction.

const SymmetryAxis &axis(AxisName name) const

Access the axis with name name.

Parameters:

name – Axis name to look up.

Throws:

std::runtime_error – if no such axis exists in this set.

Returns:

Reference to the matching SymmetryAxis.

inline virtual std::string get_data_type_name() const override

DataClass type identifier.

Returns:

The string "symmetries".

virtual std::string get_summary() const override

Single-line human-readable summary.

Returns:

A string of the form SymmetryProduct(axes=N; [name0, name1, ...]).

bool has_axis(AxisName name) const

Look up whether an axis with the given name exists.

Parameters:

name – Axis name to look for.

Returns:

true if an axis with name name exists in this set.

std::size_t hash() const

Hash consistent with operator==.

Returns:

Hash value suitable for use with std::hash.

inline bool operator!=(const SymmetryProduct &other) const

Inverse of operator==.

Parameters:

other – Right-hand symmetry set to compare against.

Returns:

true if the axis sequences differ.

bool operator==(const SymmetryProduct &other) const

Value-equality against another symmetry set.

Parameters:

other – Right-hand symmetry set to compare against.

Returns:

true if both sets contain the same axes in the same order.

virtual void to_file(const std::string &filename, const std::string &type) const override

Dispatch to JSON or HDF5 serialization based on type.

Parameters:
  • filename – Path to the output file.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if an I/O error occurs.

virtual void to_hdf5(H5::Group &group) const override

Serialize this symmetry set into an HDF5 group.

The implementation writes the JSON form (see to_json) as a single string dataset within group, mirroring the HDF5 layout used by SymmetryBlockedIndexSet.

Parameters:

group – HDF5 group to write data to.

Throws:

std::runtime_error – if an HDF5 I/O error occurs.

virtual void to_hdf5_file(const std::string &filename) const override

Serialize this symmetry set to an HDF5 file.

Parameters:

filename – Path to the output HDF5 file (created or truncated).

Throws:

std::runtime_error – if an HDF5 I/O error occurs.

virtual nlohmann::json to_json() const override

Serialize this symmetry set to JSON.

Returns:

JSON object with an "axes" array; each entry is the SymmetryAxis::to_json output of the corresponding axis.

virtual void to_json_file(const std::string &filename) const override

Serialize this symmetry set to a JSON file.

Parameters:

filename – Path to the output JSON file.

Throws:

std::runtime_error – if filename cannot be opened for writing.

Public Static Functions

static std::shared_ptr<SymmetryProduct> from_file(const std::string &filename, const std::string &type)

Dispatch to JSON or HDF5 deserialization based on type.

Parameters:
  • filename – Path to the input file.

  • type – Either "json" or "hdf5".

Throws:
  • std::invalid_argument – if type is not "json" or "hdf5".

  • std::runtime_error – if filename cannot be read or its contents are malformed.

Returns:

Shared pointer to the deserialized SymmetryProduct.

static std::shared_ptr<SymmetryProduct> from_hdf5(H5::Group &group)

Load a SymmetryProduct from an HDF5 group produced by to_hdf5.

Parameters:

group – HDF5 group to read data from.

Throws:

std::runtime_error – if the expected dataset is missing or the payload is malformed.

Returns:

Shared pointer to the deserialized SymmetryProduct.

static std::shared_ptr<SymmetryProduct> from_hdf5_file(const std::string &filename)

Load a SymmetryProduct from an HDF5 file produced by to_hdf5_file.

Parameters:

filename – Path to the input HDF5 file.

Throws:

std::runtime_error – if filename cannot be read or its contents are malformed.

Returns:

Shared pointer to the deserialized SymmetryProduct.

static std::shared_ptr<SymmetryProduct> from_json(const nlohmann::json &j)

Reconstruct a SymmetryProduct from JSON produced by to_json.

Parameters:

j – JSON object containing symmetry-set data.

Throws:

std::runtime_error – if j is missing required fields or an embedded axis is malformed.

Returns:

Shared pointer to the deserialized SymmetryProduct.

static std::shared_ptr<SymmetryProduct> from_json_file(const std::string &filename)

Load a SymmetryProduct from a JSON file produced by to_json_file.

Parameters:

filename – Path to the input JSON file.

Throws:

std::runtime_error – if filename cannot be read or its contents are malformed.

Returns:

Shared pointer to the deserialized SymmetryProduct.

static inline SymmetryProduct trivial()

Construct a trivial symmetry set with no axes.

Returns:

An empty SymmetryProduct instance.

class TaperingSpecification : public qdk::chemistry::data::DataClass
#include <qdk/chemistry/data/tapering.hpp>

Specification for post-mapping qubit tapering.

Records which qubits to remove after a fermion-to-qubit mapping and the symmetry eigenvalue (+1 or −1) to substitute for each. Used by MajoranaMapping to carry tapering metadata through the mapping pipeline.

Public Functions

TaperingSpecification(std::vector<std::size_t> qubit_indices, std::vector<int> eigenvalues)

Construct a tapering specification.

Parameters:
  • qubit_indices – Indices of qubits to taper (remove).

  • eigenvalues – Symmetry eigenvalue (+1 or −1) for each qubit.

Throws:

std::invalid_argument – If sizes differ, indices contain duplicates, or any eigenvalue is not +1 or −1.

inline const std::vector<int> &eigenvalues() const

Symmetry eigenvalue (+1 or −1) for each tapered qubit.

inline virtual std::string get_data_type_name() const override

Get the data type name for serialization.

virtual std::string get_summary() const override

Get a human-readable summary of the tapering specification.

inline std::size_t num_tapered() const

Number of qubits removed by tapering.

bool operator==(const TaperingSpecification &other) const

Value equality (compares qubit indices and eigenvalues).

inline const std::vector<std::size_t> &qubit_indices() const

Indices of qubits to taper (remove).

virtual void to_file(const std::string &filename, const std::string &type) const override

Save to file in the specified format.

Parameters:
  • filename – Path to the output file.

  • type – Format type (“json”, “hdf5”, or “h5”).

virtual void to_hdf5(H5::Group &group) const override

Save to an HDF5 group.

virtual void to_hdf5_file(const std::string &filename) const override

Save to an HDF5 file.

virtual nlohmann::json to_json() const override

Serialize to JSON.

virtual void to_json_file(const std::string &filename) const override

Save to a JSON file.

Public Static Functions

static TaperingSpecification from_file(const std::string &filename, const std::string &type)

Load from file in the specified format.

Parameters:
  • filename – Path to the input file.

  • type – Format type (“json”, “hdf5”, or “h5”).

static TaperingSpecification from_hdf5(H5::Group &group)

Load from an HDF5 group.

static TaperingSpecification from_hdf5_file(const std::string &filename)

Load from an HDF5 file.

static TaperingSpecification from_json(const nlohmann::json &data)

Deserialize from JSON.

static TaperingSpecification from_json_file(const std::string &filename)

Load from a JSON file.

static TaperingSpecification parity_two_qubit_reduction(std::size_t num_modes, std::size_t n_alpha, std::size_t n_beta)

Tapering for the parity encoding with two-qubit reduction.

Removes the same two symmetry qubits as symmetry_conserving_bravyi_kitaev().

Parameters:
  • num_modes – Total number of spin-orbitals (must be even, ≥ 4).

  • n_alpha – Number of alpha electrons.

  • n_beta – Number of beta electrons.

Throws:

std::invalid_argument – If num_modes is odd, < 4, or electron counts exceed spatial orbitals.

static TaperingSpecification symmetry_conserving_bravyi_kitaev(std::size_t num_modes, std::size_t n_alpha, std::size_t n_beta)

Tapering for the symmetry-conserving Bravyi-Kitaev encoding.

Removes the two qubits that encode the alpha and total particle-number parities in a balanced binary-tree (BK-tree) mapping.

Parameters:
  • num_modes – Total number of spin-orbitals (must be even, ≥ 4).

  • n_alpha – Number of alpha electrons.

  • n_beta – Number of beta electrons.

Throws:

std::invalid_argument – If num_modes is odd, < 4, or electron counts exceed spatial orbitals.

class Wavefunction : public qdk::chemistry::data::DataClass, public std::enable_shared_from_this<Wavefunction>
#include <qdk/chemistry/data/wavefunction.hpp>

Main wavefunction class that wraps container implementations.

This class provides a high-level interface to wavefunction data by delegating to specific container implementations. It combines orbital information with wavefunction coefficients and provides convenient access to all wavefunction properties. All methods redirect to the underlying container.

Public Types

using DeterminantVector = ContainerTypes::DeterminantVector
using MatrixVariant = ContainerTypes::MatrixVariant
using ScalarVariant = ContainerTypes::ScalarVariant
using VectorVariant = ContainerTypes::VectorVariant

Public Functions

Wavefunction(const Wavefunction &other)

Copy constructor.

Wavefunction(std::unique_ptr<WavefunctionContainer> container)

Construct wavefunction with container (orbitals are stored in container).

Parameters:

containerWavefunction container implementation.

Wavefunction(Wavefunction &&other) noexcept = default

Move constructor.

~Wavefunction() = default
std::shared_ptr<const SymmetryBlockedScalar<std::size_t>> active_num_particles() const

Number of active-space particles as a symmetry-blocked scalar.

Forwards to the underlying container’s WavefunctionContainer::active_num_particles.

Returns:

Shared pointer to the symmetry-blocked active particle count.

const SymmetryBlockedTensorVariant<2> &active_one_rdm() const

Active-space 1-RDM as a rank-2 symmetry-blocked tensor variant (real or complex).

Forwards to the underlying container’s WavefunctionContainer::active_one_rdm.

Throws:

std::runtime_error – if the 1-RDM is not available.

Returns:

Const reference to the 1-RDM symmetry-blocked tensor variant.

MatrixVariant active_one_rdm_block(const SymmetryLabel &row, const SymmetryLabel &col) const

Active-space 1-RDM block for the given row/column symmetry labels.

Forwards to the underlying container’s WavefunctionContainer::active_one_rdm_block.

Parameters:
  • row – Row-slot symmetry label.

  • col – Column-slot symmetry label.

Throws:
  • std::runtime_error – if the 1-RDM is not available.

  • std::invalid_argument – if no block is stored for the requested label pair.

Returns:

MatrixVariant holding the requested block.

std::shared_ptr<const SymmetryBlockedTensor<1>> active_orbital_occupations() const

Orbital occupations for active orbitals as a rank-1 symmetry-blocked tensor.

Forwards to the underlying container’s WavefunctionContainer::active_orbital_occupations.

Returns:

Shared pointer to the symmetry-blocked active orbital occupations.

const SymmetryBlockedTensorVariant<4> &active_two_rdm() const

Active-space 2-RDM as a rank-4 symmetry-blocked tensor variant (real or complex).

Forwards to the underlying container’s WavefunctionContainer::active_two_rdm.

Throws:

std::runtime_error – if the 2-RDM is not available.

Returns:

Const reference to the 2-RDM symmetry-blocked tensor variant.

VectorVariant active_two_rdm_block(const SymmetryLabel &p, const SymmetryLabel &q, const SymmetryLabel &r, const SymmetryLabel &s) const

Active-space 2-RDM block for the given symmetry labels.

Forwards to the underlying container’s WavefunctionContainer::active_two_rdm_block.

Parameters:
  • p – First slot’s symmetry label.

  • q – Second slot’s symmetry label.

  • r – Third slot’s symmetry label.

  • s – Fourth slot’s symmetry label.

Throws:
  • std::runtime_error – if the 2-RDM is not available.

  • std::invalid_argument – if no block is stored for the requested label tuple.

Returns:

VectorVariant holding the requested block.

Configuration get_active_determinant(const Configuration &total_determinant) const

Extract active space determinant from a full orbital space determinant.

Removes inactive and virtual orbital information, keeping only the active space orbitals.

Parameters:

total_determinantConfiguration representing full orbital space

Returns:

Configuration representing only the active space portion

const DeterminantVector &get_active_determinants() const

Get all determinants in the wavefunction.

Returns:

Vector of all configurations/determinants

virtual std::pair<size_t, size_t> get_active_num_electrons() const

Get number of active alpha and beta electrons.

Spin-resolved view of active_num_particles.

Throws:

std::runtime_error – if the single-particle basis carries no spin ( \(S_z\)) axis; use active_num_particles instead.

Returns:

Pair of (n_alpha_active, n_beta_active) electrons

std::tuple<MatrixVariant, MatrixVariant> get_active_one_rdm_spin_dependent() const

Get spin-dependent one-particle RDMs.

Returns:

Tuple of (alpha-alpha, beta-beta) one-particle RDMs

const MatrixVariant &get_active_one_rdm_spin_traced() const

Get spin-traced one-particle RDM.

Returns:

Spin-traced one-particle RDM

std::pair<Eigen::VectorXd, Eigen::VectorXd> get_active_orbital_occupations() const

Get orbital occupations for active orbitals only.

Spin-resolved view of active_orbital_occupations.

Throws:

std::runtime_error – if occupations are not available, or if the single-particle basis carries no spin ( \(S_z\)) axis; use active_orbital_occupations instead.

Returns:

Pair of (alpha_active_occupations, beta_active_occupations)

std::tuple<VectorVariant, VectorVariant, VectorVariant> get_active_two_rdm_spin_dependent() const

Get spin-dependent two-particle RDMs.

Returns:

Tuple of (aaaa, aabb, bbbb) two-particle RDMs

const VectorVariant &get_active_two_rdm_spin_traced() const

Get spin-traced two-particle RDM.

Returns:

Spin-traced two-particle RDM

ScalarVariant get_coefficient(const Configuration &det) const

Get coefficient for a specific determinant.

The configuration is expected to be a determinant describing only the wavefunction’s active space.

Parameters:

det – Configuration/determinant to get coefficient for

Returns:

Scalar coefficient (real or complex)

const VectorVariant &get_coefficients() const

Get coefficients for all determinants as a vector, in which the sequence of coefficients is consistent with the vector from get_active_determinants()

Returns:

Vector of coefficients (real or complex)

template<typename T>
inline const T &get_container() const

Get typed reference to the underlying container.

Template Parameters:

T – Container type to cast to

Throws:

std::bad_cast – if container is not of type T

Returns:

Reference to container as type T

virtual std::string get_container_type() const

Get the type of the underlying container.

Returns:

String identifying the container type (e.g., “state_vector”, “coupled_cluster”, “mp2”)

inline virtual std::string get_data_type_name() const override

Get the data type name for this class.

Returns:

“wavefunction”

virtual Eigen::MatrixXd get_mutual_information() const

Get the mutual information matrix for active orbitals.

Throws:

std::runtime_error – if mutual information is not available

Returns:

Matrix of mutual information values for active orbitals

virtual std::shared_ptr<Orbitals> get_orbitals() const

Get reference to orbital basis set.

Returns:

Shared pointer to orbitals

virtual Eigen::VectorXd get_single_orbital_entropies() const

Calculate single orbital entropies for active orbitals only.

Returns:

Vector of orbital entropies for active orbitals (always real)

virtual std::string get_summary() const override

Get a summary string.

Returns:

String containing summary

std::pair<DeterminantVector, VectorVariant> get_top_determinants(std::optional<size_t> max_determinants = std::nullopt) const

Get top N determinants ranked by absolute CI coefficient.

Parameters:

max_determinants – Maximum number of determinants to return. If nullopt, returns all determinants.

Returns:

Pair of (configurations, coefficients) where configurations is a vector of Configuration objects and coefficients is a VectorVariant (Eigen::VectorXd or Eigen::VectorXcd), both sorted by descending absolute coefficient value.

Configuration get_total_determinant(const Configuration &active_determinant) const

Convert active space determinant to full orbital space determinant.

Expands active-space-only determinant to full orbital space by prepending doubly occupied inactive orbitals and appending unoccupied virtual orbitals.

Parameters:

active_determinantConfiguration representing only active space

Returns:

Configuration representing full orbital space

DeterminantVector get_total_determinants() const

Get all determinants in the wavefunction with full orbital space.

Converts stored active-space-only determinants to full orbital space by prepending doubly occupied inactive orbitals and appending unoccupied virtual orbitals.

Returns:

Vector of all configurations/determinants including inactive and virtual orbitals

virtual std::pair<size_t, size_t> get_total_num_electrons() const

Get total number of alpha and beta electrons (active + inactive)

Spin-resolved view of total_num_particles.

Throws:

std::runtime_error – if the single-particle basis carries no spin ( \(S_z\)) axis; use total_num_particles instead.

Returns:

Pair of (n_alpha_total, n_beta_total) electrons

std::pair<Eigen::VectorXd, Eigen::VectorXd> get_total_orbital_occupations() const

Get orbital occupations for all orbitals (total = active + inactive.

  • virtual)

Spin-resolved view of total_orbital_occupations.

Throws:

std::runtime_error – if occupations are not available, or if the single-particle basis carries no spin ( \(S_z\)) axis; use total_orbital_occupations instead.

Returns:

Pair of (alpha_occupations_total, beta_occupations_total)

virtual Eigen::MatrixXd get_two_orbital_entropies() const

Get the two-orbital entropy matrix for active orbitals.

Throws:

std::runtime_error – if two-orbital entropies are not available

Returns:

Matrix of two-orbital entropies for active orbitals

WavefunctionType get_type() const

Get the wavefunction type (SelfDual or NotSelfDual)

Returns:

WavefunctionType enum value

bool has_active_one_rdm() const

True if the active-space 1-RDM symmetry-blocked tensor is available (real or complex).

Returns:

true iff active_one_rdm would succeed without throwing.

bool has_active_two_rdm() const

True if the active-space 2-RDM symmetry-blocked tensor is available (real or complex).

Returns:

true iff active_two_rdm would succeed without throwing.

template<typename T>
inline bool has_container_type() const

Check if container is of specific type.

Template Parameters:

T – Container type to check

Returns:

True if container is of type T

virtual bool has_mutual_information() const

Checks if mutual information for active orbitals is available.

Returns:

True if mutual information matrix is available, false otherwise

bool has_one_rdm_spin_dependent() const

Check if spin-dependent one-particle RDMs are available.

Returns:

True if available

bool has_one_rdm_spin_traced() const

Check if spin-traced one-particle RDM is available.

Returns:

True if available

bool has_sector(const std::string &name) const

Whether a sector with the given name is present.

Parameters:

name – Sector name to look up.

Returns:

true iff the container binds a basis under name.

virtual bool has_single_orbital_entropies() const

Checks if single-orbital entropies for active orbitals are available.

Returns:

True if single-orbital entropies are available, false otherwise

virtual bool has_two_orbital_entropies() const

Checks if two-orbital entropies for active orbitals are available.

Returns:

True if two-orbital entropies are available, false otherwise

bool has_two_rdm_spin_dependent() const

Check if spin-dependent two-particle RDMs are available.

Returns:

True if available

bool has_two_rdm_spin_traced() const

Check if spin-traced two-particle RDM is available.

Returns:

True if available

bool is_complex() const

Check if the wavefunction is complex-valued.

Returns:

True if complex, false if real

double norm() const

Calculate norm of the wavefunction.

Returns:

Norm (always real)

Wavefunction &operator=(const Wavefunction &other)

Copy assignment operator.

Wavefunction &operator=(Wavefunction &&other) noexcept = default

Move assignment operator.

ScalarVariant overlap(const Wavefunction &other) const

Calculate overlap with another wavefunction.

Parameters:

other – Other wavefunction

Returns:

Overlap value (real or complex)

std::shared_ptr<const Orbitals> sector_basis(const std::string &name) const

Single-particle basis associated with a sector.

Parameters:

name – Sector name to resolve.

Throws:

std::out_of_range – if no sector named name is present.

Returns:

Shared pointer to the Orbitals bound to name.

std::shared_ptr<const SymmetryProduct> sector_symmetries(const std::string &name) const

Single-particle symmetries inherited from a sector’s basis.

Parameters:

name – Sector name to resolve.

Throws:

std::out_of_range – if no sector named name is present.

Returns:

Shared pointer to the SymmetryProduct of the sector’s basis.

std::vector<std::string> sectors() const

Names of the single-particle sectors this wavefunction spans.

A sector is a named single-particle basis; the sector inherits that basis’s single-particle symmetries (see sector_symmetries). Sectors are owned by the underlying container (which binds each name to a basis); these accessors surface that binding. The current single-species data model reports the sole Wavefunction::DEFAULT_SECTOR.

Returns:

Names of the wavefunction’s sectors.

size_t size() const

Get number of determinants.

Returns:

Number of determinants in the wavefunction

virtual void to_file(const std::string &filename, const std::string &type) const override

Save wavefunction to file in specified format.

Parameters:
  • filename – Path to file to create/overwrite

  • type – Format type (“json” or “hdf5”)

Throws:
  • std::invalid_argument – if unknown type

  • std::runtime_error – if I/O error occurs

virtual void to_hdf5(H5::Group &group) const override

Convert wavefunction to HDF5 group.

Parameters:

group – HDF5 group to write wavefunction data to

Throws:

std::runtime_error – if HDF5 I/O error occurs

virtual void to_hdf5_file(const std::string &filename) const override

Save wavefunction to HDF5 file.

Parameters:

filename – Path to HDF5 file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

virtual nlohmann::json to_json() const override

Convert wavefunction to JSON format.

Returns:

JSON object containing wavefunction data

virtual void to_json_file(const std::string &filename) const override

Save wavefunction to JSON file.

Parameters:

filename – Path to JSON file to create/overwrite

Throws:

std::runtime_error – if I/O error occurs

std::shared_ptr<const SymmetryBlockedScalar<std::size_t>> total_num_particles() const

Number of particles (active + inactive) as a symmetry-blocked scalar.

Forwards to the underlying container’s WavefunctionContainer::total_num_particles.

Returns:

Shared pointer to the symmetry-blocked total particle count.

std::shared_ptr<const SymmetryBlockedTensor<1>> total_orbital_occupations() const

Orbital occupations for all orbitals as a rank-1 symmetry-blocked tensor.

Forwards to the underlying container’s WavefunctionContainer::total_orbital_occupations.

Returns:

Shared pointer to the symmetry-blocked total orbital occupations.

std::shared_ptr<Wavefunction> truncate(std::optional<size_t> max_determinants = std::nullopt) const

Create a truncated wavefunction with top N determinants.

Creates a new wavefunction containing only the top N determinants ranked by absolute coefficient value, with coefficients renormalized. The resulting wavefunction uses a StateVectorContainer.

Parameters:

max_determinants – Maximum number of determinants to keep. If nullopt, returns a copy with all determinants, with coefficients renormalized.

Returns:

Shared pointer to new Wavefunction with truncated and renormalized coefficients

Public Static Functions

static std::shared_ptr<Wavefunction> from_file(const std::string &filename, const std::string &type)

Load wavefunction from file in specified format.

Parameters:
  • filename – Path to file to read

  • type – Format type (“json” or “hdf5”)

Throws:
  • std::invalid_argument – if unknown type

  • std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to Wavefunction object created from file

static std::shared_ptr<Wavefunction> from_hdf5(H5::Group &group)

Load wavefunction from HDF5 group.

Note that due to significant code duplication in the cas and sci containers, their common logic is shared in this base class, and not re-implemented in the cas and sci containers.

Parameters:

group – HDF5 group containing wavefunction data

Throws:

std::runtime_error – if HDF5 data is malformed or I/O error occurs

Returns:

Shared pointer to Wavefunction object created from HDF5 group

static std::shared_ptr<Wavefunction> from_hdf5_file(const std::string &filename)

Load wavefunction from HDF5 file.

Parameters:

filename – Path to HDF5 file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to Wavefunction object created from HDF5 file

static std::shared_ptr<Wavefunction> from_json(const nlohmann::json &j)

Load wavefunction from JSON format.

Parameters:

j – JSON object containing wavefunction data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Shared pointer to Wavefunction object created from JSON data

static std::shared_ptr<Wavefunction> from_json_file(const std::string &filename)

Load wavefunction from JSON file.

Parameters:

filename – Path to JSON file to read

Throws:

std::runtime_error – if file doesn’t exist or I/O error occurs

Returns:

Shared pointer to Wavefunction object created from JSON file

Public Static Attributes

static constexpr const char *DEFAULT_SECTOR = "__default__"

Sentinel sector name for single-species wavefunctions.

class WavefunctionContainer
#include <qdk/chemistry/data/wavefunction.hpp>

Abstract base class for wavefunction containers.

This class provides the interface for different types of wavefunction representations (e.g., CI, MCSCF, coupled cluster). It uses variant types to support both real and complex arithmetic, and provides methods for accessing coefficients, reduced density matrices (RDMs), and other wavefunction properties.

Subclassed by qdk::chemistry::data::AmplitudeContainer, qdk::chemistry::data::StateVectorContainer

Public Types

using DeterminantVector = ContainerTypes::DeterminantVector
using MatrixVariant = ContainerTypes::MatrixVariant
using ScalarVariant = ContainerTypes::ScalarVariant
using VectorVariant = ContainerTypes::VectorVariant

Public Functions

WavefunctionContainer(const std::optional<MatrixVariant> &one_rdm_spin_traced, const std::optional<MatrixVariant> &one_rdm_aa, const std::optional<MatrixVariant> &one_rdm_bb, const std::optional<VectorVariant> &two_rdm_spin_traced, const std::optional<VectorVariant> &two_rdm_aaaa, const std::optional<VectorVariant> &two_rdm_aabb, const std::optional<VectorVariant> &two_rdm_bbbb, const OrbitalEntropies &entropies = OrbitalEntropies{}, WavefunctionType type = WavefunctionType::SelfDual)

Constructs a wavefunction container with reduced density matrix (RDM) data.

Parameters:
  • one_rdm_spin_traced – Spin-traced 1-RDM for active orbitals (optional)

  • one_rdm_aa – Alpha-alpha block of 1-RDM for active orbitals (optional)

  • one_rdm_bb – Beta-beta block of 1-RDM for active orbitals (optional)

  • two_rdm_spin_traced – Spin-traced 2-RDM for active orbitals (optional)

  • two_rdm_aaaa – Alpha-alpha-alpha-alpha block of 2-RDM for active orbitals (optional)

  • two_rdm_aabb – Alpha-alpha-beta-beta block of 2-RDM for active orbitals (optional)

  • two_rdm_bbbb – Beta-beta-beta-beta block of 2-RDM for active orbitals (optional)

  • entropies – Orbital entropy data (optional)

  • type – The type of wavefunction

WavefunctionContainer(const std::optional<MatrixVariant> &one_rdm_spin_traced, const std::optional<VectorVariant> &two_rdm_spin_traced, const OrbitalEntropies &entropies = OrbitalEntropies{}, WavefunctionType type = WavefunctionType::SelfDual)

Constructs a wavefunction with spin-traced reduced density matrix (RDM) data.

Parameters:
  • one_rdm_spin_traced – Spin-traced 1-RDM for active orbitals (optional)

  • two_rdm_spin_traced – Spin-traced 2-RDM for active orbitals (optional)

  • entropies – Orbital entropy data (optional)

  • type – The type of wavefunction

WavefunctionContainer(std::shared_ptr<MatrixVariant> one_rdm_spin_traced, std::shared_ptr<VectorVariant> two_rdm_spin_traced, std::shared_ptr<const SymmetryBlockedTensorVariant<2>> active_one_rdm, std::shared_ptr<const SymmetryBlockedTensorVariant<4>> active_two_rdm, const OrbitalEntropies &entropies = OrbitalEntropies{}, WavefunctionType type = WavefunctionType::SelfDual)

Constructs a wavefunction container directly from preconstructed symmetry-blocked storage for the spin-dependent active-space RDMs.

Used by the serialization layer to hand reconstructed SymmetryBlockedTensorVariant objects to the container without going through the per-block construction path. Any of the four shared pointers may be nullptr to indicate that the corresponding RDM is not stored.

Parameters:
  • one_rdm_spin_traced – Spin-traced 1-RDM for active orbitals (may be nullptr).

  • two_rdm_spin_traced – Spin-traced 2-RDM for active orbitals (may be nullptr).

  • active_one_rdm – Spin-dependent active-space 1-RDM (may be nullptr).

  • active_two_rdm – Spin-dependent active-space 2-RDM (may be nullptr).

  • entropies – Orbital entropy data.

  • type – The type of wavefunction.

WavefunctionContainer(WavefunctionType type = WavefunctionType::SelfDual)

Constructor.

Parameters:

type – Type of wavefunction (SelfDual or NotSelfDual)

virtual ~WavefunctionContainer() = default
virtual std::shared_ptr<const SymmetryBlockedScalar<std::size_t>> active_num_particles() const = 0

Number of active-space particles as a symmetry-blocked scalar.

Blocked the same way as total_num_particles; see that method for the basis-induced block structure.

Returns:

Shared pointer to the symmetry-blocked active particle count.

virtual const SymmetryBlockedTensorVariant<2> &active_one_rdm() const

Active-space 1-RDM as a rank-2 symmetry-blocked tensor.

The block structure (label set, per-slot extents, equivalence aliasing) is determined by the symmetries carried on the associated Orbitals. The returned SymmetryBlockedTensorVariant holds either the real (SymmetryBlockedTensor<2, double>) or complex (SymmetryBlockedTensor<2, std::complex<double>>) alternative depending on the scalar type of the underlying RDM.

Throws:

std::runtime_error – if not available.

Returns:

Const reference to the 1-RDM symmetry-blocked tensor variant.

MatrixVariant active_one_rdm_block(const SymmetryLabel &row, const SymmetryLabel &col) const

Active-space 1-RDM block for the given row/column symmetry labels.

Parameters:
  • row – Row-slot symmetry label.

  • col – Column-slot symmetry label.

Throws:
  • std::runtime_error – if the 1-RDM is not available.

  • std::invalid_argument – if no block is stored for the requested label pair.

Returns:

MatrixVariant holding the requested block as either an Eigen::MatrixXd or an Eigen::MatrixXcd, matching the scalar type of the underlying RDM.

virtual std::shared_ptr<const SymmetryBlockedTensor<1>> active_orbital_occupations() const = 0

Orbital occupations for active orbitals only as a rank-1 symmetry-blocked tensor.

Blocked the same way as total_orbital_occupations.

Throws:

std::runtime_error – if occupations are not available for this container type.

Returns:

Shared pointer to the symmetry-blocked active orbital occupations.

virtual const SymmetryBlockedTensorVariant<4> &active_two_rdm() const

Active-space 2-RDM as a rank-4 symmetry-blocked tensor.

The block structure is determined by the symmetries carried on the associated Orbitals. The returned SymmetryBlockedTensorVariant holds either the real or complex alternative depending on the scalar type of the underlying RDM.

Throws:

std::runtime_error – if not available.

Returns:

Const reference to the 2-RDM symmetry-blocked tensor variant.

VectorVariant active_two_rdm_block(const SymmetryLabel &p, const SymmetryLabel &q, const SymmetryLabel &r, const SymmetryLabel &s) const

Active-space 2-RDM block for the given symmetry labels.

Parameters:
  • p – First slot’s symmetry label.

  • q – Second slot’s symmetry label.

  • r – Third slot’s symmetry label.

  • s – Fourth slot’s symmetry label.

Throws:
  • std::runtime_error – if the 2-RDM is not available.

  • std::invalid_argument – if no block is stored for the requested label tuple.

Returns:

VectorVariant holding the requested block as either an Eigen::VectorXd or an Eigen::VectorXcd, matching the scalar type of the underlying RDM.

virtual void clear_caches() const = 0

Clear cached data to release memory.

This method cleans up memoized evaluations of data derived from the wavefunction, such as reduced density matrices (RDMs), and other computed properties. Each derived container implementation decides specifically what cached data to clear based on its internal structure.

Calling this method can help manage memory usage for large systems.

virtual std::unique_ptr<WavefunctionContainer> clone() const = 0

Create a deep copy of this container.

Returns:

Unique pointer to a cloned container

virtual const DeterminantVector &get_active_determinants() const

Get all determinants in the wavefunction.

Only meaningful for determinant-expansion containers. The base implementation throws; containers that are not a determinant/coefficient expansion (e.g. amplitude-based wavefunctions) do not override it.

Returns:

Vector of all configurations/determinants

virtual std::pair<size_t, size_t> get_active_num_electrons() const

Get number of active alpha and beta electrons.

Spin-resolved view of active_num_particles.

Throws:

std::runtime_error – if the single-particle basis carries no spin ( \(S_z\)) axis; use active_num_particles instead.

Returns:

Pair of (n_alpha_active, n_beta_active) electrons

virtual std::tuple<MatrixVariant, MatrixVariant> get_active_one_rdm_spin_dependent() const

Get spin-dependent one-particle RDMs for active orbitals only.

Returns:

Tuple of (alpha-alpha, beta-beta) one-particle RDMs for active orbitals, constructed from the canonical symmetry-blocked tensor.

virtual const MatrixVariant &get_active_one_rdm_spin_traced() const

Get spin-traced one-particle RDM for active orbitals only.

Returns:

Spin-traced one-particle RDM for active orbitals

virtual std::pair<Eigen::VectorXd, Eigen::VectorXd> get_active_orbital_occupations() const

Get orbital occupations for active orbitals only.

Spin-resolved view of active_orbital_occupations.

Throws:

std::runtime_error – if occupations are not available, or if the single-particle basis carries no spin ( \(S_z\)) axis; use active_orbital_occupations instead.

Returns:

Pair of (alpha_active_occupations, beta_active_occupations)

virtual std::tuple<VectorVariant, VectorVariant, VectorVariant> get_active_two_rdm_spin_dependent() const

Get spin-dependent two-particle RDMs for active orbitals only.

Returns:

Tuple of (aaaa, aabb, bbbb) two-particle RDMs for active orbitals, constructed from the canonical symmetry-blocked tensor.

virtual const VectorVariant &get_active_two_rdm_spin_traced() const

Get spin-traced two-particle RDM for active orbitals only.

Returns:

Spin-traced two-particle RDM for active orbitals

virtual ScalarVariant get_coefficient(const Configuration &det) const

Get coefficient for a specific determinant.

Only meaningful for determinant-expansion containers. The base implementation throws; containers that are not a determinant/coefficient expansion (e.g. amplitude-based wavefunctions) do not override it.

Parameters:

det – Configuration/determinant to get coefficient for

Returns:

Scalar coefficient (real or complex)

virtual const VectorVariant &get_coefficients() const

Get all coefficients.

Only meaningful for determinant-expansion containers. The base implementation throws; containers that are not a determinant/coefficient expansion (e.g. amplitude-based wavefunctions) do not override it.

Returns:

Vector of all coefficients (real or complex)

inline virtual const ConfigurationSet &get_configuration_set() const

Get the configuration set for this wavefunction.

Throws:

std::runtime_error – if configuration set is not available

Returns:

Reference to the configuration set containing determinants and orbitals

virtual std::string get_container_type() const = 0

Get container type identifier for serialization.

Returns:

String identifying the container type (e.g., “state_vector”, “coupled_cluster”, “mp2”)

virtual Eigen::MatrixXd get_mutual_information() const

Get the mutual information matrix for active orbitals.

The mutual information is defined as: \( I_{ij} = s_{1,i} + s_{1,j} - s_{2,ij} \)

Throws:

std::runtime_error – if mutual information is not available

Returns:

Matrix of mutual information values for active orbitals

virtual std::shared_ptr<Orbitals> get_orbitals() const = 0

Get reference to orbital basis set.

Returns:

Shared pointer to orbitals

virtual Eigen::VectorXd get_single_orbital_entropies() const

Get or calculate single orbital entropies for active orbitals only.

Returns pre-computed entropies if provided at construction. Otherwise, uses the method of Boguslawski & Tecmer (2015), doi:10.1002/qua.24832, [BT15].

Returns:

Vector of orbital entropies for active orbitals (always real)

virtual std::pair<size_t, size_t> get_total_num_electrons() const

Get total number of alpha and beta electrons (active + inactive)

Spin-resolved view of total_num_particles.

Throws:

std::runtime_error – if the single-particle basis carries no spin ( \(S_z\)) axis; use total_num_particles instead.

Returns:

Pair of (n_alpha_total, n_beta_total) electrons

virtual std::pair<Eigen::VectorXd, Eigen::VectorXd> get_total_orbital_occupations() const

Get orbital occupations for all orbitals (total = active + inactive.

  • virtual)

Spin-resolved view of total_orbital_occupations.

Throws:

std::runtime_error – if occupations are not available, or if the single-particle basis carries no spin ( \(S_z\)) axis; use total_orbital_occupations instead.

Returns:

Pair of (alpha_occupations_total, beta_occupations_total)

virtual Eigen::MatrixXd get_two_orbital_entropies() const

Get the two-orbital entropies matrix for active orbitals.

Throws:

std::runtime_error – if two-orbital entropies are not available

Returns:

Matrix of two-orbital entropies for active orbitals

WavefunctionType get_type() const

Get the wavefunction type (SelfDual or NotSelfDual)

Returns:

WavefunctionType enum value

bool has_active_one_rdm() const

True if the active-space 1-RDM symmetry-blocked tensor is available (real or complex).

Returns:

true iff active_one_rdm would succeed without throwing.

bool has_active_two_rdm() const

True if the active-space 2-RDM symmetry-blocked tensor is available (real or complex).

Returns:

true iff active_two_rdm would succeed without throwing.

inline virtual bool has_coefficients() const

Check if this container has coefficients data.

Returns:

True if coefficients are available, false otherwise

inline virtual bool has_configuration_set() const

Check if this container has configuration set data.

Returns:

True if configuration set is available, false otherwise

virtual bool has_mutual_information() const

Checks if mutual information for active orbitals is available.

Returns:

True if mutual information matrix is available, false otherwise

virtual bool has_one_rdm_spin_dependent() const

Check if spin-dependent one-particle RDMs for active orbitals are available.

Returns:

True if available

virtual bool has_one_rdm_spin_traced() const

Check if spin-traced one-particle RDM for active orbitals is available.

Returns:

True if available

virtual bool has_single_orbital_entropies() const

Checks if single-orbital entropies for active orbitals are available.

Returns true if pre-computed entropies were provided at construction, or if the required RDMs are available to compute them.

Returns:

True if single-orbital entropies are available, false otherwise

virtual bool has_two_orbital_entropies() const

Checks if two-orbital entropies for active orbitals are available.

Returns:

True if two-orbital entropies are available, false otherwise

virtual bool has_two_rdm_spin_dependent() const

Check if spin-dependent two-particle RDMs for active orbitals are available.

Returns:

True if available

virtual bool has_two_rdm_spin_traced() const

Check if spin-traced two-particle RDM for active orbitals is available.

Returns:

True if available

virtual void hash_update(qdk::chemistry::utils::HashContext &ctx) const

Feed identifying data into a hash context.

Subclasses override to add their container-specific data.

virtual bool is_complex() const = 0

Check if the wavefunction is complex-valued.

Returns:

True if complex, false if real

virtual double norm() const = 0

Calculate norm of the wavefunction.

Returns:

Norm (always real)

virtual ScalarVariant overlap(const WavefunctionContainer &other) const = 0

Calculate overlap with another wavefunction.

Parameters:

other – Other wavefunction container

Returns:

Overlap value (real or complex)

virtual std::shared_ptr<const Orbitals> sector_basis(const std::string &name) const = 0

Single-particle basis bound to a sector.

Parameters:

name – Sector name to resolve.

Throws:

std::out_of_range – if this container has no sector named name.

Returns:

Shared pointer to the Orbitals bound to name.

virtual std::vector<std::string> sectors() const = 0

Names of the single-particle sectors this container spans.

A sector is a named single-particle basis; every container owns its own sector-to-basis binding (see sector_basis) and must report it. The current single-species containers report one electronic sector.

Returns:

Names of the container’s sectors.

virtual size_t size() const

Get number of determinants.

Only meaningful for determinant-expansion containers. The base implementation throws; containers that are not a determinant/coefficient expansion (e.g. amplitude-based wavefunctions) do not override it.

Returns:

Number of determinants in the wavefunction

virtual void to_hdf5(H5::Group &group) const

Convert container to HDF5 group.

Parameters:

group – HDF5 group to write container data to

Throws:

std::runtime_error – if HDF5 I/O error occurs

virtual nlohmann::json to_json() const = 0

Convert container to JSON format.

Returns:

JSON object containing container data

virtual std::shared_ptr<const SymmetryBlockedScalar<std::size_t>> total_num_particles() const = 0

Number of particles (active + inactive) as a symmetry-blocked scalar.

The block structure is induced by the single-particle basis: when the associated Orbitals carry a spin ( \(S_z\)) axis the result holds an independent \(\alpha\) and \(\beta\) count; when they carry no spin axis the result holds a single trivial block with the aggregate count.

Returns:

Shared pointer to the symmetry-blocked total particle count.

virtual std::shared_ptr<const SymmetryBlockedTensor<1>> total_orbital_occupations() const = 0

Orbital occupations for all orbitals (total = active + inactive + virtual) as a rank-1 symmetry-blocked tensor.

When the associated Orbitals carry a spin axis the result holds an independent \(\alpha\) and \(\beta\) occupation vector; otherwise it holds a single trivial block with the spin-summed occupations.

Throws:

std::runtime_error – if occupations are not available for this container type.

Returns:

Shared pointer to the symmetry-blocked total orbital occupations.

Public Static Functions

static std::unique_ptr<WavefunctionContainer> from_hdf5(H5::Group &group)

Load container from HDF5 group.

Parameters:

group – HDF5 group containing container data

Throws:

std::runtime_error – if HDF5 data is malformed or I/O error occurs

Returns:

Unique pointer to container created from HDF5 group

static std::unique_ptr<WavefunctionContainer> from_json(const nlohmann::json &j)

Load container from JSON format.

Parameters:

j – JSON object containing container data

Throws:

std::runtime_error – if JSON is malformed

Returns:

Unique pointer to container created from JSON data

namespace axes

Functions

const std::shared_ptr<const SpinValue> &alpha()

Interned shared spin-½ value with \(2 M_s = +1\).

Returns:

Reference to the global \(\alpha\) instance; safe to capture by shared_ptr.

const std::shared_ptr<const SpinValue> &beta()

Interned shared spin-½ value with \(2 M_s = -1\).

Returns:

Reference to the global \(\beta\) instance; safe to capture by shared_ptr.

SymmetryAxis spin(unsigned two_s, bool equivalent = true)

Build a spin axis carrying 2s+1 labels at \(2 M_s \in \{-2s, -2s+2, \ldots, +2s\}\).

For the standard single-particle (two_s = 1) case, this is the spin-1/2 axis with the two labels \(\alpha\) (2 M_s = +1) and \(\beta\) (2 M_s = -1).

Parameters:
  • two_s – Twice the total spin.

  • equivalent – Whether labels under this axis share storage (i.e. restricted-spin storage).

Returns:

A fully populated SymmetryAxis for the spin degree of freedom.

std::shared_ptr<const SpinValue> spin_value(int two_ms)

Construct a spin value carrying \(2 M_s = \) two_ms.

Parameters:

two_ms – Twice the spin projection. The standard interned values (alpha and beta) are returned when two_ms is +1 or -1 respectively.

Returns:

Shared pointer to the (possibly interned) spin value.

namespace ciaaw_2024

CIAAW 2024 recommended values for atomic weights.

Standard atomic weights in AMU (atomic mass units) for all elements 1-118. IUPAC (International Union of Pure and Applied Chemistry) Commission on Isotopic Abundances and Atomic Weights (CIAAW), 2024.

T. Prohaska et al., Standard atomic weights of the elements 2021 (IUPAC Technical Report), Pure and Applied Chemistry 2022, 94, 573-600 (DOI: 10.1515/pac-2019-0603). [PIB+22]

Standard atomic masses of gadolinium, lutetium, and zirconium have been revised by IUPAC CIAAW in 2024 and these revisions are included here.

For radioactive elements the mass number of the most stable isotope is used as standard atomic weight.

F. G. Kondev et al., The NUBASE2020 evaluation of nuclear physics properties, Chinese Physics C 2021, 45, 030001 (DOI: 10.1088/1674-1137/abddae). [KWH+21]

Isotope masses in AMU (atomic mass units) for all elements 1-118. IUPAC (International Union of Pure and Applied Chemistry) Commission on Isotopic Abundances and Atomic Weights (CIAAW), 2021.

W. J. Huang et al., The AME 2020 atomic mass evaluation (I). Evaluation of input data, and adjustment procedures, Chinese Physics C 2021, 45, 030002 (DOI: 10.1088/1674-1137/abddb0). [HWK+21]

M. Wang et al., The AME 2020 atomic mass evaluation (II). Tables, graphs and references, Chinese Physics C 2021, 45, 030003 (DOI: 10.1088/1674-1137/abddaf). [WHK+21]

F. G. Kondev et al., The NUBASE2020 evaluation of nuclear physics properties, Chinese Physics C 2021, 45, 030001 (DOI: 10.1088/1674-1137/abddae). [KWH+21]

Functions

inline double get_atomic_weight(Element element)

Get atomic weight for an Element.

This function converts Element to unsigned and looks up the standard atomic weight.

Parameters:

element – Element enum value

Throws:

std::invalid_argument – if element is not found in the atomic weights map

Returns:

Atomic weight in AMU

inline double get_atomic_weight(unsigned Z, unsigned A)

Get atomic weight for an atomic number Z and mass number A.

This function looks up the atomic weight for the given pair of atomic number Z and mass number A.

Parameters:
  • Z – Atomic number (proton count)

  • A – Mass number (proton + neutron count) for a specific isotope mass or 0 for a standard atomic weight

Throws:

std::invalid_argument – if pair of atomic number Z and mass number A is not found in the atomic weights map

Returns:

Atomic weight in AMU

constexpr unsigned isotope(const unsigned Z, const unsigned A) noexcept

Helper function to calculate unique unsigned keys for isotopes.

For isotopes, put the atomic mass number in the unsigned’s bit representation. Z ranges up to 118 < 128 = 2^7, so we use 7 bits for Z. A ranges up to 295 < 512 = 2^9, so we need at least 16 bits total.

Parameters:
  • Z – Atomic number (proton count)

  • A – Mass number (proton + neutron count) for a specific isotope mass or 0 for a standard atomic weight

Returns:

Encoded unsigned key for atomic weight representation

Variables

const std::unordered_map<unsigned, double> atomic_weights

Standard atomic weights and specific isotope masses in AMU (atomic mass units)

Includes both standard atomic weights for elements 1-118 and specific isotope masses. For the standard atomic weights of radioactive elements, the mass numbers of the most stable isotopes are used.

namespace ContainerTypes

Common type definitions used across all container types.

This struct provides centralized type definitions for scalar, matrix, and vector types that can be either real or complex, used throughout the wavefunction system.

Typedefs

using DeterminantVector = std::vector<Configuration>
using MatrixVariant = std::variant<Eigen::MatrixXd, Eigen::MatrixXcd>
using ScalarVariant = std::variant<double, std::complex<double>>
using VectorVariant = std::variant<Eigen::VectorXd, Eigen::VectorXcd>
namespace detail

Functions

std::shared_ptr<ContainerTypes::MatrixVariant> add_matrix_variants(const ContainerTypes::MatrixVariant &mat1, const ContainerTypes::MatrixVariant &mat2)

Helper to add two ContainerTypes::MatrixVariants.

Parameters:
  • mat1 – First matrix variant

  • mat2 – Second matrix variant

Returns:

Shared pointer to new ContainerTypes::MatrixVariant containing the sum

std::shared_ptr<ContainerTypes::VectorVariant> add_vector_variants(const ContainerTypes::VectorVariant &vec1, const ContainerTypes::VectorVariant &vec2)

Helper to add two ContainerTypes::VectorVariants.

Parameters:
  • vec1 – First vector variant

  • vec2 – Second vector variant

Returns:

Shared pointer to new ContainerTypes::VectorVariant containing the sum

void consolidate_determinants(std::vector<Configuration> &determinants, ContainerTypes::VectorVariant &coefficients, double threshold = 1e-9)

Consolidate duplicate determinants by summing their coefficients.

This utility function merges duplicate determinants in a CI expansion by summing their coefficients. Determinants with coefficients below the threshold are removed.

Parameters:
  • determinants – Vector of determinants (modified in place)

  • coefficients – VectorVariant of coefficients (modified in place)

  • threshold – Coefficient magnitude threshold for pruning (default 1e-9)

std::string denormalize_basis_set_name(const std::string &normalized)

Denormalize basis set name from filesystem representation.

Reverses the normalization:

  • st’ -> ‘*’

  • sl’ -> ‘/’

  • pl’ -> ‘+’

Parameters:

normalized – Normalized name from filesystem

Returns:

Original basis set name

bool is_matrix_variant_complex(const ContainerTypes::MatrixVariant &variant)

Check if a ContainerTypes::MatrixVariant contains complex type.

Parameters:

variant – The matrix variant to check

Returns:

True if contains Eigen::MatrixXcd, false if Eigen::MatrixXd

bool is_vector_variant_complex(const ContainerTypes::VectorVariant &variant)

Check if a ContainerTypes::VectorVariant contains complex type.

Parameters:

variant – The vector variant to check

Returns:

True if contains Eigen::VectorXcd, false if Eigen::VectorXd

template<std::size_t Rank>
std::array<SymmetryLabel, Rank> make_labels(const std::vector<SymmetryLabel> &values)
template<typename Scalar>
std::shared_ptr<ContainerTypes::MatrixVariant> multiply_matrix_variant(const ContainerTypes::MatrixVariant &matrix, Scalar scalar)

Helper to create a ContainerTypes::MatrixVariant from scalar multiplication.

Parameters:
  • matrix – The matrix variant to multiply

  • scalar – The scalar value to multiply by

Returns:

Shared pointer to new ContainerTypes::MatrixVariant containing the result

template<typename Scalar>
std::shared_ptr<ContainerTypes::VectorVariant> multiply_vector_variant(const ContainerTypes::VectorVariant &vector, Scalar scalar)

Helper to create a ContainerTypes::VectorVariant from scalar multiplication.

Parameters:
  • vector – The vector variant to multiply

  • scalar – The scalar value to multiply by

Returns:

Shared pointer to new ContainerTypes::VectorVariant containing the result

std::string normalize_basis_set_name(const std::string &name)

Normalize basis set name for filesystem usage.

Replaces special characters that are problematic in filenames:

  • ’*’ -> ‘st’ (star)

  • ’/’ -> ‘sl’ (slash)

  • ’+’ -> ‘pl’ (plus)

Parameters:

name – Original basis set name (e.g., “6-31g*+”)

Returns:

Normalized name safe for filesystem (e.g., “6-31g_st__pl_”)

template<class S>
S scalar_from_json(const nlohmann::json &j)
template<class S>
nlohmann::json scalar_to_json(const S &value)
std::shared_ptr<ContainerTypes::VectorVariant> transpose_ijkl_klij_vector_variant(const ContainerTypes::VectorVariant &variant, size_t norbs)

Transpose a 2-RDM vector from (ij|kl) to (kl|ij) ordering.

Parameters:
  • variant – The vector variant to transpose

  • norbs – Number of orbitals

Returns:

shared pointer to new ContainerTypes::VectorVariant containing the transposed data

namespace utils

Enums

enum class HashValueTag : uint8_t

Stable byte tags used to delimit generic hash_value encodings.

These are explicit hash-format markers, not serialized C++ type identity. RTTI names are implementation-defined and may vary by compiler, standard library, and build flags; fixed tags keep the digest format deterministic.

Values:

enumerator RealAlternative
enumerator ComplexAlternative
enumerator SharedPtr
enumerator Optional
enumerator Vector
enumerator Variant
enum class LogLevel

Log level enumeration for QDK Chemistry logging.

Values:

enumerator trace

Most verbose logging.

enumerator debug

Debug information.

enumerator info

General information.

enumerator warn

Warning messages.

enumerator error

Error messages.

enumerator critical

Critical errors.

enumerator off

Disable logging.

Functions

std::pair<size_t, size_t> compute_valence_space_parameters(std::shared_ptr<qdk::chemistry::data::Wavefunction> wavefunction, int charge, bool include_double_d_shell = false)

Computes the default number of valence orbitals and electrons for a given structure and wavefunction.

This function analyzes the provided molecular structure and wavefunction to determine the number of electrons and orbitals in valence shell

Parameters:
  • wavefunction – Shared pointer to the wavefunction containing electronic structure information (structure is extracted from wavefunction->orbitals->basis_set)

  • charge – The total charge of the molecular system, which should be equal to the charge set in scf calculation

  • include_double_d_shell – If true, add 5 correlating d’ orbitals to the valence space for d-block elements (Sc-Zn, Y-Cd, Hf-Hg) to capture the strong nd / (n+1)d’ radial correlation in transition metals (the “double d-shell” effect). Defaults to false.

Returns:

A pair where:

  • first: Number of valence electrons

  • second: Number of valence orbitals

template<typename T, typename Hasher = std::hash<T>>
inline std::size_t hash_combine(std::size_t seed, const T &value)

Combine an existing hash seed with the hash of another value.

This helper is intended for fast local hash-code composition, not for persistent content hashes.

Template Parameters:
  • T – Value type to hash.

  • Hasher – Hash function type. Defaults to std::hash<T>.

Parameters:
  • seed – Existing hash seed.

  • value – Value to hash and combine into the seed.

Returns:

Combined hash value.

template<typename T, typename ...Args>
inline std::size_t hash_combine(std::size_t seed, const T &value, Args&&... args)

Combine an existing hash seed with multiple values from left to right.

This helper is intended for fast local hash-code composition, not for persistent content hashes.

Template Parameters:
  • T – First value type to hash.

  • Args – Remaining value types to hash.

Parameters:
  • seed – Existing hash seed.

  • value – First value to hash and combine into the seed.

  • args – Remaining values to hash and combine into the seed.

Returns:

Combined hash value.

inline void hash_field_presence(HashContext &ctx, bool present)

Hash whether a nullable field is present before its payload.

Parameters:
  • ctx – Hash context to update

  • present – Whether the field is present

void hash_value(HashContext &ctx, bool value)

Hash a boolean value as one byte.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const char *value)

Hash a null-terminated string value.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const Eigen::MatrixXcd &value)

Hash a complex dense matrix.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const Eigen::MatrixXd &value)

Hash a dense matrix.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const Eigen::SparseMatrix<double> &value)

Hash a sparse matrix.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const Eigen::VectorXcd &value)

Hash a complex dense vector.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const Eigen::VectorXd &value)

Hash a dense vector.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const Eigen::VectorXi &value)

Hash a dense integer vector.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const HashContext::MatrixVariant &value)

Hash a matrix variant.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, const HashContext::VectorVariant &value)

Hash a vector variant.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

template<typename T>
void hash_value(HashContext &ctx, const std::complex<T> &value)
template<typename T>
void hash_value(HashContext &ctx, const std::optional<T> &value)
template<typename T>
void hash_value(HashContext &ctx, const std::shared_ptr<T> &value)
void hash_value(HashContext &ctx, const std::string &value)

Hash a string value with a length prefix.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

template<typename ...Ts>
void hash_value(HashContext &ctx, const std::variant<Ts...> &value)
template<typename T>
void hash_value(HashContext &ctx, const std::vector<T> &values)
void hash_value(HashContext &ctx, double value)

Hash a double value as deterministic little-endian bytes.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, float value)

Hash a float value through the canonical double encoding.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

inline void hash_value(HashContext &ctx, HashValueTag tag)

Hash a generic hash-format tag.

Parameters:
  • ctx – Hash context to update

  • tag – Tag to hash

void hash_value(HashContext &ctx, int64_t value)

Hash a signed 64-bit integer as deterministic little-endian bytes.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, long double value)

Hash a long double value as a canonical hexadecimal string.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, std::string_view value)

Hash a string value with a length prefix.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

template<typename T>
void hash_value(HashContext &ctx, T value)
template<typename T>
void hash_value(HashContext &ctx, T value)
template<typename T>
void hash_value(HashContext &ctx, T value)
void hash_value(HashContext &ctx, uint64_t value)

Hash an unsigned 64-bit integer as deterministic little-endian bytes.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void hash_value(HashContext &ctx, uint8_t value)

Hash a single sentinel byte.

Parameters:
  • ctx – Hash context to update

  • value – Value to hash

void log_trace_entering(const std::source_location &location = std::source_location::current())

Logs a standardized trace message for entering a function.

Automatically uses std::source_location to determine the calling function and logs a message in the form: “[context] Entering method_name”

This function is typically called via the QDK_LOG_TRACE_ENTERING() macro for convenience.

Example:

void compute() {
  QDK_LOG_TRACE_ENTERING();  // Logs "[qdk:chemistry:...:compute] Entering"
  // ...
}

Parameters:

location – Automatically provided by std::source_location::current()

std::shared_ptr<qdk::chemistry::data::Orbitals> rotate_orbitals(std::shared_ptr<const qdk::chemistry::data::Orbitals> orbitals, const Eigen::VectorXd &rotation_vector, size_t num_alpha_occupied_orbitals, size_t num_beta_occupied_orbitals, bool restricted_external = false)

Rotate molecular orbitals using a rotation vector.

This function takes Orbitals and applies orbital rotations using a rotation vector, which can be taken from stability analysis eigenvectors.

The rotation is performed by:

  1. Unpacking the rotation vector into an anti-Hermitian matrix

  2. Computing the unitary rotation matrix via matrix exponential

  3. Applying the rotation to the molecular orbital coefficients

Note

restricted_external can break spin symmetry and solve external instabilities of RHF/RKS.

Note

This function assumes aufbau filling for occupation numbers.

Note

Orbital energies are invalidated by rotation and set to null.

Parameters:
  • orbitals – The Orbitals to rotate

  • rotation_vector – The rotation vector (eigenvector from stability analysis, corresponding to the lowest eigenvalue). See StabilityResult::eigenvector_format for detailed size and indexing requirements.

  • num_alpha_occupied_orbitals – Number of alpha occupied orbitals

  • num_beta_occupied_orbitals – Number of beta occupied orbitals

  • restricted_external – If true and orbitals are restricted, creates unrestricted orbitals with rotated coefficients for alpha spin and unrotated coefficients for beta spin. Default is false.

Throws:

std::runtime_error – if rotation vector size is invalid

Returns:

A new Orbitals object with rotated molecular orbital coefficients

inline std::string to_snake_case(const char *input)

Convert a PascalCase/camelCase string to snake_case at runtime.

This function inserts an underscore before each uppercase letter (except at position 0) and converts all letters to lowercase.

Examples:

  • ”Ansatz” -> “ansatz”

  • ”ConfigurationSet” -> “configuration_set”

  • ”StabilityResult” -> “stability_result”

Parameters:

input – Input string in PascalCase or camelCase

Returns:

std::string containing the snake_case version

Variables

template<class S>
constexpr bool is_complex_scalar_v = is_complex_scalar<S>::value

Convenience value template: true iff S is a std::complex<T> specialization.

Template Parameters:

S – Scalar type under test (typically double or std::complex<double>).

class ContextLogger
#include <qdk/chemistry/utils/logger.hpp>

A logger wrapper that automatically prepends source context to messages.

This class wraps the global logger and automatically includes file/method context in every log message. It provides the same interface as spdlog::logger (trace, debug, info, warn, error, critical) but prepends source location info.

Use via the QDK_LOGGER() macro which captures the call site’s source location.

Example:

QDK_LOGGER().info("Message with {} args", 2);
// Output: [timestamp] [info] [file:method] Message with 2 args

Public Functions

inline explicit ContextLogger(const std::source_location &loc)
inline void critical(const std::string &msg)
template<typename ...Args>
inline void critical(fmt::format_string<Args...> fmt, Args&&... args)
inline void debug(const std::string &msg)
template<typename ...Args>
inline void debug(fmt::format_string<Args...> fmt, Args&&... args)
inline void error(const std::string &msg)
template<typename ...Args>
inline void error(fmt::format_string<Args...> fmt, Args&&... args)
inline void info(const std::string &msg)
template<typename ...Args>
inline void info(fmt::format_string<Args...> fmt, Args&&... args)
inline void trace(const std::string &msg)
template<typename ...Args>
inline void trace(fmt::format_string<Args...> fmt, Args&&... args)
inline void warn(const std::string &msg)
template<typename ...Args>
inline void warn(fmt::format_string<Args...> fmt, Args&&... args)
class HashContext
#include <qdk/chemistry/utils/hash_context.hpp>

Streaming context for deterministic content hashes.

Provides an incremental byte-oriented interface for feeding data into a content digest. Producers must add fields in a deterministic order; this is a sequential streaming hash interface, not a tree hash suitable for parallel producers. Use hash_value() to hash typed values.

Content hashes are intended for cache keys and checkpoint/restart workflows among compatible builds. They are not a data preservation format, and the exact digest values are not guaranteed to remain stable across releases.

HashContext favors deterministic byte encodings over lookup speed. For performance-sensitive in-memory hash tables, prefer hash_combine() from qdk/chemistry/utils/hash.hpp unless the table key must intentionally use the deterministic content digest.

Usage:

HashContext ctx;
hash_value(ctx, some_matrix);
hash_value(ctx, some_double);
hash_value(ctx, "some_string");
std::string hash = ctx.hexdigest();

Public Types

using MatrixVariant = std::variant<Eigen::MatrixXd, Eigen::MatrixXcd>
using VectorVariant = std::variant<Eigen::VectorXd, Eigen::VectorXcd>

Public Functions

HashContext()
std::size_t hash_code() const

Finalize and return the leading digest bytes as a size_t value.

Prefer hash_combine() for hot std::hash-compatible table hashers.

std::string hexdigest(size_t truncate_chars = 16) const

Finalize and return truncated hex digest.

Parameters:

truncate_chars – Number of hex characters to return (default 16)

void update(const void *data, size_t len)

Feed raw bytes into the hash.

template<class S>
struct is_complex_scalar : public std::false_type
#include <qdk/chemistry/utils/scalar_traits.hpp>

Type trait: true for std::complex<T> specializations.

Default specialization yields false.

Template Parameters:

S – Scalar type under test.

class Logger
#include <qdk/chemistry/utils/logger.hpp>

Centralized logging utility wrapper around spdlog for QDK Chemistry.

This class provides a consistent interface for logging throughout the QDK Chemistry library, wrapping the spdlog library with project-specific defaults and conventions. It uses a single global logger instance for efficiency, while still providing per-file/function context in log messages.

Public Static Functions

static std::shared_ptr<spdlog::logger> get()

Get the global logger instance.

Returns the single global logger instance for QDK Chemistry. The logger is lazily initialized on first call and reused thereafter.

New logger is created with default settings:

  • Colored console output

  • Inherit global log level

  • Consistent timestamped format

Returns:

Shared pointer to the global logger instance

static LogLevel get_global_level()

Get the current global log level.

Returns the current global logging level. This uses mutex protection to ensure thread safety.

Returns:

The current global log level

static std::string get_source_context(const std::source_location &location = std::source_location::current())

Get a formatted source context string for the given location.

Returns a string like “qdk:chemistry:utils:logger:method_name” that identifies the source file and method. This is automatically used by the ContextLogger to prefix log messages with per-file context.

Parameters:

location – Source location (defaults to caller’s location)

Returns:

Formatted context string

static bool restore_global_level_if_unchanged(LogLevel expected_current, LogLevel restored_level)

Restore the global log level if it has not changed.

Atomically compares the current global log level with expected_current. If they match, restores restored_level and returns true. Otherwise leaves the current level unchanged and returns false.

Parameters:
  • expected_current – The level that must still be current

  • restored_level – The level to restore when expected_current matches

Returns:

Whether restored_level was applied

static void set_global_level(LogLevel level)

Set the global log level for all loggers.

Changes the logging level for the global logger instance. Messages below this level will be suppressed.

Parameters:

level – The minimum log level to output

class ScopedLogLevel
#include <qdk/chemistry/utils/logger.hpp>

Temporarily raises the global log level for a scope.

If the current global log level is more verbose than the requested minimum, the constructor raises it to that minimum. The destructor restores the previous level only if no other code changed the global level while the guard was active.

Public Functions

ScopedLogLevel(const ScopedLogLevel&) = delete
explicit ScopedLogLevel(LogLevel minimum_level)
~ScopedLogLevel()
ScopedLogLevel &operator=(const ScopedLogLevel&) = delete
namespace model_hamiltonians

Functions

template<typename EpsT, typename TT, typename UT>
inline qdk::chemistry::data::Hamiltonian create_hubbard_hamiltonian(const qdk::chemistry::data::LatticeGraph &lattice, EpsT &&epsilon_in, TT &&t_in, UT &&U_in)

Create a Hubbard model Hamiltonian.

Template Parameters:
  • EpsT – double or Eigen::VectorXd

  • TT – double or Eigen::MatrixXd

  • UT – double or Eigen::VectorXd

Parameters:
  • lattice – Symmetric lattice graph defining the connectivity.

  • epsilon_in – On-site orbital energies. Scalar or VectorXd of size n.

  • t_in – Hopping integrals. Scalar or n x n MatrixXd.

  • U_in – On-site Coulomb repulsion. Scalar or VectorXd of size n.

Returns:

Hamiltonian for the Hubbard model.

template<typename EpsT, typename TT>
inline qdk::chemistry::data::Hamiltonian create_huckel_hamiltonian(const qdk::chemistry::data::LatticeGraph &lattice, EpsT &&epsilon_in, TT &&t_in)

Create a Hückel model Hamiltonian.

Template Parameters:
  • EpsT – double or Eigen::VectorXd

  • TT – double or Eigen::MatrixXd

Parameters:
  • lattice – Symmetric lattice graph defining the connectivity.

  • epsilon_in – On-site orbital energies. Scalar or VectorXd of size n.

  • t_in – Hopping integrals. Scalar or n x n MatrixXd.

Returns:

Hamiltonian for the Hückel model.

template<typename EpsT, typename TT, typename UT, typename VT, typename ZT>
inline qdk::chemistry::data::Hamiltonian create_ppp_hamiltonian(const qdk::chemistry::data::LatticeGraph &lattice, EpsT &&epsilon_in, TT &&t_in, UT &&U_in, VT &&V_in, ZT &&z_in)

Create a Pariser-Parr-Pople (PPP) model Hamiltonian.

Template Parameters:
  • EpsT – double or Eigen::VectorXd

  • TT – double or Eigen::MatrixXd

  • UT – double or Eigen::VectorXd

  • VT – double or Eigen::MatrixXd

  • ZT – double or Eigen::VectorXd

Parameters:
  • lattice – Symmetric lattice graph defining the connectivity.

  • epsilon_in – On-site orbital energies. Scalar or VectorXd of size n.

  • t_in – Hopping integrals. Scalar or n x n MatrixXd.

  • U_in – On-site Coulomb repulsion. Scalar or VectorXd of size n.

  • V_in – Intersite Coulomb interaction matrix. Scalar or n x n MatrixXd.

  • z_in – Effective core charges. Scalar or VectorXd of size n.

Returns:

Hamiltonian for the PPP model.

template<typename UT, typename RT>
inline Eigen::MatrixXd mataga_nishimoto_potential(const qdk::chemistry::data::LatticeGraph &lattice, UT &&U, RT &&R, double epsilon_r = 1.0, bool nearest_neighbor_only = false)

Compute the Mataga-Nishimoto intersite potential matrix.

V_ij = U_ij / (1 + U_ij * epsilon_r * R_ij)

where U_ij = sqrt(U_i * U_j) is the geometric mean of on-site parameters.

All parameters should be in atomic units (Hartree for U, Bohr for R).

Template Parameters:
  • UT – double or Eigen::VectorXd

  • RT – double or Eigen::MatrixXd

Parameters:
  • lattice – Lattice graph (used for the number of sites).

  • U – On-site Coulomb parameter(s) in Hartree. Scalar or VectorXd.

  • R – Intersite distances in Bohr. Scalar or n x n MatrixXd.

  • epsilon_r – Relative permittivity (dimensionless, default 1.0).

  • nearest_neighbor_only – If true, restrict to lattice-connected pairs (default false).

Returns:

n x n symmetric MatrixXd of Mataga-Nishimoto potential values in Hartree.

template<typename UT, typename RT>
inline Eigen::MatrixXd ohno_potential(const qdk::chemistry::data::LatticeGraph &lattice, UT &&U, RT &&R, double epsilon_r = 1.0, bool nearest_neighbor_only = false)

Compute the Ohno intersite potential matrix.

V_ij = U_ij / sqrt(1 + (U_ij * epsilon_r * R_ij)^2)

where U_ij = sqrt(U_i * U_j) is the geometric mean of on-site parameters.

All parameters should be in atomic units (Hartree for U, Bohr for R).

Template Parameters:
  • UT – double or Eigen::VectorXd

  • RT – double or Eigen::MatrixXd

Parameters:
  • lattice – Lattice graph (used for the number of sites).

  • U – On-site Coulomb parameter(s) in Hartree. Scalar or VectorXd.

  • R – Intersite distances in Bohr. Scalar or n x n MatrixXd.

  • epsilon_r – Relative permittivity (dimensionless, default 1.0).

  • nearest_neighbor_only – If true, restrict to lattice-connected pairs (default false).

Returns:

n x n symmetric MatrixXd of Ohno potential values in Hartree.

template<typename UT, typename RT, typename PotentialFunc>
inline Eigen::MatrixXd pairwise_potential(const qdk::chemistry::data::LatticeGraph &lattice, UT &&U_in, RT &&R_in, PotentialFunc &&func, bool nearest_neighbor_only = false)

Compute a symmetric pairwise potential matrix from a custom formula.

For each unique pair (i < j), computes the geometric mean U_ij = sqrt(U_i * U_j), reads R_ij, and evaluates func(i, j, U_ij, R_ij). The result is stored symmetrically: V(i,j) = V(j,i).

When nearest_neighbor_only is true, only pairs connected by a lattice edge are evaluated; all other entries remain zero.

Template Parameters:
  • UT – double or Eigen::VectorXd — on-site Coulomb parameter(s).

  • RT – double or Eigen::MatrixXd — intersite distances.

  • PotentialFunc – Callable with signature (int i, int j, double Uij, double Rij) -> double.

Parameters:
  • lattice – Lattice graph defining the connectivity and number of sites.

  • U_in – On-site Coulomb parameter(s). Scalar or VectorXd of size n.

  • R_in – Distance matrix. Scalar or n x n MatrixXd.

  • func – Potential formula to evaluate for each pair.

  • nearest_neighbor_only – If true, restrict to lattice-connected pairs (default false).

Throws:

std::invalid_argument – if U size or R dimensions mismatch.

Returns:

n x n symmetric MatrixXd of pairwise potential values.

namespace detail

Functions

template<typename EpsT, typename TT, typename UT>
inline std::tuple<Eigen::SparseMatrix<double>, qdk::chemistry::data::SparseHamiltonianContainer::TwoBodyMap> _build_hubbard_integrals(const qdk::chemistry::data::LatticeGraph &lattice, EpsT &&epsilon_in, TT &&t_in, UT &&U_in)

Construct a Hubbard Hamiltonian on a lattice.

Extends the Hückel model with on-site electron-electron repulsion: H = H_huckel + U sum_i n_{i,up} n_{i,down}

Template Parameters:
  • EpsT – double or Eigen::VectorXd

  • TT – double or Eigen::MatrixXd

  • UT – double or Eigen::VectorXd

Parameters:
  • lattice – Symmetric lattice graph defining the connectivity.

  • epsilon_in – On-site orbital energies. Scalar or VectorXd of size n.

  • t_in – Hopping integrals. Scalar or n x n MatrixXd.

  • U_in – On-site Coulomb repulsion. Scalar or VectorXd of size n.

Throws:

std::invalid_argument – if U vector size mismatches the number of sites.

Returns:

Tuple of (sparse one-body matrix, two-body map).

template<typename EpsT, typename TT>
inline Eigen::SparseMatrix<double> _build_huckel_integrals(const qdk::chemistry::data::LatticeGraph &lattice, EpsT &&epsilon_in, TT &&t_in)

Construct a Hückel Hamiltonian on a lattice.

Builds the one-body Hamiltonian: H = sum_i epsilon_i n_i - sum_{<i,j>} t_ij (a_i^dag a_j + a_j^dag a_i) where n_i = sum_sigma a_{i,sigma}^dag a_{i,sigma} and the sum over <i,j> runs over edges of the lattice graph.

Template Parameters:
  • EpsT – double or Eigen::VectorXd

  • TT – double or Eigen::MatrixXd

Parameters:
  • lattice – Symmetric lattice graph defining the connectivity.

  • epsilon_in – On-site orbital energies. Scalar or VectorXd of size n.

  • t_in – Hopping integrals. Scalar or n x n MatrixXd.

Throws:

std::invalid_argument – if dimensions mismatch, lattice is asymmetric, or empty.

Returns:

Sparse one-body integral matrix (n x n).

template<typename EpsT, typename TT, typename UT, typename VT, typename ZT>
inline std::tuple<Eigen::SparseMatrix<double>, qdk::chemistry::data::SparseHamiltonianContainer::TwoBodyMap, double> _build_ppp_integrals(const qdk::chemistry::data::LatticeGraph &lattice, EpsT &&epsilon_in, TT &&t_in, UT &&U_in, VT &&V_in, ZT &&z_in)

Construct a Pariser-Parr-Pople (PPP) Hamiltonian on a lattice.

Extends the Hubbard model with long-range intersite Coulomb interactions: H = H_hubbard + 1/2 sum_{i!=j} V_ij (n_i - z_i)(n_j - z_j)

Note

The 1/2 prefactor from the PPP formula is not included in the stored two-body integrals.

Template Parameters:
  • EpsT – double or Eigen::VectorXd

  • TT – double or Eigen::MatrixXd

  • UT – double or Eigen::VectorXd

  • VT – double or Eigen::MatrixXd

  • ZT – double or Eigen::VectorXd

Parameters:
  • lattice – Symmetric lattice graph defining the connectivity.

  • epsilon_in – On-site orbital energies. Scalar or VectorXd of size n.

  • t_in – Hopping integrals. Scalar or n x n MatrixXd.

  • U_in – On-site Coulomb repulsion. Scalar or VectorXd of size n.

  • V_in – Intersite Coulomb interaction matrix. Scalar or n x n MatrixXd.

  • z_in – Effective core charges. Scalar or VectorXd of size n.

Throws:

std::invalid_argument – if V or z dimensions mismatch.

Returns:

Tuple of (sparse one-body matrix, two-body map, energy offset).

inline const Eigen::MatrixXd &to_pair_param(const Eigen::MatrixXd &m, const qdk::chemistry::data::LatticeGraph &lattice, const std::string &name = "parameter")

Convert a per-pair parameter to MatrixXd with validation.

For MatrixXd input, validates that both dimensions match the number of lattice sites and returns a reference to the original matrix. For double input, broadcasts to a constant n x n MatrixXd.

Parameters:
  • m – Per-pair parameter matrix.

  • lattice – Lattice graph whose site count defines the expected size.

  • name – Parameter name used in error messages.

Throws:

std::invalid_argument – if the matrix dimensions do not match.

Returns:

Reference to the validated matrix.

inline Eigen::MatrixXd to_pair_param(double val, const qdk::chemistry::data::LatticeGraph &lattice, const std::string& = "parameter")

Convert a scalar per-pair parameter to a constant n x n MatrixXd.

inline const Eigen::VectorXd &to_site_param(const Eigen::VectorXd &v, const qdk::chemistry::data::LatticeGraph &lattice, const std::string &name = "parameter")

Convert a per-site parameter to VectorXd with validation.

For VectorXd input, validates that the vector length matches the number of lattice sites and returns a reference to the original vector. For double input, broadcasts to a constant VectorXd.

Parameters:
  • v – Per-site parameter vector.

  • lattice – Lattice graph whose site count defines the expected size.

  • name – Parameter name used in error messages.

Throws:

std::invalid_argument – if the vector size does not match.

Returns:

Reference to the validated vector.

inline Eigen::VectorXd to_site_param(double val, const qdk::chemistry::data::LatticeGraph &lattice, const std::string& = "parameter")

Convert a scalar per-site parameter to a constant VectorXd.

Variables

template<typename T>
constexpr bool is_pair_param_v = std::is_same_v<std::decay_t<T>, double> || std::is_same_v<std::decay_t<T>, Eigen::MatrixXd>

True if T (after decay) is double or Eigen::MatrixXd — valid per-pair parameter.

template<typename T>
constexpr bool is_site_param_v = std::is_same_v<std::decay_t<T>, double> || std::is_same_v<std::decay_t<T>, Eigen::VectorXd>

True if T (after decay) is double or Eigen::VectorXd — valid per-site parameter.