From 00788313a17fda1bb973974e13fc5722ecf9d51a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 11:51:05 +0000 Subject: [PATCH 1/2] Add LimaconPotential2d and FarField analyzer LimaconPotential2d is a billiard or dielectric cavity shaped like Pascal's limacon; LimaconPotential2d.dielectric() sets the well depth for the Schroedinger/Helmholtz analogy. FarField integrates the density on a ring over time and bins it by angle, built on IntegratedDensity, which can now integrate in a masked region only. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01C4brZS9khK8H1Y8XhaYcPH --- CHANGELOG.md | 6 +++ so_schroedinger/analyzers.py | 82 ++++++++++++++++++++++++++++++++--- so_schroedinger/potentials.py | 81 ++++++++++++++++++++++++++++++++++ tests/test_2d.py | 19 ++++++++ tests/test_analyzers.py | 47 ++++++++++++++++++++ 5 files changed, 230 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01c6d90..bce02f1 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 angular distribution of the time integrated + density on a ring, i.e. the emission pattern of a cavity. + `IntegratedDensity(mask=...)` integrates only in a region. - 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..d7bc110 100644 --- a/so_schroedinger/analyzers.py +++ b/so_schroedinger/analyzers.py @@ -10,8 +10,9 @@ >>> 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. """ @@ -30,6 +31,7 @@ "EigenstateFilter", "EigenfunctionBuilder", "IntegratedDensity", + "FarField", "Flux", "Wigner", "Husimi", @@ -327,16 +329,25 @@ 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. + + Parameters + ---------- + mask : boolean array, optional + Integrate only at the grid points where ``mask`` is True, which + saves memory and time if only a region matters; ``density`` then + holds the values at these points, in the order of ``grid.psi[mask]``. """ - def __init__(self): + def __init__(self, mask=None): + self.mask = None if mask is None else np.asarray(mask, dtype=bool) self._acc = None self._trapezoid = _Trapezoid() def add_data(self, grid): + rho = grid.density if self.mask is None else np.abs(grid.psi[self.mask]) ** 2 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 +360,67 @@ def density(self): return self._acc if last is None else self._acc + last[2] * last[1] +class FarField(Analyzer): + r"""Angular distribution of the emission from a cavity or scatterer: + the time integrated density on a ring around ``center``, averaged over + angular bins, $I(\varphi) \propto \int |\psi(r, \varphi, t)|^2\,\mathrm{d}t$ + for $|r - r_0| < \delta r/2$. 2d only. + + Far from the source, an outgoing wave at energy $E = k^2/2$ carries the + radial flux $k |\psi|^2$, so $I(\varphi)$ is the emitted probability per + angle, the far field. The ring should lie well outside the source (a few + wavelengths at least) and inside the absorber, and the propagation + should last until the emission has passed the ring. Waves reflected by + the absorber are counted as well. + + Parameters + ---------- + radius : float + Radius $r_0$ of the ring. + width : float + Width $\delta r$ of the ring; at least a few grid spacings, so that + every angular bin holds grid points. + center : tuple of float, optional + Center of the ring. + n_angles : int, optional + Number of angular bins on $[-\pi, \pi)$. + """ + + def __init__(self, radius, width, center=(0.0, 0.0), n_angles=180): + self.radius, self.width = float(radius), float(width) + self.center = (float(center[0]), float(center[1])) + self.n_angles = int(n_angles) + self._integrated = None + self._bin = None + self._count = None + + def add_data(self, grid): + if grid.dim != 2: + raise ValueError(f"{type(self).__name__} works on 2d grids only") + if self._integrated is None: + x, y = grid.X - self.center[0], grid.Y - self.center[1] + mask = np.abs(np.hypot(x, y) - self.radius) < self.width / 2 + phi = np.arctan2(y[mask], x[mask]) + self._bin = np.minimum(((phi + np.pi) / (2 * np.pi) * self.n_angles).astype(int), self.n_angles - 1) + self._count = np.bincount(self._bin, minlength=self.n_angles) + if np.any(self._count == 0): + raise ValueError("some angular bins hold no grid points; use a wider ring or fewer angles") + self._integrated = IntegratedDensity(mask) + self._integrated.add_data(grid) + + @property + def angles(self): + r"""Centers of the angular bins, in $[-\pi, \pi)$.""" + return -np.pi + (np.arange(self.n_angles) + 0.5) * 2 * np.pi / self.n_angles + + @property + def intensity(self): + r"""$I(\varphi)$: the integrated density averaged over each bin.""" + if self._integrated is None: + raise ValueError("no data has been added yet") + return np.bincount(self._bin, self._integrated.density, minlength=self.n_angles) / self._count + + 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..9a22390 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,52 @@ def test_integrated_density(): assert np.sum(acc.density) * grid.dx == pytest.approx(3.0) # reading does not change the result +def test_integrated_density_mask(): + grid = so.Grid2d(((-8, 8), (-8, 8)), 64, so.ConstantPotential(0.0), so.Gaussian2d(-1.0, 0.0, 1.0, px=2.0)) + mask = grid.X > 0.0 + full, part = IntegratedDensity(), IntegratedDensity(mask) + full(grid) + part(grid) + so.SplitOperator().propagate(grid, 0.01, 100, callback=[full, part], every=5) + assert part.density.shape == (np.count_nonzero(mask),) + assert part.density == pytest.approx(full.density[mask]) + + +def far_field_of(psi0, n_angles=36): + 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(radius=8.0, width=1.0, n_angles=n_angles) + ff(grid) + so.SplitOperator().propagate(grid, 0.02, 400, callback=ff, every=2) + return ff + + +def test_far_field_isotropic(): + ff = far_field_of(so.Gaussian2d(0.0, 0.0, 0.5)) + assert ff.angles.shape == ff.intensity.shape == (36,) + assert ff.angles[0] == pytest.approx(-np.pi + np.pi / 36) + assert ff.intensity == pytest.approx(np.full(36, np.mean(ff.intensity)), rel=0.05) + + +def test_far_field_direction(): + angle = 2.0 + psi0 = so.Gaussian2d(0.0, 0.0, 1.0, px=3.0 * np.cos(angle), py=3.0 * np.sin(angle)) + ff = far_field_of(psi0) + assert ff.angles[np.argmax(ff.intensity)] == pytest.approx(angle, abs=2 * np.pi / 36) + assert ff.intensity.min() < 1e-3 * ff.intensity.max() + + +def test_far_field_errors(): + grid = so.Grid2d(((-4, 4), (-4, 4)), 32, so.ConstantPotential(0.0), so.Gaussian2d(0.0, 0.0, 1.0)) + with pytest.raises(ValueError, match="no data"): + _ = FarField(2.0, 0.5).intensity + with pytest.raises(ValueError, match="angular bins"): + FarField(1.0, 0.01, n_angles=360)(grid) + with pytest.raises(ValueError, match="2d"): + FarField(1.0, 0.5)(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)) From 09a28713027810119b2247e1d1d1be61ace1b9dc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 12:08:40 +0000 Subject: [PATCH 2/2] FarField: far field from the momentum distribution in a ring The time integrated density on a ring of finite radius is still a near field: at r = 2.5 and 3.5 around the limacon its lobes differ by about 10 degrees. The momentum directions of the wave in a ring give the far field directly and agree with a Hankel extrapolation of the stationary mode. FarField now integrates the momentum density, reusing IntegratedDensity through a _density() hook; the mask option is no longer needed. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01C4brZS9khK8H1Y8XhaYcPH --- CHANGELOG.md | 6 +- so_schroedinger/analyzers.py | 120 ++++++++++++++++++++--------------- tests/test_analyzers.py | 45 ++++++------- 3 files changed, 92 insertions(+), 79 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bce02f1..c63e2d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,9 @@ - `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 angular distribution of the time integrated - density on a ring, i.e. the emission pattern of a cavity. - `IntegratedDensity(mask=...)` integrates only in a region. +- `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 d7bc110..31e51e3 100644 --- a/so_schroedinger/analyzers.py +++ b/so_schroedinger/analyzers.py @@ -19,6 +19,7 @@ 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 @@ -329,22 +330,19 @@ 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. - - Parameters - ---------- - mask : boolean array, optional - Integrate only at the grid points where ``mask`` is True, which - saves memory and time if only a region matters; ``density`` then - holds the values at these points, in the order of ``grid.psi[mask]``. + Subclasses integrate other densities by overriding ``_density(grid)``. """ - def __init__(self, mask=None): - self.mask = None if mask is None else np.asarray(mask, dtype=bool) + 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 = grid.density if self.mask is None else np.abs(grid.psi[self.mask]) ** 2 + rho = self._density(grid) if self._acc is None: self._acc = np.zeros(np.shape(rho)) done = self._trapezoid.push(grid.t, rho) @@ -360,65 +358,87 @@ def density(self): return self._acc if last is None else self._acc + last[2] * last[1] -class FarField(Analyzer): - r"""Angular distribution of the emission from a cavity or scatterer: - the time integrated density on a ring around ``center``, averaged over - angular bins, $I(\varphi) \propto \int |\psi(r, \varphi, t)|^2\,\mathrm{d}t$ - for $|r - r_0| < \delta r/2$. 2d only. +class FarField(IntegratedDensity): + r"""Far field of the waves emitted by a cavity or scatterer at ``center``. + 2d only. - Far from the source, an outgoing wave at energy $E = k^2/2$ carries the - radial flux $k |\psi|^2$, so $I(\varphi)$ is the emitted probability per - angle, the far field. The ring should lie well outside the source (a few - wavelengths at least) and inside the absorber, and the propagation - should last until the emission has passed the ring. Waves reflected by - the absorber are counted as well. + 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 ---------- - radius : float - Radius $r_0$ of the ring. - width : float - Width $\delta r$ of the ring; at least a few grid spacings, so that - every angular bin holds grid points. + r_min, r_max : float + Radii of the ring. center : tuple of float, optional - Center of the ring. + 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 angular bins on $[-\pi, \pi)$. + 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, radius, width, center=(0.0, 0.0), n_angles=180): - self.radius, self.width = float(radius), float(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._integrated = None - self._bin = None - self._count = None + self.edge = (self.r_max - self.r_min) / 8 if edge is None else float(edge) + self._window = None + self._k = None - def add_data(self, grid): + def _density(self, grid): if grid.dim != 2: raise ValueError(f"{type(self).__name__} works on 2d grids only") - if self._integrated is None: - x, y = grid.X - self.center[0], grid.Y - self.center[1] - mask = np.abs(np.hypot(x, y) - self.radius) < self.width / 2 - phi = np.arctan2(y[mask], x[mask]) - self._bin = np.minimum(((phi + np.pi) / (2 * np.pi) * self.n_angles).astype(int), self.n_angles - 1) - self._count = np.bincount(self._bin, minlength=self.n_angles) - if np.any(self._count == 0): - raise ValueError("some angular bins hold no grid points; use a wider ring or fewer angles") - self._integrated = IntegratedDensity(mask) - self._integrated.add_data(grid) + 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"""Centers of the angular bins, in $[-\pi, \pi)$.""" - return -np.pi + (np.arange(self.n_angles) + 0.5) * 2 * np.pi / self.n_angles + 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)$: the integrated density averaged over each bin.""" - if self._integrated is None: - raise ValueError("no data has been added yet") - return np.bincount(self._bin, self._integrated.density, minlength=self.n_angles) / self._count + 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): diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py index 9a22390..288493a 100644 --- a/tests/test_analyzers.py +++ b/tests/test_analyzers.py @@ -135,50 +135,43 @@ def test_integrated_density(): assert np.sum(acc.density) * grid.dx == pytest.approx(3.0) # reading does not change the result -def test_integrated_density_mask(): - grid = so.Grid2d(((-8, 8), (-8, 8)), 64, so.ConstantPotential(0.0), so.Gaussian2d(-1.0, 0.0, 1.0, px=2.0)) - mask = grid.X > 0.0 - full, part = IntegratedDensity(), IntegratedDensity(mask) - full(grid) - part(grid) - so.SplitOperator().propagate(grid, 0.01, 100, callback=[full, part], every=5) - assert part.density.shape == (np.count_nonzero(mask),) - assert part.density == pytest.approx(full.density[mask]) - - -def far_field_of(psi0, n_angles=36): +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(radius=8.0, width=1.0, n_angles=n_angles) + 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(): - ff = far_field_of(so.Gaussian2d(0.0, 0.0, 0.5)) + # 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 + np.pi / 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(): - angle = 2.0 - psi0 = so.Gaussian2d(0.0, 0.0, 1.0, px=3.0 * np.cos(angle), py=3.0 * np.sin(angle)) - ff = far_field_of(psi0) - assert ff.angles[np.argmax(ff.intensity)] == pytest.approx(angle, abs=2 * np.pi / 36) - assert ff.intensity.min() < 1e-3 * ff.intensity.max() +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(): - grid = so.Grid2d(((-4, 4), (-4, 4)), 32, so.ConstantPotential(0.0), so.Gaussian2d(0.0, 0.0, 1.0)) with pytest.raises(ValueError, match="no data"): - _ = FarField(2.0, 0.5).intensity - with pytest.raises(ValueError, match="angular bins"): - FarField(1.0, 0.01, n_angles=360)(grid) + _ = FarField(2.0, 3.0).intensity with pytest.raises(ValueError, match="2d"): - FarField(1.0, 0.5)(oscillator_grid()) + FarField(1.0, 2.0)(oscillator_grid()) def test_flux_measures_transmission():