ofex.utils¶
ofex.utils.binary¶
This module provides utility functions for binary manipulation and calculations.
Functions: - int_to_binary: Converts an integer to a binary representation as a tuple. - binary_to_int: Converts a binary tuple back into an integer. - hamming_weight: Computes the Hamming weight (number of 1 bits) in an integer.
- ofex.utils.binary.int_to_binary(integer, length: int, lsb_first: bool) Tuple[int, ...][source]¶
Convert an integer to its binary representation as a tuple of bits.
- Parameters:
integer (int) – The integer to be converted.
length (int) – The length of the resulting binary tuple, padded with zeros if needed.
lsb_first (bool) – If True, the least significant bit (LSB) is placed at the start of the tuple.
- Returns:
A tuple representing the binary form of the integer.
- Return type:
Tuple[int, …]
- ofex.utils.binary.binary_to_int(binary: Tuple[int, ...], lsb_first: bool) int[source]¶
Convert a tuple of binary digits into its integer representation.
- Parameters:
binary (Tuple[int, ...]) – A tuple containing binary digits (0s and 1s).
lsb_first (bool) – If True, the least significant bit (LSB) is placed at the start of the tuple.
- Returns:
The integer value of the binary input.
- Return type:
int
- ofex.utils.binary.hamming_weight(x: int) int[source]¶
Calculate the Hamming weight (number of 1s in the binary representation) of an integer.
- Parameters:
x (int) – The integer whose Hamming weight is to be calculated.
- Returns:
The number of 1s in the binary representation of x.
- Return type:
int
- Raises:
ValueError – If the input integer is negative.
ofex.utils.chem¶
This module provides tools and methods for working with molecular geometries and quantum chemistry calculations. It includes utilities for generating linear and bent molecular structures, defining example molecular geometries, and running quantum chemistry simulations using various drivers.
Main functionalities: - Define linear and bent molecular geometries. - Predefine common molecules with standard parameters. - Run quantum chemistry calculations using drivers like PySCF and Psi4.
- ofex.utils.chem.linear_geometry(atoms: List[str], distances: float | List[float]) List[Tuple[str, Tuple[float, float, float]]][source]¶
Generate a linear molecular geometry based on specified atoms and interatomic distances.
This function positions a series of atoms in a one-dimensional linear arrangement, computing their coordinates such that each atom is separated from its neighbors by the specified distances.
- Parameters:
atoms (List[str]) – A list of atom symbols with length n. Example: [‘H’, ‘Be’, ‘H’].
distances (Union[float, List[float]]) – A single numeric value or a list of n-1 distances representing interatomic separations in angstrom. If a single value is provided, it will be uniformly applied between all atoms. Example: 1.5 or [1.5, 1.5].
- Returns:
- A list of tuples where each tuple contains the atomic symbol
and its 3D coordinates (0.0, 0.0, z) in a linear arrangement. Example: [(‘H’, (0.0, 0.0, 0.0)), (‘Be’, (0.0, 0.0, 1.5)), (‘H’, (0.0, 0.0, 3.0))].
- Return type:
MoleculeGeometry
- Raises:
ValueError – If the number of distances provided does not match the number of atoms - 1.
- ofex.utils.chem.bent_geometry(central: str, peripheral: str | List[str], distances: float | List[float], angle: float) List[Tuple[str, Tuple[float, float, float]]][source]¶
Generate the 3D geometry of a bent molecule.
- Parameters:
central (str) – The central atom. Example: ‘O’.
peripheral (Union[str, List[str]]) – The peripheral atoms. Example: ‘H’ or [‘H’, ‘H’].
distances (Union[float, List[float]]) – Distances from the central atom to the peripheral atoms in angstrom. Example: 0.97 or [0.97, 0.97].
angle (float) – Angle between the bonds in degrees. Example: 104.5.
- Returns:
- A list of tuples representing atom names and their 3D coordinates.
Example: [(‘O’, (0, 0, 0)), (‘H’, (0, 0.97, 0)), (‘H’, (0, 0.825, 0.509))].
- Return type:
MoleculeGeometry
- Raises:
ValueError – If less than two peripheral atoms or distances are specified.
- ofex.utils.chem.molecule_example(molecule_name: str, param: Number | List[Number] | None = None, geometry: List[Tuple[str, Tuple[float, float, float]]] | None = None, **kwargs) MolecularData[source]¶
Generate a Molecule object using a predefined molecular name and its geometry parameters.
- Parameters:
molecule_name (str) – Supported molecules include “H2”, “H4”, “HeH+”, “LiH”, “BeH2”, “H2O”, and “Li2O”.
param (Optional[Union[Number, List[Number]]]) – Parameters for the geometry. Examples: - Single distance (e.g., 0.74 for “H2”). - List of distances and angles (e.g., [0.957, 0.957, 104.5] for “H2O”).
geometry (Optional[MoleculeGeometry]) – Custom molecular geometry as a list of tuples. If not provided, a default geometry based on molecule_name and param will be used.
**kwargs – Additional keyword arguments passed to the Molecule object initialization, such as: - basis (str): Basis set to use. Default is “sto-3g”. - multiplicity (int): Spin multiplicity. Default is 1.
- Returns:
A Molecule object with the defined geometry and properties.
- Return type:
MolecularData
- Raises:
ValueError – If the molecule_name is not recognized.
- ofex.utils.chem.run_driver(molecule: MolecularData, run_scf: bool = True, run_mp2: bool = False, run_cisd: bool = False, run_ccsd: bool = False, run_fci: bool = False, driver: str = 'pyscf', **kwargs) MolecularData[source]¶
Execute quantum chemistry calculations for a molecule using a specified driver.
This function supports running various levels of theory calculations, including SCF, MP2, CISD, CCSD, and FCI, for molecules represented as MolecularData objects. It works with multiple external drivers such as pyscf and psi4.
- Parameters:
molecule (MolecularData) – A molecule object including its geometry, charge, and multiplicity.
run_scf (bool) – If True, perform a Self-Consistent Field (SCF) calculation. Default is True.
run_mp2 (bool) – If True, perform a 2nd order Møller–Plesset (MP2) calculation. Default is False.
run_cisd (bool) – If True, perform a Configuration Interaction with Single and Double Excitations (CISD) calculation. Default is False.
run_ccsd (bool) – If True, perform a Coupled Cluster with Single and Double Excitations (CCSD) calculation. Default is False.
run_fci (bool) – If True, perform a Full Configuration Interaction (FCI) calculation. Default is False.
driver (str) – The quantum chemistry driver to use (‘pyscf’ or ‘psi4’). Default is ‘pyscf’.
**kwargs – Additional arguments specific to the quantum chemistry driver used.
- Returns:
The input molecule object updated with the results of the calculations.
- Return type:
MolecularData
- Raises:
ValueError – If an unsupported driver is specified.
AttributeError – If a required class or updated module is not available for the driver.
ofex.utils.dict_utils¶
This module provides a collection of utility functions for working with nested dictionaries. It includes functions for recursive operations such as updating, traversing, and assigning values within nested dictionaries. The module also supports mathematical operations like addition and subtraction of dictionary values, as well as comparison utilities that handle both numeric and non-numeric data types.
- ofex.utils.dict_utils.recursive_dict_update(previous: dict, additional: dict) dict[source]¶
Recursively updates a dictionary with values from another dictionary.
- Parameters:
previous (dict) – The original dictionary to be updated.
additional (dict) – The dictionary containing new values.
- Returns:
A new dictionary with the values from additional merged into previous.
- Return type:
dict
- ofex.utils.dict_utils.recursive_dict_keys(dictionary: dict, max_depth=None)[source]¶
Recursively yields all keys in a nested dictionary.
- Parameters:
dictionary (dict) – The dictionary whose keys to traverse.
max_depth (int, optional) – The maximum depth to traverse. If None, no limit.
- Yields:
tuple – The keys in the dictionary as nested tuples.
- ofex.utils.dict_utils.recursive_dict_items(dictionary: dict, max_depth=None)[source]¶
Recursively yields all key-value pairs in a nested dictionary.
- Parameters:
dictionary (dict) – The dictionary whose items to traverse.
max_depth (int, optional) – The maximum depth to traverse. If None, no limit.
- Yields:
tuple – A tuple containing the key path and the value.
- ofex.utils.dict_utils.nested_dict_assign(dictionary: dict, key_list: list, value: Any)[source]¶
Assigns a value to a nested key in a dictionary.
- Parameters:
dictionary (dict) – The dictionary to modify.
key_list (list) – A list of keys defining the nested structure.
value (Any) – The value to assign to the nested key.
- ofex.utils.dict_utils.add_values(a: dict | None, b: dict | None) dict | None[source]¶
Adds the values of two dictionaries by matching their keys.
- Parameters:
a (dict or None) – The first dictionary with numeric values.
b (dict or None) – The second dictionary with numeric values.
- Returns:
A new dictionary containing the sum of values for matching keys, or None if both are None.
- Return type:
dict or None
- ofex.utils.dict_utils.sub_values(a: dict | None, b: dict | None) dict | None[source]¶
Subtracts the values of the second dictionary from the first dictionary by matching keys.
- Parameters:
a (dict or None) – The first dictionary with numeric values.
b (dict or None) – The second dictionary with numeric values.
- Returns:
A new dictionary containing the difference of values for matching keys, or None if both are None.
- Return type:
dict or None
- ofex.utils.dict_utils.dict_allclose(a: dict, b: dict, atol=1e-08) bool[source]¶
Checks whether two dictionaries are approximately equal, element-wise.
- Parameters:
a (dict) – The first dictionary to compare.
b (dict) – The second dictionary to compare.
atol (float) – The absolute tolerance for comparison of numerical values.
- Returns:
True if all values are close within the given tolerance, False otherwise.
- Return type:
bool
- ofex.utils.dict_utils.compare_dict(dict_1, dict_2, repr_func: Callable[[Any, Number], str], str_len=40, atol=1e-08) str[source]¶
Compares two dictionaries and generates a formatted string of differences.
- Parameters:
dict_1 (dict) – The first dictionary to compare.
dict_2 (dict) – The second dictionary to compare.
repr_func (Callable) – A function to format the key-value pairs for display.
str_len (int) – The length of the formatted string for each dictionary entry.
atol (float) – The absolute tolerance for numerical comparisons.
- Returns:
A multi-line string summarizing the differences between dict_1 and dict_2.
- Return type:
str