qdk_chemistry.data package
QDK/Chemistry data module for quantum chemistry data structures and settings.
This module provides access to core quantum chemistry data types including molecular structures, basis sets, wavefunctions, and computational settings. It serves as the primary interface for managing quantum chemical data within the QDK/Chemistry framework.
Exposed classes are:
Ansatz: Quantum chemical ansatz combining a Hamiltonian and wavefunction for energy calculations.BasisSet: Gaussian basis set definitions for quantum calculations.AOType: Enumeration of basis set types (STO-3G, 6-31G, etc.).CasWavefunctionContainer: Complete Active Space (CAS) wavefunction with CI coefficients and determinants.Circuit: Quantum circuit information.Configuration: Electronic configuration state information.ConfigurationSet: Collection of electronic configurations with associated orbital information.ControlledTimeEvolutionUnitary: Controlled time evolution unitary.CoupledClusterContainer: Container for coupled cluster wavefunction amplitudes and determinants.DataClass: Base data class.ElectronicStructureSettings: Specialized settings for electronic structure calculations.Element: Represents a chemical element with its properties.EnergyExpectationResult: Result for Hamiltonian energy expectation value and variance.Hamiltonian: Quantum mechanical Hamiltonian operator representation.HamiltonianContainer: Abstract base class for different Hamiltonian storage formats.MeasurementData: Measurement bitstring data and metadata for QubitHamiltonian objects.ModelOrbitals: Simple orbital representation for model systems without full basis set information.MP2Container: Container for MP2 wavefunction with Hamiltonian reference and optional amplitudes.Orbitals: Molecular orbital information and properties.OrbitalType: Enumeration of orbital angular momentum types (s, p, d, f, etc.).PauliOperator: Pauli operator (I, X, Y, Z) for quantum operator expressions with arithmetic support.PauliProductFormulaContainer: Container for Pauli product formula representation of time evolution unitary.QpeResult: Result of quantum phase estimation workflows, including phase, energy, and metadata.QuantumErrorProfile: Information about quantum gates and error properties.QubitHamiltonian: Molecular electronic Hamiltonians mapped to qubits.SciWavefunctionContainer: Selected Configuration Interaction (SCI) wavefunction with CI coefficients.Settings: Configuration settings for quantum chemistry calculations.SettingValue: Type-safe variant for storing different setting value types.Shell: Individual shell within a basis set.SlaterDeterminantContainer: Single Slater determinant wavefunction representation.StabilityResult: Result of stability analysis for electronic structure calculations.Structure: Molecular structure and geometry information.TimeEvolutionUnitary: Time evolution unitary.TimeEvolutionUnitaryContainer: Abstract base class for different time evolution unitary representation.Wavefunction: Electronic wavefunction data and coefficients.WavefunctionContainer: Abstract base class for different wavefunction representations.WavefunctionType: Enumeration of wavefunction types (SelfDual, NotSelfDual).
Exposed exceptions are:
SettingNotFound/SettingNotFoundError: Raised when a requested setting is not found.SettingTypeMismatch/SettingTypeMismatchError: Raised when a setting value has an incorrect type.
- class qdk_chemistry.data.AOType
Bases:
pybind11_objectEnumeration of atomic orbital types
Members:
Spherical : Spherical harmonics (2l+1 functions per shell)
Cartesian : Cartesian coordinates (more functions for l>=2)
- Cartesian = <AOType.Cartesian: 1>
- Spherical = <AOType.Spherical: 0>
- __init__(self: qdk_chemistry.data.AOType, value: SupportsInt) None
- AOType.name -> str
- property value
- class qdk_chemistry.data.Ansatz
Bases:
DataClassRepresents 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 (MCSCF) calculations
Coupled cluster calculations
Energy expectation value computations
Examples
Create an
AnsatzfromHamiltonianandWavefunction:>>> import qdk_chemistry.data as data >>> # Assuming you have hamiltonian and wavefunction objects >>> ansatz = data.Ansatz(hamiltonian, wavefunction) True
Create from shared pointers:
>>> ansatz2 = data.Ansatz(hamiltonian_ptr, wavefunction_ptr)
Access components:
>>> h = ansatz.get_hamiltonian() >>> wf = ansatz.get_wavefunction() >>> orbs = ansatz.get_orbitals()
Calculate energy:
>>> energy = ansatz.calculate_energy()
File I/O:
>>> ansatz.to_json_file("ansatz.json") >>> ansatz.to_hdf5_file("ansatz.h5") >>> ansatz2 = data.Ansatz.from_json_file("ansatz.json") >>> ansatz3 = data.Ansatz.from_hdf5_file("ansatz.h5")
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.Ansatz, hamiltonian: qdk_chemistry.data.Hamiltonian, wavefunction: qdk_chemistry.data.Wavefunction) -> None
Constructor with
HamiltonianandWavefunctionobjects.- Parameters:
hamiltonian (qdk_chemistry.data.Hamiltonian) – The Hamiltonian operator for the system
wavefunction (qdk_chemistry.data.Wavefunction) – The wavefunction describing the quantum state
- Raises:
ValueError – If orbital dimensions are inconsistent between Hamiltonian and wavefunction
__init__(self: qdk_chemistry.data.Ansatz, hamiltonian: qdk_chemistry.data.Hamiltonian, wavefunction: qdk_chemistry.data.Wavefunction) -> None
Constructor with shared pointers to Hamiltonian and Wavefunction.
- Parameters:
hamiltonian (qdk_chemistry.data.Hamiltonian) – Shared pointer to the Hamiltonian operator
wavefunction (qdk_chemistry.data.Wavefunction) – Shared pointer to the wavefunction
- Raises:
ValueError – If pointers are None or orbital dimensions are inconsistent
__init__(self: qdk_chemistry.data.Ansatz, other: qdk_chemistry.data.Ansatz) -> None
Copy constructor
- calculate_energy(self: qdk_chemistry.data.Ansatz) float
Calculate the energy expectation value ⟨ψ|H|ψ⟩.
- Returns:
Energy expectation value in atomic units
- Return type:
- Raises:
RuntimeError – If calculation cannot be performed
Notes
This method will be implemented once energy calculation algorithms are available.
- static from_file(filename: object, type: str) qdk_chemistry.data.Ansatz
Load from file based on type parameter.
- Parameters:
filename (str | pathlib.Path) – Path to file to read
type (str) – File format type (“json” or “hdf5”)
- Returns:
New Ansatz loaded from file
- Return type:
- Raises:
RuntimeError – If file doesn’t exist, unsupported type, or I/O error occurs
- static from_hdf5_file(filename: object) qdk_chemistry.data.Ansatz
Load Ansatz from HDF5 file.
- Parameters:
filename (str | pathlib.Path) – Path to HDF5 file to read
- Returns:
Ansatz loaded from file
- Return type:
- Raises:
RuntimeError – If file doesn’t exist or I/O error occurs
- static from_json(json_str: str) qdk_chemistry.data.Ansatz
Load Ansatz from JSON string format.
- Parameters:
json_str (str) – JSON string containing Ansatz data
- Returns:
Ansatz loaded from JSON string
- Return type:
- Raises:
RuntimeError – If JSON string is malformed
- static from_json_file(filename: object) qdk_chemistry.data.Ansatz
Load Ansatz from JSON file.
- Parameters:
filename (str | pathlib.Path) – Path to JSON file to read
- Returns:
Ansatz loaded from file
- Return type:
- Raises:
RuntimeError – If file doesn’t exist or I/O error occurs
- get_hamiltonian(self: qdk_chemistry.data.Ansatz) qdk_chemistry.data.Hamiltonian
Get shared pointer to the Hamiltonian.
- Returns:
Shared pointer to the Hamiltonian object
- Return type:
- Raises:
RuntimeError – If Hamiltonian is not set
- get_orbitals(self: qdk_chemistry.data.Ansatz) qdk_chemistry.data.Orbitals
Get shared pointer to the orbital basis set from the Hamiltonian.
- Returns:
Shared pointer to the Orbitals object
- Return type:
- Raises:
RuntimeError – If orbitals are not available
- get_summary(self: qdk_chemistry.data.Ansatz) str
Get a summary string describing the Ansatz object.
- Returns:
Human-readable summary of the Ansatz object
- Return type:
- get_wavefunction(self: qdk_chemistry.data.Ansatz) qdk_chemistry.data.Wavefunction
Get shared pointer to the wavefunction.
- Returns:
Shared pointer to the Wavefunction object
- Return type:
- Raises:
RuntimeError – If wavefunction is not set
- property hamiltonian
Get shared pointer to the Hamiltonian.
- Returns:
Shared pointer to the Hamiltonian object
- Return type:
- Raises:
RuntimeError – If Hamiltonian is not set
- has_hamiltonian(self: qdk_chemistry.data.Ansatz) bool
Check if Hamiltonian is available.
- Returns:
True if Hamiltonian is set
- Return type:
- has_orbitals(self: qdk_chemistry.data.Ansatz) bool
Check if orbital data is available.
- Returns:
True if orbitals are set in both Hamiltonian and wavefunction
- Return type:
- has_wavefunction(self: qdk_chemistry.data.Ansatz) bool
Check if wavefunction is available.
- Returns:
True if wavefunction is set
- Return type:
- property orbitals
Get shared pointer to the orbital basis set from the Hamiltonian.
- Returns:
Shared pointer to the Orbitals object
- Return type:
- Raises:
RuntimeError – If orbitals are not available
- property summary
Get a summary string describing the Ansatz object.
- Returns:
Human-readable summary of the Ansatz object
- Return type:
- to_file(self: qdk_chemistry.data.Ansatz, filename: object, type: str) None
Save to file based on type parameter.
- Parameters:
filename (str | pathlib.Path) – Path to file to create/overwrite
type (str) – File format type (“json” or “hdf5”)
- Raises:
RuntimeError – If unsupported type or I/O error occurs
- to_hdf5_file(self: qdk_chemistry.data.Ansatz, filename: object) None
Save Ansatz to HDF5 file.
- Parameters:
filename (str | pathlib.Path) – Path to HDF5 file to create/overwrite
- Raises:
RuntimeError – If I/O error occurs
- to_json(self: qdk_chemistry.data.Ansatz) str
Convert Ansatz to JSON string format.
- Returns:
JSON string containing Ansatz data
- Return type:
- to_json_file(self: qdk_chemistry.data.Ansatz, filename: object) None
Save ansatz to JSON file.
- Parameters:
filename (str | pathlib.Path) – Path to JSON file to create/overwrite
- Raises:
RuntimeError – If I/O error occurs
- validate_orbital_consistency(self: qdk_chemistry.data.Ansatz) None
Validate orbital consistency between Hamiltonian and wavefunction.
- Raises:
RuntimeError – If orbital dimensions are inconsistent
- property wavefunction
Get shared pointer to the wavefunction.
- Returns:
Shared pointer to the Wavefunction object
- Return type:
- Raises:
RuntimeError – If wavefunction is not set
- class qdk_chemistry.data.BasisSet
Bases:
DataClassRepresents 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.
Examples
Create a simple basis set:
>>> from qdk_chemistry.data import BasisSet, OrbitalType >>> basis = BasisSet("STO-3G") >>> basis.add_shell(0, OrbitalType.S, 1.0, 1.0) # s orbital on atom 0 >>> print(f"Number of atomic orbitals: {basis.get_num_atomic_orbitals()}")
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.BasisSet, name: str, structure: qdk_chemistry.data.Structure, atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) -> None
Constructor with basis set name, structure, and basis type.
Creates a basis set associated with a molecular structure.
- Parameters:
Examples
>>> from qdk_chemistry.data import Structure >>> structure = Structure.from_xyz_file("water.xyz") >>> basis = BasisSet("cc-pVDZ", structure, AOType.Spherical) >>> print(f"Basis set for {structure.get_num_atoms()} atoms")
__init__(self: qdk_chemistry.data.BasisSet, name: str, shells: collections.abc.Sequence[qdk_chemistry.data.Shell], atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) -> None
Constructor with basis set name, shells, and basis type.
Creates a basis set with predefined shells.
- Parameters:
Examples
>>> shells = [Shell(0, OrbitalType.S), Shell(0, OrbitalType.P)] >>> basis = BasisSet("custom", shells) >>> print(f"Created basis with {len(shells)} shells")
__init__(self: qdk_chemistry.data.BasisSet, name: str, shells: collections.abc.Sequence[qdk_chemistry.data.Shell], structure: qdk_chemistry.data.Structure, atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) -> None
Constructor with basis set name, shells, structure, and basis type.
Creates a complete basis set with shells and molecular structure.
- Parameters:
name (str) – Name of the basis set
shells (list[Shell]) – Vector of shell objects defining the atomic orbitals
structure (Structure) – Molecular structure to associate with this basis set
atomic_orbital_type (AOType | None) – Whether to use spherical or Cartesian atomic orbitals. Default is Spherical
Examples
>>> from qdk_chemistry.data import Structure >>> structure = Structure.from_xyz_file("water.xyz") >>> shells = [Shell(0, OrbitalType.S), Shell(1, OrbitalType.S)] >>> basis = BasisSet("custom", shells, structure) >>> print(f"Complete basis set with {len(shells)} shells")
__init__(self: qdk_chemistry.data.BasisSet, name: str, shells: collections.abc.Sequence[qdk_chemistry.data.Shell], ecp_shells: collections.abc.Sequence[qdk_chemistry.data.Shell], structure: qdk_chemistry.data.Structure, atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) -> None
Constructor with basis set name, shells, ECP shells, structure, and basis type.
Creates a complete basis set with regular shells, ECP shells, and molecular structure.
- Parameters:
name (str) – Name of the basis set
shells (list[Shell]) – Vector of shell objects defining the atomic orbitals
structure (Structure) – Molecular structure to associate with this basis set
atomic_orbital_type (AOType | None) – Whether to use spherical or Cartesian atomic orbitals. Default is Spherical
Examples
>>> from qdk_chemistry.data import Structure >>> structure = Structure.from_xyz_file("water.xyz") >>> shells = [Shell(0, OrbitalType.S), Shell(1, OrbitalType.S)] >>> ecp_shells = [Shell(0, OrbitalType.S, exp, coeff, rpow)] >>> basis = BasisSet("custom-ecp", shells, ecp_shells, structure) >>> print(f"Basis with {len(shells)} shells and {len(ecp_shells)} ECP shells")
__init__(self: qdk_chemistry.data.BasisSet, name: str, shells: collections.abc.Sequence[qdk_chemistry.data.Shell], ecp_name: str, ecp_shells: collections.abc.Sequence[qdk_chemistry.data.Shell], ecp_electrons: collections.abc.Sequence[typing.SupportsInt], structure: qdk_chemistry.data.Structure, atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) -> None
Constructor with basis set name, shells, ECP name, ECP shells, ECP electrons, structure, and basis type.
Creates a complete basis set with regular shells, ECP shells, ECP metadata, and molecular structure.
- Parameters:
name (str) – Name of the basis set
shells (list[Shell]) – Vector of shell objects defining the atomic orbitals
ecp_name (str) – Name of the ECP (basis set)
ecp_electrons (list[int]) – Number of ECP electrons for each atom
structure (Structure) – Molecular structure to associate with this basis set
atomic_orbital_type (AOType | None) – Whether to use spherical or Cartesian atomic orbitals. Default is Spherical
Examples
>>> from qdk_chemistry.data import Structure >>> structure = Structure.from_xyz_file("water.xyz") >>> shells = [Shell(0, OrbitalType.S), Shell(1, OrbitalType.S)] >>> ecp_shells = [Shell(0, OrbitalType.S, exp, coeff, rpow)] >>> ecp_electrons = [10, 10, 0] >>> basis = BasisSet("custom-ecp", shells, "custom-ecp", ecp_shells, ecp_electrons, structure) >>> print(f"Basis with {len(shells)} shells, {len(ecp_shells)} ECP shells, ECP: {basis.get_ecp_name()}")
__init__(self: qdk_chemistry.data.BasisSet, arg0: qdk_chemistry.data.BasisSet) -> None
Copy constructor.
Creates a deep copy of another basis set.
- Parameters:
other (BasisSet) – Basis set to copy
Examples
>>> original = BasisSet("cc-pVDZ") >>> copy = BasisSet(original) >>> print(f"Copied basis set: {copy.get_name()}")
- static atomic_orbital_type_to_string(atomic_orbital_type: qdk_chemistry.data.AOType) str
Convert basis type enum to string representation.
- Parameters:
atomic_orbital_type (AOType) – The basis type enum value
- Returns:
String representation (“Spherical” or “Cartesian”)
- Return type:
Examples
>>> basis_str = BasisSet.atomic_orbital_type_to_string(AOType.Spherical) >>> print(f"Basis type: {basis_str}") # Prints "Spherical"
- basis_to_shell_index(self: qdk_chemistry.data.BasisSet, atomic_orbital_index: SupportsInt) tuple[int, int]
Convert atomic orbital index to shell index and local function index.
- Parameters:
atomic_orbital_index (int) – Global atomic orbital index
- Returns:
Shell index and local function index within that shell
- Return type:
Examples
>>> shell_idx, local_idx = basis_set.basis_to_shell_index(7) >>> print(f"atomic orbital 7: shell {shell_idx}, local index {local_idx}")
- custom_ecp_name = 'custom_ecp'
- custom_name = 'custom_basis_set'
- default_ecp_name = 'default_ecp'
- static from_basis_name(basis_name: str, structure: qdk_chemistry.data.Structure, ecp_name: str = 'default_ecp', atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) qdk_chemistry.data.BasisSet
Create a basis set by name for a molecular structure.
Loads a standard basis set (e.g., “sto-3g”, “cc-pvdz”) for all atoms in the structure.
- Parameters:
basis_name (str) – Name of the basis set (e.g., “sto-3g”, “cc-pvdz”, “6-31g”)
structure (Structure) – Molecular structure
ecp_name (str, optional) – Name of the ECP basis set. Default is “default_ecp”
atomic_orbital_type (AOType, optional) – Whether to use spherical or Cartesian atomic orbitals. Default is Spherical
- Returns:
New basis set instance
- Return type:
- Raises:
ValueError – If basis set name is not recognized or structure is invalid
Examples
>>> from qdk_chemistry.data import Structure >>> structure = Structure.from_xyz_file("water.xyz") >>> basis = BasisSet.from_basis_name("sto-3g", structure) >>> print(f"Created {basis.get_name()} basis with {basis.get_num_shells()} shells")
- static from_element_map(element_to_basis_map: collections.abc.Mapping[str, str], structure: qdk_chemistry.data.Structure, element_to_ecp_map: collections.abc.Mapping[str, str] = {}, atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) qdk_chemistry.data.BasisSet
Create a basis set with different basis sets per element.
Allows specifying different basis sets for different elements in the structure.
- Parameters:
element_to_basis_map (dict[str, str]) – Dictionary mapping element symbols to basis set names. Example: {“H”: “sto-3g”, “O”: “cc-pvdz”}
structure (Structure) – Molecular structure
element_to_ecp_map (dict[str, str], optional) – Dictionary mapping element symbols to ECP basis set names. Default is empty dict
atomic_orbital_type (AOType, optional) – Whether to use spherical or Cartesian atomic orbitals. Default is Spherical
- Returns:
New basis set instance with custom name “custom_basis_set”
- Return type:
- Raises:
ValueError – If any element in structure is not in the map or basis set names are invalid
Examples
>>> from qdk_chemistry.data import Structure >>> structure = Structure.from_xyz_file("water.xyz") >>> basis_map = {"H": "sto-3g", "O": "cc-pvdz"} >>> basis = BasisSet.from_element_map(basis_map, structure) >>> print(f"Created custom basis with {basis.get_num_shells()} shells")
- static from_file(filename: object, type: str) qdk_chemistry.data.BasisSet
Load basis set from file with specified format.
Generic method to load basis set data from a file. The format is determined by the ‘type’ parameter.
- Parameters:
filename (str | pathlib.Path) – Path to the file to read. Must have ‘.basis_set’ before the file extension (e.g.,
sto-3g.basis_set.json,cc-pvdz.basis_set.h5)type (str) – File format type (“json” or “hdf5”)
- Returns:
New BasisSet instance loaded from file
- Return type:
- Raises:
RuntimeError – If the file cannot be opened/read, invalid data format, or unsupported type
Examples
>>> basis_set = BasisSet.from_file("sto-3g.basis_set.json", "json") >>> basis_set = BasisSet.from_file("cc-pvdz.basis_set.h5", "hdf5")
- static from_hdf5_file(filename: object) qdk_chemistry.data.BasisSet
Load basis set from HDF5 file (with validation).
Reads basis set data from an HDF5 file and returns a new BasisSet instance. The file should contain data in the format produced by
to_hdf5_file().- Parameters:
filename (str | pathlib.Path) – Path to the HDF5 file to read. Must have ‘.basis_set’ before the file extension (e.g.,
sto-3g.basis_set.h5,cc-pvdz.basis_set.hdf5)- Returns:
New
BasisSetinstance loaded from file- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid basis set data
Examples
>>> basis_set = BasisSet.from_hdf5_file("sto-3g.basis_set.h5") >>> basis_set = BasisSet.from_hdf5_file("cc-pvdz.basis_set.hdf5")
- static from_index_map(index_to_basis_map: collections.abc.Mapping[typing.SupportsInt, str], structure: qdk_chemistry.data.Structure, index_to_ecp_map: collections.abc.Mapping[typing.SupportsInt, str] = {}, atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) qdk_chemistry.data.BasisSet
Create a basis set with different basis sets per atom index.
Allows specifying different basis sets for individual atoms by their index.
- Parameters:
index_to_basis_map (dict[int, str]) – Dictionary mapping atom indices to basis set names. Example: {0: “sto-3g”, 1: “cc-pvdz”, 2: “sto-3g”}
structure (Structure) – Molecular structure
index_to_ecp_map (dict[int, str], optional) – Dictionary mapping atom indices to ECP basis set names. Default is empty dict
atomic_orbital_type (AOType, optional) – Whether to use spherical or Cartesian atomic orbitals. Default is Spherical
- Returns:
New basis set instance with custom name “custom_basis_set”
- Return type:
- Raises:
ValueError – If any atom index in structure is not in the map or basis set names are invalid
Examples
>>> from qdk_chemistry.data import Structure >>> structure = Structure.from_xyz_file("water.xyz") >>> basis_map = {0: "cc-pvdz", 1: "sto-3g", 2: "sto-3g"} # O at 0, H at 1 and 2 >>> basis = BasisSet.from_index_map(basis_map, structure) >>> print(f"Created custom basis with {basis.get_num_shells()} shells")
- static from_json(json_str: str) qdk_chemistry.data.BasisSet
Load basis set from JSON string.
Parses basis set data from a JSON string and returns a new BasisSet instance. The string should contain JSON data in the format produced by
to_json().- Parameters:
json_str (str) – JSON string containing basis set data
- Returns:
New BasisSet instance loaded from JSON
- Return type:
- Raises:
RuntimeError – If the JSON string is malformed or contains invalid basis set data
Examples
>>> basis_set = BasisSet.from_json('{"name": "STO-3G", "shells": [...]}')
- static from_json_file(filename: object) qdk_chemistry.data.BasisSet
Load basis set from JSON file (with validation).
Reads basis set data from a JSON file and returns a new BasisSet instance. The file should contain JSON data in the format produced by
to_json_file().- Parameters:
filename (str) – Path to the JSON file to read. Must have ‘.basis_set’ before the file extension (e.g.,
sto-3g.basis_set.json,cc-pvdz.basis_set.json)- Returns:
New
BasisSetinstance loaded from file- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid basis set data
Examples
>>> basis_set = BasisSet.from_json_file("sto-3g.basis_set.json") >>> basis_set = BasisSet.from_json_file("my_basis.basis_set.json")
- static get_angular_momentum(orbital_type: qdk_chemistry.data.OrbitalType) int
Get angular momentum quantum number for orbital type.
- Parameters:
orbital_type (OrbitalType) – The orbital type
- Returns:
Angular momentum quantum number l (0=s, 1=p, 2=d, etc.)
- Return type:
Examples
>>> l = BasisSet.get_angular_momentum(OrbitalType.D) >>> print(f"D orbital has l = {l}") # l = 2
- get_atom_index_for_atomic_orbital(self: qdk_chemistry.data.BasisSet, atomic_orbital_index: SupportsInt) int
Get the atom index for a given atomic orbital.
- Parameters:
atomic_orbital_index (int) – Global index of the atomic orbital
- Returns:
- Index of the atom to which this atomic orbital belongs.
Index of the atom to which this atomic orbital belongs
- Return type:
Examples
>>> atom_idx = basis_set.get_atom_index_for_atomic_orbital(3) >>> print(f"atomic orbital 3 belongs to atom {atom_idx}")
- get_atomic_orbital_indices_for_atom(self: qdk_chemistry.data.BasisSet, atom_index: SupportsInt) list[int]
Get all atomic orbital indices for a specific atom.
- Parameters:
atom_index (int) – Index of the atom
- Returns:
Vector of global atomic orbital indices for the atom
- Return type:
Examples
>>> atomic_orbital_indices = basis_set.get_atomic_orbital_indices_for_atom(0) >>> print(f"Atom 0 has atomic orbitals: {atomic_orbital_indices}")
- get_atomic_orbital_info(self: qdk_chemistry.data.BasisSet, atomic_orbital_index: SupportsInt) tuple[int, int]
Get shell index and magnetic quantum number for a atomic orbital.
- Parameters:
atomic_orbital_index (int) – Global index of the atomic orbital
- Returns:
Shell index and magnetic quantum number (m_l) for the atomic orbital
- Return type:
Examples
>>> shell_idx, m_l = basis_set.get_atomic_orbital_info(5) >>> print(f"atomic orbital 5: shell {shell_idx}, m_l = {m_l}")
- get_atomic_orbital_type(self: qdk_chemistry.data.BasisSet) qdk_chemistry.data.AOType
Get the basis type.
- Returns:
Current basis type (Spherical or Cartesian)
- Return type:
Examples
>>> atomic_orbital_type = basis_set.get_atomic_orbital_type() >>> print(f"Basis type: {atomic_orbital_type}")
- get_ecp_electrons(self: qdk_chemistry.data.BasisSet) list[int]
Get the ECP (Effective Core Potential) electrons vector.
Examples
>>> ecp_electrons = basis_set.get_ecp_electrons() >>> print(f"ECP electrons per atom: {ecp_electrons}")
- get_ecp_name(self: qdk_chemistry.data.BasisSet) str
Get the ECP (Effective Core Potential) name.
- Returns:
Name of the ECP (basis set)
- Return type:
Examples
>>> ecp_name = basis_set.get_ecp_name() >>> print(f"ECP: {ecp_name}")
- get_ecp_shell(self: qdk_chemistry.data.BasisSet, shell_index: SupportsInt) qdk_chemistry.data.Shell
Get a specific ECP shell by global index.
- Parameters:
shell_index (int) – Global index of the ECP shell
- Returns:
Reference to the specified ECP shell
- Return type:
- Raises:
IndexError – If ECP shell index is out of range
Examples
>>> ecp_shell = basis_set.get_ecp_shell(0) >>> print(f"First ECP shell has {ecp_shell.get_num_primitives()} primitives")
- get_ecp_shell_indices_for_atom(self: qdk_chemistry.data.BasisSet, atom_index: SupportsInt) list[int]
Get ECP shell indices for a specific atom.
- Parameters:
atom_index (int) – Index of the atom
- Returns:
Vector of ECP shell indices for this atom
- Return type:
Examples
>>> ecp_indices = basis_set.get_ecp_shell_indices_for_atom(0) >>> print(f"Atom 0 ECP shell indices: {ecp_indices}")
- get_ecp_shell_indices_for_atom_and_orbital_type(self: qdk_chemistry.data.BasisSet, atom_index: SupportsInt, orbital_type: qdk_chemistry.data.OrbitalType) list[int]
Get ECP shell indices for a specific atom and orbital type.
- Parameters:
atom_index (int) – Index of the atom
orbital_type (OrbitalType) – Type of orbital (S, P, D, F, etc.)
- Returns:
Vector of ECP shell indices matching both criteria
- Return type:
Examples
>>> p_ecp_indices = basis_set.get_ecp_shell_indices_for_atom_and_orbital_type(0, OrbitalType.P) >>> print(f"P-type ECP shells on atom 0: {p_ecp_indices}")
- get_ecp_shell_indices_for_orbital_type(self: qdk_chemistry.data.BasisSet, orbital_type: qdk_chemistry.data.OrbitalType) list[int]
Get ECP shell indices for a specific orbital type.
- Parameters:
orbital_type (OrbitalType) – Type of orbital (S, P, D, F, etc.)
- Returns:
Vector of ECP shell indices of this type
- Return type:
Examples
>>> s_ecp_indices = basis_set.get_ecp_shell_indices_for_orbital_type(OrbitalType.S) >>> print(f"S-type ECP shell indices: {s_ecp_indices}")
- get_ecp_shells(self: qdk_chemistry.data.BasisSet) list[qdk_chemistry.data.Shell]
Get all ECP shells (flattened from per-atom storage).
Examples
>>> ecp_shells = basis_set.get_ecp_shells() >>> print(f"Total ECP shells: {len(ecp_shells)}")
- get_ecp_shells_for_atom(self: qdk_chemistry.data.BasisSet, atom_index: SupportsInt) list[qdk_chemistry.data.Shell]
Get ECP shells for a specific atom.
- Parameters:
atom_index (int) – Index of the atom
- Returns:
Vector of ECP shells for the specified atom
- Return type:
Examples
>>> ecp_atom_shells = basis_set.get_ecp_shells_for_atom(0) >>> print(f"Atom 0 has {len(ecp_atom_shells)} ECP shells")
- get_name(self: qdk_chemistry.data.BasisSet) str
Get the basis set name.
- Returns:
Name of the basis set (e.g., “6-31G”, “cc-pVDZ”)
- Return type:
Examples
>>> name = basis_set.get_name() >>> print(f"Using basis set: {name}")
- get_num_atomic_orbitals(self: qdk_chemistry.data.BasisSet) int
Get total number of atomic orbitals in the basis set.
- Returns:
Total number of atomic orbitals from all shells
- Return type:
Examples
>>> n_basis = basis_set.get_num_atomic_orbitals() >>> print(f"Total atomic orbitals: {n_basis}")
- get_num_atomic_orbitals_for_atom(self: qdk_chemistry.data.BasisSet, atom_index: SupportsInt) int
Get number of atomic orbitals for a specific atom.
- Parameters:
atom_index (int) – Index of the atom
- Returns:
Number of atomic orbitals on the specified atom
- Return type:
Examples
>>> n_funcs = basis_set.get_num_atomic_orbitals_for_atom(0) >>> print(f"Atom 0 has {n_funcs} atomic orbitals")
- get_num_atomic_orbitals_for_orbital_type(self: qdk_chemistry.data.BasisSet, orbital_type: qdk_chemistry.data.OrbitalType) int
Get total number of atomic orbitals for a specific orbital type.
- Parameters:
orbital_type (OrbitalType) – Type of orbital (S, P, D, F, etc.)
- Returns:
Total number of atomic orbitals of the specified type
- Return type:
Examples
>>> n_p_funcs = basis_set.get_num_atomic_orbitals_for_orbital_type(OrbitalType.P) >>> print(f"Total P-type atomic orbitals: {n_p_funcs}")
- get_num_atoms(self: qdk_chemistry.data.BasisSet) int
Get number of atoms that have shells.
- Returns:
Number of atoms with shells
- Return type:
Examples
>>> n_atoms = basis_set.get_num_atoms() >>> print(f"Atoms with atomic orbitals: {n_atoms}")
- get_num_ecp_shells(self: qdk_chemistry.data.BasisSet) int
Get total number of ECP shells across all atoms.
- Returns:
Total number of ECP shells
- Return type:
Examples
>>> n_ecp_shells = basis_set.get_num_ecp_shells() >>> print(f"Total ECP shells: {n_ecp_shells}")
- static get_num_orbitals_for_l(l: SupportsInt, atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) int
Get number of orbitals for given angular momentum.
- Parameters:
- Returns:
Number of orbital functions
- Return type:
Examples
>>> # For d orbitals (l=2) >>> n_sph = BasisSet.get_num_orbitals_for_l(2, AOType.Spherical) # 5 >>> n_cart = BasisSet.get_num_orbitals_for_l(2, AOType.Cartesian) # 6 >>> print(f"d orbitals: {n_sph} spherical, {n_cart} Cartesian")
- get_num_shells(self: qdk_chemistry.data.BasisSet) int
Get total number of shells across all atoms.
- Returns:
Total number of shells
- Return type:
Examples
>>> n_shells = basis_set.get_num_shells() >>> print(f"Total shells: {n_shells}")
- get_shell(self: qdk_chemistry.data.BasisSet, shell_index: SupportsInt) qdk_chemistry.data.Shell
Get a specific shell by global index.
- Parameters:
shell_index (int) – Global index of the shell
- Returns:
Reference to the specified shell
- Return type:
- Raises:
IndexError – If shell index is out of range
Examples
>>> shell = basis_set.get_shell(0) >>> print(f"First shell type: {shell.orbital_type}")
- get_shell_indices_for_atom(self: qdk_chemistry.data.BasisSet, atom_index: SupportsInt) list[int]
Get shell indices for a specific atom.
- Parameters:
atom_index (int) – Index of the atom
- Returns:
Vector of global shell indices for the atom
- Return type:
Examples
>>> shell_indices = basis_set.get_shell_indices_for_atom(0) >>> print(f"Atom 0 has shells: {shell_indices}")
- get_shell_indices_for_atom_and_orbital_type(self: qdk_chemistry.data.BasisSet, atom_index: SupportsInt, orbital_type: qdk_chemistry.data.OrbitalType) list[int]
Get shell indices for a specific atom and orbital type.
- Parameters:
atom_index (int) – Index of the atom
orbital_type (OrbitalType) – Type of orbital (S, P, D, F, etc.)
- Returns:
Vector of shell indices matching both criteria
- Return type:
Examples
>>> p_shell_indices = basis_set.get_shell_indices_for_atom_and_orbital_type(0, OrbitalType.P) >>> print(f"P-shells on atom 0: {p_shell_indices}")
- get_shell_indices_for_orbital_type(self: qdk_chemistry.data.BasisSet, orbital_type: qdk_chemistry.data.OrbitalType) list[int]
Get shell indices for a specific orbital type.
- Parameters:
orbital_type (OrbitalType) – Type of orbital (S, P, D, F, etc.)
- Returns:
Vector of shell indices with the specified orbital type
- Return type:
Examples
>>> p_shells = basis_set.get_shell_indices_for_orbital_type(OrbitalType.P) >>> print(f"P-shell indices: {p_shells}")
- get_shells(self: qdk_chemistry.data.BasisSet) list[qdk_chemistry.data.Shell]
Get all shells (flattened from per-atom storage).
Examples
>>> shells = basis_set.get_shells() >>> print(f"Total shells: {len(shells)}")
- get_shells_for_atom(self: qdk_chemistry.data.BasisSet, atom_index: SupportsInt) list[qdk_chemistry.data.Shell]
Get shells for a specific atom.
- Parameters:
atom_index (int) – Index of the atom
- Returns:
Vector of shells for the specified atom
- Return type:
Examples
>>> atom_shells = basis_set.get_shells_for_atom(0) >>> print(f"Atom 0 has {len(atom_shells)} shells")
- get_structure(self: qdk_chemistry.data.BasisSet) qdk_chemistry.data.Structure
Get the molecular structure.
- Returns:
The molecular structure associated with this basis set
- Return type:
- Raises:
RuntimeError – If no structure is associated with this basis set
Examples
>>> structure = basis_set.get_structure() >>> print(f"Number of atoms: {structure.get_num_atoms()}")
- get_summary(self: qdk_chemistry.data.BasisSet) str
Get summary string of basis set information.
- Returns:
Human-readable summary of basis set properties
- Return type:
Examples
>>> summary = basis_set.get_summary() >>> print(summary)
- static get_supported_basis_set_names() list[str]
Get list of supported basis set names.
Examples
>>> supported = BasisSet.get_supported_basis_set_names()
- static get_supported_elements_for_basis_set(basis_name: str) list[qdk_chemistry.data.Element]
Get list of supported elements for a given basis set.
Returns all elements that are defined for the specified basis set.
- Parameters:
basis_name (str) – Name of the basis set (e.g., “sto-3g”, “cc-pvdz”)
- Returns:
Vector of supported elements as Element enum values
- Return type:
Examples
>>> elements = BasisSet.get_supported_elements_for_basis_set("sto-3g") >>> print(f"STO-3G supports: {[elem.name for elem in elements]}")
- has_ecp_electrons(self: qdk_chemistry.data.BasisSet) bool
Check if ECP (Effective Core Potential) electrons are present.
- Returns:
True if ECP electrons are present, False otherwise
- Return type:
Examples
>>> if basis_set.has_ecp_electrons(): ... ecp_electrons = basis_set.get_ecp_electrons() ... print(f"ECP electrons per atom: {ecp_electrons}")
- has_ecp_shells(self: qdk_chemistry.data.BasisSet) bool
Check if this basis set has ECP shells.
- Returns:
True if there are any ECP shells
- Return type:
Examples
>>> if basis_set.has_ecp_shells(): ... print("This basis set includes ECP shells")
- has_structure(self: qdk_chemistry.data.BasisSet) bool
Check if a structure is associated with this basis set.
- Returns:
True if a molecular structure is set, False otherwise
- Return type:
Examples
>>> if basis_set.has_structure(): ... structure = basis_set.get_structure() ... else: ... print("No structure associated with basis set")
- static l_to_orbital_type(l: SupportsInt) qdk_chemistry.data.OrbitalType
Get orbital type for angular momentum quantum number.
- Parameters:
l (int) – Angular momentum quantum number
- Returns:
Corresponding orbital type (S, P, D, etc.)
- Return type:
- Raises:
ValueError – If l is negative or exceeds supported range
Examples
>>> orbital_type = BasisSet.l_to_orbital_type(2) >>> print(f"l=2 corresponds to orbital type: {orbital_type}") # D
- static orbital_type_to_string(orbital_type: qdk_chemistry.data.OrbitalType) str
Convert orbital type enum to string representation.
- Parameters:
orbital_type (OrbitalType) – The orbital type enum value
- Returns:
String representation (e.g., “S”, “P”, “D”, “F”)
- Return type:
Examples
>>> orbital_str = BasisSet.orbital_type_to_string(OrbitalType.P) >>> print(f"Orbital type: {orbital_str}") # Prints "P"
- static string_to_atomic_orbital_type(basis_string: str) qdk_chemistry.data.AOType
Convert string to basis type enum.
- Parameters:
basis_string (str) – String representation (“Spherical” or “Cartesian”)
- Returns:
Corresponding basis type enum
- Return type:
- Raises:
ValueError – If the string does not correspond to a valid basis type
Examples
>>> atomic_orbital_type = BasisSet.string_to_atomic_orbital_type("Cartesian") >>> print(atomic_orbital_type) # AOType.Cartesian
- static string_to_orbital_type(orbital_string: str) qdk_chemistry.data.OrbitalType
Convert string to orbital type enum.
- Parameters:
orbital_string (str) – String representation of orbital type (e.g., “S”, “P”, “D”)
- Returns:
Corresponding orbital type enum
- Return type:
- Raises:
ValueError – If the string does not correspond to a valid orbital type
Examples
>>> orbital_type = BasisSet.string_to_orbital_type("P") >>> print(orbital_type) # OrbitalType.P
- to_file(self: qdk_chemistry.data.BasisSet, filename: object, type: str) None
Save basis set to file with specified format.
Generic method to save basis set data to a file. The format is determined by the ‘type’ parameter.
- Parameters:
filename (str | pathlib.Path) – Path to the file to write. Must have ‘.basis_set’ before the file extension (e.g.,
sto-3g.basis_set.json,cc-pvdz.basis_set.h5)type (str) – File format type (“json” or “hdf5”)
- Raises:
RuntimeError – If the basis set data is invalid, unsupported type, or file cannot be opened/written
Examples
>>> basis_set.to_file("sto-3g.basis_set.json", "json") >>> basis_set.to_file("cc-pvdz.basis_set.h5", "hdf5") >>> from pathlib import Path >>> basis_set.to_file(Path("sto-3g.basis_set.json"), "json")
- to_hdf5_file(self: qdk_chemistry.data.BasisSet, filename: object) None
Save basis set to HDF5 file (with validation).
Writes all basis set data to an HDF5 file, preserving numerical precision. HDF5 format is efficient for large datasets and supports hierarchical data structures, making it ideal for storing basis set information.
- Parameters:
filename (str | pathlib.Path) – Path to the HDF5 file to write. Must have ‘.basis_set’ before the file extension (e.g.,
sto-3g.basis_set.h5,cc-pvdz.basis_set.hdf5)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the basis set data is invalid or the file cannot be opened/written
Examples
>>> basis_set.to_hdf5_file("sto-3g.basis_set.h5") >>> basis_set.to_hdf5_file("cc-pvdz.basis_set.hdf5") >>> from pathlib import Path >>> basis_set.to_hdf5_file(Path("sto-3g.basis_set.h5"))
- to_json(self: qdk_chemistry.data.BasisSet) str
Convert basis set to JSON string.
Serializes all basis set information to a JSON string format. JSON is human-readable and suitable for debugging or data exchange.
- Returns:
JSON string representation of the basis set data
- Return type:
- Raises:
RuntimeError – If the basis set data is invalid
Examples
>>> json_str = basis_set.to_json() >>> print(json_str) # Pretty-printed JSON
- to_json_file(self: qdk_chemistry.data.BasisSet, filename: object) None
Save basis set to JSON file (with validation).
Writes all basis set data to a JSON file with pretty formatting. The file will be created or overwritten if it already exists.
- Parameters:
filename (str) – Path to the JSON file to write. Must have ‘.basis_set’ before the file extension (e.g.,
sto-3g.basis_set.json,cc-pvdz.basis_set.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the basis set data is invalid or the file cannot be opened/written
Examples
>>> basis_set.to_json_file("sto-3g.basis_set.json") >>> basis_set.to_json_file("my_basis.basis_set.json")
- class qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer
Bases:
HamiltonianContainerRepresents a molecular Hamiltonian with canonical 4-center 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
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 is the standard full integral storage format where two-electron integrals are stored as a flattened [norb^4] vector.
Examples
>>> import numpy as np >>> # Create restricted Hamiltonian >>> one_body = np.random.rand(4, 4) # 4 orbitals >>> two_body = np.random.rand(256) # 4^4 elements >>> fock_matrix = np.random.rand(4, 4) >>> container = CanonicalFourCenterHamiltonianContainer( ... one_body, two_body, orbitals, 10.5, fock_matrix ... ) >>> # Wrap in Hamiltonian interface >>> hamiltonian = Hamiltonian(container)
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer, one_body_integrals: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], two_body_integrals: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], orbitals: qdk_chemistry.data.Orbitals, core_energy: typing.SupportsFloat, inactive_fock_matrix: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], type: qdk_chemistry.data.HamiltonianType = <HamiltonianType.Hermitian: 0>) -> None
Constructor for restricted active space Hamiltonian with 4-center integrals.
- Parameters:
one_body_integrals (numpy.ndarray) – One-electron integrals matrix [norb x norb]
two_body_integrals (numpy.ndarray) – Two-electron integrals vector [norb^4]
orbitals (Orbitals) – Molecular orbital data
core_energy (float) – Core energy (nuclear repulsion + inactive orbitals)
inactive_fock_matrix (numpy.ndarray) – Inactive Fock matrix [norb x norb]
type (HamiltonianType, optional) – Type of Hamiltonian (Hermitian by default)
Examples
>>> import numpy as np >>> one_body = np.random.rand(4, 4) >>> two_body = np.random.rand(256) >>> fock_matrix = np.random.rand(4, 4) >>> container = CanonicalFourCenterHamiltonianContainer( ... one_body, two_body, orbitals, 10.5, fock_matrix ... )
__init__(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer, one_body_integrals_alpha: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], one_body_integrals_beta: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], two_body_integrals_aaaa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], two_body_integrals_aabb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], two_body_integrals_bbbb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], orbitals: qdk_chemistry.data.Orbitals, core_energy: typing.SupportsFloat, inactive_fock_matrix_alpha: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], inactive_fock_matrix_beta: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], type: qdk_chemistry.data.HamiltonianType = <HamiltonianType.Hermitian: 0>) -> None
Constructor for unrestricted active space Hamiltonian with 4-center integrals.
- Parameters:
one_body_integrals_alpha (numpy.ndarray) – Alpha one-electron integrals [norb x norb]
one_body_integrals_beta (numpy.ndarray) – Beta one-electron integrals [norb x norb]
two_body_integrals_aaaa (numpy.ndarray) – Alpha-alpha-alpha-alpha integrals [norb^4]
two_body_integrals_aabb (numpy.ndarray) – Alpha-beta-alpha-beta integrals [norb^4]
two_body_integrals_bbbb (numpy.ndarray) – Beta-beta-beta-beta integrals [norb^4]
orbitals (Orbitals) – Molecular orbital data
core_energy (float) – Core energy (nuclear repulsion + inactive orbitals)
inactive_fock_matrix_alpha (numpy.ndarray) – Alpha inactive Fock matrix [norb x norb]
inactive_fock_matrix_beta (numpy.ndarray) – Beta inactive Fock matrix [norb x norb]
type (HamiltonianType, optional) – Type of Hamiltonian (Hermitian by default)
Examples
>>> import numpy as np >>> one_body_a = np.random.rand(4, 4) >>> one_body_b = np.random.rand(4, 4) >>> two_body_aaaa = np.random.rand(256) >>> two_body_aabb = np.random.rand(256) >>> two_body_bbbb = np.random.rand(256) >>> fock_a = np.random.rand(4, 4) >>> fock_b = np.random.rand(4, 4) >>> container = CanonicalFourCenterHamiltonianContainer( ... one_body_a, one_body_b, ... two_body_aaaa, two_body_aabb, two_body_bbbb, ... orbitals, 10.5, fock_a, fock_b ... )
- get_two_body_element(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer, i: SupportsInt, j: SupportsInt, k: SupportsInt, l: SupportsInt, channel: qdk_chemistry.data.SpinChannel = <SpinChannel.aaaa: 2>) float
Get specific two-electron integral element <ij|kl>.
- get_two_body_integrals(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get two-electron integrals in molecular orbital basis.
- Returns:
Tuple of two-electron integral vectors [norb^4] for aaaa, aabb, and bbbb spin channels.
- Return type:
Notes
Integrals are stored as flattened vectors in chemist notation <ij|kl> where indices are ordered as i + j*norb + k*norb^2 + l*norb^3
- has_two_body_integrals(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer) bool
Check if two-body integrals are available.
- Returns:
True if two-body integrals have been set
- Return type:
- is_restricted(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer) bool
Check if Hamiltonian is restricted (alpha == beta).
- Returns:
True if alpha and beta integrals are identical
- Return type:
- is_valid(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer) bool
Check if the Hamiltonian data is complete and consistent.
- Returns:
True if all required data is set and dimensions are consistent
- Return type:
- to_fcidump_file(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer, filename: str, nalpha: SupportsInt, nbeta: SupportsInt) None
Save Hamiltonian to FCIDUMP file.
- to_json(self: qdk_chemistry.data.CanonicalFourCenterHamiltonianContainer) str
Convert container to JSON string.
- Returns:
JSON representation of the container
- Return type:
- property two_body_integrals
Get two-electron integrals in molecular orbital basis.
- Returns:
Tuple of two-electron integral vectors [norb^4] for aaaa, aabb, and bbbb spin channels.
- Return type:
Notes
Integrals are stored as flattened vectors in chemist notation <ij|kl> where indices are ordered as i + j*norb + k*norb^2 + l*norb^3
- class qdk_chemistry.data.CasWavefunctionContainer
Bases:
WavefunctionContainerComplete Active Space (CAS) wavefunction container implementation.
This container represents wavefunctions obtained from complete active space self-consistent field (CASSCF) or complete active space configuration interaction (CASCI) methods.
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.CasWavefunctionContainer, coeffs: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”], dets: collections.abc.Sequence[qdk_chemistry.data.Configuration], orbitals: qdk_chemistry.data.Orbitals, type: qdk_chemistry.data.WavefunctionType = <WavefunctionType.SelfDual: 0>) -> None
Constructs a basic CAS wavefunction container.
- Parameters:
coeffs (numpy.ndarray) – The vector of CI coefficients (real or complex)
dets (list[Configuration]) – The vector of determinants
orbitals (Orbitals) – Shared pointer to orbital basis set
type (WavefunctionType | None) – Type of wavefunction (default: SelfDual)
Examples
>>> import numpy as np >>> coeffs = np.array([0.9, 0.1]) >>> dets = [qdk_chemistry.Configuration("33221100"), qdk_chemistry.Configuration("33221001")] >>> container = qdk_chemistry.CasWavefunctionContainer(coeffs, dets, orbitals)
__init__(self: qdk_chemistry.data.CasWavefunctionContainer, coeffs: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”], dets: collections.abc.Sequence[qdk_chemistry.data.Configuration], orbitals: qdk_chemistry.data.Orbitals, one_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, two_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, type: qdk_chemistry.data.WavefunctionType = <WavefunctionType.SelfDual: 0>) -> None
Constructs a CAS wavefunction container with spin-traced RDMs.
- Parameters:
coeffs (numpy.ndarray) – The vector of CI coefficients (real or complex)
dets (list[Configuration]) – The vector of determinants
orbitals (Orbitals) – Shared pointer to orbital basis set
one_rdm_spin_traced (numpy.ndarray | None) – Spin-traced one-particle reduced density matrix
two_rdm_spin_traced (numpy.ndarray | None) – Spin-traced two-particle reduced density matrix
type (WavefunctionType | None) – Type of wavefunction (default: SelfDual)
Examples
>>> import numpy as np >>> coeffs = np.array([0.9, 0.1]) >>> dets = [qdk_chemistry.Configuration("33221100"), qdk_chemistry.Configuration("33221001")] >>> one_rdm = np.eye(4) # Example 1-RDM >>> container = qdk_chemistry.CasWavefunctionContainer(coeffs, dets, orbitals, one_rdm, None)
__init__(self: qdk_chemistry.data.CasWavefunctionContainer, coeffs: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”], dets: collections.abc.Sequence[qdk_chemistry.data.Configuration], orbitals: qdk_chemistry.data.Orbitals, one_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, one_rdm_aa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, one_rdm_bb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, two_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, two_rdm_aabb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, two_rdm_aaaa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, two_rdm_bbbb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, type: qdk_chemistry.data.WavefunctionType = <WavefunctionType.SelfDual: 0>) -> None
Constructs a CAS wavefunction container with full RDM data.
- Parameters:
coeffs (numpy.ndarray) – The vector of CI coefficients (real or complex)
dets (list[Configuration]) – The vector of determinants
orbitals (Orbitals) – Shared pointer to orbital basis set
one_rdm_spin_traced (numpy.ndarray | None) – Spin-traced one-particle reduced density matrix
one_rdm_aa (numpy.ndarray | None) – Alpha-alpha block of one-particle RDM
one_rdm_bb (numpy.ndarray | None) – Beta-beta block of one-particle RDM
two_rdm_spin_traced (numpy.ndarray | None) – Spin-traced two-particle reduced density matrix
two_rdm_aabb (numpy.ndarray | None) – Alpha-beta-beta-alpha block of two-particle RDM
two_rdm_aaaa (numpy.ndarray | None) – Alpha-alpha-alpha-alpha block of two-particle RDM
two_rdm_bbbb (numpy.ndarray | None) – Beta-beta-beta-beta block of two-particle RDM
type (WavefunctionType | None) – Type of wavefunction (default: SelfDual)
Examples
>>> import numpy as np >>> coeffs = np.array([0.9, 0.1]) >>> dets = [qdk_chemistry.Configuration("33221100"), qdk_chemistry.Configuration("33221001")] >>> container = qdk_chemistry.CasWavefunctionContainer(coeffs, dets, orbitals, ... one_rdm, one_rdm_aa, one_rdm_bb, ... two_rdm, two_rdm_aabb, two_rdm_aaaa, two_rdm_bbbb)
- get_coefficients(self: qdk_chemistry.data.CasWavefunctionContainer) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'] | Annotated[numpy.typing.NDArray[numpy.complex128], '[m, 1]']
Get the coefficients of the wavefunction
- class qdk_chemistry.data.Circuit(qasm=None)
Bases:
DataClassData class for a quantum circuit.
- Parameters:
qasm (str | None)
- __init__(qasm=None)
Initialize a Circuit.
- Parameters:
qasm (str | None) – The quantum circuit in QASM format. Defaults to None.
- Return type:
None
- get_qasm()
Get the quantum circuit in QASM format.
- get_qsharp(remove_idle_qubits=True, remove_classical_qubits=True)
Parse a Circuit object into a qsharp Circuit object with trimming options.
- Return type:
- Parameters:
- Returns:
A qsharp Circuit object representing the trimmed circuit.
- Return type:
qsharp._native.Circuit
- get_summary()
Get a human-readable summary of the Circuit.
- to_json()
Convert the Circuit to a dictionary for JSON serialization.
- to_hdf5(group)
Save the Circuit to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write the quantum circuit to.
- classmethod from_json(json_data)
Create a Circuit from a JSON dictionary.
- Return type:
- Parameters:
json_data (dict[str, Any]) – Dictionary containing the serialized data.
- Returns:
New instance of the Circuit.
- Return type:
- Raises:
RuntimeError – If version field is missing or incompatible.
- classmethod from_hdf5(group)
Load a Circuit from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to read data from.
- Returns:
New instance of the Circuit.
- Return type:
- Raises:
RuntimeError – If version attribute is missing or incompatible.
- class qdk_chemistry.data.Configuration
Bases:
DataClassRepresents a molecular electronic configuration.
This class efficiently stores the occupation pattern of molecular orbitals using a compact representation where each orbital can be in one of four states:
UNOCCUPIED (‘0’): No electrons
ALPHA (‘u’): One alpha electron
BETA (‘d’): One beta electron
DOUBLY (‘2’): Both alpha and beta electrons
The class provides methods for constructing, manipulating, and querying configurations.
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.Configuration) -> None
Default constructor for an empty configuration.
Examples
>>> config = qdk_chemistry.Configuration()
__init__(self: qdk_chemistry.data.Configuration, str: str) -> None
Constructs a configuration from a string representation.
- Parameters:
str (str) –
String representation of the configuration
Where ‘0’ = unoccupied orbital, ‘u’ = alpha-occupied orbital, ‘d’ = beta-occupied orbital, ‘2’ = doubly-occupied orbital
Examples
>>> config = qdk_chemistry.Configuration("22ud0ud") # 7 orbitals with different occupations
- static canonical_hf_configuration(n_alpha: SupportsInt, n_beta: SupportsInt, n_orbitals: SupportsInt) qdk_chemistry.data.Configuration
Create a canonical Hartree-Fock configuration using the Aufbau principle.
Fills orbitals from lowest energy according to the Aufbau principle:
Doubly occupied orbitals for paired electrons
Singly occupied orbitals for unpaired electrons (alpha first if n_alpha > n_beta)
Unoccupied orbitals for remaining positions
- Parameters:
- Returns:
Configuration representing the HF ground state
- Return type:
Examples
>>> config = qdk_chemistry.Configuration.canonical_hf_configuration(3, 2, 5) >>> print(config.to_string()) 22u00
- get_n_electrons(self: qdk_chemistry.data.Configuration) tuple[int, int]
Get the number of alpha and beta electrons in this configuration.
- Returns:
A tuple containing (n_alpha, n_beta)
- Return type:
Examples
>>> config = qdk_chemistry.Configuration("22ud0ud") >>> n_alpha, n_beta = config.get_n_electrons() >>> print(f"Alpha electrons: {n_alpha}, Beta electrons: {n_beta}")
- property n_electrons
Get the number of alpha and beta electrons in this configuration.
- Returns:
A tuple containing (n_alpha, n_beta)
- Return type:
Examples
>>> config = qdk_chemistry.Configuration("22ud0ud") >>> n_alpha, n_beta = config.get_n_electrons() >>> print(f"Alpha electrons: {n_alpha}, Beta electrons: {n_beta}")
- to_binary_strings(self: qdk_chemistry.data.Configuration, num_orbitals: SupportsInt) tuple[str, str]
Convert configuration to separate alpha and beta binary strings.
- Parameters:
num_orbitals (int) – Number of spatial orbitals to use from the configuration
- Returns:
tuple[str, str]
Tuple of binary strings (alpha, beta) where ‘1’ indicates occupied and ‘0’ indicates unoccupied for each spin channel
Examples
>>> config = qdk_chemistry.Configuration("2du0") >>> print(config.to_binary_strings(4)) ("1010", "1100")
- to_string(self: qdk_chemistry.data.Configuration) str
Convert the configuration to a string representation.
- Returns:
String representation
where ‘0’ = unoccupied orbital, ‘u’ = alpha-occupied orbital, ‘d’ = beta-occupied orbital, ‘2’ = doubly-occupied orbital
- Return type:
Examples
>>> config = qdk_chemistry.Configuration("22ud0ud") >>> print(config.to_string()) 22ud0ud
- class qdk_chemistry.data.ConfigurationSet
Bases:
DataClassRepresents a collection of electronic configurations with associated orbital information.
This class manages a set of Configuration objects 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, redundant storage of orbital information is eliminated.
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 a Python list
Immutable after construction to ensure consistency
Common use cases:
Storing selected CI configurations
Representing determinant spaces for multi-reference calculations
Managing configuration lists for projected multi-configuration calculations
Examples
Create a ConfigurationSet from configurations and orbitals:
>>> import qdk_chemistry.data as data >>> configs = [data.Configuration("2200"), data.Configuration("22ud")] >>> config_set = data.ConfigurationSet(configs, orbitals)
Access configurations:
>>> len(config_set) # Number of configurations 2 >>> config_set[0] # First configuration >>> for config in config_set: ... print(config.to_string())
Get orbital information:
>>> orbs = config_set.get_orbitals()
File I/O:
>>> config_set.to_json_file("configs.json") >>> config_set.to_hdf5_file("configs.h5") >>> loaded = data.ConfigurationSet.from_json_file("configs.json")
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.ConfigurationSet, configurations: collections.abc.Sequence[qdk_chemistry.data.Configuration], orbitals: qdk_chemistry.data.Orbitals) -> None
Construct a ConfigurationSet from configurations and orbital information.
- Parameters:
configurations (list[Configuration]) – List of Configuration objects representing the active space
orbitals (Orbitals) – Orbitals object defining the single-particle basis
- Raises:
ValueError – If configurations are inconsistent with active space or if orbitals is None
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.
Examples
>>> configs = [Configuration("2200"), Configuration("22ud")] >>> config_set = ConfigurationSet(configs, orbitals)
__init__(self: qdk_chemistry.data.ConfigurationSet, other: qdk_chemistry.data.ConfigurationSet) -> None
Copy constructor
- at(self: qdk_chemistry.data.ConfigurationSet, idx: SupportsInt) qdk_chemistry.data.Configuration
Access configuration by index with bounds checking.
- Parameters:
idx (int) – Index of the configuration
- Returns:
The configuration at the given index
- Return type:
- Raises:
IndexError – If index is out of range
- property configurations
Get the list of configurations.
- Returns:
List of Configuration objects in the set
- Return type:
- empty(self: qdk_chemistry.data.ConfigurationSet) bool
Check if the set is empty.
- Returns:
True if the set contains no configurations
- Return type:
- static from_file(filename: object, type: str) qdk_chemistry.data.ConfigurationSet
Load from file based on type parameter.
- Parameters:
filename (str | pathlib.Path) – Path to file to read
type (str) – File format type (“json” or “hdf5”)
- Returns:
New ConfigurationSet loaded from file
- Return type:
- Raises:
RuntimeError – If file doesn’t exist, unsupported type, or I/O error occurs
- static from_hdf5_file(filename: object) qdk_chemistry.data.ConfigurationSet
Load ConfigurationSet from HDF5 file.
- Parameters:
filename (str | pathlib.Path) – Path to HDF5 file to read
- Returns:
ConfigurationSet loaded from file
- Return type:
- Raises:
RuntimeError – If file doesn’t exist or I/O error occurs
- static from_json(json_str: str) qdk_chemistry.data.ConfigurationSet
Load ConfigurationSet from JSON string format.
- Parameters:
json_str (str) – JSON string containing ConfigurationSet data
- Returns:
ConfigurationSet loaded from JSON string
- Return type:
- Raises:
RuntimeError – If JSON string is malformed
- static from_json_file(filename: object) qdk_chemistry.data.ConfigurationSet
Load ConfigurationSet from JSON file.
- Parameters:
filename (str | pathlib.Path) – Path to JSON file to read
- Returns:
ConfigurationSet loaded from file
- Return type:
- Raises:
RuntimeError – If file doesn’t exist or I/O error occurs
- get_configurations(self: qdk_chemistry.data.ConfigurationSet) list[qdk_chemistry.data.Configuration]
Get the list of configurations.
- Returns:
List of Configuration objects in the set
- Return type:
- get_orbitals(self: qdk_chemistry.data.ConfigurationSet) qdk_chemistry.data.Orbitals
Get the orbital information.
- Returns:
Shared pointer to the Orbitals object
- Return type:
- get_summary(self: qdk_chemistry.data.ConfigurationSet) str
Get a summary string describing the ConfigurationSet.
- Returns:
Human-readable summary of the ConfigurationSet
- Return type:
- property orbitals
Get the orbital information.
- Returns:
Shared pointer to the Orbitals object
- Return type:
- property summary
Get a summary string describing the ConfigurationSet.
- Returns:
Human-readable summary of the ConfigurationSet
- Return type:
- to_file(self: qdk_chemistry.data.ConfigurationSet, filename: object, type: str) None
Save to file based on type parameter.
- Parameters:
filename (str | pathlib.Path) – Path to file to create/overwrite
type (str) – File format type (“json” or “hdf5”)
- Raises:
RuntimeError – If unsupported type or I/O error occurs
- to_hdf5_file(self: qdk_chemistry.data.ConfigurationSet, filename: object) None
Save ConfigurationSet to HDF5 file.
- Parameters:
filename (str | pathlib.Path) – Path to HDF5 file to create/overwrite
- Raises:
RuntimeError – If I/O error occurs
- to_json(self: qdk_chemistry.data.ConfigurationSet) str
Convert ConfigurationSet to JSON string format.
- Returns:
JSON string containing ConfigurationSet data
- Return type:
- to_json_file(self: qdk_chemistry.data.ConfigurationSet, filename: object) None
Save ConfigurationSet to JSON file.
- Parameters:
filename (str | pathlib.Path) – Path to JSON file to create/overwrite
- Raises:
RuntimeError – If I/O error occurs
- class qdk_chemistry.data.ControlledTimeEvolutionUnitary(time_evolution_unitary, control_indices)
Bases:
DataClassData class for a controlled time evolution unitary.
- Parameters:
time_evolution_unitary (TimeEvolutionUnitary)
- __init__(time_evolution_unitary, control_indices)
Initialize a ControlledTimeEvolutionUnitary.
- Parameters:
time_evolution_unitary (TimeEvolutionUnitary) – The time evolution unitary to be controlled.
- get_unitary_container_type()
Get the type of the time evolution unitary container.
- Return type:
- Returns:
The type of the time evolution unitary container.
- get_num_total_qubits()
Get the total number of qubits including control qubits.
- Return type:
- Returns:
The total number of qubits (time evolution qubits + control qubits).
- to_json()
Convert the ControlledTimeEvolutionUnitary to a dictionary for JSON serialization.
- to_hdf5(group)
Save the ControlledTimeEvolutionUnitary to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write the controlled time evolution unitary to
- classmethod from_json(json_data)
Create ControlledTimeEvolutionUnitary from a JSON dictionary.
- classmethod from_hdf5(group)
Load a ControlledTimeEvolutionUnitary from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – The HDF5 group containing the serialized object.
- Returns:
ControlledTimeEvolutionUnitary
- class qdk_chemistry.data.CoupledClusterContainer
Bases:
WavefunctionContainerCoupled cluster wavefunction container implementation.
This container represents a coupled cluster wavefunction with T1 and T2 amplitudes. It supports both restricted and unrestricted coupled cluster methods, optionally storing spin-separated amplitudes as well as reduced density matrices (RDMs).
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.CoupledClusterContainer, orbitals: qdk_chemistry.data.Orbitals, wavefunction: qdk_chemistry.data.Wavefunction, t1_amplitudes: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t2_amplitudes: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None) -> None
Constructs a coupled cluster wavefunction container with amplitudes.
- Parameters:
orbitals (Orbitals) – Shared pointer to orbital basis set
wavefunction (Wavefunction) – Shared pointer to wavefunction
t1_amplitudes (numpy.ndarray, optional) – T1 amplitudes (both alpha, beta spin)
t2_amplitudes (numpy.ndarray, optional) – T2 amplitudes (both alpha, beta spin)
Examples
>>> t1 = np.array([...]) >>> t2 = np.array([...]) >>> container = qdk_chemistry.CoupledClusterContainer( ... orbitals, wfn, t1, t2)
__init__(self: qdk_chemistry.data.CoupledClusterContainer, orbitals: qdk_chemistry.data.Orbitals, wavefunction: qdk_chemistry.data.Wavefunction, t1_amplitudes_aa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t1_amplitudes_bb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t2_amplitudes_abab: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t2_amplitudes_aaaa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t2_amplitudes_bbbb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None) -> None
Constructs a coupled cluster wavefunction container with spin-separated amplitudes.
- Parameters:
orbitals (Orbitals) – Shared pointer to orbital basis set
wavefunction (Wavefunction) – Shared pointer to wavefunction
t1_amplitudes_aa (numpy.ndarray, optional) – Alpha T1 amplitudes
t1_amplitudes_bb (numpy.ndarray, optional) – Beta T1 amplitudes
t2_amplitudes_abab (numpy.ndarray, optional) – Alpha-beta T2 amplitudes
t2_amplitudes_aaaa (numpy.ndarray, optional) – Alpha-alpha T2 amplitudes
t2_amplitudes_bbbb (numpy.ndarray, optional) – Beta-beta T2 amplitudes
Examples
>>> t1_aa = np.array([...]) >>> t1_bb = np.array([...]) >>> t2_abab = np.array([...]) >>> container = qdk_chemistry.CoupledClusterContainer( ... orbitals, wfn, t1_aa, t1_bb, t2_abab, None, None)
__init__(self: qdk_chemistry.data.CoupledClusterContainer, orbitals: qdk_chemistry.data.Orbitals, wavefunction: qdk_chemistry.data.Wavefunction, t1_amplitudes_aa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t1_amplitudes_bb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t2_amplitudes_abab: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t2_amplitudes_aaaa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, t2_amplitudes_bbbb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, one_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, two_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None) -> None
Constructs a coupled cluster wavefunction container with amplitudes and RDMs.
- Parameters:
orbitals (Orbitals) – Shared pointer to orbital basis set
wavefunction (Wavefunction) – Shared pointer to wavefunction
t1_amplitudes_aa (numpy.ndarray, optional) – Alpha T1 amplitudes
t1_amplitudes_bb (numpy.ndarray, optional) – Beta T1 amplitudes
t2_amplitudes_abab (numpy.ndarray, optional) – Alpha-beta T2 amplitudes
t2_amplitudes_aaaa (numpy.ndarray, optional) – Alpha-alpha T2 amplitudes
t2_amplitudes_bbbb (numpy.ndarray, optional) – Beta-beta T2 amplitudes
one_rdm_spin_traced (numpy.ndarray, optional) – Spin-traced one-particle RDM
two_rdm_spin_traced (numpy.ndarray, optional) – Spin-traced two-particle RDM
Examples
>>> t1_aa = np.array([...]) >>> t2_abab = np.array([...]) >>> one_rdm = np.array([...]) >>> container = qdk_chemistry.CoupledClusterContainer( ... orbitals, wfn, t1_aa, None, t2_abab, None, None, one_rdm, None)
- get_t1_amplitudes(self: qdk_chemistry.data.CoupledClusterContainer) tuple
Get T1 amplitudes. In restricted CC, both T1 amplitudes will be identical.
- Returns:
Pair of (alpha, beta) T1 amplitudes
- Return type:
Examples
>>> t1_aa, t1_bb = cc_container.get_t1_amplitudes()
- get_t2_amplitudes(self: qdk_chemistry.data.CoupledClusterContainer) tuple
Get T2 amplitudes. In restricted CC, only the alpha-beta T2 amplitudes will be used.
- Returns:
Tuple of (alpha-beta, alpha-alpha, beta-beta) T2 amplitudes
- Return type:
Examples
>>> t2_abab, t2_aaaa, t2_bbbb = cc_container.get_t2_amplitudes()
- get_wavefunction(self: qdk_chemistry.data.CoupledClusterContainer) qdk_chemistry.data.Wavefunction
Get reference to Wavefunction.
- Returns:
Shared pointer to Wavefunction
- Return type:
Examples
>>> wfn = cc_container.get_wavefunction()
- has_t1_amplitudes(self: qdk_chemistry.data.CoupledClusterContainer) bool
Check if T1 amplitudes are available.
- Returns:
True if T1 amplitudes are available
- Return type:
Examples
>>> if cc_container.has_t1_amplitudes():
… t1_aa, t1_bb = cc_container.get_t1_amplitudes()
- has_t2_amplitudes(self: qdk_chemistry.data.CoupledClusterContainer) bool
Check if T2 amplitudes are available.
- Returns:
True if T2 amplitudes are available
- Return type:
Examples
>>> if cc_container.has_t2_amplitudes(): ... t2 = cc_container.get_t2_amplitudes()
- class qdk_chemistry.data.DataClass
Bases:
DataClassBase class for immutable data classes with common serialization methods.
This abstract base class provides:
Immutability after construction (__setattr__ and __delattr__ protection)
Common implementations of to_json_file, to_hdf5_file, and to_file
Filename validation to enforce naming convention (.<data_type>.<extension>)
Requires derived classes to implement abstract methods
Derived classes MUST implement:
_data_type_name class attribute (e.g., “structure”, “wavefunction”)
_serialization_version class attribute (e.g., “0.1.0”)
- get_summary() -> str
Return a human-readable summary string of the object
- to_json() -> dict[str, Any]
Return a dictionary representation suitable for JSON serialization Use _add_json_version() to include version information
- to_hdf5(group: h5py.Group) -> None
Write the object’s data to an HDF5 group Use _add_hdf5_version() to include version information
- from_json(json_data: dict[str, Any]) -> DataClass
Create an instance from a JSON dictionary Use _validate_json_version() to check version compatibility
- from_hdf5(group: h5py.Group) -> DataClass
Load an instance from an HDF5 group. Use _validate_hdf5_version() to check version compatibility
Derived classes should:
Set all attributes before calling super().__init__()
Call super().__init__() at the end of __init__ to enable immutability
Notes
These methods are pure virtual in the C++ base class and MUST be overridden. The C++ binding will enforce this at runtime.
Filename validation enforces the convention that filenames must include the data type, e.g., “example.structure.json” or “data.wavefunction.h5”
The _serialization_version attribute must be set for each derived class to track serialization format versions independently. Version validation ensures major and minor versions match exactly during deserialization, while allowing patch version differences for backward compatibility.
- __init__()
Initialize the base class and mark instance as initialized.
This must be called by derived classes after setting all attributes.
- Return type:
None
- get_summary()
Get a human-readable summary of the object.
- Return type:
- Returns:
Summary string describing the object’s contents and properties
- Return type:
Note
This method must be implemented by derived classes. The C++ binding enforces this as a pure virtual function.
- to_dict()
Convert the object to a dictionary.
- to_json()
Convert the object to a dictionary for JSON serialization.
- Return type:
- Returns:
Dictionary representation of the object
- Return type:
Note
This method must be implemented by derived classes. The returned dictionary should contain all data needed to reconstruct the object. The C++ binding enforces this as a pure virtual function.
- to_hdf5(group)
Save the object to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write data to
Note
This method must be implemented by derived classes. Use group.attrs for attributes and group.create_dataset() for array data. The C++ binding enforces this as a pure virtual function.
- to_json_file(filename)
Save the object to a JSON file.
- Return type:
- Parameters:
filename (str | pathlib.Path) –
Path to the output JSON file
Must match pattern: <name>.<data_type>.json
- Raises:
ValueError – If filename doesn’t match required pattern
- to_hdf5_file(filename)
Save the object to an HDF5 file.
- Return type:
- Parameters:
filename (str | pathlib.Path) –
Path to the output HDF5 file
Must match pattern: <name>.<data_type>.h5 or <name>.<data_type>.hdf5
- Raises:
ValueError – If filename doesn’t match required pattern
- to_file(filename, format_type)
Save the object to a file with the specified format.
- Return type:
- Parameters:
filename (str | pathlib.Path) –
Path to the output file
Must match pattern: <name>.<data_type>.<extension>
format_type (str) – Format type (“json”, “hdf5”, or “h5”)
- Raises:
ValueError – If format_type is not supported or filename doesn’t match required pattern
- classmethod from_dict(dict_data)
Create an instance from a dictionary.
- classmethod from_json(json_data)
Create an instance from a JSON dictionary.
- Return type:
- Parameters:
json_data (dict[str, Any]) – Dictionary containing the serialized data
- Returns:
New instance of the derived class
- Return type:
Note
This method must be implemented by derived classes. The C++ binding enforces this as a static method requirement.
- classmethod from_json_file(filename)
Load an instance from a JSON file.
- Return type:
- Parameters:
filename (str | pathlib.Path) –
Path to the input JSON file
Must match pattern: <name>.<data_type>.json
- Returns:
New instance of the derived class
- Return type:
- Raises:
ValueError – If filename doesn’t match required pattern
- classmethod from_hdf5(group)
Load an instance from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to read data from
- Returns:
New instance of the derived class
- Return type:
Note
This method must be implemented by derived classes. Read data using group.attrs for attributes and group[key] for datasets. The C++ binding enforces this as a static method requirement.
- classmethod from_hdf5_file(filename)
Load an instance from an HDF5 file.
- Return type:
- Parameters:
filename (str | pathlib.Path) –
Path to the input HDF5 file
Must match pattern: <name>.<data_type>.h5 or <name>.<data_type>.hdf5
- Returns:
New instance of the derived class
- Return type:
- Raises:
ValueError – If filename doesn’t match required pattern
- classmethod from_file(filename, format_type)
Load an instance from a file with the specified format.
- Return type:
- Parameters:
filename (str | pathlib.Path) –
Path to the input file
Must match pattern: <name>.<data_type>.<extension>
format_type (str) – Format type (“json”, “hdf5”, or “h5”)
- Returns:
New instance of the derived class
- Return type:
- Raises:
ValueError – If format_type is not supported or filename doesn’t match required pattern
- class qdk_chemistry.data.ElectronicStructureSettings
Bases:
SettingsBase class for electronic structure algorithms settings.
This class extends the base Settings class with default values commonly used in electronic structure calculations such as basis sets, molecular charge, spin multiplicity, and convergence parameters.
The default settings include:
method: “hf” - The electronic structure method (Hartree-Fock)
charge: 0 - Molecular charge
spin_multiplicity: 1 - Spin multiplicity (2S+1)
basis_set: “def2-svp” - Default basis set
tolerance: 1e-6 - Convergence tolerance
max_iterations: 50 - Maximum number of iterations
These defaults can be overridden by setting new values after instantiation.
Examples
>>> import qdk_chemistry.data as data >>> settings = data.ElectronicStructureSettings() >>> print(settings.method) # "hf" >>> print(settings.basis_set) # "def2-svp" >>> settings.basis_set = "6-31G*" # Override default >>> settings.charge = -1 # Set molecular charge >>> settings.max_iterations = 100 # Increase max iterations
- __init__(self: qdk_chemistry.data.ElectronicStructureSettings) None
Create ElectronicStructureSettings with default values.
Initializes settings with sensible defaults for electronic structure calculations. All defaults can be modified after construction.
- class qdk_chemistry.data.Element
Bases:
pybind11_objectChemical elements enumeration.
This enum represents all chemical elements from hydrogen (1) to oganesson (118). Each element is represented by its atomic number.
Examples
>>> from qdk_chemistry.data import Element >>> Element.H # Hydrogen >>> Element.C # Carbon >>> Element.O # Oxygen
Members:
H : Hydrogen
He : Helium
Li : Lithium
Be : Beryllium
B : Boron
C : Carbon
N : Nitrogen
O : Oxygen
F : Fluorine
Ne : Neon
Na : Sodium
Mg : Magnesium
Al : Aluminum
Si : Silicon
P : Phosphorus
S : Sulfur
Cl : Chlorine
Ar : Argon
K : Potassium
Ca : Calcium
Sc : Scandium
Ti : Titanium
V : Vanadium
Cr : Chromium
Mn : Manganese
Fe : Iron
Co : Cobalt
Ni : Nickel
Cu : Copper
Zn : Zinc
Ga : Gallium
Ge : Germanium
As : Arsenic
Se : Selenium
Br : Bromine
Kr : Krypton
Rb : Rubidium
Sr : Strontium
Y : Yttrium
Zr : Zirconium
Nb : Niobium
Mo : Molybdenum
Tc : Technetium
Ru : Ruthenium
Rh : Rhodium
Pd : Palladium
Ag : Silver
Cd : Cadmium
In : Indium
Sn : Tin
Sb : Antimony
Te : Tellurium
I : Iodine
Xe : Xenon
Cs : Cesium
Ba : Barium
La : Lanthanum
Ce : Cerium
Pr : Praseodymium
Nd : Neodymium
Pm : Promethium
Sm : Samarium
Eu : Europium
Gd : Gadolinium
Tb : Terbium
Dy : Dysprosium
Ho : Holmium
Er : Erbium
Tm : Thulium
Yb : Ytterbium
Lu : Lutetium
Hf : Hafnium
Ta : Tantalum
W : Tungsten
Re : Rhenium
Os : Osmium
Ir : Iridium
Pt : Platinum
Au : Gold
Hg : Mercury
Tl : Thallium
Pb : Lead
Bi : Bismuth
Po : Polonium
At : Astatine
Rn : Radon
Fr : Francium
Ra : Radium
Ac : Actinium
Th : Thorium
Pa : Protactinium
U : Uranium
Np : Neptunium
Pu : Plutonium
Am : Americium
Cm : Curium
Bk : Berkelium
Cf : Californium
Es : Einsteinium
Fm : Fermium
Md : Mendelevium
No : Nobelium
Lr : Lawrencium
Rf : Rutherfordium
Db : Dubnium
Sg : Seaborgium
Bh : Bohrium
Hs : Hassium
Mt : Meitnerium
Ds : Darmstadtium
Rg : Roentgenium
Cn : Copernicium
Nh : Nihonium
Fl : Flerovium
Mc : Moscovium
Lv : Livermorium
Ts : Tennessine
Og : Oganesson
- Ac = <Element.Ac: 89>
- Ag = <Element.Ag: 47>
- Al = <Element.Al: 13>
- Am = <Element.Am: 95>
- Ar = <Element.Ar: 18>
- As = <Element.As: 33>
- At = <Element.At: 85>
- Au = <Element.Au: 79>
- B = <Element.B: 5>
- Ba = <Element.Ba: 56>
- Be = <Element.Be: 4>
- Bh = <Element.Bh: 107>
- Bi = <Element.Bi: 83>
- Bk = <Element.Bk: 97>
- Br = <Element.Br: 35>
- C = <Element.C: 6>
- Ca = <Element.Ca: 20>
- Cd = <Element.Cd: 48>
- Ce = <Element.Ce: 58>
- Cf = <Element.Cf: 98>
- Cl = <Element.Cl: 17>
- Cm = <Element.Cm: 96>
- Cn = <Element.Cn: 112>
- Co = <Element.Co: 27>
- Cr = <Element.Cr: 24>
- Cs = <Element.Cs: 55>
- Cu = <Element.Cu: 29>
- Db = <Element.Db: 105>
- Ds = <Element.Ds: 110>
- Dy = <Element.Dy: 66>
- Er = <Element.Er: 68>
- Es = <Element.Es: 99>
- Eu = <Element.Eu: 63>
- F = <Element.F: 9>
- Fe = <Element.Fe: 26>
- Fl = <Element.Fl: 114>
- Fm = <Element.Fm: 100>
- Fr = <Element.Fr: 87>
- Ga = <Element.Ga: 31>
- Gd = <Element.Gd: 64>
- Ge = <Element.Ge: 32>
- H = <Element.H: 1>
- He = <Element.He: 2>
- Hf = <Element.Hf: 72>
- Hg = <Element.Hg: 80>
- Ho = <Element.Ho: 67>
- Hs = <Element.Hs: 108>
- I = <Element.I: 53>
- In = <Element.In: 49>
- Ir = <Element.Ir: 77>
- K = <Element.K: 19>
- Kr = <Element.Kr: 36>
- La = <Element.La: 57>
- Li = <Element.Li: 3>
- Lr = <Element.Lr: 103>
- Lu = <Element.Lu: 71>
- Lv = <Element.Lv: 116>
- Mc = <Element.Mc: 115>
- Md = <Element.Md: 101>
- Mg = <Element.Mg: 12>
- Mn = <Element.Mn: 25>
- Mo = <Element.Mo: 42>
- Mt = <Element.Mt: 109>
- N = <Element.N: 7>
- Na = <Element.Na: 11>
- Nb = <Element.Nb: 41>
- Nd = <Element.Nd: 60>
- Ne = <Element.Ne: 10>
- Nh = <Element.Nh: 113>
- Ni = <Element.Ni: 28>
- No = <Element.No: 102>
- Np = <Element.Np: 93>
- O = <Element.O: 8>
- Og = <Element.Og: 118>
- Os = <Element.Os: 76>
- P = <Element.P: 15>
- Pa = <Element.Pa: 91>
- Pb = <Element.Pb: 82>
- Pd = <Element.Pd: 46>
- Pm = <Element.Pm: 61>
- Po = <Element.Po: 84>
- Pr = <Element.Pr: 59>
- Pt = <Element.Pt: 78>
- Pu = <Element.Pu: 94>
- Ra = <Element.Ra: 88>
- Rb = <Element.Rb: 37>
- Re = <Element.Re: 75>
- Rf = <Element.Rf: 104>
- Rg = <Element.Rg: 111>
- Rh = <Element.Rh: 45>
- Rn = <Element.Rn: 86>
- Ru = <Element.Ru: 44>
- S = <Element.S: 16>
- Sb = <Element.Sb: 51>
- Sc = <Element.Sc: 21>
- Se = <Element.Se: 34>
- Sg = <Element.Sg: 106>
- Si = <Element.Si: 14>
- Sm = <Element.Sm: 62>
- Sn = <Element.Sn: 50>
- Sr = <Element.Sr: 38>
- Ta = <Element.Ta: 73>
- Tb = <Element.Tb: 65>
- Tc = <Element.Tc: 43>
- Te = <Element.Te: 52>
- Th = <Element.Th: 90>
- Ti = <Element.Ti: 22>
- Tl = <Element.Tl: 81>
- Tm = <Element.Tm: 69>
- Ts = <Element.Ts: 117>
- U = <Element.U: 92>
- V = <Element.V: 23>
- W = <Element.W: 74>
- Xe = <Element.Xe: 54>
- Y = <Element.Y: 39>
- Yb = <Element.Yb: 70>
- Zn = <Element.Zn: 30>
- Zr = <Element.Zr: 40>
- __init__(self: qdk_chemistry.data.Element, value: SupportsInt) None
- Element.name -> str
- property value
- class qdk_chemistry.data.EnergyExpectationResult(energy_expectation_value, energy_variance, expvals_each_term, variances_each_term)
Bases:
DataClassExpectation value and variance for a Hamiltonian energy estimate.
- Parameters:
- expvals_each_term
Expectation values for each term in the Hamiltonian.
- Type:
- variances_each_term
Variances for each term in the Hamiltonian.
- Type:
- __init__(energy_expectation_value, energy_variance, expvals_each_term, variances_each_term)
Initialize an energy expectation result.
- Parameters:
energy_expectation_value (float) – Expectation value of the energy.
energy_variance (float) – Variance of the energy.
expvals_each_term (list[numpy.ndarray]) – Expectation values for each term in the Hamiltonian.
variances_each_term (list[numpy.ndarray]) – Variances for each term in the Hamiltonian.
- Return type:
None
- get_summary()
Get a human-readable summary of the energy expectation result.
- to_json()
Convert energy expectation result to a dictionary for JSON serialization.
- to_hdf5(group)
Save the energy expectation result to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write the energy expectation result to.
- classmethod from_json(json_data)
Create an energy expectation result from a JSON dictionary.
- Return type:
- Parameters:
json_data (dict[str, Any]) – Dictionary containing the serialized data.
- Returns:
New instance reconstructed from JSON data.
- Return type:
- Raises:
RuntimeError – If version field is missing or incompatible.
- classmethod from_hdf5(group)
Load an energy expectation result from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file containing the data.
- Returns:
New instance reconstructed from HDF5 data.
- Return type:
- Raises:
RuntimeError – If version attribute is missing or incompatible.
- class qdk_chemistry.data.Hamiltonian
Bases:
DataClassInterface class for molecular Hamiltonians in the molecular orbital basis.
This class provides a unified interface to molecular Hamiltonian data by wrapping a HamiltonianContainer implementation. It supports:
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
The actual integral storage is handled by the underlying container, which can use different representations (canonical 4-center, density-fitted, etc.).
Examples
>>> # Create a Hamiltonian from a CanonicalFourCenterHamiltonianContainer container >>> container = CanonicalFourCenterHamiltonianContainer(h1, h2, orbitals, e_core, fock) >>> hamiltonian = Hamiltonian(container) >>> >>> # Access integrals through the interface >>> h1_alpha, h1_beta = hamiltonian.get_one_body_integrals >>> core_energy = hamiltonian.get_core_energy
- __init__(self: qdk_chemistry.data.Hamiltonian, container: qdk_chemistry.data.HamiltonianContainer) None
Construct a Hamiltonian from a HamiltonianContainer.
- Parameters:
container (HamiltonianContainer) – The container holding the Hamiltonian data. Ownership is transferred to the Hamiltonian.
Examples
>>> container = CanonicalFourCenterHamiltonianContainer(h1, h2, orbitals, e_core, fock) >>> hamiltonian = Hamiltonian(container)
- property core_energy
Get core energy in atomic units.
- Returns:
Core energy contribution in Hartree
- Return type:
- static from_file(filename: object, type: str) qdk_chemistry.data.Hamiltonian
Load Hamiltonian from file based on type parameter.
- Parameters:
filename (str or pathlib.Path) – Path to file to read
type (str) – File format type (‘json’ or ‘hdf5’)
- Returns:
New Hamiltonian loaded from file
- Return type:
- Raises:
ValueError – If format_type is not supported
RuntimeError – If file doesn’t exist or I/O error occurs
Examples
>>> hamiltonian = Hamiltonian.from_file("water.hamiltonian.json", "json") >>> hamiltonian = Hamiltonian.from_file("molecule.hamiltonian.h5", "hdf5")
- static from_hdf5_file(filename: object) qdk_chemistry.data.Hamiltonian
Load Hamiltonian from HDF5 file.
- Parameters:
filename (str or pathlib.Path) – Path to HDF5 file to read. Must have
.hamiltonianbefore the file extension.- Returns:
New Hamiltonian loaded from file
- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If file doesn’t exist or I/O error occurs
Examples
>>> hamiltonian = Hamiltonian.from_hdf5_file("water.hamiltonian.h5")
- static from_json(json_data: str) qdk_chemistry.data.Hamiltonian
Load Hamiltonian from JSON string.
- Parameters:
json_data (str) – JSON string containing Hamiltonian data
- Returns:
New Hamiltonian loaded from JSON
- Return type:
- Raises:
RuntimeError – If JSON is malformed or contains invalid data
Examples
>>> json_str = hamiltonian.to_json() >>> loaded = Hamiltonian.from_json(json_str)
- static from_json_file(filename: object) qdk_chemistry.data.Hamiltonian
Load Hamiltonian from JSON file.
- Parameters:
filename (str or pathlib.Path) – Path to JSON file to read. Must have
.hamiltonianbefore the file extension.- Returns:
New Hamiltonian loaded from file
- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If file doesn’t exist or I/O error occurs
Examples
>>> hamiltonian = Hamiltonian.from_json_file("water.hamiltonian.json")
- get_container_type(self: qdk_chemistry.data.Hamiltonian) str
Get the type of the underlying container.
- Returns:
Container type identifier (e.g., “canonical_four_center”)
- Return type:
- get_core_energy(self: qdk_chemistry.data.Hamiltonian) float
Get core energy in atomic units.
- Returns:
Core energy contribution in Hartree
- Return type:
- get_inactive_fock_matrix(self: qdk_chemistry.data.Hamiltonian) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']]
Get tuple of inactive Fock matrices (alpha, beta).
- Returns:
Inactive Fock matrices for the active space
- Return type:
- get_one_body_element(self: qdk_chemistry.data.Hamiltonian, i: SupportsInt, j: SupportsInt, channel: qdk_chemistry.data.SpinChannel = <SpinChannel.aa: 0>) float
Get specific one-electron integral element <ij>.
- Parameters:
i (int) – First orbital index
j (int) – Second orbital index
channel (SpinChannel) – Spin channel (aa or bb), defaults to aa
- Returns:
Value of the one-electron integral <ij>
- Return type:
- get_one_body_integrals(self: qdk_chemistry.data.Hamiltonian) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']]
Get tuple of one-electron integrals (alpha, beta) in molecular orbital basis.
- Returns:
One-electron integral matrices [norb x norb] for alpha and beta spin channels.
- Return type:
- Raises:
RuntimeError – If one-body integrals have not been set
Examples
>>> h1_alpha, h1_beta = hamiltonian.get_one_body_integrals >>> print(f"One-body matrix shape: {h1_alpha.shape}")
- get_orbitals(self: qdk_chemistry.data.Hamiltonian) qdk_chemistry.data.Orbitals
Get molecular orbital data.
- Returns:
The orbital data associated with this Hamiltonian
- Return type:
- Raises:
RuntimeError – If orbital data has not been set
- get_summary(self: qdk_chemistry.data.Hamiltonian) str
Get a human-readable summary of the Hamiltonian data.
- Returns:
Multi-line string describing the Hamiltonian properties
- Return type:
- get_two_body_element(self: qdk_chemistry.data.Hamiltonian, i: SupportsInt, j: SupportsInt, k: SupportsInt, l: SupportsInt, channel: qdk_chemistry.data.SpinChannel = <SpinChannel.aaaa: 2>) float
Get specific two-electron integral element <ij|kl>.
- get_two_body_integrals(self: qdk_chemistry.data.Hamiltonian) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get two-electron integrals in molecular orbital basis.
- Returns:
Tuple of two-electron integral vectors [norb^4] for aaaa, aabb, and bbbb spin channels.
- Return type:
- Raises:
RuntimeError – If two-body integrals have not been set
Notes
Integrals are stored as flattened vectors in chemist notation <ij|kl>
- get_type(self: qdk_chemistry.data.Hamiltonian) qdk_chemistry.data.HamiltonianType
Get the type of Hamiltonian (Hermitian or NonHermitian).
- Returns:
The Hamiltonian type
- Return type:
- has_inactive_fock_matrix(self: qdk_chemistry.data.Hamiltonian) bool
Check if inactive Fock matrix is available.
- Returns:
True if inactive Fock matrix has been set
- Return type:
- has_one_body_integrals(self: qdk_chemistry.data.Hamiltonian) bool
Check if one-body integrals are available.
- Returns:
True if one-body integrals have been set
- Return type:
- has_orbitals(self: qdk_chemistry.data.Hamiltonian) bool
Check if orbital data is available.
- Returns:
True if orbital data has been set
- Return type:
- has_two_body_integrals(self: qdk_chemistry.data.Hamiltonian) bool
Check if two-body integrals are available.
- Returns:
True if two-body integrals have been set
- Return type:
- property inactive_fock_matrix
Get tuple of inactive Fock matrices (alpha, beta).
- Returns:
Inactive Fock matrices for the active space
- Return type:
- is_hermitian(self: qdk_chemistry.data.Hamiltonian) bool
Check if the Hamiltonian is Hermitian.
- Returns:
True if the Hamiltonian type is Hermitian
- Return type:
- is_restricted(self: qdk_chemistry.data.Hamiltonian) bool
Check if Hamiltonian is restricted (alpha == beta).
- Returns:
True if alpha and beta integrals are identical
- Return type:
- is_unrestricted(self: qdk_chemistry.data.Hamiltonian) bool
Check if Hamiltonian is unrestricted (alpha != beta).
- Returns:
True if alpha and beta integrals are different
- Return type:
- property one_body_integrals
Get tuple of one-electron integrals (alpha, beta) in molecular orbital basis.
- Returns:
One-electron integral matrices [norb x norb] for alpha and beta spin channels.
- Return type:
- Raises:
RuntimeError – If one-body integrals have not been set
Examples
>>> h1_alpha, h1_beta = hamiltonian.get_one_body_integrals >>> print(f"One-body matrix shape: {h1_alpha.shape}")
- property orbitals
Get molecular orbital data.
- Returns:
The orbital data associated with this Hamiltonian
- Return type:
- Raises:
RuntimeError – If orbital data has not been set
- to_fcidump_file(self: qdk_chemistry.data.Hamiltonian, filename: object, nalpha: SupportsInt, nbeta: SupportsInt) None
Save Hamiltonian to FCIDUMP file.
- Parameters:
filename (str or pathlib.Path) – Path to FCIDUMP file to create/overwrite
nalpha (int) – Number of alpha electrons
nbeta (int) – Number of beta electrons
- Raises:
RuntimeError – If I/O error occurs
Examples
>>> hamiltonian.to_fcidump_file("water.fcidump", 5, 5)
Notes
FCIDUMP format is a standard quantum chemistry format for storing molecular integrals and is widely supported by quantum chemistry codes.
- to_file(self: qdk_chemistry.data.Hamiltonian, filename: object, type: str) None
Save Hamiltonian to file based on type parameter.
- Parameters:
filename (str or pathlib.Path) – Path to file to create/overwrite
type (str) – File format type (‘json’ or ‘hdf5’)
- Raises:
ValueError – If format_type is not supported
RuntimeError – If I/O error occurs
Examples
>>> hamiltonian.to_file("water.hamiltonian.json", "json") >>> hamiltonian.to_file("molecule.hamiltonian.h5", "hdf5")
- to_hdf5_file(self: qdk_chemistry.data.Hamiltonian, filename: object) None
Save Hamiltonian to HDF5 file (with validation).
- Parameters:
filename (str or pathlib.Path) – Path to HDF5 file to create/overwrite. Must have
.hamiltonianbefore the file extension.- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If I/O error occurs
Examples
>>> hamiltonian.to_hdf5_file("water.hamiltonian.h5")
- to_json(self: qdk_chemistry.data.Hamiltonian) str
Convert Hamiltonian to JSON string.
- Returns:
JSON representation of the Hamiltonian
- Return type:
- to_json_file(self: qdk_chemistry.data.Hamiltonian, filename: object) None
Save Hamiltonian to JSON file (with validation).
- Parameters:
filename (str or pathlib.Path) – Path to JSON file to create/overwrite. Must have
.hamiltonianbefore the file extension.- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If an I/O error occurs
Examples
>>> hamiltonian.to_json_file("water.hamiltonian.json")
- property two_body_integrals
Get two-electron integrals in molecular orbital basis.
- Returns:
Tuple of two-electron integral vectors [norb^4] for aaaa, aabb, and bbbb spin channels.
- Return type:
- Raises:
RuntimeError – If two-body integrals have not been set
Notes
Integrals are stored as flattened vectors in chemist notation <ij|kl>
- property type
Get the type of Hamiltonian (Hermitian or NonHermitian).
- Returns:
The Hamiltonian type
- Return type:
- class qdk_chemistry.data.HamiltonianContainer
Bases:
pybind11_objectAbstract base class for Hamiltonian container implementations.
This class defines the interface for storing molecular Hamiltonian data for quantum chemistry calculations. 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
Derived classes implement specific storage formats for two-electron integrals (e.g., canonical 4-center, density-fitted, etc.).
Note
This class cannot be instantiated directly. Use a derived class like CanonicalFourCenterHamiltonianContainer instead.
- __init__(*args, **kwargs)
- property core_energy
Get core energy in atomic units.
- Returns:
Core energy contribution in Hartree
- Return type:
- get_container_type(self: qdk_chemistry.data.HamiltonianContainer) str
Get the type of this container as a string.
- Returns:
Container type identifier (e.g., “canonical_four_center”)
- Return type:
- get_core_energy(self: qdk_chemistry.data.HamiltonianContainer) float
Get core energy in atomic units.
- Returns:
Core energy contribution in Hartree
- Return type:
- get_inactive_fock_matrix(self: qdk_chemistry.data.HamiltonianContainer) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']]
Get tuple of inactive Fock matrices (alpha, beta).
- Returns:
Inactive Fock matrices for the active space
- Return type:
- get_one_body_element(self: qdk_chemistry.data.HamiltonianContainer, i: SupportsInt, j: SupportsInt, channel: qdk_chemistry.data.SpinChannel = <SpinChannel.aa: 0>) float
Get specific one-electron integral element <ij>.
- Parameters:
i (int) – First orbital index
j (int) – Second orbital index
channel (SpinChannel) – Spin channel (aa or bb), defaults to aa
- Returns:
Value of the one-electron integral <ij>
- Return type:
- get_one_body_integrals(self: qdk_chemistry.data.HamiltonianContainer) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']]
Get tuple of one-electron integrals (alpha, beta) in molecular orbital basis.
- Returns:
One-electron integral matrices [norb x norb] for alpha and beta spin channels.
- Return type:
- get_orbitals(self: qdk_chemistry.data.HamiltonianContainer) qdk_chemistry.data.Orbitals
Get molecular orbital data.
- Returns:
The orbital data associated with this container
- Return type:
- get_type(self: qdk_chemistry.data.HamiltonianContainer) qdk_chemistry.data.HamiltonianType
Get the type of Hamiltonian (Hermitian or NonHermitian).
- Returns:
The Hamiltonian type
- Return type:
- has_inactive_fock_matrix(self: qdk_chemistry.data.HamiltonianContainer) bool
Check if inactive Fock matrix is available.
- Returns:
True if inactive Fock matrix has been set
- Return type:
- has_one_body_integrals(self: qdk_chemistry.data.HamiltonianContainer) bool
Check if one-body integrals are available.
- Returns:
True if one-body integrals have been set
- Return type:
- has_orbitals(self: qdk_chemistry.data.HamiltonianContainer) bool
Check if orbital data is available.
- Returns:
True if orbital data has been set
- Return type:
- property inactive_fock_matrix
Get tuple of inactive Fock matrices (alpha, beta).
- Returns:
Inactive Fock matrices for the active space
- Return type:
- is_hermitian(self: qdk_chemistry.data.HamiltonianContainer) bool
Check if the Hamiltonian is Hermitian.
- Returns:
True if the Hamiltonian type is Hermitian
- Return type:
- is_unrestricted(self: qdk_chemistry.data.HamiltonianContainer) bool
Check if Hamiltonian is unrestricted.
- Returns:
True if alpha and beta integrals are different
- Return type:
- property one_body_integrals
Get tuple of one-electron integrals (alpha, beta) in molecular orbital basis.
- Returns:
One-electron integral matrices [norb x norb] for alpha and beta spin channels.
- Return type:
- property orbitals
Get molecular orbital data.
- Returns:
The orbital data associated with this container
- Return type:
- property type
Get the type of Hamiltonian (Hermitian or NonHermitian).
- Returns:
The Hamiltonian type
- Return type:
- class qdk_chemistry.data.HamiltonianType
Bases:
pybind11_objectEnumeration for Hamiltonian types.
- Values:
Hermitian: Standard Hermitian Hamiltonian NonHermitian: Non-Hermitian Hamiltonian
Members:
Hermitian
NonHermitian
- Hermitian = <HamiltonianType.Hermitian: 0>
- NonHermitian = <HamiltonianType.NonHermitian: 1>
- __init__(self: qdk_chemistry.data.HamiltonianType, value: SupportsInt) None
- HamiltonianType.name -> str
- property value
- class qdk_chemistry.data.MP2Container
Bases:
WavefunctionContainerMP2 wavefunction container implementation.
- __init__(self: qdk_chemistry.data.MP2Container, hamiltonian: qdk_chemistry.data.Hamiltonian, wavefunction: qdk_chemistry.data.Wavefunction, partitioning: str = 'mp') None
Constructs an MP2 wavefunction container.
- Parameters:
hamiltonian (Hamiltonian) – Shared pointer to the Hamiltonian
wavefunction (Wavefunction) – Shared pointer to the Wavefunction
partitioning (str, optional) – Choice of partitioning in perturbation theory (default: “mp”)
Examples
>>> container = qdk_chemistry.MP2Container( ... hamiltonian, wfn, "mp")
- get_hamiltonian(self: qdk_chemistry.data.MP2Container) qdk_chemistry.data.Hamiltonian
Get reference to Hamiltonian.
- Returns:
Shared pointer to Hamiltonian
- Return type:
Examples
>>> ham = mp2_container.get_hamiltonian()
- get_t1_amplitudes(self: qdk_chemistry.data.MP2Container) tuple
Get T1 amplitudes.
- Returns:
Pair of (alpha, beta) T1 amplitudes (zeros for MP2)
- Return type:
Examples
>>> if mp2_container.has_t1_amplitudes(): ... t1_aa, t1_bb = mp2_container.get_t1_amplitudes()
- get_t2_amplitudes(self: qdk_chemistry.data.MP2Container) tuple
Get T2 amplitudes.
- Returns:
Tuple of (alpha-beta, alpha-alpha, beta-beta) T2 amplitudes
- Return type:
Examples
>>> if mp2_container.has_t2_amplitudes(): ... t2_abab, t2_aaaa, t2_bbbb = mp2_container.get_t2_amplitudes()
- get_wavefunction(self: qdk_chemistry.data.MP2Container) qdk_chemistry.data.Wavefunction
Get reference to Wavefunction.
- Returns:
Shared pointer to Wavefunction
- Return type:
Examples
>>> wfn = mp2_container.get_wavefunction()
- has_t1_amplitudes(self: qdk_chemistry.data.MP2Container) bool
Check if T1 amplitudes are available.
- Returns:
Whether t1 amplitudes are available.
- Return type:
Examples
>>> if mp2_container.has_t1_amplitudes(): ... t1_aa, t1_bb = mp2_container.get_t1_amplitudes()
- has_t2_amplitudes(self: qdk_chemistry.data.MP2Container) bool
Check if T2 amplitudes are available.
- Returns:
Whether T2 amplitudes are available.
- Return type:
Examples
>>> if mp2_container.has_t2_amplitudes(): ... t2 = mp2_container.get_t2_amplitudes()
- class qdk_chemistry.data.MeasurementData(hamiltonians, bitstring_counts=None, shots_list=None)
Bases:
DataClassMeasurement bitstring data and metadata for a
QubitHamiltonian.- Parameters:
- hamiltonians
List of QubitHamiltonian corresponding to the measurement data.
- Type:
- bitstring_counts
Bitstring count dictionaries for each QubitHamiltonian.
- __init__(hamiltonians, bitstring_counts=None, shots_list=None)
Initialize measurement data.
- get_summary()
Get a human-readable summary of the measurement data.
- to_json()
Convert measurement data to a dictionary for JSON serialization.
- to_hdf5(group)
Save the measurement data to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write the measurement data to.
- classmethod from_json(json_data)
Create measurement data from a JSON dictionary.
- Return type:
- Parameters:
json_data (dict[str, Any]) – Dictionary containing the serialized data.
- Returns:
New instance reconstructed from JSON data.
- Return type:
- Raises:
RuntimeError – If version field is missing or incompatible.
- classmethod from_hdf5(group)
Load measurement data from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file containing the data.
- Returns:
New instance reconstructed from HDF5 data.
- Return type:
- Raises:
RuntimeError – If version attribute is missing or incompatible.
- class qdk_chemistry.data.ModelOrbitals
Bases:
OrbitalsSimple subclass of
Orbitalsfor model systems without basis set information.This class allows creating
Orbitalsobjects 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.Examples
>>> # Create a simple 4-orbital restricted model system >>> model_orb = ModelOrbitals(4, True) >>> print(f"Number of orbitals: {model_orb.get_num_molecular_orbitals()}")
>>> # Create with active and inactive spaces >>> active_indices = [1, 2] >>> inactive_indices = [0, 3] >>> model_orb = ModelOrbitals(4, active_indices, inactive_indices)
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.ModelOrbitals, basis_size: typing.SupportsInt, restricted: bool) -> None
Constructor for model orbitals with basic parameters.
- Parameters:
Examples
>>> # Restricted calculation with 6 orbitals >>> model_orb = ModelOrbitals(6, True) >>> print(f"Is restricted: {model_orb.is_restricted()}")
>>> # Unrestricted calculation with 4 orbitals >>> model_orb = ModelOrbitals(4, False) >>> print(f"Is unrestricted: {model_orb.is_unrestricted()}")
__init__(self: qdk_chemistry.data.ModelOrbitals, basis_size: typing.SupportsInt, indices: tuple[collections.abc.Sequence[typing.SupportsInt], collections.abc.Sequence[typing.SupportsInt]]) -> None
Constructor with active and inactive space indices (restricted).
For restricted calculations, the same active and inactive space indices are used for both alpha and beta electrons.
- Parameters:
- Raises:
ValueError – If indices are >= basis_size or if active and inactive spaces overlap
Examples
>>> # Create a 6-orbital system with orbitals 2,3 active and 0,1,4,5 inactive >>> active = [2, 3] >>> inactive = [0, 1, 4, 5] >>> indices = (active, inactive) >>> model_orb = ModelOrbitals(6, indices) >>> print(f"Active space size: {len(model_orb.get_active_space_indices()[0])}")
__init__(self: qdk_chemistry.data.ModelOrbitals, basis_size: typing.SupportsInt, indices: tuple[collections.abc.Sequence[typing.SupportsInt], collections.abc.Sequence[typing.SupportsInt], collections.abc.Sequence[typing.SupportsInt], collections.abc.Sequence[typing.SupportsInt]]) -> None
Constructor with active and inactive space indices (unrestricted).
For unrestricted calculations, separate active and inactive space indices can be provided for alpha and beta electrons.
- Parameters:
- Raises:
ValueError – If indices are >= basis_size or if active and inactive spaces overlap
Examples
>>> # Create unrestricted system with different alpha/beta active spaces >>> alpha_active = [1, 2] >>> beta_active = [2, 3] >>> alpha_inactive = [0, 3, 4] >>> beta_inactive = [0, 1, 4] >>> indices = (alpha_active, beta_active, alpha_inactive, beta_inactive) >>> model_orb = ModelOrbitals(5, indices) >>> print(f"Is unrestricted: {model_orb.is_unrestricted()}")
- static from_json(json_str: str) qdk_chemistry.data.ModelOrbitals
Load ModelOrbitals from JSON string (static method).
Parses ModelOrbitals data from a JSON string and creates a new
ModelOrbitalsobject. The string should contain JSON data in the format produced byto_json().- Parameters:
json_str (str) – JSON string containing
ModelOrbitalsdata- Returns:
New ModelOrbitals object created from JSON data
- Return type:
- Raises:
RuntimeError – If the JSON string is malformed or contains invalid
ModelOrbitalsdata
Examples
>>> json_str = '{"num_orbitals": 4, "is_restricted": true, ...}' >>> model_orb = ModelOrbitals.from_json(json_str) >>> print(f"Loaded {model_orb.get_num_molecular_orbitals()} orbitals")
- class qdk_chemistry.data.OrbitalType
Bases:
pybind11_objectEnumeration of orbital types
Members:
S : s orbital (l=0)
P : p orbital (l=1)
D : d orbital (l=2)
F : f orbital (l=3)
G : g orbital (l=4)
H : h orbital (l=5)
I : i orbital (l=6)
- D = <OrbitalType.D: 2>
- F = <OrbitalType.F: 3>
- G = <OrbitalType.G: 4>
- H = <OrbitalType.H: 5>
- I = <OrbitalType.I: 6>
- P = <OrbitalType.P: 1>
- S = <OrbitalType.S: 0>
- __init__(self: qdk_chemistry.data.OrbitalType, value: SupportsInt) None
- OrbitalType.name -> str
- property value
- class qdk_chemistry.data.Orbitals
Bases:
DataClassRepresents molecular orbitals with coefficients and energies.
This class stores and manipulates molecular orbital data including:
Orbital coefficients (alpha/beta spin channels)
Orbital energies (alpha/beta spin channels)
Atomic orbital overlap matrix
Basis set information
The class provides methods to calculate atomic orbital density matrices from occupation vectors or reduced density matrices (RDMs) passed as parameters.
Supports both restricted (RHF/RKS) and unrestricted (UHF/UKS) orbitals.
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.Orbitals, arg0: qdk_chemistry.data.Orbitals) -> None
Copy constructor.
Creates a deep copy of another
Orbitalsobject.- Parameters:
other (Orbitals) – The Orbitals object to copy
Examples
>>> original_orbitals = Orbitals(...) >>> copied_orbitals = Orbitals(original_orbitals) >>> print(f"Copied {copied_orbitals.get_num_molecular_orbitals()} orbitals")
__init__(self: qdk_chemistry.data.Orbitals, coefficients: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], energies: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | None = None, ao_overlap: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | None = None, basis_set: qdk_chemistry.data.BasisSet, indices: tuple[collections.abc.Sequence[typing.SupportsInt], collections.abc.Sequence[typing.SupportsInt]] | None = None) -> None
Constructor for restricted orbitals.
num_atomic_orbitalsrefers to the number of atomic orbitals andnum_molecular_orbitalsrefers to the number of molecular orbitals.- Parameters:
coefficients (numpy.ndarray) – The molecular orbital coefficients matrix (
num_atomic_orbitals×num_molecular_orbitals)energies (numpy.ndarray | None) – The orbital energies (
num_molecular_orbitals), can be Noneao_overlap (numpy.ndarray | None) – The atomic orbital overlap matrix (
num_atomic_orbitals×num_atomic_orbitals), can beNonebasis_set (BasisSet) – The basis set
indices (tuple[list[int], list[int]] | None) – Tuple of (active_space_indices, inactive_space_indices), can be
None
Examples
>>> import numpy as np >>> coeffs = np.random.random((4, 3)) >>> basis_set = BasisSet(...) >>> orbitals = Orbitals(coeffs, None, None, basis_set, None)
__init__(self: qdk_chemistry.data.Orbitals, coefficients_alpha: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], coefficients_beta: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], energies_alpha: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | None = None, energies_beta: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | None = None, ao_overlap: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | None = None, basis_set: qdk_chemistry.data.BasisSet, indices: tuple[collections.abc.Sequence[typing.SupportsInt], collections.abc.Sequence[typing.SupportsInt], collections.abc.Sequence[typing.SupportsInt], collections.abc.Sequence[typing.SupportsInt]] | None = None) -> None
Constructor for unrestricted orbitals.
num_atomic_orbitalsrefers to the number of atomic orbitals andnum_molecular_orbitalsrefers to the number of molecular orbitals.- Parameters:
coefficients_alpha (numpy.ndarray) –
The alpha molecular orbital coefficients matrix
(
num_atomic_orbitals×num_molecular_orbitals)coefficients_beta (numpy.ndarray) –
The beta molecular orbital coefficients matrix
(
num_atomic_orbitals×num_molecular_orbitals)energies_alpha (numpy.ndarray | None) –
The alpha orbital energies
(
num_molecular_orbitals), can be Noneenergies_beta (numpy.ndarray | None) –
The beta orbital energies
(
num_molecular_orbitals), can be Noneao_overlap (numpy.ndarray | None) –
The atomic orbital overlap matrix
(
num_atomic_orbitals×num_atomic_orbitals), can be Nonebasis_set (BasisSet) – The basis set
indices (tuple[list[int], list[int], list[int], list[int]] | None) –
Tuple of
(
active_alpha,active_beta,inactive_alpha,inactive_beta), can beNone
Examples
>>> import numpy as np >>> alpha_coeffs = np.random.random((4, 3)) >>> beta_coeffs = np.random.random((4, 3)) >>> basis_set = BasisSet(...) >>> orbitals = Orbitals(alpha_coeffs, beta_coeffs, None, None, None, basis_set, None)
- property basis_set
Get basis set information.
- Returns:
The basis set associated with these orbitals
- Return type:
- Raises:
RuntimeError – If basis set has not been set
Examples
>>> basis_set = orbitals.get_basis_set() >>> print(f"Basis set name: {basis_set.get_name()}")
- calculate_ao_density_matrix(*args, **kwargs)
Overloaded function.
calculate_ao_density_matrix(self: qdk_chemistry.data.Orbitals, occupations_alpha: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], occupations_beta: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”]) -> tuple[typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, n]”], typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, n]”]]
Calculate atomic orbital density matrix from occupation vectors (unrestricted).
- Parameters:
occupations_alpha (numpy.ndarray) – Alpha spin occupation vector (size must match number of MOs)
occupations_beta (numpy.ndarray) – Beta spin occupation vector (size must match number of MOs)
- Returns:
Pair of (alpha, beta) atomic orbital density matrices
- Return type:
- Raises:
RuntimeError – If occupation vector sizes don’t match number of MOs
Examples
>>> alpha_occ = np.array([1.0, 1.0, 0.0]) >>> beta_occ = np.array([1.0, 0.0, 0.0]) >>> P_alpha, P_beta = orbitals.calculate_ao_density_matrix(alpha_occ, beta_occ)
calculate_ao_density_matrix(self: qdk_chemistry.data.Orbitals, occupations: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”]) -> typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, n]”]
Calculate atomic orbital density matrix from occupation vector (restricted).
- Parameters:
occupations (numpy.ndarray) – Total occupation vector (size must match number of molecular orbitals)
- Returns:
Atomic orbital density matrix (total alpha + beta)
- Return type:
- Raises:
RuntimeError – If occupation vector size doesn’t match number of MOs
Examples
>>> occupations = np.array([2.0, 0.0, 0.0]) # 2 electrons in first MO >>> P_total = orbitals.calculate_ao_density_matrix(occupations)
- calculate_ao_density_matrix_from_rdm(*args, **kwargs)
Overloaded function.
calculate_ao_density_matrix_from_rdm(self: qdk_chemistry.data.Orbitals, rdm_alpha: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], rdm_beta: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”]) -> tuple[typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, n]”], typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, n]”]]
Calculate atomic orbital density matrix from 1RDM in molecular orbital space (unrestricted).
- Parameters:
rdm_alpha (numpy.ndarray) – Alpha 1RDM in MO basis (size must match number of MOs × MOs)
rdm_beta (numpy.ndarray) – Beta 1RDM in MO basis (size must match number of MOs × MOs)
- Returns:
Pair of (alpha, beta) AO density matrices
- Return type:
- Raises:
RuntimeError – If 1RDM matrix sizes don’t match number of MOs
Examples
>>> rdm_alpha = np.eye(3) # Simple example with identity matrix >>> rdm_beta = np.zeros((3, 3)) >>> P_alpha, P_beta = orbitals.calculate_ao_density_matrix_from_rdm(rdm_alpha, rdm_beta)
calculate_ao_density_matrix_from_rdm(self: qdk_chemistry.data.Orbitals, rdm: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”]) -> typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, n]”]
Calculate atomic orbital density matrix from 1RDM in molecular orbital space (restricted).
- Parameters:
rdm (numpy.ndarray) – 1RDM in MO basis (size must match number of MOs × MOs)
- Returns:
AO density matrix (total alpha + beta)
- Return type:
- Raises:
RuntimeError – If 1RDM matrix size doesn’t match number of MOs
Examples
>>> rdm = np.eye(3) # Simple example with identity matrix >>> P_total = orbitals.calculate_ao_density_matrix_from_rdm(rdm)
- property coefficients_alpha
Get alpha orbital coefficients matrix.
- Returns:
Alpha orbital coefficients with shape
(num_atomic_orbitals, num_molecular_orbitals)- Return type:
Examples
>>> alpha_coeffs = orbitals.get_coefficients_alpha() >>> print(f"Alpha coefficients shape: {alpha_coeffs.shape}")
- property coefficients_beta
Get beta orbital coefficients matrix.
- Returns:
Beta orbital coefficients with shape
(num_atomic_orbitals, num_molecular_orbitals)- Return type:
Examples
>>> beta_coeffs = orbitals.get_coefficients_beta() >>> print(f"Beta coefficients shape: {beta_coeffs.shape}")
- property energies_alpha
Get alpha orbital energies (Hartree).
- Returns:
Alpha orbital energies with length
num_molecular_orbitals- Return type:
Examples
>>> alpha_energies = orbitals.get_energies_alpha() >>> homo_energy = alpha_energies[homo_index]
- property energies_beta
Get beta orbital energies (Hartree).
- Returns:
Beta orbital energies with length
num_molecular_orbitals- Return type:
Examples
>>> beta_energies = orbitals.get_energies_beta() >>> homo_energy = beta_energies[homo_index]
- static from_file(filename: object, type: str) qdk_chemistry.data.Orbitals
Load orbital data from file with specified format (static method).
Generic method to load orbital data from a file.
- Parameters:
filename (str | pathlib.Path) – Path to the file to read.
type (str) – File format type (‘json’ or ‘hdf5’)
- Returns:
New
Orbitalsobject loaded from the file- Return type:
- Raises:
ValueError – If format_type is not supported or filename doesn’t follow naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid orbital data
Examples
>>> orbitals = Orbitals.from_file("water.orbitals.json", "json") >>> orbitals = Orbitals.from_file("molecule.orbitals.h5", "hdf5") >>> from pathlib import Path >>> orbitals = Orbitals.from_file(Path("water.orbitals.json"), "json")
- static from_hdf5_file(filename: object) qdk_chemistry.data.Orbitals
Load orbital data from HDF5 file (static method with validation).
Reads orbital data from an HDF5 file. The file should contain data in the format produced by
to_hdf5_file().- Parameters:
filename (str | pathlib.Path) –
Path to the HDF5 file to read.
Must have ‘.orbitals’ before the file extension (e.g.,
water.orbitals.h5,molecule.orbitals.hdf5)- Returns:
New
Orbitalsobject loaded from the file- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid orbital data
Examples
>>> orbitals = Orbitals.from_hdf5_file("water.orbitals.h5") >>> orbitals = Orbitals.from_hdf5_file("molecule.orbitals.hdf5") >>> from pathlib import Path >>> orbitals = Orbitals.from_hdf5_file(Path("water.orbitals.h5"))
- static from_json(json_str: str) qdk_chemistry.data.Orbitals
Load orbital data from JSON string (static method).
Parses orbital data from a JSON string and creates a new Orbitals object. The string should contain JSON data in the format produced by
to_json().- Parameters:
json_str (str) – JSON string containing orbital data
- Returns:
New Orbitals object created from JSON data
- Return type:
- Raises:
RuntimeError – If the JSON string is malformed or contains invalid orbital data
Examples
>>> orbitals = Orbitals.from_json('{"num_atomic_orbitals": 4, "num_molecular_orbitals": 3, ...}')
- static from_json_file(filename: object) qdk_chemistry.data.Orbitals
Load orbital data from JSON file (static method).
Reads orbital data from a JSON file. The file should contain JSON data in the format produced by
to_json_file().- Parameters:
filename (str | pathlib.Path) –
Path to the JSON file to read.
Must have ‘.orbitals’ before the file extension (e.g.,
water.orbitals.json,molecule.orbitals.json)- Returns:
New
Orbitalsobject loaded from the file- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid orbital data
Examples
>>> orbitals = Orbitals.from_json_file("water.orbitals.json") >>> orbitals = Orbitals.from_json_file("molecule.orbitals.json") >>> from pathlib import Path >>> orbitals = Orbitals.from_json_file(Path("water.orbitals.json"))
- get_active_space_indices(self: qdk_chemistry.data.Orbitals) tuple[list[int], list[int]]
Get the active space orbital indices.
- Returns:
Pair of
(alpha_indices, beta_indices)for active space orbitals- Return type:
Examples
>>> alpha_active, beta_active = orbitals.get_active_space_indices() >>> print(f"Active space size: {len(alpha_active)}")
- get_basis_set(self: qdk_chemistry.data.Orbitals) qdk_chemistry.data.BasisSet
Get basis set information.
- Returns:
The basis set associated with these orbitals
- Return type:
- Raises:
RuntimeError – If basis set has not been set
Examples
>>> basis_set = orbitals.get_basis_set() >>> print(f"Basis set name: {basis_set.get_name()}")
- get_coefficients(self: qdk_chemistry.data.Orbitals) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']]
Get orbital coefficients as pair of (alpha, beta) matrices.
num_atomic_orbitalsrefers to the number of atomic orbitals andnum_molecular_orbitalsrefers to the number of molecular orbitals.- Returns:
Pair of
(alpha_coeffs, beta_coeffs)matrices,each with shape
(num_atomic_orbitals, num_molecular_orbitals)- Return type:
Examples
>>> alpha_coeffs, beta_coeffs = orbitals.get_coefficients() >>> print(f'Alpha coefficients shape: {alpha_coeffs.shape}')
- get_coefficients_alpha(self: qdk_chemistry.data.Orbitals) Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']
Get alpha orbital coefficients matrix.
- Returns:
Alpha orbital coefficients with shape
(num_atomic_orbitals, num_molecular_orbitals)- Return type:
Examples
>>> alpha_coeffs = orbitals.get_coefficients_alpha() >>> print(f"Alpha coefficients shape: {alpha_coeffs.shape}")
- get_coefficients_beta(self: qdk_chemistry.data.Orbitals) Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']
Get beta orbital coefficients matrix.
- Returns:
Beta orbital coefficients with shape
(num_atomic_orbitals, num_molecular_orbitals)- Return type:
Examples
>>> beta_coeffs = orbitals.get_coefficients_beta() >>> print(f"Beta coefficients shape: {beta_coeffs.shape}")
- get_energies(self: qdk_chemistry.data.Orbitals) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get orbital energies in Hartrees as pair of (alpha, beta) vectors.
- Returns:
Pair of
(alpha_energies, beta_energies)vectors, each with lengthnum_molecular_orbitals- Return type:
- Raises:
RuntimeError – If energies have not been set
Examples
>>> alpha_energies, beta_energies = orbitals.get_energies() >>> print(f'HOMO energy: {alpha_energies[homo_index]}')
- get_energies_alpha(self: qdk_chemistry.data.Orbitals) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']
Get alpha orbital energies (Hartree).
- Returns:
Alpha orbital energies with length
num_molecular_orbitals- Return type:
Examples
>>> alpha_energies = orbitals.get_energies_alpha() >>> homo_energy = alpha_energies[homo_index]
- get_energies_beta(self: qdk_chemistry.data.Orbitals) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']
Get beta orbital energies (Hartree).
- Returns:
Beta orbital energies with length
num_molecular_orbitals- Return type:
Examples
>>> beta_energies = orbitals.get_energies_beta() >>> homo_energy = beta_energies[homo_index]
- get_inactive_space_indices(*args, **kwargs)
Overloaded function.
get_inactive_space_indices(self: qdk_chemistry.data.Orbitals) -> tuple[list[int], list[int]]
Get the inactive space orbital indices.
- Returns:
Pair of
(alpha_indices, beta_indices)for inactive space orbitals- Return type:
Examples
>>> alpha_inactive, beta_inactive = orbitals.get_inactive_space_indices() >>> print(f"Inactive space size: {len(alpha_inactive)}")
get_inactive_space_indices(self: qdk_chemistry.data.Orbitals) -> tuple[list[int], list[int]]
Get the inactive space orbital indices.
- Returns:
Pair of
(alpha_indices, beta_indices)for inactive space orbitals- Return type:
Examples
>>> alpha_inactive, beta_inactive = orbitals.get_inactive_space_indices() >>> print(f"Inactive space size: {len(alpha_inactive)}")
- get_num_atomic_orbitals(self: qdk_chemistry.data.Orbitals) int
Get number of atomic orbitals (atomic orbitals).
- Returns:
Number of atomic orbitals/atomic orbitals
- Return type:
Examples
>>> num_atomic_orbitals = orbitals.get_num_atomic_orbitals() >>> print(f'Basis set size: {num_atomic_orbitals}')
- get_num_molecular_orbitals(self: qdk_chemistry.data.Orbitals) int
Get number of molecular orbitals.
- Returns:
Number of molecular orbitals
- Return type:
Examples
>>> num_molecular_orbitals = orbitals.get_num_molecular_orbitals() >>> print(f'Number of MOs: {num_molecular_orbitals}')
- get_overlap_matrix(self: qdk_chemistry.data.Orbitals) Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']
Get atomic orbital overlap matrix.
- Returns:
Atomic orbital overlap matrix with shape
(num_atomic_orbitals, num_atomic_orbitals)- Return type:
Examples
>>> overlap = orbitals.get_overlap_matrix() >>> print(f"Overlap matrix shape: {overlap.shape}")
- get_summary(self: qdk_chemistry.data.Orbitals) str
Get summary string of orbital information.
- Returns:
Human-readable summary of orbital properties
- Return type:
Examples
>>> summary = orbitals.get_summary() >>> print(summary)
- get_virtual_space_indices(self: qdk_chemistry.data.Orbitals) tuple[list[int], list[int]]
Get the virtual space orbital indices.
- Returns:
Pair of (alpha_indices, beta_indices) for virtual orbitals
- Return type:
Examples
>>> alpha_virtual, beta_virtual = orbitals.get_virtual_space_indices() >>> print(f"Virtual space size: {len(alpha_virtual)}")
- has_active_space(self: qdk_chemistry.data.Orbitals) bool
Check if active space data is set.
- Returns:
True if active space information is available, False otherwise
- Return type:
Examples
>>> if orbitals.has_active_space(): ... active_indices = orbitals.get_active_space_indices() ... else: ... print("No active space defined")
- has_basis_set(self: qdk_chemistry.data.Orbitals) bool
Check if basis set information is available.
- Returns:
True if basis set is set, False otherwise
- Return type:
Examples
>>> if orbitals.has_basis_set(): ... basis = orbitals.get_basis_set() ... else: ... print("Basis set not available")
- has_energies(self: qdk_chemistry.data.Orbitals) bool
Check if orbital energies have been internally set.
- Returns:
True if energies have been set, false otherwise
- Return type:
Examples
>>> if orbitals.has_energies(): ... alpha_e, beta_e = orbitals.get_energies() ... else: ... print("Energies not yet set")
- has_overlap_matrix(self: qdk_chemistry.data.Orbitals) bool
Check if atomic orbital overlap matrix is available.
- Returns:
True if overlap matrix is set, False otherwise
- Return type:
Examples
>>> if orbitals.has_overlap_matrix(): ... overlap = orbitals.get_overlap_matrix() ... else: ... print("Overlap matrix not available")
- is_restricted(self: qdk_chemistry.data.Orbitals) bool
Check if calculation is restricted.
Restricted calculations use identical alpha and beta coefficients.
- Returns:
True if alpha and beta coefficients are identical, False otherwise
- Return type:
Examples
>>> is_rhf = orbitals.is_restricted() >>> print(f"Restricted calculation: {is_rhf}")
- is_unrestricted(self: qdk_chemistry.data.Orbitals) bool
Check if calculation is unrestricted.
Unrestricted calculations use separate alpha and beta coefficients.
- Returns:
True if separate alpha/beta coefficients are used, False otherwise
- Return type:
Examples
>>> is_uhf = orbitals.is_unrestricted() >>> print(f"Unrestricted calculation: {is_uhf}")
- property summary
Get summary string of orbital information.
- Returns:
Human-readable summary of orbital properties
- Return type:
Examples
>>> summary = orbitals.get_summary() >>> print(summary)
- to_file(self: qdk_chemistry.data.Orbitals, filename: object, type: str) None
Save orbital data to file with specified format.
Generic method to save orbital data to a file.
- Parameters:
filename (str | pathlib.Path) – Path to the file to write.
type (str) – File format type (‘json’ or ‘hdf5’)
- Raises:
RuntimeError – If the orbital data is invalid, unsupported type, or file cannot be opened/written
Examples
>>> orbitals.to_file("water.orbitals.json", "json") >>> orbitals.to_file("molecule.orbitals.h5", "hdf5") >>> from pathlib import Path >>> orbitals.to_file(Path("water.orbitals.json"), "json")
- to_hdf5_file(self: qdk_chemistry.data.Orbitals, filename: object) None
Save orbital data to HDF5 file (with validation).
Writes all orbital data to an HDF5 file, preserving numerical precision. HDF5 format is efficient for large datasets and supports hierarchical data structures, making it ideal for storing molecular orbital information.
- Parameters:
filename (str | pathlib.Path) –
Path to the HDF5 file to write.
Must have ‘.orbitals’ before the file extension (e.g.,
water.orbitals.h5,molecule.orbitals.hdf5)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the orbital data is invalid or the file cannot be opened/written
Examples
>>> orbitals.to_hdf5_file("water.orbitals.h5") >>> orbitals.to_hdf5_file("molecule.orbitals.hdf5") >>> from pathlib import Path >>> orbitals.to_hdf5_file(Path("water.orbitals.h5"))
- to_json(self: qdk_chemistry.data.Orbitals) str
Convert orbital data to JSON string.
Serializes all orbital information to a JSON string format. JSON is human-readable and suitable for debugging or data exchange.
- Returns:
JSON string representation of the orbital data
- Return type:
- Raises:
RuntimeError – If the orbital data is invalid
Examples
>>> json_str = orbitals.to_json() >>> print(json_str) # Pretty-printed JSON
- to_json_file(self: qdk_chemistry.data.Orbitals, filename: object) None
Save orbital data to JSON file.
Writes all orbital data to a JSON file with pretty formatting. The file will be created or overwritten if it already exists.
- Parameters:
filename (str | pathlib.Path) –
Path to the JSON file to write.
Must have ‘.orbitals’ before the file extension (e.g.,
water.orbitals.json,molecule.orbitals.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the orbital data is invalid or the file cannot be opened/written
Examples
>>> orbitals.to_json_file("water.orbitals.json") >>> orbitals.to_json_file("molecule.orbitals.json") >>> from pathlib import Path >>> orbitals.to_json_file(Path("water.orbitals.json"))
- class qdk_chemistry.data.PauliOperator
Bases:
PauliOperatorExpressionA single Pauli operator (I, X, Y, or Z) acting on a specific qubit.
This class represents one of the four Pauli matrices acting on a single qubit. Pauli operators can be combined using arithmetic operators to form expressions:
Multiplication (*): Creates a product of operators
Addition (+): Creates a sum of operators
Subtraction (-): Creates a difference of operators
Scalar multiplication: Multiplies by a complex coefficient
Examples
Create Pauli operators:
>>> X0 = PauliOperator.X(0) # X operator on qubit 0 >>> Z1 = PauliOperator.Z(1) # Z operator on qubit 1
Form expressions:
>>> expr = X0 * Z1 # Product X_0 * Z_1 >>> expr = 0.5 * X0 + Z1 # Sum 0.5*X_0 + Z_1
- static I(qubit_index: SupportsInt) qdk_chemistry.data.PauliOperator
Create an identity operator on the specified qubit.
- Parameters:
qubit_index – The index of the qubit.
- Returns:
The identity operator I on the given qubit.
- Return type:
- static X(qubit_index: SupportsInt) qdk_chemistry.data.PauliOperator
Create a Pauli X operator on the specified qubit.
- Parameters:
qubit_index – The index of the qubit.
- Returns:
The Pauli X operator on the given qubit.
- Return type:
- static Y(qubit_index: SupportsInt) qdk_chemistry.data.PauliOperator
Create a Pauli Y operator on the specified qubit.
- Parameters:
qubit_index – The index of the qubit.
- Returns:
The Pauli Y operator on the given qubit.
- Return type:
- static Z(qubit_index: SupportsInt) qdk_chemistry.data.PauliOperator
Create a Pauli Z operator on the specified qubit.
- Parameters:
qubit_index – The index of the qubit.
- Returns:
The Pauli Z operator on the given qubit.
- Return type:
- __init__(*args, **kwargs)
- prune_threshold(self: qdk_chemistry.data.PauliOperator, epsilon: SupportsFloat) qdk::chemistry::data::SumPauliOperatorExpression
Remove terms with coefficient magnitude below the threshold.
- Parameters:
epsilon – The threshold below which terms are removed.
- Returns:
A new expression with small terms filtered out.
- Return type:
SumPauliOperatorExpression
- property qubit_index
The index of the qubit this operator acts on.
- to_char(self: qdk_chemistry.data.PauliOperator) str
Return the character representation of this Pauli operator.
- Returns:
‘I’, ‘X’, ‘Y’, or ‘Z’.
- Return type:
Examples
>>> PauliOperator.X(0).to_char() 'X' >>> PauliOperator.Z(1).to_char() 'Z'
- class qdk_chemistry.data.PauliProductFormulaContainer(step_terms, step_reps, num_qubits)
Bases:
TimeEvolutionUnitaryContainerDataclass for a Pauli product formula container.
A Pauli Product Formula decomposes a time-evolution operator \(U(t) = e^{-i H t}\), into a product of exponentials of Pauli strings. A single product-formula step is represented as \(U_{\mathrm{step}}(t) = \prod_{j \in \pi} e^{-i \theta_j P_j}\), where:
\(P_j\) is a Pauli string
\(\theta_j\) is the rotation angle for that term
\(\prod_{j \in \pi}\) is a permutation defining the multiplication order
The full time-evolution unitary is: \(U(t) \approx \left[ U_{\mathrm{step}}\!\left(\tfrac{t}{r}\right) \right]^{r}\), where
step_reps = ris the number of repeated steps.- Parameters:
step_terms (list[ExponentiatedPauliTerm])
step_reps (int)
num_qubits (int)
- __init__(step_terms, step_reps, num_qubits)
Initialize a PauliProductFormulaContainer.
- Parameters:
step_terms (list[ExponentiatedPauliTerm]) – The list of exponentiated Pauli terms in a single step.
step_reps (int) – The number of repetitions of the single step.
num_qubits (int) – The number of qubits the unitary acts on.
- Return type:
None
- property type: str
Get the type of the time evolution unitary container.
- Returns:
The type of the time evolution unitary container.
- property num_qubits: int
Get the number of qubits the time evolution unitary acts on.
- Returns:
The number of qubits.
- reorder_terms(permutation)
Reorder the Pauli terms according to a given permutation.
- Return type:
- Parameters:
permutation (list[int]) – A list where
permutation[i]gives the old index of the term that should be placed at positioniin the reordered list.- Returns:
A new container with the updated ordering.
- Return type:
Note
permutation[i]is the old index for new positioni. For example,permutation = [2, 0, 1]yieldsnew_terms = [old_terms[2], old_terms[0], old_terms[1]].
- to_json()
Convert the PauliProductFormulaContainer to a dictionary for JSON serialization.
- to_hdf5(group)
Save the PauliProductFormulaContainer to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write data to
- classmethod from_json(json_data)
Create PauliProductFormulaContainer from a JSON dictionary.
- classmethod from_hdf5(group)
Load an instance from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to read data from
- Returns:
PauliProductFormulaContainer
- class qdk_chemistry.data.QpeResult(method, evolution_time, phase_fraction, phase_angle, canonical_phase_fraction, canonical_phase_angle, raw_energy, branching, resolved_energy=None, bits_msb_first=None, bitstring_msb_first=None, metadata=None)
Bases:
DataClassStructured output for quantum phase estimation workflows.
- Parameters:
- canonical_phase_fraction
Alias-resolved phase fraction consistent with the selected energy branch.
- Type:
- resolved_energy
Alias energy selected with the optional reference value, if available.
- Type:
float | None
- bits_msb_first
Tuple of measured bits ordered from MSB to LSB, when provided.
- __init__(method, evolution_time, phase_fraction, phase_angle, canonical_phase_fraction, canonical_phase_angle, raw_energy, branching, resolved_energy=None, bits_msb_first=None, bitstring_msb_first=None, metadata=None)
Initialize a QPE result.
- Parameters:
method (str) – Identifier for the algorithm or workflow.
evolution_time (float) – Evolution time used in the simulation.
phase_fraction (float) – Raw measured phase fraction.
phase_angle (float) – Raw measured phase angle in radians.
canonical_phase_fraction (float) – Alias-resolved phase fraction.
canonical_phase_angle (float) – Alias-resolved phase angle.
raw_energy (float) – Energy computed from phase_fraction.
branching (tuple[float, ...]) – Tuple of alias energy candidates.
resolved_energy (float | None) – Alias energy selected with reference.
bits_msb_first (tuple[int, ...] | None) – Measured bits from MSB to LSB.
bitstring_msb_first (str | None) – Bitstring representation.
metadata (dict[str, object] | None) – Optional metadata dictionary.
- Return type:
None
- classmethod from_phase_fraction(*, method, phase_fraction, evolution_time, branch_shifts=range(-2, 3), bits_msb_first=None, bitstring_msb_first=None, reference_energy=None, metadata=None)
Construct a
QpeResultfrom a measured phase fraction.- Return type:
- Parameters:
method (PhaseEstimationAlgorithm | str) – Phase estimation algorithm or workflow label.
phase_fraction (float) – Measured phase fraction in
[0, 1).evolution_time (float) – Evolution time
tused inU = exp(-i H t).branch_shifts (Iterable[int]) – Integer multiples of
2π / texamined when forming alias candidates.bits_msb_first (Sequence[int] | None) – Optional measured bits ordered from MSB to LSB.
bitstring_msb_first (str | None) – Optional string representation of the measured bits.
reference_energy (float | None) – Optional target value used to select the canonical alias branch.
metadata (dict[str, object] | None) – Optional dictionary copied into the result for caller-defined context.
- Returns:
Populated
QpeResultinstance reflecting the supplied data.- Return type:
- property algorithm: PhaseEstimationAlgorithm | None
Return the phase estimation algorithm that produced the result if available.
- Returns:
Phase estimation algorithm that produced the result or None.
- Return type:
PhaseEstimationAlgorithm | None
- get_summary()
Get a human-readable summary of the QPE result.
- to_json()
Convert the QPE result to a dictionary for JSON serialization.
- to_hdf5(group)
Save the QPE result to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write the QPE result to.
- classmethod from_json(json_data)
Create a QPE result from a JSON dictionary.
- Return type:
- Parameters:
json_data (dict[str, Any]) – Dictionary containing the serialized QPE result data.
- Returns:
New instance reconstructed from the JSON data.
- Return type:
- Raises:
RuntimeError – If version field is missing or incompatible.
- classmethod from_hdf5(group)
Load a QPE result from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file containing the QPE result data.
- Returns:
New instance reconstructed from the HDF5 data.
- Return type:
- Raises:
RuntimeError – If version attribute is missing or incompatible.
- class qdk_chemistry.data.QuantumErrorProfile(name=None, description=None, errors=None)
Bases:
DataClassA class representing a quantum error profile containing information about quantum gates and error properties.
This class provides functionalities to define, load, and save quantum error profiles.
- Parameters:
name (str | None)
description (str | None)
errors (dict[SupportedGate, GateErrorDef] | None)
- errors
Dictionary mapping gate names to their error properties.
- Type:
- basis_gates_exclusion: ClassVar[set[str]] = {'barrier', 'measure', 'reset'}
Gates to exclude from basis gates in noise model.
- __init__(name=None, description=None, errors=None)
Initialize a QuantumErrorProfile.
- to_yaml_file(yaml_file)
Save quantum error profile to YAML file.
- Return type:
- Parameters:
yaml_file (str | pathlib.Path) – Path to save YAML file.
- classmethod from_yaml_file(yaml_file)
Load quantum error profile from YAML file.
- Return type:
- Parameters:
yaml_file (str | pathlib.Path) – Path to YAML file.
- Returns:
Loaded profile.
- Return type:
- get_summary()
Get a human-readable summary of the QuantumErrorProfile.
- to_json()
Convert the QuantumErrorProfile to a dictionary for JSON serialization.
- to_hdf5(group)
Save the QuantumErrorProfile to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write the quantum error profile to.
- classmethod from_json(json_data)
Create a QuantumErrorProfile from a JSON dictionary.
- Return type:
- Parameters:
json_data (dict[str, Any]) – Dictionary containing the serialized data.
- Returns:
New instance of the QuantumErrorProfile.
- Return type:
- Raises:
RuntimeError – If version field is missing or incompatible.
- classmethod from_hdf5(group)
Load a QuantumErrorProfile from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to read data from.
- Returns:
New instance of the QuantumErrorProfile.
- Return type:
- Raises:
RuntimeError – If version attribute is missing or incompatible.
- class qdk_chemistry.data.QubitHamiltonian(pauli_strings, coefficients)
Bases:
DataClassData class for representing chemical electronic Hamiltonians in qubits.
- coefficients
Array of coefficients corresponding to each Pauli string.
- Type:
- __init__(pauli_strings, coefficients)
Initialize a QubitHamiltonian.
- Parameters:
pauli_strings (list[str]) – List of Pauli strings representing the
QubitHamiltonian.coefficients (numpy.ndarray) – Array of coefficients corresponding to each Pauli string.
- Raises:
ValueError – If the number of Pauli strings and coefficients don’t match, or if the Pauli strings or coefficients are invalid.
- Return type:
None
- property num_qubits: int
Get the number of qubits in the Hamiltonian.
- Returns:
The number of qubits.
- Return type:
- property pauli_ops: SparsePauliOp
Get the qubit Hamiltonian as a
SparsePauliOp.- Returns:
The qubit Hamiltonian represented as a
SparsePauliOp.- Return type:
- group_commuting(qubit_wise=True)
Group the qubit Hamiltonian into commuting subsets.
- Return type:
- Parameters:
qubit_wise (bool) – Whether to use qubit-wise commuting grouping. Default is True.
- Returns:
A list of
QubitHamiltonianrepresenting the grouped Hamiltonian.- Return type:
- get_summary()
Get a human-readable summary of the qubit Hamiltonian.
- to_json()
Convert the qubit Hamiltonian to a dictionary for JSON serialization.
- to_hdf5(group)
Save the qubit Hamiltonian to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write the qubit Hamiltonian to.
- classmethod from_json(json_data)
Create a QubitHamiltonian from a JSON dictionary.
- Return type:
- Parameters:
json_data (dict[str, Any]) – Dictionary containing the serialized data.
- Returns:
New instance reconstructed from JSON data.
- Return type:
- Raises:
RuntimeError – If version field is missing or incompatible.
- classmethod from_hdf5(group)
Load a QubitHamiltonian from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file containing the data.
- Returns:
New instance reconstructed from HDF5 data.
- Return type:
- Raises:
RuntimeError – If version attribute is missing or incompatible.
- class qdk_chemistry.data.SciWavefunctionContainer
Bases:
WavefunctionContainerSelected CI wavefunction container implementation.
This container represents wavefunctions obtained from selected configuration interaction (SCI) methods or full configuration interaction (FCI).
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.SciWavefunctionContainer, coeffs: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”], dets: collections.abc.Sequence[qdk_chemistry.data.Configuration], orbitals: qdk_chemistry.data.Orbitals, type: qdk_chemistry.data.WavefunctionType = <WavefunctionType.SelfDual: 0>) -> None
Constructs a basic SCI wavefunction container.
- Parameters:
coeffs (numpy.ndarray) – The vector of CI coefficients (real or complex)
dets (list[Configuration]) – The vector of determinants
orbitals (Orbitals) – Shared pointer to orbital basis set
type (WavefunctionType | None) – Type of wavefunction (default: SelfDual)
Examples
>>> import numpy as np >>> coeffs = np.array([0.9, 0.1]) >>> dets = [qdk_chemistry.Configuration("33221100"), qdk_chemistry.Configuration("33221001")] >>> container = qdk_chemistry.SciWavefunctionContainer(coeffs, dets, orbitals)
__init__(self: qdk_chemistry.data.SciWavefunctionContainer, coeffs: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”], dets: collections.abc.Sequence[qdk_chemistry.data.Configuration], orbitals: qdk_chemistry.data.Orbitals, one_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, two_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, type: qdk_chemistry.data.WavefunctionType = <WavefunctionType.SelfDual: 0>) -> None
Constructs a SCI wavefunction container with spin-traced RDMs.
- Parameters:
coeffs (numpy.ndarray) – The vector of CI coefficients (real or complex)
dets (list[Configuration]) – The vector of determinants
orbitals (Orbitals) – Shared pointer to orbital basis set
one_rdm_spin_traced (numpy.ndarray | None) – Spin-traced one-particle reduced density matrix
two_rdm_spin_traced (numpy.ndarray | None) – Spin-traced two-particle reduced density matrix
type (WavefunctionType | None) – Type of wavefunction (default: SelfDual)
Examples
>>> import numpy as np >>> coeffs = np.array([0.9, 0.1]) >>> dets = [qdk_chemistry.Configuration("33221100"), qdk_chemistry.Configuration("33221001")] >>> one_rdm = np.eye(4) # Example 1-RDM >>> container = qdk_chemistry.SciWavefunctionContainer(coeffs, dets, orbitals, one_rdm, None)
__init__(self: qdk_chemistry.data.SciWavefunctionContainer, coeffs: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”], dets: collections.abc.Sequence[qdk_chemistry.data.Configuration], orbitals: qdk_chemistry.data.Orbitals, one_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, one_rdm_aa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, one_rdm_bb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, n]”] | None = None, two_rdm_spin_traced: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, two_rdm_aabb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, two_rdm_aaaa: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, two_rdm_bbbb: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] | typing.Annotated[numpy.typing.ArrayLike, numpy.complex128, “[m, 1]”] | None = None, type: qdk_chemistry.data.WavefunctionType = <WavefunctionType.SelfDual: 0>) -> None
Constructs a SCI wavefunction container with full RDM data.
- Parameters:
coeffs (numpy.ndarray) – The vector of CI coefficients (real or complex)
dets (list[Configuration]) – The vector of determinants
orbitals (Orbitals) – Shared pointer to orbital basis set
one_rdm_spin_traced (numpy.ndarray | None) – Spin-traced one-particle reduced density matrix
one_rdm_aa (numpy.ndarray | None) – Alpha-alpha block of one-particle RDM
one_rdm_bb (numpy.ndarray | None) – Beta-beta block of one-particle RDM
two_rdm_spin_traced (numpy.ndarray | None) – Spin-traced two-particle reduced density matrix
two_rdm_aabb (numpy.ndarray | None) – Alpha-beta-beta-alpha block of two-particle RDM
two_rdm_aaaa (numpy.ndarray | None) – Alpha-alpha-alpha-alpha block of two-particle RDM
two_rdm_bbbb (numpy.ndarray | None) – Beta-beta-beta-beta block of two-particle RDM
type (WavefunctionType | None) – Type of wavefunction (default: SelfDual)
Examples
>>> import numpy as np >>> coeffs = np.array([0.9, 0.1]) >>> dets = [qdk_chemistry.Configuration("33221100"), qdk_chemistry.Configuration("33221001")] >>> container = qdk_chemistry.SciWavefunctionContainer(coeffs, dets, orbitals, ... one_rdm, one_rdm_aa, one_rdm_bb, ... two_rdm, two_rdm_aabb, two_rdm_aaaa, two_rdm_bbbb)
- get_coefficients(self: qdk_chemistry.data.SciWavefunctionContainer) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'] | Annotated[numpy.typing.NDArray[numpy.complex128], '[m, 1]']
Get the coefficients of the wavefunction
- qdk_chemistry.data.SettingNotFoundError
alias of
SettingNotFound
- qdk_chemistry.data.SettingTypeMismatchError
alias of
SettingTypeMismatch
- class qdk_chemistry.data.SettingValue
Bases:
pybind11_objectType-safe variant for storing different setting value types.
This variant can hold common types used in settings configurations: bool, int, long, size_t, float, double, string, vector<int>, vector<double>, vector<string>
- __init__(*args, **kwargs)
- class qdk_chemistry.data.Settings
Bases:
DataClassBase 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 _set_default.
Examples
To create a custom settings class in Python: >>> class MySettings(qdk_chemistry.data.Settings): … def __init__(self): … super().__init__() … self._set_default(“method”, “string”, “default”) … self._set_default(“max_iterations”, “int”, 100) … self._set_default(“convergence_threshold”, “double”, 1e-6) … >>> settings = MySettings() >>> settings[“method”] = “hf” >>> settings.method = “hf” # Alternative access >>> settings[“max_iterations”] = 200 >>> settings[“convergence_threshold”] = 1e-8 >>> value = settings[“method”] >>> print(“convergence_threshold” in settings) >>> print(len(settings)) >>> >>> # Iterator functionality >>> for key in settings: … print(key, settings[key]) >>> for key in settings.keys(): … print(key) >>> for value in settings.values(): … print(value) >>> for key, value in settings.items(): … print(f”{key}: {value}”) >>> >>> print(settings.to_dict()) # Convert to dict
Alternative: If you have an existing Settings object
>>> settings = get_settings_from_somewhere() # Already has keys defined >>> settings["method"] = "hf" # This works if "method" key exists >>> settings.method = "hf" # This also works
- __init__(self: qdk_chemistry.data.Settings) None
Default constructor.
Creates an empty Settings object with no key-value pairs.
Examples
>>> settings = Settings()
- as_table(self: qdk_chemistry.data.Settings, max_width: SupportsInt = 120, show_undocumented: bool = False) str
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:
- Returns:
Formatted table string
- Return type:
Examples
>>> print(settings.as_table()) ------------------------------------------------------------ Key | Value | Limits | Description ------------------------------------------------------------ max_iterations | 100 | [1, 1000] | Maximum number of iterations method | "hf" | ["hf", "dft"...] | Electronic structure method tolerance | 1.00e-06 | [1.00e-08, 1.00... | Convergence tolerance ------------------------------------------------------------
- empty(self: qdk_chemistry.data.Settings) bool
Check if settings are empty.
- Returns:
True if no settings are stored, False otherwise
- Return type:
Examples
>>> if settings.empty(): ... print("No settings configured")
- from_dict(*args, **kwargs)
Overloaded function.
from_dict(self: qdk_chemistry.data.Settings, dict: dict) -> None
Load settings from Python dictionary.
Updates existing settings with values from the provided dictionary. Keys must be strings or convertible to strings. Only predefined settings keys can be updated. Values must match expected types.
- Parameters:
dict (dict) – Python dictionary containing settings
- Raises:
SettingNotFound – If any key does not exist in settings
SettingTypeMismatch – If any value type does not match the expected type for its key
Examples
>>> config = { ... 'method': 'hf', ... 'max_iterations': 100, ... 'tolerance': 1e-6, ... 'parameters': [1.0, 2.0, 3.0] ... } >>> settings.from_dict(config) >>> assert settings['method'] == 'hf'
from_dict(self: qdk_chemistry.data.Settings, dict: dict) -> None
Load settings from Python dictionary.
Updates existing settings with values from the provided dictionary. Keys must be strings or convertible to strings. Only predefined settings keys can be updated. Values must match expected types.
- Parameters:
dict (dict) – Python dictionary containing settings
- Raises:
SettingNotFound – If any key does not exist in settings
SettingTypeMismatch – If any value type does not match the expected type for its key
Examples
>>> config = { ... 'method': 'hf', ... 'max_iterations': 100, ... 'tolerance': 1e-6, ... 'parameters': [1.0, 2.0, 3.0] ... } >>> settings.from_dict(config) >>> assert settings['method'] == 'hf'
- static from_file(filename: object, format_type: str) qdk_chemistry.data.Settings
Load settings from file in specified format.
- Parameters:
filename (str | pathlib.Path) – Path to input file.
format_type (str) – Format type (“json” or “hdf5”)
- Raises:
RuntimeError – If the file cannot be opened, read, or contains invalid settings data
Examples
>>> settings.from_file("config.settings.json", "json") >>> settings.from_file("config.settings.h5", "hdf5") >>> from pathlib import Path >>> settings.from_file(Path("config.settings.json"), "json")
- static from_hdf5_file(filename: object) qdk_chemistry.data.Settings
Load settings from HDF5 file.
- Parameters:
filename (str) – Path to input file. Must have ‘.settings.h5’ extension (e.g.,
config.settings.h5,parameters.settings.h5)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid settings data
Examples
>>> settings.from_hdf5_file("config.settings.h5") >>> settings.from_hdf5_file("parameters.settings.h5")
- static from_json(json_str: str) qdk_chemistry.data.Settings
Load settings from JSON format.
Parses a JSON string and loads all contained settings, replacing any existing settings. The JSON format should match the output of
to_json().- Parameters:
json_str (str) – JSON string containing settings data
- Raises:
RuntimeError – If the JSON string is malformed or contains unsupported types
Examples
>>> json_data = '{"method": "hf", "max_iterations": 100}' >>> settings.from_json(json_data) >>> assert settings["method"] == "hf"
- static from_json_file(*args, **kwargs)
Overloaded function.
from_json_file(filename: object) -> qdk_chemistry.data.Settings
Load settings from JSON file.
Reads settings from a JSON file, replacing any existing settings. The file should contain JSON data in the format produced by
to_json_file().- Parameters:
filename (str | pathlib.Path) – Path to the JSON file to read. Must have ‘.settings’ before the file extension (e.g.,
config.settings.json,params.settings.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains malformed JSON
Examples
>>> settings.from_json_file("config.settings.json") >>> settings.from_json_file("params.settings.json") >>> from pathlib import Path >>> settings.from_json_file(Path("config.settings.json"))
from_json_file(filename: object) -> qdk_chemistry.data.Settings
Load settings from JSON file.
Reads settings from a JSON file, replacing any existing settings. The file should contain JSON data in the format produced by
to_json_file().- Parameters:
filename (str | pathlib.Path) – Path to the JSON file to read. Must have ‘.settings’ before the file extension (e.g.,
config.settings.json,params.settings.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains malformed JSON
Examples
>>> settings.from_json_file("config.settings.json") >>> settings.from_json_file("parameters.settings.json") >>> from pathlib import Path >>> settings.from_json_file(Path("config.settings.json"))
from_json_file(filename: object) -> qdk_chemistry.data.Settings
Load settings from JSON file.
- Parameters:
filename (str | pathlib.Path) – Path to input file. Must have ‘.settings.json’ extension (e.g.,
config.settings.json,parameters.settings.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid settings data
Examples
>>> settings.from_json_file("config.settings.json") >>> settings.from_json_file("parameters.settings.json") >>> from pathlib import Path >>> settings.from_json_file(Path("config.settings.json"))
- static from_json_string(json_str: str) qdk_chemistry.data.Settings
Load settings from JSON string format.
This is an alias for
from_json()provided for backward compatibility. Both methods accept the same JSON string format.- Parameters:
json_str (str) – JSON string containing settings data
- Raises:
RuntimeError – If the JSON string is malformed or contains unsupported types
Examples
>>> settings.from_json_string('{"method": "hf"}') >>> # Equivalent to: >>> settings.from_json('{"method": "hf"}')
- get(self: qdk_chemistry.data.Settings, key: str) object
Get a setting value as a Python object.
Retrieves the value associated with the given key and converts it to the appropriate Python type.
- Parameters:
key (str) – The setting key name
- Returns:
The setting value as a Python object (bool, int, float, str, list)
- Return type:
- Raises:
SettingNotFound – If the key is not found in the settings
Examples
>>> method = settings.get("method") >>> max_iter = settings.get("max_iterations") >>> convergence_threshold = settings.get("convergence_threshold")
- get_as_string(self: qdk_chemistry.data.Settings, key: str) str
Get a setting value as a string representation.
Converts any setting value to its string representation, regardless of the original type.
- Parameters:
key (str) – The setting key name
- Returns:
String representation of the setting value
- Return type:
- Raises:
SettingNotFound – If the key is not found
Examples
>>> str_val = settings.get_as_string("convergence_threshold") # "1e-06" >>> str_val = settings.get_as_string("max_iterations") # "100"
- get_description(self: qdk_chemistry.data.Settings, key: str) str
Get the description of a setting.
- Parameters:
key (str) – The setting key name
- Returns:
The description string
- Return type:
- Raises:
SettingNotFound – If the key doesn’t exist or has no description
Examples
>>> desc = settings.get_description("max_iterations") >>> print(desc) # "Maximum number of iterations"
- get_expected_python_type(self: qdk_chemistry.data.Settings, key: str) str
Get the expected Python type for a setting key.
Returns a string describing what Python type should be provided when setting the value for the given key. This is useful for understanding what type of value is expected before attempting to set it.
- Parameters:
key (str) – The setting key name
- Returns:
Expected Python type (e.g., “int”, “float”, “str”, “bool”, “list[int]”, “list[float]”, “list[str]”, “list[bool]”)
- Return type:
- Raises:
SettingNotFound – If the key is not found
Examples
>>> expected = settings.get_expected_python_type("max_iterations") >>> print(expected) # "int" >>> expected = settings.get_expected_python_type("convergence_threshold") >>> print(expected) # "float" >>> expected = settings.get_expected_python_type("basis_set") >>> print(expected) # "str" >>> expected = settings.get_expected_python_type("active_orbitals") >>> print(expected) # "list[int]"
- get_limits(self: qdk_chemistry.data.Settings, key: str) object
Get the limits of a setting.
Returns the limit value which can be a range (tuple of min, max) or an enumeration (list of allowed values).
- Parameters:
key (str) – The setting key name
- Returns:
The limit value - either a range tuple or a list of allowed values
- Return type:
tuple[int, int] | tuple[float, float] | list[int] | list[str]
- Raises:
SettingNotFound – If the key doesn’t exist or has no limits
Examples
>>> limits = settings.get_limits("max_iterations") >>> print(limits) # (1, 1000) for a range >>> >>> limits = settings.get_limits("method") >>> print(limits) # ['hf', 'dft', 'mp2'] for allowed values
- get_or_default(self: qdk_chemistry.data.Settings, key: str, default_value: object) object
Get a setting value with a default if not found (accepts any Python object).
Retrieves the value for the given key if it exists, or returns the default value if the key is not found.
- Parameters:
- Returns:
The setting value or default value as a Python object
- Return type:
Examples
>>> method = settings.get_or_default("method", "default_method") >>> max_iter = settings.get_or_default("max_iterations", 1000) >>> params = settings.get_or_default("parameters", [])
- get_or_default_raw(self: qdk_chemistry.data.Settings, key: str, default_value: bool | SupportsInt | SupportsFloat | str | collections.abc.Sequence[SupportsInt] | collections.abc.Sequence[SupportsFloat] | collections.abc.Sequence[str]) bool | int | float | str | list[int] | list[float] | list[str]
Get a setting value with a default if not found (SettingValue).
Raw interface that works with SettingValue variants directly.
- Parameters:
key (str) – The setting key name
default_value (SettingValue) – Default
SettingValueto return if key not found
- Returns:
The
SettingValuevariant or default value- Return type:
- get_raw(self: qdk_chemistry.data.Settings, key: str) bool | int | float | str | list[int] | list[float] | list[str]
Get a setting value as a
SettingValuevariant.This is the raw interface that returns a
SettingValuedirectly, primarily for internal use or advanced scenarios.- Parameters:
key (str) – The setting key name
- Returns:
The SettingValue variant
- Return type:
- Raises:
SettingNotFound – If the key is not found in the settings
- get_type_name(*args, **kwargs)
Overloaded function.
get_type_name(self: qdk_chemistry.data.Settings, key: str) -> str
Get the type name of a setting value.
Returns a string describing the current type of the value stored for the given key.
- Parameters:
key (str) – The setting key name
- Returns:
Type name (e.g., “int”, “double”, “string”, “vector<int>”)
- Return type:
- Raises:
SettingNotFound – If the key is not found
Examples
>>> type_name = settings.get_type_name("max_iterations") # "int" >>> type_name = settings.get_type_name("convergence_threshold") # "double"
get_type_name(self: qdk_chemistry.data.Settings, key: str) -> str
Get the type name of a setting value.
Returns a string describing the current type of the value stored for the given key.
- Parameters:
key (str) – The setting key name
- Returns:
Type name (e.g., “int”, “double”, “string”, “vector<int>”)
- Return type:
- Raises:
SettingNotFound – If the key is not found
Examples
>>> type_name = settings.get_type_name("max_iterations") # "int" >>> type_name = settings.get_type_name("convergence_threshold") # "double"
- has(self: qdk_chemistry.data.Settings, key: str) bool
Check if a setting exists.
- Parameters:
key (str) – The setting key name to check
- Returns:
True if the setting exists, False otherwise
- Return type:
Examples
>>> if settings.has("method"): ... method = settings.get("method") >>> exists = settings.has("nonexistent_key") # False
- has_description(self: qdk_chemistry.data.Settings, key: str) bool
Check if a setting has a description.
- Parameters:
key (str) – The setting key name
- Returns:
True if the setting has a description, False otherwise
- Return type:
Examples
>>> if settings.has_description("max_iterations"): ... desc = settings.get_description("max_iterations")
- has_limits(self: qdk_chemistry.data.Settings, key: str) bool
Check if a setting has defined limits.
- Parameters:
key (str) – The setting key name
- Returns:
True if the setting has limits defined, False otherwise
- Return type:
Examples
>>> if settings.has_limits("max_iterations"): ... limits = settings.get_limits("max_iterations")
- is_documented(self: qdk_chemistry.data.Settings, key: str) bool
Check if a setting is documented.
- Parameters:
key (str) – The setting key name
- Returns:
True if the setting is marked as documented, False otherwise
- Return type:
- Raises:
SettingNotFound – If the key doesn’t exist
Examples
>>> if settings.is_documented("max_iterations"): ... print("This setting is documented")
- items(*args, **kwargs)
Overloaded function.
items(self: qdk_chemistry.data.Settings) -> list
Get key-value pairs as a list of tuples.
Examples
>>> all_items = settings.items() >>> for key, value in all_items: ... print(f"{key}: {value}") >>> # Or iterate directly: >>> for key, value in settings.items(): ... print(f"{key}: {value}")
items(self: qdk_chemistry.data.Settings) -> list
Get key-value pairs as a list of tuples.
Examples
>>> all_items = settings.items() >>> for key, value in all_items: ... print(f"{key}: {value}") >>> # Or iterate directly: >>> for key, value in settings.items(): ... print(f"{key}: {value}")
- keys(self: qdk_chemistry.data.Settings) list[str]
Get all setting keys.
Examples
>>> all_keys = settings.keys() >>> for key in all_keys: ... print(f"{key}: {settings[key]}")
- lock(self: qdk_chemistry.data.Settings) None
Lock the settings to prevent further modifications.
Once settings are locked, any attempt to modify them will raise an exception. This is useful to ensure that settings remain unchanged after they have been validated or after a computation has started.
Notes
Locking is irreversible for the lifetime of the Settings object. To modify settings after locking, create a copy of the Settings object.
Examples
>>> settings["method"] = "hf" >>> settings["max_iterations"] = 100 >>> settings.lock() >>> # Any further modifications will raise SettingsAreLocked exception >>> settings["method"] = "dft" # Raises SettingsAreLocked
- set(self: qdk_chemistry.data.Settings, key: str, value: object) None
Set a setting value (accepts any Python object).
This method allows setting values using any supported Python type, which will be automatically converted to the appropriate SettingValue variant. The value must match the expected type for the setting key.
- Parameters:
- Raises:
SettingNotFound – If the key does not exist in settings
SettingTypeMismatch – If the value type does not match the expected type for this key
RuntimeError – If the value type is not supported or if the key cannot be set
Examples
>>> settings.set("method", "hf") >>> settings.set("max_iterations", 100) >>> settings.set("convergence_threshold", 1e-6) >>> settings.set("parameters", [1.0, 2.0, 3.0])
- set_raw(self: qdk_chemistry.data.Settings, key: str, value: bool | SupportsInt | SupportsFloat | str | collections.abc.Sequence[SupportsInt] | collections.abc.Sequence[SupportsFloat] | collections.abc.Sequence[str]) None
Set a setting value using a SettingValue variant.
This is the raw interface that accepts a SettingValue directly, primarily for internal use or advanced scenarios.
- Parameters:
key (str) – The setting key name
value (SettingValue) – The SettingValue variant to set
- Raises:
RuntimeError – If the key cannot be set
- size(self: qdk_chemistry.data.Settings) int
Get the number of settings.
- Returns:
Number of setting key-value pairs
- Return type:
Examples
>>> count = settings.size() >>> print(f"Settings contain {count} entries")
- to_dict(*args, **kwargs)
Overloaded function.
to_dict(self: qdk_chemistry.data.Settings) -> dict
Convert settings to Python dictionary.
Creates a Python dictionary containing all settings with keys as strings and values converted to appropriate Python types.
- Returns:
Python dictionary with all settings
- Return type:
Examples
>>> settings_dict = settings.to_dict() >>> print(settings_dict) {'method': 'hf', 'max_iterations': 100, 'tolerance': 1e-06} >>> >>> # Can be used with JSON, pickle, etc. >>> import json >>> json_str = json.dumps(settings_dict)
to_dict(self: qdk_chemistry.data.Settings) -> dict
Convert settings to Python dictionary.
Creates a Python dictionary containing all settings with keys as strings and values converted to appropriate Python types.
- Returns:
Python dictionary with all settings
- Return type:
Examples
>>> settings_dict = settings.to_dict() >>> print(settings_dict) {'method': 'hf', 'max_iterations': 100, 'tolerance': 1e-06} >>> >>> # Can be used with JSON, pickle, etc. >>> import json >>> json_str = json.dumps(settings_dict)
- to_file(self: qdk_chemistry.data.Settings, filename: object, format_type: str) None
Save settings to file in specified format.
- Parameters:
filename (str | pathlib.Path) – Path to output file.
format_type (str) – Format type (“json” or “hdf5”)
- Raises:
RuntimeError – If the file cannot be opened or written
Examples
>>> settings.to_file("config.settings.json", "json") >>> settings.to_file("config.settings.h5", "hdf5") >>> from pathlib import Path >>> settings.to_file(Path("config.settings.json"), "json")
- to_hdf5_file(self: qdk_chemistry.data.Settings, filename: str) None
Save settings to HDF5 file.
- Parameters:
filename (str) – Path to output file. Must have ‘.settings.h5’ extension (e.g.,
config.settings.h5,parameters.settings.h5)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened or written
Examples
>>> settings.to_hdf5_file("config.settings.h5") >>> settings.to_hdf5_file("parameters.settings.h5")
- to_json(self: qdk_chemistry.data.Settings) str
Convert settings to JSON format.
Serializes all settings to a JSON string with pretty formatting. The JSON format preserves all type information and can be used to reconstruct the settings later.
- Returns:
JSON string representation of all settings
- Return type:
Examples
>>> json_str = settings.to_json() >>> print(json_str) { "method": "hf", "max_iterations": 100, "convergence_threshold": 1e-06 }
- to_json_file(*args, **kwargs)
Overloaded function.
to_json_file(self: qdk_chemistry.data.Settings, filename: object) -> None
Save settings to JSON file.
Writes all settings to a JSON file with pretty formatting. The file will be created or overwritten if it already exists.
- Parameters:
filename (str | pathlib.Path) – Path to the JSON file to write. Must have ‘.settings’ before the file extension (e.g.,
config.settings.json,params.settings.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened or written
Examples
>>> settings.to_json_file("config.settings.json") >>> settings.to_json_file("params.settings.json") >>> from pathlib import Path >>> settings.to_json_file(Path("config.settings.json"))
to_json_file(self: qdk_chemistry.data.Settings, filename: object) -> None
Save settings to JSON file.
- Parameters:
filename (str | pathlib.Path) – Path to output file. Must have ‘.settings.json’ extension (e.g.,
config.settings.json,parameters.settings.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened or written
Examples
>>> settings.to_json_file("config.settings.json") >>> settings.to_json_file("parameters.settings.json") >>> from pathlib import Path >>> settings.to_json_file(Path("config.settings.json"))
to_json_file(self: qdk_chemistry.data.Settings, filename: object) -> None
Save settings to JSON file.
- Parameters:
filename (str | pathlib.Path) – Path to output file. Must have ‘.settings.json’ extension (e.g.,
config.settings.json,parameters.settings.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened or written
Examples
>>> settings.to_json_file("config.settings.json") >>> settings.to_json_file("parameters.settings.json") >>> from pathlib import Path >>> settings.to_json_file(Path("config.settings.json"))
- to_json_string(self: qdk_chemistry.data.Settings) str
Convert settings to JSON string format.
This is an alias for
to_json()provided for backward compatibility. Both methods return the same JSON string representation.- Returns:
JSON string representation of all settings
- Return type:
Examples
>>> json_str = settings.to_json_string() >>> # Equivalent to: >>> json_str = settings.to_json()
- update(*args, **kwargs)
Overloaded function.
update(self: qdk_chemistry.data.Settings, key: str, value: object) -> None
Update a setting value, throwing if key doesn’t exist.
Unlike
set(), this method will only update existing settings and will raise an exception if the key is not already present. Accepts any Python object for the value, which must match the expected type.- Parameters:
- Raises:
SettingNotFound – If the key doesn’t exist in the settings
SettingTypeMismatch – If the value type does not match the expected type for this key
RuntimeError – If the value type is not supported
Examples
>>> settings.update("max_iterations", 200) # OK if key exists >>> settings.update("new_key", "value") # Raises SettingNotFound
>>> updates = { ... 'max_iterations': 200, ... 'tolerance': 1e-8 ... } >>> settings.update(updates) # OK if both keys exist >>> settings.update({'new_key': 'value'}) # Raises SettingNotFound
update(self: qdk_chemistry.data.Settings, dict: dict) -> None
update(self: qdk_chemistry.data.Settings, key: str, value: object) -> None
Update a setting value, throwing if key doesn’t exist.
Unlike
set(), this method will only update existing settings and will raise an exception if the key is not already present. Accepts any Python object for the value, which must match the expected type.- Parameters:
- Raises:
SettingNotFound – If the key doesn’t exist in the settings
SettingTypeMismatch – If the value type does not match the expected type for this key
RuntimeError – If the value type is not supported
Examples
>>> settings.update("max_iterations", 200) # OK if key exists >>> settings.update("new_key", "value") # Raises SettingNotFound
>>> updates = { ... 'max_iterations': 200, ... 'tolerance': 1e-8 ... } >>> settings.update(updates) # OK if both keys exist >>> settings.update({'new_key': 'value'}) # Raises SettingNotFound
update(self: qdk_chemistry.data.Settings, dict: dict) -> None
- update_raw(*args, **kwargs)
Overloaded function.
update_raw(self: qdk_chemistry.data.Settings, key: str, value: bool | typing.SupportsInt | typing.SupportsFloat | str | collections.abc.Sequence[typing.SupportsInt] | collections.abc.Sequence[typing.SupportsFloat] | collections.abc.Sequence[str]) -> None
Update a setting value using
SettingValue, throwing if key doesn’t exist.Raw interface that works with
SettingValuevariants directly.- Parameters:
key (str) – The setting key name (must already exist)
value (SettingValue) – The new SettingValue to set
- Raises:
SettingNotFound – If the key doesn’t exist in the settings
update_raw(self: qdk_chemistry.data.Settings, key: str, value: bool | typing.SupportsInt | typing.SupportsFloat | str | collections.abc.Sequence[typing.SupportsInt] | collections.abc.Sequence[typing.SupportsFloat] | collections.abc.Sequence[str]) -> None
Update a setting value using
SettingValue, throwing if key doesn’t exist.Raw interface that works with
SettingValuevariants directly.- Parameters:
key (str) – The setting key name (must already exist)
value (SettingValue) – The new SettingValue to set
- Raises:
SettingNotFound – If the key doesn’t exist in the settings
- validate_required(*args, **kwargs)
Overloaded function.
validate_required(self: qdk_chemistry.data.Settings, required_keys: collections.abc.Sequence[str]) -> None
Validate that all required settings are present.
Checks that all keys in the provided list exist in the settings. This is useful for ensuring that all necessary configuration parameters have been set before proceeding with computations.
- Parameters:
required_keys (list[str]) – List of setting keys that must be present
- Raises:
SettingNotFound – If any required key is missing
Examples
>>> required = ["method", "max_iter"] >>> settings.validate_required(required) >>> # Raises SettingNotFound if any key is missing
validate_required(self: qdk_chemistry.data.Settings, required_keys: collections.abc.Sequence[str]) -> None
Validate that all required settings are present.
Checks that all keys in the provided list exist in the settings. This is useful for ensuring that all necessary configuration parameters have been set before proceeding with computations.
- Parameters:
required_keys (list[str]) – List of setting keys that must be present
- Raises:
SettingNotFound – If any required key is missing
Examples
>>> required = ["method", "max_iter"] >>> settings.validate_required(required) >>> # Raises SettingNotFound if any key is missing
- values(*args, **kwargs)
Overloaded function.
values(self: qdk_chemistry.data.Settings) -> list
Get all setting values as a list.
- Returns:
List of all setting values
- Return type:
Examples
>>> all_values = settings.values() >>> for value in all_values: ... print(value) >>> # Or iterate directly: >>> for value in settings.values(): ... print(value)
values(self: qdk_chemistry.data.Settings) -> list
Get all setting values as a list.
- Returns:
List of all setting values
- Return type:
Examples
>>> all_values = settings.values() >>> for value in all_values: ... print(value) >>> # Or iterate directly: >>> for value in settings.values(): ... print(value)
- qdk_chemistry.data.SettingsAreLockedError
alias of
SettingsAreLocked
- class qdk_chemistry.data.Shell
Bases:
pybind11_objectShell of atomic orbitals
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.Shell, atom_index: typing.SupportsInt, orbital_type: qdk_chemistry.data.OrbitalType, exponents: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], coefficients: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”]) -> None
Constructor with complete primitive data.
Creates a shell with all primitive functions specified.
- Parameters:
atom_index (int) – Index of the atom this shell belongs to
orbital_type (OrbitalType) – Type of orbital (S, P, D, F, etc.)
exponents (numpy.ndarray) – Vector of Gaussian exponent coefficients (alpha values)
coefficients (numpy.ndarray) – Vector of contraction coefficients (must be same length as exponents)
- Raises:
ValueError – If exponents and coefficients have different lengths
Examples
>>> import numpy as np >>> exponents = np.array([1.0, 0.5, 0.1]) >>> coefficients = np.array([0.444, 0.555, 0.222]) >>> shell = Shell(0, OrbitalType.S, exponents, coefficients)
__init__(self: qdk_chemistry.data.Shell, atom_index: typing.SupportsInt, orbital_type: qdk_chemistry.data.OrbitalType, exponents: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], coefficients: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], rpowers: typing.Annotated[numpy.typing.ArrayLike, numpy.int32, “[m, 1]”]) -> None
Constructor with primitive data and radial powers for ECP shells.
Creates an ECP (Effective Core Potential) shell with radial powers.
- Parameters:
atom_index (int) – Index of the atom this shell belongs to
orbital_type (OrbitalType) – Type of orbital (S, P, D, F, etc.)
exponents (numpy.ndarray) – Vector of Gaussian exponent coefficients (alpha values)
coefficients (numpy.ndarray) – Vector of contraction coefficients (must be same length as exponents)
rpowers (numpy.ndarray[int]) – Vector of radial powers (r^n terms) for ECP shells
- Raises:
ValueError – If exponents, coefficients, and rpowers have different lengths
Examples
>>> import numpy as np >>> exponents = np.array([1.0, 0.5, 0.1]) >>> coefficients = np.array([0.444, 0.555, 0.222]) >>> rpowers = np.array([2, 1, 0], dtype=np.int32) >>> ecp_shell = Shell(0, OrbitalType.S, exponents, coefficients, rpowers)
- property atom_index
Index of the atom
- property coefficients
Vector of contraction coefficients
- property exponents
Vector of orbital exponents
- get_angular_momentum(self: qdk_chemistry.data.Shell) int
Get the angular momentum quantum number (l) for this shell.
- Returns:
Angular momentum quantum number (0=s, 1=p, 2=d, etc.)
- Return type:
Examples
>>> l = shell.get_angular_momentum() >>> print(f"Angular momentum l = {l}")
- get_num_atomic_orbitals(self: qdk_chemistry.data.Shell, atomic_orbital_type: qdk_chemistry.data.AOType = <AOType.Spherical: 0>) int
Get number of atomic orbitals this shell contributes.
- Parameters:
atomic_orbital_type (AOType | None) – Whether to use spherical (2l+1) or Cartesian functions. Default is Spherical
- Returns:
Number of atomic orbitals
- Return type:
Examples
>>> # For p-shell: 3 spherical, 3 Cartesian >>> n_sph = shell.get_num_atomic_orbitals(AOType.Spherical) >>> n_cart = shell.get_num_atomic_orbitals(AOType.Cartesian) >>> print(f"Spherical: {n_sph}, Cartesian: {n_cart}")
- get_num_primitives(self: qdk_chemistry.data.Shell) int
Get the number of primitive Gaussians in this shell.
- Returns:
Number of primitive functions
- Return type:
Examples
>>> n_prim = shell.get_num_primitives() >>> print(f"Shell has {n_prim} primitives")
- has_radial_powers(self: qdk_chemistry.data.Shell) bool
Check if this shell has radial powers (i.e., is an ECP shell).
- Returns:
True if this shell has radial powers defined
- Return type:
Examples
>>> if shell.has_radial_powers(): ... print("This is an ECP shell")
- property orbital_type
Type of orbital
- property rpowers
Vector of radial powers for ECP shells (r^n terms)
- class qdk_chemistry.data.SlaterDeterminantContainer
Bases:
WavefunctionContainerSingle Slater determinant wavefunction container implementation.
This container represents the simplest wavefunction - a single Slater determinant with coefficient 1.0. It provides efficient storage and computation for single-determinant wavefunctions such as Hartree-Fock reference states.
- __init__(self: qdk_chemistry.data.SlaterDeterminantContainer, det: qdk_chemistry.data.Configuration, orbitals: qdk_chemistry.data.Orbitals, type: qdk_chemistry.data.WavefunctionType = <WavefunctionType.SelfDual: 0>) None
Constructs a single Slater determinant wavefunction container.
- Parameters:
det (Configuration) – The single determinant configuration
orbitals (Orbitals) – Shared pointer to orbital basis set
type (WavefunctionType | None) – Type of wavefunction (default: Both)
Examples
>>> det = qdk_chemistry.Configuration("33221100") >>> container = qdk_chemistry.SlaterDeterminantContainer(det, orbitals)
- contains_determinant(self: qdk_chemistry.data.SlaterDeterminantContainer, det: qdk_chemistry.data.Configuration) bool
Check if a determinant matches the stored one
- class qdk_chemistry.data.SpinChannel
Bases:
pybind11_objectEnumeration for different spin channels in unrestricted calculations.
- Values:
aa: Alpha-alpha spin channel (for one-body integrals) bb: Beta-beta spin channel (for one-body integrals) aaaa: Alpha-alpha-alpha-alpha spin channel (for two-body integrals) aabb: Alpha-beta-alpha-beta spin channel (for two-body integrals) bbbb: Beta-beta-beta-beta spin channel (for two-body integrals)
Members:
aa
bb
aaaa
aabb
bbbb
- __init__(self: qdk_chemistry.data.SpinChannel, value: SupportsInt) None
- aa = <SpinChannel.aa: 0>
- aaaa = <SpinChannel.aaaa: 2>
- aabb = <SpinChannel.aabb: 3>
- bb = <SpinChannel.bb: 1>
- bbbb = <SpinChannel.bbbb: 4>
- SpinChannel.name -> str
- property value
- class qdk_chemistry.data.StabilityResult
Bases:
DataClassResult 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.
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
Examples
Create a stability result:
>>> import qdk_chemistry.data as data >>> import numpy as np >>> internal_eigenvals = np.array([1.0, 2.0, 3.0]) >>> external_eigenvals = np.array([0.5, 1.5]) >>> internal_eigenvecs = np.eye(3) >>> external_eigenvecs = np.eye(2) >>> result = data.StabilityResult(True, True, internal_eigenvals, internal_eigenvecs, ... external_eigenvals, external_eigenvecs)
Check if stable:
>>> print(result.is_stable()) True
Get internal eigenvalues:
>>> print(result.get_internal_eigenvalues()) [1. 2. 3.]
Get smallest eigenvalue overall:
>>> print(result.get_smallest_eigenvalue()) 0.5
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.StabilityResult) -> None
Default constructor
__init__(self: qdk_chemistry.data.StabilityResult, internal_stable: bool, external_stable: bool, internal_eigenvalues: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], internal_eigenvectors: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], external_eigenvalues: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”], external_eigenvectors: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”]) -> None
Construct a StabilityResult with specific values.
- Parameters:
internal_stable (bool) – True if internal stability is satisfied
external_stable (bool) – True if external stability is satisfied
internal_eigenvalues (numpy.ndarray) – Eigenvalues of the internal stability matrix
internal_eigenvectors (numpy.ndarray) – Eigenvectors of the internal stability matrix
external_eigenvalues (numpy.ndarray) – Eigenvalues of the external stability matrix
external_eigenvectors (numpy.ndarray) – Eigenvectors of the external stability matrix
Examples
>>> import numpy as np >>> from qdk_chemistry.data import StabilityResult >>> internal_eigenvals = np.array([1.0, 2.0, 3.0]) >>> external_eigenvals = np.array([0.5, 1.5]) >>> internal_eigenvecs = np.eye(3) >>> external_eigenvecs = np.eye(2) >>> result = StabilityResult(True, True, internal_eigenvals, internal_eigenvecs, ... external_eigenvals, external_eigenvecs)
- empty(self: qdk_chemistry.data.StabilityResult) bool
Check if stability result is empty (contains no eigenvalue/eigenvector data).
- Returns:
True if stability result contains no eigenvalue/eigenvector data
- Return type:
Examples
>>> if not result.empty(): ... print("Result contains stability data")
- property external_eigenvalues
Get the external eigenvalues of the stability matrix.
- Returns:
The external eigenvalues of the stability matrix
- Return type:
Examples
>>> external_eigenvals = result.get_external_eigenvalues() >>> print(f"External eigenvalues: {external_eigenvals}")
- property external_eigenvectors
Get the external eigenvectors of the stability matrix.
- Returns:
The external eigenvectors of the stability matrix
- Return type:
Examples
>>> external_eigenvecs = result.get_external_eigenvectors() >>> print(f"External eigenvectors shape: {external_eigenvecs.shape}")
- external_size(self: qdk_chemistry.data.StabilityResult) int
Get the number of external eigenvalues.
- Returns:
Number of external eigenvalues in the stability matrix
- Return type:
- static from_file(filename: object, type: str) qdk_chemistry.data.StabilityResult
Load stability result data from file with specified format (static method).
Generic method to load stability result data from a file.
- Parameters:
filename (str | pathlib.Path) – Path to the file to read.
type (str) – File format type (‘json’ or ‘hdf5’)
- Returns:
New
StabilityResultobject loaded from the file- Return type:
- Raises:
ValueError – If format_type is not supported or filename doesn’t follow naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid stability result data
Examples
>>> result = StabilityResult.from_file("water.stability_result.json", "json") >>> result = StabilityResult.from_file("molecule.stability_result.h5", "hdf5") >>> from pathlib import Path >>> result = StabilityResult.from_file(Path("water.stability_result.json"), "json")
- static from_hdf5_file(filename: object) qdk_chemistry.data.StabilityResult
Load stability result data from HDF5 file (static method with validation).
Reads stability result data from an HDF5 file. The file should contain data in the format produced by
to_hdf5_file().- Parameters:
filename (str | pathlib.Path) – Path to the HDF5 file to read. Must have ‘.stability_result’ before the file extension (e.g.,
water.stability_result.h5,molecule.stability_result.hdf5)- Returns:
New
StabilityResultobject loaded from the file- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid stability result data
Examples
>>> result = StabilityResult.from_hdf5_file("water.stability_result.h5") >>> result = StabilityResult.from_hdf5_file("molecule.stability_result.hdf5") >>> from pathlib import Path >>> result = StabilityResult.from_hdf5_file(Path("water.stability_result.h5"))
- static from_json(json_str: str) qdk_chemistry.data.StabilityResult
Load stability result data from JSON string (static method).
Parses stability result data from a JSON string and creates a new StabilityResult object. The string should contain JSON data in the format produced by
to_json().- Parameters:
json_str (str) – JSON string containing stability result data
- Returns:
New StabilityResult object created from JSON data
- Return type:
- Raises:
RuntimeError – If the JSON string is malformed or contains invalid stability result data
Examples
>>> result = StabilityResult.from_json('{"internal_stable": true, "external_stable": false, ...}')
- static from_json_file(filename: object) qdk_chemistry.data.StabilityResult
Load stability result data from JSON file (static method).
Reads stability result data from a JSON file. The file should contain JSON data in the format produced by
to_json_file().- Parameters:
filename (str | pathlib.Path) – Path to the JSON file to read. Must have ‘.stability_result’ before the file extension (e.g.,
water.stability_result.json,molecule.stability_result.json)- Returns:
New
StabilityResultobject loaded from the file- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid stability result data
Examples
>>> result = StabilityResult.from_json_file("water.stability_result.json") >>> result = StabilityResult.from_json_file("molecule.stability_result.json") >>> from pathlib import Path >>> result = StabilityResult.from_json_file(Path("water.stability_result.json"))
- get_external_eigenvalues(self: qdk_chemistry.data.StabilityResult) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']
Get the external eigenvalues of the stability matrix.
- Returns:
The external eigenvalues of the stability matrix
- Return type:
Examples
>>> external_eigenvals = result.get_external_eigenvalues() >>> print(f"External eigenvalues: {external_eigenvals}")
- get_external_eigenvectors(self: qdk_chemistry.data.StabilityResult) Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']
Get the external eigenvectors of the stability matrix.
- Returns:
The external eigenvectors of the stability matrix
- Return type:
Examples
>>> external_eigenvecs = result.get_external_eigenvectors() >>> print(f"External eigenvectors shape: {external_eigenvecs.shape}")
- get_internal_eigenvalues(self: qdk_chemistry.data.StabilityResult) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']
Get the internal eigenvalues of the stability matrix.
- Returns:
The internal eigenvalues of the stability matrix
- Return type:
Examples
>>> internal_eigenvals = result.get_internal_eigenvalues() >>> print(f"Internal eigenvalues: {internal_eigenvals}")
- get_internal_eigenvectors(self: qdk_chemistry.data.StabilityResult) Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']
Get the internal eigenvectors of the stability matrix.
- Returns:
The internal eigenvectors of the stability matrix
- Return type:
Examples
>>> internal_eigenvecs = result.get_internal_eigenvectors() >>> print(f"Internal eigenvectors shape: {internal_eigenvecs.shape}")
- get_smallest_eigenvalue(self: qdk_chemistry.data.StabilityResult) float
Get the smallest eigenvalue overall.
- Returns:
Smallest eigenvalue across both internal and external (most negative for unstable systems)
- Return type:
- Raises:
RuntimeError – If no eigenvalues are present
- get_smallest_eigenvalue_and_vector(self: qdk_chemistry.data.StabilityResult) tuple[float, Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get the smallest eigenvalue and its corresponding eigenvector overall.
- Returns:
Tuple of (eigenvalue, eigenvector) for the smallest eigenvalue across both internal and external
- Return type:
- Raises:
RuntimeError – If no eigenvalues are present
- get_smallest_external_eigenvalue(self: qdk_chemistry.data.StabilityResult) float
Get the smallest external eigenvalue.
- Returns:
Smallest external eigenvalue (most negative for unstable systems)
- Return type:
- Raises:
RuntimeError – If no external eigenvalues are present
- get_smallest_external_eigenvalue_and_vector(self: qdk_chemistry.data.StabilityResult) tuple[float, Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get the smallest external eigenvalue and its corresponding eigenvector.
- Returns:
Tuple of (eigenvalue, eigenvector) for the smallest external eigenvalue
- Return type:
- Raises:
RuntimeError – If no external eigenvalues are present
- get_smallest_internal_eigenvalue(self: qdk_chemistry.data.StabilityResult) float
Get the smallest internal eigenvalue.
- Returns:
Smallest internal eigenvalue (most negative for unstable systems)
- Return type:
- Raises:
RuntimeError – If no internal eigenvalues are present
- get_smallest_internal_eigenvalue_and_vector(self: qdk_chemistry.data.StabilityResult) tuple[float, Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get the smallest internal eigenvalue and its corresponding eigenvector.
- Returns:
Tuple of (eigenvalue, eigenvector) for the smallest internal eigenvalue
- Return type:
- Raises:
RuntimeError – If no internal eigenvalues are present
- get_summary(self: qdk_chemistry.data.StabilityResult) str
Get summary string of stability result information.
- Returns:
Summary information about the stability result
- Return type:
Examples
>>> summary = result.get_summary() >>> print(summary)
- has_external_result(self: qdk_chemistry.data.StabilityResult) bool
Check if stability result contains external eigenvalue/eigenvector data.
- Returns:
True if stability result contains external eigenvalue/eigenvector data
- Return type:
Examples
>>> if result.has_external_result(): ... print("Result contains external stability data")
- has_internal_result(self: qdk_chemistry.data.StabilityResult) bool
Check if stability result contains internal eigenvalue/eigenvector data.
- Returns:
True if stability result contains internal eigenvalue/eigenvector data
- Return type:
Examples
>>> if result.has_internal_result(): ... print("Result contains internal stability data")
- property internal_eigenvalues
Get the internal eigenvalues of the stability matrix.
- Returns:
The internal eigenvalues of the stability matrix
- Return type:
Examples
>>> internal_eigenvals = result.get_internal_eigenvalues() >>> print(f"Internal eigenvalues: {internal_eigenvals}")
- property internal_eigenvectors
Get the internal eigenvectors of the stability matrix.
- Returns:
The internal eigenvectors of the stability matrix
- Return type:
Examples
>>> internal_eigenvecs = result.get_internal_eigenvectors() >>> print(f"Internal eigenvectors shape: {internal_eigenvecs.shape}")
- internal_size(self: qdk_chemistry.data.StabilityResult) int
Get the number of internal eigenvalues.
- Returns:
Number of internal eigenvalues in the stability matrix
- Return type:
- is_external_stable(self: qdk_chemistry.data.StabilityResult) bool
Check if external stability is satisfied.
- Returns:
True if external stability is satisfied
- Return type:
- is_internal_stable(self: qdk_chemistry.data.StabilityResult) bool
Check if internal stability is satisfied.
- Returns:
True if internal stability is satisfied
- Return type:
- is_stable(self: qdk_chemistry.data.StabilityResult) bool
Check if the wavefunction is stable overall.
- Returns:
True if both internal and external stability are satisfied
- Return type:
Examples
>>> if result.is_stable(): ... print("Wavefunction is stable")
- set_external_eigenvalues(self: qdk_chemistry.data.StabilityResult, external_eigenvalues: Annotated[numpy.typing.ArrayLike, numpy.float64, '[m, 1]']) None
Set the external eigenvalues.
- Parameters:
external_eigenvalues (numpy.ndarray) – The external eigenvalues of the stability matrix
Examples
>>> import numpy as np >>> new_external_eigenvals = np.array([0.2, 1.8]) >>> result.set_external_eigenvalues(new_external_eigenvals)
- set_external_eigenvectors(self: qdk_chemistry.data.StabilityResult, external_eigenvectors: Annotated[numpy.typing.ArrayLike, numpy.float64, '[m, n]']) None
Set the external eigenvectors.
- Parameters:
external_eigenvectors (numpy.ndarray) – The external eigenvectors of the stability matrix
Examples
>>> import numpy as np >>> new_external_eigenvecs = np.random.rand(2, 2) >>> result.set_external_eigenvectors(new_external_eigenvecs)
- set_external_stable(self: qdk_chemistry.data.StabilityResult, external_stable: bool) None
Set the external stability status.
- Parameters:
external_stable (bool) – True if external stability is satisfied
Examples
>>> result.set_external_stable(False)
- set_internal_eigenvalues(self: qdk_chemistry.data.StabilityResult, internal_eigenvalues: Annotated[numpy.typing.ArrayLike, numpy.float64, '[m, 1]']) None
Set the internal eigenvalues.
- Parameters:
internal_eigenvalues (numpy.ndarray) – The internal eigenvalues of the stability matrix
Examples
>>> import numpy as np >>> new_internal_eigenvals = np.array([0.5, 1.5, 2.5]) >>> result.set_internal_eigenvalues(new_internal_eigenvals)
- set_internal_eigenvectors(self: qdk_chemistry.data.StabilityResult, internal_eigenvectors: Annotated[numpy.typing.ArrayLike, numpy.float64, '[m, n]']) None
Set the internal eigenvectors.
- Parameters:
internal_eigenvectors (numpy.ndarray) – The internal eigenvectors of the stability matrix
Examples
>>> import numpy as np >>> new_internal_eigenvecs = np.random.rand(3, 3) >>> result.set_internal_eigenvectors(new_internal_eigenvecs)
- set_internal_stable(self: qdk_chemistry.data.StabilityResult, internal_stable: bool) None
Set the internal stability status.
- Parameters:
internal_stable (bool) – True if internal stability is satisfied
Examples
>>> result.set_internal_stable(True)
- property summary
Get summary string of stability result information.
- Returns:
Summary information about the stability result
- Return type:
Examples
>>> summary = result.get_summary() >>> print(summary)
- to_file(self: qdk_chemistry.data.StabilityResult, filename: object, type: str) None
Save stability result data to file with specified format.
Generic method to save stability result data to a file.
- Parameters:
filename (str | pathlib.Path) – Path to the file to write.
type (str) – File format type (‘json’ or ‘hdf5’)
- Raises:
RuntimeError – If the stability result data is invalid, unsupported type, or file cannot be opened/written
Examples
>>> result.to_file("water.stability_result.json", "json") >>> result.to_file("molecule.stability_result.h5", "hdf5") >>> from pathlib import Path >>> result.to_file(Path("water.stability_result.json"), "json")
- to_hdf5_file(self: qdk_chemistry.data.StabilityResult, filename: object) None
Save stability result data to HDF5 file (with validation).
Writes all stability result data to an HDF5 file, preserving numerical precision. HDF5 format is efficient for large datasets and supports hierarchical data structures, making it ideal for storing stability analysis results.
- Parameters:
filename (str | pathlib.Path) – Path to the HDF5 file to write. Must have ‘.stability_result’ before the file extension (e.g.,
water.stability_result.h5,molecule.stability_result.hdf5)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the stability result data is invalid or the file cannot be opened/written
Examples
>>> result.to_hdf5_file("water.stability_result.h5") >>> result.to_hdf5_file("molecule.stability_result.hdf5") >>> from pathlib import Path >>> result.to_hdf5_file(Path("water.stability_result.h5"))
- to_json(self: qdk_chemistry.data.StabilityResult) str
Convert stability result data to JSON string.
Serializes all stability result information to a JSON string format. JSON is human-readable and suitable for debugging or data exchange.
- Returns:
JSON string representation of the stability result data
- Return type:
- Raises:
RuntimeError – If the stability result data is invalid
Examples
>>> json_str = result.to_json() >>> print(json_str) # Pretty-printed JSON
- to_json_file(self: qdk_chemistry.data.StabilityResult, filename: object) None
Save stability result data to JSON file.
Writes all stability result data to a JSON file with pretty formatting. The file will be created or overwritten if it already exists.
- Parameters:
filename (str | pathlib.Path) – Path to the JSON file to write. Must have ‘.stability_result’ before the file extension (e.g.,
water.stability_result.json,molecule.stability_result.json)- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the stability result data is invalid or the file cannot be opened/written
Examples
>>> result.to_json_file("water.stability_result.json") >>> result.to_json_file("molecule.stability_result.json") >>> from pathlib import Path >>> result.to_json_file(Path("water.stability_result.json"))
- class qdk_chemistry.data.Structure
Bases:
DataClassRepresents 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 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.
- Units:
Constructors and add_atom expect coordinates in Bohr (atomic units).
Getters/setters operate in Bohr (atomic units).
JSON serialization stores/loads coordinates in Bohr.
XYZ files are read/written in Angstrom (conversion handled at I/O boundary).
Examples
Create a water molecule from symbols and coordinates:
>>> import numpy as np >>> from qdk_chemistry.data import Structure >>> coords = np.array([[0.0, 0.0, 0.0], ... [0.757, 0.586, 0.0], ... [-0.757, 0.586, 0.0]]) >>> symbols = ["O", "H", "H"] >>> water = Structure(coords, symbols) >>> print(f"Number of atoms: {water.get_num_atoms()}") >>> print(f"Total charge: {water.get_total_nuclear_charge()}")
Create from elements enum:
>>> from qdk_chemistry.data import Element >>> coords = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]]) >>> elements = [Element.H, Element.H] >>> h2 = Structure(coords, elements)
Create from XYZ string:
>>> xyz_str = '''3 ... Water molecule ... O 0.000000 0.000000 0.000000 ... H 0.757000 0.586000 0.000000 ... H -0.757000 0.586000 0.000000''' >>> water = Structure() >>> water.from_xyz(xyz_str)
Save and load from files:
>>> water.to_xyz_file("water.xyz", "Water molecule") >>> water.to_json_file("water.json") >>> water_copy = Structure() >>> water_copy.from_xyz_file("water.xyz")
- __init__(*args, **kwargs)
Overloaded function.
__init__(self: qdk_chemistry.data.Structure, coordinates: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], elements: collections.abc.Sequence[qdk_chemistry.data.Element], masses: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] = array([], dtype=float64), nuclear_charges: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] = array([], dtype=float64)) -> None
Create structure from coordinates, elements, masses, and nuclear charges.
- Parameters:
coordinates (numpy.ndarray) – Matrix of atomic coordinates (N x 3) in Angstrom
elements (list[Element]) – Vector of atomic elements using Element enum
masses (numpy.ndarray | None) – Vector of atomic masses in AMU (default: use standard masses)
nuclear_charges (numpy.ndarray | None) – Vector of nuclear charges (default: use standard charges)
Examples
One way to generate a structure includes:
>>> import numpy as np >>> from qdk_chemistry.data import Structure, Element >>> coords = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]]) >>> elements = [Element.H, Element.H] >>> masses = np.array([1.008, 1.008]) >>> charges = np.array([1.0, 1.0]) >>> h2 = Structure(coords, elements, masses, charges)
Or:
>>> coords = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]]) >>> elements = [Element.H, Element.H] >>> h2 = Structure(coords, elements)
Or:
>>> coords = np.array([[0.0, 0.0, 0.0], [0.757, 0.586, 0.0], [-0.757, 0.586, 0.0]]) >>> symbols = ["O", "H", "H"] >>> masses = np.array([15.999, 1.008, 1.008]) >>> charges = np.array([8.0, 1.0, 1.0]) >>> water = Structure(coords, symbols, masses, charges)
Or:
>>> coords = np.array([[0.0, 0.0, 0.0], [0.757, 0.586, 0.0], [-0.757, 0.586, 0.0]]) >>> symbols = ["O", "H", "H"] >>> water = Structure(coords, symbols)
Or:
>>> coords = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]]) >>> charges = [1, 1] # Hydrogen atoms >>> h2 = Structure(coords, charges)
Or:
>>> symbols = ["O", "H", "H"] >>> coords = np.array([[0.0, 0.0, 0.0], [0.757, 0.586, 0.0], [-0.757, 0.586, 0.0]]) >>> water = Structure(symbols, coords)
__init__(self: qdk_chemistry.data.Structure, coordinates: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], elements: collections.abc.Sequence[qdk_chemistry.data.Element]) -> None
__init__(self: qdk_chemistry.data.Structure, coordinates: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], symbols: collections.abc.Sequence[str], masses: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] = array([], dtype=float64), nuclear_charges: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, 1]”] = array([], dtype=float64)) -> None
__init__(self: qdk_chemistry.data.Structure, coordinates: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], symbols: collections.abc.Sequence[str]) -> None
__init__(self: qdk_chemistry.data.Structure, coordinates: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”], nuclear_charges: collections.abc.Sequence[typing.SupportsInt]) -> None
__init__(self: qdk_chemistry.data.Structure, symbols: collections.abc.Sequence[str], coordinates: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, “[m, n]”]) -> None
- property atomic_symbols
Get all atomic symbols.
Examples
>>> symbols = structure.get_atomic_symbols() >>> print(f"Molecule formula: {''.join(symbols)}")
- calculate_nuclear_repulsion_energy(self: qdk_chemistry.data.Structure) float
Calculate nuclear-nuclear repulsion energy.
- Returns:
Nuclear repulsion energy in atomic units (Hartree)
- Return type:
Notes
This function calculates the Coulombic repulsion energy between all nuclei in the structure using the formula: \(E_{nn} = \sum_{i<j} Z_i \cdot Z_j / |R_i - R_j|\) where Z_i is the nuclear charge of atom i and R_i is its position vector.
Examples
>>> energy = structure.calculate_nuclear_repulsion_energy() >>> print(f'Nuclear repulsion energy: {energy:.6f} hartree')
- property coordinates
Get the atomic coordinates matrix.
- Returns:
Matrix of coordinates (N x 3) in Bohr
- Return type:
Examples
>>> coords = structure.get_coordinates() >>> print(f"Shape: {coords.shape}") # (N, 3)
- static element_to_nuclear_charge(element: qdk_chemistry.data.Element) int
Convert element enum to nuclear charge.
- Parameters:
element (Element) – Element enum value
- Returns:
Nuclear charge (atomic number)
- Return type:
Examples
>>> charge = Structure.element_to_nuclear_charge(Element.C) >>> assert charge == 6
- static element_to_symbol(element: qdk_chemistry.data.Element) str
Convert element enum to atomic symbol.
Examples
>>> symbol = Structure.element_to_symbol(Element.C) >>> assert symbol == "C"
- property elements
Get the atomic elements vector.
Examples
>>> elements = structure.get_elements() >>> print(f"First element: {elements[0]}")
- static from_file(filename: object, format_type: str) qdk_chemistry.data.Structure
Load structure from file in specified format (static method).
- Parameters:
filename (str | pathlib.Path) – Path to input file.
format_type (str) – Format type (“json” or “xyz”)
- Returns:
New Structure object loaded from the file
- Return type:
- Raises:
ValueError – If format_type is not supported or filename doesn’t follow naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid structure data
Examples
>>> water = Structure.from_file("water.structure.json", "json") >>> h2 = Structure.from_file("h2.structure.xyz", "xyz") >>> from pathlib import Path >>> water = Structure.from_file(Path("water.structure.json"), "json")
- static from_hdf5(group: object) qdk_chemistry.data.Structure
Load structure from HDF5 group (static method).
- Parameters:
group (h5py.Group | h5py.File) – HDF5 group or file object to load data from
- Returns:
New Structure object loaded from the group
- Return type:
- Raises:
RuntimeError – If the group cannot be read or contains invalid structure data
Examples
>>> import h5py >>> with h5py.File("data.structure.h5", "r") as f: ... water = Structure.from_hdf5(f) >>> with h5py.File("data.structure.h5", "r") as f: ... group = f["structure"] ... water = Structure.from_hdf5(group)
- static from_hdf5_file(filename: object) qdk_chemistry.data.Structure
Load structure from HDF5 file (static method).
- Parameters:
filename (str | pathlib.Path) – Path to input file. Must have ‘.structure’ before the file extension (e.g., “water.structure.h5”, “molecule.structure.hdf5”)
- Returns:
New Structure object loaded from the file
- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid structure data
Examples
>>> water = Structure.from_hdf5_file("water.structure.h5") >>> molecule = Structure.from_hdf5_file("molecule.structure.hdf5") >>> from pathlib import Path >>> water = Structure.from_hdf5_file(Path("water.structure.h5"))
- static from_json(json_data: str) qdk_chemistry.data.Structure
Load structure from JSON format string (static method).
- Parameters:
json_data (str) – JSON string representation with coordinates in Bohr
- Returns:
New Structure object created from JSON data
- Return type:
- Raises:
RuntimeError – If JSON format is invalid or contains invalid structure data
Examples
>>> json_str = '{"num_atoms": 2, "symbols": ["H", "H"], ...}' >>> h2 = Structure.from_json(json_str)
- static from_json_file(filename: object) qdk_chemistry.data.Structure
Load structure from JSON file (static method).
- Parameters:
filename (str | pathlib.Path) –
Path to input file.
Must have ‘.structure’ before the file extension (e.g., “water.structure.json”, “molecule.structure.json”)
- Returns:
New Structure object loaded from the file
- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid structure data
Examples
>>> water = Structure.from_json_file("water.structure.json") >>> molecule = Structure.from_json_file("molecule.structure.json") >>> from pathlib import Path >>> water = Structure.from_json_file(Path("water.structure.json"))
- static from_xyz(xyz_string: str) qdk_chemistry.data.Structure
Load structure from XYZ format string (static method).
- Parameters:
xyz_string (str) – XYZ format string with coordinates in Angstrom
- Returns:
New Structure object created from XYZ string
- Return type:
- Raises:
RuntimeError – If XYZ format is invalid
Examples
>>> xyz_str = '''3 ... Water molecule ... O 0.000000 0.000000 0.000000 ... H 0.757000 0.586000 0.000000 ... H -0.757000 0.586000 0.000000''' >>> water = Structure.from_xyz(xyz_str)
- static from_xyz_file(filename: object) qdk_chemistry.data.Structure
Load structure from XYZ file (static method).
- Parameters:
filename (str | pathlib.Path) –
Path to input file.
Must have ‘.structure.xyz’ extension (e.g., “water.structure.xyz”, “molecule.structure.xyz”)
- Returns:
New Structure object loaded from the file
- Return type:
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened, read, or contains invalid structure data
Examples
>>> water = Structure.from_xyz_file("water.structure.xyz") >>> from pathlib import Path >>> water = Structure.from_xyz_file(Path("water.structure.xyz"))
- get_atom_coordinates(self: qdk_chemistry.data.Structure, atom_index: SupportsInt) Annotated[numpy.typing.NDArray[numpy.float64], '[3, 1]']
Get coordinates for a specific atom.
- Parameters:
atom_index (int) – Index of the atom (0-based)
- Returns:
3D coordinates in Bohr as numpy array
- Return type:
Examples
>>> coords = structure.get_atom_coordinates(0) >>> print(f"Atom 0 position: {coords}")
- get_atom_element(self: qdk_chemistry.data.Structure, atom_index: SupportsInt) qdk_chemistry.data.Element
Get element for a specific atom.
- Parameters:
atom_index (int) – Index of the atom (0-based)
- Returns:
Atomic element enum
- Return type:
Examples
>>> element = structure.get_atom_element(0) >>> print(f"Atom 0 element: {element}")
- get_atom_mass(self: qdk_chemistry.data.Structure, atom_index: SupportsInt) float
Get mass for a specific atom.
- Parameters:
atom_index (int) – Index of the atom (0-based)
- Returns:
Atomic mass in AMU
- Return type:
Examples
>>> mass = structure.get_atom_mass(0) >>> print(f"Atom 0 mass: {mass} AMU")
- get_atom_nuclear_charge(self: qdk_chemistry.data.Structure, atom_index: SupportsInt) float
Get nuclear charge for a specific atom.
- Parameters:
atom_index (int) – Index of the atom (0-based)
- Returns:
Nuclear charge (atomic number)
- Return type:
Examples
>>> charge = structure.get_atom_nuclear_charge(0) >>> print(f"Atom 0 charge: {charge}")
- get_atom_symbol(self: qdk_chemistry.data.Structure, atom_index: SupportsInt) str
Get atomic symbol for a specific atom.
- Parameters:
atom_index (int) – Index of the atom (0-based)
- Returns:
Atomic symbol (e.g., “H”, “C”, “O”)
- Return type:
Examples
>>> symbol = structure.get_atom_symbol(0) >>> print(f"Atom 0 symbol: {symbol}")
- get_atomic_symbols(self: qdk_chemistry.data.Structure) list[str]
Get all atomic symbols.
Examples
>>> symbols = structure.get_atomic_symbols() >>> print(f"Molecule formula: {''.join(symbols)}")
- get_coordinates(self: qdk_chemistry.data.Structure) Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']
Get the atomic coordinates matrix.
- Returns:
Matrix of coordinates (N x 3) in Bohr
- Return type:
Examples
>>> coords = structure.get_coordinates() >>> print(f"Shape: {coords.shape}") # (N, 3)
- static get_default_atomic_mass(*args, **kwargs)
Overloaded function.
get_default_atomic_mass(element: qdk_chemistry.data.Element) -> float
Get default atomic mass for an element.
- Parameters:
element (Element) – Element enum value
- Returns:
Default atomic mass in AMU
- Return type:
Examples
>>> mass = Structure.get_default_atomic_mass(Element.C) >>> print(f"Carbon mass: {mass} AMU")
get_default_atomic_mass(symbol: str) -> float
Get default atomic mass for an element symbol string.
- Parameters:
symbol (str) – 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
- Return type:
Examples
>>> mass = Structure.get_default_atomic_mass("C") # Standard carbon mass >>> print(f"Carbon mass: {mass} AMU") >>> mass = Structure.get_default_atomic_mass("C13") # Carbon-13 >>> print(f"Carbon-13 mass: {mass} AMU") >>> mass = Structure.get_default_atomic_mass("D") # Deuterium >>> print(f"Deuterium mass: {mass} AMU")
- static get_default_nuclear_charge(element: qdk_chemistry.data.Element) int
Get default nuclear charge for an element.
- Parameters:
element (Element) – Element enum value
- Returns:
Nuclear charge (atomic number)
- Return type:
Examples
>>> charge = Structure.get_default_nuclear_charge(Element.C) >>> assert charge == 6
- get_elements(self: qdk_chemistry.data.Structure) list[qdk_chemistry.data.Element]
Get the atomic elements vector.
Examples
>>> elements = structure.get_elements() >>> print(f"First element: {elements[0]}")
- get_masses(self: qdk_chemistry.data.Structure) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']
Get the atomic masses vector.
- Returns:
Vector of atomic masses in AMU
- Return type:
Examples
>>> masses = structure.get_masses() >>> print(f"Total mass: {masses.sum()} AMU")
- get_nuclear_charges(self: qdk_chemistry.data.Structure) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']
Get the nuclear charges vector.
- Returns:
Vector of nuclear charges (atomic numbers)
- Return type:
Examples
>>> charges = structure.get_nuclear_charges() >>> print(f"Total charge: {charges.sum()}")
- get_num_atoms(self: qdk_chemistry.data.Structure) int
Get the number of atoms in the structure.
- Returns:
Number of atoms
- Return type:
Examples
>>> num_atoms = structure.get_num_atoms() >>> print(f"Structure has {num_atoms} atoms")
- get_summary(self: qdk_chemistry.data.Structure) str
Get summary string of structure information.
- Returns:
Summary information about the structure
- Return type:
Examples
>>> summary = structure.get_summary() >>> print(summary)
- get_total_mass(self: qdk_chemistry.data.Structure) float
Get the total mass of all atoms.
- Returns:
Total mass in AMU
- Return type:
Examples
>>> total_mass = structure.get_total_mass() >>> print(f"Total mass: {total_mass} AMU")
- get_total_nuclear_charge(self: qdk_chemistry.data.Structure) float
Get the total nuclear charge of all atoms.
- Returns:
Sum of all nuclear charges
- Return type:
Examples
>>> total_charge = structure.get_total_nuclear_charge() >>> print(f"Total nuclear charge: {total_charge}")
- is_empty(self: qdk_chemistry.data.Structure) bool
Check if the structure is empty.
- Returns:
True if structure has no atoms
- Return type:
Examples
>>> if structure.is_empty(): ... print("Structure is empty")
- property masses
Get the atomic masses vector.
- Returns:
Vector of atomic masses in AMU
- Return type:
Examples
>>> masses = structure.get_masses() >>> print(f"Total mass: {masses.sum()} AMU")
- static nuclear_charge_to_element(nuclear_charge: SupportsInt) qdk_chemistry.data.Element
Convert nuclear charge to element enum.
- Parameters:
nuclear_charge (int) – Nuclear charge (atomic number)
- Returns:
Element enum value
- Return type:
Examples
>>> element = Structure.nuclear_charge_to_element(6) >>> assert element == Element.C
- static nuclear_charge_to_symbol(nuclear_charge: SupportsInt) str
Convert nuclear charge to atomic symbol.
- Parameters:
nuclear_charge (int) – Nuclear charge (atomic number)
- Returns:
Atomic symbol
- Return type:
Examples
>>> symbol = Structure.nuclear_charge_to_symbol(6) >>> assert symbol == "C"
- property nuclear_charges
Get the nuclear charges vector.
- Returns:
Vector of nuclear charges (atomic numbers)
- Return type:
Examples
>>> charges = structure.get_nuclear_charges() >>> print(f"Total charge: {charges.sum()}")
- property num_atoms
Get the number of atoms in the structure.
- Returns:
Number of atoms
- Return type:
Examples
>>> num_atoms = structure.get_num_atoms() >>> print(f"Structure has {num_atoms} atoms")
- property summary
Get summary string of structure information.
- Returns:
Summary information about the structure
- Return type:
Examples
>>> summary = structure.get_summary() >>> print(summary)
- static symbol_to_element(symbol: str) qdk_chemistry.data.Element
Convert atomic symbol to element enum.
- Parameters:
symbol (str) – Atomic symbol (e.g., “H”, “C”, “O”)
- Returns:
Element enum value
- Return type:
Examples
>>> element = Structure.symbol_to_element("C") >>> assert element == Element.C
- static symbol_to_nuclear_charge(symbol: str) int
Convert atomic symbol to nuclear charge.
- Parameters:
symbol (str) – Atomic symbol (e.g., “H”, “C”, “O”)
- Returns:
Nuclear charge (atomic number)
- Return type:
Examples
>>> charge = Structure.symbol_to_nuclear_charge("C") >>> assert charge == 6
- to_file(self: qdk_chemistry.data.Structure, filename: object, format_type: str) None
Save structure to file in specified format.
- Parameters:
filename (str | pathlib.Path) – Path to output file.
format_type (str) – Format type (“json” or “xyz”)
- Raises:
RuntimeError – If the file cannot be opened or written
Examples
>>> structure.to_file("water.structure.json", "json") >>> structure.to_file("water.structure.xyz", "xyz") >>> from pathlib import Path >>> structure.to_file(Path("water.structure.json"), "json")
- to_hdf5_file(self: qdk_chemistry.data.Structure, filename: object) None
Save structure to HDF5 file.
- Parameters:
filename (str | pathlib.Path) – Path to output file. Must have ‘.structure’ before the file extension (e.g., “water.structure.h5”, “molecule.structure.hdf5”)
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened or written
Examples
>>> structure.to_hdf5_file("water.structure.h5") >>> structure.to_hdf5_file("molecule.structure.hdf5") >>> from pathlib import Path >>> structure.to_hdf5_file(Path("water.structure.h5"))
- to_json(self: qdk_chemistry.data.Structure) str
Convert structure to JSON format (coordinates in Bohr).
- Returns:
JSON string representation
- Return type:
Examples
>>> json_str = structure.to_json() >>> print(json_str)
- to_json_file(self: qdk_chemistry.data.Structure, filename: object) None
Save structure to JSON file.
- Parameters:
filename (str | pathlib.Path) –
Path to output file.
Must have ‘.structure’ before the file extension (e.g., “water.structure.json”, “molecule.structure.json”)
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened or written
Examples
>>> structure.to_json_file("water.structure.json") >>> structure.to_json_file("molecule.structure.json") >>> from pathlib import Path >>> structure.to_json_file(Path("water.structure.json"))
- to_xyz(self: qdk_chemistry.data.Structure, comment: str = '') str
Convert structure to XYZ format string (coordinates in Angstrom).
- Parameters:
comment (str | None) – Comment line for XYZ format
- Returns:
XYZ format string
- Return type:
Examples
>>> xyz_str = structure.to_xyz("Water molecule") >>> print(xyz_str)
- to_xyz_file(self: qdk_chemistry.data.Structure, filename: object, comment: str = '') None
Save structure to XYZ file.
- Parameters:
filename (str | pathlib.Path) –
Path to output file.
Must have ‘.structure.xyz’ extension (e.g., “water.structure.xyz”, “molecule.structure.xyz”)
- Raises:
ValueError – If filename doesn’t follow the required naming convention
RuntimeError – If the file cannot be opened or written
Examples
>>> structure.to_xyz_file("water.structure.xyz", "Water molecule") >>> from pathlib import Path >>> structure.to_xyz_file(Path("water.structure.xyz"), "Water molecule")
- class qdk_chemistry.data.TimeEvolutionUnitary(container)
Bases:
DataClassData class for a time evolution unitary.
- Parameters:
container (TimeEvolutionUnitaryContainer)
- container
The container for representing the time evolution unitary.
- __init__(container)
Initialize a TimeEvolutionUnitary.
- Parameters:
container (TimeEvolutionUnitaryContainer)
- Return type:
None
- get_container_type()
Get the type of the time evolution unitary container.
- Return type:
- Returns:
The type of the time evolution unitary.
- get_container()
Get the time evolution unitary container.
- Return type:
- Returns:
The time evolution unitary container.
- get_num_qubits()
Get the number of qubits the time evolution unitary acts on.
- Return type:
- Returns:
The number of qubits.
- to_json()
Convert the TimeEvolutionUnitary to a dictionary for JSON serialization.
- to_hdf5(group)
Save the TimeEvolutionUnitary to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write data to
- get_summary()
Get summary of time evolution unitary.
- classmethod from_json(json_data)
Create TimeEvolutionUnitary from a JSON dictionary.
- classmethod from_hdf5(group)
Load an instance from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to read data from
- Returns:
TimeEvolutionUnitary
- class qdk_chemistry.data.TimeEvolutionUnitaryContainer
Bases:
DataClassAbstract class for a time evolution unitary container.
- abstract property type: str
Get the type of the time evolution unitary container.
- Returns:
The type of the time evolution unitary container.
- abstract property num_qubits: int
Get the number of qubits the time evolution unitary acts on.
- Returns:
The number of qubits.
- abstractmethod to_json()
Convert the TimeEvolutionUnitaryContainer to a dictionary for JSON serialization.
- abstractmethod to_hdf5(group)
Save the TimeEvolutionUnitaryContainer to an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to write data to
- abstractmethod classmethod from_json(json_data)
Create TimeEvolutionUnitaryContainer from a JSON dictionary.
- abstractmethod classmethod from_hdf5(group)
Load an instance from an HDF5 group.
- Return type:
- Parameters:
group (h5py.Group) – HDF5 group or file to read data from
- Returns:
TimeEvolutionUnitaryContainer
- class qdk_chemistry.data.Wavefunction
Bases:
DataClassRepresents a wavefunction with associated properties.
This class encapsulates wavefunction data including:
Configuration interaction coefficients
Reduced density matrices (RDMs) in spin-dependent and spin-traced forms
- Methods for computing properties
Configuration interaction coefficients
Coupled cluster amplitudes
Reduced density matrices (RDMs) in spin-dependent and spin-traced forms
Methods for computing properties
- Supports both restricted and unrestricted wavefunctions with real or complex coefficients.
Supports both restricted and unrestricted wavefunctions with real or complex coefficients.
- __init__(self: qdk_chemistry.data.Wavefunction, container: qdk_chemistry.data.WavefunctionContainer) None
Constructs a wavefunction with a container implementation.
- Parameters:
container (WavefunctionContainer) – The container holding the wavefunction implementation
Examples
>>> container = qdk_chemistry.SciWavefunctionContainer(coeffs, dets, orbitals) >>> wf = qdk_chemistry.Wavefunction(container)
- static from_file(filename: str, format: str) qdk_chemistry.data.Wavefunction
Load wavefunction from file in specified format.
- Parameters:
- Returns:
Wavefunction object created from file
- Return type:
Examples
>>> wf = qdk_chemistry.Wavefunction.from_file("wavefunction.json", "json") >>> wf = qdk_chemistry.Wavefunction.from_file("wavefunction.h5", "hdf5")
- static from_hdf5_file(filename: str) qdk_chemistry.data.Wavefunction
Load wavefunction from HDF5 file.
- Parameters:
filename (str) – Path to HDF5 file to read
- Returns:
Wavefunction object created from HDF5 file
- Return type:
Examples
>>> wf = qdk_chemistry.Wavefunction.from_hdf5_file("wavefunction.h5")
- static from_json(json_str: str) qdk_chemistry.data.Wavefunction
Load wavefunction from JSON string format.
- Parameters:
json_str (str) – JSON string containing wavefunction data
- Returns:
Wavefunction object created from JSON string
- Return type:
Examples
>>> wf = qdk_chemistry.Wavefunction.from_json(json_str)
- static from_json_file(filename: str) qdk_chemistry.data.Wavefunction
Load wavefunction from JSON file.
- Parameters:
filename (str) – Path to JSON file to read
- Returns:
Wavefunction object created from JSON file
- Return type:
Examples
>>> wf = qdk_chemistry.Wavefunction.from_json_file("wavefunction.json")
- get_active_determinant(self: qdk_chemistry.data.Wavefunction, total_determinant: qdk_chemistry.data.Configuration) qdk_chemistry.data.Configuration
Extract active space determinant from a full orbital space determinant.
- Parameters:
total_determinant (Configuration) – Configuration representing full orbital space
- Returns:
Configuration representing only the active space portion
- Return type:
Notes
Removes inactive and virtual orbital information, keeping only the active space orbitals.
Examples
>>> total_det = qdk_chemistry.Configuration("2222uudd0000") # 4 inactive, 4 active, 4 virtual >>> active_det = wf.get_active_determinant(total_det) >>> # active_det now contains only "uudd" (the 4 active orbitals)
- get_active_determinants(self: qdk_chemistry.data.Wavefunction) list[qdk_chemistry.data.Configuration]
Get all determinants in the wavefunction (active space only).
- Returns:
Vector of all configurations/determinants representing only the active space
- Return type:
Notes
The determinants only include the active space orbitals. To get determinants with full orbital space (including inactive and virtual orbitals), use
get_total_determinants().Examples
>>> dets = wf.get_active_determinants()
- get_active_num_electrons(self: qdk_chemistry.data.Wavefunction) tuple[int, int]
Get number of active alpha and beta electrons.
- Returns:
Pair of
(n_alpha, n_beta)electrons- Return type:
Examples
>>> n_alpha, n_beta = wf.get_active_num_electrons()
- get_active_one_rdm_spin_dependent(self: qdk_chemistry.data.Wavefunction) tuple
Get spin-dependent one-particle reduced density matrices (RDMs) for active orbitals only.
- Returns:
Tuple of (alpha-alpha, beta-beta) one-particle RDMs for active orbitals
- Return type:
- Raises:
RuntimeError – If the spin-dependent 1-RDM is not available
Examples
>>> rdm_aa, rdm_bb = wf.get_active_one_rdm_spin_dependent()
- get_active_one_rdm_spin_traced(self: qdk_chemistry.data.Wavefunction) object
Get spin-traced one-particle reduced density matrix (RDM) for active orbitals only.
- Returns:
Spin-traced one-particle RDM for active orbitals
- Return type:
- Raises:
RuntimeError – If the 1-RDM is not available
Examples
>>> rdm = wf.get_active_one_rdm_spin_traced()
- get_active_orbital_occupations(self: qdk_chemistry.data.Wavefunction) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get orbital occupations for active orbitals only.
- Returns:
Pair of
(alpha_active_occupations, beta_active_occupations)- Return type:
Examples
>>> alpha_active, beta_active = wf.get_active_orbital_occupations()
- get_active_two_rdm_spin_dependent(self: qdk_chemistry.data.Wavefunction) tuple
Get spin-dependent two-particle reduced density matrices (RDMs) for active orbitals only.
- Returns:
Tuple of (aaaa, aabb, bbbb) two-particle RDMs for active orbitals
- Return type:
- Raises:
RuntimeError – If the spin-dependent 2-RDM is not available
Examples
>>> aaaa, aabb, bbbb = wf.get_active_two_rdm_spin_dependent()
- get_active_two_rdm_spin_traced(self: qdk_chemistry.data.Wavefunction) object
Get spin-traced two-particle reduced density matrix (RDM) for active orbitals only.
- Returns:
Spin-traced two-particle RDM for active orbitals
- Return type:
- Raises:
RuntimeError – If the 2-RDM is not available
Examples
>>> two_rdm = wf.get_active_two_rdm_spin_traced()
- get_coefficient(self: qdk_chemistry.data.Wavefunction, det: qdk_chemistry.data.Configuration) object
Get coefficient for a specific determinant.
- Parameters:
det (Configuration) – The determinant configuration to look up
- Returns:
The coefficient for the determinant if found, zero otherwise
- Return type:
Examples
>>> coeff = wf.get_coefficient(qdk_chemistry.Configuration("33221100"))
- get_coefficients(self: qdk_chemistry.data.Wavefunction) object
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 all coefficients (real or complex)
- Return type:
Examples
>>> coeffs = wf.get_coefficients() >>> print(f"Number of coefficients: {len(coeffs)}")
- get_container(self: qdk_chemistry.data.Wavefunction) qdk_chemistry.data.WavefunctionContainer
Get the underlying wavefunction container.
- Returns:
The underlying wavefunction container
- Return type:
- Raises:
RuntimeError – If the container is not available
Examples
>>> container = wf.get_container()
- get_container_type(self: qdk_chemistry.data.Wavefunction) str
Get the type of the underlying wavefunction container.
- Returns:
Type name of the underlying wavefunction container
- Return type:
Examples
>>> container_type = wf.get_container_type() >>> print(f"Container type: {container_type}")
- get_orbitals(self: qdk_chemistry.data.Wavefunction) qdk_chemistry.data.Orbitals
Get reference to orbital basis set.
- Returns:
Shared pointer to orbital basis set
- Return type:
Examples
>>> orbitals = wf.get_orbitals()
- get_single_orbital_entropies(self: qdk_chemistry.data.Wavefunction) Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']
Calculate single orbital entropies for active orbitals only.
This function uses the method of Boguslawski & Tecmer (2015), doi:10.1002/qua.24832, [BT15].
- Returns:
Vector of orbital entropies for active orbitals (always real)
- Return type:
- Raises:
RuntimeError – If the required reduced density matrices (RDMs) are not available
Examples
>>> entropies = wf.get_single_orbital_entropies()
- get_total_determinant(self: qdk_chemistry.data.Wavefunction, active_determinant: qdk_chemistry.data.Configuration) qdk_chemistry.data.Configuration
Convert active space determinant to full orbital space determinant.
- Parameters:
active_determinant (Configuration) – Configuration representing only active space
- Returns:
Configuration representing full orbital space
- Return type:
Notes
Expands active-space-only determinant to full orbital space by prepending doubly occupied inactive orbitals and appending unoccupied virtual orbitals.
Examples
>>> active_det = qdk_chemistry.Configuration("uudd") # 4 active orbitals >>> total_det = wf.get_total_determinant(active_det) >>> # If there are 4 inactive and 4 virtual orbitals, total_det will be "2222uudd0000"
- get_total_determinants(self: qdk_chemistry.data.Wavefunction) list[qdk_chemistry.data.Configuration]
Get all determinants in the wavefunction with full orbital space.
- Returns:
Vector of all configurations/determinants including inactive and virtual orbitals
- Return type:
Notes
Converts active-space-only determinants to full orbital space by prepending doubly occupied inactive orbitals and appending unoccupied virtual orbitals.
Examples
>>> total_dets = wf.get_total_determinants() >>> # Each determinant now includes inactive (doubly occupied) and virtual (unoccupied) orbitals
- get_total_num_electrons(self: qdk_chemistry.data.Wavefunction) tuple[int, int]
Get total number of alpha and beta electrons.
- Returns:
Pair of
(n_alpha, n_beta)electrons- Return type:
Examples
>>> n_alpha, n_beta = wf.get_total_num_electrons()
- get_total_orbital_occupations(self: qdk_chemistry.data.Wavefunction) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get orbital occupations for all orbitals.
- Returns:
Pair of
(alpha_occupations, beta_occupations)- Return type:
Examples
>>> alpha_occ, beta_occ = wf.get_total_orbital_occupations()
- get_type(self: qdk_chemistry.data.Wavefunction) qdk_chemistry.data.WavefunctionType
Get the wavefunction type (Bra, Ket, or Both).
- Returns:
Enum value representing the wavefunction type
- Return type:
Examples
>>> wf_type = wf.get_type()
- has_one_rdm_spin_dependent(self: qdk_chemistry.data.Wavefunction) bool
Check if spin-dependent one-particle RDMs for active orbitals are available.
- Returns:
True if available
- Return type:
Examples
>>> if wf.has_one_rdm_spin_dependent(): ... rdm_aa, rdm_bb = wf.get_active_one_rdm_spin_dependent()
- has_one_rdm_spin_traced(self: qdk_chemistry.data.Wavefunction) bool
Check if spin-traced one-particle RDM for active orbitals is available.
- Returns:
True if available
- Return type:
Examples
>>> if wf.has_one_rdm_spin_traced(): ... rdm = wf.get_active_one_rdm_spin_traced()
- has_two_rdm_spin_dependent(self: qdk_chemistry.data.Wavefunction) bool
Check if spin-dependent two-particle RDMs for active orbitals are available.
- Returns:
True if available
- Return type:
Examples
>>> if wf.has_two_rdm_spin_dependent(): ... aaaa, aabb, bbbb = wf.get_active_two_rdm_spin_dependent()
- has_two_rdm_spin_traced(self: qdk_chemistry.data.Wavefunction) bool
Check if spin-traced two-particle RDM for active orbitals is available.
- Returns:
True if available
- Return type:
Examples
>>> if wf.has_two_rdm_spin_traced(): ... two_rdm = wf.get_active_two_rdm_spin_traced()
- is_complex(self: qdk_chemistry.data.Wavefunction) bool
Check if the wavefunction is complex-valued.
- Returns:
True if the wavefunction uses complex coefficients, False if real
- Return type:
Examples
>>> is_complex = wf.is_complex() >>> print(f"Wavefunction uses complex coefficients: {is_complex}")
- norm(self: qdk_chemistry.data.Wavefunction) float
Calculate norm of the wavefunction.
- Returns:
Norm (always real)
- Return type:
Examples
>>> norm_value = wf.norm() >>> print(f"Wavefunction norm: {norm_value}")
- property orbitals
Get reference to orbital basis set.
- Returns:
Shared pointer to orbital basis set
- Return type:
Examples
>>> orbitals = wf.get_orbitals()
- overlap(self: qdk_chemistry.data.Wavefunction, other: qdk_chemistry.data.Wavefunction) object
Calculate overlap with another wavefunction.
- Parameters:
other (Wavefunction) – Other wavefunction
- Returns:
Overlap value (real or complex)
- Return type:
Examples
>>> wf1 = qdk_chemistry.Wavefunction(container1) >>> wf2 = qdk_chemistry.Wavefunction(container2) >>> overlap = wf1.overlap(wf2) >>> print(f"Overlap: {overlap}")
- size(self: qdk_chemistry.data.Wavefunction) int
Get number of determinants.
- Returns:
Number of determinants in the wavefunction
- Return type:
Examples
>>> dim = wf.size() >>> print(f"Wavefunction dimension: {dim}")
- to_file(self: qdk_chemistry.data.Wavefunction, filename: str, format: str) None
Save wavefunction to file in specified format.
- Parameters:
Examples
>>> wf.to_file("wavefunction.json", "json") >>> wf.to_file("wavefunction.h5", "hdf5")
- to_hdf5_file(self: qdk_chemistry.data.Wavefunction, filename: str) None
Save wavefunction to HDF5 file.
- Parameters:
filename (str) – Path to HDF5 file to create/overwrite
Examples
>>> wf.to_hdf5_file("wavefunction.h5")
- to_json(self: qdk_chemistry.data.Wavefunction) str
Convert wavefunction to JSON string format.
- Returns:
JSON string containing wavefunction data
- Return type:
Examples
>>> json_str = wf.to_json()
- to_json_file(self: qdk_chemistry.data.Wavefunction, filename: str) None
Save wavefunction to JSON file.
- Parameters:
filename (str) – Path to JSON file to create/overwrite
Examples
>>> wf.to_json_file("wavefunction.json")
- class qdk_chemistry.data.WavefunctionContainer
Bases:
pybind11_objectAbstract 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.
- __init__(*args, **kwargs)
- get_active_determinants(self: qdk_chemistry.data.WavefunctionContainer) list[qdk_chemistry.data.Configuration]
Get all determinants in the wavefunction
- get_active_num_electrons(self: qdk_chemistry.data.WavefunctionContainer) tuple[int, int]
Get number of active alpha and beta electrons
- get_active_orbital_occupations(*args, **kwargs)
Overloaded function.
get_active_orbital_occupations(self: qdk_chemistry.data.WavefunctionContainer) -> tuple[typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, 1]”], typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, 1]”]]
Get orbital occupations for all orbitals
get_active_orbital_occupations(self: qdk_chemistry.data.WavefunctionContainer) -> tuple[typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, 1]”], typing.Annotated[numpy.typing.NDArray[numpy.float64], “[m, 1]”]]
Get orbital occupations for active orbitals only
- get_coefficient(self: qdk_chemistry.data.WavefunctionContainer, det: qdk_chemistry.data.Configuration) float | complex
Get coefficient for a specific determinant
- get_orbital_occupations(self: qdk_chemistry.data.WavefunctionContainer) tuple[Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]'], Annotated[numpy.typing.NDArray[numpy.float64], '[m, 1]']]
Get orbital occupations for active orbitals
- get_orbitals(self: qdk_chemistry.data.WavefunctionContainer) qdk_chemistry.data.Orbitals
Get reference to orbital basis set
- get_total_num_electrons(self: qdk_chemistry.data.WavefunctionContainer) tuple[int, int]
Get total number of alpha and beta electrons
- get_type(self: qdk_chemistry.data.WavefunctionContainer) qdk_chemistry.data.WavefunctionType
Get the wavefunction type (Bra, Ket, or Both)
- has_one_rdm_spin_dependent(self: qdk_chemistry.data.WavefunctionContainer) bool
Check if spin-dependent one-particle RDMs for active orbitals are available
- has_one_rdm_spin_traced(self: qdk_chemistry.data.WavefunctionContainer) bool
Check if spin-traced one-particle RDM for active orbitals is available
- has_two_rdm_spin_dependent(self: qdk_chemistry.data.WavefunctionContainer) bool
Check if spin-dependent two-particle RDMs for active orbitals are available
- has_two_rdm_spin_traced(self: qdk_chemistry.data.WavefunctionContainer) bool
Check if spin-traced two-particle RDM for active orbitals is available
- is_complex(self: qdk_chemistry.data.WavefunctionContainer) bool
Check if the wavefunction is complex-valued
- norm(self: qdk_chemistry.data.WavefunctionContainer) float
Calculate norm of the wavefunction
- size(self: qdk_chemistry.data.WavefunctionContainer) int
Get number of determinants
- class qdk_chemistry.data.WavefunctionType
Bases:
pybind11_objectEnum 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
Members:
SelfDual : Wavefunction that can be used as both bra and ket
NotSelfDual : Wavefunction that is strictly bra or ket
- NotSelfDual = <WavefunctionType.NotSelfDual: 1>
- SelfDual = <WavefunctionType.SelfDual: 0>
- __init__(self: qdk_chemistry.data.WavefunctionType, value: SupportsInt) None
- WavefunctionType.name -> str
- property value
- qdk_chemistry.data.get_current_ciaaw_version() str
Get the current CIAAW version being used for atomic weights.
- Returns:
The CIAAW version string (e.g., ‘CIAAW 2024’).
- Return type:
Examples
>>> from qdk_chemistry.data import get_current_ciaaw_version >>> version = get_current_ciaaw_version() >>> print(f"Using {version} atomic weights")
Subpackages
Submodules
- qdk_chemistry.data.base module
- qdk_chemistry.data.circuit module
- qdk_chemistry.data.estimator_data module
- qdk_chemistry.data.noise_models module
GateErrorDefSupportedErrorTypesSupportedGateSupportedGate.BARRIERSupportedGate.CCXSupportedGate.CCZSupportedGate.CHSupportedGate.CPSupportedGate.CRXSupportedGate.CRYSupportedGate.CRZSupportedGate.CSSupportedGate.CSDGSupportedGate.CSWAPSupportedGate.CSXSupportedGate.CUSupportedGate.CXSupportedGate.CYSupportedGate.CZSupportedGate.DCXSupportedGate.DELAYSupportedGate.ECRSupportedGate.HSupportedGate.IDSupportedGate.INITIALIZESupportedGate.ISWAPSupportedGate.MCPSupportedGate.MCRXSupportedGate.MCRYSupportedGate.MCRZSupportedGate.MCXSupportedGate.MEASURESupportedGate.MSSupportedGate.PSupportedGate.PAULISupportedGate.RSupportedGate.RCCCXSupportedGate.RCCXSupportedGate.RESETSupportedGate.RVSupportedGate.RXSupportedGate.RXXSupportedGate.RYSupportedGate.RYYSupportedGate.RZSupportedGate.RZXSupportedGate.RZZSupportedGate.SSupportedGate.SDGSupportedGate.SWAPSupportedGate.SXSupportedGate.SXDGSupportedGate.TSupportedGate.TDGSupportedGate.USupportedGate.UNITARYSupportedGate.XSupportedGate.YSupportedGate.ZSupportedGate.from_string()
- qdk_chemistry.data.qpe_result module
- qdk_chemistry.data.qubit_hamiltonian module