From cf4aec3a1fe76f957a90b6629090a20a67bae9e8 Mon Sep 17 00:00:00 2001 From: John Travers Date: Sat, 15 Aug 2026 23:27:36 +0100 Subject: [PATCH 1/9] Add rate-based absorbing boundaries to Luna - Introduced a new Boundaries module to handle absorbing boundaries with rate semantics, improving the accuracy of energy absorption during propagation. - Updated the Interface module to include new boundary options in prop_capillary and prop_gnlse functions, allowing users to specify boundary behavior. - Enhanced the run function in Luna to apply absorbing boundaries based on user-defined parameters, ensuring consistent absorption regardless of solver step count. - Implemented tests for the new boundary functionality, verifying the correctness of absorption rates and ensuring that results are independent of the number of solver steps. - Added documentation for the Boundaries module to explain the rationale and usage of the new absorbing boundary features. --- docs/src/model/model.md | 17 +++ docs/src/modules/Boundaries.md | 4 + src/Boundaries.jl | 243 +++++++++++++++++++++++++++++++++ src/Interface.jl | 52 ++++++- src/Luna.jl | 152 +++++++++++++++++++-- test/runtests.jl | 5 + test/test_boundaries.jl | 229 +++++++++++++++++++++++++++++++ 7 files changed, 685 insertions(+), 17 deletions(-) create mode 100644 docs/src/modules/Boundaries.md create mode 100644 src/Boundaries.jl create mode 100644 test/test_boundaries.jl diff --git a/docs/src/model/model.md b/docs/src/model/model.md index 362cad431..75dff9786 100644 --- a/docs/src/model/model.md +++ b/docs/src/model/model.md @@ -18,6 +18,23 @@ E(t, \mathbf{r}_\perp, z) = \int_{-\infty}^{\infty} \mathrm{d}\omega \mathcal{T ``` where ``\mathcal{T}_\perp^{-1}`` is simply the inverse of ``\mathcal{T}_\perp`` so transforms from transverse reciprocal space to real space. The chief difference between variations of the UPPE implemented in `Luna` is the definition of ``\mathbf{k}_\perp`` and ``\mathcal{T}_\perp``, that is, the choice of [Modal decompositions](@ref) of the field. +## Absorbing boundaries + +Both the frequency and the time axes are finite and periodic (they are sampled for FFTs), so energy which reaches the edge of either window does not leave the simulation — it wraps around, and the result is wrong. `Luna` therefore applies absorbing boundaries at the edges of both windows. These matter whenever the spectrum or the pulse genuinely reaches the edge of the grid: soliton self-compression, modulation instability, or a dispersive wave walking out of the time window. + +The absorbers are defined by an absorption **rate per unit propagation distance** ``\alpha``, so that propagating a distance ``L`` attenuates the field by ``\mathrm{e}^{-\alpha L}`` no matter how the solver subdivides that distance. The rate is derived from the apodisation profiles ``W`` built by [`Grid`](@ref Grid) as +```math +\alpha(x) = -\frac{\log W(x)}{\ell}\,, +``` +where the reference length ``\ell`` is the distance over which the historical profile is applied exactly once. By default ``\ell = z_\mathrm{max}/N`` with ``N`` set by `boundary_N`, i.e. the profile is applied ``N`` times over the whole propagation. + +The spectral absorber is diagonal in ``\omega``, so it is simply an imaginary part of ``k(\omega)`` and is added to the linear operator ``\mathcal{L}``. The interaction-picture propagator then applies it *exactly*, over whatever sub-interval the adaptive stepper chooses, at no extra cost. The temporal absorber is diagonal in ``t`` and so cannot ride the propagator; it is applied as a factor ``\mathrm{e}^{-\alpha(t)\Delta z}`` after each accepted step. Because these factors telescope, the total absorption over a distance is again independent of the step layout. + +!!! note "Change in behaviour" + Before this scheme was introduced, the absorbing boundaries were applied by multiplying the solution by the fixed profile ``W`` once per accepted step. The cumulative absorption was then ``W^N`` with ``N`` the number of steps — a number the adaptive controller derives from `rtol`. The consequence was that the converged solution depended on the tolerance: tightening `rtol` did not approach a limit, it increased the absorption, and with typical step counts the graded taper acted as a brick wall which eroded genuine spectral wings. Results from that scheme can be reproduced with `boundary=:legacy`, and the absorbers can be switched off entirely with `boundary=:none`. See [`Luna.run`](@ref) and [`Boundaries`](@ref Boundaries.Boundaries). + +Note that this is separate from the band-limiting of the nonlinear polarisation which happens inside [`NonlinearRHS`](@ref NonlinearRHS): that is part of the definition of the equation being solved, and is applied to ``P_\mathrm{nl}`` rather than to the field. + ## A note on sign conventions In optics, a plane wave is usually written as ```math diff --git a/docs/src/modules/Boundaries.md b/docs/src/modules/Boundaries.md new file mode 100644 index 000000000..dc1708ce3 --- /dev/null +++ b/docs/src/modules/Boundaries.md @@ -0,0 +1,4 @@ +# Boundaries.jl +```@autodocs +Modules = [Boundaries] +``` diff --git a/src/Boundaries.jl b/src/Boundaries.jl new file mode 100644 index 000000000..1829f98dc --- /dev/null +++ b/src/Boundaries.jl @@ -0,0 +1,243 @@ +""" + Boundaries + +Absorbing boundaries with **rate semantics**. + +Luna's spectral and temporal absorbing boundaries used to be applied by multiplying the +solution by a fixed profile `W` after every accepted step. That makes the cumulative +absorption `W^N`, where `N` is the number of steps the adaptive controller happens to +take — so the answer depended on `rtol` and never converged. (With the step counts of a +typical run, `W^N` is not a taper at all: it is a brick wall at the edge of the flat +region, which is why the old scheme eroded genuine spectral wings.) An absorbing boundary +must instead have an absorption *rate per unit propagation distance* `α`, so that +traversing a distance `L` attenuates by `exp(-αL)` however that path is subdivided. + +This module turns the historical taper profiles into rates, + + α(x) = -log(W(x)) / ℓ + +where `ℓ` is a reference length: propagating through `ℓ` attenuates the field by exactly +the historical profile once. `ℓ` defaults to `zmax/N`, i.e. "the historical window is +applied `N` times over the whole propagation". + +The two rates are then applied by different mechanisms, chosen by what the existing +machinery can do *exactly*: + +- `α_ω` is diagonal in ω, so it is folded into the linear operator ([`addloss`](@ref)) and + the interaction-picture propagator applies `exp(-α_ω Δz)` exactly, for whatever + sub-interval the stepper uses, at no extra cost, and consistently with dense output. +- `α_t` is diagonal in `t`, so it cannot ride the propagator. It is applied as an + exponential split-step factor `exp(-α_t Δz)` in `Luna.run`'s `stepfun`. Those factors + telescope exactly to `exp(-α_t L)` regardless of the step layout, so the *total* + absorption is still a rate. (This is a first-order Lie splitting, but the commutator is + supported only inside the collar, where the field is being destroyed anyway.) + +Separately from both, the *hard* band limit — the 0/1 part of the spectral window — stays a +per-step multiply. A 0/1 mask is idempotent, so it never suffered from the `W^N` problem, +and it is not optional: see [`ωmask`](@ref). + +See also `Luna.run`'s `boundary` keyword argument. +""" +module Boundaries + +import ..Maths +import ..Grid +import Logging +import Printf: @sprintf + +"Default number of applications of the historical window profile over `zmax`." +const DEFAULT_N = 20 + +"Default minimum temporal collar width, as a fraction of the full time window." +const DEFAULT_TCOLLAR = 0.05 + +#= Cap on α*ℓ, i.e. on the depth of the absorber over one reference length. + + RK45's `fbar!` back-propagates the RHS with exp(-linop*Δz), i.e. it *amplifies* by + exp(+α Δz) for a decaying linop. Two things follow. + + First, α must be finite: the tapers reach exactly 0 at the band edge, and Inf*0 = NaN. + + Second — and this is the constraint that actually binds — the amplified elements must + not pollute the step-size controller. `RK45.weaknorm` sums abs2(yerr) over *all* + elements and divides by the global ‖y‖, and it is evaluated in the interaction-picture + frame, before `prop!_maybe`. So an amplified band-edge element is not independent of the + rest: it can dominate the error estimate and drive the controller into repeated + rejections. The saving grace is that the nonlinear drive is itself ∝ ωwin = exp(-α ℓ), + so the amplified drive scales as exp(α(Δz - ℓ)) — bounded by 1 as long as Δz ≤ ℓ, for + any α. `Luna.run` therefore caps `max_dz` (and `init_dz`) at ℓ, and this constant then + only has to keep exp(α Δz) ≤ exp(MAX_αℓ) finite. exp(30) ≈ 1e13, and the corresponding + floor on the profile, exp(-30) ≈ 1e-13, is far below anything physically meaningful. =# +const MAX_αℓ = 30.0 + +""" + reflength(grid, N, ℓ) + +The absorber reference length in metres. `ℓ` wins if given; otherwise `zmax/N`. +""" +reflength(grid, N, ℓ) = isnothing(ℓ) ? grid.zmax/N : float(ℓ) + +""" + rate(W, ℓ) + +Convert an apodisation profile `W ∈ [0, 1]` (1 in the interior, falling to 0 at the +boundary) into a field-amplitude absorption rate in 1/m, such that propagating through `ℓ` +attenuates the field by `W`. Exactly zero where `W == 1`, and clamped at +`MAX_αℓ/ℓ` so that `W == 0` gives a large but finite rate. +""" +rate(W, ℓ) = clamp.(.-log.(W) ./ ℓ, 0.0, MAX_αℓ/ℓ) + +""" + spectral_rate(grid; N=DEFAULT_N, ℓ=nothing) + +Field-amplitude absorption rate in 1/m across the frequency grid, derived from +`grid.ωwin`. Exactly zero outside `grid.sidx`, where the linear operator is zero by +construction and the hard mask [`ωmask`](@ref) applies instead. +""" +function spectral_rate(grid; N=DEFAULT_N, ℓ=nothing) + α = rate(grid.ωwin, reflength(grid, N, ℓ)) + α[.!grid.sidx] .= 0 + α +end + +""" + tcollarwidth(grid, collar) + +Width (in seconds) of the temporal absorber collar at each end of the time window. + +`grid.twin`'s own collar is only the *slack* between the requested `trange` and the +realised power-of-two window, so it can be exactly zero — for a `trange` that already lands +on a power of two, `grid.twin` is identically 1 except for a single sample, i.e. those +grids have no temporal absorber at all. The collar used here is therefore the wider of that +slack and `collar` times the full time window. +""" +function tcollarwidth(grid, collar) + t = grid.t + tmin, tmax = extrema(t) + i1 = findfirst(isequal(1.0), grid.twin) + i2 = findlast(isequal(1.0), grid.twin) + slack = (isnothing(i1) || isnothing(i2)) ? 0.0 : min(t[i1] - tmin, tmax - t[i2]) + max(slack, collar*(tmax - tmin)) +end + +""" + tprofile(grid; collar=DEFAULT_TCOLLAR) + +The temporal absorber profile: the pointwise minimum of `grid.twin` and a Planck taper with +a guaranteed non-degenerate collar (see [`tcollarwidth`](@ref)). Taking the minimum means +the absorber is never weaker than the historical profile, and equals it exactly whenever +the natural collar is already wide enough. + +Deliberately not stored on the grid: `Grid.to_dict`/`from_dict` serialise every grid field +and `from_dict` requires them all, so adding one would make existing output files +unreadable. +""" +function tprofile(grid; collar=DEFAULT_TCOLLAR) + t = grid.t + tmin, tmax = extrema(t) + w = tcollarwidth(grid, collar) + min.(grid.twin, Maths.planck_taper(t, tmin, tmin + w, tmax - w, tmax)) +end + +""" + temporal_rate(grid; N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) + +Field-amplitude absorption rate in 1/m across the time grid. +""" +temporal_rate(grid; N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) = + rate(tprofile(grid; collar), reflength(grid, N, ℓ)) + +""" + ωmask(grid) + +The hard band limit, as a 0/1 multiplier over ω: `float.(grid.sidx)`. + +This is **not** optional and is not part of the graded absorber. `NonlinearRHS.TransModeAvg` +skips both the normalisation and the `ωwin` multiply outside `grid.sidx` +(`!t.grid.sidx[i] && continue`), so out-of-band `nl` is the raw, unnormalised transform of +the polarisation, and the linear operator is zero there — nothing else removes it. Being a +0/1 mask it is idempotent, so applying it every step was never step-count dependent. +""" +ωmask(grid) = float.(grid.sidx) + +""" + addloss(linop, α) + +Add the field-amplitude absorption rate `α` (a vector over ω) to a linear operator, +returning a linop of the same kind, so that `RK45.make_prop!` dispatch and +`Luna.linoptype` are unchanged. Handles both forms Luna uses: a materialised +`AbstractArray` and a closure `linop!(out, z)`. + +ω is axis 1 for every linop shape — `(Nω,)` mode-averaged, `(Nω, nmodes)` multimode, +`(Nω, q.N)` radial, `(Nω, Nky, Nkx)` free-space — so one broadcast covers all of them. + +The array method **allocates a copy** rather than subtracting in place: +`Interface.prop_capillary_args` is documented as being for repeated simulations in an +identical fibre, i.e. the same linop is deliberately reused across `Luna.run` calls, and an +in-place subtraction would compound the absorber on every reuse. +""" +addloss(linop::AbstractArray, α) = linop .- α + +function addloss(linop!, α) + function linop_absorbing!(out, z) + linop!(out, z) + out .-= α + out + end +end + +""" + walkoff_check(grid, L, αt, collarwidth; quantile=0.95, threshold=1e-2) + +Warn if the temporal absorber is too weak for the group-delay walk-off the simulation can +produce. + +The absorber's job in time is to kill energy before it wraps around the periodic time +window. A component walking off at `τ` (s/m) crosses the collar in `collarwidth/τ` metres, +so the relevant figure of merit is the attenuation over that distance. `τ` is read off the +linear operator: `imag(linop) = -(β - β₁ω)`, so `-d imag(L)/dω` is the group delay per unit +length relative to the reference frame. A high quantile over `grid.sidx` is used rather +than the maximum, because β₁ diverges at the band edges. + +The default `threshold` is a *field* retention of 1e-2, i.e. 1e-4 in intensity — roughly +where wraparound starts to be visible on a log-scale spectral plot. A tighter threshold +warns about wraparound far below any level that could matter. + +This is a diagnostic only — a bad estimate costs a spurious log line, not a wrong answer. +""" +function walkoff_check(grid, L, αt, collarwidth; quantile=0.95, threshold=1e-2) + ω = grid.ω + length(ω) > 2 || return nothing + #= Group delay per unit length, on the ω midpoints; keep only pairs fully inside the + simulation band, and only finite values. Only the first trailing slice is used — for + a multimode or free-space linop that is the fundamental mode or zero transverse + wavevector, which is representative, and scanning the whole array would mean tens of + millions of points for a large 3-D grid. =# + τ = Float64[] + dωs = diff(ω) + lead = ntuple(_ -> 1, max(ndims(L) - 1, 0)) + for i = 1:length(ω)-1 + (grid.sidx[i] && grid.sidx[i+1]) || continue + v = abs((imag(L[i+1, lead...]) - imag(L[i, lead...]))/dωs[i]) + isfinite(v) && push!(τ, v) + end + isempty(τ) && return nothing + sort!(τ) + τq = τ[clamp(ceil(Int, quantile*length(τ)), 1, length(τ))] + τq > 0 || return nothing + zcross = collarwidth/τq # distance to walk across the collar + # mean rate through the collar, i.e. what such a component actually experiences + collar = filter(>(0), αt) + isempty(collar) && return nothing + att = exp(-sum(collar)/length(collar)*zcross) + if att > threshold + Logging.@warn(@sprintf( + "Temporal absorbing boundary may be too weak: a component walking off at \ + %.3g fs/mm crosses the %.3g fs collar in %.3g mm and is only attenuated by \ + %.1e. Increase boundary_N, widen trange, or increase tcollar.", + τq*1e15/1e3, collarwidth*1e15, zcross*1e3, att)) + end + nothing +end + +end diff --git a/src/Interface.jl b/src/Interface.jl index b28fae180..a374db45b 100644 --- a/src/Interface.jl +++ b/src/Interface.jl @@ -1,7 +1,7 @@ module Interface using Luna import Luna.PhysData: wlfreq, roomtemp -import Luna: Grid, Modes, Output, Fields +import Luna: Grid, Modes, Output, Fields, Boundaries import Random: AbstractRNG, GLOBAL_RNG import Logging: @info, @debug @@ -354,13 +354,33 @@ If `raman` is `true`, then the following options apply: - `filename`: Can be used to to overwrite the scan name when running a parameter scan. The running `scanidx` will be appended to this filename. Ignored if no `scan` is given. - `status_period::Number`: Interval (in seconds) between printed status updates. +- `boundary::Symbol=:rate`: How the absorbing boundaries at the edges of the frequency and + time windows are applied. `:rate` treats them as an absorption rate per unit distance, + so the total absorption depends only on the propagation distance and not on how many + steps the solver took. `:legacy` reproduces the historical behaviour, in which the + windows were applied once per accepted step and the result therefore depended on + `rtol`. `:none` disables them. See [`Luna.run`](@ref). +- `boundary_N::Real`: Absorber strength, expressed as the number of times the historical + window profile is applied over the whole propagation length. +- `boundary_length`: Absorber reference length in metres, overriding `boundary_N`. +- `tcollar::Real`: Minimum width of the temporal absorber collar, as a fraction of the time + window. """ function prop_capillary(args...; status_period=5, kwargs...) Eω, grid, linop, transform, FT, output = prop_capillary_args(args...; kwargs...) - Luna.run(Eω, grid, linop, transform, FT, output; status_period) + Luna.run(Eω, grid, linop, transform, FT, output; status_period, + boundary_kwargs(kwargs)...) output end +#= Pick the absorbing-boundary options out of the user's keyword arguments so they can be + forwarded to Luna.run. They are declared on the *_args functions rather than here so that + there is one set of defaults and so that saveargs records them; whatever the user did not + pass simply falls through to Luna.run's own defaults. =# +boundary_kwargs(kwargs) = NamedTuple( + k => v for (k, v) in pairs(kwargs) + if k in (:boundary, :boundary_N, :boundary_length, :tcollar)) + """ prop_capillary_args(radius, flength, gas, pressure; λ0, λlims, trange, kwargs...) @@ -385,7 +405,9 @@ function prop_capillary_args(radius, flength, gas, pressure; PPT_options=Dict{Symbol, Any}(), preionfrac=0.0, rotation=true, vibration=true, temperature=roomtemp, saveN=201, filepath=nothing, - scan=nothing, scanidx=nothing, filename=nothing) + scan=nothing, scanidx=nothing, filename=nothing, + boundary=:rate, boundary_N=Boundaries.DEFAULT_N, + boundary_length=nothing, tcollar=Boundaries.DEFAULT_TCOLLAR) # do we have energy in the orthogonal polarisation states, or just the fundamental? # if so, we need to treat double the number of modes @@ -420,7 +442,8 @@ function prop_capillary_args(radius, flength, gas, pressure; saveargs(output; radius, flength, gas, pressure, λlims, trange, envelope, thg, δt, λ0, τfwhm, τw, ϕ, power, energy, pulseshape, polarisation, propagator, pulses, shotnoise, modes, model, loss, raman, kerr, plasma, PPT_options, - temperature, saveN, filepath, filename) + temperature, saveN, filepath, filename, + boundary, boundary_N, boundary_length, tcollar) return Eω, grid, linop, transform, FT, output end @@ -970,10 +993,22 @@ Note that the current GNLSE model is single mode only. - `filename`: Can be used to to overwrite the scan name when running a parameter scan. The running `scanidx` will be appended to this filename. Ignored if no `scan` is given. - `status_period::Number`: Interval (in seconds) between printed status updates. +- `boundary::Symbol=:rate`: How the absorbing boundaries at the edges of the frequency and + time windows are applied. `:rate` treats them as an absorption rate per unit distance, + so the total absorption depends only on the propagation distance and not on how many + steps the solver took. `:legacy` reproduces the historical behaviour, in which the + windows were applied once per accepted step and the result therefore depended on + `rtol`. `:none` disables them. See [`Luna.run`](@ref). +- `boundary_N::Real`: Absorber strength, expressed as the number of times the historical + window profile is applied over the whole propagation length. +- `boundary_length`: Absorber reference length in metres, overriding `boundary_N`. +- `tcollar::Real`: Minimum width of the temporal absorber collar, as a fraction of the time + window. """ function prop_gnlse(args...; status_period=5, kwargs...) Eω, grid, linop, transform, FT, output = prop_gnlse_args(args...; kwargs...) - Luna.run(Eω, grid, linop, transform, FT, output; status_period) + Luna.run(Eω, grid, linop, transform, FT, output; status_period, + boundary_kwargs(kwargs)...) output end @@ -996,7 +1031,9 @@ function prop_gnlse_args(γ, flength, βs; λ0, λlims, trange, loss=0.0, raman=true, fr=0.18, ramanmodel=:sdo, τ1=12.2e-15, τ2=32e-15, saveN=201, filepath=nothing, - scan=nothing, scanidx=nothing, filename=nothing) + scan=nothing, scanidx=nothing, filename=nothing, + boundary=:rate, boundary_N=Boundaries.DEFAULT_N, + boundary_length=nothing, tcollar=Boundaries.DEFAULT_TCOLLAR) envelope = true thg = false polarisation=:linear @@ -1044,7 +1081,8 @@ function prop_gnlse_args(γ, flength, βs; λ0, λlims, trange, saveargs(output; γ, flength, βs, λlims, trange, envelope, thg, δt, λ0, τfwhm, τw, ϕ, power, energy, pulseshape, polarisation, propagator, pulses, shotnoise, shock, loss, raman, ramanmodel, fr, τ1, τ2, - saveN, filepath, filename) + saveN, filepath, filename, + boundary, boundary_N, boundary_length, tcollar) return Eω, grid, linop, transform, FT, output end diff --git a/src/Luna.jl b/src/Luna.jl index cc206f2da..19e2dca13 100644 --- a/src/Luna.jl +++ b/src/Luna.jl @@ -3,6 +3,7 @@ import FFTW import Hankel import Logging import LinearAlgebra: mul!, ldiv! +import Printf: @sprintf Logging.disable_logging(Logging.BelowMinLevel) """ @@ -54,6 +55,7 @@ include("Output.jl") include("Maths.jl") include("PhysData.jl") include("Grid.jl") +include("Boundaries.jl") include("Modes.jl") include("Fields.jl") include("RK45.jl") @@ -335,6 +337,20 @@ end linoptype(l::AbstractArray) = "constant" linoptype(l) = "variable" +""" + linop_array(linop, Eω, z) + +The linear operator as an array, materialising the z-dependent (closure) form at `z`. The +linop has the same shape as the field, which is how `RK45.make_prop!` allocates its own +buffer. +""" +linop_array(linop::AbstractArray, Eω, z) = linop +function linop_array(linop!, Eω, z) + out = similar(Eω) + linop!(out, z) + out +end + gridtype(g::Grid.RealGrid) = "field-resolved" gridtype(g::Grid.EnvGrid) = "envelope" gridtype(g) = "unknown" @@ -363,21 +379,65 @@ sym2string(other) = other save_modeinfo_maybe(output, t) = nothing +"Report the absorbing-boundary configuration." +function log_boundary(grid, N, ℓ, collar) + l = Boundaries.reflength(grid, N, ℓ) + w = Boundaries.tcollarwidth(grid, collar) + trange = maximum(grid.t) - minimum(grid.t) + #= The clamp in Boundaries.rate is not worth reporting: it bites only where the profile + is already below exp(-30), and even there the attenuation over the whole propagation + is exp(-30 zmax/ℓ). What is worth reporting is the strength the user actually chose, + so quote the attenuation over the propagation at the half-way point of a taper. =# + Logging.@info(@sprintf( + "Absorbing boundaries: rate-based, reference length %.3g m (%.3g applications of \ + the window profile over %.3g m; a %.0f%% point of the taper attenuates by %.1e \ + over the propagation). Temporal collar %.3g fs, %.1f%% of the time window.", + l, grid.zmax/l, grid.zmax, 50, 0.5^(grid.zmax/l), w*1e15, 100*w/trange)) +end + +""" + run(Eω, grid, linop, transform, FT, output; kwargs...) + +Run the propagation. + +# Absorbing boundaries +- `boundary::Symbol=:rate`: how the absorbing boundaries at the edges of the frequency and + time windows are applied. + - `:rate` applies them as an absorption *rate per unit distance*: the spectral absorber + is folded into `linop` (so the propagator applies it exactly) and the temporal + absorber is applied as `exp(-α_t Δz)`. The total absorption over a distance depends + only on that distance, not on how many steps the solver took. + - `:legacy` reproduces the historical behaviour — multiplying the solution by + `grid.ωwin` and `grid.twin` after every accepted step. This makes the cumulative + absorption depend on the step count and hence on `rtol`, so the result does not + converge as the tolerance is tightened. Provided only to reproduce older results. + - `:none` disables the graded absorbers. The hard band limit outside `grid.sidx` is + still applied (it is a 0/1 mask, so it never had a step-count dependence), and the + nonlinear polarisation is still band-limited in `NonlinearRHS`, but nothing stops + energy wrapping around the time window or piling up at the edge of the frequency + window. +- `boundary_N::Real=$(Boundaries.DEFAULT_N)`: absorber strength, expressed as the number of + times the historical window profile is applied over the whole propagation length. The + reference length is `ℓ = zmax/boundary_N`. +- `boundary_length=nothing`: reference length `ℓ` in metres, overriding `boundary_N`. +- `tcollar::Real=$(Boundaries.DEFAULT_TCOLLAR)`: width of the temporal absorber collar as a + fraction of the time window. Only used if it is wider than the collar `grid.twin` + already has (which can be nearly zero, depending on how `trange` rounds up). + +See [`Luna.Boundaries`](@ref) for the rationale. +""" function run(Eω, grid, linop, transform, FT, output; min_dz=0, max_dz=grid.zmax/2, init_dz=1e-4, z0=0.0, rtol=1e-6, atol=1e-10, safety=0.9, norm=RK45.weaknorm, - status_period=1) + status_period=1, + boundary=:rate, boundary_N=Boundaries.DEFAULT_N, boundary_length=nothing, + tcollar=Boundaries.DEFAULT_TCOLLAR) - Et = FT \ Eω + boundary in (:rate, :legacy, :none) || error( + "boundary must be :rate, :legacy or :none, not $boundary") - function stepfun(Eω, z, dz, interpolant) - Eω .*= grid.ωwin - ldiv!(Et, FT, Eω) - Et .*= grid.twin - mul!(Eω, FT, Et) - output(Eω, z, dz, interpolant) - end + Et = FT \ Eω # check_cache does nothing except for HDF5Outputs Eωc, zc, dzc = Output.check_cache(output, Eω, z0, init_dz) @@ -386,8 +446,80 @@ function run(Eω, grid, Eω, z0, init_dz = Eωc, zc, dzc end + #= NOTE: everything below must come after check_cache, which can move z0 and init_dz: + zprev seeds the distance the temporal absorber is applied over. =# + ℓabs = Boundaries.reflength(grid, boundary_N, boundary_length) + ωmask = Boundaries.ωmask(grid) + + stepfun = if boundary === :rate + #= The stepper must resolve the absorber's reference length. RK45's fbar! amplifies + the RHS by exp(+α Δz) while the nonlinear drive it acts on is ∝ exp(-α ℓ), so the + amplified band-edge elements stay bounded — and stay small in weaknorm's global + sum — only while Δz ≤ ℓ. This costs nothing in practice: it just requires at + least boundary_N steps, and real runs take far more. =# + if max_dz > ℓabs + Logging.@info(@sprintf( + "Reducing max_dz from %.3g m to the absorber reference length %.3g m.", + max_dz, ℓabs)) + max_dz = ℓabs + end + init_dz = min(init_dz, max_dz) + + αω = Boundaries.spectral_rate(grid; N=boundary_N, ℓ=boundary_length) + αt = Boundaries.temporal_rate(grid; N=boundary_N, ℓ=boundary_length, + collar=tcollar) + Boundaries.walkoff_check(grid, linop_array(linop, Eω, z0), αt, + Boundaries.tcollarwidth(grid, tcollar)) + linop = Boundaries.addloss(linop, αω) + log_boundary(grid, boundary_N, boundary_length, tcollar) + + # only the collar entries are ever ≠ 1, so only those need updating each step + tidcs = findall(>(0), αt) + tfac = ones(Float64, length(grid.t)) + zprev = Ref(float(z0)) + function stepfun_rate(Eω, z, dz, interpolant) + #= The absorption applied here is exp(-αt*Δz) over the distance actually + travelled, so successive factors telescope to exp(-αt*L) no matter how the + solver subdivides the propagation. =# + Δz = z - zprev[] + zprev[] = z + Eω .*= ωmask # idempotent hard band limit, so no rate treatment needed + if Δz > 0 + @inbounds for i in tidcs + tfac[i] = exp(-αt[i]*Δz) + end + ldiv!(Et, FT, Eω) # NB: for a RealGrid rfft plan this destroys Eω + Et .*= tfac + mul!(Eω, FT, Et) + end + output(Eω, z, dz, interpolant) + end + elseif boundary === :legacy + Logging.@warn( + "boundary=:legacy applies the absorbing boundaries once per accepted step, " * + "so the absorption depends on the step count and the result depends on rtol.") + function stepfun_legacy(Eω, z, dz, interpolant) + Eω .*= grid.ωwin + ldiv!(Et, FT, Eω) + Et .*= grid.twin + mul!(Eω, FT, Et) + output(Eω, z, dz, interpolant) + end + else + #= Even with no absorber the hard band limit has to stay: TransModeAvg leaves the + out-of-band part of nl unnormalised and unwindowed, and the linear operator is + zero there, so nothing else removes it. =# + function stepfun_none(Eω, z, dz, interpolant) + Eω .*= ωmask + output(Eω, z, dz, interpolant) + end + end + output(Grid.to_dict(grid), group="grid") - output(simtype(grid, transform, linop), group="simulation_type") + st = simtype(grid, transform, linop) + st["boundary"] = string(boundary) + boundary === :rate && (st["boundary_length"] = string(ℓabs)) + output(st, group="simulation_type") save_modeinfo_maybe(output, transform) flush(stderr) # flush std error once before starting to show setup steps diff --git a/test/runtests.jl b/test/runtests.jl index 48ac8dd9c..82ae71af0 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -97,6 +97,11 @@ end include(joinpath(testdir, "test_linops.jl")) end +@testset "Boundaries" begin + @info("================= test_boundaries.jl") + include(joinpath(testdir, "test_boundaries.jl")) +end + @testset "Modes" begin @info("================= test_modes.jl") include(joinpath(testdir, "test_modes.jl")) diff --git a/test/test_boundaries.jl b/test/test_boundaries.jl new file mode 100644 index 000000000..fdc13d259 --- /dev/null +++ b/test/test_boundaries.jl @@ -0,0 +1,229 @@ +import Test: @test, @testset, @test_throws +import FFTW +import LinearAlgebra: mul!, ldiv! +import Luna +import Luna: Grid, Boundaries, Maths, RK45, Output +import Luna.Interface: prop_capillary_args +import Logging + +#= These tests cover the rate-based absorbing boundaries. The property they exist to + protect is that the absorption depends on the propagation *distance* and not on how many + steps the adaptive solver took to cover it -- the old scheme multiplied the solution by a + fixed profile once per accepted step, so the answer depended on rtol. =# + +@testset "profiles and rates" begin +grid = Grid.RealGrid(0.3, 800e-9, (150e-9, 4e-6), 1e-12) +ℓ = 0.3/20 + +α = Boundaries.rate(grid.ωwin, ℓ) +@test all(isfinite, α) +@test all(α .>= 0) +@test all(α[grid.ωwin .== 1] .== 0) +@test maximum(α) <= Boundaries.MAX_αℓ/ℓ*(1 + 1e-12) +# the rate reproduces the profile over one reference length, where it is not clamped +unclamped = grid.ωwin .> exp(-Boundaries.MAX_αℓ) +@test isapprox(exp.(-α[unclamped].*ℓ), grid.ωwin[unclamped]; rtol=1e-12) + +#= Telescoping: this is the whole point. Applying exp(-α dz) over any partition of [0, L] + gives exactly exp(-α L), so the absorption cannot depend on the step layout. =# +i = findfirst(x -> 0 < x < 1, grid.ωwin) +for n in (3, 17, 200) + dzs = rand(n) + dzs .*= 0.3/sum(dzs) + @test isapprox(prod(exp.(-α[i].*dzs)), exp(-α[i]*0.3); rtol=1e-12) +end + +# ωwin is exactly zero outside the simulation band, so the hard mask is grid.sidx +@test (grid.ωwin .> 0) == grid.sidx +@test all(Boundaries.spectral_rate(grid)[.!grid.sidx] .== 0) +end + +@testset "temporal collar is never degenerate" begin +#= grid.twin's collar is only the slack between the requested trange and the realised + power-of-two window, so for some tranges it is a single sample wide -- those grids have + no temporal absorber at all. tprofile guarantees a collar while never being weaker than + grid.twin. =# +for (zmax, trange) in ((0.3, 1e-12), (0.3, 0.6825e-12), (1.0, 250e-15), (4e-5, 1e-12)) + for grid in (Grid.RealGrid(zmax, 800e-9, (150e-9, 4e-6), trange), + Grid.EnvGrid(zmax, 800e-9, (150e-9, 4e-6), trange)) + W = Boundaries.tprofile(grid) + @test all(W .<= grid.twin .+ 1e-15) # never weaker than the historical profile + @test count(0 .< W .< 1) > 0.03*length(grid.t) # and never degenerate + @test all(isfinite, Boundaries.temporal_rate(grid)) + end +end +# a wider natural collar is kept as-is +grid = Grid.RealGrid(0.3, 800e-9, (150e-9, 4e-6), 1e-12) +@test Boundaries.tprofile(grid; collar=0) == grid.twin +end + +@testset "addloss" begin +grid = Grid.RealGrid(0.3, 800e-9, (150e-9, 4e-6), 1e-12) +α = Boundaries.spectral_rate(grid) +Nω = length(grid.ω) +# ω is axis 1 for every linop shape Luna uses +for sz in ((Nω,), (Nω, 4), (Nω, 8), (Nω, 8, 6)) + L = randn(ComplexF64, sz...) + La = Boundaries.addloss(L, α) + @test La isa AbstractArray # so linoptype stays "constant" + @test size(La) == size(L) + @test imag(La) == imag(L) # dispersion untouched + trailing = ntuple(_ -> 1, length(sz) - 1) + @test real(La)[:, trailing...] ≈ real(L)[:, trailing...] .- α + # the closure form must agree with the array form + Lc! = (out, z) -> (out .= L) + Lac! = Boundaries.addloss(Lc!, α) + out = similar(L) + Lac!(out, 0.0) + @test out ≈ La + @test !isa(Lac!, AbstractArray) # so linoptype stays "variable" +end +end + +@testset "propagator applies the rate exactly" begin +#= The spectral absorber rides the interaction-picture propagator, so exp(-α Δz) must be + applied exactly for whatever sub-interval the stepper chooses. =# +grid = Grid.RealGrid(0.3, 800e-9, (150e-9, 4e-6), 1e-12) +α = Boundaries.spectral_rate(grid) +linop = Boundaries.addloss(zeros(ComplexF64, length(grid.ω)), α) +y = ones(ComplexF64, length(grid.ω)) +prop! = RK45.make_prop!(linop, y) + +onestep = copy(y) +prop!(onestep, 0.0, 0.3) +for n in (2, 7, 1000) + many = copy(y) + zs = range(0, 0.3, length=n+1) + for j = 1:n + prop!(many, zs[j], zs[j+1]) + end + @test isapprox(many, onestep; rtol=1e-12) +end +@test isapprox(abs.(onestep), exp.(-α.*0.3); rtol=1e-12) +end + +@testset "temporal absorber converges to the rate limit" begin +#= Zero RHS and zero linear operator, so the only thing acting on the field is the temporal + absorber applied in Luna.run's stepfun, whose target is exp(-α_t L) applied once. + + The exponential factors telescope exactly, but the hard band mask is interleaved with + them and the two do not commute, so the result approaches exp(-α_t L) as the steps get + smaller rather than matching it exactly. That is a splitting error of the same order as + the temporal splitting itself, and — unlike the historical scheme — it converges. =# +grid = Grid.EnvGrid(0.2, 800e-9, (400e-9, 2e-6), 1e-12) +FT = FFTW.plan_fft(zeros(ComplexF64, length(grid.t))) +αt = Boundaries.temporal_rate(grid) +mask = Boundaries.ωmask(grid) +# deliberately wide, so that the field actually overlaps the absorber collar +Et0 = Maths.gauss.(grid.t, fwhm=0.5*(maximum(grid.t) - minimum(grid.t))) .+ 0im +Eω0 = (FT*Et0) .* mask + +function bare_run(; kwargs...) + Eω = copy(Eω0) + out = Output.MemoryOutput(0, grid.zmax, 3) + Logging.with_logger(Logging.NullLogger()) do + Luna.run(Eω, grid, zeros(ComplexF64, length(grid.ω)), + (nl, Eω, z) -> fill!(nl, 0), FT, out; kwargs...) + end + out["Eω"][:, end] +end +reldiff(a, b) = sqrt(sum(abs2, a .- b))/sqrt(sum(abs2, b)) + +expected = (FT*((FT \ Eω0) .* exp.(-αt.*grid.zmax))) .* mask +coarse = reldiff(bare_run(init_dz=1e-3), expected) # 20 steps +fine = reldiff(bare_run(init_dz=1e-5, max_dz=grid.zmax/500), expected) # 500 steps +@test coarse < 1e-3 +@test fine < 10*coarse/25 # converges at least first order in the step size + +# :none applies only the (idempotent) hard band limit +@test bare_run(boundary=:none) == Eω0 +# :legacy applies the whole window once per step and does not approach the rate limit +legacy = Logging.with_logger(Logging.NullLogger()) do + reldiff(bare_run(boundary=:legacy), expected) +end +@test legacy > 100*fine +end + +@testset "legacy reproduces the historical scheme bit-identically" begin +#= boundary=:legacy must be an exact reproduction of the pre-change behaviour, so that + published results stay reproducible. Compare against the historical stepfun driven + straight through RK45, with no other part of `run` involved. =# +grid = Grid.EnvGrid(0.2, 800e-9, (400e-9, 2e-6), 1e-12) +FT = FFTW.plan_fft(zeros(ComplexF64, length(grid.t))) +Et0 = Maths.gauss.(grid.t, fwhm=0.5*(maximum(grid.t) - minimum(grid.t))) .+ 0im +Eω0 = FT*Et0 +linop = -im.*(1e4.*(grid.ω .- grid.ω0).^2) # some dispersion, so the steps do something +transform = (nl, Eω, z) -> fill!(nl, 0) +maxdz = grid.zmax/50 # force ~50 window applications, so bit-identity is a real statement + +Eωa = copy(Eω0) +outa = Output.MemoryOutput(0, grid.zmax, 3) +Logging.with_logger(Logging.NullLogger()) do + Luna.run(Eωa, grid, linop, transform, FT, outa; boundary=:legacy, max_dz=maxdz) +end + +Eωb = copy(Eω0) +outb = Output.MemoryOutput(0, grid.zmax, 3) +Et = FT \ Eωb +function historical_stepfun(Eω, z, dz, interpolant) + Eω .*= grid.ωwin + ldiv!(Et, FT, Eω) + Et .*= grid.twin + mul!(Eω, FT, Et) + outb(Eω, z, dz, interpolant) +end +Logging.with_logger(Logging.NullLogger()) do + RK45.solve_precon(transform, linop, Eωb, 0.0, 1e-4, grid.zmax; + stepfun=historical_stepfun, max_dt=maxdz, min_dt=0, + rtol=1e-6, atol=1e-10, safety=0.9, norm=RK45.weaknorm, + status_period=1) +end + +@test outa["Eω"] == outb["Eω"] # bit-identical, not merely approximately equal +end + +@testset "tolerance independence" begin +#= The measured defect: with the historical per-step windowing, tightening rtol changes the + answer because it changes the number of times the window is applied. Use a case with + real energy in the taper collars -- a strongly self-broadening capillary run. =# +function arm(boundary, rtol) + Eω, grid, linop, transform, FT, output = prop_capillary_args( + 125e-6, 0.15, :He, 3.0; λ0=800e-9, energy=300e-6, τfwhm=10e-15, + λlims=(120e-9, 4e-6), trange=1e-12, saveN=3, plasma=false, boundary, + PPT_options=Dict(:cache => false)) + Luna.run(Eω, grid, linop, transform, FT, output; rtol, boundary) + #= Compare only inside the flat part of the window: interpolated saves reconstruct the + out-of-band part from the stepper's stages, which is rtol-dependent by construction + and is not what this test is about. =# + output["Eω"][grid.ωwin .== 1, end] +end + +reldiff(a, b) = sqrt(sum(abs2, a .- b))/sqrt(sum(abs2, a)) + +rate, legacy = Logging.with_logger(Logging.NullLogger()) do + (reldiff(arm(:rate, 1e-6), arm(:rate, 1e-9)), + reldiff(arm(:legacy, 1e-6), arm(:legacy, 1e-9))) +end +@info "tolerance sensitivity: :rate $rate, :legacy $legacy" +@test rate < 1e-5 +@test legacy > 20*rate # the mechanism is genuinely exercised +end + +@testset "run interface" begin +@test_throws ErrorException Logging.with_logger(Logging.NullLogger()) do + grid = Grid.EnvGrid(0.1, 800e-9, (400e-9, 2e-6), 1e-12) + FT = FFTW.plan_fft(zeros(ComplexF64, length(grid.t))) + Luna.run(zeros(ComplexF64, length(grid.ω)), grid, + zeros(ComplexF64, length(grid.ω)), (nl, Eω, z) -> fill!(nl, 0), FT, + Output.MemoryOutput(0, grid.zmax, 3); boundary=:nonsense) +end + +# the chosen mode is recorded, so a saved run can be reproduced +out = Logging.with_logger(Logging.NullLogger()) do + prop_capillary(125e-6, 0.05, :He, 1.0; λ0=800e-9, energy=1e-6, τfwhm=10e-15, + λlims=(150e-9, 4e-6), trange=1e-12, saveN=3, plasma=false, + boundary_N=5, PPT_options=Dict(:cache => false)) +end +@test out["simulation_type"]["boundary"] == "rate" +@test out["prop_capillary_args"]["boundary_N"] == "5" +end From b9479eae4a80f6457332d0a84677e1617b6db91e Mon Sep 17 00:00:00 2001 From: John Travers Date: Wed, 19 Aug 2026 15:56:03 +0100 Subject: [PATCH 2/9] Test that the temporal absorbing boundary catches a walked-off pulse Nothing in test_boundaries.jl exercised the absorber in time: the only temporal testset runs with a zero linear operator, so the field never moves and never reaches the collar. Add a "temporal walk-off" testset built on the case where this bites in practice -- a deep-UV resonant dispersive wave in a deliberately small time window, walking away from the pump at ~100 fs/m and leaving the 171 fs window halfway along the fibre. It asserts that the absorber is inert until the pulse arrives, that it then removes it, that what :none keeps instead is wraparound at the front of the window, and that the absorbed fraction is step-count independent for :rate but not for :legacy (0.9% vs 33% for the same rtol and 3.6x the steps). Uses plasma=false, which halves the cost and drops the PPT-cache dependency without changing the walk-off physics. 9 assertions, 3.3 s. Co-Authored-By: Claude Opus 5 --- test/test_boundaries.jl | 74 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/test/test_boundaries.jl b/test/test_boundaries.jl index fdc13d259..ff5b8b911 100644 --- a/test/test_boundaries.jl +++ b/test/test_boundaries.jl @@ -2,9 +2,10 @@ import Test: @test, @testset, @test_throws import FFTW import LinearAlgebra: mul!, ldiv! import Luna -import Luna: Grid, Boundaries, Maths, RK45, Output +import Luna: Grid, Boundaries, Maths, RK45, Output, Processing, PhysData import Luna.Interface: prop_capillary_args import Logging +import Random: MersenneTwister #= These tests cover the rate-based absorbing boundaries. The property they exist to protect is that the absorption depends on the propagation *distance* and not on how many @@ -209,6 +210,77 @@ end @test legacy > 20*rate # the mechanism is genuinely exercised end +@testset "temporal walk-off" begin +#= The temporal absorber's job is to destroy light that walks off the end of the time + window *before* it wraps around and aliases onto the rest of the field. Nothing above + exercises that: the temporal tests use a zero linear operator, so nothing moves. + + Use the case where this actually bites in practice -- a deep-UV resonant dispersive wave + in a deliberately small time window. The DW is emitted at ~230 nm around z = 0.2 m and + then walks away from the pump at the group-delay difference of the fibre (~100 fs/m + here), so in a 171 fs window it leaves the flat region at ~0.7 m and reaches the window + edge at ~1.0 m, i.e. halfway along the 2 m fibre. =# +RDWBAND = (200e-9, 260e-9) +ZMAX = 2.0 + +function walkoff_arm(boundary; max_dz=ZMAX/2, rtol=1e-6) + Eω, grid, linop, transform, FT, output = prop_capillary_args( + 50e-6, ZMAX, :Ar, 0.4; λ0=800e-9, energy=29e-6, τfwhm=10e-15, + λlims=(150e-9, 4e-6), trange=100e-15, saveN=51, plasma=false, boundary, + rng=MersenneTwister(1234)) + Luna.run(Eω, grid, linop, transform, FT, output; rtol, boundary, max_dz) + output +end + +#= Energy in the DW band, via a hard 0/1 spectral mask. Processing.energy's tuple bandpass + picks its taper width from the frequency spacing, which differs between grids; a hard + mask is exact by Parseval and comparable across everything here. =# +function bandE(output) + grid = Processing.makegrid(output) + mask = float.(RDWBAND[1] .< PhysData.wlfreq.(grid.ω) .< RDWBAND[2]) + Processing.energy(grid, output["Eω"]; bandpass=mask) +end + +# power in the leading half of the window, where anything that wraps around must appear +function leadingpower(output) + t, Et = Processing.getEt(output, ZMAX; bandpass=(RDWBAND..., 1e14)) + maximum(abs2.(Et[t .< -30e-15, 1])) +end + +rate, legacy, none, ratefine, legacyfine = Logging.with_logger(Logging.NullLogger()) do + (walkoff_arm(:rate), walkoff_arm(:legacy), walkoff_arm(:none), + walkoff_arm(:rate; max_dz=ZMAX/4000), walkoff_arm(:legacy; max_dz=ZMAX/4000)) +end + +z = rate["z"] +i0 = argmin(abs.(z .- 0.5)) # before the DW has reached the taper +Erate, Elegacy, Enone = bandE(rate), bandE(legacy), bandE(none) + +# the absorber does nothing at all until the pulse gets there +@test isapprox(Erate[i0], Enone[i0]; rtol=1e-2) + +# ... and then removes the DW: two orders of magnitude, where :none keeps most of it +@test Erate[end]/Erate[i0] < 1e-2 +@test Elegacy[end]/Elegacy[i0] < 1e-2 +@test Enone[end]/Enone[i0] > 0.5 + +#= What :none keeps is not physics, it is wraparound: with no absorber the DW reappears at + the *front* of the time window. That is the aliasing the boundary exists to prevent. =# +@test leadingpower(none) > 100*leadingpower(rate) +@test leadingpower(none) > 100*leadingpower(legacy) + +#= The point of rate semantics: how much is absorbed depends on the distance travelled, not + on how the solver chose to subdivide it. Same rtol in both arms -- so the same local + error control and the same physics -- with max_dz forcing ~3.5x as many steps, hence + 3.5x as many applications of the historical window. =# +dr = abs(bandE(ratefine)[end] - Erate[end])/Erate[end] +dl = abs(bandE(legacyfine)[end] - Elegacy[end])/Elegacy[end] +@info "walk-off, step-count sensitivity of the surviving DW: :rate $dr, :legacy $dl" +@test dr < 0.05 +@test dl > 0.1 # the mechanism is genuinely exercised +@test dl > 10*dr +end + @testset "run interface" begin @test_throws ErrorException Logging.with_logger(Logging.NullLogger()) do grid = Grid.EnvGrid(0.1, 800e-9, (400e-9, 2e-6), 1e-12) From d507c3c3307c0edd3aa74aa410e674fd1af6fbe5 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 20 Aug 2026 11:36:20 +0100 Subject: [PATCH 3/9] Fix the documentation build The docs build fails on this branch (master is green). Five distinct errors, all introduced here: - `Modules = [Boundaries]` in the new autodocs page could not be evaluated: `Boundaries` was missing from Luna's export list, so it does not resolve in `Main` where Documenter evaluates the block. Every other module with a docs page is exported. - `[`Luna.run`](@ref)`, added to the model docs and to the `prop_capillary`/`prop_gnlse` docstrings, had no page to resolve to -- `Luna.run` gained a docstring but nothing included it. Add a page for the top-level module which documents it. - `[`Grid`](@ref Grid)` and `[`NonlinearRHS`](@ref NonlinearRHS)` in the model docs pointed at modules with no module-level docstring, so there was no binding to link to. Give both a short one. Cross-references inside a module docstring resolve with `CurrentModule` set to that module, so the two new docstrings refer to `@ref Luna.Boundaries` rather than the bare name. Verified by building the docs locally: no errors, and the only remaining warning (an unescaped $HOME in an `Ionisation` docstring) is pre-existing. Co-Authored-By: Claude Opus 5 --- docs/src/modules/Luna.md | 8 ++++++++ src/Grid.jl | 11 +++++++++++ src/Luna.jl | 2 +- src/NonlinearRHS.jl | 11 +++++++++++ 4 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 docs/src/modules/Luna.md diff --git a/docs/src/modules/Luna.md b/docs/src/modules/Luna.md new file mode 100644 index 000000000..cf47445b7 --- /dev/null +++ b/docs/src/modules/Luna.md @@ -0,0 +1,8 @@ +# Luna.jl + +The top-level module. [`Luna.run`](@ref) is the low-level entry point which drives the +propagation; most users will go through [The simple interface](../interface.md) instead. + +```@docs +Luna.run +``` diff --git a/src/Grid.jl b/src/Grid.jl index 9aa093caf..ee819870a 100644 --- a/src/Grid.jl +++ b/src/Grid.jl @@ -1,3 +1,14 @@ +""" + Grid + +The sampling grids on which `Luna` solves the propagation equation: the time and frequency +axes, the oversampled axes used for the nonlinear polarisation, and the apodisation windows +which go with them. + +A grid also carries `sidx`, the indices of the frequency axis which are inside the +simulation band, and the profiles `ωwin`, `twin` and `towin` from which +[`Boundaries`](@ref Luna.Boundaries) derives the absorbing boundaries. +""" module Grid import Logging import FFTW diff --git a/src/Luna.jl b/src/Luna.jl index 19e2dca13..e305b4276 100644 --- a/src/Luna.jl +++ b/src/Luna.jl @@ -87,7 +87,7 @@ makefilename = Scans.makefilename addvariable! = Scans.addvariable! export Utils, Scans, Output, Maths, PhysData, Grid, RK45, Modes, Capillary, RectModes, - Nonlinear, Ionisation, NonlinearRHS, LinearOps, Stats, Polarisation, + Nonlinear, Ionisation, NonlinearRHS, LinearOps, Boundaries, Stats, Polarisation, Tools, Plotting, Raman, Antiresonant, Fields, Processing, Interface, SFA, prop_capillary, prop_gnlse, Pulses, Scan, runscan, makefilename, addvariable!, StepIndexFibre, SimpleFibre diff --git a/src/NonlinearRHS.jl b/src/NonlinearRHS.jl index 722a462b6..d2567cce5 100644 --- a/src/NonlinearRHS.jl +++ b/src/NonlinearRHS.jl @@ -1,3 +1,14 @@ +""" + NonlinearRHS + +The right-hand side of the propagation equation: transforms which take the frequency-domain +field `E(ω)` to the nonlinear polarisation `Pₙₗ(ω)` for each modal decomposition +`Luna` supports. + +Each transform also band-limits `Pₙₗ` to the simulation band. That is part of the +definition of the equation being solved and is separate from the absorbing boundaries +applied to the field itself, which live in [`Boundaries`](@ref Luna.Boundaries). +""" module NonlinearRHS import FFTW import Hankel From 377a0beda1f55b2813796f26c494a9ed36d43ec3 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 20 Aug 2026 11:39:12 +0100 Subject: [PATCH 4/9] Reject a non-positive absorber reference length `reflength` took `boundary_N` and `boundary_length` on trust. Neither is merely useless when non-positive, both are silently destructive: - `boundary_length=0` makes `rate` evaluate -log(1)/0 in the interior, so the profile comes back NaN wherever the window is flat -- 2636 of 4097 points on a typical grid -- and Inf everywhere else. - `boundary_length<0` inverts the clamp bounds. `clamp(x, 0.0, -600.0)` returns -600.0 for every element, so the absorber becomes a gain, and applies over the whole grid rather than just the collar. - `boundary_N=0` gives an infinite reference length, i.e. no absorber at all, with no indication that the setting did nothing. Validate both in `reflength`, which every call site goes through. `boundary=:none` remains the way to switch the absorbers off. Also add `using Luna` to test_boundaries.jl, which called `prop_capillary` unqualified while importing only submodules. It passes under runtests.jl only because test_ionisation.jl and test_scans.jl happen to be included first and do bring the name into scope; run on its own the file threw UndefVarError. It is the only test file calling prop_capillary without `using Luna`. Co-Authored-By: Claude Opus 5 --- src/Boundaries.jl | 19 ++++++++++++++++++- test/test_boundaries.jl | 15 +++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/Boundaries.jl b/src/Boundaries.jl index 1829f98dc..ca96ddcaf 100644 --- a/src/Boundaries.jl +++ b/src/Boundaries.jl @@ -74,8 +74,25 @@ const MAX_αℓ = 30.0 reflength(grid, N, ℓ) The absorber reference length in metres. `ℓ` wins if given; otherwise `zmax/N`. + +Both are validated here so that every call site is protected. A non-positive length is not +merely useless, it is silently destructive: `ℓ == 0` makes [`rate`](@ref) evaluate `0/0` in +the interior and fills the grid with NaN, and `ℓ < 0` inverts the clamp bounds so that +`clamp` returns the (negative) upper bound everywhere — an absorber which amplifies, over +the whole grid rather than just the collar. To switch the absorbers off, use +`boundary=:none`. """ -reflength(grid, N, ℓ) = isnothing(ℓ) ? grid.zmax/N : float(ℓ) +function reflength(grid, N, ℓ) + if isnothing(ℓ) + (N > 0 && isfinite(N)) || error( + "boundary_N must be finite and positive, got $N") + grid.zmax/N + else + (ℓ > 0 && isfinite(ℓ)) || error( + "boundary_length must be finite and positive, got $ℓ") + float(ℓ) + end +end """ rate(W, ℓ) diff --git a/test/test_boundaries.jl b/test/test_boundaries.jl index ff5b8b911..7667226c4 100644 --- a/test/test_boundaries.jl +++ b/test/test_boundaries.jl @@ -1,7 +1,7 @@ +using Luna import Test: @test, @testset, @test_throws import FFTW import LinearAlgebra: mul!, ldiv! -import Luna import Luna: Grid, Boundaries, Maths, RK45, Output, Processing, PhysData import Luna.Interface: prop_capillary_args import Logging @@ -282,14 +282,25 @@ dl = abs(bandE(legacyfine)[end] - Elegacy[end])/Elegacy[end] end @testset "run interface" begin +grid = Grid.EnvGrid(0.1, 800e-9, (400e-9, 2e-6), 1e-12) + @test_throws ErrorException Logging.with_logger(Logging.NullLogger()) do - grid = Grid.EnvGrid(0.1, 800e-9, (400e-9, 2e-6), 1e-12) FT = FFTW.plan_fft(zeros(ComplexF64, length(grid.t))) Luna.run(zeros(ComplexF64, length(grid.ω)), grid, zeros(ComplexF64, length(grid.ω)), (nl, Eω, z) -> fill!(nl, 0), FT, Output.MemoryOutput(0, grid.zmax, 3); boundary=:nonsense) end +#= A non-positive reference length is silently destructive rather than merely useless -- it + NaNs the whole grid or turns the absorber into a gain -- so reject it at the one place + every call site goes through. =# +@test Boundaries.reflength(grid, 20, nothing) == grid.zmax/20 +@test Boundaries.reflength(grid, 20, 0.05) == 0.05 +for bad in (0, -1, Inf, NaN) + @test_throws ErrorException Boundaries.reflength(grid, bad, nothing) + @test_throws ErrorException Boundaries.reflength(grid, 20, bad) +end + # the chosen mode is recorded, so a saved run can be reproduced out = Logging.with_logger(Logging.NullLogger()) do prop_capillary(125e-6, 0.05, :He, 1.0; λ0=800e-9, energy=1e-6, τfwhm=10e-15, From dcac64eee919b7600b062c01bcc4b7b22b10fdd1 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 20 Aug 2026 11:43:50 +0100 Subject: [PATCH 5/9] Make the absorber alpha a power coefficient, as elsewhere in Luna Luna's convention is that alpha is a *power* attenuation coefficient and a linear operator carries -alpha/2 -- see `Modes.alpha` feeding `LinearOps.make_const_linop`. `Boundaries` used the same symbol for a field-amplitude rate and subtracted it from the linop whole, so the two meanings collided in the one place they meet. Redefine the coefficient as a power one, alpha = -2 log(W)/l, and have `addloss` subtract alpha/2. The relation to the historical profiles is unchanged and still stated in terms of the field, since that is what they multiplied: over one reference length the field is attenuated by exactly W, i.e. exp(-alpha*l/2) == W. `boundary_N` and `boundary_length` keep their meaning. The temporal factor in `Luna.run` and the walk-off diagnostic both act on the field, so both gain the same factor of 2, and `MAX_alpha_l` becomes 60 so the floor on the profile stays exp(-30). This is a pure change of convention: every factor of 2 introduced is cancelled by one already there, and the scalings are exact in binary, so the result is bit-identical. Checked on the walk-off case -- the final field hashes to a26bdbac before and after. Co-Authored-By: Claude Opus 5 --- src/Boundaries.jl | 64 +++++++++++++++++++++++------------------ src/Luna.jl | 2 +- test/test_boundaries.jl | 15 +++++----- 3 files changed, 45 insertions(+), 36 deletions(-) diff --git a/src/Boundaries.jl b/src/Boundaries.jl index ca96ddcaf..97ec4c31b 100644 --- a/src/Boundaries.jl +++ b/src/Boundaries.jl @@ -9,26 +9,28 @@ absorption `W^N`, where `N` is the number of steps the adaptive controller happe take — so the answer depended on `rtol` and never converged. (With the step counts of a typical run, `W^N` is not a taper at all: it is a brick wall at the edge of the flat region, which is why the old scheme eroded genuine spectral wings.) An absorbing boundary -must instead have an absorption *rate per unit propagation distance* `α`, so that -traversing a distance `L` attenuates by `exp(-αL)` however that path is subdivided. +must instead have an absorption *coefficient per unit propagation distance* `α`, so that +traversing a distance `L` attenuates by a fixed factor however that path is subdivided. -This module turns the historical taper profiles into rates, +`α` here is a **power** absorption coefficient, as everywhere else in Luna (`Modes.α`, +`LinearOps`): power falls as `exp(-αL)`, the field as `exp(-αL/2)`, and a linear operator +carries `-α/2`. This module turns the historical taper profiles into such coefficients, - α(x) = -log(W(x)) / ℓ + α(x) = -2 log(W(x)) / ℓ -where `ℓ` is a reference length: propagating through `ℓ` attenuates the field by exactly -the historical profile once. `ℓ` defaults to `zmax/N`, i.e. "the historical window is -applied `N` times over the whole propagation". +where `ℓ` is a reference length: propagating through `ℓ` attenuates the *field* by exactly +the historical profile once, since the profiles were applied to the field. `ℓ` defaults to +`zmax/N`, i.e. "the historical window is applied `N` times over the whole propagation". The two rates are then applied by different mechanisms, chosen by what the existing machinery can do *exactly*: - `α_ω` is diagonal in ω, so it is folded into the linear operator ([`addloss`](@ref)) and - the interaction-picture propagator applies `exp(-α_ω Δz)` exactly, for whatever + the interaction-picture propagator applies `exp(-α_ω Δz/2)` exactly, for whatever sub-interval the stepper uses, at no extra cost, and consistently with dense output. - `α_t` is diagonal in `t`, so it cannot ride the propagator. It is applied as an - exponential split-step factor `exp(-α_t Δz)` in `Luna.run`'s `stepfun`. Those factors - telescope exactly to `exp(-α_t L)` regardless of the step layout, so the *total* + exponential split-step factor `exp(-α_t Δz/2)` in `Luna.run`'s `stepfun`. Those factors + telescope exactly to `exp(-α_t L/2)` regardless of the step layout, so the *total* absorption is still a rate. (This is a first-order Lie splitting, but the commutator is supported only inside the collar, where the field is being destroyed anyway.) @@ -51,7 +53,8 @@ const DEFAULT_N = 20 "Default minimum temporal collar width, as a fraction of the full time window." const DEFAULT_TCOLLAR = 0.05 -#= Cap on α*ℓ, i.e. on the depth of the absorber over one reference length. +#= Cap on α*ℓ, i.e. on the depth of the absorber over one reference length. α is a power + coefficient, so the field is attenuated by at most exp(-MAX_αℓ/2) over ℓ. RK45's `fbar!` back-propagates the RHS with exp(-linop*Δz), i.e. it *amplifies* by exp(+α Δz) for a decaying linop. Two things follow. @@ -66,9 +69,10 @@ const DEFAULT_TCOLLAR = 0.05 rejections. The saving grace is that the nonlinear drive is itself ∝ ωwin = exp(-α ℓ), so the amplified drive scales as exp(α(Δz - ℓ)) — bounded by 1 as long as Δz ≤ ℓ, for any α. `Luna.run` therefore caps `max_dz` (and `init_dz`) at ℓ, and this constant then - only has to keep exp(α Δz) ≤ exp(MAX_αℓ) finite. exp(30) ≈ 1e13, and the corresponding - floor on the profile, exp(-30) ≈ 1e-13, is far below anything physically meaningful. =# -const MAX_αℓ = 30.0 + only has to keep exp(α Δz/2) ≤ exp(MAX_αℓ/2) finite. exp(30) ≈ 1e13, and the + corresponding floor on the profile, exp(-30) ≈ 1e-13, is far below anything physically + meaningful. =# +const MAX_αℓ = 60.0 """ reflength(grid, N, ℓ) @@ -98,16 +102,17 @@ end rate(W, ℓ) Convert an apodisation profile `W ∈ [0, 1]` (1 in the interior, falling to 0 at the -boundary) into a field-amplitude absorption rate in 1/m, such that propagating through `ℓ` -attenuates the field by `W`. Exactly zero where `W == 1`, and clamped at -`MAX_αℓ/ℓ` so that `W == 0` gives a large but finite rate. +boundary) into a power absorption coefficient in 1/m, such that propagating through `ℓ` +attenuates the *field* by `W` — that is, `exp(-αℓ/2) == W`, since the historical profiles +multiplied the field. Exactly zero where `W == 1`, and clamped at `MAX_αℓ/ℓ` so that +`W == 0` gives a large but finite coefficient. """ -rate(W, ℓ) = clamp.(.-log.(W) ./ ℓ, 0.0, MAX_αℓ/ℓ) +rate(W, ℓ) = clamp.(.-2 .* log.(W) ./ ℓ, 0.0, MAX_αℓ/ℓ) """ spectral_rate(grid; N=DEFAULT_N, ℓ=nothing) -Field-amplitude absorption rate in 1/m across the frequency grid, derived from +Power absorption coefficient in 1/m across the frequency grid, derived from `grid.ωwin`. Exactly zero outside `grid.sidx`, where the linear operator is zero by construction and the hard mask [`ωmask`](@ref) applies instead. """ @@ -159,7 +164,7 @@ end """ temporal_rate(grid; N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) -Field-amplitude absorption rate in 1/m across the time grid. +Power absorption coefficient in 1/m across the time grid. """ temporal_rate(grid; N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) = rate(tprofile(grid; collar), reflength(grid, N, ℓ)) @@ -180,10 +185,11 @@ the polarisation, and the linear operator is zero there — nothing else removes """ addloss(linop, α) -Add the field-amplitude absorption rate `α` (a vector over ω) to a linear operator, -returning a linop of the same kind, so that `RK45.make_prop!` dispatch and -`Luna.linoptype` are unchanged. Handles both forms Luna uses: a materialised -`AbstractArray` and a closure `linop!(out, z)`. +Add the power absorption coefficient `α` (a vector over ω) to a linear operator as +`-α/2`, which is how loss enters a linop everywhere in Luna (see `LinearOps`). Returns a +linop of the same kind, so that `RK45.make_prop!` dispatch and `Luna.linoptype` are +unchanged. Handles both forms Luna uses: a materialised `AbstractArray` and a closure +`linop!(out, z)`. ω is axis 1 for every linop shape — `(Nω,)` mode-averaged, `(Nω, nmodes)` multimode, `(Nω, q.N)` radial, `(Nω, Nky, Nkx)` free-space — so one broadcast covers all of them. @@ -193,12 +199,12 @@ The array method **allocates a copy** rather than subtracting in place: identical fibre, i.e. the same linop is deliberately reused across `Luna.run` calls, and an in-place subtraction would compound the absorber on every reuse. """ -addloss(linop::AbstractArray, α) = linop .- α +addloss(linop::AbstractArray, α) = linop .- α./2 function addloss(linop!, α) function linop_absorbing!(out, z) linop!(out, z) - out .-= α + out .-= α./2 out end end @@ -243,10 +249,12 @@ function walkoff_check(grid, L, αt, collarwidth; quantile=0.95, threshold=1e-2) τq = τ[clamp(ceil(Int, quantile*length(τ)), 1, length(τ))] τq > 0 || return nothing zcross = collarwidth/τq # distance to walk across the collar - # mean rate through the collar, i.e. what such a component actually experiences + #= Mean coefficient through the collar, i.e. what such a component actually + experiences. αt is a power coefficient and `threshold` is a field retention, hence + the factor of 2. =# collar = filter(>(0), αt) isempty(collar) && return nothing - att = exp(-sum(collar)/length(collar)*zcross) + att = exp(-sum(collar)/length(collar)*zcross/2) if att > threshold Logging.@warn(@sprintf( "Temporal absorbing boundary may be too weak: a component walking off at \ diff --git a/src/Luna.jl b/src/Luna.jl index e305b4276..31379dc09 100644 --- a/src/Luna.jl +++ b/src/Luna.jl @@ -486,7 +486,7 @@ function run(Eω, grid, Eω .*= ωmask # idempotent hard band limit, so no rate treatment needed if Δz > 0 @inbounds for i in tidcs - tfac[i] = exp(-αt[i]*Δz) + tfac[i] = exp(-αt[i]*Δz/2) # αt is a power coefficient, tfac hits the field end ldiv!(Et, FT, Eω) # NB: for a RealGrid rfft plan this destroys Eω Et .*= tfac diff --git a/test/test_boundaries.jl b/test/test_boundaries.jl index 7667226c4..9a5771020 100644 --- a/test/test_boundaries.jl +++ b/test/test_boundaries.jl @@ -21,9 +21,10 @@ grid = Grid.RealGrid(0.3, 800e-9, (150e-9, 4e-6), 1e-12) @test all(α .>= 0) @test all(α[grid.ωwin .== 1] .== 0) @test maximum(α) <= Boundaries.MAX_αℓ/ℓ*(1 + 1e-12) -# the rate reproduces the profile over one reference length, where it is not clamped -unclamped = grid.ωwin .> exp(-Boundaries.MAX_αℓ) -@test isapprox(exp.(-α[unclamped].*ℓ), grid.ωwin[unclamped]; rtol=1e-12) +#= α is a power coefficient, so the field over one reference length goes as exp(-αℓ/2) and + that is what must reproduce the profile, where it is not clamped. =# +unclamped = grid.ωwin .> exp(-Boundaries.MAX_αℓ/2) +@test isapprox(exp.(-α[unclamped].*ℓ./2), grid.ωwin[unclamped]; rtol=1e-12) #= Telescoping: this is the whole point. Applying exp(-α dz) over any partition of [0, L] gives exactly exp(-α L), so the absorption cannot depend on the step layout. =# @@ -31,7 +32,7 @@ i = findfirst(x -> 0 < x < 1, grid.ωwin) for n in (3, 17, 200) dzs = rand(n) dzs .*= 0.3/sum(dzs) - @test isapprox(prod(exp.(-α[i].*dzs)), exp(-α[i]*0.3); rtol=1e-12) + @test isapprox(prod(exp.(-α[i].*dzs./2)), exp(-α[i]*0.3/2); rtol=1e-12) end # ωwin is exactly zero outside the simulation band, so the hard mask is grid.sidx @@ -70,7 +71,7 @@ for sz in ((Nω,), (Nω, 4), (Nω, 8), (Nω, 8, 6)) @test size(La) == size(L) @test imag(La) == imag(L) # dispersion untouched trailing = ntuple(_ -> 1, length(sz) - 1) - @test real(La)[:, trailing...] ≈ real(L)[:, trailing...] .- α + @test real(La)[:, trailing...] ≈ real(L)[:, trailing...] .- α./2 # linops carry -α/2 # the closure form must agree with the array form Lc! = (out, z) -> (out .= L) Lac! = Boundaries.addloss(Lc!, α) @@ -100,7 +101,7 @@ for n in (2, 7, 1000) end @test isapprox(many, onestep; rtol=1e-12) end -@test isapprox(abs.(onestep), exp.(-α.*0.3); rtol=1e-12) +@test isapprox(abs.(onestep), exp.(-α.*0.3./2); rtol=1e-12) end @testset "temporal absorber converges to the rate limit" begin @@ -130,7 +131,7 @@ function bare_run(; kwargs...) end reldiff(a, b) = sqrt(sum(abs2, a .- b))/sqrt(sum(abs2, b)) -expected = (FT*((FT \ Eω0) .* exp.(-αt.*grid.zmax))) .* mask +expected = (FT*((FT \ Eω0) .* exp.(-αt.*grid.zmax./2))) .* mask coarse = reldiff(bare_run(init_dz=1e-3), expected) # 20 steps fine = reldiff(bare_run(init_dz=1e-5, max_dz=grid.zmax/500), expected) # 500 steps @test coarse < 1e-3 From 9f422803343c0f12c7f072d15dfdeda11ec3d891 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 20 Aug 2026 11:56:52 +0100 Subject: [PATCH 6/9] Band-limit the nonlinear polarisation in TransModeAvg, not the field MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Boundaries.ωmask` existed to mop up after one transform. `TransModeAvg` normalises before windowing and `norm_mode_average` skips everything outside `grid.sidx` -- it has to, because β is only filled in-band and the normalisation divides by it -- so the out-of-band part of `nl` was left as the raw, unnormalised transform of the polarisation. The linear operator is zero there, so nothing removed it and every step of `run` had to multiply the field by a 0/1 mask. No other transform has this problem: `TransModal` windows before it normalises, and the radial and free-space norms return 1.0 out of band, so in all three cases `ωwin` (exactly zero outside `sidx`) already zeroes it. So fix it where it happens: zero `nl` out of band in `norm_mode_average` and `norm_mode_average_gnlse`, which also lets `TransModeAvg` window the whole array like the others rather than looping with a `continue`. With `nl` zero out of band and the linop zero there, nothing can put anything back, so `ωmask` and both per-step multiplies go, replaced by a single band limit on the field at the start of `run`. `:legacy` is excluded from that initial band limit so it stays a bit-identical reproduction of the historical scheme; its own per-step `ωwin` multiply does the same job from the first step. Removing the mask also removes its non-commutation with the temporal factor, so the residual splitting error in the temporal absorber is now only against the spectral absorber on the propagator. Co-Authored-By: Claude Opus 5 --- src/Boundaries.jl | 22 +++++----------------- src/Luna.jl | 27 +++++++++++++-------------- src/NonlinearRHS.jl | 19 +++++++++++++------ test/test_boundaries.jl | 13 +++++++------ 4 files changed, 38 insertions(+), 43 deletions(-) diff --git a/src/Boundaries.jl b/src/Boundaries.jl index 97ec4c31b..6aae36ffb 100644 --- a/src/Boundaries.jl +++ b/src/Boundaries.jl @@ -34,9 +34,10 @@ machinery can do *exactly*: absorption is still a rate. (This is a first-order Lie splitting, but the commutator is supported only inside the collar, where the field is being destroyed anyway.) -Separately from both, the *hard* band limit — the 0/1 part of the spectral window — stays a -per-step multiply. A 0/1 mask is idempotent, so it never suffered from the `W^N` problem, -and it is not optional: see [`ωmask`](@ref). +The *hard* band limit — the 0/1 part of the spectral window — is not applied here at all. +`NonlinearRHS` zeroes the nonlinear polarisation outside `grid.sidx` and the linear operator +is zero there, so once the field has been band-limited at the start of `Luna.run` nothing +can put anything back. See also `Luna.run`'s `boundary` keyword argument. """ @@ -114,7 +115,7 @@ rate(W, ℓ) = clamp.(.-2 .* log.(W) ./ ℓ, 0.0, MAX_αℓ/ℓ) Power absorption coefficient in 1/m across the frequency grid, derived from `grid.ωwin`. Exactly zero outside `grid.sidx`, where the linear operator is zero by -construction and the hard mask [`ωmask`](@ref) applies instead. +construction and there is nothing left to absorb. """ function spectral_rate(grid; N=DEFAULT_N, ℓ=nothing) α = rate(grid.ωwin, reflength(grid, N, ℓ)) @@ -169,19 +170,6 @@ Power absorption coefficient in 1/m across the time grid. temporal_rate(grid; N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) = rate(tprofile(grid; collar), reflength(grid, N, ℓ)) -""" - ωmask(grid) - -The hard band limit, as a 0/1 multiplier over ω: `float.(grid.sidx)`. - -This is **not** optional and is not part of the graded absorber. `NonlinearRHS.TransModeAvg` -skips both the normalisation and the `ωwin` multiply outside `grid.sidx` -(`!t.grid.sidx[i] && continue`), so out-of-band `nl` is the raw, unnormalised transform of -the polarisation, and the linear operator is zero there — nothing else removes it. Being a -0/1 mask it is idempotent, so applying it every step was never step-count dependent. -""" -ωmask(grid) = float.(grid.sidx) - """ addloss(linop, α) diff --git a/src/Luna.jl b/src/Luna.jl index 31379dc09..d37a28708 100644 --- a/src/Luna.jl +++ b/src/Luna.jl @@ -411,11 +411,10 @@ Run the propagation. `grid.ωwin` and `grid.twin` after every accepted step. This makes the cumulative absorption depend on the step count and hence on `rtol`, so the result does not converge as the tolerance is tightened. Provided only to reproduce older results. - - `:none` disables the graded absorbers. The hard band limit outside `grid.sidx` is - still applied (it is a 0/1 mask, so it never had a step-count dependence), and the - nonlinear polarisation is still band-limited in `NonlinearRHS`, but nothing stops - energy wrapping around the time window or piling up at the edge of the frequency - window. + - `:none` disables the absorbers. The nonlinear polarisation is still band-limited in + `NonlinearRHS` and the field is still band-limited once at the start, but nothing + stops energy wrapping around the time window or piling up at the edge of the + frequency window. - `boundary_N::Real=$(Boundaries.DEFAULT_N)`: absorber strength, expressed as the number of times the historical window profile is applied over the whole propagation length. The reference length is `ℓ = zmax/boundary_N`. @@ -449,7 +448,14 @@ function run(Eω, grid, #= NOTE: everything below must come after check_cache, which can move z0 and init_dz: zprev seeds the distance the temporal absorber is applied over. =# ℓabs = Boundaries.reflength(grid, boundary_N, boundary_length) - ωmask = Boundaries.ωmask(grid) + + #= Band-limit the field once, here, rather than after every step. `NonlinearRHS` zeroes + the nonlinear polarisation outside `grid.sidx` and the linear operator is zero there, + so nothing can put anything back; all this removes is the numerical dust the input + transform leaves outside the band. Not for :legacy, which must reproduce the + historical scheme exactly -- its per-step `ωwin` multiply does the same job from the + first step anyway. =# + boundary === :legacy || (Eω[.!grid.sidx, ntuple(_ -> :, ndims(Eω) - 1)...] .= 0) stepfun = if boundary === :rate #= The stepper must resolve the absorber's reference length. RK45's fbar! amplifies @@ -483,7 +489,6 @@ function run(Eω, grid, solver subdivides the propagation. =# Δz = z - zprev[] zprev[] = z - Eω .*= ωmask # idempotent hard band limit, so no rate treatment needed if Δz > 0 @inbounds for i in tidcs tfac[i] = exp(-αt[i]*Δz/2) # αt is a power coefficient, tfac hits the field @@ -506,13 +511,7 @@ function run(Eω, grid, output(Eω, z, dz, interpolant) end else - #= Even with no absorber the hard band limit has to stay: TransModeAvg leaves the - out-of-band part of nl unnormalised and unwindowed, and the linear operator is - zero there, so nothing else removes it. =# - function stepfun_none(Eω, z, dz, interpolant) - Eω .*= ωmask - output(Eω, z, dz, interpolant) - end + stepfun_none(Eω, z, dz, interpolant) = output(Eω, z, dz, interpolant) end output(Grid.to_dict(grid), group="grid") diff --git a/src/NonlinearRHS.jl b/src/NonlinearRHS.jl index d2567cce5..f5442c45a 100644 --- a/src/NonlinearRHS.jl +++ b/src/NonlinearRHS.jl @@ -460,10 +460,7 @@ function (t::TransModeAvg)(nl, Eω, z) @. t.Pto *= t.grid.towin to_freq!(nl, t.Pωo, t.Pto, t.FT) t.norm!(nl, z) - for i in eachindex(nl) - !t.grid.sidx[i] && continue - nl[i] *= t.grid.ωwin[i] - end + @. nl *= t.grid.ωwin # zero outside the simulation band, where ωwin is exactly 0 end function norm_mode_average(grid, βfun!, aeff; shock=true) @@ -474,7 +471,14 @@ function norm_mode_average(grid, βfun!, aeff; shock=true) βfun!(β, z) sqrtaeff = sqrt(aeff(z)) for i in eachindex(nl) - !grid.sidx[i] && continue + #= β is only filled inside the simulation band, so the normalisation cannot be + evaluated outside it. Zero nl there rather than skipping: skipping leaves the + raw, unnormalised transform of the polarisation in place, and since the + linear operator is also zero out of band, nothing downstream removes it. =# + if !grid.sidx[i] + nl[i] = 0 + continue + end nl[i] *= pre[i]/β[i]*sqrtaeff end end @@ -486,7 +490,10 @@ function norm_mode_average_gnlse(grid, aeff; shock=true) function norm!(nl, z) sqrtaeff = sqrt(aeff(z)) for i in eachindex(nl) - !grid.sidx[i] && continue + if !grid.sidx[i] # as in norm_mode_average + nl[i] = 0 + continue + end nl[i] *= pre[i]*sqrtaeff end end diff --git a/test/test_boundaries.jl b/test/test_boundaries.jl index 9a5771020..7278ddd39 100644 --- a/test/test_boundaries.jl +++ b/test/test_boundaries.jl @@ -108,14 +108,15 @@ end #= Zero RHS and zero linear operator, so the only thing acting on the field is the temporal absorber applied in Luna.run's stepfun, whose target is exp(-α_t L) applied once. - The exponential factors telescope exactly, but the hard band mask is interleaved with - them and the two do not commute, so the result approaches exp(-α_t L) as the steps get - smaller rather than matching it exactly. That is a splitting error of the same order as - the temporal splitting itself, and — unlike the historical scheme — it converges. =# + The exponential factors telescope exactly among themselves, but the spectral absorber + rides the propagator in between them and the two do not commute, so the result approaches + exp(-α_t L/2) as the steps get smaller rather than matching it exactly. That is a + splitting error of the same order as the temporal splitting itself, and — unlike the + historical scheme — it converges. =# grid = Grid.EnvGrid(0.2, 800e-9, (400e-9, 2e-6), 1e-12) FT = FFTW.plan_fft(zeros(ComplexF64, length(grid.t))) αt = Boundaries.temporal_rate(grid) -mask = Boundaries.ωmask(grid) +mask = float.(grid.sidx) # the band limit Luna.run applies once, at the start # deliberately wide, so that the field actually overlaps the absorber collar Et0 = Maths.gauss.(grid.t, fwhm=0.5*(maximum(grid.t) - minimum(grid.t))) .+ 0im Eω0 = (FT*Et0) .* mask @@ -137,7 +138,7 @@ fine = reldiff(bare_run(init_dz=1e-5, max_dz=grid.zmax/500), expected) # 500 st @test coarse < 1e-3 @test fine < 10*coarse/25 # converges at least first order in the step size -# :none applies only the (idempotent) hard band limit +# with nothing driving it and no absorber, :none must leave the field exactly alone @test bare_run(boundary=:none) == Eω0 # :legacy applies the whole window once per step and does not approach the rate limit legacy = Logging.with_logger(Logging.NullLogger()) do From 80195a21f5e6897ffeda646b3925dd81acd036e8 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 20 Aug 2026 12:01:31 +0100 Subject: [PATCH 7/9] Make the absorbing boundaries functors behind one setup call Setting up the boundaries was an `if` expression whose *value* was the stepfun but which also reassigned `max_dz`, `init_dz` and `linop` in the enclosing scope, so `run` had to be read for side effects as well as for its result. Move it into `Boundaries.setup`, which returns `(; stepfun, linop, max_dz, init_dz, l)` -- the three it changes are handed back rather than mutated from inside a branch, and why each one changes is documented on `setup` instead of in a comment halfway down `run`. The stepfuns become functors: `RateAbsorber`, `LegacyAbsorber`, `NoAbsorber`. That gives `setup` one return type per mode, names the state each carries instead of capturing it, and means the spatial windows a free-space simulation wants become another struct rather than another branch inside `run`. `linop_array` and the setup log line move across with them, since nothing else uses either. The reference length is now only computed for `:rate`, so a stray `boundary_N` no longer gets validated in a mode which never looks at it. Pure restructuring: the walk-off case hashes to e019a5fd before and after. Co-Authored-By: Claude Opus 5 --- src/Boundaries.jl | 158 ++++++++++++++++++++++++++++++++++++++++++++++ src/Luna.jl | 103 +++--------------------------- 2 files changed, 166 insertions(+), 95 deletions(-) diff --git a/src/Boundaries.jl b/src/Boundaries.jl index 6aae36ffb..8021141b9 100644 --- a/src/Boundaries.jl +++ b/src/Boundaries.jl @@ -45,6 +45,7 @@ module Boundaries import ..Maths import ..Grid +import LinearAlgebra: mul!, ldiv! import Logging import Printf: @sprintf @@ -253,4 +254,161 @@ function walkoff_check(grid, L, αt, collarwidth; quantile=0.95, threshold=1e-2) nothing end +# --------------------------------------------------------------------------- application + +#= The three ways a boundary can be applied per accepted step. Each is a functor rather than + a closure so that `setup` has one return type per mode, the state each needs is named, + and a new kind of boundary (the spatial windows a free-space simulation wants) is another + struct rather than another branch inside `Luna.run`. Each ends by calling `output`, + because that is what `RK45.solve` expects of a `stepfun`. =# + +""" + RateAbsorber(αt, Et, FT, output, z0) + +Applies the temporal absorber as `exp(-αt Δz/2)` over the distance actually travelled. +Successive factors telescope to `exp(-αt L/2)` however the solver subdivides the +propagation, which is the whole point of rate semantics. The spectral absorber is not here: +it rides the propagator, having been folded into the linear operator by [`addloss`](@ref). +""" +struct RateAbsorber{tT, fT, oT} + αt::Vector{Float64} + tidcs::Vector{Int} # only the collar is ever ≠ 1, so only those need updating each step + tfac::Vector{Float64} + Et::tT + FT::fT + output::oT + zprev::Base.RefValue{Float64} +end + +RateAbsorber(αt, Et, FT, output, z0) = RateAbsorber( + αt, findall(>(0), αt), ones(Float64, length(αt)), Et, FT, output, Ref(float(z0))) + +function (b::RateAbsorber)(Eω, z, dz, interpolant) + Δz = z - b.zprev[] + b.zprev[] = z + if Δz > 0 + @inbounds for i in b.tidcs + b.tfac[i] = exp(-b.αt[i]*Δz/2) # αt is a power coefficient, tfac hits the field + end + #= An inverse real FFT overwrites its input, so between these two lines Eω holds + whatever FFTW left there and must not be read; the forward transform refills it. =# + ldiv!(b.Et, b.FT, Eω) + b.Et .*= b.tfac + mul!(Eω, b.FT, b.Et) + end + b.output(Eω, z, dz, interpolant) +end + +""" + LegacyAbsorber(grid, Et, FT, output) + +The historical scheme: multiply the solution by the fixed profiles once per accepted step. +Kept only so that results from before rate semantics can be reproduced exactly. +""" +struct LegacyAbsorber{gT, tT, fT, oT} + grid::gT + Et::tT + FT::fT + output::oT +end + +function (b::LegacyAbsorber)(Eω, z, dz, interpolant) + Eω .*= b.grid.ωwin + ldiv!(b.Et, b.FT, Eω) # destroys Eω, see RateAbsorber + b.Et .*= b.grid.twin + mul!(Eω, b.FT, b.Et) + b.output(Eω, z, dz, interpolant) +end + +""" + NoAbsorber(output) + +No boundary at all. The field is still band-limited once at the start of `Luna.run` and the +nonlinear polarisation is still band-limited in `NonlinearRHS`, but nothing stops energy +wrapping around the time window or piling up at the edge of the frequency window. +""" +struct NoAbsorber{oT} + output::oT +end + +(b::NoAbsorber)(Eω, z, dz, interpolant) = b.output(Eω, z, dz, interpolant) + +""" + linop_array(linop, Eω, z) + +The linear operator as an array, materialising the z-dependent (closure) form at `z`. The +linop has the same shape as the field, which is how `RK45.make_prop!` allocates its own +buffer. +""" +linop_array(linop::AbstractArray, Eω, z) = linop +function linop_array(linop!, Eω, z) + out = similar(Eω) + linop!(out, z) + out +end + +"Report the absorbing-boundary configuration." +function log_setup(grid, ℓ, collar) + w = tcollarwidth(grid, collar) + trange = maximum(grid.t) - minimum(grid.t) + #= The clamp in `rate` is not worth reporting: it bites only where the profile is + already below exp(-30), and even there the attenuation over the whole propagation is + exp(-30 zmax/ℓ). What is worth reporting is the strength the user actually chose, so + quote the attenuation over the propagation at the half-way point of a taper. =# + Logging.@info(@sprintf( + "Absorbing boundaries: rate-based, reference length %.3g m (%.3g applications of \ + the window profile over %.3g m; a 50%% point of the taper attenuates by %.1e over \ + the propagation). Temporal collar %.3g fs, %.1f%% of the time window.", + ℓ, grid.zmax/ℓ, grid.zmax, 0.5^(grid.zmax/ℓ), w*1e15, 100*w/trange)) +end + +""" + setup(boundary, grid, linop, Eω, Et, FT, output, z0, max_dz, init_dz; + N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) + +Everything `Luna.run` needs in order to apply absorbing boundaries, as a named tuple +`(; stepfun, linop, max_dz, init_dz, ℓ)`. `ℓ` is the reference length actually used, or +`nothing` for the modes which do not have one. + +Three of those are returned because setting up an absorber genuinely changes them, and it is +clearer to hand them back than to mutate them from inside a branch: + +- `linop` gains the spectral absorber, which the interaction-picture propagator then applies + exactly (see [`addloss`](@ref)). +- `max_dz` is capped at the reference length `ℓ`, and `init_dz` with it. RK45's `fbar!` + amplifies the RHS by `exp(+α Δz/2)` while the nonlinear drive it acts on is ∝ `exp(-α ℓ/2)`, + so the amplified band-edge elements stay bounded — and stay small in `weaknorm`'s global + sum — only while `Δz ≤ ℓ`. This costs nothing in practice: it requires at least `N` steps + and real runs take far more. +""" +function setup(boundary, grid, linop, Eω, Et, FT, output, z0, max_dz, init_dz; + N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) + ℓabs = nothing + if boundary === :rate + ℓabs = reflength(grid, N, ℓ) + if max_dz > ℓabs + Logging.@info(@sprintf( + "Reducing max_dz from %.3g m to the absorber reference length %.3g m.", + max_dz, ℓabs)) + max_dz = ℓabs + end + init_dz = min(init_dz, max_dz) + αt = temporal_rate(grid; N, ℓ, collar) + walkoff_check(grid, linop_array(linop, Eω, z0), αt, tcollarwidth(grid, collar)) + linop = addloss(linop, spectral_rate(grid; N, ℓ)) + log_setup(grid, ℓabs, collar) + stepfun = RateAbsorber(αt, Et, FT, output, z0) + elseif boundary === :legacy + Logging.@warn( + "boundary=:legacy applies the absorbing boundaries once per accepted step, " * + "so the absorption depends on the step count and the result depends on rtol.") + stepfun = LegacyAbsorber(grid, Et, FT, output) + elseif boundary === :none + stepfun = NoAbsorber(output) + else + error("boundary must be :rate, :legacy or :none, not $boundary") + end + (; stepfun, linop, max_dz, init_dz, ℓ=ℓabs) +end + end diff --git a/src/Luna.jl b/src/Luna.jl index d37a28708..9e98dd52b 100644 --- a/src/Luna.jl +++ b/src/Luna.jl @@ -3,7 +3,6 @@ import FFTW import Hankel import Logging import LinearAlgebra: mul!, ldiv! -import Printf: @sprintf Logging.disable_logging(Logging.BelowMinLevel) """ @@ -337,20 +336,6 @@ end linoptype(l::AbstractArray) = "constant" linoptype(l) = "variable" -""" - linop_array(linop, Eω, z) - -The linear operator as an array, materialising the z-dependent (closure) form at `z`. The -linop has the same shape as the field, which is how `RK45.make_prop!` allocates its own -buffer. -""" -linop_array(linop::AbstractArray, Eω, z) = linop -function linop_array(linop!, Eω, z) - out = similar(Eω) - linop!(out, z) - out -end - gridtype(g::Grid.RealGrid) = "field-resolved" gridtype(g::Grid.EnvGrid) = "envelope" gridtype(g) = "unknown" @@ -379,22 +364,6 @@ sym2string(other) = other save_modeinfo_maybe(output, t) = nothing -"Report the absorbing-boundary configuration." -function log_boundary(grid, N, ℓ, collar) - l = Boundaries.reflength(grid, N, ℓ) - w = Boundaries.tcollarwidth(grid, collar) - trange = maximum(grid.t) - minimum(grid.t) - #= The clamp in Boundaries.rate is not worth reporting: it bites only where the profile - is already below exp(-30), and even there the attenuation over the whole propagation - is exp(-30 zmax/ℓ). What is worth reporting is the strength the user actually chose, - so quote the attenuation over the propagation at the half-way point of a taper. =# - Logging.@info(@sprintf( - "Absorbing boundaries: rate-based, reference length %.3g m (%.3g applications of \ - the window profile over %.3g m; a %.0f%% point of the taper attenuates by %.1e \ - over the propagation). Temporal collar %.3g fs, %.1f%% of the time window.", - l, grid.zmax/l, grid.zmax, 50, 0.5^(grid.zmax/l), w*1e15, 100*w/trange)) -end - """ run(Eω, grid, linop, transform, FT, output; kwargs...) @@ -433,9 +402,6 @@ function run(Eω, grid, boundary=:rate, boundary_N=Boundaries.DEFAULT_N, boundary_length=nothing, tcollar=Boundaries.DEFAULT_TCOLLAR) - boundary in (:rate, :legacy, :none) || error( - "boundary must be :rate, :legacy or :none, not $boundary") - Et = FT \ Eω # check_cache does nothing except for HDF5Outputs @@ -445,9 +411,13 @@ function run(Eω, grid, Eω, z0, init_dz = Eωc, zc, dzc end - #= NOTE: everything below must come after check_cache, which can move z0 and init_dz: - zprev seeds the distance the temporal absorber is applied over. =# - ℓabs = Boundaries.reflength(grid, boundary_N, boundary_length) + #= NOTE: this must come after check_cache, which can move z0 and init_dz: the temporal + absorber measures the distance it is applied over from z0. =# + absorber = Boundaries.setup(boundary, grid, linop, Eω, Et, FT, output, z0, + max_dz, init_dz; + N=boundary_N, ℓ=boundary_length, collar=tcollar) + stepfun = absorber.stepfun + linop, max_dz, init_dz = absorber.linop, absorber.max_dz, absorber.init_dz #= Band-limit the field once, here, rather than after every step. `NonlinearRHS` zeroes the nonlinear polarisation outside `grid.sidx` and the linear operator is zero there, @@ -457,67 +427,10 @@ function run(Eω, grid, first step anyway. =# boundary === :legacy || (Eω[.!grid.sidx, ntuple(_ -> :, ndims(Eω) - 1)...] .= 0) - stepfun = if boundary === :rate - #= The stepper must resolve the absorber's reference length. RK45's fbar! amplifies - the RHS by exp(+α Δz) while the nonlinear drive it acts on is ∝ exp(-α ℓ), so the - amplified band-edge elements stay bounded — and stay small in weaknorm's global - sum — only while Δz ≤ ℓ. This costs nothing in practice: it just requires at - least boundary_N steps, and real runs take far more. =# - if max_dz > ℓabs - Logging.@info(@sprintf( - "Reducing max_dz from %.3g m to the absorber reference length %.3g m.", - max_dz, ℓabs)) - max_dz = ℓabs - end - init_dz = min(init_dz, max_dz) - - αω = Boundaries.spectral_rate(grid; N=boundary_N, ℓ=boundary_length) - αt = Boundaries.temporal_rate(grid; N=boundary_N, ℓ=boundary_length, - collar=tcollar) - Boundaries.walkoff_check(grid, linop_array(linop, Eω, z0), αt, - Boundaries.tcollarwidth(grid, tcollar)) - linop = Boundaries.addloss(linop, αω) - log_boundary(grid, boundary_N, boundary_length, tcollar) - - # only the collar entries are ever ≠ 1, so only those need updating each step - tidcs = findall(>(0), αt) - tfac = ones(Float64, length(grid.t)) - zprev = Ref(float(z0)) - function stepfun_rate(Eω, z, dz, interpolant) - #= The absorption applied here is exp(-αt*Δz) over the distance actually - travelled, so successive factors telescope to exp(-αt*L) no matter how the - solver subdivides the propagation. =# - Δz = z - zprev[] - zprev[] = z - if Δz > 0 - @inbounds for i in tidcs - tfac[i] = exp(-αt[i]*Δz/2) # αt is a power coefficient, tfac hits the field - end - ldiv!(Et, FT, Eω) # NB: for a RealGrid rfft plan this destroys Eω - Et .*= tfac - mul!(Eω, FT, Et) - end - output(Eω, z, dz, interpolant) - end - elseif boundary === :legacy - Logging.@warn( - "boundary=:legacy applies the absorbing boundaries once per accepted step, " * - "so the absorption depends on the step count and the result depends on rtol.") - function stepfun_legacy(Eω, z, dz, interpolant) - Eω .*= grid.ωwin - ldiv!(Et, FT, Eω) - Et .*= grid.twin - mul!(Eω, FT, Et) - output(Eω, z, dz, interpolant) - end - else - stepfun_none(Eω, z, dz, interpolant) = output(Eω, z, dz, interpolant) - end - output(Grid.to_dict(grid), group="grid") st = simtype(grid, transform, linop) st["boundary"] = string(boundary) - boundary === :rate && (st["boundary_length"] = string(ℓabs)) + boundary === :rate && (st["boundary_length"] = string(absorber.ℓ)) output(st, group="simulation_type") save_modeinfo_maybe(output, transform) From 539b04d2c8eceda20b879908c586c8aa428a7c87 Mon Sep 17 00:00:00 2001 From: John Travers Date: Thu, 20 Aug 2026 12:06:26 +0100 Subject: [PATCH 8/9] Move the step-size rationale into the docs, and plainer prose Three things, all wording. The fifteen-line comment block on MAX_alpha_l explained why `run` caps `max_dz` -- that belongs where someone hitting the "Reducing max_dz" log line will find it, not hidden above a constant. It becomes a "Step size" section of the module docstring, which is what the Boundaries docs page renders, and the constant keeps a two-line docstring saying what it caps. Plainer language where the jargon was doing no work: "first-order Lie splitting, but the commutator is supported only inside the collar" now says the two parts do not commute, the error is first order in the step size, and it is confined to the collar. "never converged" was too strong, and a reviewer would rightly pick at it. The old scheme does have a limit as rtol tightens -- it is just that the limit is a hard truncation at the edge of the flat region rather than the taper the profile describes. Say that instead, in both the module docstring and the model docs. The model docs also still described the coefficient as a field rate; bring them in line with the power convention and its factor of 2, and note the max_dz cap, which is user-visible. Docs build clean, tests pass, walk-off case still hashes to e019a5fd. Co-Authored-By: Claude Opus 5 --- docs/src/model/model.md | 12 ++++--- src/Boundaries.jl | 69 +++++++++++++++++++++++------------------ src/Luna.jl | 12 ++++--- 3 files changed, 52 insertions(+), 41 deletions(-) diff --git a/docs/src/model/model.md b/docs/src/model/model.md index 75dff9786..318773007 100644 --- a/docs/src/model/model.md +++ b/docs/src/model/model.md @@ -22,16 +22,18 @@ where ``\mathcal{T}_\perp^{-1}`` is simply the inverse of ``\mathcal{T}_\perp`` Both the frequency and the time axes are finite and periodic (they are sampled for FFTs), so energy which reaches the edge of either window does not leave the simulation — it wraps around, and the result is wrong. `Luna` therefore applies absorbing boundaries at the edges of both windows. These matter whenever the spectrum or the pulse genuinely reaches the edge of the grid: soliton self-compression, modulation instability, or a dispersive wave walking out of the time window. -The absorbers are defined by an absorption **rate per unit propagation distance** ``\alpha``, so that propagating a distance ``L`` attenuates the field by ``\mathrm{e}^{-\alpha L}`` no matter how the solver subdivides that distance. The rate is derived from the apodisation profiles ``W`` built by [`Grid`](@ref Grid) as +The absorbers are defined by an absorption **coefficient per unit propagation distance** ``\alpha``, so that propagating a distance ``L`` attenuates by a fixed factor no matter how the solver subdivides that distance. As everywhere else in `Luna`, ``\alpha`` is a *power* coefficient: the power falls as ``\mathrm{e}^{-\alpha L}``, the field as ``\mathrm{e}^{-\alpha L/2}``, and a linear operator carries ``-\alpha/2``. The coefficient is derived from the apodisation profiles ``W`` built by [`Grid`](@ref Grid) as ```math -\alpha(x) = -\frac{\log W(x)}{\ell}\,, +\alpha(x) = -\frac{2\log W(x)}{\ell}\,, ``` -where the reference length ``\ell`` is the distance over which the historical profile is applied exactly once. By default ``\ell = z_\mathrm{max}/N`` with ``N`` set by `boundary_N`, i.e. the profile is applied ``N`` times over the whole propagation. +where the reference length ``\ell`` is the distance over which the historical profile is applied to the field exactly once, i.e. ``\mathrm{e}^{-\alpha\ell/2} = W``. By default ``\ell = z_\mathrm{max}/N`` with ``N`` set by `boundary_N`, i.e. the profile is applied ``N`` times over the whole propagation. -The spectral absorber is diagonal in ``\omega``, so it is simply an imaginary part of ``k(\omega)`` and is added to the linear operator ``\mathcal{L}``. The interaction-picture propagator then applies it *exactly*, over whatever sub-interval the adaptive stepper chooses, at no extra cost. The temporal absorber is diagonal in ``t`` and so cannot ride the propagator; it is applied as a factor ``\mathrm{e}^{-\alpha(t)\Delta z}`` after each accepted step. Because these factors telescope, the total absorption over a distance is again independent of the step layout. +Because the adaptive stepper has to resolve ``\ell`` for the absorber to behave itself, `Luna.run` reduces `max_dz` to ``\ell`` if it is larger, and says so in the log. In practice this changes nothing — it asks for at least ``N`` steps over the propagation, and real runs take far more. + +The spectral absorber is diagonal in ``\omega``, so it is simply an imaginary part of ``k(\omega)`` and is added to the linear operator ``\mathcal{L}``. The interaction-picture propagator then applies it *exactly*, over whatever sub-interval the adaptive stepper chooses, at no extra cost. The temporal absorber is diagonal in ``t`` and so cannot ride the propagator; it is applied as a factor ``\mathrm{e}^{-\alpha(t)\Delta z/2}`` to the field after each accepted step. Because these factors telescope, the total absorption over a distance is again independent of the step layout. !!! note "Change in behaviour" - Before this scheme was introduced, the absorbing boundaries were applied by multiplying the solution by the fixed profile ``W`` once per accepted step. The cumulative absorption was then ``W^N`` with ``N`` the number of steps — a number the adaptive controller derives from `rtol`. The consequence was that the converged solution depended on the tolerance: tightening `rtol` did not approach a limit, it increased the absorption, and with typical step counts the graded taper acted as a brick wall which eroded genuine spectral wings. Results from that scheme can be reproduced with `boundary=:legacy`, and the absorbers can be switched off entirely with `boundary=:none`. See [`Luna.run`](@ref) and [`Boundaries`](@ref Boundaries.Boundaries). + Before this scheme was introduced, the absorbing boundaries were applied by multiplying the solution by the fixed profile ``W`` once per accepted step. The cumulative absorption was then ``W^N`` with ``N`` the number of steps — a number the adaptive controller derives from `rtol`. The consequence was that the solution depended on the tolerance: tightening `rtol` increased the absorption. Nor does tightening it recover the intended taper — at typical step counts ``W^N`` is a brick wall at the edge of the flat region rather than a taper, and that brick wall is the limit the old scheme approaches. It is what eroded genuine spectral wings. Results from that scheme can be reproduced with `boundary=:legacy`, and the absorbers can be switched off entirely with `boundary=:none`. See [`Luna.run`](@ref) and [`Boundaries`](@ref Boundaries.Boundaries). Note that this is separate from the band-limiting of the nonlinear polarisation which happens inside [`NonlinearRHS`](@ref NonlinearRHS): that is part of the definition of the equation being solved, and is applied to ``P_\mathrm{nl}`` rather than to the field. diff --git a/src/Boundaries.jl b/src/Boundaries.jl index 8021141b9..08c1cb172 100644 --- a/src/Boundaries.jl +++ b/src/Boundaries.jl @@ -5,11 +5,12 @@ Absorbing boundaries with **rate semantics**. Luna's spectral and temporal absorbing boundaries used to be applied by multiplying the solution by a fixed profile `W` after every accepted step. That makes the cumulative -absorption `W^N`, where `N` is the number of steps the adaptive controller happens to -take — so the answer depended on `rtol` and never converged. (With the step counts of a -typical run, `W^N` is not a taper at all: it is a brick wall at the edge of the flat -region, which is why the old scheme eroded genuine spectral wings.) An absorbing boundary -must instead have an absorption *coefficient per unit propagation distance* `α`, so that +absorption `W^N`, where `N` is the number of steps the adaptive controller happens to take, +so the answer depended on `rtol`. Tightening the tolerance does not converge on the taper +the profile describes: at the step counts of a typical run `W^N` is not a taper at all but a +brick wall at the edge of the flat region, and that brick wall is the limit it approaches. +It is why the old scheme eroded genuine spectral wings. An absorbing boundary must instead +have an absorption *coefficient per unit propagation distance* `α`, so that traversing a distance `L` attenuates by a fixed factor however that path is subdivided. `α` here is a **power** absorption coefficient, as everywhere else in Luna (`Modes.α`, @@ -31,14 +32,33 @@ machinery can do *exactly*: - `α_t` is diagonal in `t`, so it cannot ride the propagator. It is applied as an exponential split-step factor `exp(-α_t Δz/2)` in `Luna.run`'s `stepfun`. Those factors telescope exactly to `exp(-α_t L/2)` regardless of the step layout, so the *total* - absorption is still a rate. (This is a first-order Lie splitting, but the commutator is - supported only inside the collar, where the field is being destroyed anyway.) + absorption is still a rate. Interleaving the two parts this way would only be exact if + they commuted, which they do not; the resulting error is first order in the step size and + is confined to the collar, where the field is being destroyed anyway. The *hard* band limit — the 0/1 part of the spectral window — is not applied here at all. `NonlinearRHS` zeroes the nonlinear polarisation outside `grid.sidx` and the linear operator is zero there, so once the field has been band-limited at the start of `Luna.run` nothing can put anything back. +# Step size + +`Luna.run` caps `max_dz` (and `init_dz`) at the reference length `ℓ`. This is not about +accuracy, it is about not confusing the step-size controller. + +RK45 works in the interaction picture, and `fbar!` back-propagates the right-hand side with +`exp(-linop Δz)` — which, for a linop that decays, means it *amplifies* by `exp(+α Δz/2)`. +The elements it amplifies most are at the band edge, where the absorber is deepest. Those +elements are not independent of the rest, because `RK45.weaknorm` sums the error estimate +over every element and divides by the global norm of the solution, so an amplified band-edge +element can come to dominate the error estimate and drive the controller into repeated +rejections. + +What saves it is that the nonlinear drive at the band edge is itself proportional to +`ωwin = exp(-α ℓ/2)`. The amplified drive therefore scales as `exp(α(Δz - ℓ)/2)`, which +stays below 1 for any `α` as long as `Δz ≤ ℓ`. Hence the cap, which costs nothing in +practice: it requires at least `boundary_N` steps, and real runs take far more. + See also `Luna.run`'s `boundary` keyword argument. """ module Boundaries @@ -55,25 +75,14 @@ const DEFAULT_N = 20 "Default minimum temporal collar width, as a fraction of the full time window." const DEFAULT_TCOLLAR = 0.05 -#= Cap on α*ℓ, i.e. on the depth of the absorber over one reference length. α is a power - coefficient, so the field is attenuated by at most exp(-MAX_αℓ/2) over ℓ. - - RK45's `fbar!` back-propagates the RHS with exp(-linop*Δz), i.e. it *amplifies* by - exp(+α Δz) for a decaying linop. Two things follow. - - First, α must be finite: the tapers reach exactly 0 at the band edge, and Inf*0 = NaN. - - Second — and this is the constraint that actually binds — the amplified elements must - not pollute the step-size controller. `RK45.weaknorm` sums abs2(yerr) over *all* - elements and divides by the global ‖y‖, and it is evaluated in the interaction-picture - frame, before `prop!_maybe`. So an amplified band-edge element is not independent of the - rest: it can dominate the error estimate and drive the controller into repeated - rejections. The saving grace is that the nonlinear drive is itself ∝ ωwin = exp(-α ℓ), - so the amplified drive scales as exp(α(Δz - ℓ)) — bounded by 1 as long as Δz ≤ ℓ, for - any α. `Luna.run` therefore caps `max_dz` (and `init_dz`) at ℓ, and this constant then - only has to keep exp(α Δz/2) ≤ exp(MAX_αℓ/2) finite. exp(30) ≈ 1e13, and the - corresponding floor on the profile, exp(-30) ≈ 1e-13, is far below anything physically - meaningful. =# +""" +Cap on `α*ℓ`, the depth of the absorber over one reference length. + +Two jobs. It keeps `α` finite at all — the tapers reach exactly zero at the band edge, and +`Inf*0` is `NaN` — and, given the step-size cap described in the module docstring, it keeps +`exp(α Δz/2)` finite in the interaction picture. At 60 the field is attenuated by at most +`exp(-30) ≈ 1e-13` over one reference length, far below anything physically meaningful. +""" const MAX_αℓ = 60.0 """ @@ -375,11 +384,9 @@ clearer to hand them back than to mutate them from inside a branch: - `linop` gains the spectral absorber, which the interaction-picture propagator then applies exactly (see [`addloss`](@ref)). -- `max_dz` is capped at the reference length `ℓ`, and `init_dz` with it. RK45's `fbar!` - amplifies the RHS by `exp(+α Δz/2)` while the nonlinear drive it acts on is ∝ `exp(-α ℓ/2)`, - so the amplified band-edge elements stay bounded — and stay small in `weaknorm`'s global - sum — only while `Δz ≤ ℓ`. This costs nothing in practice: it requires at least `N` steps - and real runs take far more. +- `max_dz` is capped at the reference length `ℓ`, and `init_dz` with it, so that the + step-size controller is not thrown by the amplified band-edge elements the interaction + picture produces. See "Step size" in the module docstring. """ function setup(boundary, grid, linop, Eω, Et, FT, output, z0, max_dz, init_dz; N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) diff --git a/src/Luna.jl b/src/Luna.jl index 9e98dd52b..4c71fa44d 100644 --- a/src/Luna.jl +++ b/src/Luna.jl @@ -372,14 +372,16 @@ Run the propagation. # Absorbing boundaries - `boundary::Symbol=:rate`: how the absorbing boundaries at the edges of the frequency and time windows are applied. - - `:rate` applies them as an absorption *rate per unit distance*: the spectral absorber - is folded into `linop` (so the propagator applies it exactly) and the temporal - absorber is applied as `exp(-α_t Δz)`. The total absorption over a distance depends + - `:rate` applies them as an absorption *coefficient per unit distance*: the spectral + absorber is folded into `linop` (so the propagator applies it exactly) and the + temporal absorber is applied to the field as `exp(-α_t Δz/2)`, `α` being a power + coefficient as it is elsewhere in Luna. The total absorption over a distance depends only on that distance, not on how many steps the solver took. - `:legacy` reproduces the historical behaviour — multiplying the solution by `grid.ωwin` and `grid.twin` after every accepted step. This makes the cumulative - absorption depend on the step count and hence on `rtol`, so the result does not - converge as the tolerance is tightened. Provided only to reproduce older results. + absorption depend on the step count and hence on `rtol`, and tightening the tolerance + approaches a hard truncation at the edge of the flat region rather than the taper the + profiles describe. Provided only to reproduce older results. - `:none` disables the absorbers. The nonlinear polarisation is still band-limited in `NonlinearRHS` and the field is still band-limited once at the start, but nothing stops energy wrapping around the time window or piling up at the edge of the From c4d099d414fa4ba59daa4f5413604de4f857d9d8 Mon Sep 17 00:00:00 2001 From: John Travers Date: Sun, 30 Aug 2026 23:09:31 +0100 Subject: [PATCH 9/9] Measure what the temporal absorber removes instead of predicting it `walkoff_check` predicted, from the linear operator, whether a component could cross the collar faster than the absorber could kill it. It fired during test_gnlse.jl, and not spuriously: with a band running to 8 um the edge components walk 525 ps over a fibre with a 4 ps window. But there is nothing out there except shot noise. That is the flaw. The check took the 95th percentile of group delay across the whole simulation band, which on any broadband grid is the dispersive edge rather than where the light is, so it warned on ordinary runs. A warning that is usually wrong is one people stop reading. It could not easily be made energy-aware either: at setup time the only spectrum available is the input pulse, and the light that walks off is generated during propagation. So measure instead. `RateAbsorber` already multiplies the collar every step; doing that in an explicit loop rather than a whole-array broadcast gives the energy it removes for free, and does less work than before since only the collar can change. It warns once, when the running total passes a thousandth of the pulse. This fires when something real is being absorbed and stays quiet otherwise: on the DUV walk-off case it warns at z = 0.61 m having removed 0.11%, well before the wave's centre reaches the flat edge at ~1.0 m, and the same fibre with a wide time window is silent. test_gnlse.jl is now silent too. `linop_array` goes with it, having had no other caller, and `setup` no longer needs the field. Bit-identical: the walk-off case still hashes to e019a5fd. Co-Authored-By: Claude Opus 5 --- docs/src/model/model.md | 2 + src/Boundaries.jl | 137 +++++++++++++++++----------------------- src/Luna.jl | 2 +- test/test_boundaries.jl | 34 ++++++++++ 4 files changed, 94 insertions(+), 81 deletions(-) diff --git a/docs/src/model/model.md b/docs/src/model/model.md index 318773007..9d63be298 100644 --- a/docs/src/model/model.md +++ b/docs/src/model/model.md @@ -35,6 +35,8 @@ The spectral absorber is diagonal in ``\omega``, so it is simply an imaginary pa !!! note "Change in behaviour" Before this scheme was introduced, the absorbing boundaries were applied by multiplying the solution by the fixed profile ``W`` once per accepted step. The cumulative absorption was then ``W^N`` with ``N`` the number of steps — a number the adaptive controller derives from `rtol`. The consequence was that the solution depended on the tolerance: tightening `rtol` increased the absorption. Nor does tightening it recover the intended taper — at typical step counts ``W^N`` is a brick wall at the edge of the flat region rather than a taper, and that brick wall is the limit the old scheme approaches. It is what eroded genuine spectral wings. Results from that scheme can be reproduced with `boundary=:legacy`, and the absorbers can be switched off entirely with `boundary=:none`. See [`Luna.run`](@ref) and [`Boundaries`](@ref Boundaries.Boundaries). +Because an absorbing boundary is doing its job silently, `Luna.run` also reports when it starts to matter: the temporal absorber keeps a running total of what it removes, and warns once if that exceeds a thousandth of the pulse. That is a measurement of what was actually absorbed rather than a prediction from the dispersion — on a grid running to several microns the largest group delays belong to the band edges, which carry nothing but shot noise, so a prediction would warn on almost every run. Seeing the warning means light is genuinely reaching the edge of the time window; if that is not intended, widen `trange`. + Note that this is separate from the band-limiting of the nonlinear polarisation which happens inside [`NonlinearRHS`](@ref NonlinearRHS): that is part of the definition of the equation being solved, and is applied to ``P_\mathrm{nl}`` rather than to the field. ## A note on sign conventions diff --git a/src/Boundaries.jl b/src/Boundaries.jl index 08c1cb172..88286e2e7 100644 --- a/src/Boundaries.jl +++ b/src/Boundaries.jl @@ -75,6 +75,9 @@ const DEFAULT_N = 20 "Default minimum temporal collar width, as a fraction of the full time window." const DEFAULT_TCOLLAR = 0.05 +"Fraction of the pulse the temporal absorber may remove before `Luna.run` warns about it." +const DEFAULT_WARNFRAC = 1e-3 + """ Cap on `α*ℓ`, the depth of the absorber over one reference length. @@ -207,62 +210,6 @@ function addloss(linop!, α) end end -""" - walkoff_check(grid, L, αt, collarwidth; quantile=0.95, threshold=1e-2) - -Warn if the temporal absorber is too weak for the group-delay walk-off the simulation can -produce. - -The absorber's job in time is to kill energy before it wraps around the periodic time -window. A component walking off at `τ` (s/m) crosses the collar in `collarwidth/τ` metres, -so the relevant figure of merit is the attenuation over that distance. `τ` is read off the -linear operator: `imag(linop) = -(β - β₁ω)`, so `-d imag(L)/dω` is the group delay per unit -length relative to the reference frame. A high quantile over `grid.sidx` is used rather -than the maximum, because β₁ diverges at the band edges. - -The default `threshold` is a *field* retention of 1e-2, i.e. 1e-4 in intensity — roughly -where wraparound starts to be visible on a log-scale spectral plot. A tighter threshold -warns about wraparound far below any level that could matter. - -This is a diagnostic only — a bad estimate costs a spurious log line, not a wrong answer. -""" -function walkoff_check(grid, L, αt, collarwidth; quantile=0.95, threshold=1e-2) - ω = grid.ω - length(ω) > 2 || return nothing - #= Group delay per unit length, on the ω midpoints; keep only pairs fully inside the - simulation band, and only finite values. Only the first trailing slice is used — for - a multimode or free-space linop that is the fundamental mode or zero transverse - wavevector, which is representative, and scanning the whole array would mean tens of - millions of points for a large 3-D grid. =# - τ = Float64[] - dωs = diff(ω) - lead = ntuple(_ -> 1, max(ndims(L) - 1, 0)) - for i = 1:length(ω)-1 - (grid.sidx[i] && grid.sidx[i+1]) || continue - v = abs((imag(L[i+1, lead...]) - imag(L[i, lead...]))/dωs[i]) - isfinite(v) && push!(τ, v) - end - isempty(τ) && return nothing - sort!(τ) - τq = τ[clamp(ceil(Int, quantile*length(τ)), 1, length(τ))] - τq > 0 || return nothing - zcross = collarwidth/τq # distance to walk across the collar - #= Mean coefficient through the collar, i.e. what such a component actually - experiences. αt is a power coefficient and `threshold` is a field retention, hence - the factor of 2. =# - collar = filter(>(0), αt) - isempty(collar) && return nothing - att = exp(-sum(collar)/length(collar)*zcross/2) - if att > threshold - Logging.@warn(@sprintf( - "Temporal absorbing boundary may be too weak: a component walking off at \ - %.3g fs/mm crosses the %.3g fs collar in %.3g mm and is only attenuated by \ - %.1e. Increase boundary_N, widen trange, or increase tcollar.", - τq*1e15/1e3, collarwidth*1e15, zcross*1e3, att)) - end - nothing -end - # --------------------------------------------------------------------------- application #= The three ways a boundary can be applied per accepted step. Each is a functor rather than @@ -281,16 +228,21 @@ it rides the propagator, having been folded into the linear operator by [`addlos """ struct RateAbsorber{tT, fT, oT} αt::Vector{Float64} - tidcs::Vector{Int} # only the collar is ever ≠ 1, so only those need updating each step + tidcs::Vector{Int} # only the collar is ever ≠ 1, so only those need touching each step tfac::Vector{Float64} Et::tT FT::fT output::oT zprev::Base.RefValue{Float64} + removed::Base.RefValue{Float64} # running total of |E|² taken out of the collar + reference::Base.RefValue{Float64} # |E|² over the whole window, at the first step + warned::Base.RefValue{Bool} + warnfrac::Float64 end -RateAbsorber(αt, Et, FT, output, z0) = RateAbsorber( - αt, findall(>(0), αt), ones(Float64, length(αt)), Et, FT, output, Ref(float(z0))) +RateAbsorber(αt, Et, FT, output, z0; warnfrac=DEFAULT_WARNFRAC) = RateAbsorber( + αt, findall(>(0), αt), ones(Float64, length(αt)), Et, FT, output, Ref(float(z0)), + Ref(0.0), Ref(0.0), Ref(false), warnfrac) function (b::RateAbsorber)(Eω, z, dz, interpolant) Δz = z - b.zprev[] @@ -302,12 +254,52 @@ function (b::RateAbsorber)(Eω, z, dz, interpolant) #= An inverse real FFT overwrites its input, so between these two lines Eω holds whatever FFTW left there and must not be read; the forward transform refills it. =# ldiv!(b.Et, b.FT, Eω) - b.Et .*= b.tfac + b.reference[] == 0 && (b.reference[] = sum(abs2, b.Et)) + #= Apply the collar and measure what it took out, in one pass. Only the collar can + change, so this also does less work than multiplying the whole array. The trailing + index covers every field shape: none for mode-averaged, modes, or transverse. =# + removed = 0.0 + @inbounds for J in CartesianIndices(size(b.Et)[2:end]), i in b.tidcs + before = abs2(b.Et[i, J]) + b.Et[i, J] *= b.tfac[i] + removed += before - abs2(b.Et[i, J]) + end + b.removed[] += removed mul!(Eω, b.FT, b.Et) + warn_maybe(b, z) end b.output(Eω, z, dz, interpolant) end +""" + warn_maybe(b::RateAbsorber, z) + +Warn, once, if the temporal absorber has eaten a noticeable fraction of the pulse. + +This is a measurement of what the boundary actually removed, not a prediction from the +dispersion. A prediction cannot work well here: at setup time the only thing available is +the group delay across the simulation band, and on a broadband grid that is dominated by +the band edges — where a capillary has an enormous group delay and nothing but shot noise +to carry it. Such a check fires on almost every realistic run, and a warning which is +usually wrong is one people learn to ignore. + +What the user needs to know is whether light they care about is leaving the time window, +and the absorber is the thing that finds out. Measuring costs nothing extra, since the +collar is being multiplied anyway, and it fires when it becomes true rather than +speculating beforehand. +""" +function warn_maybe(b::RateAbsorber, z) + (b.warned[] || b.reference[] == 0) && return nothing + frac = b.removed[]/b.reference[] + frac > b.warnfrac || return nothing + b.warned[] = true + Logging.@warn(@sprintf( + "Temporal absorbing boundary has removed %.2g%% of the pulse by z = %.3g m. Light \ + is reaching the edge of the time window and being absorbed; if that is not \ + intended, widen `trange`. (Reported once.)", 100frac, z)) + nothing +end + """ LegacyAbsorber(grid, Et, FT, output) @@ -342,20 +334,6 @@ end (b::NoAbsorber)(Eω, z, dz, interpolant) = b.output(Eω, z, dz, interpolant) -""" - linop_array(linop, Eω, z) - -The linear operator as an array, materialising the z-dependent (closure) form at `z`. The -linop has the same shape as the field, which is how `RK45.make_prop!` allocates its own -buffer. -""" -linop_array(linop::AbstractArray, Eω, z) = linop -function linop_array(linop!, Eω, z) - out = similar(Eω) - linop!(out, z) - out -end - "Report the absorbing-boundary configuration." function log_setup(grid, ℓ, collar) w = tcollarwidth(grid, collar) @@ -372,8 +350,8 @@ function log_setup(grid, ℓ, collar) end """ - setup(boundary, grid, linop, Eω, Et, FT, output, z0, max_dz, init_dz; - N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) + setup(boundary, grid, linop, Et, FT, output, z0, max_dz, init_dz; + N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR, warnfrac=DEFAULT_WARNFRAC) Everything `Luna.run` needs in order to apply absorbing boundaries, as a named tuple `(; stepfun, linop, max_dz, init_dz, ℓ)`. `ℓ` is the reference length actually used, or @@ -388,8 +366,8 @@ clearer to hand them back than to mutate them from inside a branch: step-size controller is not thrown by the amplified band-edge elements the interaction picture produces. See "Step size" in the module docstring. """ -function setup(boundary, grid, linop, Eω, Et, FT, output, z0, max_dz, init_dz; - N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR) +function setup(boundary, grid, linop, Et, FT, output, z0, max_dz, init_dz; + N=DEFAULT_N, ℓ=nothing, collar=DEFAULT_TCOLLAR, warnfrac=DEFAULT_WARNFRAC) ℓabs = nothing if boundary === :rate ℓabs = reflength(grid, N, ℓ) @@ -401,10 +379,9 @@ function setup(boundary, grid, linop, Eω, Et, FT, output, z0, max_dz, init_dz; end init_dz = min(init_dz, max_dz) αt = temporal_rate(grid; N, ℓ, collar) - walkoff_check(grid, linop_array(linop, Eω, z0), αt, tcollarwidth(grid, collar)) linop = addloss(linop, spectral_rate(grid; N, ℓ)) log_setup(grid, ℓabs, collar) - stepfun = RateAbsorber(αt, Et, FT, output, z0) + stepfun = RateAbsorber(αt, Et, FT, output, z0; warnfrac) elseif boundary === :legacy Logging.@warn( "boundary=:legacy applies the absorbing boundaries once per accepted step, " * diff --git a/src/Luna.jl b/src/Luna.jl index 4c71fa44d..8d4a82808 100644 --- a/src/Luna.jl +++ b/src/Luna.jl @@ -415,7 +415,7 @@ function run(Eω, grid, #= NOTE: this must come after check_cache, which can move z0 and init_dz: the temporal absorber measures the distance it is applied over from z0. =# - absorber = Boundaries.setup(boundary, grid, linop, Eω, Et, FT, output, z0, + absorber = Boundaries.setup(boundary, grid, linop, Et, FT, output, z0, max_dz, init_dz; N=boundary_N, ℓ=boundary_length, collar=tcollar) stepfun = absorber.stepfun diff --git a/test/test_boundaries.jl b/test/test_boundaries.jl index 7278ddd39..1b7d8020d 100644 --- a/test/test_boundaries.jl +++ b/test/test_boundaries.jl @@ -281,6 +281,40 @@ dl = abs(bandE(legacyfine)[end] - Elegacy[end])/Elegacy[end] @test dr < 0.05 @test dl > 0.1 # the mechanism is genuinely exercised @test dl > 10*dr + +#= The absorber reports what it removed. This has to fire here -- the DW really is being + eaten -- and it has to stay quiet when nothing reaches the boundary. The old diagnostic + predicted from the group delay across the band instead of measuring, which on a grid + running to 4 um is dominated by band-edge components carrying nothing but shot noise, so + it warned on runs where the absorber never touched anything real. =# +warnings = String[] +mutable struct CollectWarnings <: Logging.AbstractLogger; msgs::Vector{String}; end +Logging.min_enabled_level(::CollectWarnings) = Logging.Info +Logging.shouldlog(::CollectWarnings, args...) = true +Logging.catch_exceptions(::CollectWarnings) = false +function Logging.handle_message(l::CollectWarnings, lvl, msg, _m, g, id, file, line; kw...) + occursin("Temporal absorbing boundary", string(msg)) && push!(l.msgs, string(msg)) + nothing +end + +function warnings_from(; trange, flength) + lg = CollectWarnings(String[]) + Logging.with_logger(lg) do + Eω, grid, linop, transform, FT, output = prop_capillary_args( + 50e-6, flength, :Ar, 0.4; λ0=800e-9, energy=29e-6, τfwhm=10e-15, + λlims=(150e-9, 4e-6), trange, saveN=11, plasma=false, + rng=MersenneTwister(1234)) + Luna.run(Eω, grid, linop, transform, FT, output) + end + lg.msgs +end + +# the DW is well into the collar by 2 m, so this must warn -- exactly once +warned = warnings_from(trange=100e-15, flength=ZMAX) +@test length(warned) == 1 +@test occursin("removed", warned[1]) +# stop before the DW gets there and there is nothing to report +@test isempty(warnings_from(trange=100e-15, flength=0.3)) end @testset "run interface" begin