0
# Utilities
1
2
Mathematical libraries, file I/O, analysis tools, and computational utilities supporting quantum chemistry calculations, data processing, and result analysis in PySCF.
3
4
## Capabilities
5
6
### Mathematical Functions
7
8
Enhanced mathematical operations optimized for quantum chemistry calculations.
9
10
```python { .api }
11
def einsum(subscripts, *tensors, **kwargs):
12
"""
13
Enhanced Einstein summation with memory optimization.
14
15
Parameters:
16
- subscripts: str, Einstein summation subscripts
17
- tensors: ndarray arguments
18
- kwargs: optimization options
19
20
Returns:
21
ndarray, result of Einstein summation
22
"""
23
24
def pack_tril(mat, axis=-1, out=None):
25
"""
26
Pack lower triangular part of matrix.
27
28
Efficiently stores symmetric matrices using only
29
lower triangular elements.
30
"""
31
32
def unpack_tril(tril, filltriu='HERMITIAN', axis=-1, out=None):
33
"""
34
Unpack triangular matrix to full matrix.
35
36
Reconstructs full matrix from packed triangular storage.
37
"""
38
```
39
40
### Linear Algebra Solvers
41
42
Specialized linear algebra routines for quantum chemistry eigenvalue problems.
43
44
```python { .api }
45
def davidson(aop, x0, precond, tol=1e-12, max_cycle=50, max_space=12, **kwargs):
46
"""
47
Davidson diagonalization for large matrices.
48
49
Iterative eigensolver optimized for quantum chemistry
50
applications with sparse, large matrices.
51
52
Parameters:
53
- aop: function, matrix-vector product function
54
- x0: ndarray, initial guess vectors
55
- precond: function, preconditioning function
56
- tol: float, convergence tolerance
57
- max_cycle: int, maximum iterations
58
- max_space: int, maximum subspace size
59
60
Returns:
61
tuple of (eigenvalues, eigenvectors)
62
"""
63
64
def safe_eigh(h, s, lindep=1e-12):
65
"""
66
Safe eigenvalue decomposition with linear dependency handling.
67
68
Handles near-singular overlap matrices common in
69
quantum chemistry with large basis sets.
70
"""
71
```
72
73
### File I/O and Format Conversion
74
75
Tools for reading, writing, and converting between various quantum chemistry file formats.
76
77
```python { .api }
78
def fcidump_write(mol, h1e, h2e, nmo, nelec, filename='FCIDUMP'):
79
"""
80
Write FCIDUMP file for external CI programs.
81
82
Parameters:
83
- mol: Mole object
84
- h1e: ndarray, 1-electron integrals
85
- h2e: ndarray, 2-electron integrals
86
- nmo: int, number of molecular orbitals
87
- nelec: int, number of electrons
88
- filename: str, output filename
89
"""
90
91
def molden_write(mol, mo_coeff, mo_energy, filename='output.molden'):
92
"""
93
Write Molden file for orbital visualization.
94
95
Parameters:
96
- mol: Mole object
97
- mo_coeff: ndarray, molecular orbital coefficients
98
- mo_energy: ndarray, orbital energies
99
- filename: str, output filename
100
"""
101
102
def cubegen_write(mol, filename, mo_coeff, nx=80, ny=80, nz=80):
103
"""
104
Generate Gaussian cube file for density visualization.
105
106
Parameters:
107
- mol: Mole object
108
- filename: str, output cube filename
109
- mo_coeff: ndarray, orbital coefficients
110
- nx, ny, nz: int, grid dimensions
111
"""
112
```
113
114
### System Utilities
115
116
Core system functions for memory management, parallelization, and library loading.
117
118
```python { .api }
119
def load_library(libname):
120
"""
121
Load C extension libraries with platform-specific handling.
122
123
Automatically handles different platforms and library paths
124
for PySCF's compiled extensions.
125
"""
126
127
def current_memory():
128
"""
129
Get current memory usage in MB.
130
131
Returns:
132
float, current memory usage
133
"""
134
135
def num_threads(n=None):
136
"""
137
Get or set number of OpenMP threads.
138
139
Parameters:
140
- n: int, number of threads to set (None to query)
141
142
Returns:
143
int, current number of threads
144
"""
145
146
class with_omp_threads:
147
"""
148
Context manager for temporary OpenMP thread control.
149
150
Usage:
151
with lib.with_omp_threads(4):
152
# code runs with 4 threads
153
calculation()
154
# thread count restored
155
"""
156
```
157
158
### Analysis Tools
159
160
Functions for analyzing quantum chemistry results and extracting chemical information.
161
162
```python { .api }
163
def mulliken_pop(mol, dm, s=None, verbose=None):
164
"""
165
Mulliken population analysis.
166
167
Parameters:
168
- mol: Mole object
169
- dm: ndarray, density matrix
170
- s: ndarray, overlap matrix
171
- verbose: int, output verbosity
172
173
Returns:
174
tuple of (atomic_charges, orbital_populations)
175
"""
176
177
def lowdin_pop(mol, dm, s=None):
178
"""
179
Löwdin population analysis.
180
181
Symmetric orthogonalization-based population analysis
182
reducing basis set dependence compared to Mulliken.
183
"""
184
185
def dipole_moment(mol, dm):
186
"""
187
Calculate electric dipole moment.
188
189
Parameters:
190
- mol: Mole object
191
- dm: ndarray, density matrix
192
193
Returns:
194
ndarray, dipole moment vector
195
"""
196
```
197
198
### Symmetry Operations
199
200
Molecular symmetry detection and utilization for computational efficiency.
201
202
```python { .api }
203
def detect_symm(mol, thrhf=1e-8):
204
"""
205
Detect molecular point group symmetry.
206
207
Parameters:
208
- mol: Mole object
209
- thrhf: float, symmetry detection threshold
210
211
Returns:
212
str, point group symbol
213
"""
214
215
def symmetrize_orb(mol, mo_coeff, s=None):
216
"""
217
Symmetrize molecular orbitals according to point group.
218
219
Projects orbitals onto irreducible representations
220
for proper symmetry labeling.
221
"""
222
```
223
224
## Usage Examples
225
226
### Mathematical Operations
227
228
```python
229
import pyscf
230
import numpy as np
231
232
# Enhanced Einstein summation
233
a = np.random.random((100, 100))
234
b = np.random.random((100, 100))
235
c = pyscf.lib.einsum('ij,jk->ik', a, b) # optimized matrix multiply
236
237
# Davidson diagonalization for large matrix
238
def matvec(x):
239
return H @ x # your matrix-vector product
240
241
H = np.random.random((1000, 1000))
242
H = H + H.T # make symmetric
243
x0 = np.random.random((1000, 5)) # 5 initial vectors
244
245
eigenvalues, eigenvectors = pyscf.lib.davidson(
246
matvec, x0,
247
precond=lambda x, e, x0: x/(np.diag(H)-e+0.1),
248
nroots=5
249
)
250
```
251
252
### File Operations
253
254
```python
255
# Write Molden file for visualization
256
mol = pyscf.M(atom='H2O', basis='6-31g')
257
mf = mol.RHF().run()
258
259
pyscf.tools.molden.from_scf(mf, 'h2o_orbitals.molden')
260
261
# Generate cube files for density plots
262
pyscf.tools.cubegen.density(mol, 'h2o_density.cube', mf.make_rdm1())
263
pyscf.tools.cubegen.orbital(mol, 'h2o_homo.cube', mf.mo_coeff[:, -1])
264
265
# FCIDUMP for external programs
266
from pyscf import ao2mo
267
h1e = mol.intor('int1e_kin') + mol.intor('int1e_nuc')
268
h2e = ao2mo.full(mol, mf.mo_coeff)
269
pyscf.tools.fcidump.from_integrals('water.fcidump', h1e, h2e,
270
mol.nao, mol.nelectron)
271
```
272
273
### Analysis and Properties
274
275
```python
276
# Population analysis
277
charges, pops = pyscf.tools.mulliken_pop(mol, mf.make_rdm1())
278
print("Mulliken charges:", charges)
279
280
# Löwdin analysis
281
charges_lowdin = pyscf.tools.lowdin_pop(mol, mf.make_rdm1())
282
283
# Dipole moment
284
dip = pyscf.tools.dipole_moment(mol, mf.make_rdm1())
285
print(f"Dipole moment: {np.linalg.norm(dip):.3f} Debye")
286
287
# Symmetry analysis
288
symm = pyscf.symm.detect_symm(mol)
289
print(f"Point group: {symm}")
290
```
291
292
### System Management
293
294
```python
295
# Memory and threading control
296
print(f"Current memory usage: {pyscf.lib.current_memory()} MB")
297
298
# Temporary thread control
299
with pyscf.lib.with_omp_threads(8):
300
# This calculation uses 8 threads
301
mf = mol.RHF().run()
302
# Thread count restored to original
303
304
# Set global thread count
305
pyscf.lib.num_threads(4)
306
```
307
308
## Types
309
310
```python { .api }
311
from typing import Tuple
312
from typing_extensions import Literal
313
import numpy as np
314
ndarray = np.ndarray
315
316
# Analysis result types
317
PopulationAnalysis = Tuple[ndarray, ndarray] # (charges, populations)
318
319
# Symmetry types
320
PointGroup = str # Point group symbol
321
IrrepLabel = str # Irreducible representation label
322
323
# File format specifications
324
FileFormat = Literal['molden', 'cube', 'fcidump', 'xyz']
325
326
# System resource types
327
MemorySize = float # Memory in MB
328
ThreadCount = int # Number of threads
329
```