Python-based quantum chemistry framework providing electronic structure methods for molecular simulations
—
Mathematical libraries, file I/O, analysis tools, and computational utilities supporting quantum chemistry calculations, data processing, and result analysis in PySCF.
Enhanced mathematical operations optimized for quantum chemistry calculations.
def einsum(subscripts, *tensors, **kwargs):
"""
Enhanced Einstein summation with memory optimization.
Parameters:
- subscripts: str, Einstein summation subscripts
- tensors: ndarray arguments
- kwargs: optimization options
Returns:
ndarray, result of Einstein summation
"""
def pack_tril(mat, axis=-1, out=None):
"""
Pack lower triangular part of matrix.
Efficiently stores symmetric matrices using only
lower triangular elements.
"""
def unpack_tril(tril, filltriu='HERMITIAN', axis=-1, out=None):
"""
Unpack triangular matrix to full matrix.
Reconstructs full matrix from packed triangular storage.
"""Specialized linear algebra routines for quantum chemistry eigenvalue problems.
def davidson(aop, x0, precond, tol=1e-12, max_cycle=50, max_space=12, **kwargs):
"""
Davidson diagonalization for large matrices.
Iterative eigensolver optimized for quantum chemistry
applications with sparse, large matrices.
Parameters:
- aop: function, matrix-vector product function
- x0: ndarray, initial guess vectors
- precond: function, preconditioning function
- tol: float, convergence tolerance
- max_cycle: int, maximum iterations
- max_space: int, maximum subspace size
Returns:
tuple of (eigenvalues, eigenvectors)
"""
def safe_eigh(h, s, lindep=1e-12):
"""
Safe eigenvalue decomposition with linear dependency handling.
Handles near-singular overlap matrices common in
quantum chemistry with large basis sets.
"""Tools for reading, writing, and converting between various quantum chemistry file formats.
def fcidump_write(mol, h1e, h2e, nmo, nelec, filename='FCIDUMP'):
"""
Write FCIDUMP file for external CI programs.
Parameters:
- mol: Mole object
- h1e: ndarray, 1-electron integrals
- h2e: ndarray, 2-electron integrals
- nmo: int, number of molecular orbitals
- nelec: int, number of electrons
- filename: str, output filename
"""
def molden_write(mol, mo_coeff, mo_energy, filename='output.molden'):
"""
Write Molden file for orbital visualization.
Parameters:
- mol: Mole object
- mo_coeff: ndarray, molecular orbital coefficients
- mo_energy: ndarray, orbital energies
- filename: str, output filename
"""
def cubegen_write(mol, filename, mo_coeff, nx=80, ny=80, nz=80):
"""
Generate Gaussian cube file for density visualization.
Parameters:
- mol: Mole object
- filename: str, output cube filename
- mo_coeff: ndarray, orbital coefficients
- nx, ny, nz: int, grid dimensions
"""Core system functions for memory management, parallelization, and library loading.
def load_library(libname):
"""
Load C extension libraries with platform-specific handling.
Automatically handles different platforms and library paths
for PySCF's compiled extensions.
"""
def current_memory():
"""
Get current memory usage in MB.
Returns:
float, current memory usage
"""
def num_threads(n=None):
"""
Get or set number of OpenMP threads.
Parameters:
- n: int, number of threads to set (None to query)
Returns:
int, current number of threads
"""
class with_omp_threads:
"""
Context manager for temporary OpenMP thread control.
Usage:
with lib.with_omp_threads(4):
# code runs with 4 threads
calculation()
# thread count restored
"""Functions for analyzing quantum chemistry results and extracting chemical information.
def mulliken_pop(mol, dm, s=None, verbose=None):
"""
Mulliken population analysis.
Parameters:
- mol: Mole object
- dm: ndarray, density matrix
- s: ndarray, overlap matrix
- verbose: int, output verbosity
Returns:
tuple of (atomic_charges, orbital_populations)
"""
def lowdin_pop(mol, dm, s=None):
"""
Löwdin population analysis.
Symmetric orthogonalization-based population analysis
reducing basis set dependence compared to Mulliken.
"""
def dipole_moment(mol, dm):
"""
Calculate electric dipole moment.
Parameters:
- mol: Mole object
- dm: ndarray, density matrix
Returns:
ndarray, dipole moment vector
"""Molecular symmetry detection and utilization for computational efficiency.
def detect_symm(mol, thrhf=1e-8):
"""
Detect molecular point group symmetry.
Parameters:
- mol: Mole object
- thrhf: float, symmetry detection threshold
Returns:
str, point group symbol
"""
def symmetrize_orb(mol, mo_coeff, s=None):
"""
Symmetrize molecular orbitals according to point group.
Projects orbitals onto irreducible representations
for proper symmetry labeling.
"""import pyscf
import numpy as np
# Enhanced Einstein summation
a = np.random.random((100, 100))
b = np.random.random((100, 100))
c = pyscf.lib.einsum('ij,jk->ik', a, b) # optimized matrix multiply
# Davidson diagonalization for large matrix
def matvec(x):
return H @ x # your matrix-vector product
H = np.random.random((1000, 1000))
H = H + H.T # make symmetric
x0 = np.random.random((1000, 5)) # 5 initial vectors
eigenvalues, eigenvectors = pyscf.lib.davidson(
matvec, x0,
precond=lambda x, e, x0: x/(np.diag(H)-e+0.1),
nroots=5
)# Write Molden file for visualization
mol = pyscf.M(atom='H2O', basis='6-31g')
mf = mol.RHF().run()
pyscf.tools.molden.from_scf(mf, 'h2o_orbitals.molden')
# Generate cube files for density plots
pyscf.tools.cubegen.density(mol, 'h2o_density.cube', mf.make_rdm1())
pyscf.tools.cubegen.orbital(mol, 'h2o_homo.cube', mf.mo_coeff[:, -1])
# FCIDUMP for external programs
from pyscf import ao2mo
h1e = mol.intor('int1e_kin') + mol.intor('int1e_nuc')
h2e = ao2mo.full(mol, mf.mo_coeff)
pyscf.tools.fcidump.from_integrals('water.fcidump', h1e, h2e,
mol.nao, mol.nelectron)# Population analysis
charges, pops = pyscf.tools.mulliken_pop(mol, mf.make_rdm1())
print("Mulliken charges:", charges)
# Löwdin analysis
charges_lowdin = pyscf.tools.lowdin_pop(mol, mf.make_rdm1())
# Dipole moment
dip = pyscf.tools.dipole_moment(mol, mf.make_rdm1())
print(f"Dipole moment: {np.linalg.norm(dip):.3f} Debye")
# Symmetry analysis
symm = pyscf.symm.detect_symm(mol)
print(f"Point group: {symm}")# Memory and threading control
print(f"Current memory usage: {pyscf.lib.current_memory()} MB")
# Temporary thread control
with pyscf.lib.with_omp_threads(8):
# This calculation uses 8 threads
mf = mol.RHF().run()
# Thread count restored to original
# Set global thread count
pyscf.lib.num_threads(4)from typing import Tuple
from typing_extensions import Literal
import numpy as np
ndarray = np.ndarray
# Analysis result types
PopulationAnalysis = Tuple[ndarray, ndarray] # (charges, populations)
# Symmetry types
PointGroup = str # Point group symbol
IrrepLabel = str # Irreducible representation label
# File format specifications
FileFormat = Literal['molden', 'cube', 'fcidump', 'xyz']
# System resource types
MemorySize = float # Memory in MB
ThreadCount = int # Number of threadsInstall with Tessl CLI
npx tessl i tessl/pypi-pyscf