diff --git a/docs/src/model/model.md b/docs/src/model/model.md index 362cad431..9d63be298 100644 --- a/docs/src/model/model.md +++ b/docs/src/model/model.md @@ -18,6 +18,27 @@ 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 **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{2\log W(x)}{\ell}\,, +``` +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. + +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 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 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/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/Boundaries.jl b/src/Boundaries.jl new file mode 100644 index 000000000..88286e2e7 --- /dev/null +++ b/src/Boundaries.jl @@ -0,0 +1,398 @@ +""" + 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`. 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.α`, +`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) = -2 log(W(x)) / ℓ + +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/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/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. 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 + +import ..Maths +import ..Grid +import LinearAlgebra: mul!, ldiv! +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 + +"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. + +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 + +""" + 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`. +""" +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, ℓ) + +Convert an apodisation profile `W ∈ [0, 1]` (1 in the interior, falling to 0 at the +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.(.-2 .* log.(W) ./ ℓ, 0.0, MAX_αℓ/ℓ) + +""" + spectral_rate(grid; N=DEFAULT_N, ℓ=nothing) + +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 there is nothing left to absorb. +""" +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) + +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, ℓ)) + +""" + addloss(linop, α) + +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. + +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 .- α./2 + +function addloss(linop!, α) + function linop_absorbing!(out, z) + linop!(out, z) + out .-= α./2 + out + end +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 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; 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[] + 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.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) + +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) + +"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, 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 +`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, 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, 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, ℓ) + 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) + linop = addloss(linop, spectral_rate(grid; N, ℓ)) + log_setup(grid, ℓabs, collar) + stepfun = RateAbsorber(αt, Et, FT, output, z0; warnfrac) + 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/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/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..8d4a82808 100644 --- a/src/Luna.jl +++ b/src/Luna.jl @@ -54,6 +54,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") @@ -85,7 +86,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 @@ -363,22 +364,48 @@ sym2string(other) = other save_modeinfo_maybe(output, t) = nothing +""" + 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 *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`, 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 + 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ω - 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 - # check_cache does nothing except for HDF5Outputs Eωc, zc, dzc = Output.check_cache(output, Eω, z0, init_dz) if zc > z0 @@ -386,8 +413,27 @@ function run(Eω, grid, Eω, z0, init_dz = Eωc, zc, dzc end + #= 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, 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, + 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) + 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(absorber.ℓ)) + 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/src/NonlinearRHS.jl b/src/NonlinearRHS.jl index 722a462b6..f5442c45a 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 @@ -449,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) @@ -463,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 @@ -475,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/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..1b7d8020d --- /dev/null +++ b/test/test_boundaries.jl @@ -0,0 +1,348 @@ +using Luna +import Test: @test, @testset, @test_throws +import FFTW +import LinearAlgebra: mul!, ldiv! +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 + 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) +#= α 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. =# +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./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 +@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...] .- α./2 # linops carry -α/2 + # 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./2); 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 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 = 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 + +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./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 +@test fine < 10*coarse/25 # converges at least first order in the step size + +# 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 + 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 "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 + +#= 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 +grid = Grid.EnvGrid(0.1, 800e-9, (400e-9, 2e-6), 1e-12) + +@test_throws ErrorException Logging.with_logger(Logging.NullLogger()) do + 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, + λ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