diff --git a/CHANGELOG.md b/CHANGELOG.md index 01c6d90..c63e2d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ - Absorbers: `ManolopoulosAbsorber1d` (transmission-free), `PowerAbsorber1d` and `MaskAbsorber1d` (cos^(1/8) mask), and a notebook that measures reflection and transmission of the absorbers versus energy. +- `LimaconPotential2d`: billiard or dielectric cavity shaped like Pascal's + limaçon, with `LimaconPotential2d.dielectric(R, eps, n, E)` for the optical + analogy. +- `FarField` analyzer: the far field of a cavity or scatterer, from the time + integrated momentum distribution of the wave in a ring around it. It is an + `IntegratedDensity`, which subclasses can now reuse for other densities. - New notebooks: double slit in 2d; double well with Rabi oscillations and coherent destruction of tunneling; dynamical localization in the kicked rotor. diff --git a/so_schroedinger/analyzers.py b/so_schroedinger/analyzers.py index 14e689e..31e51e3 100644 --- a/so_schroedinger/analyzers.py +++ b/so_schroedinger/analyzers.py @@ -10,14 +10,16 @@ >>> prop.propagate(grid, dt, n_steps, callback=obs, every=10) >>> obs.t, obs.position -All analyzers except ``Wigner`` and ``Husimi`` (1d only) work on 1d and 2d grids. Time integrals use the trapezoidal -rule on the sample times, which need not be equidistant (except for +All analyzers except ``Wigner``, ``Husimi`` (1d only) and ``FarField`` (2d +only) work on 1d and 2d grids. Time integrals use the trapezoidal rule on the +sample times, which need not be equidistant (except for ``AutoCorrelation.spectrum()``). Analyzers copy what they need, so the grid may change after each call. None of them plots or prints anything. """ import numpy as np from scipy.integrate import cumulative_trapezoid, trapezoid +from scipy.interpolate import RegularGridInterpolator from scipy.signal import get_window from .phasespace import husimi, wigner @@ -30,6 +32,7 @@ "EigenstateFilter", "EigenfunctionBuilder", "IntegratedDensity", + "FarField", "Flux", "Wigner", "Husimi", @@ -327,16 +330,22 @@ class IntegratedDensity(Analyzer): r"""Time integrated density $\int |\psi(\mathbf{r}, t)|^2\,\mathrm{d}t$. Shows where a wave has been, e.g. the branches of branched flow. + Subclasses integrate other densities by overriding ``_density(grid)``. """ def __init__(self): self._acc = None self._trapezoid = _Trapezoid() + def _density(self, grid): + """The density to integrate, from the grid at its current time.""" + return grid.density + def add_data(self, grid): + rho = self._density(grid) if self._acc is None: - self._acc = np.zeros(np.shape(grid.psi)) - done = self._trapezoid.push(grid.t, grid.density) + self._acc = np.zeros(np.shape(rho)) + done = self._trapezoid.push(grid.t, rho) if done is not None: self._acc += done[2] * done[1] @@ -349,6 +358,89 @@ def density(self): return self._acc if last is None else self._acc + last[2] * last[1] +class FarField(IntegratedDensity): + r"""Far field of the waves emitted by a cavity or scatterer at ``center``. + 2d only. + + Far from its source, a wave moves along its momentum, so the far field + is the distribution of the momentum directions of the emitted wave. + The analyzer takes the wave in a ring $r_\mathrm{min} < |\mathbf{r} - + \mathbf{r}_c| < r_\mathrm{max}$ (with edges smoothed over ``edge``), + which excludes the source, Fourier transforms it and integrates the + momentum density $|\tilde\psi(\mathbf{k}, t)|^2$ over time. Every part + of the emitted wave crosses the ring once, in the same time for every + direction, so + + $$I(\varphi) = \int_{k_\mathrm{min}}^{k_\mathrm{max}} \int + |\tilde\psi(k\cos\varphi, k\sin\varphi, t)|^2\,\mathrm{d}t\;k\,\mathrm{d}k$$ + + is proportional to the probability emitted per angle $\varphi$. The + time integrated momentum density itself is in ``density``, on the + momenta ``(grid.kx_vals, grid.ky_vals)`` in FFT order. + + The ring should start a few wavelengths outside the source, so that + evanescent fields are excluded, end inside the absorber, and be wide + enough to resolve the angles: its width $\Delta r$ blurs them by about + $1/(k\Delta r)$. The propagation should last until the emission has + passed the ring. Waves reflected back from the absorber are counted as + well. + + Parameters + ---------- + r_min, r_max : float + Radii of the ring. + center : tuple of float, optional + Center $\mathbf{r}_c$ of the ring. + k_range : tuple of float, optional + Range of $|\mathbf{k}|$ in $I(\varphi)$, e.g. around the wavenumber + of an emitting mode. Defaults to all momenta on the grid. + n_angles : int, optional + Number of angles $\varphi$ on $[-\pi, \pi)$. + edge : float, optional + Width of the smoothed edges; defaults to an eighth of the ring + width. + """ + + def __init__(self, r_min, r_max, center=(0.0, 0.0), k_range=None, n_angles=360, edge=None): + super().__init__() + self.r_min, self.r_max = float(r_min), float(r_max) + self.center = (float(center[0]), float(center[1])) + self.k_range = k_range + self.n_angles = int(n_angles) + self.edge = (self.r_max - self.r_min) / 8 if edge is None else float(edge) + self._window = None + self._k = None + + def _density(self, grid): + if grid.dim != 2: + raise ValueError(f"{type(self).__name__} works on 2d grids only") + if self._window is None: + r = np.hypot(grid.X - self.center[0], grid.Y - self.center[1]) + self._window = (1 + np.tanh((r - self.r_min) / self.edge)) * (1 - np.tanh((r - self.r_max) / self.edge)) / 4 + self._k = (grid.kx_vals, grid.ky_vals) + self._norm = grid.dV**2 / (4 * np.pi**2) # psi(k) = dV/(2 pi) sum_r psi(r) exp(-ikr) + return np.abs(np.fft.fft2(self._window * grid.psi)) ** 2 * self._norm + + @property + def angles(self): + r"""The angles $\varphi$, in $[-\pi, \pi)$.""" + return -np.pi + np.arange(self.n_angles) * 2 * np.pi / self.n_angles + + @property + def intensity(self): + r"""$I(\varphi)$ at ``angles``.""" + rho = np.fft.fftshift(self.density) + kx, ky = np.fft.fftshift(self._k[0]), np.fft.fftshift(self._k[1]) + k_max = min(-kx[0], -ky[0]) + k_min, k_max = (0.0, k_max) if self.k_range is None else self.k_range + dk = min(kx[1] - kx[0], ky[1] - ky[0]) / 2 + k = np.arange(k_min + dk / 2, k_max, dk) + phi = self.angles + interp = RegularGridInterpolator((kx, ky), rho, bounds_error=False, fill_value=0.0) + points = np.stack(np.broadcast_arrays(k[None, :] * np.cos(phi[:, None]), k[None, :] * np.sin(phi[:, None])), -1) + return np.sum(interp(points) * k, axis=1) * dk + + class Flux(Analyzer): r"""Probability flux through a point (1d) or a line (2d). diff --git a/so_schroedinger/potentials.py b/so_schroedinger/potentials.py index 27a4ba9..e7557fd 100644 --- a/so_schroedinger/potentials.py +++ b/so_schroedinger/potentials.py @@ -38,6 +38,7 @@ "HarmOscPot2d", "GaussBump2d", "StadiumPotential2d", + "LimaconPotential2d", "RandomPotential2d", "BoundaryAbsorber2d", ] @@ -800,6 +801,86 @@ def V(self, r, t): return 0.5 * self._V0 * (1 + np.tanh(self.signed_distance(r) / self._w)) + 0.0j +class LimaconPotential2d(Potential2d): + r"""Billiard or dielectric cavity shaped like Pascal's limaçon, + $\rho(\varphi) = R\,(1 + \varepsilon\cos\varphi)$ in polar coordinates + around $(x_0, y_0)$. + + The potential is $V_\mathrm{in}$ inside and $V_\mathrm{out}$ outside, + with walls smoothed over a width $w$: + $V = V_\mathrm{in} + (V_\mathrm{out} - V_\mathrm{in})/2\,(1 + \tanh(d/w))$, + where $d$ is an approximate signed distance to the boundary (negative + inside, exact on the boundary to first order). For $\varepsilon = 0$ the + limaçon is a circle; for $\varepsilon > 1/4$ it has a dimple at + $\varphi = \pi$; for $\varepsilon < 1$ it has no inner loop. + + A large $V_\mathrm{out}$ gives a billiard. A well, + $V_\mathrm{in} < V_\mathrm{out} = 0$, models a dielectric cavity: the + Schroedinger equation $(\nabla^2 + 2(E - V))\psi = 0$ at energy + $E = k^2/2$ is the Helmholtz equation $(\nabla^2 + n^2 k^2)\psi = 0$ of + TM polarized light with refractive index $n$ inside and 1 outside if + $V_\mathrm{in} = (1 - n^2) E$, see ``dielectric()``. The analogy holds + at that one energy only: a state at energy $E'$ sees the index + $n' = \sqrt{(E' - V_\mathrm{in})/E'}$. With $n = 3.3$ and $\varepsilon \approx 0.43$ + the limaçon combines high-Q whispering gallery modes with directional + emission, cmp. Wiersig and Hentschel, Phys. Rev. Lett. 100, 033901 (2008). + """ + + is_time_dependent = False + + def __init__(self, R, eps, V_in, V_out=0.0, w=0.02, x0=0.0, y0=0.0): + """Create a limaçon potential. + + Parameters + ---------- + R : float + Radius parameter. + eps : float + Deformation $\varepsilon$, between 0 (circle) and 1. + V_in : float + Potential inside. + V_out : float, optional + Potential outside. + w : float, optional + Width of the smoothed walls. + x0, y0 : float, optional + Pole of the limaçon, the origin of $\varphi$. + """ + + self._R, self._eps, self._w = float(R), float(eps), float(w) + self._V_in, self._V_out = float(V_in), float(V_out) + self._x0, self._y0 = float(x0), float(y0) + + @classmethod + def dielectric(cls, R, eps, n, E, w=0.02, x0=0.0, y0=0.0): + """Dielectric cavity with refractive index ``n`` in vacuum, for the + energy ``E``: a well of depth $(n^2 - 1) E$.""" + + return cls(R, eps, (1.0 - float(n) ** 2) * float(E), 0.0, w, x0, y0) + + def boundary(self, phi): + """Points $(x, y)$ of the boundary at the polar angles ``phi``.""" + + phi = np.asarray(phi, dtype=float) + rho = self._R * (1 + self._eps * np.cos(phi)) + return self._x0 + rho * np.cos(phi), self._y0 + rho * np.sin(phi) + + def signed_distance(self, r): + r"""Approximate signed distance to the boundary (negative inside): + $(r - \rho(\varphi))/\sqrt{1 + (\rho'(\varphi)/r)^2}$.""" + + x, y = r + x, y = np.asarray(x) - self._x0, np.asarray(y) - self._y0 + dist, phi = np.hypot(x, y), np.arctan2(y, x) + rho = self._R * (1 + self._eps * np.cos(phi)) + drho = -self._R * self._eps * np.sin(phi) + return (dist - rho) / np.sqrt(1 + (drho / np.maximum(dist, 1e-12)) ** 2) + + def V(self, r, t): + step = 0.5 * (1 + np.tanh(self.signed_distance(r) / self._w)) + return self._V_in + (self._V_out - self._V_in) * step + 0.0j + + class RandomPotential2d(Potential2d): r"""Gaussian random potential with a given autocorrelation function. diff --git a/tests/test_2d.py b/tests/test_2d.py index fee6325..f1c5f2d 100644 --- a/tests/test_2d.py +++ b/tests/test_2d.py @@ -51,6 +51,25 @@ def test_stadium_signed_distance(): assert np.real(V[1]) == pytest.approx(10.0) +def test_limacon_boundary_and_values(): + pot = so.LimaconPotential2d(R=1.0, eps=0.43, V_in=-5.0, V_out=1.0, w=0.001, x0=0.5) + phi = np.linspace(-np.pi, np.pi, 50) + x, y = pot.boundary(phi) + assert np.hypot(x - 0.5, y) == pytest.approx(1 + 0.43 * np.cos(phi)) + assert pot.signed_distance((x, y)) == pytest.approx(np.zeros(50), abs=1e-12) + # on the symmetry axis, near the boundary, the radial distance is the exact distance + r = (np.array([0.5 + 1.33, 2.43, 0.5 - 0.57 - 0.2]), np.zeros(3)) + assert pot.signed_distance(r) == pytest.approx([-0.1, 0.5, 0.2]) + assert np.real(pot.V(r, 0.0)) == pytest.approx([-5.0, 1.0, 1.0]) + + +def test_limacon_circle_and_dielectric(): + pot = so.LimaconPotential2d.dielectric(R=2.0, eps=0.0, n=1.5, E=4.0) + r = (np.array([0.0, 1.0, 3.0, 0.0]), np.array([0.0, 1.0, 0.0, -1.8])) + assert pot.signed_distance(r) == pytest.approx([-2.0, np.sqrt(2) - 2, 1.0, -0.2]) + assert np.real(pot.V(r, 0.0)) == pytest.approx([-5.0, -5.0, 0.0, -5.0], abs=1e-6) + + def test_random_potential2d(): x, y = np.linspace(0, 64, 256, endpoint=False), np.linspace(0, 32, 128, endpoint=False) corr = lambda dx, dy: np.exp(-(dx**2 + dy**2) / 2) diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py index d16e546..288493a 100644 --- a/tests/test_analyzers.py +++ b/tests/test_analyzers.py @@ -6,6 +6,7 @@ AutoCorrelation, EigenfunctionBuilder, EigenstateFilter, + FarField, Flux, IntegratedDensity, Observables, @@ -134,6 +135,45 @@ def test_integrated_density(): assert np.sum(acc.density) * grid.dx == pytest.approx(3.0) # reading does not change the result +def far_field_of(psi0, **kwargs): + size = ((-16.0, 16.0), (-16.0, 16.0)) + absorber = so.BoundaryAbsorber2d(size, width=4.0, strength=5.0) + grid = so.Grid2d(size, 128, so.ConstantPotential(0.0), psi0, absorber=absorber) + ff = FarField(4.0, 10.0, **kwargs) + ff(grid) + so.SplitOperator().propagate(grid, 0.02, 400, callback=ff, every=2) + return ff + + +def test_far_field_isotropic(): + # a ring shaped packet at rest spreads equally in all directions + ff = far_field_of(so.Gaussian2d(0.0, 0.0, 0.5), n_angles=36) + assert ff.angles.shape == ff.intensity.shape == (36,) + assert ff.angles[0] == pytest.approx(-np.pi) + assert ff.intensity == pytest.approx(np.full(36, np.mean(ff.intensity)), rel=0.05) + + +def test_far_field_direction_and_normalization(): + angle, p = 2.0, 3.0 + psi0 = so.Gaussian2d(-3.0 * np.cos(angle), -3.0 * np.sin(angle), 1.0, px=p * np.cos(angle), py=p * np.sin(angle)) + ff = far_field_of(psi0, k_range=(1.0, 6.0)) + assert ff.angles[np.argmax(ff.intensity)] == pytest.approx(angle, abs=np.radians(2)) + # the packet crosses the ring at speed p, so its time integrated probability there is + # the integral of the squared window over r, divided by p (a little more for the spread of speeds) + r = np.linspace(0.0, 20.0, 2001) + window = (1 + np.tanh((r - 4.0) / ff.edge)) * (1 - np.tanh((r - 10.0) / ff.edge)) / 4 + total = np.sum(ff.intensity) * 2 * np.pi / ff.n_angles + assert total == pytest.approx(np.sum(window**2) * (r[1] - r[0]) / p, rel=0.05) + assert ff.density.shape == (128, 128) + + +def test_far_field_errors(): + with pytest.raises(ValueError, match="no data"): + _ = FarField(2.0, 3.0).intensity + with pytest.raises(ValueError, match="2d"): + FarField(1.0, 2.0)(oscillator_grid()) + + def test_flux_measures_transmission(): size = (-80.0, 80.0) grid = so.Grid1d(size, 2**12, so.GaussBarrier1d(0.0, 1.0, 1.0), so.Gaussian1d(-20.0, 3.0, 1.2))