atomic_femdvr 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ """Solver for the atomic Kohn-Sham equation, including all-electron and pseudo-potential calculation."""
@@ -0,0 +1,12 @@
1
+ """Entrypoint module, in case you use `python -m atomic_femdvr`.
2
+
3
+ Why does this file exist, and why ``__main__``? For more info, read:
4
+
5
+ - https://www.python.org/dev/peps/pep-0338/
6
+ - https://docs.python.org/3/using/cmdline.html#cmdoption-m
7
+ """
8
+
9
+ from .cli import main
10
+
11
+ if __name__ == "__main__":
12
+ main()
@@ -0,0 +1,164 @@
1
+ import numpy as np
2
+
3
+
4
+ #=================================================================
5
+ def adaptive_runge_kutta_23(f, y0, t0, t1, h_min, h_max, tol, arg=None):
6
+ # Adaptive Runge-Kutta 2-3 method for solving ODEs
7
+
8
+ def rk23_step(f, y, t, h, arg=None):
9
+ if arg is not None:
10
+ fn = lambda t, y: f(t, y, arg)
11
+ else:
12
+ fn = f
13
+ # Runge-Kutta 2-3 step
14
+ k1 = fn(t, y)
15
+ k2 = fn(t + h / 2, y + h / 2 * k1)
16
+ k3 = fn(t + h, y + h * k2)
17
+
18
+ y2 = y + h * (k1 + 4 * k2 + k3) / 6
19
+ y3 = y + h * (k1 + 3 * k2) / 4
20
+
21
+ return y2, y3
22
+ t = t0
23
+ y = y0
24
+ h = h_max
25
+ t_values = [t]
26
+ y_values = [y]
27
+ while t < t1:
28
+ if t + h > t1:
29
+ h = t1 - t
30
+
31
+ y2, y3 = rk23_step(f, y, t, h, arg=arg)
32
+
33
+ error = np.linalg.norm(y3 - y2)
34
+
35
+ if error < tol:
36
+ t += h
37
+ y = y2
38
+ t_values.append(t)
39
+ y_values.append(y)
40
+ else:
41
+ # Decrease step size
42
+ if h <= h_min:
43
+ # If already at minimal step size, proceed with h_min
44
+ t += h
45
+ y = y2
46
+ t_values.append(t)
47
+ y_values.append(y)
48
+ h = h_min
49
+ else:
50
+ h = max(h * 0.5, h_min)
51
+
52
+
53
+ # print(f"t: {t:.4f}, h: {h:.4f}, error: {error:.4e}")
54
+
55
+ return np.array(t_values), np.array(y_values)
56
+ #=================================================================
57
+ def adaptive_runge_kutta_23_outward(f, y0, t0, t1, h_min, h_max, tol):
58
+ """
59
+ Adaptive RK23 propagating outward from t0 to t1.
60
+
61
+ Unlike the inward variant, the step size is allowed to grow (up to h_max)
62
+ when the local error is small, so coarser elements are placed automatically
63
+ as the weight function decays away from the nucleus.
64
+ """
65
+ def rk23_step(fn, y, t, h):
66
+ k1 = fn(t, y)
67
+ k2 = fn(t + h / 2, y + h / 2 * k1)
68
+ k3 = fn(t + h, y + h * k2)
69
+ y2 = y + h * (k1 + 4 * k2 + k3) / 6
70
+ y3 = y + h * (k1 + 3 * k2) / 4
71
+ return y2, y3
72
+
73
+ t = t0
74
+ y = y0
75
+ h = h_min # start small at the core boundary, grow as weight decays
76
+ t_values = [t]
77
+ y_values = [y]
78
+
79
+ while t < t1:
80
+ if t + h > t1:
81
+ h = t1 - t
82
+
83
+ y2, y3 = rk23_step(f, y, t, h)
84
+ error = np.linalg.norm(y3 - y2)
85
+
86
+ if error < tol:
87
+ t += h
88
+ y = y2
89
+ t_values.append(t)
90
+ y_values.append(y)
91
+ # Error-based growth: jump h aggressively when error << tol,
92
+ # capped at 5x per step to avoid overshooting.
93
+ growth = min(5.0, 0.9 * (tol / max(error, 1e-15)) ** (1.0 / 3.0))
94
+ h = min(h * growth, h_max)
95
+ else:
96
+ if h <= h_min:
97
+ # at minimum step, accept and stay at h_min
98
+ t += h
99
+ y = y2
100
+ t_values.append(t)
101
+ y_values.append(y)
102
+ else:
103
+ h = max(h * 0.5, h_min)
104
+
105
+ return np.array(t_values), np.array(y_values)
106
+ #=================================================================
107
+ def optimize_elements_ae(Zc: float, h_min: float, h_max: float, Rmax: float,
108
+ tol: float = 1.0e-2, Za: float = 1.0,
109
+ n_core_factor: float = 5.0,
110
+ method: str = 'exponential') -> np.ndarray:
111
+ """
112
+ Element boundaries for all-electron calculations.
113
+
114
+ Core region [0, r_c]: uniform spacing with n_core elements, spacing
115
+ chosen as close to h_min as possible while exactly filling the interval.
116
+
117
+ Outer region [r_c, Rmax]: outward adaptive RK23 starting at h_min,
118
+ step size grows as the weight function decays, reaching h_max in the
119
+ asymptotic region.
120
+
121
+ r_c = n_core_factor / Zc defines the core boundary (default: 5/Z).
122
+ """
123
+ r_c = n_core_factor / Zc
124
+
125
+ # Core: uniform grid with spacing as close to h_min as possible
126
+ n_core = max(1, round(r_c / h_min))
127
+ core_grid = np.linspace(0.0, r_c, n_core + 1)
128
+
129
+ # Outer: outward adaptive RK23 from r_c to Rmax
130
+ if method.lower() == 'exponential':
131
+ wght_fnc = lambda r: np.exp(-Zc * r) + np.exp(-Za * r)
132
+ elif method.lower() == 'wkb':
133
+ Vc_fnc = lambda r: -Zc / np.sqrt(r**2 + 1.0e-2)
134
+ wght_fnc = lambda r: np.sqrt(2.0 * np.abs(Vc_fnc(r)))
135
+ else:
136
+ raise ValueError(f"Unknown method '{method}' for optimizing elements.")
137
+
138
+ outer_t, _ = adaptive_runge_kutta_23_outward(
139
+ lambda r, _: wght_fnc(r), 0.0, r_c, Rmax, h_min, h_max, tol
140
+ )
141
+
142
+ # Concatenate, dropping the duplicate point at r_c
143
+ return np.concatenate([core_grid, outer_t[1:]])
144
+ #=================================================================
145
+ def optimize_elements(Zc: float, h_min: float, h_max: float, Rmax: float,
146
+ tol: float = 1.0e-2, Za: float = 1.0,
147
+ method: str = 'exponential') -> np.ndarray:
148
+
149
+ if method.lower() == 'exponential':
150
+ wght_fnc = lambda r: np.exp(-Zc *r) + np.exp(-Za * r)
151
+
152
+ elif method.lower() == 'wkb':
153
+ Vc_fnc = lambda r: -Zc / np.sqrt(r**2 + 1.0e-2)
154
+ wght_fnc = lambda r: np.sqrt(2.0 * np.abs(Vc_fnc(r)))
155
+ else:
156
+ raise ValueError(f"Unknown method '{method}' for optimizing elements.")
157
+
158
+ wght_fnc_r = lambda r, y, L: wght_fnc(Rmax - r)
159
+ xk, _ = adaptive_runge_kutta_23(wght_fnc_r, 0.0, 0.0, Rmax,
160
+ h_min, h_max, tol, arg=Rmax)
161
+ grid = np.flip(Rmax - xk)
162
+
163
+ return grid
164
+ #=================================================================
@@ -0,0 +1,108 @@
1
+ """Functionality shared by the all-electron and pseudo-atom Kohn-Sham solvers."""
2
+
3
+ import os
4
+
5
+ import h5py
6
+ import numpy as np
7
+
8
+ import atomic_femdvr.density_potential as density_potential
9
+ from atomic_femdvr.femdvr import FEDVR_Basis
10
+ from atomic_femdvr.input import ControlInput, DFTInput
11
+ from atomic_femdvr.mixing import make_mixer
12
+
13
+
14
+ #==========================================================================
15
+ class AtomDFT:
16
+ """Base class: radial FE-DVR basis, SCF loop and density storage.
17
+
18
+ Subclasses implement ``get_effective_potential``, ``solve_schrodinger`` and
19
+ ``occupied_states``.
20
+ """
21
+
22
+ control: ControlInput
23
+ dft: DFTInput
24
+ element: str | None
25
+ rho_grid: np.ndarray
26
+
27
+ #.......................................................
28
+ def set_basis(self, r_elements: np.ndarray, ng: int) -> None:
29
+ """Set up the FE-DVR basis for the given element boundaries."""
30
+ self.r_elements = r_elements
31
+ ne = len(r_elements) - 1
32
+ self.basis = FEDVR_Basis(ne, ng, r_elements, build_derivatives=True, build_integrals=True)
33
+ self.grid = self.basis.get_gridpoints()
34
+ self.num_grid = len(self.grid)
35
+
36
+ # Quadrature weights for the grid-invariant L2 density norm.
37
+ # Bridge points accumulate contributions from both adjacent elements.
38
+ self.quad_w = np.zeros(ne * ng + 1)
39
+ for ie in range(ne):
40
+ h_e = 0.5 * (self.basis.xp[ie + 1] - self.basis.xp[ie])
41
+ self.quad_w[ie * ng : ie * ng + ng + 1] += h_e * self.basis.leg.w_i
42
+ #.......................................................
43
+ def get_effective_potential(self, rho_grid: np.ndarray | None = None) -> np.ndarray:
44
+ raise NotImplementedError
45
+ #.......................................................
46
+ def solve_schrodinger(self, Veff: np.ndarray, lmax: int, nmax: int) -> tuple[np.ndarray, np.ndarray]:
47
+ raise NotImplementedError
48
+ #.......................................................
49
+ def occupied_states(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
50
+ """Return (radial quantum numbers, angular momenta, occupations) of the occupied states."""
51
+ raise NotImplementedError
52
+ #.......................................................
53
+ def ks_self_consistency(self) -> tuple[int, float]:
54
+ """Iterate the Kohn-Sham equations to self-consistency.
55
+
56
+ Returns the number of iterations and the final density residual.
57
+ """
58
+ nrad, ll, occ = self.occupied_states()
59
+ lmax, nmax = int(np.amax(ll)), int(np.amax(nrad))
60
+ mixer = make_mixer(self.dft.mixing_scheme, self.dft.alpha_mix, self.dft.mixing_history)
61
+
62
+ rho = self.rho_grid.copy()
63
+ _, psi = self.solve_schrodinger(self.get_effective_potential(rho), lmax, nmax)
64
+
65
+ err = np.inf
66
+ iter_count = 0
67
+ while err > self.dft.conv_tol and iter_count < self.dft.max_iter:
68
+ iter_count += 1
69
+ rho_out = density_potential.charge_density(self.basis, nrad, ll, occ, psi)
70
+ err = np.sqrt(np.dot(self.quad_w, (rho_out - rho)**2))
71
+
72
+ rho = mixer.mix(rho, rho_out)
73
+ rho[rho < 0.0] = 0.0
74
+
75
+ _, psi = self.solve_schrodinger(self.get_effective_potential(rho), lmax, nmax)
76
+
77
+ self.rho_grid = rho
78
+ return iter_count, err
79
+ #.......................................................
80
+ def _density_file(self) -> str:
81
+ return os.path.join(self.control.storage_dir, f'{self.element}_density_potential.h5')
82
+ #.......................................................
83
+ def save_density_potential(self) -> None:
84
+ """Save the density and effective potential (if ``control.store_density`` is set)."""
85
+ if not self.control.store_density:
86
+ return
87
+
88
+ os.makedirs(self.control.storage_dir, exist_ok=True)
89
+ with h5py.File(self._density_file(), 'w') as f:
90
+ f.create_dataset('grid', data=self.grid)
91
+ f.create_dataset('rho', data=self.rho_grid)
92
+ f.create_dataset('Veff', data=self.get_effective_potential())
93
+ #.......................................................
94
+ def read_density_potential(self) -> bool:
95
+ """Load a saved density if it exists and was computed on the same grid."""
96
+ filepath = self._density_file()
97
+ if not os.path.isfile(filepath):
98
+ return False
99
+
100
+ with h5py.File(filepath, 'r') as f:
101
+ grid = f['grid'][:]
102
+ rho_grid = f['rho'][:]
103
+
104
+ if len(grid) != self.num_grid or not np.allclose(grid, self.grid):
105
+ return False
106
+
107
+ self.rho_grid = rho_grid.copy()
108
+ return True
@@ -0,0 +1,58 @@
1
+ import numpy as np
2
+ from scipy.integrate import simpson
3
+ from scipy.special import spherical_jn
4
+
5
+ from atomic_femdvr.femdvr import FEDVR_Basis
6
+
7
+
8
+ #=================================================================
9
+ def bessel_integral(basis: FEDVR_Basis, l: int, rpow: int, qgrid: np.ndarray,
10
+ phi: np.ndarray, npoints: int = 41,
11
+ method: str = 'simpson') -> np.ndarray:
12
+ """
13
+ Perform the spherical Bessel transform of the wavefunction.
14
+
15
+ Args:
16
+ basis (FEDVR_Basis): The finite element basis.
17
+ l (int): The angular momentum quantum number.
18
+ rpow (int): The power of the radial coordinate.
19
+ phi (np.ndarray): The wavefunction.
20
+
21
+ Returns:
22
+ np.ndarray: The Bessel-transformed wavefunction.
23
+ """
24
+
25
+ ne = basis.ne
26
+ ng = basis.ng
27
+ xp = basis.xp
28
+ grid = basis.get_gridpoints()
29
+
30
+ phiq = np.zeros_like(qgrid)
31
+
32
+ for i in range(ne):
33
+ # Get the grid points for the current element
34
+ r_elem = grid[i*ng : i*ng + ng + 1]
35
+ phi_elem = phi[i*ng : i*ng + ng + 1]
36
+
37
+ # Convert to Legendre coefficients
38
+ c_elem = basis.leg.to_spectral(phi_elem)
39
+
40
+ if method.lower() == 'simpson':
41
+ # Perform integration using Simpson's rule
42
+ rs = np.linspace(xp[i], xp[i+1], npoints)
43
+ xred = np.linspace(-1, 1, npoints)
44
+ psi_elem_lin = np.polynomial.legendre.legval(xred, c_elem)
45
+ integrand = rs[:, None]**rpow * psi_elem_lin[:, None] * spherical_jn(l, rs[:, None] * qgrid[None, :])
46
+ phiq = phiq + simpson(integrand, dx=rs[1] - rs[0], axis=0)
47
+
48
+ elif method.lower() == 'lobatto':
49
+ # Perform integration using Gauss-Lobatto quadrature
50
+ h = 0.5 * (xp[i+1] - xp[i])
51
+ w_i = basis.leg.w_i * h
52
+ integrand = r_elem[None, :]**rpow * phi_elem[None, :] * spherical_jn(l, r_elem[None, :] * qgrid[:, None])
53
+ phiq = phiq + np.dot(integrand, w_i)
54
+ else:
55
+ raise ValueError(f"Unknown integration method: {method}")
56
+
57
+ return phiq
58
+ #=================================================================
atomic_femdvr/cli.py ADDED
@@ -0,0 +1,96 @@
1
+ """Command line interface for :mod:`atomic_femdvr`."""
2
+
3
+ import json
4
+
5
+ import click
6
+
7
+ from atomic_femdvr.full_atomic import TASKS as AE_TASKS
8
+ from atomic_femdvr.full_atomic import FullAtomicInput, solve_atomic
9
+ from atomic_femdvr.input import PhotoemissionInput
10
+ from atomic_femdvr.pseudo_atomic import TASKS as PSEUDO_TASKS
11
+ from atomic_femdvr.pseudo_atomic import PseudoAtomicInput, solve_pseudo_atomic
12
+ from atomic_femdvr.version import get_version
13
+
14
+ __all__ = [
15
+ "atomic",
16
+ "main",
17
+ "photoemission",
18
+ "pseudoatomic",
19
+ "pseudophotoemission",
20
+ ]
21
+
22
+
23
+ def _read_json(input_file: str) -> dict:
24
+ with open(input_file) as f:
25
+ return json.load(f)
26
+
27
+
28
+ @click.group()
29
+ @click.version_option(version=get_version(), message="atomic_femdvr %(version)s")
30
+ def main() -> None:
31
+ """Kohn-Sham solver for isolated atoms (all-electron and pseudopotential) using FE-DVR."""
32
+
33
+
34
+ @main.command()
35
+ @click.argument("input_file", type=click.Path(exists=True))
36
+ @click.option("-t", "--task", type=str, multiple=True, required=True,
37
+ help=f"Task(s) to run: {', '.join(AE_TASKS)}.")
38
+ @click.option("--plot", is_flag=True, help="Plot the wavefunctions.")
39
+ @click.argument("export_dir", type=click.Path(), required=False)
40
+ def atomic(input_file: str, task: tuple[str, ...], plot: bool, export_dir: str | None) -> None:
41
+ """All-electron calculation defined by INPUT_FILE (JSON)."""
42
+ data = _read_json(input_file)
43
+ data.pop('photoemission', None)
44
+ solve_atomic(FullAtomicInput(**data), task, plot, export_dir)
45
+
46
+
47
+ @main.command()
48
+ @click.argument("input_file", type=click.Path(exists=True))
49
+ @click.option("-t", "--task", type=str, multiple=True, required=True,
50
+ help=f"Task(s) to run, comma-separated or repeated: {', '.join(PSEUDO_TASKS)}.")
51
+ @click.option("--plot", is_flag=True, help="Plot the wavefunctions.")
52
+ @click.argument("export_dir", type=click.Path(), required=False)
53
+ def pseudoatomic(input_file: str, task: tuple[str, ...], plot: bool, export_dir: str | None) -> None:
54
+ """Pseudo-atom calculation defined by INPUT_FILE (JSON) using a UPF pseudopotential.
55
+
56
+ If EXPORT_DIR is given, the orbitals from the 'nscf' task are written there.
57
+ """
58
+ data = _read_json(input_file)
59
+ data.pop('photoemission', None)
60
+ solve_pseudo_atomic(PseudoAtomicInput(**data), task, plot, export_dir)
61
+
62
+
63
+ @main.command()
64
+ @click.argument("input_file", type=click.Path(exists=True))
65
+ def photoemission(input_file: str) -> None:
66
+ """Compute photoemission matrix elements from a completed all-electron SCF calculation.
67
+
68
+ INPUT_FILE is the same JSON as used for 'atomic', with an additional
69
+ 'photoemission' section specifying the energy range and output options.
70
+ The KS potential must already be saved (run 'atomic -t scf' first).
71
+ """
72
+ from atomic_femdvr.photo_atomic import solve_photoemission_atomic
73
+
74
+ data = _read_json(input_file)
75
+ photo_inp = PhotoemissionInput(**data.pop('photoemission', {}))
76
+ solve_photoemission_atomic(FullAtomicInput(**data), photo_inp)
77
+
78
+
79
+ @main.command()
80
+ @click.argument("input_file", type=click.Path(exists=True))
81
+ def pseudophotoemission(input_file: str) -> None:
82
+ """Compute photoemission matrix elements from a completed pseudo-atomic SCF calculation.
83
+
84
+ INPUT_FILE is the same JSON as used for 'pseudoatomic', with an additional
85
+ 'photoemission' section specifying the energy range and output options.
86
+ The KS potential must already be saved (run 'pseudoatomic -t scf' first).
87
+ """
88
+ from atomic_femdvr.photo_pseudo import solve_photoemission_pseudo
89
+
90
+ data = _read_json(input_file)
91
+ photo_inp = PhotoemissionInput(**data.pop('photoemission', {}))
92
+ solve_photoemission_pseudo(PseudoAtomicInput(**data), photo_inp)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
@@ -0,0 +1,63 @@
1
+ import numpy as np
2
+
3
+
4
+ #===================================================================
5
+ def soft_confinement(r: np.ndarray, ri: float, rc: float, bignumber: float = 1.0e10) -> np.ndarray:
6
+ """
7
+ Soft confinement potential for a given radius r, inner radius ri, and outer radius rc.
8
+ """
9
+ Vc = np.zeros_like(r)
10
+
11
+ Ir, = np.where(r < ri)
12
+ if len(Ir) > 0:
13
+ Vc[Ir] = 0.0
14
+ Ir, = np.where(r >= rc)
15
+ if len(Ir) > 0:
16
+ Vc[Ir] = bignumber
17
+
18
+ Ir, = np.where((r >= ri) & (r < rc))
19
+ if len(Ir) > 0:
20
+ Vc[Ir] = np.exp(-(rc - ri) / (r[Ir] - ri)) / (rc - r[Ir])
21
+
22
+ return Vc
23
+ #===================================================================
24
+ def parabolic_confinement(r: np.ndarray, ri: float, rc: float, bignumber: float = 1.0e3) -> np.ndarray:
25
+ """
26
+ Parabolic confinement potential for a given radius r, inner radius ri, and outer radius rc.
27
+ """
28
+ Vc = np.zeros_like(r)
29
+
30
+ Ir, = np.where(r < ri)
31
+ if len(Ir) > 0:
32
+ Vc[Ir] = 0.0
33
+ Ir, = np.where(r >= rc)
34
+ if len(Ir) > 0:
35
+ Vc[Ir] = bignumber
36
+
37
+ Ir, = np.where((r >= ri) & (r < rc))
38
+ if len(Ir) > 0:
39
+ Vc[Ir] = (r[Ir] - ri)**2 / (rc - ri)**2
40
+
41
+ return Vc
42
+ #===================================================================
43
+ def soft_step(r: np.ndarray, ri: float, rc: float, Vbarrier: float = 1.0e1) -> np.ndarray:
44
+ """
45
+ Soft step potential for a given radius r, inner radius ri, and outer radius rc.
46
+ """
47
+ Vc = np.zeros_like(r)
48
+
49
+ Ir, = np.where(r < ri)
50
+ if len(Ir) > 0:
51
+ Vc[Ir] = 0.0
52
+ Ir, = np.where(r >= rc)
53
+ if len(Ir) > 0:
54
+ Vc[Ir] = Vbarrier
55
+
56
+ Ir, = np.where((r >= ri) & (r < rc))
57
+ if len(Ir) > 0:
58
+ Vc[Ir] = Vbarrier * np.sin(0.5*np.pi * (r[Ir] - ri) / (rc - ri))**2
59
+
60
+ return Vc
61
+ #===================================================================
62
+ def soft_coulomb_potential(r: np.ndarray, Q: float, delta: float, lam: float = 0.0) -> np.ndarray:
63
+ return -Q / np.sqrt(r**2 + delta**2) * np.exp(-lam * r)
@@ -0,0 +1,153 @@
1
+ import numpy as np
2
+
3
+ from atomic_femdvr.femdvr import FEDVR_Basis
4
+ from atomic_femdvr.xc_functionals import gga_functional
5
+
6
+
7
+ #===================================================================
8
+ def charge_density(basis:FEDVR_Basis, nnodes_chi:np.ndarray, lchi:np.ndarray,
9
+ occ:np.ndarray, psi:np.ndarray) -> np.ndarray:
10
+ """Computes the charge density from given wave-functions"""
11
+ nwf = len(occ)
12
+
13
+ grid = basis.get_gridpoints()
14
+ rho = np.zeros_like(grid)
15
+
16
+ # get derivative at r=0
17
+ h = 0.5 * (basis.xp[1] - basis.xp[0])
18
+ psi_elem = psi[:, :, :basis.ng + 1]
19
+ dpsi_dr_elem = np.einsum('ij,lnj->lni', basis.leg.D_ii, psi_elem) / h
20
+
21
+ for iwf in range(nwf):
22
+ l = lchi[iwf]
23
+ n = nnodes_chi[iwf]
24
+ rho[1:] += occ[iwf] * np.abs(psi[l, n, 1:])**2 / grid[1:]**2
25
+ rho[0] += occ[iwf] * dpsi_dr_elem[l, n, 0]**2
26
+
27
+ return rho
28
+ #===================================================================
29
+
30
+ #===================================================================
31
+ def hartree_potential(basis:FEDVR_Basis, rho:np.ndarray) -> np.ndarray:
32
+
33
+ ne = basis.ne
34
+ ng = basis.ng
35
+ grid = basis.get_gridpoints()
36
+
37
+ A_integ = np.zeros_like(grid)
38
+ B_integ = np.zeros_like(grid)
39
+
40
+ A_tot_integ = 0.
41
+ B_tot_integ = 0.
42
+
43
+ for i in range(ne):
44
+ rho_elem = rho[i*ng : i*ng + ng + 1]
45
+ r_elem = grid[i*ng : i*ng + ng + 1]
46
+
47
+ A_integrand = rho_elem * r_elem
48
+ B_integrand = rho_elem * r_elem**2
49
+ A_elem_integ = np.dot(basis.leg_integ[i, :, :], A_integrand)
50
+ B_elem_integ = np.dot(basis.leg_integ[i, :, :], B_integrand)
51
+
52
+ A_integ[i*ng : i*ng + ng + 1] = A_elem_integ + A_tot_integ
53
+ B_integ[i*ng : i*ng + ng + 1] = B_elem_integ + B_tot_integ
54
+
55
+ A_tot_integ += A_elem_integ[-1]
56
+ B_tot_integ += B_elem_integ[-1]
57
+
58
+ V_Ha = np.zeros_like(grid)
59
+ V_Ha[1:] = A_integ[-1] - A_integ[1:] + B_integ[1:] / grid[1:]
60
+ V_Ha[0] = A_integ[-1] - A_integ[0]
61
+
62
+ return V_Ha
63
+ #===================================================================
64
+ def exchange_correlation_potential(basis:FEDVR_Basis, rho:np.ndarray,
65
+ rho_nlcc:np.ndarray | None=None,
66
+ xc_functional:str='', x_functional:str='gga_x_pbe',
67
+ c_functional:str='gga_c_pbe',
68
+ alpha_x:float=1.0, driver='internal') -> np.ndarray:
69
+ """Computes the exchange-correlation potential using libxc"""
70
+ grid = basis.get_gridpoints()
71
+ ne = basis.ne
72
+ ng = basis.ng
73
+
74
+ # Our rho is in the radial convention: ∫ rho r² dr = N.
75
+ # The 3D density is n = rho / (4π).
76
+ # rho_nlcc from UPF is already the 3D core density (electrons/Bohr³),
77
+ # so it must be added AFTER dividing rho by 4π, not before.
78
+ rho_ = rho.copy() / (4.0 * np.pi)
79
+ if rho_nlcc is not None and len(rho_nlcc) == len(rho):
80
+ rho_ += rho_nlcc.copy()
81
+
82
+ drho_dr = np.zeros_like(rho_)
83
+ for i in range(ne):
84
+ h = 0.5 * (basis.xp[i+1] - basis.xp[i])
85
+ rho_elem = rho_[i*ng : i*ng + ng + 1]
86
+ drho_dr_elem = np.dot(basis.leg.D_ii, rho_elem) / h
87
+ drho_dr[i*ng : i*ng + ng + 1] = drho_dr_elem
88
+
89
+
90
+ sigma = drho_dr**2
91
+
92
+ if driver == 'internal':
93
+ available_functionals = ['PBE', 'PBE0', 'B3LYP']
94
+
95
+ if xc_functional not in available_functionals:
96
+ raise ValueError(f"Unsupported exchange-correlation functional: {xc_functional}. "
97
+ f"Available functionals: {available_functionals}")
98
+
99
+ _, xc_data = gga_functional(xc_functional, rho_, drho_dr, alpha_x)
100
+ V_xc_grid = xc_data[0]
101
+ vsigma = xc_data[1]
102
+
103
+ elif driver == 'pylibxc':
104
+ try:
105
+ import pylibxc
106
+ except ImportError as err:
107
+ raise ImportError("The 'pylibxc' driver requires the libxc Python bindings "
108
+ "(see https://libxc.gitlab.io/installation/).") from err
109
+
110
+ rho_libxc = np.reshape(rho_, [len(rho_), 1])
111
+ sigma_libxc = np.reshape(sigma, [len(sigma), 1])
112
+ input_data = {"rho": rho_libxc, "sigma": sigma_libxc}
113
+
114
+ if len(xc_functional) > 0:
115
+ xc_func = pylibxc.LibXCFunctional(xc_functional.lower(), "unpolarized")
116
+ output = xc_func.compute(input_data)
117
+ V_xc_grid = output["vrho"].reshape(-1)
118
+ vsigma = output.get("vsigma", np.zeros_like(V_xc_grid)).reshape(-1)
119
+ else:
120
+ x_func = pylibxc.LibXCFunctional(x_functional.lower(), "unpolarized")
121
+ output_x = x_func.compute(input_data)
122
+ V_x = output_x["vrho"].reshape(-1)
123
+ vsigma_x = output_x.get("vsigma", np.zeros_like(V_x)).reshape(-1)
124
+
125
+ c_func = pylibxc.LibXCFunctional(c_functional.lower(), "unpolarized")
126
+ output_c = c_func.compute(input_data)
127
+ V_c = np.array(output_c["vrho"]).flatten()
128
+ vsigma_c = np.array(output_c.get("vsigma", np.zeros_like(V_c))).flatten()
129
+
130
+ V_xc_grid = alpha_x * V_x + V_c
131
+ vsigma = alpha_x * vsigma_x + vsigma_c
132
+
133
+ else:
134
+ raise ValueError(f"Unsupported driver: {driver}. Available drivers: 'internal', 'pylibxc'.")
135
+
136
+ # GGA sigma correction: V_xc += -(2/r²) d/dr(r² vsigma dn/dr)
137
+ # Both drivers return vsigma = ∂e_xc/∂σ (σ = |∇n|²); the divergence term
138
+ # is not included in vrho and must be applied here. f = r² vsigma dn/dr
139
+ # absorbs the 1/r² to keep the boundary at r=0 well-behaved.
140
+ if np.any(vsigma != 0.0):
141
+ f = np.zeros(len(grid))
142
+ f[1:] = grid[1:]**2 * vsigma[1:] * drho_dr[1:]
143
+ df_dr = np.zeros_like(f)
144
+ for i in range(ne):
145
+ h = 0.5 * (basis.xp[i+1] - basis.xp[i])
146
+ f_elem = f[i*ng : i*ng + ng + 1]
147
+ df_dr_elem = np.dot(basis.leg.D_ii, f_elem) / h
148
+ df_dr[i*ng : i*ng + ng + 1] = df_dr_elem
149
+ V_xc_grid[1:] -= 2.0 * df_dr[1:] / grid[1:]**2
150
+ V_xc_grid[0] = V_xc_grid[1]
151
+
152
+ return V_xc_grid
153
+ #===================================================================