Skip to content

Basis sets and orbitals

Wavefunction.orbitals is the one home of a calculation's orbital levels: energies and occupations per spin, the electronic temperature and Fermi levels, and the electrons each atom keeps outside the orbitals (core_electrons). On request it also holds the coefficients, so they can seed another program's SCF, be plotted, or be compared across programs. Wavefunction adds the AO matrices (overlap, hamiltonian_a/_b and core_hamiltonian) and basis, the basis set that the coefficients and every AO matrix share, with the AO convention they follow and its effective core potentials (Ecp). The design and its reasons are in Wavefunctions.

qcdata.Wavefunction

The wavefunction of a single point calculation: its orbitals and AO matrices.

The SCF density is not stored: it is C n C^T of the returned orbitals (Orbitals.density). The orbitals' coefficients and the AO matrices come only on request, and all of them are indexed by the AOs of one basis set, basis: it is present whenever any of them is, and only then. An overlap alone therefore ships the basis set and no coefficients. with_convention converts the coefficients and every matrix together.

Attributes:

Name Type Description
orbitals Orbitals

The orbital levels and, on request, the orbitals' coefficients.

basis BasisSet | None

The basis set that the coefficients and every AO matrix share (its centers refer to the structure's atoms), in AO order and with its AOConvention; present whenever coefficients or an AO matrix are.

overlap SerializableMatrix | None

The AO overlap matrix S the program used, with its own screening.

hamiltonian_a SerializableMatrix | None

The Fock or Kohn-Sham matrix, or the tight-binding Hamiltonian (Eh), of alpha electrons or of both spins for restricted orbitals: the operator of one build at the SCF's last input (a density, or charges and multipole moments), however that input was mixed. The canonical orbitals are its fresh generalized eigenvectors with the returned S, H C = S C diag(energies). It is built from the last input, not from the returned orbitals' density, which is one step ahead; the two differ by the SCF residual. It holds everything in the SCF operator (exchange-correlation on the final grid, nonlocal correlation, a continuum solvent's operator) and nothing that does not depend on the density (dispersion, a solvent's CDS term). Requesting it changes no other number.

hamiltonian_b SerializableMatrix | None

The beta Hamiltonian (Eh) of unrestricted orbitals.

core_hamiltonian SerializableMatrix | None

Every density-independent one-electron term of the run (Eh): the kinetic energy, the attraction of nuclei with charges Z - core_electrons, the ECPs, and external point charges and fields where a program supports them. tr((P_a + P_b) h), with P the density of the SCF's last input, is the energy's one_electron component; with Orbitals.density, the density a reader has, the two agree to the SCF residual, so compare them at SCF tolerance, not at round-off.

with_convention

with_convention(convention: AOConvention) -> Wavefunction

The same wavefunction with its AOs in another convention.

Each array changes with its variance (BasisSet.transform): coefficients scale by s per AO index and the AO matrices, all operators, by 1 / (s_mu s_nu). The orbital levels are shared, not copied.

Parameters:

Name Type Description Default
convention AOConvention

The target AO convention.

required

Returns:

Type Description
Wavefunction

A new wavefunction whose basis set has the target convention.

Raises:

Type Description
ValueError

If the wavefunction has no basis set (only orbital levels).

Source code in src/qcdata/models/data.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def with_convention(self, convention: AOConvention) -> Wavefunction:
    """The same wavefunction with its AOs in another convention.

    Each array changes with its variance (`BasisSet.transform`): coefficients scale
    by s per AO index and the AO matrices, all operators, by 1 / (s_mu s_nu). The
    orbital levels are shared, not copied.

    Args:
        convention: The target AO convention.

    Returns:
        A new wavefunction whose basis set has the target convention.

    Raises:
        ValueError: If the wavefunction has no basis set (only orbital levels).
    """
    basis = self.basis
    if basis is None:
        raise ValueError(
            "with_convention() needs the basis set, and this wavefunction has only "
            "orbital levels: programs return the basis set with the coefficients or "
            "an AO matrix, on request"
        )
    update: dict[str, Any] = {
        "basis": basis.model_copy(update={"ao_convention": convention})
    }
    orbitals = self.orbitals
    coefficients = {
        name: basis.transform(c, convention, kind="coefficients")
        for name in ("coefficients_a", "coefficients_b")
        if (c := getattr(orbitals, name)) is not None
    }
    if coefficients:
        update["orbitals"] = orbitals.model_copy(update=coefficients)
    for name in _AO_MATRICES:
        matrix = getattr(self, name)
        if matrix is not None:
            update[name] = basis.transform(matrix, convention, kind="operator")
    return self.model_copy(update=update)

qcdata.Orbitals

The orbital levels of a calculation and, on request, the orbitals themselves.

The one home of orbital energies and occupations. The levels are cheap and come with every wavefunction; the coefficients (nao x nmo numbers per spin) come only on request, and expand in the wavefunction's basis set (Wavefunction.basis), which checks their rows. Every per-orbital vector has one value per orbital, in the order of the coefficient matrices' columns.

Where the structure is known (a ProgramOutput or a Frame), the occupations add up to sum(Z - core_electrons) - charge.

Attributes:

Name Type Description
spin OrbitalSpin

restricted: one set of spatial orbitals (one coefficient matrix, one set of energies, one Hamiltonian), occupied per spin. unrestricted: everything per spin.

kind OrbitalKind

What the orbitals are: canonical (with energies), natural or localized (without).

localization str | None

The method that localized localized orbitals (e.g. "boys", "pipek_mezey"); None for every other kind.

energies_a SerializableVector | None

Orbital energies (Eh) of canonical orbitals: alpha, or both spins.

energies_b SerializableVector | None

Beta orbital energies (Eh) of unrestricted canonical orbitals.

occupations_a SerializableVector

Alpha electrons in each orbital, between 0 and 1.

occupations_b SerializableVector

Beta electrons in each orbital, between 0 and 1; for restricted orbitals of an open shell they differ from the alpha ones.

electronic_temperature float

The temperature (K) of the Fermi smearing that set the occupations; 0 for aufbau occupations.

fermi_level_a float | None

The alpha Fermi level (Eh) of smeared occupations; None at 0 K. A spin that holds no electrons (an H atom's beta) has no Fermi level and may leave it None.

fermi_level_b float | None

The beta Fermi level (Eh); None at 0 K. Each spin is filled at its own fixed electron count, so an open shell has two levels; a closed shell's are equal.

core_electrons list[int] | None

One per atom of the structure: the electrons the orbitals do not represent, those an ECP replaces (equal to Ecp.core_electrons on every ECP atom of Wavefunction.basis) or a valence-only method leaves out (28 for Zn in GFN2-xTB and g-xTB). None: every electron is in the orbitals.

coefficients_a SerializableMatrix | None

nao x nmo, in the AOs of Wavefunction.basis; column i is orbital i (alpha, or both spins). Only on request.

coefficients_b SerializableMatrix | None

The beta orbitals, nao x nmo: unrestricted orbitals with coefficients only.

nmo int

@property The number of orbitals.

nmo property

nmo: int

Number of molecular orbitals.

restricted property

restricted: bool

Whether the orbitals are restricted.

density

density() -> tuple[ndarray, ndarray]

The alpha and beta AO density matrices, C n C^T per spin.

Returns:

Type Description
tuple[ndarray, ndarray]

Two nao x nao matrices in the AOs of the wavefunction's basis set.

Raises:

Type Description
ValueError

If the orbitals have no coefficients.

Source code in src/qcdata/models/orbitals.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
def density(self) -> tuple[np.ndarray, np.ndarray]:
    """The alpha and beta AO density matrices, C n C^T per spin.

    Returns:
        Two nao x nao matrices in the AOs of the wavefunction's basis set.

    Raises:
        ValueError: If the orbitals have no coefficients.
    """
    ca = self.coefficients_a
    if ca is None:
        raise ValueError(
            "density() needs the orbitals' coefficients, and these orbitals have "
            "only their levels: programs return coefficients on request (output "
            "orbitals)"
        )
    cb = self.coefficients_b if self.coefficients_b is not None else ca
    return (ca * self.occupations_a) @ ca.T, (cb * self.occupations_b) @ cb.T

qcdata.OrbitalKind

What a set of orbitals is.

Values are added when a program produces them.

Attributes:

Name Type Description
canonical

The eigenvectors of the Hamiltonian, with their energies.

natural

The eigenvectors of a density, with their occupations; no energies.

localized

Localized orbitals, with no energies; Orbitals.localization names the method.

qcdata.OrbitalSpin

Whether alpha and beta electrons share spatial orbitals.

Attributes:

Name Type Description
restricted

One set of spatial orbitals for both spins, occupied per spin: RHF and RKS; ROHF; and tight binding's open shells (GFN2-xTB), the eigenvectors of one spin-averaged Hamiltonian with per-spin occupations, which are not ROHF.

unrestricted

Separate alpha and beta orbitals (UHF, UKS).

qcdata.BasisSet

A basis set placed on the atoms of a structure, in AO order.

A basis set belongs to one geometry: a tight-binding basis whose contraction depends on the geometry (g-xTB's q-vSZP) differs from frame to frame.

Attributes:

Name Type Description
name str | None

The basis set's name (e.g. "def2-svp"), if it has one.

shells list[Shell]

The contracted shells; the AOs are their functions in this order.

ecp list[Ecp]

The effective core potentials, at most one per atom, each with the number of core electrons it replaces.

ao_convention AOConvention

Order and normalization of the functions within each shell.

nao int

@property The number of AOs.

nao property

nao: int

Number of atomic orbitals (basis functions).

ao_labels

ao_labels(
    symbols: Sequence[str] | None = None,
) -> list[str]

One label per AO, e.g. "0 O 2p x" or "1 H 1s".

Spherical functions are labelled d-2 .. d+2, Cartesian ones dxy; shells are numbered by l per atom.

Parameters:

Name Type Description Default
symbols Sequence[str] | None

Element symbols of the structure's atoms, to include in the labels.

None

Returns:

Type Description
list[str]

One label per AO, in AO order.

Source code in src/qcdata/models/orbitals.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def ao_labels(self, symbols: Sequence[str] | None = None) -> list[str]:
    """One label per AO, e.g. ``"0 O 2p x"`` or ``"1 H 1s"``.

    Spherical functions are labelled ``d-2 .. d+2``, Cartesian ones ``dxy``; shells
    are numbered by l per atom.

    Args:
        symbols: Element symbols of the structure's atoms, to include in the labels.

    Returns:
        One label per AO, in AO order.
    """
    labels: list[str] = []
    count: dict[tuple[int, int], int] = {}
    for s in self.shells:
        l = s.angular_momentum
        n = count[(s.center, l)] = count.get((s.center, l), 0) + 1
        atom = (
            f"{s.center} {symbols[s.center]}"
            if symbols is not None
            else f"{s.center}"
        )
        for key in _function_keys(s, self.ao_convention):
            labels.append(f"{atom} {n + l}{_function_name(l, key)}")
    return labels

shell_offsets

shell_offsets() -> list[int]

Index of the first AO of each shell.

Source code in src/qcdata/models/orbitals.py
299
300
301
302
303
304
305
def shell_offsets(self) -> list[int]:
    """Index of the first AO of each shell."""
    out, n = [], 0
    for s in self.shells:
        out.append(n)
        n += s.nfunc
    return out

transform

transform(
    array: Any,
    convention: AOConvention,
    *,
    kind: AOArrayKind,
    shell_order: Sequence[int] | None = None,
) -> ndarray

Convert an AO-indexed array to another AO convention and shell order.

A target AO is a source AO divided by s, the ratio of the function's norm in this convention to its norm in the target (1 for every spherical function and for a reordering alone). Coefficients therefore scale by s per AO index, densities by s_mu s_nu and operators by 1 / (s_mu s_nu); a reordering permutes the AO indices of all three alike.

Parameters:

Name Type Description Default
array Any

The array in this basis set's convention.

required
convention AOConvention

The target convention.

required
kind AOArrayKind

How the array transforms: coefficients (its first index is an AO, e.g. MO coefficients, nao x nmo), operator (an nao x nao matrix of integrals : overlap, Hamiltonians) or density (an nao x nao matrix that contracts with operators, e.g. C n C^T).

required
shell_order Sequence[int] | None

The shells' order in the target, as indices into shells; None keeps the order.

None

Returns:

Type Description
ndarray

A new array in the target convention.

Raises:

Type Description
ValueError

If kind is unknown or the array does not match the basis set's AOs.

Source code in src/qcdata/models/orbitals.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def transform(
    self,
    array: Any,
    convention: AOConvention,
    *,
    kind: AOArrayKind,
    shell_order: Sequence[int] | None = None,
) -> np.ndarray:
    """Convert an AO-indexed array to another AO convention and shell order.

    A target AO is a source AO divided by s, the ratio of the function's norm in
    this convention to its norm in the target (1 for every spherical function and
    for a reordering alone). Coefficients therefore scale by s per AO index,
    densities by s_mu s_nu and operators by 1 / (s_mu s_nu); a reordering permutes
    the AO indices of all three alike.

    Args:
        array: The array in this basis set's convention.
        convention: The target convention.
        kind: How the array transforms: ``coefficients`` (its first index is an AO,
            e.g. MO coefficients, nao x nmo), ``operator`` (an nao x nao matrix of
            integrals <mu|O|nu>: overlap, Hamiltonians) or ``density`` (an
            nao x nao matrix that contracts with operators, e.g. C n C^T).
        shell_order: The shells' order in the target, as indices into `shells`;
            None keeps the order.

    Returns:
        A new array in the target convention.

    Raises:
        ValueError: If `kind` is unknown or the array does not match the basis set's
            AOs.
    """
    if kind not in ("coefficients", "operator", "density"):
        raise ValueError(
            f"kind must be coefficients, operator or density, not {kind!r}"
        )
    a = np.asarray(array, dtype=float)
    nao = self.nao
    perm, scale = _ao_map(self, convention, shell_order)
    if kind == "coefficients":
        if a.ndim == 0 or a.shape[0] != nao:
            raise ValueError(f"expected {nao} rows (AOs), got shape {a.shape}")
        return a[perm] * scale.reshape((-1,) + (1,) * (a.ndim - 1))
    if a.shape != (nao, nao):
        raise ValueError(f"expected an {nao} x {nao} matrix, got shape {a.shape}")
    moved = a[np.ix_(perm, perm)]
    pair = np.outer(scale, scale)
    return moved / pair if kind == "operator" else moved * pair

qcdata.Shell

One contracted shell on an atom.

Attributes:

Name Type Description
center int

Index of the atom (0-based) in the structure the basis set belongs to.

angular_momentum int

l (0 for s, 1 for p, ...).

pure bool

Spherical (2l + 1 functions) or Cartesian ((l+1)(l+2)/2 functions). s and p shells are the same either way except for the order of p (see AOConvention).

exponents SerializableVector

Primitive exponents (bohr^-2).

coefficients SerializableVector

Contraction coefficients of the unnormalized primitives r^l exp(-a r^2), normalization included: the x^l component of the shell (and every spherical function) has unit norm.

nfunc property

nfunc: int

Number of functions of the shell.

primitive_coefficients

primitive_coefficients() -> ndarray

Coefficients of x^l-normalized primitives.

This is the convention of basis set files, Molden and most programs' input; the contraction stays normalized.

Returns:

Type Description
ndarray

One coefficient per primitive.

Source code in src/qcdata/models/orbitals.py
199
200
201
202
203
204
205
206
207
208
def primitive_coefficients(self) -> np.ndarray:
    """Coefficients of x^l-normalized primitives.

    This is the convention of basis set files, Molden and most programs' input; the
    contraction stays normalized.

    Returns:
        One coefficient per primitive.
    """
    return self.coefficients / _xl_norm(self.angular_momentum, self.exponents)

qcdata.Ecp

The scalar effective core potential of one atom.

The potential is U_L(r) + sum_{l<L} (U_l(r) - U_L(r)) P_l, with P_l the projector on angular momentum l about the atom and L = len(semilocal): the layout of Basis Set Exchange, NWChem, PySCF and Psi4. Spin-orbit terms have no place here. With the number of core electrons it replaces, an ECP is a complete potential; in a Wavefunction, the atom's Orbitals.core_electrons agrees with it.

Attributes:

Name Type Description
center int

Index of the atom (0-based) in the structure the basis set belongs to.

core_electrons int

The number of core electrons the potential replaces, so the nucleus enters with charge Z - core_electrons.

local list[EcpTerm]

The terms of U_L, felt by every angular momentum.

semilocal list[list[EcpTerm]]

semilocal[l], for l = 0..L-1: the terms of U_l - U_L.

qcdata.EcpTerm

One Gaussian term of an ECP channel: coefficient * r^power * exp(-exponent r^2).

Attributes:

Name Type Description
power int

The power of r, -2 or more. Basis Set Exchange JSON and NWChem write n for r^(n-2), so their power is n - 2.

exponent float

Gaussian exponent (bohr^-2), positive.

coefficient float

Coefficient (Eh bohr^-power).

qcdata.AOConvention

How the functions of each shell are ordered and normalized.

Shells are always in the order of BasisSet.shells; this says which functions a shell contributes and in what order. The default is PySCF's ordering with x^l-normalized Cartesian components (libcint). Real solid harmonics are the usual unit-normalized ones without a Condon-Shortley phase (as PySCF, libint and Molden).

Attributes:

Name Type Description
spherical_order SphericalOrder

Order of the functions of pure shells.

cartesian_order CartesianOrder

Order of the components of Cartesian shells.

cartesian_normalization CartesianNormalization

Norm of the components of Cartesian shells.

qcdata.SphericalOrder

Order of the 2l+1 real solid harmonics of a pure shell.

Attributes:

Name Type Description
pyscf

m = -l..l, except p shells, which are (x, y, z) (libcint, PySCF).

increasing_m

m = -l..l for every l, so p is (y, z, x) (libint's "standard", CCA, order).

molden

m = 0, +1, -1, +2, -2, ..., with p as (x, y, z) (Molden, Gaussian, ORCA's order; ORCA also flips the sign of some f and g functions, not covered here).

trexio

m = 0, +1, -1, +2, -2, ... for every l, so p is (z, x, y) (TREXIO).

qcdata.CartesianOrder

Order of the (l+1)(l+2)/2 components of a Cartesian shell.

Attributes:

Name Type Description
lexicographic

xx, xy, xz, yy, yz, zz (lx descending, then ly descending; libint, libcint, PySCF, CCA, TREXIO).

molden

xx, yy, zz, xy, xz, yz; xxx, yyy, zzz, xyy, xxy, xxz, xzz, yzz, yyz, xyz; and Molden's g order (up to l = 4).

qcdata.CartesianNormalization

Norm of the components of a Cartesian shell (pure functions always have unit norm).

Attributes:

Name Type Description
axis

every component carries the normalization of x^l: x^l, y^l, z^l have unit norm, xy has norm 1/sqrt(3) (libint).

unit

every component has unit norm (Molden).

pyscf

as axis times sqrt(4 pi / (2l + 1)) for l >= 2 (PySCF's cart=True).