diff --git a/README.md b/README.md index 9d4ebe3..4a51609 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,9 @@ Every new feature is checked against exact or independent results; see [Validati ### New since v1.2 (unreleased) +- **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. - **Strong-field physics** (`quantumlab.strongfield`): - high-harmonic generation from a hydrogen atom (`SoftCoulomb`) in intense laser pulses (`flat_top_envelope`); - harmonic spectra, Gabor time–frequency maps, the classical three-step model, and attosecond pulse synthesis. @@ -80,6 +83,7 @@ quantumlab/ │ ├── split_step_3d.py # 3D Split-Step Fourier solver (CPU/SciPy) │ ├── split_step_3d_gpu.py # 3D SSFM with CuPy GPU acceleration + CPU fallback │ ├── split_operator.py # Generic 1D/2D/3D engine: order 2/4, V(r,t), GPE, imaginary time, rotation, damping +│ ├── multicomponent.py # Coupled multi-component Gross–Pitaevskii solver │ └── backends.py # NumPy/SciPy (CPU) and CuPy (CUDA GPU) array backends ├── stationary/ │ ├── eigensolver.py # Lanczos / preconditioned LOBPCG on a matrix-free Hamiltonian @@ -120,7 +124,7 @@ quantumlab/ ## Example Gallery -The framework includes 12 pre-built simulation scripts under the `examples/` directory. Run any example to generate high-quality scientific visualizations saved to the `output/` directory. +The framework includes 13 pre-built simulation scripts under the `examples/` directory. Run any example to generate high-quality scientific visualizations saved to the `output/` directory. --- @@ -315,6 +319,35 @@ A hydrogen atom (1D soft-core model, I_p = 13.6 eV) is driven by an intense 800 ![Cutoff scan](images/12_hhg_cutoff_scan.png) +### 13. Two-Component Condensates (`examples/13_two_component_bec.py`) + +Two condensates with intra-species couplings g₁₁ = g₂₂ = g and inter-species coupling g₁₂ obey coupled Gross–Pitaevskii equations. They mix when g₁₂² < g₁₁g₂₂ and separate when g₁₂² > g₁₁g₂₂. + +

+ Spinodal phase separation + Interlaced vortex lattices +

+

Left: a uniform mixture with g₁₂ = 1.3g separates into domains that coarsen. Right: a rotating two-component condensate forms two interlaced vortex lattices (pink and cyan).

+ +**Validation:** +- **Miscibility:** in a trap, the ground-state overlap Λ stays 1.000 up to g₁₂/g = 1.05 and drops to 0.72, 0.31 and 0.16 at 1.1, 1.2 and 1.4. A finite cloud shifts the uniform threshold g₁₂ = g slightly upward, because the domain wall costs gradient energy. +- **Spinodal decomposition:** + - the spin mode on the |k| ≈ k\* shell grows at 0.2992 against the Bogoliubov rate γ\* = n(g₁₂ − g) = 0.3000 (−0.3%); + - the structure factor peaks at k = 0.785 against k\* = 0.775 (within one bin); + - the populations are conserved to 10⁻¹³. +- **Two-colour vortex lattices:** with g₁₂ = 0.5g, Ω = 0.8 and damping, 16 + 15 vortices form. **Every** vortex core of one component sits on a density maximum of the other, at a median 1.8× its local average. +- **Exact limits, from the test and validation suites:** + - g₁₂ = 0 reproduces two independent condensates bit for bit; + - at the Manakov point g₁₁ = g₂₂ = g₁₂ the total density equals the one-component ground state to 2·10⁻⁷; + - the Bogoliubov spin-mode frequency is reproduced to 10⁻⁹ relative; + - the coupled virial theorem holds to 2·10⁻⁶. + +![Miscibility](images/13_miscibility.png) + +![Growth of the phase-separation instability](images/13_phase_separation_growth.png) + +![Interlaced vortex lattices](images/13_vortex_lattices.png) + --- ## Validation @@ -331,7 +364,7 @@ A hydrogen atom (1D soft-core model, I_p = 13.6 eV) is driven by an intense 800 | 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.68e-14 | +| Harmonic spectrum 1D, 10 levels (Lanczos) | E_n = n + ½ | 5.24e-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 | @@ -340,12 +373,16 @@ A hydrogen atom (1D soft-core model, I_p = 13.6 eV) is driven by an intense 800 | 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) | 3.21e-14 | +| 1D soft-core hydrogen ground state | E₀ = −½ a.u. (I_p = 13.6 eV) | 1.61e-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 | +| Bogoliubov spin mode, miscible mixture (t ≤ 60) | δ(n₁−n₂) ∝ cos ω_s t, ω_s² = ε_k(ε_k + 2n(g − g₁₂)) | 8.53e-10 | +| 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 | -All 21 checks pass. A few rows report something other than a plain error: +All 25 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. @@ -435,6 +472,7 @@ python examples/09_soliton_collision.py python examples/10_quantum_chaos_stadium.py python examples/11_rotating_bec_vortex_lattice.py python examples/12_high_harmonic_generation.py +python examples/13_two_component_bec.py # CPU vs GPU timing (GPU columns appear only with CuPy and a CUDA device) python benchmarks/gpu_split_operator.py @@ -468,6 +506,7 @@ Test coverage includes: - `test_volume_3d.py` — isosurface geometry, phase sampling, PNG/GIF/HTML export, overlays - `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_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 d3bd46d..49cb5f6 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: 57 s. +Total runtime: 65 s. | Category | Check | Reference | Metric | Error | Tolerance | Result | |---|---|---|---|---|---|---| @@ -15,7 +15,7 @@ Total runtime: 57 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.68e-14 | 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 | 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,9 +24,13 @@ Total runtime: 57 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₀ + ½\| | 3.21e-14 | 1e-09 | 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 | 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 | +| Two-component BEC | Bogoliubov spin mode, miscible mixture (t ≤ 60) | δ(n₁−n₂) ∝ cos ω_s t, ω_s² = ε_k(ε_k + 2n(g − g₁₂)) | max relative deviation | 8.53e-10 | 1e-06 | pass | +| 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 | -**21/21 checks passed.** +**25/25 checks passed.** diff --git a/benchmarks/validation_suite.py b/benchmarks/validation_suite.py index 30a649e..5fdb5a3 100644 --- a/benchmarks/validation_suite.py +++ b/benchmarks/validation_suite.py @@ -242,6 +242,71 @@ def level(q): 'max |spacing − ½| (cycles)', float(np.max(np.abs(spacing - 0.5))), 0.01) +def two_component(): + from quantumlab.solvers.multicomponent import CoupledGPESolver + from quantumlab.stationary import coupled_ground_state + box = Grid1D(256, -20 * np.pi, 20 * np.pi) + n, g = 1.0, 1.0 + + def seeded(k): + return (WaveFunction1D(box, np.sqrt(n) * (1 + 1e-6 * np.cos(k * box.x)) + 0j), + WaveFunction1D(box, np.sqrt(n) * (1 - 1e-6 * np.cos(k * box.x)) + 0j)) + + def spin(states, k): + return float(np.sum((states[0].probability_density - states[1].probability_density) + * np.cos(k * box.x)) * 2 / box.N) + + g12, k = 0.6, box.dk * 10 + omega = np.sqrt(k ** 2 / 2 * (k ** 2 / 2 + 2 * n * (g - g12))) + solver = CoupledGPESolver(box, (None, None), [[g, g12], [g12, g]], 0.01, order=4) + state, err = seeded(k), 0.0 + for _ in range(12): + state = solver.evolve(state, 500) + err = max(err, abs(spin(state, k) - 4e-6 * np.cos(omega * solver.t)) / 4e-6) + check('Two-component BEC', 'Bogoliubov spin mode, miscible mixture (t ≤ 60)', + 'δ(n₁−n₂) ∝ cos ω_s t, ω_s² = ε_k(ε_k + 2n(g − g₁₂))', 'max relative deviation', err, 1e-6) + + g12 = 1.3 + k = box.dk * np.round(np.sqrt(2 * n * (g12 - g)) / box.dk) + gamma = np.sqrt(k ** 2 / 2 * (2 * n * (g12 - g) - k ** 2 / 2)) + solver = CoupledGPESolver(box, (None, None), [[g, g12], [g12, g]], 0.01, order=4) + state, t, amp = seeded(k), [], [] + while not amp or amp[-1] < 1e-3: + state = solver.evolve(state, 100) + t.append(solver.t) + amp.append(abs(spin(state, k))) + t, amp = np.array(t), np.array(amp) + rate = np.polyfit(t[amp > 1.2e-4], np.log(amp[amp > 1.2e-4]), 1)[0] + check('Two-component BEC', 'Phase-separation instability, g₁₂ = 1.3 g', 'growth rate γ = √(ε_k(2n(g₁₂ − g) − ε_k))', + '|γ_measured/γ − 1|', abs(rate / gamma - 1), 1e-3) + + grid = Grid2D(64, -8.0, 8.0, 64, -8.0, 8.0) + trap, G = HarmonicTrap((1.0, 1.3)), 60.0 + a = WaveFunction2D.gaussian(grid, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0) + b = WaveFunction2D.gaussian(grid, -1.0, 0.5, 0.0, 0.0, 1.0, 1.0) + a.psi *= np.sqrt(0.3) + b.psi *= np.sqrt(0.7) + (s1, s2), _ = coupled_ground_state(grid, (trap, trap), [[G, G], [G, G]], (a, b), dtau=0.005) + single, _ = ground_state(grid, trap, dtau=0.005, nonlinearity=G) + check('Two-component BEC', 'Manakov point g₁₁ = g₂₂ = g₁₂', 'n₁ + n₂ equals the one-component GP ground state', + 'max |n₁ + n₂ − n|', float(np.max(np.abs(s1.probability_density + s2.probability_density + - single.probability_density))), 1e-6) + + G2 = np.array([[100.0, 70.0], [70.0, 120.0]]) + grid = Grid2D(80, -9.0, 9.0, 80, -9.0, 9.0) + a = WaveFunction2D.gaussian(grid, 1.5, 0.0, 0.0, 0.0, 1.0, 1.0) + b = WaveFunction2D.gaussian(grid, -1.5, 0.0, 0.0, 0.0, 1.0, 1.0) + a.psi *= np.sqrt(0.5) + b.psi *= np.sqrt(0.5) + states, _ = coupled_ground_state(grid, (HarmonicTrap(1.0), HarmonicTrap(1.0)), G2, (a, b), dtau=0.005) + T = sum(kinetic_energy_expectation(s) for s in states) + V = sum(potential_energy_expectation(s, HarmonicTrap(1.0)) for s in states) + nn = [s.probability_density for s in states] + E_int = 0.5 * sum(G2[i, j] * np.sum(nn[i] * nn[j]) for i in range(2) for j in range(2)) * grid.dx * grid.dy + check('Two-component BEC', 'Virial theorem, coupled GP ground state', '2⟨T⟩ − 2⟨V⟩ + 2E_int = 0 (2D)', + '|2T − 2V + 2E_int| / V', abs(2 * T - 2 * V + 2 * E_int) / V, 1e-4) + + def write_report(path, elapsed): lines = [ '# QuantumLab validation report', @@ -271,7 +336,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): + rotating_frame, high_harmonics, two_component): print(f'{fn.__name__}:') fn() out = Path(__file__).with_name('validation_report.md') diff --git a/docs/api/solvers.md b/docs/api/solvers.md index 1846abe..39a6c40 100644 --- a/docs/api/solvers.md +++ b/docs/api/solvers.md @@ -4,6 +4,8 @@ Generated from the docstrings in the source code. ::: quantumlab.solvers.split_operator +::: quantumlab.solvers.multicomponent + ::: quantumlab.solvers.backends ::: quantumlab.solvers.split_step_1d diff --git a/docs/examples.md b/docs/examples.md index 1d35d55..4e64d53 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -86,3 +86,16 @@ A hydrogen atom (soft-core model, I_p = 13.6 eV) is driven by an 800 nm pulse at ![Electron in space and time](images/12_electron_spacetime.png) ![Cutoff scan](images/12_hhg_cutoff_scan.png) +## 13. Two-component condensates + +Two condensates with couplings g₁₁ = g₂₂ = g and g₁₂: +- **Miscibility:** in a trap, the overlap of the ground states drops sharply just above g₁₂ = g. The uniform criterion is g₁₂² = g₁₁g₂₂, and a finite cloud shifts the transition slightly upward. +- **Spinodal decomposition:** a uniform mixture with g₁₂ = 1.3g separates into labyrinthine domains. Their growth on the |k| ≈ k\* shell matches the Bogoliubov rate γ\* = n(g₁₂ − g) to 0.3%, and the structure-factor peak sits at k\* within one bin. Afterwards the domains coarsen. +- **Two-colour vortex lattices:** in a rotating trap both components nucleate vortices, which interlace. Every vortex core of one component sits on a density maximum of the other, at a median 1.8× its local average. + +![Phase separation](images/13_phase_separation.gif) +![Interlaced vortex lattices](images/13_vortex_lattices.gif) +![Miscibility](images/13_miscibility.png) +![Growth of the instability](images/13_phase_separation_growth.png) +![Interlaced lattices](images/13_vortex_lattices.png) + diff --git a/docs/guide/multicomponent.md b/docs/guide/multicomponent.md new file mode 100644 index 0000000..f24c249 --- /dev/null +++ b/docs/guide/multicomponent.md @@ -0,0 +1,43 @@ +# Two-component condensates + +[`CoupledGPESolver`](../api/solvers.md) integrates coupled Gross–Pitaevskii equations for condensates of equal mass, for example two hyperfine states of ⁸⁷Rb: + +> iℏ ∂ψ_i/∂t = [ −ℏ²∇²/2m + V_i(r) + Σ_j g_ij |ψ_j|² − ΩL_z ] ψ_i + +```python +from quantumlab.solvers.multicomponent import CoupledGPESolver +from quantumlab.stationary import coupled_ground_state + +G = [[100.0, 120.0], + [120.0, 100.0]] # g11, g12 / g21, g22 (symmetric) +states, info = coupled_ground_state(grid, (trap, trap), G, (guess_1, guess_2), dtau=0.005) +print(info.chemical_potentials, info.residuals) + +solver = CoupledGPESolver(grid, (trap, trap), G, dt=0.005, order=4, rotation=0.8) +psi_1, psi_2 = solver.evolve(states, 1000) +``` + +- The solver supports the same options as `SplitOperatorSolver`: order 2/4, imaginary time, rotation, damping and the GPU backend. +- Each component keeps its own particle number, which is the norm of its initial state. +- In real time the coupled potential step is exact. In imaginary time and with damping it uses rescaled midpoint densities, as for one component. + +## Miscibility + +A uniform mixture with g₁₁, g₂₂ > 0 is stable (**miscible**) when g₁₂² < g₁₁g₂₂ and separates into domains (**immiscible**) when g₁₂² > g₁₁g₂₂. `miscibility_overlap(wf_1, wf_2)` gives Λ = ∫n₁n₂ / √(∫n₁²∫n₂²): 1 for identical profiles, close to 0 for separated ones. In a trap the transition is slightly shifted above g₁₂ = g, because the domain wall between the components costs gradient energy. + +!!! tip + Immiscible ground states break the symmetry between the components. Start imaginary time from a guess that already breaks it, e.g. displaced clouds; a symmetric guess can stay on a symmetric saddle point. + +## Dynamics and the Bogoliubov spin mode + +For equal densities n and g₁₁ = g₂₂ = g, small differences between the components (the *spin* mode) obey + +> ω_s(k)² = ε_k (ε_k + 2n(g − g₁₂)), ε_k = ℏ²k²/2m + +For g₁₂ < g these are stable oscillations. For g₁₂ > g the long wavelengths become unstable and grow as e^{γt}, fastest at k\* = √(2mn(g₁₂ − g))/ℏ with γ\* = n(g₁₂ − g). This **spinodal decomposition** is reproduced to 10⁻⁹ (frequency) and 10⁻⁴ (growth rate) in the validation suite. + +`coupled_gp_energy` gives the conserved total energy Σ(⟨T⟩ + ⟨V_i⟩) + ½Σg_ij∫n_in_j. + +## Numerical stability + +For nonlinear real-time runs on a uniform background, keep the kinetic phase of the shortest grid wavelength below π per (sub)step, i.e. ℏk_max²/2m · |w|dt < π with k_max = π/dx (|w| ≤ 1.71 for order 4). Above it, the split-step method has a parametric instability in which round-off noise grows (Weideman & Herbst 1986). diff --git a/docs/guide/solvers.md b/docs/guide/solvers.md index e977942..bee76b7 100644 --- a/docs/guide/solvers.md +++ b/docs/guide/solvers.md @@ -58,3 +58,10 @@ The rotation term −ΩL_z = Ω(y p_x − x p_y) is split with the kinetic energ ## Legacy solvers `SplitStep1DSolver`, `SplitStep2DSolver`, `SplitStep3DSolver` and `SplitStep3DGPU` from the first release are kept for compatibility. For a static potential, `SplitOperatorSolver(order=2)` gives bit-identical results to them. + +## Numerical stability of nonlinear runs + +Every factor of the split-step method is unitary. Still, for nonlinear problems on a uniform or broad background it has a parametric instability when the kinetic phase of the shortest grid wavelength per (sub)step exceeds π (Weideman & Herbst 1986). Keep ℏk_max²/2m · |w|dt < π with k_max = π/dx, where |w| ≤ 1.71 for order 4. Localised states such as solitons and trapped condensates are much less sensitive. + +Two-component condensates are covered in [Two-component condensates](multicomponent.md). + diff --git a/docs/index.md b/docs/index.md index 52289b0..66bb3a6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -15,7 +15,7 @@ | Area | Capabilities | |---|---| -| **Time evolution** | Split-operator propagation of order 2 (Strang) and 4 (Yoshida); time-dependent potentials V(r, t); Gross–Pitaevskii nonlinearity; rotating frames (H − ΩL_z); dissipative dynamics; absorbing boundaries | +| **Time evolution** | Split-operator propagation of order 2 (Strang) and 4 (Yoshida); time-dependent potentials V(r, t); Gross–Pitaevskii nonlinearity, including coupled multi-component condensates; rotating frames (H − ΩL_z); dissipative dynamics; absorbing boundaries | | **Stationary states** | Lanczos and preconditioned LOBPCG eigensolvers on a matrix-free FFT Hamiltonian; imaginary-time ground and excited states, including GP ground states in rotating frames | | **Physics models** | Barriers, wells, (anisotropic) harmonic traps, multi-slit and pinhole screens, chaotic stadium billiard, soft-core Coulomb atoms, lattices, disorder, laser-like dipole driving, custom potentials | | **Strong-field physics** | High-harmonic spectra, Gabor time–frequency analysis, three-step model, attosecond pulse synthesis | @@ -31,5 +31,5 @@ Every feature is checked against exact, analytic or independent numerical result - [Getting started](getting-started.md): installation and a first simulation - [User guide](guide/solvers.md): the solvers, stationary states, potentials and visualization in depth -- [Examples](examples.md): twelve ready-to-run simulations with their results +- [Examples](examples.md): thirteen ready-to-run simulations with their results - [API reference](api/core.md): every class and function, generated from the source diff --git a/examples/13_two_component_bec.py b/examples/13_two_component_bec.py new file mode 100644 index 0000000..658652d --- /dev/null +++ b/examples/13_two_component_bec.py @@ -0,0 +1,289 @@ +""" +Example 13: Two-component Bose–Einstein condensates: phase separation and +interlaced ("two-colour") vortex lattices. + +Two condensates of equal mass with intra-species couplings g11 = g22 = g and +inter-species coupling g12 obey coupled Gross–Pitaevskii equations. A uniform +mixture is stable (miscible) when g12² < g11 g22 and separates into domains +(immiscible) when g12² > g11 g22. + +Part A: miscibility in a trap. The ground-state overlap of the two components + is scanned across g12/g = 1. +Part B: spinodal decomposition. A uniform mixture with g12 > g, seeded with + weak noise, separates into domains that then coarsen. The early growth + is compared with Bogoliubov theory: the spin mode with + ε_k = ℏ²k²/2m grows as exp(γt) with γ(k) = √(ε_k (2n(g12 − g) − ε_k)), + fastest at k* = √(2mn(g12 − g))/ℏ with γ* = n(g12 − g). The noise + seeds every wavevector, so the growth is measured on the shell + |k| ≈ k* of the spin structure factor, not on the total rms. +Part C: rotation. Both components in a rotating trap (damped dynamics, as in + example 11) nucleate vortices. With g12 > 0 the two lattices interlace: + the vortex cores of one component sit where the other is densest. + +Run all parts, or a subset: python examples/13_two_component_bec.py [A] [B] [C] + +Outputs (in output/): + 13_miscibility.png overlap vs g12/g and ground-state densities + 13_phase_separation.mp4 domain formation and coarsening (two colours) + 13_phase_separation_growth.png spin-density growth vs Bogoliubov + 13_vortex_lattices.mp4 formation of the interlaced lattices + 13_vortex_lattices.png final interlaced lattices with vortex positions +""" +import os +import sys +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.animation import FFMpegWriter +from scipy.ndimage import gaussian_filter +from scipy.spatial import cKDTree +from quantumlab.core.grid import Grid2D +from quantumlab.core.wavefunction import WaveFunction2D +from quantumlab.potentials import HarmonicTrap +from quantumlab.solvers.multicomponent import CoupledGPESolver +from quantumlab.stationary import coupled_ground_state +from quantumlab.observables import miscibility_overlap, vortex_positions, angular_momentum_z_expectation +from quantumlab.visualization.style import set_style + +COLOUR_A = np.array([1.00, 0.35, 0.55]) # component 1 +COLOUR_B = np.array([0.25, 0.85, 1.00]) # component 2 + + +def two_colour(n1, n2, vmax=None): + """RGB image: component 1 in pink, component 2 in cyan, overlap tends to white.""" + vmax = vmax or max(n1.max(), n2.max()) + a = np.clip(n1 / vmax, 0, 1)[..., None] + b = np.clip(n2 / vmax, 0, 1)[..., None] + return np.clip(a * COLOUR_A + b * COLOUR_B, 0, 1).transpose(1, 0, 2) + + +def displaced(grid, dx, norm): + wf = WaveFunction2D.gaussian(grid, dx, 0.0, 0.0, 0.0, 1.8, 1.8) + wf.psi *= np.sqrt(norm) + return wf + + +def part_a(): + print('\n[A] Miscibility of the ground state in a harmonic trap (g11 = g22 = g = 100, N1 = N2 = 0.5)') + grid = Grid2D(96, -9.0, 9.0, 96, -9.0, 9.0) + trap = HarmonicTrap(1.0) + g = 100.0 + ratios = np.array([0.6, 0.8, 0.9, 0.95, 1.0, 1.05, 1.1, 1.2, 1.4]) + overlaps, examples = [], {} + for r in ratios: + states, info = coupled_ground_state(grid, (trap, trap), [[g, r * g], [r * g, g]], + (displaced(grid, 1.5, 0.5), displaced(grid, -1.5, 0.5)), + dtau=0.005, tol=1e-10, max_steps=30000) + overlaps.append(miscibility_overlap(*states)) + print(f' g12/g = {r:4.2f}: overlap Λ = {overlaps[-1]:.4f} (residuals {max(info.residuals):.1e}, ' + f'{info.steps} steps)') + if r in (0.8, 1.2): + examples[r] = states + fig = plt.figure(figsize=(12, 4.2)) + ax = fig.add_subplot(1, 3, 1) + ax.plot(ratios, overlaps, 'o-', color='#ffb000') + ax.axvline(1.0, color='#7fd4ff', ls='--', lw=1, label='g$_{12}^2$ = g$_{11}$g$_{22}$') + ax.set_xlabel('g$_{12}$ / g') + ax.set_ylabel('overlap Λ') + ax.set_title('Miscible → immiscible', fontweight='bold') + ax.legend(fontsize=8) + extent = [grid.x[0], grid.x[-1], grid.y[0], grid.y[-1]] + for k, r in enumerate((0.8, 1.2)): + s1, s2 = examples[r] + ax = fig.add_subplot(1, 3, 2 + k) + ax.imshow(two_colour(s1.probability_density, s2.probability_density), origin='lower', extent=extent) + ax.set_xlim(-6, 6) + ax.set_ylim(-6, 6) + ax.set_title(f'g$_{{12}}$/g = {r} ({"miscible" if r < 1 else "phase separated"})', fontweight='bold') + ax.set_xticks([]) + ax.set_yticks([]) + fig.tight_layout() + fig.savefig('output/13_miscibility.png', dpi=150) + plt.close(fig) + return ratios, np.array(overlaps) + + +def part_b(): + print('\n[B] Spinodal decomposition of a uniform mixture (n = 1 per component, g = 1, g12 = 1.3)') + L, N = 128.0, 256 + grid = Grid2D(N, -L / 2, L / 2, N, -L / 2, L / 2) + n, g, g12 = 1.0, 1.0, 1.3 + dt = 0.05 + k_star = np.sqrt(2 * n * (g12 - g)) + gamma_star = n * (g12 - g) + print(f' Bogoliubov: fastest-growing wavelength 2π/k* = {2 * np.pi / k_star:.2f}, growth rate γ* = {gamma_star:.3f}') + print(f' split-step stability: kinetic phase per step {(np.pi / grid.dx) ** 2 / 2 * dt:.2f} rad (< π)') + rng = np.random.default_rng(1) + noise = 1e-4 * (rng.standard_normal(grid.shape) + 1j * rng.standard_normal(grid.shape)) + wf1 = WaveFunction2D(grid, np.sqrt(n) * (1 + noise)) + wf2 = WaveFunction2D(grid, np.sqrt(n) * (1 - noise)) + norms0 = (wf1.norm(), wf2.norm()) + solver = CoupledGPESolver(grid, (None, None), [[g, g12], [g12, g]], dt, order=2) + + times, spin_rms, shell_amp, k_peak = [], [], [], [] + K = np.sqrt(grid.K_x ** 2 + grid.K_y ** 2) + shell = np.abs(K - k_star) < grid.dk_x + k_bins = np.arange(0.0, 2.0, grid.dk_x) + k_index = np.digitize(K, k_bins) + bin_count = np.maximum(np.bincount(k_index.ravel(), minlength=len(k_bins) + 1), 1) + + fig, ax = plt.subplots(figsize=(6, 6.3)) + fig.patch.set_facecolor('#0b0b10') + im = ax.imshow(two_colour(wf1.probability_density, wf2.probability_density, vmax=2 * n), origin='lower', + extent=[grid.x[0], grid.x[-1], grid.y[0], grid.y[-1]]) + ax.set_xticks([]) + ax.set_yticks([]) + title = ax.set_title('', fontsize=12, fontweight='bold') + writer = FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-crf', '20']) + n_steps = int(round(150.0 / dt)) + with writer.saving(fig, 'output/13_phase_separation.mp4', dpi=100): + state = (wf1, wf2) + for step in range(0, n_steps + 1, 20): + if step: + state = solver.evolve(state, 20) + s = state[0].probability_density - state[1].probability_density + times.append(solver.t) + spin_rms.append(float(np.sqrt(np.mean(s ** 2)))) + S = np.abs(np.fft.fft2(s)) ** 2 + S[0, 0] = 0.0 + shell_amp.append(float(np.sqrt(S[shell].mean()))) + radial = np.bincount(k_index.ravel(), S.ravel(), minlength=len(k_bins) + 1) / bin_count + k_peak.append(float(k_bins[np.argmax(radial[1:len(k_bins)])])) + if step % 60 == 0: + im.set_data(two_colour(state[0].probability_density, state[1].probability_density, vmax=2 * n)) + title.set_text(f'Phase separation of a binary BEC t = {solver.t:5.1f}') + writer.grab_frame(facecolor='#0b0b10') + plt.close(fig) + times, spin_rms, shell_amp, k_peak = map(np.array, (times, spin_rms, shell_amp, k_peak)) + lin = (shell_amp > 10 * shell_amp[0]) & (spin_rms < 1e-2) + gamma_fit = np.polyfit(times[lin], np.log(shell_amp[lin]), 1)[0] + k_lin = np.median(k_peak[lin]) + print(f' linear stage (t = {times[lin][0]:.0f}–{times[lin][-1]:.0f}): growth on the |k| ≈ k* shell {gamma_fit:.4f} ' + f'vs γ* = {gamma_star:.4f} ({100 * (gamma_fit / gamma_star - 1):+.2f}%); peak of the spin structure ' + f'factor at k = {k_lin:.3f} vs k* = {k_star:.3f} (bin width {grid.dk_x:.3f})') + print(f' late stage: domains coarsen, the structure-factor peak moves from {k_lin:.2f} to {k_peak[-1]:.2f} ' + f'by t = {times[-1]:.0f}') + print(f' populations conserved: relative drift {abs(state[0].norm() / norms0[0] - 1):.1e}, ' + f'{abs(state[1].norm() / norms0[1] - 1):.1e}') + + fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4)) + a1.semilogy(times, shell_amp, color='#ffb000', lw=1.8, label='simulation: spin mode on |k| ≈ k*') + # theory line anchored at the start of the fitted window and drawn beyond it + t_ref = times[times <= times[lin][-1] + 12] + a1.semilogy(t_ref, shell_amp[lin][0] * np.exp(gamma_star * (t_ref - times[lin][0])), '--', color='#7fd4ff', + lw=1.4, label=f'Bogoliubov e$^{{γ^* t}}$, γ* = {gamma_star:.2f}') + a1.axvspan(times[lin][0], times[lin][-1], color='#7fd4ff', alpha=0.08, label='fit window (linear stage)') + a1.set_xlabel('t') + a1.set_ylabel('amplitude (arb. units)') + a1.set_title('Exponential growth of the instability', fontweight='bold') + a1.legend(fontsize=8) + a2.plot(times, k_peak, color='#ffb000', lw=1.8, label='simulation: peak of the spin structure factor') + a2.axhline(k_star, color='#7fd4ff', ls='--', lw=1, label=f'fastest-growing k* = {k_star:.2f}') + a2.set_xlabel('t') + a2.set_ylabel('characteristic wavenumber') + a2.set_title('Domain size: selection, then coarsening', fontweight='bold') + a2.legend(fontsize=8) + fig.tight_layout() + fig.savefig('output/13_phase_separation_growth.png', dpi=150) + plt.close(fig) + return gamma_fit, gamma_star, k_lin, k_star + + +def part_c(): + print('\n[C] Rotating two-component condensate (g = 500, g12 = 0.5 g, Ω = 0.8, damping γ = 0.05)') + grid = Grid2D(128, -10.0, 10.0, 128, -10.0, 10.0) + g, delta, Om, gamma = 500.0, 0.5, 0.8, 0.05 + G = [[g, delta * g], [delta * g, g]] + eps_x, eps_y = 0.03, 0.09 + trap = HarmonicTrap((np.sqrt(1.0 + eps_x), np.sqrt(1.0 + eps_y))) + (s1, s2), info = coupled_ground_state(grid, (HarmonicTrap(1.0), HarmonicTrap(1.0)), G, + (displaced(grid, 0.2, 0.5), displaced(grid, -0.2, 0.5)), dtau=0.005) + print(f' non-rotating ground state: overlap Λ = {miscibility_overlap(s1, s2):.4f} (miscible, g12 < g)') + solver = CoupledGPESolver(grid, (trap, trap), G, 0.005, rotation=Om, damping=gamma) + extent = [grid.x[0], grid.x[-1], grid.y[0], grid.y[-1]] + fig, ax = plt.subplots(figsize=(6, 6.3)) + fig.patch.set_facecolor('#0b0b10') + vmax = max(s1.probability_density.max(), s2.probability_density.max()) + im = ax.imshow(two_colour(s1.probability_density, s2.probability_density, vmax), origin='lower', extent=extent) + ax.set_xlim(-8, 8) + ax.set_ylim(-8, 8) + ax.set_xticks([]) + ax.set_yticks([]) + title = ax.set_title('', fontsize=12, fontweight='bold') + writer = FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-crf', '20']) + state = (s1, s2) + with writer.saving(fig, 'output/13_vortex_lattices.mp4', dpi=100): + for k in range(161): + if k: + state = solver.evolve(state, 250) + im.set_data(two_colour(state[0].probability_density, state[1].probability_density, vmax)) + title.set_text(f'Two-component vortex lattices t = {solver.t:5.1f}') + writer.grab_frame(facecolor='#0b0b10') + if k % 40 == 0 and k: + n1v = len(vortex_positions(state[0])[0]) + n2v = len(vortex_positions(state[1])[0]) + print(f' t = {solver.t:5.1f}: vortices {n1v} + {n2v}, ' + f'⟨L_z⟩ = {angular_momentum_z_expectation(state[0]):.2f} + {angular_momentum_z_expectation(state[1]):.2f}') + plt.close(fig) + + s1, s2 = state + p1, q1 = vortex_positions(s1) + p2, q2 = vortex_positions(s2) + n1, n2 = s1.probability_density, s2.probability_density + + def relative_density_at(points, n): + """Density at the given points relative to its local average (smoothing 1.5).""" + smooth = gaussian_filter(n, 1.5 / grid.dx) + i = np.clip(np.searchsorted(grid.x, points[:, 0]), 0, grid.N_x - 1) + j = np.clip(np.searchsorted(grid.y, points[:, 1]), 0, grid.N_y - 1) + return n[i, j] / smooth[i, j] + + r12 = relative_density_at(p1, n2) # density of 2 at the cores of 1 + r21 = relative_density_at(p2, n1) + print(f' final: {len(p1)} + {len(p2)} vortices (charges {sorted(set(q1.tolist()) | set(q2.tolist()))})') + print(f' interlacing: at the vortex cores of one component the other component\'s density is ' + f'{np.median(r12):.2f}× / {np.median(r21):.2f}× its local average (median); ' + f'{100 * np.mean(r12 > 1):.0f}% / {100 * np.mean(r21 > 1):.0f}% of cores sit on a density maximum (> 1×)') + d_same, _ = cKDTree(p1).query(p1, k=2) + d_cross, _ = cKDTree(p2).query(p1, k=1) + print(f' nearest same-component vortex {np.median(d_same[:, 1]):.2f}, nearest other-component vortex ' + f'{np.median(d_cross):.2f} (interlaced: ≈ half the same-component spacing or more)') + + fig, axes = plt.subplots(1, 3, figsize=(13, 4.6)) + for ax, img, ttl in ((axes[0], two_colour(n1, 0 * n2, vmax), 'component 1'), + (axes[1], two_colour(0 * n1, n2, vmax), 'component 2'), + (axes[2], two_colour(n1, n2, vmax), 'both: interlaced lattices')): + ax.imshow(img, origin='lower', extent=extent) + ax.set_xlim(-7.5, 7.5) + ax.set_ylim(-7.5, 7.5) + ax.set_title(ttl, fontweight='bold') + ax.set_xticks([]) + ax.set_yticks([]) + axes[2].scatter(p1[:, 0], p1[:, 1], s=14, facecolors='none', edgecolors=COLOUR_A, linewidths=1) + axes[2].scatter(p2[:, 0], p2[:, 1], s=14, facecolors='none', edgecolors=COLOUR_B, linewidths=1) + fig.suptitle('Rotating two-component BEC: the vortices of each component fill the other\'s density peaks', + fontweight='bold') + fig.tight_layout() + fig.savefig('output/13_vortex_lattices.png', dpi=150) + plt.close(fig) + return r12, r21 + + +def main(): + if hasattr(sys.stdout, 'reconfigure'): + sys.stdout.reconfigure(encoding='utf-8') + os.makedirs('output', exist_ok=True) + set_style('dark') + print('--- Example 13: two-component Bose–Einstein condensates ---') + parts = {a.upper() for a in sys.argv[1:]} or {'A', 'B', 'C'} + if 'A' in parts: + part_a() + if 'B' in parts: + part_b() + if 'C' in parts: + part_c() + print('\nSaved: output/13_miscibility.png, 13_phase_separation.mp4, 13_phase_separation_growth.png, ' + '13_vortex_lattices.mp4, 13_vortex_lattices.png') + + +if __name__ == '__main__': + main() diff --git a/images/13_miscibility.png b/images/13_miscibility.png new file mode 100644 index 0000000..979bd98 Binary files /dev/null and b/images/13_miscibility.png differ diff --git a/images/13_phase_separation.gif b/images/13_phase_separation.gif new file mode 100644 index 0000000..f9fbdb2 Binary files /dev/null and b/images/13_phase_separation.gif differ diff --git a/images/13_phase_separation_growth.png b/images/13_phase_separation_growth.png new file mode 100644 index 0000000..c660bbf Binary files /dev/null and b/images/13_phase_separation_growth.png differ diff --git a/images/13_vortex_lattices.gif b/images/13_vortex_lattices.gif new file mode 100644 index 0000000..8cb26fa Binary files /dev/null and b/images/13_vortex_lattices.gif differ diff --git a/images/13_vortex_lattices.png b/images/13_vortex_lattices.png new file mode 100644 index 0000000..8d0ef5b Binary files /dev/null and b/images/13_vortex_lattices.png differ diff --git a/mkdocs.yml b/mkdocs.yml index 96e3e21..46d58c8 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -80,6 +80,7 @@ nav: - Potentials: guide/potentials.md - Observables: guide/observables.md - Visualization: guide/visualization.md + - Two-component condensates: guide/multicomponent.md - Strong-field physics: guide/strongfield.md - GPU acceleration: guide/gpu.md - YAML batch runner: guide/runner.md diff --git a/quantumlab/observables/__init__.py b/quantumlab/observables/__init__.py index 0b6ccba..04a36bd 100644 --- a/quantumlab/observables/__init__.py +++ b/quantumlab/observables/__init__.py @@ -1,6 +1,7 @@ from quantumlab.observables.expectation import position_expectation, position_squared_expectation, position_uncertainty, y_expectation, y_squared_expectation, y_uncertainty, z_expectation, z_squared_expectation, z_uncertainty, momentum_expectation, momentum_squared_expectation, momentum_uncertainty, potential_energy_expectation, kinetic_energy_expectation, total_energy_expectation from quantumlab.observables.coefficients import transmission_coefficient, reflection_coefficient from quantumlab.observables.momentum import get_momentum_wavefunction, get_momentum_probability_density -from quantumlab.observables.nonlinear import interaction_energy, gross_pitaevskii_energy, chemical_potential +from quantumlab.observables.nonlinear import (interaction_energy, gross_pitaevskii_energy, chemical_potential, + coupled_gp_energy, miscibility_overlap) from quantumlab.observables.current import gradient, probability_current, angular_momentum_z_expectation, autocorrelation, vortex_positions -__all__ = ['position_expectation', 'position_squared_expectation', 'position_uncertainty', 'y_expectation', 'y_squared_expectation', 'y_uncertainty', 'z_expectation', 'z_squared_expectation', 'z_uncertainty', 'momentum_expectation', 'momentum_squared_expectation', 'momentum_uncertainty', 'potential_energy_expectation', 'kinetic_energy_expectation', 'total_energy_expectation', 'transmission_coefficient', 'reflection_coefficient', 'get_momentum_wavefunction', 'get_momentum_probability_density', 'interaction_energy', 'gross_pitaevskii_energy', 'chemical_potential', 'gradient', 'probability_current', 'angular_momentum_z_expectation', 'autocorrelation', 'vortex_positions'] +__all__ = ['position_expectation', 'position_squared_expectation', 'position_uncertainty', 'y_expectation', 'y_squared_expectation', 'y_uncertainty', 'z_expectation', 'z_squared_expectation', 'z_uncertainty', 'momentum_expectation', 'momentum_squared_expectation', 'momentum_uncertainty', 'potential_energy_expectation', 'kinetic_energy_expectation', 'total_energy_expectation', 'transmission_coefficient', 'reflection_coefficient', 'get_momentum_wavefunction', 'get_momentum_probability_density', 'interaction_energy', 'gross_pitaevskii_energy', 'chemical_potential', 'coupled_gp_energy', 'miscibility_overlap', 'gradient', 'probability_current', 'angular_momentum_z_expectation', 'autocorrelation', 'vortex_positions'] diff --git a/quantumlab/observables/nonlinear.py b/quantumlab/observables/nonlinear.py index 9f0fe3f..df4ed98 100644 --- a/quantumlab/observables/nonlinear.py +++ b/quantumlab/observables/nonlinear.py @@ -18,3 +18,27 @@ def chemical_potential(wf, potential, nonlinearity: float, hbar: float = 1.0, m: """μ = ⟨T⟩ + ⟨V⟩ + g∫|ψ|⁴, the eigenvalue of the stationary GP equation.""" return float(kinetic_energy_expectation(wf, hbar, m) + potential_energy_expectation(wf, potential) + 2.0 * interaction_energy(wf, nonlinearity)) + + +def coupled_gp_energy(states, potentials, couplings, hbar: float = 1.0, m: float = 1.0) -> float: + """ + Energy functional of a multi-component condensate, + E = Σ_i (⟨T⟩_i + ⟨V_i⟩) + ½ Σ_ij g_ij ∫ n_i n_j dV, with n_i = |ψ_i|². + """ + g = np.asarray(couplings, dtype=float) + dV = volume_element(states[0].grid) + E = sum(kinetic_energy_expectation(s, hbar, m) + potential_energy_expectation(s, p) + for s, p in zip(states, potentials)) + n = [s.probability_density for s in states] + E += 0.5 * sum(g[i, j] * float(np.sum(n[i] * n[j]) * dV) + for i in range(len(states)) for j in range(len(states))) + return float(E) + + +def miscibility_overlap(wf_a, wf_b) -> float: + """ + Spatial overlap Λ = ∫ n_a n_b / sqrt(∫ n_a² ∫ n_b²) of two components: + 1 for identical density profiles, → 0 for fully separated ones. + """ + na, nb = wf_a.probability_density, wf_b.probability_density + return float(np.sum(na * nb) / np.sqrt(np.sum(na ** 2) * np.sum(nb ** 2))) diff --git a/quantumlab/solvers/multicomponent.py b/quantumlab/solvers/multicomponent.py new file mode 100644 index 0000000..0dbf3cf --- /dev/null +++ b/quantumlab/solvers/multicomponent.py @@ -0,0 +1,144 @@ +""" +Coupled Gross–Pitaevskii equations for multi-component condensates +(e.g. two hyperfine states of ⁸⁷Rb, or two atomic species of equal mass): + + iℏ ∂ψ_i/∂t = [ −ℏ²∇²/2m + V_i(r) + Σ_j g_ij |ψ_j|² − ΩL_z ] ψ_i + +The kinetic (and rotation) factor is the one of ``SplitOperatorSolver`` and is +applied to every component. The potential sub-flow is local and, in real +time, leaves every |ψ_j| unchanged, so it is integrated exactly with the +densities frozen. In imaginary time or with damping each component keeps its +own norm N_i (the populations are fixed), and the coupled potential uses the +densities rescaled to those norms at the sub-step midpoint, as for a single +component, which keeps the converged states 2nd-order accurate in dτ. +""" +from typing import Sequence +import numpy as np +from quantumlab.solvers.split_operator import SplitOperatorSolver +from quantumlab.core.spectral import volume_element, wavefunction_class + + +class CoupledGPESolver: + """ + Parameters + ---------- + grid : Grid1D, Grid2D or Grid3D + potentials : sequence of Potential or None + One static potential per component (None means free space). + couplings : (n, n) array_like + Symmetric interaction matrix g_ij. The nonlinear term uses the actual + densities |ψ_j|², so g_ij is per particle when ψ_j is normalised to + its particle number. + dt : float + Time step (dτ in imaginary time). + order, imaginary_time, rotation, damping, workers, backend, device_id, t0 + As in ``SplitOperatorSolver``; they apply to all components. + """ + + def __init__(self, grid, potentials: Sequence, couplings, dt: float, hbar: float = 1.0, + m: float = 1.0, order: int = 2, imaginary_time: bool = False, rotation: float = 0.0, + damping: float = 0.0, workers: int = -1, backend='numpy', device_id: int = 0, + t0: float = 0.0): + self.n_components = len(potentials) + g = np.asarray(couplings, dtype=float) + if g.shape != (self.n_components, self.n_components): + raise ValueError(f'couplings must be a {self.n_components}×{self.n_components} matrix') + if not np.allclose(g, g.T): + raise ValueError('couplings must be symmetric (g_ij = g_ji)') + if any(getattr(p, 'time_dependent', False) for p in potentials): + raise ValueError('CoupledGPESolver supports static potentials only') + self.grid = grid + self.potentials = list(potentials) + self.couplings = g + self.dt = dt + self.hbar = hbar + self.m = m + self.t0 = t0 + self.steps_taken = 0 + # The single-component engine supplies the kinetic/rotation propagators, + # the time-stepping constant c, the substep weights and the array backend. + self._engine = SplitOperatorSolver(grid, None, dt, hbar, m, order=order, imaginary_time=imaginary_time, + rotation=rotation, damping=damping, workers=workers, + backend=backend, device_id=device_id, t0=t0) + self._be = self._engine._be + self._xp = self._be.xp + self._c = self._engine._c + self._renormalise = self._engine._renormalise + self._substeps = self._engine._substeps + self._dV = volume_element(grid) + self._wf_class = wavefunction_class(grid) + self._V = [self._be.to_device(np.zeros(grid.shape) if p is None else + np.asarray(p.evaluate(grid), dtype=float)) for p in self.potentials] + + @property + def t(self) -> float: + return self.t0 + self.steps_taken * self.dt + + @property + def backend(self) -> str: + return self._be.name + + def _densities(self, psis, rescale: bool): + xp = self._xp + rhos = [p.real ** 2 + p.imag ** 2 for p in psis] + if rescale: + rhos = [r * (n / (float(xp.sum(r)) * self._dV)) for r, n in zip(rhos, self._targets)] + return rhos + + def _effective_potentials(self, rhos): + g = self.couplings + return [self._V[i] + sum(g[i, j] * rhos[j] for j in range(self.n_components) if g[i, j] != 0.0) + for i in range(self.n_components)] + + def _potential_half_step(self, psis, w): + xp = self._xp + h = w * self.dt + if not self._renormalise: + V_eff = self._effective_potentials(self._densities(psis, rescale=False)) + return [p * xp.exp(self._c * V * h / (2.0 * self.hbar)) for p, V in zip(psis, V_eff)] + V_eff = self._effective_potentials(self._densities(psis, rescale=True)) + mids = [p * xp.exp(self._c * V * h / (4.0 * self.hbar)) for p, V in zip(psis, V_eff)] + V_mid = self._effective_potentials(self._densities(mids, rescale=True)) + return [p * xp.exp(self._c * V * h / (2.0 * self.hbar)) for p, V in zip(psis, V_mid)] + + def _norm(self, psi) -> float: + return float(self._xp.sum(psi.real ** 2 + psi.imag ** 2)) * self._dV + + def _advance(self, psis): + if self._renormalise: + self._targets = [self._norm(p) for p in psis] + for w in self._substeps: + psis = self._potential_half_step(psis, w) + psis = [self._engine._kinetic_step(p, w) for p in psis] + psis = self._potential_half_step(psis, w) + if self._renormalise: + out = [] + for p, target in zip(psis, self._targets): + norm = self._norm(p) + out.append(p * np.sqrt(target / norm) if norm > 0 else p) + psis = out + self.steps_taken += 1 + return psis + + def _upload(self, states): + if len(states) != self.n_components: + raise ValueError(f'expected {self.n_components} wavefunctions') + return [self._be.to_device(np.array(s.psi, dtype=complex)) for s in states] + + def _download(self, psis): + return tuple(self._wf_class(self.grid, self._be.to_host(p)) for p in psis) + + def step(self, states): + return self._download(self._advance(self._upload(states))) + + def evolve(self, states, n_steps: int, callback=None, callback_interval: int = 1): + """ + Advance all components ``n_steps`` steps; ``callback(step, t, states)`` + is called every ``callback_interval`` steps with a tuple of wavefunctions. + """ + psis = self._upload(states) + for n in range(1, n_steps + 1): + psis = self._advance(psis) + if callback is not None and n % callback_interval == 0: + callback(n, self.t, self._download(psis)) + return self._download(psis) diff --git a/quantumlab/solvers/split_operator.py b/quantumlab/solvers/split_operator.py index f7466a8..922fa9f 100644 --- a/quantumlab/solvers/split_operator.py +++ b/quantumlab/solvers/split_operator.py @@ -82,6 +82,17 @@ class SplitOperatorSolver(Solver): device at every sub-step. device_id : int CUDA device for the 'cupy' backend. + + Notes + ----- + Every factor is unitary, but for nonlinear problems on a uniform (or + broad) background the split-step method has a parametric numerical + instability when the kinetic phase of the highest grid wavenumber per + (sub)step exceeds π (Weideman & Herbst, SIAM J. Numer. Anal. 23, 485 + (1986)). Keep ``ℏ k_max² / (2m) · |w| dt < π`` with k_max = π/dx, where + |w| ≤ 1.71 for order 4, otherwise round-off noise in the shortest + wavelengths can grow exponentially. Localised states (solitons, trapped + condensates) are much less sensitive. """ def __init__(self, grid, potential, dt: float, hbar: float = 1.0, m: float = 1.0, diff --git a/quantumlab/stationary/__init__.py b/quantumlab/stationary/__init__.py index 7920f70..fc46cb8 100644 --- a/quantumlab/stationary/__init__.py +++ b/quantumlab/stationary/__init__.py @@ -1,5 +1,7 @@ from quantumlab.stationary.eigensolver import eigenstates -from quantumlab.stationary.imaginary_time import ground_state, excited_states, ConvergenceInfo +from quantumlab.stationary.imaginary_time import (ground_state, excited_states, ConvergenceInfo, + coupled_ground_state, CoupledConvergenceInfo) from quantumlab.stationary.hamiltonian import apply_hamiltonian -__all__ = ['eigenstates', 'ground_state', 'excited_states', 'ConvergenceInfo', 'apply_hamiltonian'] +__all__ = ['eigenstates', 'ground_state', 'excited_states', 'ConvergenceInfo', 'apply_hamiltonian', + 'coupled_ground_state', 'CoupledConvergenceInfo'] diff --git a/quantumlab/stationary/imaginary_time.py b/quantumlab/stationary/imaginary_time.py index 99ae76c..114c895 100644 --- a/quantumlab/stationary/imaginary_time.py +++ b/quantumlab/stationary/imaginary_time.py @@ -151,3 +151,73 @@ def excited_states(grid, potential, n_states: int, dtau: float = 0.01, tol: floa energies.append(info.energy) infos.append(info) return np.array(energies), states, infos + + +@dataclass +class CoupledConvergenceInfo: + converged: bool + steps: int + energy: float + chemical_potentials: List[float] + residuals: List[float] + + +def _coupled_energy_mu(psis, grid, Vs, g, hbar, m, rotation, dV): + n = [np.abs(p) ** 2 for p in psis] + energy, mus, residuals = 0.0, [], [] + for i, p in enumerate(psis): + N = float(np.sum(n[i]) * dV) + H_lin = apply_hamiltonian(p, grid, Vs[i], hbar, m, rotation=rotation) + energy += float(np.real(_inner(p, H_lin, dV))) + H_psi = H_lin + sum(g[i, j] * n[j] for j in range(len(psis))) * p + mu = float(np.real(_inner(p, H_psi, dV))) / N + mus.append(mu) + residuals.append(float(np.sqrt(np.sum(np.abs(H_psi - mu * p) ** 2) * dV / N))) + energy += 0.5 * sum(g[i, j] * float(np.sum(n[i] * n[j]) * dV) + for i in range(len(psis)) for j in range(len(psis))) + return energy, mus, residuals + + +def coupled_ground_state(grid, potentials, couplings, initial, dtau: float = 0.005, tol: float = 1e-11, + max_steps: int = 50000, check_interval: int = 20, hbar: float = 1.0, + m: float = 1.0, rotation: float = 0.0, backend='numpy', workers: int = -1): + """ + Lowest-energy state of coupled Gross–Pitaevskii equations by imaginary + time, at fixed populations N_i given by the norms of ``initial``. + + Parameters + ---------- + initial : sequence of WaveFunction or ndarray + One starting state per component. For immiscible mixtures the guess + should break the symmetry between the components (e.g. displaced + clouds); a symmetric guess can stay on a symmetric saddle point. + + Returns + ------- + states : tuple of WaveFunction + info : CoupledConvergenceInfo + ``energy`` is the total energy functional (of H − ΩL_z when rotating), + ``chemical_potentials`` and ``residuals`` (‖H_iψ_i − μ_iψ_i‖/√N_i) are + per component. + """ + from quantumlab.solvers.multicomponent import CoupledGPESolver + g = np.asarray(couplings, dtype=float) + solver = CoupledGPESolver(grid, potentials, g, dtau, hbar, m, order=2, imaginary_time=True, + rotation=rotation, backend=backend, workers=workers) + dV = volume_element(grid) + wf_class = wavefunction_class(grid) + Vs = [np.zeros(grid.shape) if p is None else np.asarray(p.evaluate(grid), dtype=float) for p in potentials] + states = tuple(wf_class(grid, np.array(getattr(s, 'psi', s), dtype=complex)) for s in initial) + energy_prev = np.inf + converged = False + steps = 0 + while steps < max_steps: + states = solver.evolve(states, check_interval) + steps += check_interval + energy, _, _ = _coupled_energy_mu([s.psi for s in states], grid, Vs, g, hbar, m, rotation, dV) + if abs(energy - energy_prev) < tol: + converged = True + break + energy_prev = energy + energy, mus, residuals = _coupled_energy_mu([s.psi for s in states], grid, Vs, g, hbar, m, rotation, dV) + return states, CoupledConvergenceInfo(converged, steps, energy, mus, residuals) diff --git a/tests/test_backends.py b/tests/test_backends.py index 88fcee8..2fa5662 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -163,3 +163,19 @@ def test_real_cupy_matches_cpu(kwargs): gpu = gpu_solver.evolve(wf0, 50) assert gpu_solver.backend == 'cupy' np.testing.assert_allclose(gpu.psi, cpu.psi, atol=1e-11) + + +def test_coupled_solver_device_path_matches_numpy(): + from quantumlab.solvers.multicomponent import CoupledGPESolver + grid = Grid2D(40, -7.0, 7.0, 40, -7.0, 7.0) + a = WaveFunction2D.gaussian(grid, 1.0, 0.0, 0.3, 0.0, 1.0, 1.0) + b = WaveFunction2D.gaussian(grid, -1.0, 0.0, 0.0, 0.2, 1.0, 1.0) + G = [[50.0, 30.0], [30.0, 60.0]] + for kwargs in (dict(order=4, rotation=0.4), dict(damping=0.05, rotation=0.6), dict(imaginary_time=True)): + backend, calls = _strict_backend() + ref = CoupledGPESolver(grid, (HarmonicTrap(1.0), HarmonicTrap(1.2)), G, 0.01, **kwargs).evolve((a, b), 25) + dev = CoupledGPESolver(grid, (HarmonicTrap(1.0), HarmonicTrap(1.2)), G, 0.01, backend=backend, + **kwargs).evolve((a, b), 25) + for r, d in zip(ref, dev): + np.testing.assert_allclose(d.psi, r.psi, atol=1e-13) + assert calls['to_host'] == 2 # one copy back per component, at the end diff --git a/tests/test_multicomponent.py b/tests/test_multicomponent.py new file mode 100644 index 0000000..8ff1ae1 --- /dev/null +++ b/tests/test_multicomponent.py @@ -0,0 +1,140 @@ +import numpy as np +import pytest +from quantumlab.core.grid import Grid1D, Grid2D +from quantumlab.core.wavefunction import WaveFunction1D, WaveFunction2D +from quantumlab.potentials import HarmonicTrap, DipoleDrive +from quantumlab.solvers.split_operator import SplitOperatorSolver +from quantumlab.solvers.multicomponent import CoupledGPESolver +from quantumlab.stationary import ground_state, coupled_ground_state +from quantumlab.observables import ( + coupled_gp_energy, miscibility_overlap, kinetic_energy_expectation, potential_energy_expectation, +) + + +def _gauss2d(grid, x0, y0=0.0, norm=1.0, kx=0.0, ky=0.0, s=1.0): + wf = WaveFunction2D.gaussian(grid, x0, y0, kx, ky, s, s) + wf.psi *= np.sqrt(norm) + return wf + + +def test_uncoupled_components_match_independent_solvers(): + grid = Grid2D(48, -7.0, 7.0, 48, -7.0, 7.0) + t1, t2 = HarmonicTrap((1.0, 1.2)), HarmonicTrap((1.3, 0.9)) + a = _gauss2d(grid, 0.5, kx=0.3) + b = _gauss2d(grid, -0.4, 0.2, norm=0.7, ky=0.2) + c = CoupledGPESolver(grid, (t1, t2), [[20.0, 0.0], [0.0, 35.0]], 0.01, order=4, rotation=0.3).evolve((a, b), 60) + r1 = SplitOperatorSolver(grid, t1, 0.01, order=4, nonlinearity=20.0, rotation=0.3).evolve(a, 60) + r2 = SplitOperatorSolver(grid, t2, 0.01, order=4, nonlinearity=35.0, rotation=0.3).evolve(b, 60) + np.testing.assert_allclose(c[0].psi, r1.psi, atol=1e-13) + np.testing.assert_allclose(c[1].psi, r2.psi, atol=1e-13) + + +def test_manakov_point_total_density_equals_single_component(): + """For g11 = g22 = g12 = g the total density obeys the one-component GP equation.""" + grid = Grid2D(64, -8.0, 8.0, 64, -8.0, 8.0) + trap, g = HarmonicTrap((1.0, 1.3)), 60.0 + (s1, s2), info = coupled_ground_state(grid, (trap, trap), [[g, g], [g, g]], + (_gauss2d(grid, 1.0, norm=0.3), _gauss2d(grid, -1.0, 0.5, norm=0.7)), + dtau=0.005) + single, _ = ground_state(grid, trap, dtau=0.005, nonlinearity=g) + assert info.converged + np.testing.assert_allclose(s1.probability_density + s2.probability_density, single.probability_density, + atol=1e-6) + assert info.chemical_potentials[0] == pytest.approx(info.chemical_potentials[1], rel=1e-6) + assert (s1.norm(), s2.norm()) == (pytest.approx(0.3, abs=1e-12), pytest.approx(0.7, abs=1e-12)) + + +@pytest.fixture +def box(): + return Grid1D(256, -20 * np.pi, 20 * np.pi) # periodic, dk = 0.05 + + +def _spin_seeded(grid, k, n=1.0, eps=1e-6): + return (WaveFunction1D(grid, np.sqrt(n) * (1 + eps * np.cos(k * grid.x)) + 0j), + WaveFunction1D(grid, np.sqrt(n) * (1 - eps * np.cos(k * grid.x)) + 0j)) + + +def _spin_amplitude(states, k): + s = states[0].probability_density - states[1].probability_density + return float(np.sum(s * np.cos(k * states[0].grid.x)) * 2 / len(s)) + + +@pytest.mark.parametrize('g12, kk', [(0.6, 10), (0.3, 25)]) +def test_bogoliubov_spin_mode_frequency(box, g12, kk): + """Miscible mixture: δ(n1−n2) ∝ cos(ω_s t), ω_s = √(ε_k(ε_k + 2n(g − g12))).""" + n, g, dt = 1.0, 1.0, 0.01 + k = box.dk * kk + ek = k ** 2 / 2 + omega = np.sqrt(ek * (ek + 2 * n * (g - g12))) + solver = CoupledGPESolver(box, (None, None), [[g, g12], [g12, g]], dt, order=4) + state = _spin_seeded(box, k) + for _ in range(6): + state = solver.evolve(state, 500) + assert _spin_amplitude(state, k) == pytest.approx(4e-6 * np.cos(omega * solver.t), abs=1e-12) + + +@pytest.mark.parametrize('g12', [1.1, 1.5]) +def test_phase_separation_growth_rate(box, g12): + """Immiscible mixture: the spin mode at k* grows as exp(γt), γ = n(g12 − g).""" + n, g, dt = 1.0, 1.0, 0.01 + k = box.dk * np.round(np.sqrt(2 * n * (g12 - g)) / box.dk) + ek = k ** 2 / 2 + gamma = np.sqrt(ek * (2 * n * (g12 - g) - ek)) + solver = CoupledGPESolver(box, (None, None), [[g, g12], [g12, g]], dt, order=4) + state = _spin_seeded(box, k) + t, amp = [], [] + while not amp or abs(amp[-1]) < 1e-3: + state = solver.evolve(state, 100) + t.append(solver.t) + amp.append(abs(_spin_amplitude(state, k))) + t, amp = np.array(t), np.array(amp) + m = amp > 30 * 4e-6 + assert np.polyfit(t[m], np.log(amp[m]), 1)[0] == pytest.approx(gamma, rel=1e-3) + + +def test_energy_and_populations_conserved_in_real_time(): + grid = Grid2D(64, -8.0, 8.0, 64, -8.0, 8.0) + traps = (HarmonicTrap((1.0, 1.1)), HarmonicTrap((1.05, 0.95), center=(0.3, 0.0))) + G = [[100.0, 70.0], [70.0, 100.0]] + state = (_gauss2d(grid, 1.0, norm=0.5, kx=0.4), _gauss2d(grid, -1.0, norm=0.5, ky=-0.3)) + E0 = coupled_gp_energy(state, traps, G) + out = CoupledGPESolver(grid, traps, G, 0.005, order=4).evolve(state, 300) + assert coupled_gp_energy(out, traps, G) == pytest.approx(E0, rel=1e-9) + assert out[0].norm() == pytest.approx(0.5, abs=1e-12) + assert out[1].norm() == pytest.approx(0.5, abs=1e-12) + + +def test_coupled_virial_theorem(): + """Stationary states in harmonic traps obey 2⟨T⟩ − 2⟨V⟩ + d·E_int = 0 (total, all components).""" + grid = Grid2D(80, -9.0, 9.0, 80, -9.0, 9.0) + trap = HarmonicTrap(1.0) + G = np.array([[100.0, 70.0], [70.0, 120.0]]) + states, info = coupled_ground_state(grid, (trap, trap), G, (_gauss2d(grid, 1.5, norm=0.5), _gauss2d(grid, -1.5, norm=0.5)), + dtau=0.005) + T = sum(kinetic_energy_expectation(s) for s in states) + V = sum(potential_energy_expectation(s, trap) for s in states) + n = [s.probability_density for s in states] + E_int = 0.5 * sum(G[i, j] * np.sum(n[i] * n[j]) for i in range(2) for j in range(2)) * grid.dx * grid.dy + assert info.converged + assert abs(2 * T - 2 * V + 2 * E_int) / V < 1e-4 + + +def test_miscibility_overlap(): + grid = Grid2D(64, -8.0, 8.0, 64, -8.0, 8.0) + a = _gauss2d(grid, 0.0) + assert miscibility_overlap(a, a) == pytest.approx(1.0) + far = _gauss2d(grid, 5.0) + assert miscibility_overlap(_gauss2d(grid, -5.0), far) < 1e-6 + + +def test_invalid_coupled_configurations(): + grid = Grid1D(32, -4.0, 4.0) + with pytest.raises(ValueError): + CoupledGPESolver(grid, (None, None), [[1.0, 0.5], [0.4, 1.0]], 0.01) # not symmetric + with pytest.raises(ValueError): + CoupledGPESolver(grid, (None, None), [[1.0]], 0.01) # wrong shape + with pytest.raises(ValueError): + CoupledGPESolver(grid, (DipoleDrive(None, 1.0, 1.0), None), np.eye(2), 0.01) + solver = CoupledGPESolver(grid, (None, None), np.eye(2), 0.01) + with pytest.raises(ValueError): + solver.step((WaveFunction1D.gaussian(grid, 0.0, 0.0, 1.0),))