vayesta.core

Subpackages

Submodules

vayesta.core.cmdargs

vayesta.core.cmdargs.parse_cmd_args()[source]

vayesta.core.foldscf

vayesta.core.foldscf.fold_scf(kmf, *args, **kwargs)[source]

Fold k-point sampled mean-field object to Born-von Karman (BVK) supercell. See also FoldedSCF.

class vayesta.core.foldscf.FoldedSCF(kmf, kpt=array([0., 0., 0.]), **kwargs)[source]

Bases: object

Fold k-point sampled SCF calculation to the BVK (Born-von Karman) supercell.

This class automatically updates the attributes mo_energy, mo_coeff, mo_occ, e_tot, and converged. It also overwrites the methods get_ovlp, get_hcore, and get_veff, calling its more efficient k-space variant first and folding the result to the supercell.

Since get_hcore and get_veff are implemented, get_fock is supported automatically, if the inherited base SCF class implements it.

kmf

Converged k-point sampled mean-field calculation.

Type:

pyscf.pbc.gto.KRHF or pyscf.pbc.gto.KRHF

kcell

Primitive unit cell object.

Type:

pyscf.pbc.gto.Cell

ncells

Number of primitive unit cells within BVK supercell

Type:

int

kphase

Transformation matrix between k-point and BVK quantities.

Type:

(ncells, ncells) array

property e_tot
property ncells
property kcell
get_ovlp(*args, **kwargs)[source]
get_hcore(*args, make_real=True, **kwargs)[source]
get_veff(mol=None, dm=None, *args, make_real=True, **kwargs)[source]
class vayesta.core.foldscf.FoldedRHF(kmf, *args, **kwargs)[source]

Bases: FoldedSCF, RHF

Fold k-point sampled SCF calculation to the BVK (Born-von Karman) supercell.

This class automatically updates the attributes mo_energy, mo_coeff, mo_occ, e_tot, and converged. It also overwrites the methods get_ovlp, get_hcore, and get_veff, calling its more efficient k-space variant first and folding the result to the supercell.

Since get_hcore and get_veff are implemented, get_fock is supported automatically, if the inherited base SCF class implements it.

kmf

Converged k-point sampled mean-field calculation.

Type:

pyscf.pbc.gto.KRHF or pyscf.pbc.gto.KRHF

kcell

Primitive unit cell object.

Type:

pyscf.pbc.gto.Cell

ncells

Number of primitive unit cells within BVK supercell

Type:

int

kphase

Transformation matrix between k-point and BVK quantities.

Type:

(ncells, ncells) array

DIIS

alias of CDIIS

add_keys(**kwargs)

Add or update attributes of the object and register these attributes in ._keys

analyze(verbose=None, with_meta_lowdin=True, **kwargs)

Analyze the given SCF object: print orbital energies, occupancies; print orbital coefficients; Mulliken population analysis; Diople moment.

apply(fn, *args, **kwargs)

Apply the fn to rest arguments: return fn(*args, **kwargs). The return value of method set is the object itself. This allows a series of functions/methods to be executed in pipe.

as_scanner()

Generating a scanner/solver for HF PES.

The returned solver is a function. This function requires one argument “mol” as input and returns total HF energy.

The solver will automatically use the results of last calculation as the initial guess of the new calculation. All parameters assigned in the SCF object (DIIS, conv_tol, max_memory etc) are automatically applied in the solver.

Note scanner has side effects. It may change many underlying objects (_scf, with_df, with_x2c, …) during calculation.

Examples:

>>> from pyscf import gto, scf
>>> hf_scanner = scf.RHF(gto.Mole().set(verbose=0)).as_scanner()
>>> hf_scanner(gto.M(atom='H 0 0 0; F 0 0 1.1'))
-98.552190448277955
>>> hf_scanner(gto.M(atom='H 0 0 0; F 0 0 1.5'))
-98.414750424294368
build(cell=None)
canonicalize(mo_coeff, mo_occ, fock=None)

Canonicalization diagonalizes the Fock matrix within occupied, open, virtual subspaces separatedly (without change occupancy).

check_convergence = None
check_sanity()

Check input of class/object attributes, check whether a class method is overwritten. It does not check the attributes which are prefixed with “_”. The return value of method set is the object itself. This allows a series of functions/methods to be executed in pipe.

conv_check = True
conv_tol = 1e-09
conv_tol_grad = None
convert_from_(mf)

Convert given mean-field object to RHF

damp = 0
property damp_factor
density_fit(auxbasis=None, with_df=None)
diis = True
diis_file = None
diis_space = 8
diis_space_rollback = 0
diis_start_cycle = 1
dip_moment(cell=None, dm=None, unit='Debye', verbose=3, **kwargs)

Dipole moment in the cell (is it well defined)?

Parameters:
  • cell – an instance of Cell

  • dm (ndarray) – density matrix

Returns:

the dipole moment on x, y and z components

Return type:

A list

direct_scf = False
direct_scf_tol = 1e-13
dump_chk(envs)
dump_flags(verbose=None)
dump_scf_summary(verbose=5)
property e_tot
eig(h, s)

Solver for generalized eigenvalue problem

\[HC = SCE\]
energy_elec(dm=None, h1e=None, vhf=None)

Electronic part of Hartree-Fock energy, for given core hamiltonian and HF potential

… math:

E = \sum_{ij}h_{ij} \gamma_{ji}
  + \frac{1}{2}\sum_{ijkl} \gamma_{ji}\gamma_{lk} \langle ik||jl\rangle

Note this function has side effects which cause mf.scf_summary updated.

Parameters:

mf – an instance of SCF class

Kwargs:
dm2D ndarray

one-partical density matrix

h1e2D ndarray

Core hamiltonian

vhf2D ndarray

HF potential

Returns:

Hartree-Fock electronic energy and the Coulomb energy

Examples:

>>> from pyscf import gto, scf
>>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')
>>> mf = scf.RHF(mol)
>>> mf.scf()
>>> dm = mf.make_rdm1()
>>> scf.hf.energy_elec(mf, dm)
(-1.5176090667746334, 0.60917167853723675)
>>> mf.energy_elec(dm)
(-1.5176090667746334, 0.60917167853723675)
energy_nuc()
energy_tot(dm=None, h1e=None, vhf=None)

Total Hartree-Fock energy, electronic part plus nuclear repulstion See scf.hf.energy_elec() for the electron part

Note this function has side effects which cause mf.scf_summary updated.

from_chk(chk=None, project=None, kpt=None)

Read the HF results from checkpoint file, then project it to the basis defined by mol

Returns:

Density matrix, 2D ndarray

gen_response(mo_coeff=None, mo_occ=None, singlet=None, hermi=0, max_memory=None)
get_bands(kpts_band, cell=None, dm=None, kpt=None)

Get energy bands at the given (arbitrary) ‘band’ k-points.

Returns:

(nmo,) ndarray or a list of (nmo,) ndarray

Bands energies E_n(k)

mo_coeff(nao, nmo) ndarray or a list of (nao,nmo) ndarray

Band orbitals psi_n(k)

Return type:

mo_energy

get_fock(h1e=None, s1e=None, vhf=None, dm=None, cycle=-1, diis=None, diis_start_cycle=None, level_shift_factor=None, damp_factor=None)

F = h^{core} + V^{HF}

Special treatment (damping, DIIS, or level shift) will be applied to the Fock matrix if diis and cycle is specified (The two parameters are passed to get_fock function during the SCF iteration)

Kwargs:
h1e2D ndarray

Core hamiltonian

s1e2D ndarray

Overlap matrix, for DIIS

vhf2D ndarray

HF potential matrix

dm2D ndarray

Density matrix, for DIIS

cycleint

Then present SCF iteration step, for DIIS

diisan object of SCF.DIIS class

DIIS object to hold intermediate Fock and error vectors

diis_start_cycleint

The step to start DIIS. Default is 0.

level_shift_factorfloat or int

Level shift (in AU) for virtual space. Default is 0.

get_grad(mo_coeff, mo_occ, fock=None)

RHF orbital gradients

Parameters:
  • mo_coeff – 2D ndarray Obital coefficients

  • mo_occ – 1D ndarray Orbital occupancy

  • fock_ao – 2D ndarray Fock matrix in AO representation

Returns:

Gradients in MO representation. It’s a num_occ*num_vir vector.

get_hcore(*args, make_real=True, **kwargs)
get_init_guess(cell=None, key='minao')
get_j(cell=None, dm=None, hermi=1, kpt=None, kpts_band=None, omega=None)

Compute J matrix for the given density matrix and k-point (kpt). When kpts_band is given, the J matrices on kpts_band are evaluated.

J_{pq} = sum_{rs} (pq|rs) dm[s,r]

where r,s are orbitals on kpt. p and q are orbitals on kpts_band if kpts_band is given otherwise p and q are orbitals on kpt.

get_jk(cell=None, dm=None, hermi=1, kpt=None, kpts_band=None, with_j=True, with_k=True, omega=None, **kwargs)

Get Coulomb (J) and exchange (K) following scf.hf.RHF.get_jk_(). for particular k-point (kpt).

When kpts_band is given, the J, K matrices on kpts_band are evaluated.

J_{pq} = sum_{rs} (pq|rs) dm[s,r] K_{pq} = sum_{rs} (pr|sq) dm[r,s]

where r,s are orbitals on kpt. p and q are orbitals on kpts_band if kpts_band is given otherwise p and q are orbitals on kpt.

get_jk_incore(cell=None, dm=None, hermi=1, kpt=None, omega=None, **kwargs)

Get Coulomb (J) and exchange (K) following scf.hf.RHF.get_jk_().

Incore version of Coulomb and exchange build only. Currently RHF always uses PBC AO integrals (unlike RKS), since exchange is currently computed by building PBC AO integrals.

get_k(cell=None, dm=None, hermi=1, kpt=None, kpts_band=None, omega=None)

Compute K matrix for the given density matrix.

get_occ(mo_energy=None, mo_coeff=None)

Label the occupancies for each orbital

Kwargs:
mo_energy1D ndarray

Obital energies

mo_coeff2D ndarray

Obital coefficients

Examples:

>>> from pyscf import gto, scf
>>> mol = gto.M(atom='H 0 0 0; F 0 0 1.1')
>>> mf = scf.hf.SCF(mol)
>>> energy = numpy.array([-10., -1., 1, -2., 0, -3])
>>> mf.get_occ(energy)
array([2, 2, 0, 2, 2, 2])
get_ovlp(*args, **kwargs)
get_rho(dm=None, grids=None, kpt=None)

Compute density in real space

get_veff(mol=None, dm=None, *args, make_real=True, **kwargs)

Hartree-Fock potential matrix for the given density matrix. See scf.hf.get_veff() and scf.hf.RHF.get_veff()

property hf_energy
init_direct_scf(mol=None)
init_guess = 'minao'
init_guess_by_1e(cell=None)

Generate initial guess density matrix from core hamiltonian

Returns:

Density matrix, 2D ndarray

init_guess_by_atom(mol=None)

Generate initial guess density matrix from superposition of atomic HF density matrix. The atomic HF is occupancy averaged RHF

Returns:

Density matrix, 2D ndarray

init_guess_by_chkfile(chk=None, project=None, kpt=None)

Read the HF results from checkpoint file, then project it to the basis defined by mol

Returns:

Density matrix, 2D ndarray

init_guess_by_huckel(mol=None)

Generate initial guess density matrix from a Huckel calculation based on occupancy averaged atomic RHF calculations, doi:10.1021/acs.jctc.8b01089

Returns:

Density matrix, 2D ndarray

init_guess_by_minao(mol=None)

Generate initial guess density matrix based on ANO basis, then project the density matrix to the basis set defined by mol

Returns:

Density matrix, 2D ndarray

Examples:

>>> from pyscf import gto, scf
>>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')
>>> scf.hf.init_guess_by_minao(mol)
array([[ 0.94758917,  0.09227308],
       [ 0.09227308,  0.94758917]])
jk_method(J='FFTDF', K=None)

Set up the schemes to evaluate Coulomb and exchange matrix

FFTDF: planewave density fitting using Fast Fourier Transform AFTDF: planewave density fitting using analytic Fourier Transform GDF: Gaussian density fitting MDF: Gaussian and planewave mix density fitting RS: range-separation JK builder RSDF: range-separation density fitting

property kcell
kernel(dm0=None, **kwargs)

SCF main driver

Kwargs:
dm0ndarray

If given, it will be used as the initial guess density matrix

Examples:

>>> import numpy
>>> from pyscf import gto, scf
>>> mol = gto.M(atom='H 0 0 0; F 0 0 1.1')
>>> mf = scf.hf.SCF(mol)
>>> dm_guess = numpy.eye(mol.nao_nr())
>>> mf.kernel(dm_guess)
converged SCF energy = -98.5521904482821
-98.552190448282104
property kpt
level_shift = 0
property level_shift_factor
make_rdm1(mo_coeff=None, mo_occ=None, **kwargs)

One-particle density matrix in AO representation

Parameters:
  • mo_coeff – 2D ndarray Orbital coefficients. Each column is one orbital.

  • mo_occ – 1D ndarray Occupancy

Returns:

One-particle density matrix, 2D ndarray

make_rdm2(mo_coeff=None, mo_occ=None, **kwargs)

Two-particle density matrix in AO representation

Parameters:
  • mo_coeff – 2D ndarray Orbital coefficients. Each column is one orbital.

  • mo_occ – 1D ndarray Occupancy

Returns:

Two-particle density matrix, 4D ndarray

max_cycle = 50
mix_density_fit(auxbasis=None, with_df=None)
mulliken_meta(mol=None, dm=None, verbose=5, pre_orth_method='ANO', s=None)

Mulliken population analysis, based on meta-Lowdin AOs. In the meta-lowdin, the AOs are grouped in three sets: core, valence and Rydberg, the orthogonalization are carreid out within each subsets.

Parameters:
  • mol – an instance of Mole

  • dm – ndarray or 2-item list of ndarray Density matrix. ROHF dm is a 2-item list of 2D array

Kwargs:

verbose : int or instance of lib.logger.Logger

pre_orth_methodstr

Pre-orthogonalization, which localized GTOs for each atom. To obtain the occupied and unoccupied atomic shells, there are three methods

‘ano’ : Project GTOs to ANO basis
‘minao’ : Project GTOs to MINAO basis
‘scf’ : Symmetry-averaged fractional occupation atomic RHF
Returns:

pop, charges

popnparray

Mulliken population on each atomic orbitals

chargesnparray

Mulliken charges

Return type:

A list

mulliken_pop(mol=None, dm=None, s=None, verbose=5)

Mulliken population analysis

\[M_{ij} = D_{ij} S_{ji}\]

Mulliken charges

\[\delta_i = \sum_j M_{ij}\]
Returns:

pop, charges

popnparray

Mulliken population on each atomic orbitals

chargesnparray

Mulliken charges

Return type:

A list

mulliken_pop_meta_lowdin_ao(*args, **kwargs)

Mulliken population analysis, based on meta-Lowdin AOs. In the meta-lowdin, the AOs are grouped in three sets: core, valence and Rydberg, the orthogonalization are carreid out within each subsets.

Parameters:
  • mol – an instance of Mole

  • dm – ndarray or 2-item list of ndarray Density matrix. ROHF dm is a 2-item list of 2D array

Kwargs:

verbose : int or instance of lib.logger.Logger

pre_orth_methodstr

Pre-orthogonalization, which localized GTOs for each atom. To obtain the occupied and unoccupied atomic shells, there are three methods

‘ano’ : Project GTOs to ANO basis
‘minao’ : Project GTOs to MINAO basis
‘scf’ : Symmetry-averaged fractional occupation atomic RHF
Returns:

pop, charges

popnparray

Mulliken population on each atomic orbitals

chargesnparray

Mulliken charges

Return type:

A list

property ncells
newton()

Create an SOSCF object based on the mean-field object

nuc_grad_method(*args, **kwargs)

Hook to create object for analytical nuclear gradients.

pop(*args, **kwargs)

Mulliken population analysis, based on meta-Lowdin AOs. In the meta-lowdin, the AOs are grouped in three sets: core, valence and Rydberg, the orthogonalization are carreid out within each subsets.

Parameters:
  • mol – an instance of Mole

  • dm – ndarray or 2-item list of ndarray Density matrix. ROHF dm is a 2-item list of 2D array

Kwargs:

verbose : int or instance of lib.logger.Logger

pre_orth_methodstr

Pre-orthogonalization, which localized GTOs for each atom. To obtain the occupied and unoccupied atomic shells, there are three methods

‘ano’ : Project GTOs to ANO basis
‘minao’ : Project GTOs to MINAO basis
‘scf’ : Symmetry-averaged fractional occupation atomic RHF
Returns:

pop, charges

popnparray

Mulliken population on each atomic orbitals

chargesnparray

Mulliken charges

Return type:

A list

post_kernel(envs)

A hook to be run after the main body of the kernel function. Internal variables are exposed to post_kernel through the “envs” dictionary. Return value of post_kernel function is not required.

pre_kernel(envs)

A hook to be run before the main body of kernel function is executed. Internal variables are exposed to pre_kernel through the “envs” dictionary. Return value of pre_kernel function is not required.

remove_soscf()

Remove the SOSCF decorator

reset(cell=None)

Reset cell and relevant attributes associated to the old cell object

rs_density_fit(auxbasis=None, with_df=None)
run(*args, **kwargs)

Call the kernel function of current object. args will be passed to kernel function. kwargs will be used to update the attributes of current object. The return value of method run is the object itself. This allows a series of functions/methods to be executed in pipe.

scf(dm0=None, **kwargs)

SCF main driver

Kwargs:
dm0ndarray

If given, it will be used as the initial guess density matrix

Examples:

>>> import numpy
>>> from pyscf import gto, scf
>>> mol = gto.M(atom='H 0 0 0; F 0 0 1.1')
>>> mf = scf.hf.SCF(mol)
>>> dm_guess = numpy.eye(mol.nao_nr())
>>> mf.kernel(dm_guess)
converged SCF energy = -98.5521904482821
-98.552190448282104
set(*args, **kwargs)

Update the attributes of the current object. The return value of method set is the object itself. This allows a series of functions/methods to be executed in pipe.

sfx2c1e()
spin_square(mo_coeff=None, s=None)

Spin square and multiplicity of RHF determinant

stability(internal=True, external=False, verbose=None, return_status=False)

RHF/RKS stability analysis.

See also pyscf.scf.stability.rhf_stability function.

Kwargs:
internalbool

Internal stability, within the RHF optimization space.

externalbool

External stability. Including the RHF -> UHF and real -> complex stability analysis.

return_status: bool

Whether to return stable_i and stable_e

Returns:

If return_status is False (default), the return value includes two set of orbitals, which are more close to the stable condition. The first corresponds to the internal stability and the second corresponds to the external stability.

Else, another two boolean variables (indicating current status: stable or unstable) are returned. The first corresponds to the internal stability and the second corresponds to the external stability.

stdout = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
to_ghf(mf)

Convert the input mean-field object to a GHF/GKS object

to_gks(xc='HF')

Convert the input mean-field object to a GKS object.

Note this conversion only changes the class of the mean-field object. The total energy and wave-function are the same as them in the input mean-field object.

to_ks(xc='HF')

Convert the input mean-field object to the associated KS object.

Note this conversion only changes the class of the mean-field object. The total energy and wave-function are the same as them in the input mean-field object.

to_rhf(mf)

Convert the input mean-field object to a RHF/ROHF/RKS/ROKS object

to_rks(xc='HF')

Convert the input mean-field object to a RKS/ROKS object.

Note this conversion only changes the class of the mean-field object. The total energy and wave-function are the same as them in the input mean-field object.

to_uhf(mf)

Convert the input mean-field object to a UHF/UKS object

to_uks(xc='HF')

Convert the input mean-field object to a UKS object.

Note this conversion only changes the class of the mean-field object. The total energy and wave-function are the same as them in the input mean-field object.

update(chkfile=None)

Read attributes from the chkfile then replace the attributes of current object. It’s an alias of function update_from_chk_.

update_(chkfile=None)

Read attributes from the chkfile then replace the attributes of current object. It’s an alias of function update_from_chk_.

update_from_chk(chkfile=None)

Read attributes from the chkfile then replace the attributes of current object. It’s an alias of function update_from_chk_.

update_from_chk_(chkfile=None)

Read attributes from the chkfile then replace the attributes of current object. It’s an alias of function update_from_chk_.

verbose = 0
view(cls)

New view of object with the same attributes.

x2c()
x2c1e()
class vayesta.core.foldscf.FoldedUHF(kmf, *args, **kwargs)[source]

Bases: FoldedSCF, UHF

Fold k-point sampled SCF calculation to the BVK (Born-von Karman) supercell.

This class automatically updates the attributes mo_energy, mo_coeff, mo_occ, e_tot, and converged. It also overwrites the methods get_ovlp, get_hcore, and get_veff, calling its more efficient k-space variant first and folding the result to the supercell.

Since get_hcore and get_veff are implemented, get_fock is supported automatically, if the inherited base SCF class implements it.

kmf

Converged k-point sampled mean-field calculation.

Type:

pyscf.pbc.gto.KRHF or pyscf.pbc.gto.KRHF

kcell

Primitive unit cell object.

Type:

pyscf.pbc.gto.Cell

ncells

Number of primitive unit cells within BVK supercell

Type:

int

kphase

Transformation matrix between k-point and BVK quantities.

Type:

(ncells, ncells) array

DIIS

alias of CDIIS

add_keys(**kwargs)

Add or update attributes of the object and register these attributes in ._keys

analyze(verbose=None, with_meta_lowdin=True, **kwargs)

Analyze the given SCF object: print orbital energies, occupancies; print orbital coefficients; Mulliken population analysis; Diople moment.

apply(fn, *args, **kwargs)

Apply the fn to rest arguments: return fn(*args, **kwargs). The return value of method set is the object itself. This allows a series of functions/methods to be executed in pipe.

as_scanner()

Generating a scanner/solver for HF PES.

The returned solver is a function. This function requires one argument “mol” as input and returns total HF energy.

The solver will automatically use the results of last calculation as the initial guess of the new calculation. All parameters assigned in the SCF object (DIIS, conv_tol, max_memory etc) are automatically applied in the solver.

Note scanner has side effects. It may change many underlying objects (_scf, with_df, with_x2c, …) during calculation.

Examples:

>>> from pyscf import gto, scf
>>> hf_scanner = scf.RHF(gto.Mole().set(verbose=0)).as_scanner()
>>> hf_scanner(gto.M(atom='H 0 0 0; F 0 0 1.1'))
-98.552190448277955
>>> hf_scanner(gto.M(atom='H 0 0 0; F 0 0 1.5'))
-98.414750424294368
build(cell=None)
canonicalize(mo_coeff, mo_occ, fock=None)

Canonicalization diagonalizes the UHF Fock matrix within occupied, virtual subspaces separatedly (without change occupancy).

check_convergence = None
check_sanity()

Check input of class/object attributes, check whether a class method is overwritten. It does not check the attributes which are prefixed with “_”. The return value of method set is the object itself. This allows a series of functions/methods to be executed in pipe.

conv_check = True
conv_tol = 1e-09
conv_tol_grad = None
convert_from_(mf)

Convert given mean-field object to RHF/ROHF

damp = 0
property damp_factor
density_fit(auxbasis=None, with_df=None)
det_ovlp(mo1, mo2, occ1, occ2, ovlp=None)

Calculate the overlap between two different determinants. It is the product of single values of molecular orbital overlap matrix.

\[S_{12} = \langle \Psi_A | \Psi_B \rangle = (\mathrm{det}\mathbf{U}) (\mathrm{det}\mathbf{V^\dagger}) \prod\limits_{i=1}\limits^{2N} \lambda_{ii}\]

where \(\mathbf{U}, \mathbf{V}, \lambda\) are unitary matrices and single values generated by single value decomposition(SVD) of the overlap matrix \(\mathbf{O}\) which is the overlap matrix of two sets of molecular orbitals:

\[\mathbf{U}^\dagger \mathbf{O} \mathbf{V} = \mathbf{\Lambda}\]
Parameters:
  • mo1 – 2D ndarrays Molecualr orbital coefficients

  • mo2 – 2D ndarrays Molecualr orbital coefficients

  • occ1 – 2D ndarrays occupation numbers

  • occ2 – 2D ndarrays occupation numbers

Returns:

the product of single values: float (x_a, x_b): 1D ndarrays \(\mathbf{U} \mathbf{\Lambda}^{-1} \mathbf{V}^\dagger\) They are used to calculate asymmetric density matrix

Return type:

A list

diis = True
diis_file = None
diis_space = 8
diis_space_rollback = 0
diis_start_cycle = 1
dip_moment(cell=None, dm=None, unit='Debye', verbose=3, **kwargs)

Dipole moment in the cell.

Parameters:
  • cell – an instance of Cell

  • dm_kpts (a list of ndarrays) – density matrices of k-points

Returns:

the dipole moment on x, y and z components

Return type:

A list

direct_scf = False
direct_scf_tol = 1e-13
dump_chk(envs)
dump_flags(verbose=None)
dump_scf_summary(verbose=5)
property e_tot
eig(fock, s)

Solver for generalized eigenvalue problem

\[HC = SCE\]
energy_elec(dm=None, h1e=None, vhf=None)

Electronic energy of Unrestricted Hartree-Fock

Note this function has side effects which cause mf.scf_summary updated.

Returns:

Hartree-Fock electronic energy and the 2-electron part contribution

energy_nuc()
energy_tot(dm=None, h1e=None, vhf=None)

Total Hartree-Fock energy, electronic part plus nuclear repulstion See scf.hf.energy_elec() for the electron part

Note this function has side effects which cause mf.scf_summary updated.

from_chk(chk=None, project=None, kpt=None)

Read the HF results from checkpoint file, then project it to the basis defined by mol

Returns:

Density matrix, 2D ndarray

gen_response(mo_coeff=None, mo_occ=None, with_j=True, hermi=0, max_memory=None)
get_bands(kpts_band, cell=None, dm=None, kpt=None)

Get energy bands at the given (arbitrary) ‘band’ k-points.

Returns:

(nmo,) ndarray or a list of (nmo,) ndarray

Bands energies E_n(k)

mo_coeff(nao, nmo) ndarray or a list of (nao,nmo) ndarray

Band orbitals psi_n(k)

Return type:

mo_energy

get_fock(h1e=None, s1e=None, vhf=None, dm=None, cycle=-1, diis=None, diis_start_cycle=None, level_shift_factor=None, damp_factor=None)

F = h^{core} + V^{HF}

Special treatment (damping, DIIS, or level shift) will be applied to the Fock matrix if diis and cycle is specified (The two parameters are passed to get_fock function during the SCF iteration)

Kwargs:
h1e2D ndarray

Core hamiltonian

s1e2D ndarray

Overlap matrix, for DIIS

vhf2D ndarray

HF potential matrix

dm2D ndarray

Density matrix, for DIIS

cycleint

Then present SCF iteration step, for DIIS

diisan object of SCF.DIIS class

DIIS object to hold intermediate Fock and error vectors

diis_start_cycleint

The step to start DIIS. Default is 0.

level_shift_factorfloat or int

Level shift (in AU) for virtual space. Default is 0.

get_grad(mo_coeff, mo_occ, fock=None)

RHF orbital gradients

Parameters:
  • mo_coeff – 2D ndarray Obital coefficients

  • mo_occ – 1D ndarray Orbital occupancy

  • fock_ao – 2D ndarray Fock matrix in AO representation

Returns:

Gradients in MO representation. It’s a num_occ*num_vir vector.

get_hcore(*args, make_real=True, **kwargs)
get_init_guess(cell=None, key='minao')
get_j(cell=None, dm=None, hermi=1, kpt=None, kpts_band=None, omega=None)

Compute J matrix for the given density matrix and k-point (kpt). When kpts_band is given, the J matrices on kpts_band are evaluated.

J_{pq} = sum_{rs} (pq|rs) dm[s,r]

where r,s are orbitals on kpt. p and q are orbitals on kpts_band if kpts_band is given otherwise p and q are orbitals on kpt.

get_jk(cell=None, dm=None, hermi=1, kpt=None, kpts_band=None, with_j=True, with_k=True, omega=None, **kwargs)

Get Coulomb (J) and exchange (K) following scf.hf.RHF.get_jk_(). for particular k-point (kpt).

When kpts_band is given, the J, K matrices on kpts_band are evaluated.

J_{pq} = sum_{rs} (pq|rs) dm[s,r] K_{pq} = sum_{rs} (pr|sq) dm[r,s]

where r,s are orbitals on kpt. p and q are orbitals on kpts_band if kpts_band is given otherwise p and q are orbitals on kpt.

get_jk_incore(cell=None, dm=None, hermi=1, kpt=None, omega=None, **kwargs)

Get Coulomb (J) and exchange (K) following scf.hf.RHF.get_jk_().

Incore version of Coulomb and exchange build only. Currently RHF always uses PBC AO integrals (unlike RKS), since exchange is currently computed by building PBC AO integrals.

get_k(cell=None, dm=None, hermi=1, kpt=None, kpts_band=None, omega=None)

Compute K matrix for the given density matrix.

get_occ(mo_energy=None, mo_coeff=None)

Label the occupancies for each orbital

Kwargs:
mo_energy1D ndarray

Obital energies

mo_coeff2D ndarray

Obital coefficients

Examples:

>>> from pyscf import gto, scf
>>> mol = gto.M(atom='H 0 0 0; F 0 0 1.1')
>>> mf = scf.hf.SCF(mol)
>>> energy = numpy.array([-10., -1., 1, -2., 0, -3])
>>> mf.get_occ(energy)
array([2, 2, 0, 2, 2, 2])
get_ovlp(*args, **kwargs)
get_rho(dm=None, grids=None, kpt=None)

Compute density in real space

get_veff(mol=None, dm=None, *args, make_real=True, **kwargs)

Hartree-Fock potential matrix for the given density matrix. See scf.hf.get_veff() and scf.hf.RHF.get_veff()

property hf_energy
init_direct_scf(mol=None)
init_guess = 'minao'
init_guess_by_1e(cell=None)

Generate initial guess density matrix from core hamiltonian

Returns:

Density matrix, 2D ndarray

init_guess_by_atom(mol=None, breaksym=True)

Generate initial guess density matrix from superposition of atomic HF density matrix. The atomic HF is occupancy averaged RHF

Returns:

Density matrix, 2D ndarray

init_guess_by_chkfile(chk=None, project=True, kpt=None)

Read the HF results from checkpoint file, then project it to the basis defined by mol

Returns:

Density matrix, 2D ndarray

init_guess_by_huckel(mol=None, breaksym=True)

Generate initial guess density matrix from a Huckel calculation based on occupancy averaged atomic RHF calculations, doi:10.1021/acs.jctc.8b01089

Returns:

Density matrix, 2D ndarray

init_guess_by_minao(mol=None, breaksym=True)

Initial guess in terms of the overlap to minimal basis.

jk_method(J='FFTDF', K=None)

Set up the schemes to evaluate Coulomb and exchange matrix

FFTDF: planewave density fitting using Fast Fourier Transform AFTDF: planewave density fitting using analytic Fourier Transform GDF: Gaussian density fitting MDF: Gaussian and planewave mix density fitting RS: range-separation JK builder RSDF: range-separation density fitting

property kcell
kernel(dm0=None, **kwargs)

SCF main driver

Kwargs:
dm0ndarray

If given, it will be used as the initial guess density matrix

Examples:

>>> import numpy
>>> from pyscf import gto, scf
>>> mol = gto.M(atom='H 0 0 0; F 0 0 1.1')
>>> mf = scf.hf.SCF(mol)
>>> dm_guess = numpy.eye(mol.nao_nr())
>>> mf.kernel(dm_guess)
converged SCF energy = -98.5521904482821
-98.552190448282104
property kpt
level_shift = 0
property level_shift_factor
make_asym_dm(mo1, mo2, occ1, occ2, x)

One-particle asymmetric density matrix

Parameters:
  • mo1 – 2D ndarrays Molecualr orbital coefficients

  • mo2 – 2D ndarrays Molecualr orbital coefficients

  • occ1 – 2D ndarrays Occupation numbers

  • occ2 – 2D ndarrays Occupation numbers

  • x – 2D ndarrays \(\mathbf{U} \mathbf{\Lambda}^{-1} \mathbf{V}^\dagger\). See also det_ovlp()

Returns:

A list of 2D ndarrays for alpha and beta spin

Examples:

>>> mf1 = scf.UHF(gto.M(atom='H 0 0 0; F 0 0 1.3', basis='ccpvdz')).run()
>>> mf2 = scf.UHF(gto.M(atom='H 0 0 0; F 0 0 1.4', basis='ccpvdz')).run()
>>> s = gto.intor_cross('int1e_ovlp_sph', mf1.mol, mf2.mol)
>>> det, x = det_ovlp(mf1.mo_coeff, mf1.mo_occ, mf2.mo_coeff, mf2.mo_occ, s)
>>> adm = make_asym_dm(mf1.mo_coeff, mf1.mo_occ, mf2.mo_coeff, mf2.mo_occ, x)
>>> adm.shape
(2, 19, 19)
make_rdm1(mo_coeff=None, mo_occ=None, **kwargs)

One-particle density matrix in AO representation

Parameters:
  • mo_coeff – tuple of 2D ndarrays Orbital coefficients for alpha and beta spins. Each column is one orbital.

  • mo_occ – tuple of 1D ndarrays Occupancies for alpha and beta spins.

Returns:

A list of 2D ndarrays for alpha and beta spins

make_rdm2(mo_coeff=None, mo_occ=None, **kwargs)

Two-particle density matrix in AO representation

Parameters:
  • mo_coeff – tuple of 2D ndarrays Orbital coefficients for alpha and beta spins. Each column is one orbital.

  • mo_occ – tuple of 1D ndarrays Occupancies for alpha and beta spins.

Returns:

A tuple of three 4D ndarrays for alpha,alpha and alpha,beta and beta,beta spins

max_cycle = 50
mix_density_fit(auxbasis=None, with_df=None)
mulliken_meta(mol=None, dm=None, verbose=5, pre_orth_method='ANO', s=None)

Mulliken population analysis, based on meta-Lowdin AOs. In the meta-lowdin, the AOs are grouped in three sets: core, valence and Rydberg, the orthogonalization are carreid out within each subsets.

Parameters:
  • mol – an instance of Mole

  • dm – ndarray or 2-item list of ndarray Density matrix. ROHF dm is a 2-item list of 2D array

Kwargs:

verbose : int or instance of lib.logger.Logger

pre_orth_methodstr

Pre-orthogonalization, which localized GTOs for each atom. To obtain the occupied and unoccupied atomic shells, there are three methods

‘ano’ : Project GTOs to ANO basis
‘minao’ : Project GTOs to MINAO basis
‘scf’ : Symmetry-averaged fractional occupation atomic RHF
Returns:

pop, charges

popnparray

Mulliken population on each atomic orbitals

chargesnparray

Mulliken charges

Return type:

A list

mulliken_meta_spin(mol=None, dm=None, verbose=5, pre_orth_method='ANO', s=None)
mulliken_pop(mol=None, dm=None, s=None, verbose=5)

Mulliken population analysis

\[M_{ij} = D_{ij} S_{ji}\]

Mulliken charges

\[\delta_i = \sum_j M_{ij}\]
Returns:

pop, charges

popnparray

Mulliken population on each atomic orbitals

chargesnparray

Mulliken charges

Return type:

A list

mulliken_pop_meta_lowdin_ao(*args, **kwargs)

Mulliken population analysis, based on meta-Lowdin AOs. In the meta-lowdin, the AOs are grouped in three sets: core, valence and Rydberg, the orthogonalization are carreid out within each subsets.

Parameters:
  • mol – an instance of Mole

  • dm – ndarray or 2-item list of ndarray Density matrix. ROHF dm is a 2-item list of 2D array

Kwargs:

verbose : int or instance of lib.logger.Logger

pre_orth_methodstr

Pre-orthogonalization, which localized GTOs for each atom. To obtain the occupied and unoccupied atomic shells, there are three methods

‘ano’ : Project GTOs to ANO basis
‘minao’ : Project GTOs to MINAO basis
‘scf’ : Symmetry-averaged fractional occupation atomic RHF
Returns:

pop, charges

popnparray

Mulliken population on each atomic orbitals

chargesnparray

Mulliken charges

Return type:

A list

mulliken_spin_pop(mol=None, dm=None, s=None, verbose=5)
property ncells
property nelec
property nelectron_alpha
newton()

Create an SOSCF object based on the mean-field object

nuc_grad_method(*args, **kwargs)

Hook to create object for analytical nuclear gradients.

pop(*args, **kwargs)

Mulliken population analysis, based on meta-Lowdin AOs. In the meta-lowdin, the AOs are grouped in three sets: core, valence and Rydberg, the orthogonalization are carreid out within each subsets.

Parameters:
  • mol – an instance of Mole

  • dm – ndarray or 2-item list of ndarray Density matrix. ROHF dm is a 2-item list of 2D array

Kwargs:

verbose : int or instance of lib.logger.Logger

pre_orth_methodstr

Pre-orthogonalization, which localized GTOs for each atom. To obtain the occupied and unoccupied atomic shells, there are three methods

‘ano’ : Project GTOs to ANO basis
‘minao’ : Project GTOs to MINAO basis
‘scf’ : Symmetry-averaged fractional occupation atomic RHF
Returns:

pop, charges

popnparray

Mulliken population on each atomic orbitals

chargesnparray

Mulliken charges

Return type:

A list

post_kernel(envs)

A hook to be run after the main body of the kernel function. Internal variables are exposed to post_kernel through the “envs” dictionary. Return value of post_kernel function is not required.

pre_kernel(envs)

A hook to be run before the main body of kernel function is executed. Internal variables are exposed to pre_kernel through the “envs” dictionary. Return value of pre_kernel function is not required.

remove_soscf()

Remove the SOSCF decorator

reset(cell=None)

Reset cell and relevant attributes associated to the old cell object

rs_density_fit(auxbasis=None, with_df=None)
run(*args, **kwargs)

Call the kernel function of current object. args will be passed to kernel function. kwargs will be used to update the attributes of current object. The return value of method run is the object itself. This allows a series of functions/methods to be executed in pipe.

scf(dm0=None, **kwargs)

SCF main driver

Kwargs:
dm0ndarray

If given, it will be used as the initial guess density matrix

Examples:

>>> import numpy
>>> from pyscf import gto, scf
>>> mol = gto.M(atom='H 0 0 0; F 0 0 1.1')
>>> mf = scf.hf.SCF(mol)
>>> dm_guess = numpy.eye(mol.nao_nr())
>>> mf.kernel(dm_guess)
converged SCF energy = -98.5521904482821
-98.552190448282104
set(*args, **kwargs)

Update the attributes of the current object. The return value of method set is the object itself. This allows a series of functions/methods to be executed in pipe.

sfx2c1e()
spin_square(mo_coeff=None, s=None)

Spin square and multiplicity of UHF determinant

\[S^2 = \frac{1}{2}(S_+ S_- + S_- S_+) + S_z^2\]

where \(S_+ = \sum_i S_{i+}\) is effective for all beta occupied orbitals; \(S_- = \sum_i S_{i-}\) is effective for all alpha occupied orbitals.

  1. There are two possibilities for \(S_+ S_-\)
    1. same electron \(S_+ S_- = \sum_i s_{i+} s_{i-}\),

    \[\sum_i \langle UHF|s_{i+} s_{i-}|UHF\rangle = \sum_{pq}\langle p|s_+s_-|q\rangle \gamma_{qp} = n_\alpha\]

    2) different electrons \(S_+ S_- = \sum s_{i+} s_{j-}, (i\neq j)\). There are in total \(n(n-1)\) terms. As a two-particle operator,

    \[\langle S_+ S_- \rangle = \langle ij|s_+ s_-|ij\rangle - \langle ij|s_+ s_-|ji\rangle = -\langle i^\alpha|j^\beta\rangle \langle j^\beta|i^\alpha\rangle\]
  2. Similarly, for \(S_- S_+\)
    1. same electron

    \[\sum_i \langle s_{i-} s_{i+}\rangle = n_\beta\]
    1. different electrons

    \[\langle S_- S_+ \rangle = -\langle i^\beta|j^\alpha\rangle \langle j^\alpha|i^\beta\rangle\]
  3. For \(S_z^2\)
    1. same electron

    \[\langle s_z^2\rangle = \frac{1}{4}(n_\alpha + n_\beta)\]
    1. different electrons

    \[\begin{split}&\frac{1}{2}\sum_{ij}(\langle ij|2s_{z1}s_{z2}|ij\rangle -\langle ij|2s_{z1}s_{z2}|ji\rangle) \\ &=\frac{1}{4}(\langle i^\alpha|i^\alpha\rangle \langle j^\alpha|j^\alpha\rangle - \langle i^\alpha|i^\alpha\rangle \langle j^\beta|j^\beta\rangle - \langle i^\beta|i^\beta\rangle \langle j^\alpha|j^\alpha\rangle + \langle i^\beta|i^\beta\rangle \langle j^\beta|j^\beta\rangle) \\ &-\frac{1}{4}(\langle i^\alpha|j^\alpha\rangle \langle j^\alpha|i^\alpha\rangle + \langle i^\beta|j^\beta\rangle\langle j^\beta|i^\beta\rangle) \\ &=\frac{1}{4}(n_\alpha^2 - n_\alpha n_\beta - n_\beta n_\alpha + n_\beta^2) -\frac{1}{4}(n_\alpha + n_\beta) \\ &=\frac{1}{4}((n_\alpha-n_\beta)^2 - (n_\alpha+n_\beta))\end{split}\]

In total

\[\begin{split}\langle S^2\rangle &= \frac{1}{2} (n_\alpha-\sum_{ij}\langle i^\alpha|j^\beta\rangle \langle j^\beta|i^\alpha\rangle +n_\beta -\sum_{ij}\langle i^\beta|j^\alpha\rangle\langle j^\alpha|i^\beta\rangle) + \frac{1}{4}(n_\alpha-n_\beta)^2 \\\end{split}\]
Parameters:

mo – a list of 2 ndarrays Occupied alpha and occupied beta orbitals

Kwargs:
sndarray

AO overlap

Returns:

A list of two floats. The first is the expectation value of S^2. The second is the corresponding 2S+1

Examples:

>>> mol = gto.M(atom='O 0 0 0; H 0 0 1; H 0 1 0', basis='ccpvdz', charge=1, spin=1, verbose=0)
>>> mf = scf.UHF(mol)
>>> mf.kernel()
-75.623975516256706
>>> mo = (mf.mo_coeff[0][:,mf.mo_occ[0]>0], mf.mo_coeff[1][:,mf.mo_occ[1]>0])
>>> print('S^2 = %.7f, 2S+1 = %.7f' % spin_square(mo, mol.intor('int1e_ovlp_sph')))
S^2 = 0.7570150, 2S+1 = 2.0070027
stability(internal=True, external=False, verbose=None, return_status=False)

Stability analysis for UHF/UKS method.

See also pyscf.scf.stability.uhf_stability function.

Parameters:

mf – UHF or UKS object

Kwargs:
internalbool

Internal stability, within the UHF space.

externalbool

External stability. Including the UHF -> GHF and real -> complex stability analysis.

return_status: bool

Whether to return stable_i and stable_e

Returns:

If return_status is False (default), the return value includes two set of orbitals, which are more close to the stable condition. The first corresponds to the internal stability and the second corresponds to the external stability.

Else, another two boolean variables (indicating current status: stable or unstable) are returned. The first corresponds to the internal stability and the second corresponds to the external stability.

stdout = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
to_ghf(mf)

Convert the input mean-field object to a GHF/GKS object

to_gks(xc='HF')

Convert the input mean-field object to a GKS object.

Note this conversion only changes the class of the mean-field object. The total energy and wave-function are the same as them in the input mean-field object.

to_ks(xc='HF')

Convert the input mean-field object to the associated KS object.

Note this conversion only changes the class of the mean-field object. The total energy and wave-function are the same as them in the input mean-field object.

to_rhf(mf)

Convert the input mean-field object to a RHF/ROHF/RKS/ROKS object

to_rks(xc='HF')

Convert the input mean-field object to a RKS/ROKS object.

Note this conversion only changes the class of the mean-field object. The total energy and wave-function are the same as them in the input mean-field object.

to_uhf(mf)

Convert the input mean-field object to a UHF/UKS object

to_uks(xc='HF')

Convert the input mean-field object to a UKS object.

Note this conversion only changes the class of the mean-field object. The total energy and wave-function are the same as them in the input mean-field object.

update(chkfile=None)

Read attributes from the chkfile then replace the attributes of current object. It’s an alias of function update_from_chk_.

update_(chkfile=None)

Read attributes from the chkfile then replace the attributes of current object. It’s an alias of function update_from_chk_.

update_from_chk(chkfile=None)

Read attributes from the chkfile then replace the attributes of current object. It’s an alias of function update_from_chk_.

update_from_chk_(chkfile=None)

Read attributes from the chkfile then replace the attributes of current object. It’s an alias of function update_from_chk_.

verbose = 0
view(cls)

New view of object with the same attributes.

x2c()
x2c1e()
vayesta.core.foldscf.fold_mos(kmo_energy, kmo_coeff, kmo_occ, kphase, ovlp, make_real=True, sort=True)[source]
vayesta.core.foldscf.log_error_norms(msg, err, error_tol=0.001, warn_tol=1e-06)[source]
vayesta.core.foldscf.make_mo_coeff_real(mo_energy, mo_coeff, ovlp, imag_tol=1e-10)[source]
vayesta.core.foldscf.make_mo_coeff_real_2(mo_energy, mo_coeff, mo_occ, ovlp, hcore, imag_tol=1e-08)[source]
vayesta.core.foldscf.kpts_to_kmesh(cell, kpts)[source]

Guess k-mesh from k-points.

vayesta.core.foldscf.translation_vectors_for_kmesh(cell, kmesh)[source]

Translation vectors to construct super-cell of which the gamma point is identical to the k-point mesh of primitive cell

vayesta.core.foldscf.get_phase(cell, kpts, kmesh=None)[source]

The unitary transformation that transforms the supercell basis k-mesh adapted basis.

Important: This is ordered as (k,R), different to PySCF k2gamma.get_phase!

vayesta.core.foldscf.k2bvk_2d(ak, phase, make_real=True, imag_tol=1e-06)[source]

Transform unit-cell k-point AO integrals to the supercell gamma-point AO integrals.

vayesta.core.foldscf.bvk2k_2d(ag, phase)[source]

Transform supercell gamma-point AO integrals to the unit-cell k-point AO integrals.

vayesta.core.helper

vayesta.core.helper.orbital_sign_convention(mo_coeff, inplace=True)[source]
vayesta.core.helper.get_dtype_int(obj)[source]
vayesta.core.helper.get_dtype(dtint)[source]
vayesta.core.helper.pack_metadata(array, maxdim=8)[source]
vayesta.core.helper.unpack_metadata(array, maxdim=8)[source]
vayesta.core.helper.pack_arrays(*arrays, dtype=<class 'float'>, maxdim=8)[source]

Pack multiple arrays into a single array of data type dtype.

Useful for MPI communication.

vayesta.core.helper.unpack_arrays(packed, dtype=<class 'float'>, maxdim=8)[source]

Unpack a single array of data type dtype into multiple arrays.

Useful for MPI communication.

vayesta.core.linalg

vayesta.core.linalg.recursive_block_svd(a, n, tol=1e-10, maxblock=100)[source]

Perform SVD of rectangular, offdiagonal blocks of a matrix recursively.

Parameters:
  • a ((m, m) array) – Input matrix.

  • n (int) – Number of rows of the first offdiagonal block.

  • tol (float, optional) – Singular values below the tolerance are considered uncoupled. Default: 1e-10.

  • maxblock (int, optional) – Maximum number of recursions. Default: 100.

Returns:

  • coeff ((m-n, m-n) array) – Coefficients.

  • sv ((m-n) array) – Singular values.

  • order ((m-n) array) – Orders.

vayesta.core.spinalg

Some utility to perform operations for RHF and UHF using the same functions

vayesta.core.spinalg.add_numbers(*args)[source]
vayesta.core.spinalg.hstack_matrices(*args, ignore_none=True)[source]

vayesta.core.util

class vayesta.core.util.Object[source]

Bases: object

class vayesta.core.util.OptionsBase[source]

Bases: object

Abstract base class for Option dataclasses.

This should be inherited and decorated with @dataclasses.dataclass. One can then define attributes and default values as for any dataclass. This base class provides some dictionary-like methods, like get and items and also the method replace, in order to update options from another Option object or dictionary.

get(attr, default=None)[source]

Dictionary-like access to attributes. Allows the definition of a default value, of the attribute is not present.

asdict(deepcopy=False)[source]
keys()[source]
values()[source]
items()[source]
classmethod get_default(field)[source]
classmethod get_default_factory(field)[source]
replace(**kwargs)[source]
update(**kwargs)[source]
static dict_with_defaults(**kwargs)[source]
classmethod change_dict_defaults(field, **kwargs)[source]
vayesta.core.util.brange(*args, minstep=1, maxstep=None)[source]

Similar to PySCF’s prange, but returning a slice instead.

Start, stop, and blocksize can be accessed from each slice blk as blk.start, blk.stop, and blk.step.

vayesta.core.util.deprecated(message=None, replacement=None)[source]

This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.

vayesta.core.util.cache(maxsize_or_user_function=16, typed=False, copy=False)[source]

Adds LRU cache to function or method.

If the function or method returns a mutable object, e.g. a NumPy array, cache hits will return the same object. If the object has been modified (for example by the user on the script level), the modified object will be returned by future calls. To avoid this, a (deep)copy of the result can be performed, by setting copy=True.

modified from https://stackoverflow.com/questions/54909357

vayesta.core.util.call_once(func, *args, **kwargs)[source]
vayesta.core.util.with_doc(doc)[source]

Use this decorator to add doc string for function

@with_doc(doc) def func:

is equivalent to

func.__doc__ = doc

vayesta.core.util.dot(*args, out=None, ignore_none=False)[source]

Like NumPy’s multi_dot, but variadic

vayesta.core.util.einsum(subscripts, *operands, **kwargs)[source]
vayesta.core.util.hstack(*args, ignore_none=True)[source]

Like NumPy’s hstack, but variadic, ignores any arguments which are None and improved error message.

exception vayesta.core.util.AbstractMethodError[source]

Bases: NotImplementedError

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception vayesta.core.util.ConvergenceError[source]

Bases: RuntimeError

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception vayesta.core.util.OrthonormalityError[source]

Bases: RuntimeError

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception vayesta.core.util.ImaginaryPartError[source]

Bases: RuntimeError

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception vayesta.core.util.NotCalculatedError[source]

Bases: AttributeError

Raise if a necessary attribute has not been calculated.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

vayesta.core.util.energy_string(energy, unit='Ha')[source]
vayesta.core.util.time_string(seconds, show_zeros=False)[source]

String representation of seconds.

vayesta.core.util.memory_string(nbytes, fmt='6.2f')[source]

String representation of nbytes

vayesta.core.util.timer()

perf_counter() -> float

Performance counter for benchmarking.

vayesta.core.util.log_time(logger, message, *args, mintime=None, **kwargs)[source]

Log time to execute the body of a with-statement.

Use as:
>>> with log_time(log.info, 'Time for hcore: %s'):
>>>     hcore = mf.get_hcore()
Parameters:
  • logger

  • message

vayesta.core.util.get_used_memory(unit='b')[source]
vayesta.core.util.log_method(message='Time for %(classname).%(funcname): %s', log=None)[source]
vayesta.core.util.getattr_recursive(obj, attr, *args)[source]
vayesta.core.util.setattr_recursive(obj, attr, val)[source]
vayesta.core.util.replace_attr(obj, **kwargs)[source]

Temporary replace attributes and methods of object.

vayesta.core.util.break_into_lines(string, linelength=100, sep=None, newline='\n')[source]

Break a long string into multiple lines

vayesta.core.util.fix_orbital_sign(mo_coeff, inplace=True)[source]
vayesta.core.util.split_into_blocks(array, axis=0, blocksize=None, max_memory=1000000000)[source]
vayesta.core.util.getif(obj, key, cond=<function <lambda>>, default=None)[source]

Returns obj[key] if cond(obj) else default.

vayesta.core.util.callif(func, arg, cond=<function <lambda>>, default=None, **kwargs)[source]

Returns func(arg, **kwargs) if cond(arg, **kwargs) else default.

vayesta.core.vlog

Vayesta logging module

class vayesta.core.vlog.NoLogger[source]

Bases: object

class vayesta.core.vlog.LevelRangeFilter(*args, low=None, high=None, **kwargs)[source]

Bases: Filter

Only log events with level in interval [low, high).

filter(record)[source]

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

class vayesta.core.vlog.LevelIncludeFilter(*args, include, **kwargs)[source]

Bases: Filter

Only log events with level in include.

filter(record)[source]

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

class vayesta.core.vlog.LevelExcludeFilter(*args, exclude, **kwargs)[source]

Bases: Filter

Only log events with level not in exlude.

filter(record)[source]

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

class vayesta.core.vlog.VFormatter(*args, show_level=True, show_mpi_rank=False, prefix_sep='|', indent=False, indent_char=' ', indent_width=4, **kwargs)[source]

Bases: Formatter

Formatter which adds a prefix column and indentation.

format(record)[source]

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

converter()
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,

tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time. When ‘seconds’ is not passed in, convert the current time instead.

default_msec_format = '%s,%03d'
default_time_format = '%Y-%m-%d %H:%M:%S'
formatException(ei)

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

formatMessage(record)
formatStack(stack_info)

This method is provided as an extension point for specialized formatting of stack information.

The input data is a string as returned from a call to traceback.print_stack(), but with the last trailing newline removed.

The base implementation just returns the value passed in.

formatTime(record, datefmt=None)

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

usesTime()

Check if the format uses the creation time of the record.

class vayesta.core.vlog.VStreamHandler(stream, formatter=None, **kwargs)[source]

Bases: StreamHandler

Default stream handler with IndentedFormatter

acquire()

Acquire the I/O thread lock.

addFilter(filter)

Add the specified filter to this handler.

close()

Tidy up any resources used by the handler.

This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.

createLock()

Acquire a thread lock for serializing access to the underlying I/O.

emit(record)

Emit a record.

If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.

filter(record)

Determine if a record is loggable by consulting all the filters.

The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.

Changed in version 3.2: Allow filters to be just callables.

flush()

Flushes the stream.

format(record)

Format the specified record.

If a formatter is set, use it. Otherwise, use the default formatter for the module.

get_name()
handle(record)

Conditionally emit the specified logging record.

Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.

handleError(record)

Handle errors which occur during an emit() call.

This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method.

property name
release()

Release the I/O thread lock.

removeFilter(filter)

Remove the specified filter from this handler.

setFormatter(fmt)

Set the formatter for this handler.

setLevel(level)

Set the logging level of this handler. level must be an int or a str.

setStream(stream)

Sets the StreamHandler’s stream to the specified value, if it is different.

Returns the old stream, if the stream was changed, or None if it wasn’t.

set_name(name)
terminator = '\n'
class vayesta.core.vlog.VFileHandler(filename, mode='a', formatter=None, add_mpi_rank=True, delay=True, **kwargs)[source]

Bases: FileHandler

Default file handler with IndentedFormatter

acquire()

Acquire the I/O thread lock.

addFilter(filter)

Add the specified filter to this handler.

close()

Closes the stream.

createLock()

Acquire a thread lock for serializing access to the underlying I/O.

emit(record)

Emit a record.

If the stream was not opened because ‘delay’ was specified in the constructor, open it before calling the superclass’s emit.

filter(record)

Determine if a record is loggable by consulting all the filters.

The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.

Changed in version 3.2: Allow filters to be just callables.

flush()

Flushes the stream.

format(record)

Format the specified record.

If a formatter is set, use it. Otherwise, use the default formatter for the module.

get_name()
handle(record)

Conditionally emit the specified logging record.

Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.

handleError(record)

Handle errors which occur during an emit() call.

This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method.

property name
release()

Release the I/O thread lock.

removeFilter(filter)

Remove the specified filter from this handler.

setFormatter(fmt)

Set the formatter for this handler.

setLevel(level)

Set the logging level of this handler. level must be an int or a str.

setStream(stream)

Sets the StreamHandler’s stream to the specified value, if it is different.

Returns the old stream, if the stream was changed, or None if it wasn’t.

set_name(name)
terminator = '\n'
vayesta.core.vlog.get_logname(name, add_mpi_rank=True, ext='txt')[source]
vayesta.core.vlog.init_logging()[source]

Call this to initialize and configure logging, when importing Vayesta.

This will: 1) Add four new logging levels:

output, infov, timing, debugv, and timingv.

  1. Adds the attribute indentLevel to the root logger and two new Logger methods:

    setIndentLevel, changeIndentLevel.

Module contents