lumeq.utils package
Submodules
lumeq.utils.cg_coeffs module
- clebsch_gordan_coeff_direct(j1, m1, j2, m2, j3, m3, sqrt=False)[source]
j3 is in {|j_1 - j_2|, dots, j_1 + j_2} m3 = m_1 + m_2 in {-J, -J+1, dots, J-1, J}
- clebsch_gordan_coeff_recur(j1, m1, j2, m2)[source]
j3 is in {|j_1 - j_2|, dots, j_1 + j_2} m3 = m_1 + m_2 in {-J, -J+1, dots, J-1, J}
- ladder_coeff(j, m, operator)[source]
Return the ladder-operator coefficient for angular momentum
j, m.Notes
jcan take values such as0, ±1/2, ±1, ±3/2, ±2, ...andmmust lie in{-j, -j+1, ..., j-1, j}.The ladder coefficients are
C_± = sqrt(j (j + 1) - m (m ± 1))and equivalentlyC_± = sqrt((j ∓ m) (j ± m + 1)).They satisfy
j_± |j m> = C_± |j (m ± 1)>.
lumeq.utils.data_io module
lumeq.utils.fdiff module
lumeq.utils.get_cx module
lumeq.utils.monitor_performance module
- monitor_performance(_func=None, *, level=1)[source]
decorator for monitoring memory of CPU (GPU) and timing of wall, CPU (GPU). Use either as @monitor_performance or @monitor_performance(level=1).
- set_performance_log(level=1, filename=None, debug=None)[source]
Configure performance monitoring and optionally change the output destination. - level = 0 disables monitoring - level >= 1 enables monitoring with increasing detail - debug is kept for backward compatibility and maps True/False to level 1/0 - filename = None keeps stdout logging
lumeq.utils.ortho_basis module
lumeq.utils.parser module
- put_keys_kwargs_to_object(obj, key={}, **kwargs)[source]
Put the individual keys in the dictionary first, then use dictionary to assign the obj class attributes.
lumeq.utils.print_matrix module
- print_matrix(keyword, matrix, nwidth=6, nind=0, digits=[13, 8, 'f'], trans=False, dtype=<class 'float'>)[source]
Print multi dimensional array in formatted way.
- Parameters:
keyword (str) – Title line.
matrix (array-like) – Multi-dimensional array.
nwidth (int, optional) – Number of columns to print in one block. Defaults to 6.
nind (int, optional) – Whether to print the row and column indices. Values larger than 0 print the indices. Defaults to 0.
digits (list, optional) –
[width, precision, notation], wherewidthis the total width of each number,precisionis the number of digits after the decimal point, andnotationis'f'for fixed-point or'e'for scientific notation. Defaults to[13, 8, 'f'].trans (bool, optional) – Whether to transpose the last two dimensions. Defaults to False.
dtype (type, optional) – Data type used to convert the input matrix.
- print_statistics(keyword, array, digits=[4, 4])[source]
Print mean value and standard deviation of a 1D array.
- Parameters:
keyword (str) – Title line.
array (array-like) – One-dimensional array.
digits (list, optional) –
[precision_mean, precision_std], whereprecision_meanis the number of digits after the decimal point for the mean andprecision_stdis the number of digits after the decimal point for the standard deviation. Defaults to[4, 4].
lumeq.utils.pyscf_helper module
- class MoleculeInput(charge: int = 0, spin: int = 1, atom: list[str] = None, symbols: list[str] = None, coords: ndarray = None, unit: str = 'angstrom')[source]
Bases:
objectClass to hold molecule input data.
- atom: list[str] = None
- charge: int = 0
- coords: ndarray = None
- spin: int = 1
- symbols: list[str] = None
- unit: str = 'angstrom'
- class QEDInput(cavity_freq: numpy.ndarray, cavity_mode: numpy.ndarray, cavity_model: str = 'JC', uniform_field: bool = True, freq_window: list[float] = <factory>, solver_algorithm: str = 'davidson_qr', solver_conv_prop: str = 'norm', target_states: str = 'polariton', nstates: int = 4, solver_conv_thresh: float = 1e-08, resonance_state: int = None, verbose: int = 0, debug: int = 0)[source]
Bases:
object- cavity_freq: ndarray
- cavity_mode: ndarray
- cavity_model: str = 'JC'
- debug: int = 0
- freq_window: list[float]
- nstates: int = 4
- resonance_state: int = None
- solver_algorithm: str = 'davidson_qr'
- solver_conv_prop: str = 'norm'
- solver_conv_thresh: float = 1e-08
- target_states: str = 'polariton'
- uniform_field: bool = True
- verbose: int = 0
- class SCFInput(functional: str, basis: str, method: str = 'RKS', grids_prune: bool = True, unrestricted: bool = False, h: Any = None, e_field: ndarray = None, max_cycle: int = 50, convergence: float = 1e-06, jobtype: str = 'energy', max_memory: int = 60000, verbose: int = 0, debug: int = 0)[source]
Bases:
objectClass to hold SCF input data.
- basis: str
- convergence: float = 1e-06
- debug: int = 0
- e_field: ndarray = None
- functional: str
- grids_prune: bool = True
- h: Any = None
- jobtype: str = 'energy'
- max_cycle: int = 50
- max_memory: int = 60000
- method: str = 'RKS'
- unrestricted: bool = False
- verbose: int = 0
- class SystemInput(molecules: list[MoleculeInput])[source]
Bases:
objectClass to hold system input data.
- molecules: list[MoleculeInput]
- property nfrag
- class TDInput(method: str = 'TDA', cis_n_roots: int = 0, cis_singlets: bool = False, cis_triplets: bool = False, rpa: bool = False, max_cycle: int = 50, max_space: int = 200, verbose: int = 0)[source]
Bases:
object- cis_n_roots: int = 0
- cis_singlets: bool = False
- cis_triplets: bool = False
- max_cycle: int = 50
- max_space: int = 200
- method: str = 'TDA'
- rpa: bool = False
- verbose: int = 0
- build_atom(atmsym, coords)[source]
Build atom string for PySCF from atomic symbols and coordinates.
- build_molecule(molecule: MoleculeInput, basis, **kwargs)[source]
Build molecule object for PySCF from MoleculeInput data and other parameters.
- Parameters:
molecule (MoleculeInput) – An instance of MoleculeInput containing the molecule data.
basis (str) – Basis set name for the molecule.
**kwargs – Extra options used to build the molecule. Supported options include
max_memoryin MB andverbose.
- Returns:
PySCF molecule object.
- Return type:
mol (pyscf.gto.Mole)
- get_frgm_idx(parameters)[source]
Get the fragment indices from the parameters provided for embedding or other purposes.
- run_pyscf_dft(molecules, scf_input)[source]
Run PySCF DFT calculation based on the parameters provided.
- run_pyscf_tddft(mf, td_input)[source]
Run PySCF TDDFT calculation based on the mean-field object and TDDFT model provided.
lumeq.utils.read_files module
- istype(data, dtype=<class 'float'>)[source]
Check if the data can be converted to the given data type.
- read_array(filename, keyword=None, nline=0, ncol=4, nrange=[0, 4], dtype=<class 'float'>, same=True)[source]
Read an array from the output file.
- Parameters:
filename (str) – The output file name
keyword (str) – The keyword to search for the target lines when keyword is None, read the whole file
nline (int) – The number of lines to read after the keyword line
ncol (int) – The expected number of columns in each line
nrange (list) – Begin and end indices of the target data in each line.
dtype (type) – Output data type, e.g. int, float, or str.
same (bool) – When same is True, only read the lines with all data of the same type
- Returns:
Array converted to the requested data type.
- Return type:
array (numpy.ndarray)
- read_matrix(filename, nrow, ncol, keyword, nwidth=6, nind=0, nskip=0, dtype=<class 'float'>)[source]
Read a matrix from the output file.
- Parameters:
filename (str) – The output file name
nrow (int) – The number of rows of the matrix
ncol (int) – The number of columns of the matrix
keyword (str) – The keyword to search for the target lines
nwidth (int) – The number of columns in each batch when nwidth == -1, nwidth = ncol
nind (int) – The number of index columns at the beginning of each row
nskip (int) – The number of rows to skip after the keyword line
dtype (type) – Output data type, e.g. int, float, or str.
- Returns:
Matrix with shape
(nrow, ncol).- Return type:
matrix (numpy.ndarray)
- read_number(filename, keyword, n=-1, o=1, dtype=<class 'int'>)[source]
Read numbers from the output file.
- Parameters:
filename (str) – The output file name
keyword (str) – The keyword to search for the target lines
n (int) – when n>=0: the nth number in the line (0-based) when n==-1: o is the begin and end indices of the number in the line
o (int or tuple) – o takes 1 or -1 for the reading order when n>=0 when n == -1: o takes the begin and end indices
dtype (type) – Output data type, e.g. int, float, or str.
- Returns:
Numbers converted to the requested data type.
- Return type:
numbers (numpy.ndarray)
lumeq.utils.sampling module
- class Sampler(size, variance, sigma=None, mean=0, seed=None, **kwargs)[source]
Bases:
objectRandom numbers sampler.
Generate correlated random numbers from Ornstein-Uhlenbeck process.
- Math<delta(t) delta(0)> = sigma^2 exp(-|t|/tau_c)
delta^{n+1} = a delta^{n} + b N(0, sigma) a = exp(-dt/tau_c) b = sigma sqrt(1 - a^2)
- Parameters:
values (array-like) – Previously sampled values.
tau_c (float) – Correlation time.
dt (float, optional) – Time step. Default is 1.
- Returns:
Correlated random numbers.
- Return type:
numpy.ndarray
- get_covariance(coordinate, ell_c, kind='exp', nugget=1e-12)[source]
Generate covariance matrix for the (to be generated) random numbers. Note it includes variance on the diagonal.
- Parameters:
coordinate ((N, 3) 2D Array) – Coordinate array.
ell_c (float) – Correlation length.
kind (str, optional) – Type of covariance function. Default is ‘exp’.
nugget (float, optional) – Small diagonal added for numerical stability. Default is 0.
- Returns:
lower/left-side of the covariance matrix.
- Return type:
covariance (2D Array)
lumeq.utils.sec_mole module
- cal_dihedral_angle(vectors)[source]
Calculate the dihedral angle between two planes defined by 2 or 4 vectors.
- get_center_property(weights, props, itype='charge', isotope_avg=True)[source]
Return the center of a property weighted by charges or masses.
- get_charge_or_mass(symbols, itype='charge', isotope_avg=True)[source]
Return the list of atomic charges or masses for given atom symbols.
- Parameters:
symbols (list) – Atom symbols.
itype (str) –
'charge'or'mass'.isotope_avg (bool) – Whether to use the average isotopic mass.
- get_molecular_center(weights, coords, itype='charge', isotope_avg=True)[source]
Return the center of charges or masses of a molecule.
- Parameters:
weights (list) – Atomic masses or charges, or atom symbols.
coords (numpy.ndarray) – Atomic coordinates in bohr.
itype (str) –
'charge'or'mass'.isotope_avg (bool) – Whether to use the average isotopic mass.
- get_moment_of_inertia(weights, coords, fix_sign=False)[source]
Return the moment of inertia tensor of a molecule.
- Parameters:
weights (list) – Atomic masses or charges.
coords (numpy.ndarray) – Atomic coordinates in bohr.
fix_sign (bool) – Whether to fix the sign of the principal axes.
- Returns:
Moment-of-inertia tensor.
- Return type:
numpy.ndarray
- get_rotation_matrix(theta, axis='x')[source]
Return the rotation matrix for a rotation of angle theta around a given axis. [cos -sin] [sin cos]
- get_symbols_coords(geometry, string=False)[source]
Get symbols and coordinates from geometry list or string.
- read_geometries_standard(infile, screen='User input: 2 of 2')[source]
Read standard geometries from an output file.
- read_molecule(data)[source]
Read molecule section info from a list of strings.
- Parameters:
data (list) – Strings containing molecule information.
- Returns:
(nfrag, charge, spin, geoms, atmsym, coords).- Return type:
tuple
- rotate_molecule(coords0, axis, theta)[source]
Rotate the molecule around a given axis by an angle theta.
- standard_orientation(symbols, coords, tol=4)[source]
Get the molecular coordinates at the standard orientation.
- standard_orientation2(symbols, coords, var, tol=4)[source]
Get the molecular coordinates and a geometry-dependent variable at the standard orientation. Here, we need the intermediate translation and principal matrices
- translate_molecule(symbols, coords, origin=None, itype='charge', isotope_avg=True)[source]
Translate the molecule to a new origin.
- write_geometry(infile, geometry, energy=None, open_file_method='w')[source]
Write geometry to an input file.
- write_mol_info(infile, charge='0', multiplicity='1', open_file_method='w', itype=0)[source]
Write molecule section info to input file. itype: 0 normal job; 1 second job; 2 fragment
- write_mol_info_geometry(infile, charge='0', multiplicity='1', frgm=False, **kwargs)[source]
Write molecule section info with geometry to input file. frgm: whether it is a fragment section kwargs: geometry or symbols and coords
lumeq.utils.unit_conversion module
lumeq.utils.utils module
- collect_lists(fn, iterable, *args, upack=False)[source]
Collect lists returned by a function into columns.
- Parameters:
fn (callable) – Function that takes an element of the iterable and returns a list of values.
iterable (iterable) – An iterable of elements to process with the function.
*args – Additional arguments to pass to the function.
upack (bool, optional) – If True, the elements of the iterable are unpacked as arguments to the function. Default is False.
- Returns:
Collected columns of values returned by
fn.- Return type:
list[list]
lumeq.utils.wick_contraction module
- combine_same_terms(contracted_strings)[source]
Apply symmetry to two-electron integrals in the contracted strings.
- Parameters:
contracted_strings (list) – Operator strings.
- Returns:
Operator strings with symmetry applied.
- Return type:
sym_strings (list)
- commutator(op1, op2, op3=None, sign='-')[source]
Compute the commutator [op1, op2] or double commutator [[op1, op2, op3] = ([[op1, op2], op3] + [op1, [op2, op3]]) / 2 = (op1 op2 op3 + op3 op2 op1) - [[op1, op3]_+, op2]_+ / 2
- Parameters:
op1 – First operator string.
op2 – Second operator string.
op3 (str, optional) – Third operator string for a double commutator.
sign (str, optional) – Sign between the two terms in the commutator.
- Returns:
(result, factor)for the commutator expansion.- Return type:
tuple
- contract_hamil_delta(hamiltonian, deltas)[source]
Contract the Hamiltonian operator with delta functions.
- Parameters:
hamiltonian (str) – Hamiltonian operator string.
deltas (list) – Delta-function strings.
- Returns:
Contracted Hamiltonian terms as strings.
- Return type:
strings (list)
- find_delta_sign(contractions_index, dtype=<class 'str'>)[source]
Determine the sign of the contraction based on the number of crossings.
- Parameters:
contractions_index (list) – List of contraction pairs.
dtype (type) – Return type, typically
strorint.
- Returns:
'+'or'-'(or+1/-1) depending on thenumber of crossings.
- Return type:
sign (str or int)
- get_list(operators)[source]
Convert input operators string to a list.
- Parameters:
operators (list or str) – Operator list, or a string separated by spaces or commas.
- Returns:
List of operator strings.
- Return type:
operators_list (list)
- has_pattern(contraction_list, target_pattern)[source]
Check if a target contraction pattern exists in a list of contraction patterns.
- Parameters:
contraction_list (list) – List of contraction patterns, where each pattern is a list of pairs.
target_pattern (list) – Contraction pattern to search for.
- Returns:
True if
target_patternexists incontraction_list.- Return type:
exists (bool)
- index_to_operators(operators, pairs_index)[source]
Convert pairs of operator indices to operator strings.
- Parameters:
operators (list) – Operator strings.
pairs_index (list) – Tuple pairs of operator indices.
- Returns:
Tuple pairs of operator strings.
- Return type:
pairs (list)
- is_same_pattern(contraction1, contraction2)[source]
Check if two contraction patterns are the same, ignoring order.
- plot_wick_diagram(operators, contractions, colors=None, width=None, end='')[source]
Plot Wick contraction diagram using graphviz.
- Parameters:
operators (list) – Operator strings.
contractions (list) – Contraction patterns.
colors (list, optional) – Colors for the contraction lines.
width (float, optional) – Line width for the contraction lines.
end (str, optional) – Symbols to append at the end of each line.
- print_math(string, title, filename=None, latex=False)[source]
Print mathematical expression in string format.
- Parameters:
string (str) – Mathematical expression.
title (str) – Title printed before the expression.
filename (str, optional) – If provided, save the expression to this file.
latex (bool, optional) – If True, print in LaTeX format.
- sqo_evaluation(bra, middle, ket, exceptions=[], title='', hamiltonian=None, latex=True, diagram=False, colors=None)[source]
Evaluate the Wick contractions for the given second-quantization operator (sqo) strings of bra, middle, and ket, while excluding specified operator pairs from contraction.
- Parameters:
bra – Left excitation operator string.
middle – Middle operator string.
ket – Right excitation operator string.
exceptions (list, optional) – Operator pairs to exclude from contraction.
title (str, optional) – Title for the evaluation.
hamiltonian (str, optional) – Hamiltonian operator string to contract with the deltas. Uses
middleif None.latex (bool, optional) – If True, format the delta strings for LaTeX rendering.
diagram (bool, optional) – If True, plot the Wick contraction diagram.
colors (list, optional) – Colors for the contraction lines in the diagram.
- Returns:
(contractions, deltas, strings).- Return type:
tuple
- wick_contraction(operators, pairs, expand=True)[source]
Perform Wick contraction on the given pairs of operators.
- Parameters:
operators (list) – Operator strings.
pairs (list) – Tuple pairs of indices to be contracted.
expand (bool, optional) – If True, return product patterns. Otherwise return a dictionary of lists of contraction patterns.
- Returns:
Contraction patterns.
- Return type:
contractions (list)
- wick_delta(contractions)[source]
Convert contraction pairs into delta functions.
- Parameters:
contractions (list) – Contraction patterns.
- Returns:
Delta-function strings representing the contractions.
- Return type:
deltas (list)
- wick_pairs(operators, exceptions=[], index=False)[source]
Pick all the possible Wick contraction pairs from a string of creation and annihilation operators.
- Parameters:
operators (list or str) – A list of strings representing creation and annihilation operators with optional spin labels, or a string separated by spaces or commas. Eg. [‘a^’, ‘i’, ‘b†’, ‘j_α’, ‘c_b^’, ‘k_beta’] or “a^ i b† j_α c_b^ k_beta”
exceptions (tuple or list, optional) – Operator pairs that should not be contracted.
index (bool, optional) – If True, return operator indices instead of operator strings.
- Returns:
All possible contraction pairs of the operators.
- Return type:
pairs (list)