diff --git a/README.md b/README.md
index 4a51609..4378bce 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,10 @@ Every new feature is checked against exact or independent results; see [Validati
### New since v1.2 (unreleased)
+- **Conjugate-gradient ground states** (`ground_state_pcg`):
+ - preconditioned nonlinear conjugate gradient on the sphere ‖ψ‖² = N, with an exact fixed point (no dτ error);
+ - converges on soft modes such as vortex lattices where imaginary time stalls;
+ - `ground_state` also accepts a decreasing dτ schedule.
- **Two-component condensates** (`CoupledGPESolver`, `coupled_ground_state`):
- coupled Gross–Pitaevskii equations, with rotation, damping and GPU support;
- miscibility, spinodal phase separation, and interlaced two-colour vortex lattices.
@@ -279,7 +283,7 @@ A condensate at rest is placed in a slightly anisotropic trap rotating at Ω = 0
@@ -287,8 +291,10 @@ The 2D lattice then seeds a 3D condensate in a cigar-shaped rotating trap (128
**Validation:**
- Feynman's rule for a rigidly rotating superfluid, n_v = mΩ/(πℏ), predicts a triangular-lattice spacing of 2.129.
-- The measured mean nearest-neighbour spacing is 2.034 ± 0.065 in 2D (−4.5%) and 2.044 ± 0.069 in the z = 0 plane of the 3D state (−4.0%).
-- Feynman's rule is exact for an infinite uniform lattice. This one has only 18 vortices in an inhomogeneous cloud, so deviations of a few percent are expected.
+- The measured mean nearest-neighbour spacing is 2.034 ± 0.065 in 2D (−4.5%) and 2.072 ± 0.059 in the z = 0 plane of the 3D state (−2.7%).
+- Feynman's rule is exact for an infinite uniform lattice. This one has only 18–19 vortices in an inhomogeneous cloud, so deviations of a few percent are expected.
+- All 19 lines can be followed slice by slice through the central region |z| ≤ 0.6Z. The inner lines stay in the same grid cell, and the outer ring bends outwards by at most 0.35 (about two grid spacings).
+- The minimiser lowers the energy at every step, so it ends in a local energy minimum, not necessarily the global one. A run from a different seed converged to an 18-line lattice whose energy is 3 × 10⁻⁵ (relative) higher.
- The rotating-frame solver itself is checked exactly in the validation suite.

@@ -364,7 +370,7 @@ Two condensates with intra-species couplings g₁₁ = g₂₂ = g and inter-spe
| Energy conservation, 3D, 500 steps (order 4) | E(t) = E(0) | 2.18e-10 |
| Minimum-uncertainty Gaussian (3D) | Δr_j Δp_j = ℏ/2 for each axis | 4.60e-12 |
| Angular momentum of a vortex state | ⟨L_z⟩ = ℏ for ψ ∝ (x+iy)e^{−r²/2} | 2.22e-16 |
-| Harmonic spectrum 1D, 10 levels (Lanczos) | E_n = n + ½ | 5.24e-14 |
+| Harmonic spectrum 1D, 10 levels (Lanczos) | E_n = n + ½ | 7.28e-14 |
| Anisotropic 3D harmonic spectrum, 6 levels (LOBPCG) | E = Σ ω_j (n_j + ½) | 1.42e-13 |
| 3D ground state by imaginary time | E₀ = ½(ω_x+ω_y+ω_z) | 6.95e-10 |
| Spectrum from autocorrelation (Feit–Fleck) | peaks of FFT[C(t)] at n + ½ | 1.62e-03 |
@@ -373,7 +379,7 @@ Two condensates with intra-species couplings g₁₁ = g₂₂ = g and inter-spe
| Imaginary-time GP ground state accuracy | residual ∝ dτ² (ratio 4 when halving dτ) | 2.23e-03 |
| Coherent state in a frame rotating at Ω = 0.6 | ⟨r'⟩ = R(−Ωt)·(x₀ cos ωt, 0) | 1.89e-08 |
| Vortex eigenstate in the rotating frame | C(t) = e^{−i(2ℏω − Ωℏ)t/ℏ} | 1.15e-08 |
-| 1D soft-core hydrogen ground state | E₀ = −½ a.u. (I_p = 13.6 eV) | 1.61e-14 |
+| 1D soft-core hydrogen ground state | E₀ = −½ a.u. (I_p = 13.6 eV) | 1.94e-14 |
| Three-step model maximum return energy | max E_return = 3.17 U_p | 3.63e-05 |
| HHG: only odd harmonics (800 nm, 10¹⁴ W/cm²) | inversion symmetry forbids even orders | 4.30e-04 |
| Attosecond pulse train (H11–H21) | one burst per half laser cycle | 3.08e-03 |
@@ -381,8 +387,10 @@ Two condensates with intra-species couplings g₁₁ = g₂₂ = g and inter-spe
| Phase-separation instability, g₁₂ = 1.3 g | growth rate γ = √(ε_k(2n(g₁₂ − g) − ε_k)) | 9.39e-05 |
| Manakov point g₁₁ = g₂₂ = g₁₂ | n₁ + n₂ equals the one-component GP ground state | 1.76e-07 |
| Virial theorem, coupled GP ground state | 2⟨T⟩ − 2⟨V⟩ + 2E_int = 0 (2D) | 2.27e-06 |
+| Conjugate-gradient minimiser, hydrogen (V < 0) | E₀ = −½ a.u. | 7.77e-16 |
+| Virial theorem, 3D GP ground state (conjugate gradient) | 2⟨T⟩ − 2⟨V⟩ + 3E_int = 0, no dτ error | 5.79e-10 |
-All 25 checks pass. A few rows report something other than a plain error:
+All 27 checks pass. A few rows report something other than a plain error:
- The two convergence rows give the deviation of the observed order (2.001 and 3.997) from the theoretical one.
- The Feit–Fleck row is limited by the spectral resolution 2π/T ≈ 0.031.
- The GP ground-state accuracy row gives the relative deviation of the observed residual ratio (3.99) from 4.
@@ -507,6 +515,7 @@ Test coverage includes:
- `test_rotation.py` — rotating-frame coherent state, vortex eigenstate, E − ΩL_z conservation, damping, vortex lattice energy
- `test_strongfield.py` — laser units, three-step 3.17 U_p, hydrogen ground state, spectra, Gabor maps, attosecond pulses, Ehrenfest acceleration
- `test_multicomponent.py` — uncoupled limit, Manakov point, Bogoliubov spin mode and phase-separation growth rate, energy and population conservation, coupled virial theorem
+- `test_conjugate_gradient.py` — exact linear ground states (including V < 0 and ℏ, m ≠ 1), GP virial theorem without a dτ floor, rotating vortex lattice below imaginary time
- `test_backends.py` — GPU code path against NumPy through a strict emulated device; a real CuPy comparison runs where a CUDA device exists
---
diff --git a/benchmarks/validation_report.md b/benchmarks/validation_report.md
index 49cb5f6..15e41e8 100644
--- a/benchmarks/validation_report.md
+++ b/benchmarks/validation_report.md
@@ -3,7 +3,7 @@
Generated by `python benchmarks/validation_suite.py`. Every row compares a
simulation with an exact, analytic or independent numerical reference.
Platform: Python 3.14.6, NumPy 2.4.6, arm64.
-Total runtime: 65 s.
+Total runtime: 73 s.
| Category | Check | Reference | Metric | Error | Tolerance | Result |
|---|---|---|---|---|---|---|
@@ -15,7 +15,7 @@ Total runtime: 65 s.
| Dynamics | Energy conservation, 3D, 500 steps (order 4) | E(t) = E(0) | \|ΔE/E\| | 2.18e-10 | 1e-08 | pass |
| Observables | Minimum-uncertainty Gaussian (3D) | Δr_j Δp_j = ℏ/2 for each axis | max \|Δr Δp − ½\| | 4.60e-12 | 1e-08 | pass |
| Observables | Angular momentum of a vortex state | ⟨L_z⟩ = ℏ for ψ ∝ (x+iy)e^{−r²/2} | \|⟨L_z⟩ − 1\| | 2.22e-16 | 1e-10 | pass |
-| Stationary states | Harmonic spectrum 1D, 10 levels (Lanczos) | E_n = n + ½ | max \|E_n − exact\| | 5.24e-14 | 1e-10 | pass |
+| Stationary states | Harmonic spectrum 1D, 10 levels (Lanczos) | E_n = n + ½ | max \|E_n − exact\| | 7.28e-14 | 1e-10 | pass |
| Stationary states | Anisotropic 3D harmonic spectrum, 6 levels (LOBPCG) | E = Σ ω_j (n_j + ½) | max \|E − exact\| | 1.42e-13 | 1e-08 | pass |
| Stationary states | 3D ground state by imaginary time | E₀ = ½(ω_x+ω_y+ω_z) | \|E₀ − exact\| | 6.95e-10 | 1e-07 | pass |
| Stationary states | Spectrum from autocorrelation (Feit–Fleck) | peaks of FFT[C(t)] at n + ½ | max peak offset (resolution 2π/T = 0.031) | 1.62e-03 | 3e-03 | pass |
@@ -24,7 +24,7 @@ Total runtime: 65 s.
| Gross–Pitaevskii | Imaginary-time GP ground state accuracy | residual ∝ dτ² (ratio 4 when halving dτ) | observed ratio 3.99 | 2.23e-03 | 1e-01 | pass |
| Rotating frame | Coherent state in a frame rotating at Ω = 0.6 | ⟨r'⟩ = R(−Ωt)·(x₀ cos ωt, 0) | max \|⟨r'⟩ − exact\| | 1.89e-08 | 1e-07 | pass |
| Rotating frame | Vortex eigenstate in the rotating frame | C(t) = e^{−i(2ℏω − Ωℏ)t/ℏ} | \|C(t) − exact\| | 1.15e-08 | 1e-07 | pass |
-| Strong-field physics | 1D soft-core hydrogen ground state | E₀ = −½ a.u. (I_p = 13.6 eV) | \|E₀ + ½\| | 1.61e-14 | 1e-09 | pass |
+| Strong-field physics | 1D soft-core hydrogen ground state | E₀ = −½ a.u. (I_p = 13.6 eV) | \|E₀ + ½\| | 1.94e-14 | 1e-09 | pass |
| Strong-field physics | Three-step model maximum return energy | max E_return = 3.17 U_p | \|max/U_p − 3.1731\| | 3.63e-05 | 2e-04 | pass |
| Strong-field physics | HHG: only odd harmonics (800 nm, 10¹⁴ W/cm²) | inversion symmetry forbids even orders | even/odd intensity, H5–H20 (odd/even = 2.3e+03) | 4.30e-04 | 1e-02 | pass |
| Strong-field physics | Attosecond pulse train (H11–H21) | one burst per half laser cycle | max \|spacing − ½\| (cycles) | 3.08e-03 | 1e-02 | pass |
@@ -32,5 +32,7 @@ Total runtime: 65 s.
| Two-component BEC | Phase-separation instability, g₁₂ = 1.3 g | growth rate γ = √(ε_k(2n(g₁₂ − g) − ε_k)) | \|γ_measured/γ − 1\| | 9.39e-05 | 1e-03 | pass |
| Two-component BEC | Manakov point g₁₁ = g₂₂ = g₁₂ | n₁ + n₂ equals the one-component GP ground state | max \|n₁ + n₂ − n\| | 1.76e-07 | 1e-06 | pass |
| Two-component BEC | Virial theorem, coupled GP ground state | 2⟨T⟩ − 2⟨V⟩ + 2E_int = 0 (2D) | \|2T − 2V + 2E_int\| / V | 2.27e-06 | 1e-04 | pass |
+| Stationary states | Conjugate-gradient minimiser, hydrogen (V < 0) | E₀ = −½ a.u. | \|E₀ + ½\| | 7.77e-16 | 1e-12 | pass |
+| Gross–Pitaevskii | Virial theorem, 3D GP ground state (conjugate gradient) | 2⟨T⟩ − 2⟨V⟩ + 3E_int = 0, no dτ error | \|2T − 2V + 3E_int\| / V | 5.79e-10 | 1e-08 | pass |
-**25/25 checks passed.**
+**27/27 checks passed.**
diff --git a/benchmarks/validation_suite.py b/benchmarks/validation_suite.py
index 5fdb5a3..87496f8 100644
--- a/benchmarks/validation_suite.py
+++ b/benchmarks/validation_suite.py
@@ -307,6 +307,19 @@ def spin(states, k):
'|2T − 2V + 2E_int| / V', abs(2 * T - 2 * V + 2 * E_int) / V, 1e-4)
+def energy_minimiser():
+ from quantumlab.stationary import ground_state_pcg
+ _, info = ground_state_pcg(Grid1D(2048, -100.0, 100.0), SoftCoulomb(), tol=1e-10)
+ check('Stationary states', 'Conjugate-gradient minimiser, hydrogen (V < 0)', 'E₀ = −½ a.u.',
+ '|E₀ + ½|', abs(info.energy + 0.5), 1e-12)
+ grid = Grid3D(48, -8.0, 8.0, 48, -8.0, 8.0, 48, -8.0, 8.0)
+ trap, g = HarmonicTrap((1.0, 1.2, 1.4)), 60.0
+ wf, info = ground_state_pcg(grid, trap, nonlinearity=g, tol=1e-9)
+ T, V, Ei = kinetic_energy_expectation(wf), potential_energy_expectation(wf, trap), interaction_energy(wf, g)
+ check('Gross–Pitaevskii', 'Virial theorem, 3D GP ground state (conjugate gradient)',
+ '2⟨T⟩ − 2⟨V⟩ + 3E_int = 0, no dτ error', '|2T − 2V + 3E_int| / V', abs(2 * T - 2 * V + 3 * Ei) / V, 1e-8)
+
+
def write_report(path, elapsed):
lines = [
'# QuantumLab validation report',
@@ -336,7 +349,7 @@ def main():
t0 = time.time()
for fn in (free_spreading, convergence_orders, driven_oscillator, norm_energy_3d, heisenberg_3d,
vortex_lz, harmonic_spectra, feit_fleck, bright_soliton, gp_virial, gp_dtau_order,
- rotating_frame, high_harmonics, two_component):
+ rotating_frame, high_harmonics, two_component, energy_minimiser):
print(f'{fn.__name__}:')
fn()
out = Path(__file__).with_name('validation_report.md')
diff --git a/docs/api/stationary.md b/docs/api/stationary.md
index 714317a..3a10a76 100644
--- a/docs/api/stationary.md
+++ b/docs/api/stationary.md
@@ -6,4 +6,6 @@ Generated from the docstrings in the source code.
::: quantumlab.stationary.imaginary_time
+::: quantumlab.stationary.conjugate_gradient
+
::: quantumlab.stationary.hamiltonian
diff --git a/docs/examples.md b/docs/examples.md
index 4e64d53..1026f9d 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -67,7 +67,7 @@ The first 60 eigenstates of a chaotic billiard computed with LOBPCG. LOBPCG and
## 11. Vortex lattice in a rotating BEC
-A condensate in a rotating, slightly anisotropic trap develops surface instabilities. Vortices then enter and crystallise into a triangular lattice of 18 vortices (dissipative GPE, following Tsubota, Kasamatsu & Ueda 2002). The mean lattice spacing is within 4.5% of Feynman's rule n_v = mΩ/πℏ, which is exact only for an infinite uniform lattice. The 3D version shows the vortex lines.
+A condensate in a rotating, slightly anisotropic trap develops surface instabilities. Vortices then enter and crystallise into a triangular lattice of 18 vortices (dissipative GPE, following Tsubota, Kasamatsu & Ueda 2002). The mean lattice spacing is within 4.5% (2D) and 2.7% (3D) of Feynman's rule n_v = mΩ/πℏ, which is exact only for an infinite uniform lattice. The 3D state is found by conjugate-gradient energy minimisation (residual below 10⁻⁶) and shows 19 nearly straight vortex lines.


diff --git a/docs/guide/stationary.md b/docs/guide/stationary.md
index f402af9..95478de 100644
--- a/docs/guide/stationary.md
+++ b/docs/guide/stationary.md
@@ -31,6 +31,27 @@ print(info.converged, info.energy, info.chemical_potential, info.residual)
- A good initial guess helps. For BECs, a Thomas–Fermi profile is a good choice.
- `excited_states` finds the lowest states one by one with Gram–Schmidt projection (linear problems only).
+### Continuation in dτ
+
+`dtau` can also be a decreasing sequence, e.g. `dtau=[0.04, 0.01, 0.0025]`. The large steps relax slow modes in few iterations, and the small ones lower the O(dτ²) error floor. `max_steps` and `tol` apply per stage.
+
+## Conjugate-gradient energy minimisation
+
+[`ground_state_pcg`](../api/stationary.md) minimises the (Gross–Pitaevskii) energy directly on the sphere ‖ψ‖² = N with a preconditioned nonlinear conjugate-gradient method (Antoine, Levitt & Tang, *J. Comput. Phys.* **343**, 92 (2017)):
+
+```python
+from quantumlab.stationary import ground_state_pcg
+
+wf, info = ground_state_pcg(grid, trap, initial=guess, nonlinearity=500.0, rotation=0.8, tol=1e-8)
+print(info.converged, info.steps, info.residual)
+```
+
+Use it when imaginary time is too slow or not accurate enough:
+- **Exact fixed point.** There is no dτ, so the residual ‖Hψ − μψ‖ can be driven to ~10⁻¹⁰. In the validation suite the 3D Gross–Pitaevskii virial theorem holds to 10⁻⁹, against 10⁻⁵–10⁻⁶ from imaginary time.
+- **Soft modes.** Vortex lattices and elongated condensates have modes with tiny energy gaps. Imaginary time relaxes them as e^{−Δτ}, while conjugate directions converge on them much faster. In [example 11](../examples.md#11-vortex-lattice-in-a-rotating-bec) a 3D vortex lattice on a 128 × 128 × 64 grid reaches a residual below 10⁻⁶ in about 9300 iterations; imaginary time stalled near 3 × 10⁻³.
+
+The preconditioner combines the kinetic operator (in Fourier space) and the potential plus mean field (in real space), so it works with both stiff kinetic and stiff potential terms, including attractive potentials such as `SoftCoulomb`. Near convergence the line search switches from energy values to directional derivatives, which stay resolvable below residuals of 10⁻⁷.
+
### Rotating frames and vortex states
-`ground_state(..., rotation=Ω)` works in the rotating frame, and energies and μ refer to H − ΩL_z. Above the critical rotation the ground state contains vortices. Imaginary time reaches it only from a guess that breaks rotational symmetry, for example an imprinted vortex or a lattice obtained from damped real-time dynamics, as in [example 11](../examples.md#11-vortex-lattice-in-a-rotating-bec).
+`ground_state(..., rotation=Ω)` works in the rotating frame, and energies and μ refer to H − ΩL_z. Above the critical rotation the ground state contains vortices. Imaginary time (or the conjugate-gradient minimiser) reaches it only from a guess that breaks rotational symmetry, for example an imprinted vortex or a lattice obtained from damped real-time dynamics, as in [example 11](../examples.md#11-vortex-lattice-in-a-rotating-bec).
diff --git a/examples/11_rotating_bec_vortex_lattice.py b/examples/11_rotating_bec_vortex_lattice.py
index 15d6f65..01e66c5 100644
--- a/examples/11_rotating_bec_vortex_lattice.py
+++ b/examples/11_rotating_bec_vortex_lattice.py
@@ -9,15 +9,21 @@
vortices enter from the edge and crystallise into a triangular lattice.
Part 2 — vortex lines (3D). The 2D lattice seeds a 3D condensate in a
-cigar-shaped rotating trap. Imaginary-time relaxation in the rotating frame
-(a fixed number of steps; its residual is printed) gives a state whose vortex
-lines run along z; they are drawn as tubes inside the translucent cloud.
+cigar-shaped rotating trap with the same radial anisotropy as in part 1.
+Vortex lattices have very soft modes (relaxation rates ~0.01 ω): imaginary
+time stalls on them and its fixed point also carries an O(dτ²) error. So a
+short imaginary-time run only smooths the seed, and the stationary state is
+then found by preconditioned conjugate-gradient energy minimisation
+(``ground_state_pcg``), whose fixed point is exact. The residual
+‖(H − ΩL_z)ψ − μψ‖ is printed; the vortex lines run along z and are drawn as
+tubes inside the translucent cloud. This part takes ~30–40 minutes on a CPU.
Check: a rigidly rotating superfluid has the areal vortex density
n_v = mΩ/(πℏ) (Feynman's rule), i.e. a triangular lattice with spacing
a = (2/(√3 n_v))^½. The rule is exact for an infinite uniform lattice; this
lattice has fewer than 20 vortices in an inhomogeneous cloud, so deviations
-of a few percent are expected. The measured spacing is printed.
+of a few percent are expected. The measured spacing is printed, and each
+line is followed slice by slice along z to measure how straight it is.
Outputs (in output/):
11_vortex_lattice_formation.mp4 density and phase during formation (2D)
@@ -36,7 +42,7 @@
from quantumlab.core.grid import Grid2D, Grid3D
from quantumlab.core.wavefunction import WaveFunction2D, WaveFunction3D
from quantumlab.potentials import HarmonicTrap
-from quantumlab.stationary import ground_state
+from quantumlab.stationary import ground_state, ground_state_pcg
from quantumlab.solvers.split_operator import SplitOperatorSolver
from quantumlab.observables import angular_momentum_z_expectation, vortex_positions
from quantumlab.visualization.volume_3d import IsosurfaceAnimation, IsosurfaceRenderer
@@ -148,20 +154,50 @@ def main():
grid3 = Grid3D(128, -10.0, 10.0, 128, -10.0, 10.0, 64, -(Z + 3.0), Z + 3.0)
trap3 = HarmonicTrap((np.sqrt(1.0 + eps_x), np.sqrt(1.0 + eps_y), omega_z))
profile_z = np.sqrt(np.clip(1.0 - grid3.z ** 2 / Z ** 2, 0.0, None))
- guess = wf.psi[:, :, None] * profile_z[None, None, :]
- print(f'\n[2] 3D: cigar trap ω = (1.015, 1.044, {omega_z}), g = {g3:.0f}, '
- f'grid {grid3.N_x}×{grid3.N_y}×{grid3.N_z}; imaginary time in the rotating frame')
- wf3, info3 = ground_state(grid3, trap3, dtau=0.005, nonlinearity=g3, rotation=Om, initial=guess,
- tol=1e-9, max_steps=3000, check_interval=50)
- print(f' steps = {info3.steps}, energy converged to 1e-9 = {info3.converged}, '
- f'μ = {info3.chemical_potential:.4f}, residual ‖(H−ΩL_z)ψ − μψ‖ = {info3.residual:.1e}')
-
+ wf3 = WaveFunction3D(grid3, wf.psi[:, :, None] * profile_z[None, None, :])
+ wf3.normalize()
+ print(f'\n[2] 3D: cigar trap ω = (1.015, 1.044, {omega_z}), g = {g3:.0f}, grid {grid3.N_x}×{grid3.N_y}×{grid3.N_z}; '
+ f'stationary state in the rotating frame')
+ # A short imaginary-time run smooths the extruded 2D seed; the energy minimiser does the rest
+ wf3, info_it = ground_state(grid3, trap3, dtau=0.02, nonlinearity=g3, rotation=Om, initial=wf3,
+ tol=0.0, max_steps=1000, check_interval=500)
+ print(f' imaginary time (dτ = 0.02, {info_it.steps} steps): residual {info_it.residual:.2e}')
+
+ def progress(it, residual, energy):
+ print(f' conjugate gradient {it:5d}: residual {residual:.2e}, E = {energy:.10f}', flush=True)
+
+ wf3, info3 = ground_state_pcg(grid3, trap3, initial=wf3, nonlinearity=g3, rotation=Om, tol=1e-6,
+ max_iter=15000, callback=progress, callback_interval=500)
+ print(f' converged = {info3.converged} after {info3.steps} iterations: E = {info3.energy:.10f}, '
+ f'μ = {info3.chemical_potential:.10f}, residual ‖(H−ΩL_z)ψ − μψ‖ = {info3.residual:.2e}')
k0 = int(np.argmin(np.abs(grid3.z)))
mid = WaveFunction2D(Grid2D(grid3.N_x, -10.0, 10.0, grid3.N_y, -10.0, 10.0), wf3.psi[:, :, k0])
pos3, q3 = vortex_positions(mid)
a3, a3_std = lattice_spacing(pos3)
print(f' vortex lines crossing z = 0: {len(pos3)}; spacing {a3:.3f} ± {a3_std:.3f} '
f'(Feynman {a_feynman:.3f}, {100 * (a3 / a_feynman - 1):+.1f}%)')
+ # Straightness: follow each line slice by slice from z = 0 out to |z| = 0.6 Z. A line is
+ # lost where no vortex lies within half a lattice spacing of its last position, i.e. it
+ # has left the region where vortices are detected (density above 20% of the slice maximum).
+ shift, followed, outward = np.zeros(len(pos3)), np.ones(len(pos3), dtype=bool), np.ones(len(pos3), dtype=bool)
+ for step in (1, -1):
+ current, alive, k = pos3.copy(), np.ones(len(pos3), dtype=bool), k0
+ while abs(grid3.z[k + step]) <= 0.6 * Z:
+ k += step
+ p, _ = vortex_positions(WaveFunction2D(mid.grid, wf3.psi[:, :, k]))
+ d, j = cKDTree(p).query(current)
+ alive &= d < 0.5 * a3
+ current[alive] = p[j[alive]]
+ shift[alive] = np.maximum(shift[alive], np.hypot(*(current[alive] - pos3[alive]).T))
+ followed &= alive
+ outward &= np.sum((current - pos3) * pos3, axis=1) >= 0.0 # moved away from the axis
+ radius = np.hypot(pos3[:, 0], pos3[:, 1])
+ inner = radius < 0.7 * radius.max()
+ print(f' {followed.sum()} of {len(pos3)} lines followed through every slice with |z| ≤ 0.6 Z; largest '
+ f'lateral shift from the z = 0 position: inner lines {shift[inner].max():.2f}, outer ring '
+ f'{shift[~inner].max():.2f}{" (outwards)" if outward.all() else ""} (grid spacing {grid3.dx:.3f})')
+ if not followed.all():
+ print(f' {(~followed).sum()} outermost line(s) leave the dense part of the cloud before |z| = 0.6 Z')
rho = wf3.probability_density
envelope = gaussian_filter(rho, sigma=(1.0 / grid3.dx, 1.0 / grid3.dy, 0.0))
diff --git a/images/11_vortex_lines_3d.gif b/images/11_vortex_lines_3d.gif
index 127c5b4..2d4284a 100644
Binary files a/images/11_vortex_lines_3d.gif and b/images/11_vortex_lines_3d.gif differ
diff --git a/images/11_vortex_lines_3d.png b/images/11_vortex_lines_3d.png
index 0831853..caa6a24 100644
Binary files a/images/11_vortex_lines_3d.png and b/images/11_vortex_lines_3d.png differ
diff --git a/quantumlab/stationary/__init__.py b/quantumlab/stationary/__init__.py
index fc46cb8..0f72d76 100644
--- a/quantumlab/stationary/__init__.py
+++ b/quantumlab/stationary/__init__.py
@@ -2,6 +2,7 @@
from quantumlab.stationary.imaginary_time import (ground_state, excited_states, ConvergenceInfo,
coupled_ground_state, CoupledConvergenceInfo)
from quantumlab.stationary.hamiltonian import apply_hamiltonian
+from quantumlab.stationary.conjugate_gradient import ground_state_pcg
__all__ = ['eigenstates', 'ground_state', 'excited_states', 'ConvergenceInfo', 'apply_hamiltonian',
- 'coupled_ground_state', 'CoupledConvergenceInfo']
+ 'coupled_ground_state', 'CoupledConvergenceInfo', 'ground_state_pcg']
diff --git a/quantumlab/stationary/conjugate_gradient.py b/quantumlab/stationary/conjugate_gradient.py
new file mode 100644
index 0000000..297c5b4
--- /dev/null
+++ b/quantumlab/stationary/conjugate_gradient.py
@@ -0,0 +1,132 @@
+"""
+Ground states by preconditioned nonlinear conjugate gradient on the sphere
+‖ψ‖² = N (Antoine, Levitt & Tang, J. Comput. Phys. 343, 92 (2017)).
+
+Imaginary-time propagation is a first-order method whose fixed point carries
+an O(dτ²) error, and soft modes (vortex lattices, elongated condensates)
+relax in it as exp(−Δτ) with a tiny gap Δ. Minimising the energy directly
+removes both problems: the fixed point is an exact stationary state, so the
+residual ‖Hψ − μψ‖ can be driven to small values, and conjugate directions
+converge on soft modes much faster than steepest descent.
+
+The preconditioner is P = P_T^½ P_V P_T^½ with P_T = (α + ℏ²k²/2m)⁻¹ in
+Fourier space and P_V = (α + V + g|ψ|²)⁻¹ in real space, which tames both the
+kinetic and the potential stiffness.
+"""
+from typing import Optional
+import numpy as np
+from scipy.fft import fftn, ifftn
+from quantumlab.core.spectral import k_squared, volume_element, wavefunction_class
+from quantumlab.stationary.hamiltonian import apply_hamiltonian
+from quantumlab.stationary.imaginary_time import ConvergenceInfo, _default_guess
+
+
+def ground_state_pcg(grid, potential, initial=None, nonlinearity: float = 0.0, rotation: float = 0.0,
+ tol: float = 1e-8, max_iter: int = 10000, hbar: float = 1.0, m: float = 1.0,
+ callback=None, callback_interval: int = 100, workers: int = -1):
+ """
+ Minimise E[ψ] = ⟨ψ|−ℏ²∇²/2m + V − ΩL_z|ψ⟩ + (g/2)∫|ψ|⁴ at fixed norm.
+
+ Parameters
+ ----------
+ initial : WaveFunction or ndarray, optional
+ Starting state; its norm N is kept. For vortex states start from a
+ guess with vortices (e.g. from damped dynamics or imaginary time).
+ tol : float
+ Stop when the residual ‖Hψ − μψ‖/√N falls below ``tol``.
+ callback : callable, optional
+ ``callback(iteration, residual, energy)`` every ``callback_interval``
+ iterations.
+
+ Returns
+ -------
+ wf : WaveFunction
+ info : ConvergenceInfo
+ ``steps`` is the number of iterations, ``converged`` whether ``tol``
+ was reached, ``residual`` = ‖Hψ − μψ‖/√N.
+ """
+ if getattr(potential, 'time_dependent', False):
+ raise ValueError('ground_state_pcg requires a time-independent potential')
+ dV = volume_element(grid)
+ V = np.zeros(grid.shape) if potential is None else np.asarray(potential.evaluate(grid), dtype=float)
+ T_k = hbar ** 2 * k_squared(grid) / (2.0 * m)
+ g = float(nonlinearity)
+ psi = _default_guess(grid) if initial is None else np.array(getattr(initial, 'psi', initial), dtype=complex)
+
+ def inner(a, b):
+ return float(np.real(np.sum(np.conj(a) * b)) * dV)
+
+ if initial is None:
+ psi /= np.sqrt(inner(psi, psi)) # default guess at unit norm
+
+ def h_psi(p):
+ return apply_hamiltonian(p, grid, V, hbar, m, nonlinearity=g, workers=workers, rotation=rotation)
+
+ def quartic(p):
+ return float(np.sum((p.real ** 2 + p.imag ** 2) ** 2) * dV)
+
+ def energy_from(p, H_p):
+ # ⟨ψ|Hψ⟩ with H including g|ψ|² counts the interaction twice: E = ⟨ψ|Hψ⟩ − (g/2)∫|ψ|⁴
+ return inner(p, H_p) - 0.5 * g * quartic(p)
+
+ # Each iteration applies H twice (trial point and accepted point); the accepted
+ # point's Hψ is reused for the next residual and energy.
+ N = inner(psi, psi)
+ Hpsi = h_psi(psi)
+ d_prev = r_prev = Pr_prev = None
+ converged = False
+ for it in range(max_iter + 1):
+ mu = inner(psi, Hpsi) / N
+ r = Hpsi - mu * psi
+ residual = np.sqrt(inner(r, r) / N)
+ E0 = energy_from(psi, Hpsi)
+ if callback is not None and it % callback_interval == 0:
+ callback(it, residual, E0)
+ if residual < tol:
+ converged = True
+ break
+ if it == max_iter:
+ break
+ # The shift keeps both preconditioner factors positive, also for V < 0
+ alpha = max(1.0, mu - float(V.min()))
+ PT_half = 1.0 / np.sqrt(alpha + T_k)
+ PV = 1.0 / (alpha + V + g * np.abs(psi) ** 2)
+ Pr = ifftn(PT_half * fftn(PV * ifftn(PT_half * fftn(r, workers=workers), workers=workers),
+ workers=workers), workers=workers)
+ Pr -= inner(psi, Pr) / N * psi # tangent space of the sphere
+ beta = 0.0 if r_prev is None else max(0.0, inner(r - r_prev, Pr) / inner(r_prev, Pr_prev))
+ d = -Pr if d_prev is None else -Pr + beta * d_prev
+ d -= inner(psi, d) / N * psi
+ if inner(r, d) >= 0.0: # not a descent direction: restart
+ d = -Pr
+ u = d * np.sqrt(N / inner(d, d)) # tangent direction with ‖u‖² = N
+ # Line search along the great circle ψ(θ) = ψ cos θ + u sin θ (norm preserved).
+ # While energy differences are resolvable, θ comes from a quadratic fit of E(θ);
+ # near convergence they scale as residual² and drown in round-off, so a secant
+ # step on the directional derivative E'(θ) = 2 Re⟨Hψ(θ), ψ'(θ)⟩ is used instead.
+ slope0 = 2.0 * inner(Hpsi, u)
+ trial = min(0.5, 0.5 * np.sqrt(inner(d, d) / N))
+ psi_t = psi * np.cos(trial) + u * np.sin(trial)
+ H_t = h_psi(psi_t)
+ E_t = energy_from(psi_t, H_t)
+ if abs(E_t - E0) > 1e-10 * max(1.0, abs(E0)):
+ curvature = (E_t - E0 - slope0 * trial) / trial ** 2
+ theta = -slope0 / (2.0 * curvature) if curvature > 0 else trial
+ else:
+ slope_t = 2.0 * inner(H_t, -psi * np.sin(trial) + u * np.cos(trial))
+ theta = trial * slope0 / (slope0 - slope_t) if slope_t > slope0 else trial
+ for _ in range(30):
+ if theta == trial:
+ candidate, H_c, E_c = psi_t, H_t, E_t
+ else:
+ candidate = psi * np.cos(theta) + u * np.sin(theta)
+ H_c = h_psi(candidate)
+ E_c = energy_from(candidate, H_c)
+ # accept unless the energy rises by more than round-off
+ if E_c <= E0 + 1e-12 * max(1.0, abs(E0)):
+ break
+ theta *= 0.5
+ psi, Hpsi = candidate, H_c
+ d_prev, r_prev, Pr_prev = d, r, Pr
+
+ return wavefunction_class(grid)(grid, psi), ConvergenceInfo(converged, it, E0, mu, residual)
diff --git a/quantumlab/stationary/imaginary_time.py b/quantumlab/stationary/imaginary_time.py
index 114c895..2d8cfe5 100644
--- a/quantumlab/stationary/imaginary_time.py
+++ b/quantumlab/stationary/imaginary_time.py
@@ -54,6 +54,12 @@ def ground_state(grid, potential, dtau: float = 0.01, nonlinearity: float = 0.0,
Parameters
----------
+ dtau : float or sequence of float
+ Imaginary time step. A decreasing sequence runs a continuation: the
+ large steps relax slow modes (e.g. of vortex lattices) in few steps,
+ the small ones lower the O(dτ²) error floor. ``max_steps`` and
+ ``tol`` apply to each stage, and ``info`` describes the last one
+ (``steps`` is the total).
nonlinearity : float
Gross–Pitaevskii coupling g (ψ normalised to 1). g = 0 gives the
linear Schrödinger ground state.
@@ -81,6 +87,14 @@ def ground_state(grid, potential, dtau: float = 0.01, nonlinearity: float = 0.0,
for g = 0), ``chemical_potential`` is μ = ⟨ψ|H_GP|ψ⟩ and ``residual``
is ‖H_GP ψ − μψ‖.
"""
+ if np.ndim(dtau) > 0:
+ wf, total = initial, 0
+ for step_size in dtau:
+ wf, info = ground_state(grid, potential, float(step_size), nonlinearity, wf, tol, max_steps,
+ check_interval, hbar, m, orthogonal_to, workers, rotation, backend)
+ total += info.steps
+ info.steps = total
+ return wf, info
if orthogonal_to and nonlinearity != 0.0:
raise ValueError('orthogonal_to is only meaningful for the linear problem')
solver = SplitOperatorSolver(grid, potential, dtau, hbar, m, order=2,
diff --git a/tests/test_conjugate_gradient.py b/tests/test_conjugate_gradient.py
new file mode 100644
index 0000000..991ceb9
--- /dev/null
+++ b/tests/test_conjugate_gradient.py
@@ -0,0 +1,68 @@
+import numpy as np
+import pytest
+from quantumlab.core.grid import Grid1D, Grid2D, Grid3D
+from quantumlab.core.wavefunction import WaveFunction2D
+from quantumlab.potentials import HarmonicTrap, SoftCoulomb, DipoleDrive
+from quantumlab.solvers.split_operator import SplitOperatorSolver
+from quantumlab.stationary import ground_state_pcg, ground_state
+from quantumlab.observables import (
+ kinetic_energy_expectation, potential_energy_expectation, interaction_energy, angular_momentum_z_expectation,
+)
+
+
+@pytest.mark.parametrize('grid, potential, kwargs, exact', [
+ (Grid1D(256, -12.0, 12.0), HarmonicTrap(1.0), {}, 0.5),
+ (Grid1D(2048, -100.0, 100.0), SoftCoulomb(), {}, -0.5), # V < 0
+ (Grid1D(256, -12.0, 12.0), HarmonicTrap(2.0, m=0.5), dict(hbar=0.7, m=0.5), 0.7),
+ (Grid3D(32, -7.0, 7.0, 32, -7.0, 7.0, 32, -7.0, 7.0), HarmonicTrap((1.0, 1.2, 1.4)), {}, 1.8),
+])
+def test_linear_ground_states_to_machine_precision(grid, potential, kwargs, exact):
+ wf, info = ground_state_pcg(grid, potential, tol=1e-10, max_iter=3000, **kwargs)
+ assert info.converged
+ assert info.residual < 1e-10
+ assert info.energy == pytest.approx(exact, abs=1e-12)
+ assert wf.norm() == pytest.approx(1.0, abs=1e-12)
+
+
+def test_gp_ground_state_without_dtau_floor():
+ """The minimiser's fixed point is exact: the virial theorem holds to ~1e-9, not to O(dτ²).
+ (The virial theorem is a continuum identity; the grid must resolve the state well.)"""
+ grid = Grid3D(48, -8.0, 8.0, 48, -8.0, 8.0, 48, -8.0, 8.0)
+ trap, g = HarmonicTrap((1.0, 1.2, 1.4)), 60.0
+ wf, info = ground_state_pcg(grid, trap, nonlinearity=g, tol=1e-9)
+ T, V, E_int = kinetic_energy_expectation(wf), potential_energy_expectation(wf, trap), interaction_energy(wf, g)
+ assert info.converged
+ assert abs(2 * T - 2 * V + 3 * E_int) / V < 1e-8
+ _, it = ground_state(grid, trap, dtau=0.005, nonlinearity=g)
+ assert info.residual < 1e-3 * it.residual
+ assert info.energy <= it.energy + 1e-12
+
+
+def test_initial_norm_is_kept():
+ grid = Grid1D(256, -12.0, 12.0)
+ guess = np.exp(-grid.x ** 2).astype(complex) * 3.0
+ wf, info = ground_state_pcg(grid, HarmonicTrap(1.0), initial=guess, nonlinearity=5.0, tol=1e-9)
+ assert wf.norm() == pytest.approx(np.sum(np.abs(guess) ** 2) * grid.dx, rel=1e-12)
+ assert info.converged
+
+
+def test_rotating_vortex_lattice_converges_below_imaginary_time():
+ grid = Grid2D(64, -8.0, 8.0, 64, -8.0, 8.0)
+ trap, g, Om = HarmonicTrap(1.0), 300.0, 0.8
+ no_vortex, _ = ground_state(grid, trap, dtau=0.005, nonlinearity=g)
+ seed = WaveFunction2D(grid, no_vortex.psi * np.exp(1j * np.arctan2(grid.Y - 0.3, grid.X - 0.2)))
+ lattice = SplitOperatorSolver(grid, trap, 0.005, nonlinearity=g, imaginary_time=True, rotation=Om).evolve(seed, 1500)
+ _, it = ground_state(grid, trap, dtau=0.005, nonlinearity=g, rotation=Om, initial=lattice, max_steps=2000)
+ wf, info = ground_state_pcg(grid, trap, initial=lattice, nonlinearity=g, rotation=Om, tol=1e-7, max_iter=3000)
+ assert info.converged
+ assert info.energy < it.energy
+ assert angular_momentum_z_expectation(wf) > 2.0
+
+
+def test_callback_and_validation():
+ calls = []
+ ground_state_pcg(Grid1D(64, -6.0, 6.0), HarmonicTrap(1.0), tol=1e-8,
+ callback=lambda i, r, E: calls.append((i, r, E)), callback_interval=5)
+ assert calls and calls[0][0] == 0 and all(c[0] % 5 == 0 for c in calls)
+ with pytest.raises(ValueError):
+ ground_state_pcg(Grid1D(32, -4.0, 4.0), DipoleDrive(None, 1.0, 1.0))
diff --git a/tests/test_stationary.py b/tests/test_stationary.py
index 6b28974..7d6aae8 100644
--- a/tests/test_stationary.py
+++ b/tests/test_stationary.py
@@ -66,3 +66,18 @@ def test_ground_state_error_is_second_order_in_dtau():
_, i1 = ground_state(grid, pot, dtau=0.02, tol=1e-14)
_, i2 = ground_state(grid, pot, dtau=0.01, tol=1e-14)
assert i1.residual / i2.residual == pytest.approx(4.0, rel=0.1)
+
+
+def test_dtau_continuation_reaches_the_small_step_accuracy_in_fewer_steps():
+ """A decreasing dτ schedule ends at the accuracy of its last step size."""
+ from quantumlab.core.grid import Grid2D
+ grid = Grid2D(64, -8.0, 8.0, 64, -8.0, 8.0)
+ trap, g = HarmonicTrap((1.0, 1.3)), 50.0
+ _, single = ground_state(grid, trap, dtau=0.0025, nonlinearity=g, tol=1e-12, max_steps=200000)
+ _, staged = ground_state(grid, trap, dtau=[0.04, 0.01, 0.0025], nonlinearity=g, tol=1e-12, max_steps=200000)
+ assert staged.converged
+ assert staged.energy == pytest.approx(single.energy, abs=1e-9)
+ # both stop on the energy criterion, which is quadratic in the residual,
+ # so the residuals agree in magnitude rather than to many digits
+ assert staged.residual < 1.5 * single.residual
+ assert staged.steps < single.steps