vayesta.core

Subpackages

Submodules

vayesta.core.cmdargs

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

vayesta.core.eris

vayesta.core.eris.get_cderi(emb, mo_coeff, compact=False, blksize=None)[source]
vayesta.core.eris.get_cderi_df(mf, mo_coeff, compact=False, blksize=None)[source]

Get density-fitted three-center integrals in MO basis.

vayesta.core.eris.get_cderi_exspace(emb, ex_coeff, compact=False, blksize=None)[source]
vayesta.core.eris.get_cderi_df_exspace(mf, ex_coeff, compact=False, blksize=None)[source]

Get density-fitted three-center integrals in MO basis.

vayesta.core.eris.get_eris_array(emb, mo_coeff, compact=False)[source]

Get electron-repulsion integrals in MO basis as a NumPy array.

Parameters:

mo_coeff ([list(4) of] (n(AO), n(MO)) array) – MO coefficients.

Returns:

eris – Electron-repulsion integrals in MO basis.

Return type:

(n(MO), n(MO), n(MO), n(MO)) array

vayesta.core.eris.get_eris_object(emb, postscf, fock=None)[source]

Get ERIs for post-SCF methods.

For folded PBC calculations, this folds the MO back into k-space and contracts with the k-space three-center integrals..

Parameters:

postscf (one of the following PySCF methods: MP2, CCSD, RCCSD, DFCCSD) – Post-SCF method with attribute mo_coeff set.

Returns:

eris – ERIs which can be used for the respective post-scf method.

Return type:

_ChemistsERIs

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

CCSD(frozen=None, mo_coeff=None, mo_occ=None)

restricted CCSD

verbose

int Print level. Default value equals to Mole.verbose

max_memory

float or int Allowed memory in MB. Default value equals to Mole.max_memory

conv_tol

float converge threshold. Default is 1e-7.

conv_tol_normt

float converge threshold for norm(t1,t2). Default is 1e-5.

max_cycle

int max number of iterations. Default is 50.

diis_space

int DIIS space size. Default is 6.

diis_start_cycle

int The step to start DIIS. Default is 0.

iterative_damping

float The self consistent damping parameter.

direct

bool AO-direct CCSD. Default is False.

async_io

bool Allow for asynchronous function execution. Default is True.

incore_complete

bool Avoid all I/O (also for DIIS). Default is False.

level_shift

float A shift on virtual orbital energies to stablize the CCSD iteration

frozen

int or list If integer is given, the inner-most orbitals are frozen from CC amplitudes. Given the orbital indices (0-based) in a list, both occupied and virtual orbitals can be frozen in CC calculation.

>>> mol = gto.M(atom = 'H 0 0 0; F 0 0 1.1', basis = 'ccpvdz')
>>> mf = scf.RHF(mol).run()
>>> # freeze 2 core orbitals
>>> mycc = cc.CCSD(mf).set(frozen = 2).run()
>>> # auto-generate the number of core orbitals to be frozen (1 in this case)
>>> mycc = cc.CCSD(mf).set_frozen().run()
>>> # freeze 2 core orbitals and 3 high lying unoccupied orbitals
>>> mycc.set(frozen = [0,1,16,17,18]).run()
callback

function(envs_dict) => None callback function takes one dict as the argument which is generated by the builtin function locals(), so that the callback function can access all local variables in the current environment.

Saved results

convergedbool

CCSD converged or not

e_corrfloat

CCSD correlation correction

e_totfloat

Total CCSD energy (HF + correlation)

t1, t2 :

T amplitudes t1[i,a], t2[i,j,a,b] (i,j in occ, a,b in virt)

l1, l2 :

Lambda amplitudes l1[i,a], l2[i,j,a,b] (i,j in occ, a,b in virt)

DIIS

alias of CDIIS

QCISD(frozen=None, mo_coeff=None, mo_occ=None)

restricted QCISD

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)
callback = 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/ROHF

copy()

Returns a shallow copy

damp = 0
density_fit(auxbasis=None, with_df=None)
diis = True
diis_damp = 0
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 = True
direct_scf_tol = 1e-13
disp = None
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

Kwargs:
projectNone or bool

Whether to project chkfile’s orbitals to the new basis. Note when the geometry of the chkfile and the given molecule are very different, this projection can produce very poor initial guess. In PES scanning, it is recommended to switch off project.

If project is set to None, the projection is only applied when the basis sets of the chkfile’s molecule are different to the basis sets of the given molecule (regardless whether the geometry of the two molecules are different). Note the basis sets are considered to be different if the two molecules are derived from the same molecule with different ordering of atoms.

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_dispersion(disp_version=None)
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, fock_last=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', s1e=None)
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()

init_direct_scf(*args, **kwargs)
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

Kwargs:
projectNone or bool

Whether to project chkfile’s orbitals to the new basis. Note when the geometry of the chkfile and the given molecule are very different, this projection can produce very poor initial guess. In PES scanning, it is recommended to switch off project.

If project is set to None, the projection is only applied when the basis sets of the chkfile’s molecule are different to the basis sets of the given molecule (regardless whether the geometry of the two molecules are different). Note the basis sets are considered to be different if the two molecules are derived from the same molecule with different ordering of atoms.

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]])
init_guess_by_mod_huckel(updated_rule, mol=None)

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

In contrast to init_guess_by_huckel, this routine employs the updated GWH rule from doi:10.1021/ja00480a005 to form the guess.

Returns:

Density matrix, 2D ndarray

istype(type_code)

Checks if the object is an instance of the class specified by the type_code. type_code can be a class or a str. If the type_code is a class, it is equivalent to the Python built-in function isinstance. If the type_code is a str, it checks the type_code against the names of the object and all its parent classes.

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
property kpts
level_shift = 0
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)
property mol
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 carried 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()

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 carried 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()

Hook to create object for analytical nuclear gradients.

property opt
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 carried 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()

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_gpu(out=None)

Convert a method to its corresponding GPU variant, and recursively converts all attributes of a method to cupy objects or gpu4pyscf objects.

to_ks(xc='HF')

Convert to RKS object.

to_kscf()

Convert gamma point SCF object to k-point SCF object

to_rhf()

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

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

CCSD(frozen=None, mo_coeff=None, mo_occ=None)

restricted CCSD

verbose

int Print level. Default value equals to Mole.verbose

max_memory

float or int Allowed memory in MB. Default value equals to Mole.max_memory

conv_tol

float converge threshold. Default is 1e-7.

conv_tol_normt

float converge threshold for norm(t1,t2). Default is 1e-5.

max_cycle

int max number of iterations. Default is 50.

diis_space

int DIIS space size. Default is 6.

diis_start_cycle

int The step to start DIIS. Default is 0.

iterative_damping

float The self consistent damping parameter.

direct

bool AO-direct CCSD. Default is False.

async_io

bool Allow for asynchronous function execution. Default is True.

incore_complete

bool Avoid all I/O (also for DIIS). Default is False.

level_shift

float A shift on virtual orbital energies to stablize the CCSD iteration

frozen

int or list If integer is given, the inner-most orbitals are frozen from CC amplitudes. Given the orbital indices (0-based) in a list, both occupied and virtual orbitals can be frozen in CC calculation.

>>> mol = gto.M(atom = 'H 0 0 0; F 0 0 1.1', basis = 'ccpvdz')
>>> mf = scf.RHF(mol).run()
>>> # freeze 2 core orbitals
>>> mycc = cc.CCSD(mf).set(frozen = 2).run()
>>> # auto-generate the number of core orbitals to be frozen (1 in this case)
>>> mycc = cc.CCSD(mf).set_frozen().run()
>>> # freeze 2 core orbitals and 3 high lying unoccupied orbitals
>>> mycc.set(frozen = [0,1,16,17,18]).run()
callback

function(envs_dict) => None callback function takes one dict as the argument which is generated by the builtin function locals(), so that the callback function can access all local variables in the current environment.

Saved results

convergedbool

CCSD converged or not

e_corrfloat

CCSD correlation correction

e_totfloat

Total CCSD energy (HF + correlation)

t1, t2 :

T amplitudes t1[i,a], t2[i,j,a,b] (i,j in occ, a,b in virt)

l1, l2 :

Lambda amplitudes l1[i,a], l2[i,j,a,b] (i,j in occ, a,b in virt)

DIIS

alias of CDIIS

QCISD(frozen=None, mo_coeff=None, mo_occ=None)

restricted QCISD

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)
callback = 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 UHF

copy()

Returns a shallow copy

damp = 0
density_fit(auxbasis=None, with_df=None)
diis = True
diis_damp = 0
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 = True
direct_scf_tol = 1e-13
disp = None
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

Kwargs:
projectNone or bool

Whether to project chkfile’s orbitals to the new basis. Note when the geometry of the chkfile and the given molecule are very different, this projection can produce very poor initial guess. In PES scanning, it is recommended to switch off project.

If project is set to None, the projection is only applied when the basis sets of the chkfile’s molecule are different to the basis sets of the given molecule (regardless whether the geometry of the two molecules are different). Note the basis sets are considered to be different if the two molecules are derived from the same molecule with different ordering of atoms.

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_dispersion(disp_version=None)
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, fock_last=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', s1e=None)
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()

init_direct_scf(*args, **kwargs)
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

Kwargs:
projectNone or bool

Whether to project chkfile’s orbitals to the new basis. Note when the geometry of the chkfile and the given molecule are very different, this projection can produce very poor initial guess. In PES scanning, it is recommended to switch off project.

If project is set to None, the projection is only applied when the basis sets of the chkfile’s molecule are different to the basis sets of the given molecule (regardless whether the geometry of the two molecules are different). Note the basis sets are considered to be different if the two molecules are derived from the same molecule with different ordering of atoms.

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.

init_guess_by_mod_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

In contrast to init_guess_by_huckel, this routine employs the updated GWH rule from doi:10.1021/ja00480a005 to form the guess.

Returns:

Density matrix, 2D ndarray

istype(type_code)

Checks if the object is an instance of the class specified by the type_code. type_code can be a class or a str. If the type_code is a class, it is equivalent to the Python built-in function isinstance. If the type_code is a str, it checks the type_code against the names of the object and all its parent classes.

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
property kpts
level_shift = 0
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)
property mol
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 carried 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 carried 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
property nelec
newton()

Create an SOSCF object based on the mean-field object

nuc_grad_method()

Hook to create object for analytical nuclear gradients.

property opt
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 carried 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()

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_gpu(out=None)

Convert a method to its corresponding GPU variant, and recursively converts all attributes of a method to cupy objects or gpu4pyscf objects.

to_ks(xc='HF')

Convert to RKS object.

to_kscf()

Convert gamma point SCF object to k-point SCF object

to_rhf()

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

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.tril_indices_ndim(n, dims, include_diagonal=False)[source]

Return lower triangular indices for a multidimensional array.

Copied from ebcc.

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.

vayesta.core.util.decompress_axes(subscript, array_flat, shape, include_diagonal=False, symmetry=None)[source]

Decompress an array that has dimensions flattened according to permutation symmetries in the signs.

Copied from ebcc.

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.util.permutations_with_signs(seq)[source]

Generate permutations of seq, yielding also a sign which is equal to +1 for an even number of swaps, and -1 for an odd number of swaps.

Copied from ebcc.

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