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

j can take values such as 0, ±1/2, ±1, ±3/2, ±2, ... and m must lie in {-j, -j+1, ..., j-1, j}.

The ladder coefficients are C_± = sqrt(j (j + 1) - m (m ± 1)) and equivalently C_± = sqrt((j m) (j ± m + 1)).

They satisfy j_± |j m> = C_± |j (m ± 1)>.

print_cg_coeff(j1=0, m1=0, j2=0, m2=0, j3=0, m3=0, cg=0, header=False, ic=0)[source]

lumeq.utils.data_io module

load_json(file_name, to_numpy=False)[source]

Load data from a JSON file.

save_json(file_name, data, indent=4)[source]

Save data to a JSON file.

lumeq.utils.fdiff module

change_matrix_phase_c(matrix0, matrix1)[source]
change_matrix_phase_rc(matrix0, matrix1)[source]
change_number_phase(num0, num1)[source]
change_wf_phase(C0, X0, Y0, C1, X1, Y1)[source]
class fdiff(norder=2, step_size=0.001, unit=1.0)[source]

Bases: object

property coeff
compute(fx, unit=1.0)[source]
get_d(ndim, idx)[source]
get_x(x0, idx)[source]

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

get_ortho_basis(S, method='lowdin', eigen=False)[source]

S is symmetric overlap matrix of atomic basis L = S^(1/2) Z = S^(-1/2) S = L * L^T S^-1 = Z^T * Z inv = S^(-1)

get_ortho_basis_deriv(S, dS, method='lowdin', l_or_z='L', solver='iter')[source]

lumeq.utils.parser module

convert_string(string)[source]

Convert string to int, float, or keep as string.

parser(file_name)[source]

Parse input file into dictionary of parameters.

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.

put_keys_to_kwargs(key, **kwargs)[source]

Put the values in key dict to kwargs dict.

put_keys_to_object(obj, key)[source]

Put all the keywords and values into the obj class.

put_kwargs_to_keys(key={}, **kwargs)[source]

Put all the individual keyword and value into the key dictionary.

put_kwargs_to_object(obj, **kwargs)[source]

Put all the keywords and values into the obj class.

read_keyword_block(data)[source]

Read keyword block like $rem … $end.

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], where width is the total width of each number, precision is the number of digits after the decimal point, and notation is '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], where precision_mean is the number of digits after the decimal point for the mean and precision_std is 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: object

Class 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: object

Class 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: object

Class 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_memory in MB and verbose.

Returns:

PySCF molecule object.

Return type:

mol (pyscf.gto.Mole)

final_print_energy(td, title='tddft', nwidth=6, iprint=0)[source]
find_oscillator_strength(td, nroots, nfrag=1)[source]
find_transition_dipole(td, nroots, nfrag=1)[source]
get_basis_info(mol)[source]
get_center_of_mass(mol, nfrag=1)[source]
get_frgm_idx(parameters)[source]

Get the fragment indices from the parameters provided for embedding or other purposes.

get_jobtype(parameters)[source]

Determine the job type based on the parameters provided.

get_photon_info(photon_key)[source]
justify_photon_info(td, nroots, nstate='max_dipole', func='average', nwidth=10)[source]
run_pyscf_dft(molecules, scf_input)[source]

Run PySCF DFT calculation based on the parameters provided.

run_pyscf_dft_tddft(molecules, scf_input, td_input)[source]
run_pyscf_final(parameters)[source]
run_pyscf_tddft(mf, td_input)[source]

Run PySCF TDDFT calculation based on the mean-field object and TDDFT model provided.

run_pyscf_tdqed(mf, td, td_input, qed_input, key)[source]
setup_molecules(parameters, unit='angstrom')[source]

Setup MoleculeInput class from input parameters.

setup_scf_input(parameters)[source]

Setup SCFInput class from input parameters.

setup_td_input(parameters)[source]

Setup TDInput class from input parameters.

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)

read_time(filename)[source]

Read the total wall time from the output file.

lumeq.utils.sampling module

class Sampler(size, variance, sigma=None, mean=0, seed=None, **kwargs)[source]

Bases: object

Random numbers sampler.

correlated_sample(values, tau_c, dt=1.0, **kwargs)[source]

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)

sample(*args, **kwargs)[source]

Generate random numbers from a normal distribution.

lumeq.utils.sec_mole module

align_principal_axes(charges, coords)[source]

Align the molecule along its principal axes.

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_geometry(infile, probe=1)[source]

Read geometry from an xyz 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

read_symbols_coords(infile, probe=1)[source]

Read symbols and coordinates from an xyz file.

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

switch_atoms(geometry, atom_list)[source]

Switch atoms in geometry according to atom_list.

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

write_rem_info(infile, method='pbe0', basis='6-31g', open_file_method='a+')[source]

Write rem section info to input file.

write_symbols_coords(infile, symbols, coords, energy=None, open_file_method='w')[source]

Write symbols and coordinates to an xyz file.

lumeq.utils.unit_conversion module

convert_different_units(value, prop, index)[source]
convert_other_property(value, unit0='au')[source]
convert_property_to_energy(value, prop, index)[source]
convert_same_units(value, prop, index)[source]
convert_units(value, unit0='au', unit1='fs')[source]
default_unit_index(prop)[source]
find_properties(unit0='au', unit1='fs')[source]

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]

ishermitian(keyword, matrix, digits=[2, 13, 8, 'f'], debug=0)[source]
random_matrix(n=10, mean=0.0, width=0.1, func='uniform', sym=True, diag=True)[source]
swap_largest_to_diagonal(matrix)[source]

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 str or int.

Returns:

'+' or '-' (or +1 / -1) depending on the

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

get_orbital_index(operator)[source]

Extract the orbital index from the operator string.

get_spin_label(operator)[source]

Extract the spin label from the operator string.

get_spin_orbital_index(operator)[source]

Get the spin orbital index from the operator string.

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_pattern exists in contraction_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_annihilator(operator)[source]

Check if the operator is an annihilation operator.

is_creator(operator)[source]

Check if the operator is a creation operator by dagger symbol.

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.

remove_dagger(operator)[source]

Remove the dagger symbol from the operator string.

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 middle if 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)

Module contents