Skip to content

Commit

Permalink
linting
Browse files Browse the repository at this point in the history
  • Loading branch information
obackhouse committed Sep 21, 2024
1 parent f179681 commit c667cdf
Show file tree
Hide file tree
Showing 11 changed files with 79 additions and 51 deletions.
32 changes: 31 additions & 1 deletion ebcc/backend/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

if TYPE_CHECKING:
from types import ModuleType
from typing import Union, TypeVar
from typing import Union, TypeVar, Optional

from numpy import int64, generic
from numpy.typing import NDArray
Expand All @@ -49,6 +49,36 @@ def __getattr__(name: str) -> ModuleType:
return importlib.import_module(f"ebcc.backend._{BACKEND.lower()}")


def to_numpy(array: NDArray[T], dtype: Optional[type[generic]] = None) -> NDArray[T]:
"""Convert an array to NumPy.
Args:
array: Array to convert.
dtype: Data type to convert to.
Returns:
Array in NumPy format.
Notes:
This function does not guarantee a copy of the array.
"""
if BACKEND == "numpy":
ndarray = array
elif BACKEND == "cupy":
ndarray = np.asnumpy(array) # type: ignore
elif BACKEND == "jax":
ndarray = np.array(array) # type: ignore
elif BACKEND == "tensorflow":
ndarray = array.numpy() # type: ignore
elif BACKEND in ("ctf", "cyclops"):
ndarray = array.to_nparray() # type: ignore
else:
raise NotImplementedError(f"Backend {BACKEND} to_numpy not implemented.")
if dtype is not None:
ndarray = ndarray.astype(dtype)
return ndarray


def _put(
array: NDArray[T],
indices: Union[NDArray[int64], tuple[NDArray[int64], ...]],
Expand Down
14 changes: 7 additions & 7 deletions ebcc/cc/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,10 @@ def __init__(
self.log = default_log if log is None else log
self.mf = self._convert_mf(mf)
self._mo_coeff: Optional[NDArray[T]] = (
np.astype(mo_coeff, types[float]) if mo_coeff is not None else None
np.asarray(mo_coeff, dtype=types[float]) if mo_coeff is not None else None
)
self._mo_occ: Optional[NDArray[T]] = (
np.astype(mo_occ, types[float]) if mo_occ is not None else None
np.asarray(mo_occ, dtype=types[float]) if mo_occ is not None else None
)

# Ansatz:
Expand All @@ -157,9 +157,9 @@ def __init__(
raise ValueError(
"Fermionic and bosonic coupling ranks must both be zero, or both non-zero."
)
self.omega = np.astype(omega, types[float]) if omega is not None else None
self.bare_g = np.astype(g, types[float]) if g is not None else None
self.bare_G = np.astype(G, types[float]) if G is not None else None
self.omega = np.asarray(omega, dtype=types[float]) if omega is not None else None
self.bare_g = np.asarray(g, dtype=types[float]) if g is not None else None
self.bare_G = np.asarray(G, dtype=types[float]) if G is not None else None
if self.boson_ansatz != "":
self.g = self.get_g()
self.G = self.get_mean_field_G()
Expand Down Expand Up @@ -964,7 +964,7 @@ def mo_coeff(self) -> NDArray[T]:
Molecular orbital coefficients.
"""
if self._mo_coeff is None:
return np.astype(self.mf.mo_coeff, types[float]) # type: ignore
return np.asarray(self.mf.mo_coeff, dtype=types[float])
return self._mo_coeff

@property
Expand All @@ -975,7 +975,7 @@ def mo_occ(self) -> NDArray[T]:
Molecular orbital occupation numbers.
"""
if self._mo_occ is None:
return np.astype(self.mf.mo_occ, types[float]) # type: ignore
return np.asarray(self.mf.mo_occ, dtype=types[float])
return self._mo_occ

@property
Expand Down
3 changes: 2 additions & 1 deletion ebcc/cc/uebcc.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,8 @@ def nocc(self) -> tuple[int, int]:
Number of occupied molecular orbitals for each spin.
"""
return cast(
tuple[int, int], tuple(np.sum(np.astype((mo_occ > 0), int)) for mo_occ in self.mo_occ)
tuple[int, int],
tuple(np.sum(np.asarray(mo_occ > 0, dtype=int)) for mo_occ in self.mo_occ),
)

@property
Expand Down
21 changes: 11 additions & 10 deletions ebcc/eom/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from ebcc import numpy as np
from ebcc import util
from ebcc.backend import to_numpy
from ebcc.core.logging import ANSI
from ebcc.core.precision import types

Expand Down Expand Up @@ -216,13 +217,13 @@ def pick(
w: NDArray[T], v: NDArray[T], nroots: int, env: dict[str, Any]
) -> tuple[NDArray[T], NDArray[T], int]:
"""Pick the eigenvalues."""
x0 = numpy.asarray(lib.linalg_helper._gen_x0(env["v"], env["xs"]))
s = numpy.conj(numpy.asarray(guesses)) @ x0.T
s = numpy.einsum("pi,pi->i", numpy.conj(s), s)
x0 = to_numpy(lib.linalg_helper._gen_x0(env["v"], env["xs"]))
s = to_numpy(guesses).conj() @ x0.T
s = numpy.einsum("pi,pi->i", s.conj(), s)
arg = numpy.argsort(-s)[:nroots]
w, v, idx = lib.linalg_helper._eigs_cmplx2real(
numpy.asarray(w),
numpy.asarray(v),
to_numpy(w),
to_numpy(v),
arg,
real_system,
)
Expand All @@ -236,8 +237,8 @@ def pick(
"""Pick the eigenvalues."""
real_idx = numpy.where(abs(numpy.imag(w)) < 1e-3)[0]
w, v, idx = lib.linalg_helper._eigs_cmplx2real(
numpy.asarray(w),
numpy.asarray(v),
to_numpy(w),
to_numpy(v),
real_idx,
real_system,
)
Expand Down Expand Up @@ -305,7 +306,7 @@ def davidson(
# Get the matrix-vector products and the diagonal:
ints = self.matvec_intermediates(eris=eris, left=self.options.left)
matvecs = lambda vs: [
numpy.asarray(self.matvec(np.asarray(v), eris=eris, ints=ints, left=self.options.left))
to_numpy(self.matvec(np.asarray(v), eris=eris, ints=ints, left=self.options.left))
for v in vs
]
diag = self.diag(eris=eris)
Expand All @@ -319,8 +320,8 @@ def davidson(
pick = self.get_pick(guesses=np.stack(guesses))
converged, e, v = lib.davidson_nosym1(
matvecs,
[numpy.asarray(g) for g in guesses],
numpy.asarray(diag),
[to_numpy(g) for g in guesses],
to_numpy(diag),
tol=self.options.e_tol,
nroots=nroots,
pick=pick,
Expand Down
5 changes: 2 additions & 3 deletions ebcc/ham/cderis.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from ebcc import numpy as np
from ebcc import util
from ebcc.backend import to_numpy
from ebcc.core.precision import types
from ebcc.ham.base import BaseERIs, BaseRHamiltonian, BaseUHamiltonian

Expand Down Expand Up @@ -57,9 +58,7 @@ def __getitem__(self, key: str, e2: Optional[bool] = False) -> NDArray[T]:
if key_e2 not in self._members:
s = 0 if not e2 else 2
coeffs = [
numpy.asarray(
self.mo_coeff[i + s][:, self.space[i + s].slice(k)], dtype=numpy.float64
)
to_numpy(self.mo_coeff[i + s][:, self.space[i + s].slice(k)], dtype=numpy.float64)
for i, k in enumerate(key)
]
ijslice = (
Expand Down
15 changes: 6 additions & 9 deletions ebcc/ham/eris.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pyscf import ao2mo

from ebcc import numpy as np
from ebcc.backend import to_numpy
from ebcc.core.precision import types
from ebcc.ham.base import BaseERIs, BaseGHamiltonian, BaseRHamiltonian, BaseUHamiltonian

Expand Down Expand Up @@ -38,15 +39,15 @@ def __getitem__(self, key: str) -> NDArray[T]:
if self.array is None:
if key not in self._members.keys():
coeffs = [
numpy.asarray(self.mo_coeff[i][:, self.space[i].slice(k)], dtype=numpy.float64)
to_numpy(self.mo_coeff[i][:, self.space[i].slice(k)], dtype=numpy.float64)
for i, k in enumerate(key)
]
if getattr(self.cc.mf, "_eri", None) is not None:
block = ao2mo.incore.general(self.cc.mf._eri, coeffs, compact=False)
else:
block = ao2mo.kernel(self.cc.mf.mol, coeffs, compact=False)
block = np.reshape(block, [c.shape[-1] for c in coeffs])
self._members[key] = np.asarray(np.astype(block, types[float]))
self._members[key] = np.asarray(block, dtype=types[float])
return self._members[key]
else:
ijkl = tuple(self.space[i].slice(k) for i, k in enumerate(key))
Expand Down Expand Up @@ -82,7 +83,7 @@ def __getitem__(self, key: str) -> RERIs:
elif isinstance(self.cc.mf._eri, tuple):
# Support spin-dependent integrals in the mean-field
coeffs = [
numpy.asarray(self.mo_coeff[x][y], dtype=numpy.float64)
to_numpy(self.mo_coeff[x][y], dtype=numpy.float64)
for y, x in enumerate(sorted((i, i, j, j)))
]
if getattr(self.cc.mf, "_eri", None) is not None:
Expand Down Expand Up @@ -119,12 +120,8 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialise the class."""
super().__init__(*args, **kwargs)
if self.array is None:
mo_a = [
numpy.asarray(mo[: self.cc.mf.mol.nao], dtype=numpy.float64) for mo in self.mo_coeff
]
mo_b = [
numpy.asarray(mo[self.cc.mf.mol.nao :], dtype=numpy.float64) for mo in self.mo_coeff
]
mo_a = [to_numpy(mo[: self.cc.mf.mol.nao], dtype=numpy.float64) for mo in self.mo_coeff]
mo_b = [to_numpy(mo[self.cc.mf.mol.nao :], dtype=numpy.float64) for mo in self.mo_coeff]
if getattr(self.cc.mf, "_eri", None) is not None:
array = ao2mo.incore.general(self.cc.mf._eri, mo_a)
array += ao2mo.incore.general(self.cc.mf._eri, mo_b)
Expand Down
30 changes: 15 additions & 15 deletions ebcc/ham/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,13 +418,13 @@ def construct_fno_space(
dm1: NDArray[T]
if not amplitudes:
solver.kernel()
dm1 = np.astype(solver.make_rdm1(), types[float])
dm1 = np.asarray(solver.make_rdm1(), dtype=types[float])
else:
if isinstance(amplitudes.t2, util.Namespace):
t2 = (amplitudes.t2.aaaa, amplitudes.t2.abab, amplitudes.t2.bbbb)
dm1 = np.astype(solver.make_rdm1(t2=t2), types[float])
dm1 = np.asarray(solver.make_rdm1(t2=t2), dtype=types[float])
else:
dm1 = np.astype(solver.make_rdm1(t2=amplitudes.t2), types[float])
dm1 = np.asarray(solver.make_rdm1(t2=amplitudes.t2), dtype=types[float])

# def _construct(dm1, mo_energy, mo_coeff, mo_occ):
def _construct(
Expand Down Expand Up @@ -479,22 +479,22 @@ def _construct(
# Construct the natural orbitals
if mf.mo_occ.ndim == 2:
coeff_a, occ_a, space_a = _construct(
np.astype(dm1[0], types[float]),
np.astype(mf.mo_energy[0], types[float]),
np.astype(mf.mo_coeff[0], types[float]),
np.astype(mf.mo_occ[0], types[float]),
np.asarray(dm1[0], dtype=types[float]),
np.asarray(mf.mo_energy[0], dtype=types[float]),
np.asarray(mf.mo_coeff[0], dtype=types[float]),
np.asarray(mf.mo_occ[0], dtype=types[float]),
)
coeff_b, occ_b, space_b = _construct(
np.astype(dm1[1], types[float]),
np.astype(mf.mo_energy[1], types[float]),
np.astype(mf.mo_coeff[1], types[float]),
np.astype(mf.mo_occ[1], types[float]),
np.asarray(dm1[1], dtype=types[float]),
np.asarray(mf.mo_energy[1], dtype=types[float]),
np.asarray(mf.mo_coeff[1], dtype=types[float]),
np.asarray(mf.mo_occ[1], dtype=types[float]),
)
return (coeff_a, coeff_b), (occ_a, occ_b), (space_a, space_b)
else:
return _construct(
np.astype(dm1, types[float]),
np.astype(mf.mo_energy, types[float]),
np.astype(mf.mo_coeff, types[float]),
np.astype(mf.mo_occ, types[float]),
np.asarray(dm1, dtype=types[float]),
np.asarray(mf.mo_energy, dtype=types[float]),
np.asarray(mf.mo_coeff, dtype=types[float]),
np.asarray(mf.mo_occ, dtype=types[float]),
)
4 changes: 2 additions & 2 deletions ebcc/opt/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ def kernel(self) -> float:
diis.damping = self.options.damping

# Initialise coefficients:
mo_coeff_new: NDArray[T] = np.copy(np.astype(self.cc.mo_coeff, types[float]))
mo_coeff_ref: NDArray[T] = np.copy(np.astype(self.cc.mo_coeff, types[float]))
mo_coeff_new: NDArray[T] = np.copy(np.asarray(self.cc.mo_coeff, dtype=types[float]))
mo_coeff_ref: NDArray[T] = np.copy(np.asarray(self.cc.mo_coeff, dtype=types[float]))
mo_coeff_ref = self.mo_to_correlated(mo_coeff_ref)
u_tot = None

Expand Down
2 changes: 1 addition & 1 deletion ebcc/opt/gbrueckner.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def get_rotation_matrix(
if np.linalg.det(u_tot) < 0:
u_tot = _put(u_tot, np.ix_(np.arange(u_tot.shape[0]), np.array([0])), -u_tot[:, 0])

a: NDArray[T] = np.astype(np.real(scipy.linalg.logm(u_tot)), types[float])
a: NDArray[T] = np.asarray(np.real(scipy.linalg.logm(u_tot)), dtype=types[float])
if diis is not None:
a = diis.update(a, xerr=t1)

Expand Down
2 changes: 1 addition & 1 deletion ebcc/opt/rbrueckner.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def get_rotation_matrix(
if np.linalg.det(u_tot) < 0:
u_tot = _put(u_tot, np.ix_(np.arange(u_tot.shape[0]), np.array([0])), -u_tot[:, 0])

a: NDArray[T] = np.astype(np.real(scipy.linalg.logm(u_tot)), types[float])
a: NDArray[T] = np.asarray(np.real(scipy.linalg.logm(u_tot)), dtype=types[float])
if diis is not None:
a = diis.update(a, xerr=t1)

Expand Down
2 changes: 1 addition & 1 deletion ebcc/opt/ubrueckner.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def get_rotation_matrix(
a = np.concatenate(
[np.ravel(scipy.linalg.logm(u_tot.aa)), np.ravel(scipy.linalg.logm(u_tot.bb))], axis=0
)
a: NDArray[T] = np.astype(np.real(a), types[float])
a: NDArray[T] = np.asarray(np.real(a), dtype=types[float])
if diis is not None:
xerr = np.concatenate([np.ravel(t1.aa), np.ravel(t1.bb)])
a = diis.update(a, xerr=xerr)
Expand Down

0 comments on commit c667cdf

Please sign in to comment.