diff --git a/Project.toml b/Project.toml
index 3f333313..71f6882a 100644
--- a/Project.toml
+++ b/Project.toml
@@ -64,7 +64,7 @@ FuseExchangeProtocol = "2"
GraphRecipes = "0.5"
Graphs = "1"
HelpPlots = "1.1"
-IMASdd = "8.3"
+IMASdd = "8.6.4"
IMASutils = "1.5.1"
Interpolations = "0.13, 0.14, 0.15, 0.16"
Jedis = "0.3"
diff --git a/src/IMAS.jl b/src/IMAS.jl
index 1890ecd7..c6a40fee 100644
--- a/src/IMAS.jl
+++ b/src/IMAS.jl
@@ -32,6 +32,7 @@ import AbstractTrees: print_tree
#= UTILS =#
#= ===== =#
include("real.jl")
+include("dual.jl")
include("get_from.jl")
include("geometry.jl")
include("math.jl")
diff --git a/src/dual.jl b/src/dual.jl
new file mode 100644
index 00000000..30b39f85
--- /dev/null
+++ b/src/dual.jl
@@ -0,0 +1,378 @@
+document[:Dual] = Symbol[]
+
+# ======================================================== #
+# Data dictionaries whose element type is ForwardDiff.Dual #
+# ======================================================== #
+# A `dd{D}` with `D<:ForwardDiff.Dual` carries, for every real-valued leaf, the derivatives with
+# respect to a small set of seeded inputs. `time` arrays, `global_time`, integers and strings stay
+# as they are. The functions here convert between element types, seed, and split value and
+# derivative parts; they are the only place where element types of a whole IDS are changed.
+
+"""
+ InputsTag
+
+Tag of the dual numbers that carry derivatives with respect to the inputs of a whole simulation.
+It is ordered before every other ForwardDiff tag, so that the derivative calculations that some
+physics routines do internally (which create their own tags) nest inside it without ambiguity.
+Use `InputsDual{N}` as the element type of a `dd` that carries `N` partial derivatives.
+"""
+struct InputsTag end
+const InputsDual{N} = Dual{InputsTag,Float64,N}
+ForwardDiff.:≺(::Type{InputsTag}, ::Type{<:ForwardDiff.Tag}) = true
+ForwardDiff.:≺(::Type{<:ForwardDiff.Tag}, ::Type{InputsTag}) = false
+ForwardDiff.:≺(::Type{InputsTag}, ::Type{InputsTag}) = false
+
+@compat public InputsTag, InputsDual
+push!(document[:Dual], :InputsTag)
+push!(document[:Dual], :InputsDual)
+
+"""
+ retype(::Type{T}, ids::Union{IDS,IDSvector}) where {T<:Real}
+
+Copy of `ids` with element type `T`. For a `dd` the `global_time` and the auxiliary storage are carried over.
+
+ - `Float64 -> Dual`: values are kept, partials are zero
+ - `Dual -> Float64`: values are kept, partials are dropped
+ - `Dual -> Dual` of a different type: values are kept, partials are zero
+
+Only filled fields are copied, so expressions remain expressions in the new element type.
+"""
+function retype(::Type{T}, @nospecialize(ids::IDS)) where {T<:Real}
+ ids_new = Base.typename(typeof(ids)).wrapper{T}(; frozen=getfield(ids, :_frozen))
+ fill!(ids_new, ids)
+ if ids isa DD
+ setfield!(ids_new, :global_time, getfield(ids, :global_time))
+ aux_new = getfield(ids_new, :_aux)
+ for (k, v) in getfield(ids, :_aux)
+ aux_new[k] = (v isa Union{IDS,IDSvector}) ? retype(T, v) : deepcopy(v)
+ end
+ end
+ return ids_new
+end
+
+function retype(::Type{T}, @nospecialize(idsv::IDSvector)) where {T<:Real}
+ idsv_new = Base.typename(typeof(idsv)).wrapper{Base.typename(eltype(idsv)).wrapper{T}}()
+ return fill!(idsv_new, idsv)
+end
+
+@compat public retype
+push!(document[:Dual], :retype)
+
+# `convert(D, ids)` is defined in IMASdd for any `Type{<:Real}` and in ForwardDiff for any argument,
+# so for a Dual element type the call is ambiguous unless it is resolved here
+Base.convert(::Type{Dual{T,V,N}}, @nospecialize(ids::IDS)) where {T,V,N} = retype(Dual{T,V,N}, ids)
+Base.convert(::Type{Dual{T,V,N}}, @nospecialize(ids::IDSvector)) where {T,V,N} = retype(Dual{T,V,N}, ids)
+
+"""
+ value_dd(ids::Union{IDS,IDSvector})
+
+Float64 copy of a Dual-typed IDS holding the value parts
+"""
+value_dd(@nospecialize(ids::Union{IDS{<:Dual},IDSvector{<:IDS{<:Dual}}})) = retype(Float64, ids)
+value_dd(@nospecialize(ids::Union{IDS{Float64},IDSvector{<:IDS{Float64}}})) = deepcopy(ids)
+
+@compat public value_dd
+push!(document[:Dual], :value_dd)
+
+# element-wise helpers that leave non-Dual data untouched
+_dual_value(x::Dual) = ForwardDiff.value(x)
+_dual_value(x) = x
+_dual_value(x::AbstractArray{<:Dual}) = ForwardDiff.value.(x)
+_dual_partial(x::Dual, k::Int) = ForwardDiff.partials(x, k)
+_dual_partial(x::AbstractArray{<:Dual}, k::Int) = ForwardDiff.partials.(x, k)
+
+"""
+ fill!(ids_new::IDS{Float64}, ids::IDS{<:Dual}, field::Symbol)
+
+Maps fields of an `IDS{Dual}` to an `IDS{Float64}`, keeping the value parts
+"""
+function Base.fill!(@nospecialize(ids_new::IDS{<:T1}), @nospecialize(ids::IDS{<:T2}), field::Symbol) where {T1<:Float64,T2<:Dual}
+ value = getraw(ids, field)
+ if field != :time && eltype(value) <: T2
+ _setproperty!(ids_new, field, _dual_value(value); from_cocos=internal_cocos)
+ else
+ _setproperty!(ids_new, field, deepcopy(value); from_cocos=internal_cocos)
+ end
+ return nothing
+end
+
+"""
+ fill!(ids_new::IDS{<:Dual}, ids::IDS{<:Dual}, field::Symbol)
+
+Maps fields between Dual-typed IDSs. Same type: plain copy. Different Dual types: values are kept and partials are zero.
+"""
+function Base.fill!(@nospecialize(ids_new::IDS{<:T1}), @nospecialize(ids::IDS{<:T2}), field::Symbol) where {T1<:Dual,T2<:Dual}
+ value = getraw(ids, field)
+ D1 = eltype(ids_new)
+ if D1 === eltype(ids) || field == :time || !(eltype(value) <: T2)
+ _setproperty!(ids_new, field, deepcopy(value); from_cocos=internal_cocos)
+ else
+ _setproperty!(ids_new, field, D1.(_dual_value(value)); from_cocos=internal_cocos)
+ end
+ return nothing
+end
+
+# visit every filled data leaf of `ids`, calling f(ids_node, other_node, field); `other` must have the same structure.
+# With `strict=false` arrays of structures of different length (e.g. a different number of X-points) are skipped
+# and counted in `mismatches` instead of raising an error.
+function _foreach_leaf(f::F, @nospecialize(ids::Union{IDS,IDSvector}), @nospecialize(other::Union{IDS,IDSvector}); strict::Bool=true, mismatches::Base.RefValue{Int}=Ref(0)) where {F}
+ stack = Tuple{Any,Any}[]
+ if ids isa IDSvector
+ if length(ids) != length(other)
+ strict && error("IDS structures do not match")
+ mismatches[] += 1
+ return ids
+ end
+ for i in eachindex(ids)
+ push!(stack, (ids[i], other[i]))
+ end
+ else
+ push!(stack, (ids, other))
+ end
+ while !isempty(stack)
+ a, b = pop!(stack)
+ filled = getfield(a, :_filled)
+ T = typeof(a)
+ for i in 1:fieldcount(T)
+ field = fieldname(T, i)
+ if hasfield(typeof(filled), field) && getfield(filled, field)
+ field_type = fieldtype_typeof(a, field)
+ if field_type <: IDS
+ push!(stack, (getfield(a, field), getfield(b, field)))
+ elseif field_type <: IDSvector
+ va = getfield(a, field)
+ vb = getfield(b, field)
+ if length(va) != length(vb)
+ strict && error("IDS structures do not match at $(location(a, field))")
+ mismatches[] += 1
+ continue
+ end
+ for j in eachindex(va)
+ push!(stack, (va[j], vb[j]))
+ end
+ else
+ f(a, b, field)
+ end
+ end
+ end
+ end
+ return ids
+end
+
+"""
+ partials_dd(ids::Union{IDS,IDSvector}, k::Int)
+
+Float64 copy of a Dual-typed IDS holding the k-th partial derivative of every real-valued leaf.
+Leaves that are not Dual-typed (times, integers, strings) are copied unchanged.
+"""
+function partials_dd(@nospecialize(ids::Union{IDS{<:Dual},IDSvector{<:IDS{<:Dual}}}), k::Int)
+ out = retype(Float64, ids)
+ _foreach_leaf(ids, out) do a, b, field
+ value = getraw(a, field)
+ if field != :time && eltype(value) <: Dual
+ setfield!(b, field, _dual_partial(value, k))
+ end
+ end
+ return out
+end
+
+@compat public partials_dd
+push!(document[:Dual], :partials_dd)
+
+"""
+ replace_values!(ids::Union{IDS,IDSvector}, ids_values::Union{IDS,IDSvector})
+
+Overwrite the value part of every real-valued leaf of the Dual-typed `ids` with the corresponding
+entry of the Float64 `ids_values`, keeping the partials of `ids`. Used to iterate derivative parts at
+a fixed solution. Both must have the same tree of sub-structures; a leaf that holds data in only one of
+the two, or arrays of different size, is left untouched. Returns the number of leaves left untouched.
+"""
+function replace_values!(@nospecialize(ids::Union{IDS{<:Dual},IDSvector{<:IDS{<:Dual}}}), @nospecialize(ids_values::Union{IDS{Float64},IDSvector{<:IDS{Float64}}}))
+ skipped = 0
+ mismatches = Ref(0)
+ _foreach_leaf(ids, ids_values; strict=false, mismatches) do a, b, field
+ value = getraw(a, field)
+ if field != :time && eltype(value) <: Dual
+ filled_b = getfield(b, :_filled)
+ if !(hasfield(typeof(filled_b), field) && getfield(filled_b, field))
+ skipped += 1
+ return
+ end
+ newval = getraw(b, field)
+ if value isa AbstractArray
+ if !(newval isa AbstractArray{<:Real}) || size(value) != size(newval)
+ skipped += 1
+ return
+ end
+ setfield!(a, field, map((d, v) -> typeof(d)(v, ForwardDiff.partials(d)), value, newval))
+ elseif newval isa Real
+ setfield!(a, field, typeof(value)(newval, ForwardDiff.partials(value)))
+ else
+ skipped += 1
+ end
+ end
+ end
+ return skipped + mismatches[]
+end
+
+@compat public replace_values!
+push!(document[:Dual], :replace_values!)
+
+"""
+ npartials(ids::Union{IDS,IDSvector})
+
+Number of partial derivatives carried by the element type of `ids` (0 for a non-Dual IDS)
+"""
+npartials(@nospecialize(ids::Union{IDS,IDSvector})) = _npartials(ids isa IDSvector ? eltype(eltype(ids)) : eltype(ids))
+_npartials(::Type{<:Dual{T,V,N}}) where {T,V,N} = N
+_npartials(::Type) = 0
+
+@compat public npartials
+push!(document[:Dual], :npartials)
+
+"""
+ seed(::Type{D}, k::Int) where {D<:Dual}
+
+Dual number of value 1 whose k-th partial is 1 and all others 0. Multiplying an input by `seed(D, k)`
+makes it the k-th differentiation variable in relative (logarithmic) terms: the k-th partial of any
+output `y` is then ∂y/∂ln(input).
+"""
+function seed(::Type{D}, k::Int) where {T,V,N,D<:Dual{T,V,N}}
+ @assert 1 <= k <= N "partial index $k is outside 1:$N"
+ return D(one(V), ForwardDiff.Partials{N,V}(ntuple(i -> i == k ? one(V) : zero(V), N)))
+end
+
+@compat public seed
+push!(document[:Dual], :seed)
+
+# ------------------------------------------------- #
+# Derivatives of solutions found by iterative search #
+# ------------------------------------------------- #
+# Root finders and minimisers (Brent, Nelder-Mead, ...) are run on value parts, exactly as in a Float64
+# calculation. The derivative of what they find with respect to the inputs carried by the dual numbers
+# follows from the implicit function theorem at the solution. The derivatives with respect to the few
+# unknowns are taken by central differences of value parts, so that the function being solved does not
+# need to accept nested dual numbers (many of them update arrays in place).
+
+"""
+ IMPLICIT_DERIVATIVES
+
+Scoped switch for the derivatives of solutions found by iterative search (`implicit_solution`,
+`implicit_argmin` and the functions built on them). An outer solver that only looks at value parts
+turns it off while it iterates, `Base.ScopedValues.with(IMAS.IMPLICIT_DERIVATIVES => false) do ... end`,
+which saves the work and avoids evaluating the implicit function theorem at iterates far from a solution;
+the result of such a search then has zero derivative part.
+"""
+const IMPLICIT_DERIVATIVES = Base.ScopedValues.ScopedValue(true)
+
+@compat public IMPLICIT_DERIVATIVES
+push!(document[:Dual], :IMPLICIT_DERIVATIVES)
+
+function _partials_matrix(x::AbstractVector{D}) where {T,V,N,D<:Dual{T,V,N}}
+ return V[ForwardDiff.partials(xi, k) for xi in x, k in 1:N]
+end
+
+function _with_partials(::Type{D}, values::AbstractVector{<:Real}, partials::AbstractMatrix{<:Real}) where {T,V,N,D<:Dual{T,V,N}}
+ return D[D(V(values[i]), ForwardDiff.Partials{N,V}(ntuple(k -> V(partials[i, k]), N))) for i in eachindex(values)]
+end
+
+_implicit_step(x::Real, relstep::Real) = relstep * max(abs(x), 1.0)
+
+"""
+ implicit_solution(G, ustar::AbstractVector{<:AbstractFloat}, ::Type{D}; relstep::Real=1E-4, atol::Real=Inf) where {D<:Dual}
+
+Given `ustar` such that `G(ustar) ≈ 0` on value parts, where `G(u::Vector{D})::Vector{D}` depends on inputs
+that carry derivatives, returns `ustar` as dual numbers with `du/dθ = -(∂G/∂u)⁻¹ ∂G/∂θ`.
+`G` is called with `u` at and around `ustar`; whatever state it leaves behind must be set again by the caller.
+
+`atol` handles searches that end without satisfying their condition (a minimisation of `|G_i|` that stops on a
+plateau, say). It requires `G` and `u` to pair up, the i-th condition being the one that determines the i-th
+unknown: an unknown whose condition is violated by more than `atol` is not determined by it, so it is held
+fixed (zero derivative part) and its condition is left out of the linear system.
+"""
+function implicit_solution(G, ustar::AbstractVector{<:AbstractFloat}, ::Type{D}; relstep::Real=1E-4, atol::Real=Inf) where {D<:Dual}
+ n = length(ustar)
+ if !IMPLICIT_DERIVATIVES[]
+ return D.(ustar)
+ end
+ G0 = G(D.(ustar))
+ Gθ = _partials_matrix(G0)
+ active = isfinite(atol) ? [i for i in 1:n if abs(ForwardDiff.value(G0[i])) <= atol] : collect(1:n)
+ isfinite(atol) && @assert length(G0) == n "with `atol`, conditions and unknowns must pair up"
+ du = zeros(n, size(Gθ, 2))
+ if !isempty(active)
+ rows = isfinite(atol) ? active : collect(1:length(G0))
+ J = Matrix{Float64}(undef, length(rows), length(active))
+ for (jj, j) in enumerate(active)
+ δ = _implicit_step(ustar[j], relstep)
+ up = collect(ustar); up[j] += δ
+ um = collect(ustar); um[j] -= δ
+ J[:, jj] .= ((ForwardDiff.value.(G(D.(up))) .- ForwardDiff.value.(G(D.(um)))) ./ (2δ))[rows]
+ end
+ du[active, :] .= -(LinearAlgebra.pinv(J; rtol=1E-12) * Gθ[rows, :])
+ end
+ return _with_partials(D, ustar, du)
+end
+
+"""
+ implicit_argmin(cost, xstar::AbstractVector{<:AbstractFloat}, ::Type{D}) where {D<:Dual}
+
+Given `xstar` that minimises the value part of `cost(x)`, where `cost` depends on inputs that carry
+derivatives, returns `xstar` as dual numbers with `dx/dθ = -(∂²c/∂x²)⁺ ∂(∂c/∂x)/∂θ`.
+
+The gradient and Hessian with respect to `x` are taken by forward-mode differentiation nested inside the
+dual numbers of the inputs, so `cost` must be a pure function of `x` (no in-place update of arrays whose
+element type is `D`). A direction along which the cost is flat does not respond to the inputs (pseudo-inverse).
+"""
+function implicit_argmin(cost, xstar::AbstractVector{<:AbstractFloat}, ::Type{D}) where {D<:Dual}
+ x0 = D.(collect(xstar))
+ if !IMPLICIT_DERIVATIVES[]
+ return x0
+ end
+ gθ = _partials_matrix(ForwardDiff.gradient(cost, x0))
+ H = ForwardDiff.value.(ForwardDiff.hessian(cost, x0))
+ H = (H .+ H') ./ 2
+ return _with_partials(D, xstar, -(LinearAlgebra.pinv(H; rtol=1E-10) * gθ))
+end
+
+@compat public implicit_solution, implicit_argmin
+push!(document[:Dual], :implicit_solution)
+push!(document[:Dual], :implicit_argmin)
+
+# ---- #
+# I/O #
+# ---- #
+# JSON and HDF5 files hold plain numbers: a Dual-typed IDS is written as one file with the values
+# and one file per partial derivative, each of which reads back as a regular Float64 IDS.
+
+"""
+ dual_filenames(filename::AbstractString, n::Int)
+
+Names of the files written for a Dual-typed IDS: `filename` for the values and `_d` for the k-th partial
+"""
+function dual_filenames(filename::AbstractString, n::Int)
+ base, ext = splitext(filename)
+ return (values=filename, partials=["$(base)_d$(k)$(ext)" for k in 1:n])
+end
+
+function IMASdd.imas2json(@nospecialize(ids::Union{IDS{<:Dual},IDSvector{<:IDS{<:Dual}}}), filename::AbstractString; partials::Bool=true, kw...)
+ names = dual_filenames(filename, npartials(ids))
+ out = IMASdd.imas2json(retype(Float64, ids), names.values; kw...)
+ if partials
+ for (k, name) in enumerate(names.partials)
+ IMASdd.imas2json(partials_dd(ids, k), name; kw...)
+ end
+ end
+ return out
+end
+
+function IMASdd.imas2hdf(@nospecialize(ids::Union{IDS{<:Dual},IDSvector{<:IDS{<:Dual}}}), filename::AbstractString; partials::Bool=true, kw...)
+ names = dual_filenames(filename, npartials(ids))
+ out = IMASdd.imas2hdf(retype(Float64, ids), names.values; kw...)
+ if partials
+ for (k, name) in enumerate(names.partials)
+ IMASdd.imas2hdf(partials_dd(ids, k), name; kw...)
+ end
+ end
+ return out
+end
diff --git a/src/expressions/onetime.jl b/src/expressions/onetime.jl
index f9cac790..41cbc46e 100644
--- a/src/expressions/onetime.jl
+++ b/src/expressions/onetime.jl
@@ -21,7 +21,7 @@ otexp["core_profiles.profiles_1d[:].grid.volume"] =
volume = eqt.profiles_1d.volume
ori_rho = eqt.profiles_1d.rho_tor_norm
new_rho = profiles_1d.grid.rho_tor_norm
- return (cubic_interp1d(ori_rho, sqrt.(volume), new_rho)).^2
+ return (cubic_interp1d(ori_rho, sqrt0.(volume), new_rho)).^2
end
otexp["core_profiles.profiles_1d[:].grid.area"] =
@@ -30,7 +30,7 @@ otexp["core_profiles.profiles_1d[:].grid.area"] =
area = eqt.profiles_1d.area
ori_rho = eqt.profiles_1d.rho_tor_norm
new_rho = profiles_1d.grid.rho_tor_norm
- return (cubic_interp1d(ori_rho, sqrt.(area), new_rho)).^2
+ return (cubic_interp1d(ori_rho, sqrt0.(area), new_rho)).^2
end
otexp["core_profiles.profiles_1d[:].grid.surface"] =
@@ -50,7 +50,7 @@ otexp["core_profiles.profiles_1d[:].grid.psi"] =
sign_psi = sign(psi[end] - psi[1])
ori_rho = eqt.profiles_1d.rho_tor_norm
new_rho = profiles_1d.grid.rho_tor_norm
- return sign_psi .* cubic_interp1d(ori_rho, sqrt.(abs.(psi .- psi[1])), new_rho).^2 .+ psi[1]
+ return sign_psi .* cubic_interp1d(ori_rho, sqrt0.(abs.(psi .- psi[1])), new_rho).^2 .+ psi[1]
end
diff --git a/src/math.jl b/src/math.jl
index f2c6479e..20a0427a 100644
--- a/src/math.jl
+++ b/src/math.jl
@@ -201,6 +201,15 @@ function cubic_interp1d(x, y, xq)
return FI.cubic_interp(x, y, xq; extrap = FI.ExtendExtrap())
end
+"""
+ sqrt0(x::Real)
+
+Square root that returns an exact zero (also in its derivative part) for a zero argument.
+For quantities that vanish identically on the magnetic axis (volume, area, ψ - ψ_axis, toroidal flux)
+the plain `sqrt` of a dual number evaluates `0 * Inf` for the derivative there.
+"""
+sqrt0(x::Real) = iszero(x) ? zero(x) : sqrt(x)
+
# A firm, type-stable linear interpolation function
function linear_interp1d(x, y)
return FI.linear_interp(x, y; extrap = FI.ExtendExtrap())
diff --git a/src/physics.jl b/src/physics.jl
index 0225b682..38e8c6aa 100644
--- a/src/physics.jl
+++ b/src/physics.jl
@@ -20,6 +20,7 @@ include(joinpath("physics", "tf.jl"))
include(joinpath("physics", "currents.jl"))
include(joinpath("physics", "fields.jl"))
include(joinpath("physics", "fluxsurfaces.jl"))
+include(joinpath("physics", "fluxsurfaces_dual.jl"))
include(joinpath("physics", "fluxsurfaces_cubic.jl"))
include(joinpath("physics", "rf.jl"))
include(joinpath("physics", "neoclassical.jl"))
diff --git a/src/physics/boundary.jl b/src/physics/boundary.jl
index d8d31f8a..679b0a60 100644
--- a/src/physics/boundary.jl
+++ b/src/physics/boundary.jl
@@ -357,7 +357,7 @@ Compute the cumulative arc length of a 2D curve defined from the coordinate vect
function arc_length(pr::AbstractVector{<:Real}, pz::AbstractVector{<:Real}; include_zero::Bool=true)
n = length(pr)
if include_zero
- ll = Vector{Float64}(undef, n)
+ ll = Vector{promote_type(Float64, eltype(pr), eltype(pz))}(undef, n)
ll[1] = 0.0
@inbounds for i in 2:n
dx = pr[i] - pr[i-1]
@@ -365,7 +365,7 @@ function arc_length(pr::AbstractVector{<:Real}, pz::AbstractVector{<:Real}; incl
ll[i] = ll[i-1] + sqrt(dx * dx + dz * dz)
end
else
- ll = Vector{Float64}(undef, n - 1)
+ ll = Vector{promote_type(Float64, eltype(pr), eltype(pz))}(undef, n - 1)
@inbounds for i in 2:n
dx = pr[i] - pr[i-1]
dz = pz[i] - pz[i-1]
@@ -387,7 +387,7 @@ Compute the cumulative arc length of a 3D curve from the Cartesian coordinate ve
function arc_length(px::AbstractVector{<:Real}, py::AbstractVector{<:Real}, pz::AbstractVector{<:Real}; include_zero::Bool=true)
n = length(px)
if include_zero
- ll = Vector{Float64}(undef, n)
+ ll = Vector{promote_type(Float64, eltype(px), eltype(py), eltype(pz))}(undef, n)
ll[1] = 0.0
@inbounds for i in 2:n
dx = px[i] - px[i-1]
@@ -396,7 +396,7 @@ function arc_length(px::AbstractVector{<:Real}, py::AbstractVector{<:Real}, pz::
ll[i] = ll[i-1] + sqrt(dx * dx + dy * dy + dz * dz)
end
else
- ll = Vector{Float64}(undef, n - 1)
+ ll = Vector{promote_type(Float64, eltype(px), eltype(py), eltype(pz))}(undef, n - 1)
@inbounds for i in 2:n
dx = px[i] - px[i-1]
dy = py[i] - py[i-1]
@@ -423,7 +423,7 @@ The arc length is calculated as:
function arc_length_cylindrical(r::AbstractVector{<:Real}, phi::AbstractVector{<:Real}, z::AbstractVector{<:Real}; include_zero::Bool=true)
n = length(r)
if include_zero
- ll = Vector{Float64}(undef, n)
+ ll = Vector{promote_type(Float64, eltype(r), eltype(phi), eltype(z))}(undef, n)
ll[1] = 0.0
@inbounds for i in 2:n
dr = r[i] - r[i-1]
@@ -434,7 +434,7 @@ function arc_length_cylindrical(r::AbstractVector{<:Real}, phi::AbstractVector{<
ll[i] = ll[i-1] + arc
end
else
- ll = Vector{Float64}(undef, n - 1)
+ ll = Vector{promote_type(Float64, eltype(r), eltype(phi), eltype(z))}(undef, n - 1)
@inbounds for i in 2:n
dr = r[i] - r[i-1]
dphi = phi[i] - phi[i-1]
diff --git a/src/physics/build.jl b/src/physics/build.jl
index 931d1454..7d4d7c9f 100644
--- a/src/physics/build.jl
+++ b/src/physics/build.jl
@@ -362,6 +362,13 @@ Memoize.@memoize function memoized_inscribed_polygon(pr::AbstractVector{Float64}
return inscribed_polygon(pr, pz; target_area_fraction)
end
+# The wall outline is machine geometry: for element types other than Float64 the simplification
+# is done on the values and the result is returned in the element type of the input
+function memoized_inscribed_polygon(pr::AbstractVector{T}, pz::AbstractVector{T}, target_area_fraction::Float64) where {T<:Real}
+ r, z = memoized_inscribed_polygon(Float64[force_float64(x) for x in pr], Float64[force_float64(x) for x in pz], target_area_fraction)
+ return T.(r), T.(z)
+end
+
"""
first_wall(wall::IMAS.wall{T}; simplify_to_inscribed_fractional_area::Float64=1 - 1E-6) where {T<:Real}
diff --git a/src/physics/currents.jl b/src/physics/currents.jl
index 1f7c9f06..ca24171a 100644
--- a/src/physics/currents.jl
+++ b/src/physics/currents.jl
@@ -39,8 +39,18 @@ function j_ohmic_steady_state(
return abs(ip - trapz(cp1d.grid.area, j_tor)) .^ 2
end
- res = Optim.optimize(cost, [I_ohmic_par_guess], Optim.Newton(); autodiff=:forward)
- I_ohmic_par = res.minimizer
+ if T <: ForwardDiff.Dual
+ # The total toroidal current is an affine function of the ohmic amplitude, so the condition
+ # ip = ∫ j_tor dA has the closed-form solution below. With dual numbers this replaces the
+ # minimisation (whose Newton solver does not accept them) and carries exact derivatives.
+ ip_of(x) = trapz(cp1d.grid.area, Jpar_2_Jtor(rho_tor_norm, x .* j_oh_par_norm .+ j_non_inductive, true, eqt))
+ ip0 = ip_of(zero(T))
+ ip1 = ip_of(one(T))
+ I_ohmic_par = [(ip - ip0) / (ip1 - ip0)]
+ else
+ res = Optim.optimize(cost, [I_ohmic_par_guess], Optim.Newton(); autodiff=:forward)
+ I_ohmic_par = res.minimizer
+ end
return I_ohmic_par .* j_oh_par_norm
end
diff --git a/src/physics/equilibrium.jl b/src/physics/equilibrium.jl
index 2e87ec6d..8cff950c 100644
--- a/src/physics/equilibrium.jl
+++ b/src/physics/equilibrium.jl
@@ -6,8 +6,9 @@ document[Symbol("Physics equilibrium")] = Symbol[]
Returns r, z, and ψ interpolant named tuple
"""
function ψ_interpolant(eqt2d::IMAS.equilibrium__time_slice___profiles_2d)
- dim1 = convert(Vector{Float64}, eqt2d.grid.dim1)
- dim2 = convert(Vector{Float64}, eqt2d.grid.dim2)
+ # the grid is always plain floats, also when ψ carries derivatives
+ dim1 = eltype(eqt2d.grid.dim1) === Float64 ? convert(Vector{Float64}, eqt2d.grid.dim1) : Float64[force_float64(x) for x in eqt2d.grid.dim1]
+ dim2 = eltype(eqt2d.grid.dim2) === Float64 ? convert(Vector{Float64}, eqt2d.grid.dim2) : Float64[force_float64(x) for x in eqt2d.grid.dim2]
r = range(dim1[1], dim1[end], length(dim1))
z = range(dim2[1], dim2[end], length(dim2))
return ψ_interpolant(r, z, eqt2d.psi)
diff --git a/src/physics/fast.jl b/src/physics/fast.jl
index 4f5fc1ed..5d903e4e 100644
--- a/src/physics/fast.jl
+++ b/src/physics/fast.jl
@@ -494,14 +494,14 @@ Smooths out the beam power history based on a given thermalization constant `tau
Such smoothing mimics the delayed contribution from the instantaneous source,
as well as the gradual decay of the previous fast ion population over time.
"""
-function smooth_beam_power(time::AbstractVector{Float64}, power::AbstractVector{T}, taus::Float64) where {T<:Real}
+function smooth_beam_power(time::AbstractVector{Float64}, power::AbstractVector{T}, taus::Real) where {T<:Real}
@assert taus >= 0.0
if taus == 0.0
return power
end
n = length(power)
- smoothed_power = similar(power)
+ smoothed_power = similar(power, promote_type(T, typeof(taus)))
if !isempty(power)
smoothed_power[1] = power[1]
@@ -509,7 +509,7 @@ function smooth_beam_power(time::AbstractVector{Float64}, power::AbstractVector{
dt = time[i] - time[i-1]
# Calculate the decay factor for the current time step
- decay_factor = exp(-dt / taus)
+ decay_factor = _decay_factor(dt, taus)
# Calculate the source contribution
source_term = power[i] * (1.0 - decay_factor)
@@ -522,12 +522,22 @@ function smooth_beam_power(time::AbstractVector{Float64}, power::AbstractVector{
return smoothed_power
end
+# exp(-dt / taus). An infinite time step (time bases can start at -Inf or end at Inf) gives an exact zero,
+# also in the derivative part when `taus` is a dual number, where the plain expression evaluates 0 * Inf.
+function _decay_factor(dt::Real, taus::Real)
+ if isfinite(dt)
+ return exp(-dt / taus)
+ else
+ return zero(dt / taus)
+ end
+end
+
"""
smooth_beam_power(time::AbstractVector{Float64}, power::AbstractVector{T}, time0::Float64, taus::Float64) where {T<:Real}
Return smoothed beam power at time0
"""
-function smooth_beam_power(time::AbstractVector{Float64}, power::AbstractVector{T}, time0::Float64, taus::Float64) where {T<:Real}
+function smooth_beam_power(time::AbstractVector{Float64}, power::AbstractVector{T}, time0::Float64, taus::Real) where {T<:Real}
n = length(power)
smoothed_power = power[1]
@@ -536,7 +546,7 @@ function smooth_beam_power(time::AbstractVector{Float64}, power::AbstractVector{
dt = time[i] - time[i-1]
# Calculate the decay factor for the current time step
- decay_factor = exp(-dt / taus)
+ decay_factor = _decay_factor(dt, taus)
# Calculate the source contribution
source_term = power[i] * (1.0 - decay_factor)
diff --git a/src/physics/fields.jl b/src/physics/fields.jl
index 5a4e5315..8bf59bcb 100644
--- a/src/physics/fields.jl
+++ b/src/physics/fields.jl
@@ -101,8 +101,9 @@ push!(document[Symbol("Physics fields")], :Bx_By_Bz)
Br_Bz_meshgrid(PSI_interpolant, r::AbstractVector{T}, z::AbstractVector{T}) where {T<:Real}
"""
function Br_Bz_meshgrid(PSI_interpolant, r::AbstractVector{T}, z::AbstractVector{T}) where {T<:Real}
- Br = Matrix{T}(undef, length(r), length(z))
- Bz = Matrix{T}(undef, length(r), length(z))
+ TB = typeof(Br_Bz(PSI_interpolant, r[1], z[1]).Br) # the field takes the number type of ψ
+ Br = Matrix{TB}(undef, length(r), length(z))
+ Bz = Matrix{TB}(undef, length(r), length(z))
for kr in eachindex(r)
for kz in eachindex(z)
Br[kr, kz], Bz[kr, kz] = Br_Bz(PSI_interpolant, r[kr], z[kz])
diff --git a/src/physics/fluxsurfaces.jl b/src/physics/fluxsurfaces.jl
index d62491b6..4b02928c 100644
--- a/src/physics/fluxsurfaces.jl
+++ b/src/physics/fluxsurfaces.jl
@@ -250,6 +250,10 @@ function find_psi_boundary(
end
psibeg = psimid
if (abs(psiend - psibeg) / (abs(psiend + psibeg) / 2.0)) < precision
+ if T2 <: ForwardDiff.Dual
+ # the bisection works on values: give the levels the derivative of what limits the surface
+ return _dual_psi_boundaries(dimR, dimZ, PSI, PSI_interpolant, psi_axis, psimid, psiend, fw_r, fw_z)
+ end
return (last_closed=psimid, first_open=psiend)
end
# open flux surface
@@ -931,6 +935,10 @@ function find_magnetic_axis(
rguess::T1=r[round(Int, length(r) / 2)],
zguess::T1=z[round(Int, length(z) / 2)]) where {T1<:Real,T2<:Real}
+ if T1 <: ForwardDiff.Dual || T2 <: ForwardDiff.Dual || PSI_interpolant(force_float64(rguess), force_float64(zguess)) isa ForwardDiff.Dual
+ return _dual_magnetic_axis(PSI_interpolant, psi_sign, force_float64(rguess), force_float64(zguess))
+ end
+
res = Optim.optimize(
x -> begin
try
@@ -1459,6 +1467,30 @@ function flux_surfaces(eqt::equilibrium__time_slice{T1}, wall_r::AbstractVector{
surfaces = trace_surfaces(eqt1d.psi, eqt1d.f, r, z, eqt2d.psi, PSI_interpolant, RA, ZA, wall_r, wall_z; refine_extrema=true, xpoints=[(xp.r, xp.z) for xp in eqt.boundary.x_point])
# calculate flux surface averaged and geometric quantities
+ _flux_surfaces_from_traced!(eqt, eqt2d, surfaces, psi_sign, R0, B0)
+
+ # find quantities on separatrix
+ find_x_point!(eqt, wall_r, wall_z)
+
+ # secondary separatrix
+ if length(eqt.boundary.x_point) > 1
+ psi2nd = find_psi_2nd_separatrix(eqt).diverted
+ pts = flux_surface(r, z, eqt2d.psi, RA, ZA, wall_r, wall_z, psi2nd, :encircling)
+ if !isempty(pts)
+ eqt.boundary_secondary_separatrix.outline.r = pts[1][1]
+ eqt.boundary_secondary_separatrix.outline.z = pts[1][2]
+ end
+ end
+
+ # find strike points
+ find_strike_points!(eqt, wall_r, wall_z, psi_boundaries.last_closed, psi_boundaries.first_open)
+
+ return eqt
+end
+
+# Flux surface averaged and geometric quantities of an equilibrium time slice from its traced flux surfaces
+function _flux_surfaces_from_traced!(eqt::equilibrium__time_slice{T1}, eqt2d, surfaces::Vector{<:FluxSurface}, psi_sign, R0, B0) where {T1<:Real}
+ eqt1d = eqt.profiles_1d
N = length(eqt1d.psi)
Np = maximum(length(surface.r) for surface in surfaces)
@@ -1493,7 +1525,7 @@ function flux_surfaces(eqt::equilibrium__time_slice{T1}, wall_r::AbstractVector{
tmp .= Btot .^ 2
avg_Btot2 = flux_surface_avg(tmp, surface)
tmp .= Btot ./ Bmax
- tmp .= (1.0 .- sqrt.(1.0 .- tmp) .* (1.0 .+ tmp ./ 2.0)) ./ tmp .^ 2
+ tmp .= (1.0 .- sqrt0.(1.0 .- tmp) .* (1.0 .+ tmp ./ 2.0)) ./ tmp .^ 2
hf = flux_surface_avg(tmp, surface)
h = avg_Btot / Bmax
h2 = avg_Btot2 / Bmax^2
@@ -1587,7 +1619,7 @@ function flux_surfaces(eqt::equilibrium__time_slice{T1}, wall_r::AbstractVector{
eqt1d.phi = cumtrapz(eqt1d.volume, tmp)
# rho_tor_norm
- rho = sqrt.(abs.(eqt1d.phi ./ (π * B0)))
+ rho = sqrt0.(abs.(eqt1d.phi ./ (π * B0)))
rho_meters = rho[end]
eqt1d.rho_tor = rho
eqt1d.rho_tor_norm = rho ./ rho_meters
@@ -1640,22 +1672,6 @@ function flux_surfaces(eqt::equilibrium__time_slice{T1}, wall_r::AbstractVector{
ip = eqt.global_quantities.ip / 1e6
eqt.global_quantities.beta_normal = eqt.global_quantities.beta_tor / abs(ip / a / Btvac) * 100
- # find quantities on separatrix
- find_x_point!(eqt, wall_r, wall_z)
-
- # secondary separatrix
- if length(eqt.boundary.x_point) > 1
- psi2nd = find_psi_2nd_separatrix(eqt).diverted
- pts = flux_surface(r, z, eqt2d.psi, RA, ZA, wall_r, wall_z, psi2nd, :encircling)
- if !isempty(pts)
- eqt.boundary_secondary_separatrix.outline.r = pts[1][1]
- eqt.boundary_secondary_separatrix.outline.z = pts[1][2]
- end
- end
-
- # find strike points
- find_strike_points!(eqt, wall_r, wall_z, psi_boundaries.last_closed, psi_boundaries.first_open)
-
return eqt
end
diff --git a/src/physics/fluxsurfaces_dual.jl b/src/physics/fluxsurfaces_dual.jl
new file mode 100644
index 00000000..3ee577a0
--- /dev/null
+++ b/src/physics/fluxsurfaces_dual.jl
@@ -0,0 +1,416 @@
+# ================================================================== #
+# Flux surfaces of an equilibrium whose data carry derivatives (duals) #
+# ================================================================== #
+# The contouring, the axis and boundary searches and the refinement of the extrema are iterative
+# geometric algorithms: they run on value parts, exactly as for a Float64 equilibrium. What they find is
+# defined by conditions on ψ(R,Z):
+#
+# - a point of a flux surface: ψ(x) = ψ_level
+# - magnetic axis and X-points: ∇ψ(x) = 0
+# - outermost/innermost and top/bottom points of a surface: ψ(x) = ψ_level and ∂ψ/∂Z = 0 (or ∂ψ/∂R = 0)
+# - last closed surface: ψ_level = ψ at the X-point or at the wall contact point that limits it
+#
+# so when ψ changes by δψ(R,Z) and the level by δψ_level each of these points moves by an amount that
+# follows from the implicit function theorem. The points are given that displacement as their derivative
+# part, and every flux-surface average and geometric quantity is then computed from them by the same code
+# as for a Float64 equilibrium, which propagates the derivatives.
+
+# dual number with zero value and the derivative part of x
+_derivative_part(x::D) where {D<:Dual} = x - ForwardDiff.value(x)
+
+# ψ gradient at a point that itself carries derivatives: first-order expansion around its value
+function _gradient_at(itp, R::D, Z::D, H::Matrix{Float64}) where {D<:Dual}
+ Rv = ForwardDiff.value(R)
+ Zv = ForwardDiff.value(Z)
+ g = _gradient(itp, Rv, Zv)
+ _hessian_values!(H, itp, Rv, Zv)
+ dR = R - Rv
+ dZ = Z - Zv
+ return (g[1] + H[1, 1] * dR + H[1, 2] * dZ, g[2] + H[2, 1] * dR + H[2, 2] * dZ)
+end
+
+function _hessian_values!(H::Matrix{Float64}, itp, R::Float64, Z::Float64)
+ HD = FI.hessian(itp, (R, Z))
+ for j in 1:2, i in 1:2
+ H[i, j] = force_float64(HD[i, j])
+ end
+ return H
+end
+
+# Point (R, Z) of the traced contour ψ = level.
+# The contouring places its points on the edges of the grid, by linear interpolation of ψ between the two
+# nodes of the edge. The same formula with dual ψ and level gives the point with its derivative. Returns
+# `nothing` when (R, Z) is not such a point.
+function _contour_point_on_edge(r::AbstractVector{Float64}, z::AbstractVector{Float64}, PSI::Matrix{D}, R::Float64, Z::Float64, level::D) where {D<:Dual}
+ ir = clamp(searchsortedlast(r, R), 1, length(r) - 1)
+ jz = clamp(searchsortedlast(z, Z), 1, length(z) - 1)
+ dr = r[ir+1] - r[ir]
+ dz = z[jz+1] - z[jz]
+ tol = 1E-8
+ for i in (ir, ir + 1) # on a grid line R = r[i]: the point moves in Z
+ if abs(R - r[i]) <= tol * dr
+ t = (level - PSI[i, jz]) / (PSI[i, jz+1] - PSI[i, jz])
+ Zd = z[jz] + t * dz
+ if abs(ForwardDiff.value(Zd) - Z) <= 1E-6 * dz
+ return (D(r[i]), Zd)
+ end
+ end
+ end
+ for j in (jz, jz + 1) # on a grid line Z = z[j]: the point moves in R
+ if abs(Z - z[j]) <= tol * dz
+ t = (level - PSI[ir, j]) / (PSI[ir+1, j] - PSI[ir, j])
+ Rd = r[ir] + t * dr
+ if abs(ForwardDiff.value(Rd) - R) <= 1E-6 * dr
+ return (Rd, D(z[j]))
+ end
+ end
+ end
+ return nothing
+end
+
+# point (R, Z) of the surface ψ = level, displaced along ∇ψ so that it stays on the surface
+function _implicit_contour_point(itp, R::Float64, Z::Float64, δlevel::D) where {D<:Dual}
+ ψ, g = _value_gradient(itp, R, Z)
+ gR = ForwardDiff.value(g[1])
+ gZ = ForwardDiff.value(g[2])
+ s = (δlevel - _derivative_part(ψ)) / (gR^2 + gZ^2)
+ return (R + s * gR, Z + s * gZ)
+end
+
+# stationary point of ψ (magnetic axis, X-point)
+function _implicit_stationary_point(itp, R::Float64, Z::Float64, H::Matrix{Float64}, ::Type{D}) where {D<:Dual}
+ g = _gradient(itp, R, Z)
+ _hessian_values!(H, itp, R, Z)
+ det = H[1, 1] * H[2, 2] - H[1, 2] * H[2, 1]
+ δg1 = _derivative_part(D(g[1]))
+ δg2 = _derivative_part(D(g[2]))
+ return (R - (H[2, 2] * δg1 - H[1, 2] * δg2) / det, Z - (-H[2, 1] * δg1 + H[1, 1] * δg2) / det)
+end
+
+# extremum in R (dir = :R, where ∂ψ/∂Z = 0) or in Z (dir = :Z, where ∂ψ/∂R = 0) of the surface ψ = level
+function _implicit_extremum(itp, R::Float64, Z::Float64, dir::Symbol, δlevel::D, H::Matrix{Float64}) where {D<:Dual}
+ ψ, g = _value_gradient(itp, R, Z)
+ _hessian_values!(H, itp, R, Z)
+ c = dir === :R ? 2 : 1 # component of the gradient that vanishes
+ a11, a12 = ForwardDiff.value(g[1]), ForwardDiff.value(g[2])
+ a21, a22 = H[c, 1], H[c, 2]
+ b1 = δlevel - _derivative_part(ψ)
+ b2 = -_derivative_part(D(g[c]))
+ det = a11 * a22 - a12 * a21
+ return (R + (a22 * b1 - a12 * b2) / det, Z + (-a21 * b1 + a11 * b2) / det)
+end
+
+# magnetic axis of a ψ interpolant whose data carry derivatives: search on values, then the displacement
+# of the stationary point
+function _dual_magnetic_axis(itp, psi_sign, rguess::Float64, zguess::Float64)
+ s = force_float64(psi_sign)
+ res = Optim.optimize(x -> force_float64(itp(x[1], x[2])) * s, [rguess, zguess], Optim.Newton())
+ D = typeof(itp(rguess, zguess))
+ H = Matrix{Float64}(undef, 2, 2)
+ RA, ZA = _implicit_stationary_point(itp, res.minimizer[1], res.minimizer[2], H, D)
+ return (RA=RA, ZA=ZA)
+end
+
+# levels of the last closed and first open flux surfaces found by the bisection of `find_psi_boundary`
+function _dual_psi_boundaries(dimR, dimZ, PSI::Matrix{D}, itp, psi_axis, psimid, psiend, fw_r, fw_z) where {D<:Dual}
+ r = Float64[force_float64(x) for x in dimR]
+ z = Float64[force_float64(x) for x in dimZ]
+ wr = Float64[force_float64(x) for x in fw_r]
+ wz = Float64[force_float64(x) for x in fw_z]
+ last_closed = _implicit_psi_boundary(r, z, PSI, itp, D(psi_axis), force_float64(psimid), force_float64(psiend), wr, wz)
+ first_open = force_float64(psiend) + _derivative_part(last_closed)
+ return (last_closed=last_closed, first_open=first_open)
+end
+
+# Level of the last closed flux surface as a dual number, given the bracket found by the bisection:
+# `psi_b_v` is the last level whose contour is closed and `psi_open_v` the first one whose contour is open.
+#
+# The contours are traced cell by cell on the grid, with linear interpolation of ψ along the edges of the
+# cells. Such a contour changes topology only when its level passes the value of ψ at a grid node, or, in
+# a cell where ψ has a saddle, the mean of ψ at the four nodes of the cell (which decides how the two
+# branches are connected). The level at which the contour opens up is therefore that node value or cell
+# mean, and it is the one that lies inside the bracket. When there is none, the surface is limited by
+# the wall, and the level follows ψ at the point of the wall that it touches. The bisection stops a
+# small, fixed fraction of the way inside that limit.
+# Saddle point of ψ (X-point) whose flux is the level `psi_b_v` to within `rtol` of the flux between axis and
+# boundary: Newton iterations on ∇ψ = 0 from the grid nodes near that level where the gradient is smallest.
+function _saddle_at_level(r::AbstractVector{Float64}, z::AbstractVector{Float64}, PSI::Matrix{D}, itp, psi_a_v::Float64, psi_b_v::Float64; rtol::Float64=1E-2) where {D<:Dual}
+ span = abs(psi_b_v - psi_a_v)
+ dr = r[2] - r[1]
+ dz = z[2] - z[1]
+ candidates = Tuple{Float64,Int,Int}[]
+ for j in 2:length(z)-1, i in 2:length(r)-1
+ if abs(ForwardDiff.value(PSI[i, j]) - psi_b_v) <= 5 * rtol * span
+ gR = (ForwardDiff.value(PSI[i+1, j]) - ForwardDiff.value(PSI[i-1, j])) / (2dr)
+ gZ = (ForwardDiff.value(PSI[i, j+1]) - ForwardDiff.value(PSI[i, j-1])) / (2dz)
+ push!(candidates, (hypot(gR, gZ), i, j))
+ end
+ end
+ sort!(candidates)
+ H = zeros(2, 2)
+ best = nothing
+ for (_, i, j) in candidates[1:min(8, end)]
+ R, Z = r[i], z[j]
+ ok = false
+ for _ in 1:30
+ g = _gradient(itp, R, Z)
+ g1 = force_float64(g[1])
+ g2 = force_float64(g[2])
+ _hessian_values!(H, itp, R, Z)
+ det = H[1, 1] * H[2, 2] - H[1, 2] * H[2, 1]
+ det < 0 || break
+ dR = -(H[2, 2] * g1 - H[1, 2] * g2) / det
+ dZ = -(-H[2, 1] * g1 + H[1, 1] * g2) / det
+ R += dR
+ Z += dZ
+ (abs(R - r[i]) <= 2dr && abs(Z - z[j]) <= 2dz) || break
+ if hypot(dR / dr, dZ / dz) < 1E-10
+ ok = true
+ break
+ end
+ end
+ ok || continue
+ miss = abs(force_float64(itp(R, Z)) - psi_b_v)
+ if miss <= rtol * span && (best === nothing || miss < best[1])
+ best = (miss, R, Z)
+ end
+ end
+ return best === nothing ? nothing : (best[2], best[3])
+end
+
+function _implicit_psi_boundary(
+ r::AbstractVector{Float64}, z::AbstractVector{Float64}, PSI::Matrix{D}, itp, psi_axis::D, psi_b_v::Float64, psi_open_v::Float64,
+ wall_r::AbstractVector{Float64}, wall_z::AbstractVector{Float64}; xpoint::Bool=true) where {D<:Dual}
+
+ psi_a_v = ForwardDiff.value(psi_axis)
+ lo, hi = minmax(psi_b_v, psi_open_v)
+ pad = 1E-3 * (hi - lo)
+ lo -= pad
+ hi += pad
+ psi_limit = nothing
+ if xpoint
+ # diverted plasma: the last closed surface follows the flux at the X-point. The level found by the
+ # search differs from it by an offset set by the contouring grid, which is piecewise in the inputs;
+ # the derivative is that of the X-point flux, which is the trend over any finite change of the inputs.
+ saddle = _saddle_at_level(r, z, PSI, itp, psi_a_v, psi_b_v)
+ if saddle !== nothing
+ psi_limit = D(itp(saddle[1], saddle[2]))
+ end
+ end
+ for j in eachindex(z), i in eachindex(r)
+ psi_limit === nothing || break
+ if lo <= ForwardDiff.value(PSI[i, j]) <= hi
+ psi_limit = PSI[i, j]
+ break
+ end
+ end
+ if psi_limit === nothing
+ for j in 1:length(z)-1, i in 1:length(r)-1
+ m = (PSI[i, j] + PSI[i+1, j] + PSI[i+1, j+1] + PSI[i, j+1]) / 4
+ if lo <= ForwardDiff.value(m) <= hi
+ psi_limit = m
+ break
+ end
+ end
+ end
+ if psi_limit === nothing && !isempty(wall_r)
+ touch = (Inf, 0.0, 0.0)
+ for k in eachindex(wall_r)
+ k2 = k == length(wall_r) ? 1 : k + 1
+ for t in range(0.0, 1.0, 21)
+ Rw = wall_r[k] + t * (wall_r[k2] - wall_r[k])
+ Zw = wall_z[k] + t * (wall_z[k2] - wall_z[k])
+ if r[1] <= Rw <= r[end] && z[1] <= Zw <= z[end]
+ touch = min(touch, (abs(force_float64(itp(Rw, Zw)) - psi_b_v), Rw, Zw))
+ end
+ end
+ end
+ psi_limit = D(itp(touch[2], touch[3]))
+ end
+ if psi_limit === nothing
+ return D(psi_b_v)
+ end
+ fraction = (psi_b_v - psi_a_v) / (ForwardDiff.value(psi_limit) - psi_a_v)
+ return psi_b_v + _derivative_part(psi_axis + fraction * (psi_limit - psi_axis))
+end
+
+"""
+ flux_surfaces(eqt::equilibrium__time_slice{D}, wall_r, wall_z) where {D<:ForwardDiff.Dual}
+
+Flux surface averaged and geometric quantities of an equilibrium time slice whose data carry derivatives.
+
+The value part of every result is that of the Float64 calculation. The derivative parts follow from the
+conditions that define the axis, the boundary, the flux surfaces and their extrema (implicit function
+theorem), and are then propagated through the flux-surface averages. The wall is machine geometry and is
+taken as given. The positions of strike points and the outlines of the separatrices are diagnostics of
+the geometry and are returned without derivative parts.
+"""
+function flux_surfaces(eqt::equilibrium__time_slice{D}, wall_r::AbstractVector{T2}, wall_z::AbstractVector{T2}) where {D<:ForwardDiff.Dual,T2<:Real}
+ wr = Float64[force_float64(x) for x in wall_r]
+ wz = Float64[force_float64(x) for x in wall_z]
+
+ # ---- Float64 calculation: values of everything, and of the points that define the geometry ----
+ # (the copy of the time slice lives in a data dictionary of its own; the inputs that are expressions
+ # of other parts of the original data dictionary are evaluated there and stored as data)
+ dd_v = dd{Float64}()
+ resize!(dd_v.equilibrium.time_slice, 1)
+ eqt_v = dd_v.equilibrium.time_slice[1]
+ fill!(eqt_v, eqt)
+ dd_v.equilibrium.time = [eqt.time]
+ dd_v.global_time = eqt.time
+ eqt_v.global_quantities.vacuum_toroidal_field.r0 = force_float64(eqt.global_quantities.vacuum_toroidal_field.r0)
+ eqt_v.global_quantities.vacuum_toroidal_field.b0 = force_float64(eqt.global_quantities.vacuum_toroidal_field.b0)
+ for field in (:psi, :f, :pressure, :dpressure_dpsi, :f_df_dpsi)
+ setproperty!(eqt_v.profiles_1d, field, Float64[force_float64(x) for x in getproperty(eqt.profiles_1d, field)])
+ end
+ xpoints_in = [(xp.r, xp.z) for xp in eqt_v.boundary.x_point]
+ psi_in = eqt.profiles_1d.psi
+ flux_surfaces(eqt_v, wr, wz)
+
+ eqt1d = eqt.profiles_1d
+ eqt1d_v = eqt_v.profiles_1d
+ eqt2d = findfirst(:rectangular, eqt.profiles_2d)
+ eqt2d_v = findfirst(:rectangular, eqt_v.profiles_2d)
+ r, z, itp_v = ψ_interpolant(eqt2d_v)
+ itp = ψ_interpolant(r, z, eqt2d.psi).PSI_interpolant # dual ψ on the plain grid
+ H = Matrix{Float64}(undef, 2, 2)
+
+ psi_sign = sign(eqt1d_v.psi[end] - eqt1d_v.psi[1])
+ R0 = eqt.global_quantities.vacuum_toroidal_field.r0
+ B0 = eqt.global_quantities.vacuum_toroidal_field.b0
+
+ for field in (:psi_boundary, :psi_axis, :q_95, :q_axis, :q_min)
+ empty!(eqt.global_quantities, field)
+ end
+
+ # ---- magnetic axis ----
+ RAv = eqt_v.global_quantities.magnetic_axis.r
+ ZAv = eqt_v.global_quantities.magnetic_axis.z
+ RA, ZA = _implicit_stationary_point(itp, RAv, ZAv, H, D)
+ eqt.global_quantities.magnetic_axis.r, eqt.global_quantities.magnetic_axis.z = RA, ZA
+ psi_axis = D(itp(RAv, ZAv)) # ∇ψ = 0 at the axis: its displacement does not change ψ there to first order
+
+ # ---- last closed flux surface ----
+ psi_b_v = eqt_v.boundary.psi
+ rescaled = eqt_v.boundary_separatrix.psi !== eqt_v.boundary.psi
+ if !isempty(wr) || eqt.global_quantities.free_boundary == 1
+ psi_boundary = _implicit_psi_boundary(collect(r), collect(z), eqt2d.psi, itp, psi_axis, psi_b_v, eqt_v.boundary_separatrix.psi, wr, wz)
+ # when the level follows an X-point the points of the last surface are displaced on the smooth ψ(R,Z)
+ # rather than along the grid edges, where the linear interpolation is poor next to the X-point
+ smooth_boundary = _saddle_at_level(collect(r), collect(z), eqt2d.psi, itp, ForwardDiff.value(psi_axis), psi_b_v) !== nothing
+ else
+ psi_boundary = psi_in[end]
+ smooth_boundary = false
+ end
+ if rescaled
+ eqt1d.psi = (psi_in .- psi_in[1]) ./ (psi_in[end] - psi_in[1]) .* (psi_boundary - psi_axis) .+ psi_axis
+ end
+ eqt.boundary.psi = psi_boundary
+ eqt.boundary_separatrix.psi = eqt_v.boundary_separatrix.psi + _derivative_part(psi_boundary)
+
+ for item in (:b_field_average, :b_field_max, :b_field_min, :elongation, :triangularity_lower, :triangularity_upper,
+ :squareness_lower_inner, :squareness_lower_outer, :squareness_upper_inner, :squareness_upper_outer, :r_inboard, :r_outboard,
+ :q, :surface, :dvolume_dpsi, :j_tor, :gm1, :gm2, :gm4, :gm5, :gm8, :gm9, :gm10, :fsa_bp, :trapped_fraction)
+ setproperty!(eqt1d, item, zeros(D, size(eqt1d.psi)))
+ end
+
+ # ---- flux surfaces: traced on values, then given their displacement ----
+ surfaces_v = trace_surfaces(eqt1d_v.psi, eqt1d_v.f, r, z, eqt2d_v.psi, itp_v, RAv, ZAv, wr, wz; refine_extrema=true, xpoints=xpoints_in)
+ N = length(surfaces_v)
+ surfaces = Vector{FluxSurface{D}}(undef, N)
+ f = eqt1d.f
+ for k in N:-1:1
+ sv = surfaces_v[k]
+ np = length(sv.r)
+ pr = Vector{D}(undef, np)
+ pz = Vector{D}(undef, np)
+ if k == 1
+ # artificial surface around the axis, scaled from the second one
+ pr .= (surfaces[2].r .- RA) ./ 100.0 .+ RA
+ pz .= (surfaces[2].z .- ZA) ./ 100.0 .+ ZA
+ else
+ level = eqt1d.psi[k]
+ δlevel = _derivative_part(level)
+ on_edges = 0
+ for i in 1:np
+ point = (k == N && smooth_boundary) ? nothing : _contour_point_on_edge(r, z, eqt2d.psi, sv.r[i], sv.z[i], level)
+ if point === nothing
+ point = _implicit_contour_point(itp, sv.r[i], sv.z[i], δlevel)
+ else
+ on_edges += 1
+ end
+ pr[i], pz[i] = point
+ end
+ if k == 2 && on_edges == 0
+ # the innermost surface could not be traced and was scaled from the next one
+ pr .= (surfaces[k+1].r .- RA) ./ 2 .+ RA
+ pz .= (surfaces[k+1].z .- ZA) ./ 2 .+ ZA
+ end
+ end
+
+ Br = Vector{D}(undef, np)
+ Bz = Vector{D}(undef, np)
+ Bp = Vector{D}(undef, np)
+ Btot = Vector{D}(undef, np)
+ fluxexpansion = Vector{D}(undef, np)
+ for i in 1:np
+ g = _gradient_at(itp, pr[i], pz[i], H)
+ inv_twopi_r = 1.0 / (2π * pr[i])
+ Br[i] = g[2] * inv_twopi_r
+ Bz[i] = -g[1] * inv_twopi_r
+ Bp2 = Br[i]^2 + Bz[i]^2
+ Bp_abs = sqrt(Bp2)
+ Bp[i] = Bp_abs * sign((pz[i] - ZA) * Br[i] - (pr[i] - RA) * Bz[i])
+ Btot[i] = sqrt(Bp2 + (f[k] / pr[i])^2)
+ fluxexpansion[i] = 1.0 / Bp_abs
+ end
+ ll = arc_length(pr, pz)
+ int_fluxexpansion_dl = trapz(ll, fluxexpansion)
+
+ if k == 1
+ frac = 0.01
+ s2 = surfaces[2]
+ ext = ((s2.r_at_max_z - RA) * frac + RA, (s2.max_z - ZA) * frac + ZA, (s2.r_at_min_z - RA) * frac + RA, (s2.min_z - ZA) * frac + ZA,
+ (s2.z_at_max_r - ZA) * frac + ZA, (s2.max_r - RA) * frac + RA, (s2.z_at_min_r - ZA) * frac + ZA, (s2.min_r - RA) * frac + RA)
+ else
+ δlevel = _derivative_part(eqt1d.psi[k])
+ r_at_max_z, max_z = _implicit_extremum(itp, sv.r_at_max_z, sv.max_z, :Z, δlevel, H)
+ r_at_min_z, min_z = _implicit_extremum(itp, sv.r_at_min_z, sv.min_z, :Z, δlevel, H)
+ max_r, z_at_max_r = _implicit_extremum(itp, sv.max_r, sv.z_at_max_r, :R, δlevel, H)
+ min_r, z_at_min_r = _implicit_extremum(itp, sv.min_r, sv.z_at_min_r, :R, δlevel, H)
+ ext = (r_at_max_z, max_z, r_at_min_z, min_z, z_at_max_r, max_r, z_at_min_r, min_r)
+ end
+
+ surfaces[k] = FluxSurface(eqt1d.psi[k], pr, pz, ext..., Br, Bz, Bp, Btot, ll, fluxexpansion, int_fluxexpansion_dl)
+ end
+
+ _flux_surfaces_from_traced!(eqt, eqt2d, surfaces, psi_sign, R0, B0)
+
+ # ---- X-points, strike points, separatrices: values from the Float64 calculation ----
+ fill!(eqt.boundary.x_point, eqt_v.boundary.x_point)
+ for xp in eqt.boundary.x_point
+ xp.r, xp.z = _implicit_stationary_point(itp, force_float64(xp.r), force_float64(xp.z), H, D)
+ end
+ fill!(eqt.boundary.strike_point, eqt_v.boundary.strike_point)
+ psi_separatrix = eqt.boundary_separatrix.psi
+ fill!(eqt.boundary_separatrix, eqt_v.boundary_separatrix)
+ eqt.boundary_separatrix.psi = psi_separatrix
+ fill!(eqt.boundary_secondary_separatrix, eqt_v.boundary_secondary_separatrix)
+
+ # the value part of every result is that of the Float64 calculation
+ replace_values!(eqt, eqt_v)
+
+ return eqt
+end
+
+# The contouring routine takes its tolerances in the number type of the grid, with defaults built from
+# `eps` of that type, which is a plain float also for dual numbers. This method supplies them in the
+# right type when grid and data are dual numbers.
+function IMASutils.contour_from_midplane!(
+ x_cache::Vector{D}, y_cache::Vector{D}, values::Matrix{D}, x_coords::AbstractVector{D}, y_coords::AbstractVector{D},
+ level::D, xaxis::D, yaxis::D, vaxis::D;
+ atol::Real=eps(Float64), rtol::Real=sqrt(eps(Float64)), dynamic_resize::Bool=true) where {D<:Dual}
+ return invoke(IMASutils.contour_from_midplane!,
+ Tuple{Vector{T1},Vector{T1},Matrix{T2},AbstractVector{T1},AbstractVector{T1},T2,T1,T1,T2} where {T1<:Real,T2<:Real},
+ x_cache, y_cache, values, x_coords, y_coords, level, xaxis, yaxis, vaxis; atol=D(atol), rtol=D(rtol), dynamic_resize)
+end
diff --git a/src/physics/particles.jl b/src/physics/particles.jl
index f510ccc6..011069d3 100644
--- a/src/physics/particles.jl
+++ b/src/physics/particles.jl
@@ -464,8 +464,9 @@ Returns all times of intersection between a moving particle and a wall in toroid
- `vx`, `vy`, `vz`: Velocity components of the particle
"""
function toroidal_intersections(wallr::Vector{T}, wallz::Vector{T}, px::Real, py::Real, pz::Real, vx::Real, vy::Real, vz::Real; max_intersections::Int=4) where {T<:Real}
- t0 = 0.0
- t_intersects = Float64[]
+ TT = promote_type(Float64, T, typeof(px), typeof(py), typeof(pz), typeof(vx), typeof(vy), typeof(vz))
+ t0 = zero(TT)
+ t_intersects = TT[]
for n in 1:max_intersections
t = toroidal_intersection(wallr, wallz, px, py, pz, vx, vy, vz)
if isnan(t)
@@ -524,7 +525,7 @@ push!(document[Symbol("Physics particles")], :pol_tor_angles_2_vector)
returns named tuple with (x, y, z, r) of a beam injected at given (px, py, pz) starting_position with velocity (vx, vy, vz)
"""
-function pencil_beam(starting_position::Vector{T}, velocity_vector::Vector{T}, time::AbstractVector{Float64}) where {T<:Real}
+function pencil_beam(starting_position::Vector{<:Real}, velocity_vector::Vector{<:Real}, time::AbstractVector{<:Real})
x = starting_position[1] .+ velocity_vector[1] .* time
y = starting_position[2] .+ velocity_vector[2] .* time
z = starting_position[3] .+ velocity_vector[3] .* time
@@ -537,7 +538,7 @@ end
returns named tuple with (x, y, z, r) of a beam injected at given (px, py, pz) starting_position with given poloidal and toroidal angles
"""
-function pencil_beam(starting_position::Vector{T}, pol_angle::T, tor_angle::T, time::AbstractVector{Float64}) where {T<:Real}
+function pencil_beam(starting_position::Vector{<:Real}, pol_angle::Real, tor_angle::Real, time::AbstractVector{<:Real})
vx, vy, vz = pol_tor_angles_2_vector(pol_angle, tor_angle)
return pencil_beam(starting_position, [vx, vy, vz], time)
end
diff --git a/src/physics/pedestal.jl b/src/physics/pedestal.jl
index bfebf649..1e6c9727 100644
--- a/src/physics/pedestal.jl
+++ b/src/physics/pedestal.jl
@@ -1,5 +1,14 @@
document[Symbol("Physics pedestal")] = Symbol[]
+"""
+ pedestal_search_tolerance
+
+Tolerances of the one-dimensional (Brent, relative) and simplex (Nelder-Mead) searches used to blend core
+and pedestal profiles. The defaults are the values these searches have always used; they can be tightened,
+for example to compare derivatives of the result with finite differences.
+"""
+const pedestal_search_tolerance = (brent=Ref(1E-3), simplex=Ref(1E-6))
+
function diffnorm(A::AbstractVector{<:Real}, B::AbstractVector{<:Real})
@assert length(A) == length(B)
return @inbounds norm(A[k] - B[k] for k in eachindex(A))
@@ -61,18 +70,78 @@ function blend_core_edge_Hmode(
expin = 1.0
expout = 1.0
x_guess = StaticArrays.@MVector[expin, expout]
- res = Optim.optimize(
- x -> cost_find_EPED_exps(x, ped_height, ped_width, rho, profile, p_targets, z_targets, rho_targets),
- x_guess,
- Optim.NelderMead(),
- Optim.Options(; g_tol=1E-6)
- )
- expin = abs(res.minimizer[1])
- expout = abs(res.minimizer[2])
+ D = promote_type(eltype(profile), typeof(ped_height), typeof(ped_width))
+ if D <: ForwardDiff.Dual
+ # search on value parts, then derivatives of the exponents from the implicit function theorem
+ cost = x -> cost_find_EPED_exps(x, ped_height, ped_width, rho, profile, p_targets, z_targets, rho_targets)
+ res = Optim.optimize(x -> force_float64(cost(x)), x_guess, Optim.NelderMead(), Optim.Options(; g_tol=pedestal_search_tolerance.simplex[]))
+ xstar = Float64[res.minimizer[1], res.minimizer[2]]
+ if IMPLICIT_DERIVATIVES[]
+ # The derivative depends on which kind of minimum this is (see `_implicit_EPED_exps`), and that can
+ # only be told apart at a tightly converged minimum: the search is continued to a tight tolerance for
+ # the derivative, while the values remain those of the search at its usual tolerance.
+ polished = Optim.optimize(x -> force_float64(cost(x)), copy(xstar), Optim.NelderMead(), Optim.Options(; g_tol=1E-14, iterations=5000))
+ exps_polished = _implicit_EPED_exps(cost, Float64[polished.minimizer[1], polished.minimizer[2]], D, ped_height, ped_width, rho, profile, p_targets, z_targets, rho_targets)
+ exps = [xstar[j] + _derivative_part(exps_polished[j]) * (sign(xstar[j]) == sign(ForwardDiff.value(exps_polished[j])) ? 1 : -1) for j in 1:2]
+ else
+ exps = D.(xstar)
+ end
+ expin = abs(exps[1])
+ expout = abs(exps[2])
+ else
+ res = Optim.optimize(
+ x -> cost_find_EPED_exps(x, ped_height, ped_width, rho, profile, p_targets, z_targets, rho_targets),
+ x_guess,
+ Optim.NelderMead(),
+ Optim.Options(; g_tol=pedestal_search_tolerance.simplex[])
+ )
+ expin = abs(res.minimizer[1])
+ expout = abs(res.minimizer[2])
+ end
return blend_core_edge_EPED(profile, rho, ped_height, ped_width, tr_bound0, tr_bound1, expin, expout; method)
end
+# Derivatives of the exponents found by the search in `blend_core_edge_Hmode`.
+#
+# The cost is the sum of two norms (mismatch of the inverse scale lengths and of the values at the two
+# blending radii) over two unknowns that enter through their absolute value. Its minimum is of one of
+# three kinds, and the condition that defines the exponents, hence their derivative, differs:
+# - one of the two mismatches vanishes exactly: the cost has a kink there and the exponents are the
+# solution of that mismatch being zero;
+# - an exponent sits at zero, the kink of the absolute value: it stays there;
+# - otherwise the cost is smooth at the minimum and its gradient vanishes.
+function _implicit_EPED_exps(cost, xstar::Vector{Float64}, ::Type{D}, ped_height, ped_width, rho, profile, p_targets, z_targets, rho_targets) where {D<:ForwardDiff.Dual}
+ function mismatches(x)
+ profile_ped = Hmode_profiles(profile[end], ped_height, length(rho), abs(x[1]), abs(x[2]), ped_width)
+ z_ped = -calc_z(rho, profile_ped, :backward)
+ mismatch_z = collect(z_targets .- interp1d(rho, z_ped).(rho_targets)) ./ sum(abs, z_targets)
+ mismatch_p = collect(p_targets .- interp1d(rho, profile_ped).(rho_targets)) ./ sum(abs, p_targets)
+ return mismatch_z, mismatch_p
+ end
+
+ free = [j for j in eachindex(xstar) if abs(xstar[j]) > 1E-2]
+ dx = zeros(length(xstar), _npartials(D))
+ if !isempty(free) && IMPLICIT_DERIVATIVES[]
+ embed(xf) = [j in free ? xf[findfirst(==(j), free)] : oftype(xf[1], xstar[j]) for j in eachindex(xstar)]
+ x0 = D.(xstar[free])
+ r_z, r_p = mismatches(embed(x0))
+ tol = 1E-6
+ if norm(ForwardDiff.value.(r_z)) < tol || norm(ForwardDiff.value.(r_p)) < tol
+ pick = norm(ForwardDiff.value.(r_z)) < tol ? 1 : 2
+ r = xf -> mismatches(embed(xf))[pick]
+ J = ForwardDiff.value.(ForwardDiff.jacobian(r, x0))
+ dx[free, :] .= -(LinearAlgebra.pinv(J; rtol=1E-10) * _partials_matrix(pick == 1 ? r_z : r_p))
+ else
+ c = xf -> cost(embed(xf))
+ gθ = _partials_matrix(ForwardDiff.gradient(c, x0))
+ H = ForwardDiff.value.(ForwardDiff.hessian(c, x0))
+ dx[free, :] .= -(LinearAlgebra.pinv((H .+ H') ./ 2; rtol=1E-10) * gθ)
+ end
+ end
+ return _with_partials(D, xstar, dx)
+end
+
@compat public blend_core_edge_Hmode
push!(document[Symbol("Physics pedestal")], :blend_core_edge_Hmode)
@@ -204,8 +273,18 @@ function blend_core_edge_Lmode(
)
@assert rho[end] == 1.0
- res = Optim.optimize(α -> cost_WPED_α!(rho, profile, α, value, rho_bound), -500, 500, Optim.Brent(); rel_tol=1E-3)
- cost_WPED_α!(rho, profile, res.minimizer, value, rho_bound)
+ res = Optim.optimize(α -> force_float64(cost_WPED_α!(rho, profile, α, value, rho_bound)), -500, 500, Optim.Brent(); rel_tol=pedestal_search_tolerance.brent[])
+ D = promote_type(eltype(profile), typeof(value))
+ if D <: ForwardDiff.Dual
+ # derivative of the exponent from the implicit function theorem on the signed mismatch
+ profile0 = copy(profile)
+ G = u -> (profile .= profile0; [residual_WPED_α!(rho, profile, u[1], value, rho_bound)])
+ α = implicit_solution(G, Float64[res.minimizer], D; atol=1E-2)[1]
+ profile .= profile0
+ cost_WPED_α!(rho, profile, α, value, rho_bound)
+ else
+ cost_WPED_α!(rho, profile, res.minimizer, value, rho_bound)
+ end
return profile
end
@@ -230,6 +309,23 @@ function cost_WPED_α!(rho::AbstractVector{<:Real}, profile::AbstractVector{<:Re
return cost
end
+"""
+ residual_WPED_α!(rho, profile, α, value_ped, rho_ped)
+
+Same update of `profile` as `cost_WPED_α!`, returning the signed relative mismatch of the inverse scale
+lengths at the pedestal boundary (`cost_WPED_α!` is its absolute value)
+"""
+function residual_WPED_α!(rho::AbstractVector{<:Real}, profile::AbstractVector{<:Real}, α::Real, value_ped::Real, rho_ped::Real)
+ @assert rho[end] == 1.0
+ rho_ped_idx = argmin_abs(rho, rho_ped)
+ profile_ped = exponential_profile(rho, rho_ped, value_ped, profile[end], α)
+ z_profile_ped = calc_z(rho, profile_ped, :backward)
+ profile .+= (-profile[rho_ped_idx] + value_ped)
+ z_profile = calc_z(rho, profile, :backward)
+ profile[rho_ped_idx+1:end] .= interp1d(rho, profile_ped).(rho[rho_ped_idx+1:end])
+ return (z_profile[rho_ped_idx] - z_profile_ped[rho_ped_idx]) / z_profile[rho_ped_idx]
+end
+
"""
pedestal_finder(profile::Vector{T}, psi_norm::Vector{T}; do_plot::Bool=false) where {T<:Real}
diff --git a/src/physics/profiles.jl b/src/physics/profiles.jl
index 5d81c619..2948e496 100644
--- a/src/physics/profiles.jl
+++ b/src/physics/profiles.jl
@@ -33,11 +33,14 @@ end
pressure_thermal(cp1di::IMAS.IDSvector{IMAS.core_profiles__profiles_1d___ion{T}}) where {T<:Real}
thermal pressure for all ions
+
+An ion contributes when its thermal density is available, either stored or derived from a stored total density
+(`density_thermal = density - density_fast`). Ions with only a fast density have no thermal pressure.
"""
function pressure_thermal(cp1di::IMAS.IDSvector{IMAS.core_profiles__profiles_1d___ion{T}}) where {T<:Real}
p = zero(cp1di[1].temperature)
for ion in cp1di
- if hasdata(ion, :density_thermal)
+ if hasdata(ion, :density_thermal) || hasdata(ion, :density)
p .+= ion.temperature .* ion.density_thermal
end
end
@@ -254,6 +257,16 @@ function ion_element!(
return ion_element!(ion, elements[ion_z].symbol; fast)
end
+# mass number given in a number type other than Float64 (e.g. read from a dd that carries derivatives):
+# the species is identified from its value
+function ion_element!(
+ ion::Union{IMAS.core_profiles__profiles_1d___ion,IMAS.core_sources__source___profiles_1d___ion},
+ ion_z::Int,
+ ion_a::Real;
+ kw...)
+ return ion_element!(ion, ion_z, force_float64(ion_a); kw...)
+end
+
@compat public ion_element!
push!(document[Symbol("Physics profiles")], :ion_element!)
diff --git a/src/physics/radiation.jl b/src/physics/radiation.jl
index 0ecdc037..7b06525a 100644
--- a/src/physics/radiation.jl
+++ b/src/physics/radiation.jl
@@ -163,6 +163,19 @@ function rad_ion_adas(Te, ne, ni, zi, namei)
return qline
end
+# Chebyshev polynomial of the first kind, T_n(x) = cos(n acos(x)) on [-1, 1].
+# At the ends of the interval the derivative of acos is infinite while T_n'(±1) is finite;
+# inputs are clamped to the interval before this is called, so there the result does not
+# depend on the input and the derivative part is dropped instead of evaluating 0 * Inf.
+_chebyshev_T(n::Int, x::Real) = cos(n * acos(x))
+function _chebyshev_T(n::Int, x::D) where {D<:ForwardDiff.Dual}
+ if abs(ForwardDiff.value(x)) >= 1.0
+ return D(cos(n * acos(ForwardDiff.value(x))))
+ else
+ return cos(n * acos(x))
+ end
+end
+
"""
adas21(Te, name)
@@ -526,7 +539,7 @@ function adas21(Te, name)
# Sum the Chebyshev series where T_n(x) = cos[n * arccos(x)]
s = zero(x)
for i in eachindex(coefficients)
- s = s .+ (coefficients[i] .* cos.((i - 1) .* acos.(x)))
+ s = s .+ (coefficients[i] .* _chebyshev_T.(i - 1, x))
end
# Lz (cooling rate) in [erg / cm^3 / s]
diff --git a/src/physics/rf.jl b/src/physics/rf.jl
index 957d6b21..a802bb88 100644
--- a/src/physics/rf.jl
+++ b/src/physics/rf.jl
@@ -98,7 +98,18 @@ function ech_resonance_layer(eqt::IMAS.equilibrium__time_slice{T}, frequency::T;
RA = eqt.global_quantities.magnetic_axis.r
ZA = eqt.global_quantities.magnetic_axis.r
- layers = Dict{T,Tuple{Vector{T},Vector{T},Int}}()
+ if !(T <: AbstractFloat)
+ # The resonance layer is contoured on value parts and returned without derivative parts:
+ # for number types that carry derivatives, the dependence of the layer position on the
+ # magnetic field is not propagated.
+ R = Float64[force_float64(x) for x in R]
+ Z = Float64[force_float64(x) for x in Z]
+ Bωce_over_Btot = force_float64.(Bωce_over_Btot)
+ RA = force_float64(RA)
+ ZA = force_float64(ZA)
+ end
+
+ layers = Dict{eltype(R),Tuple{Vector{eltype(R)},Vector{eltype(R)},Int}}()
for harmonic in harmonics
for line in Contour.lines(Contour.contour(R, Z, Bωce_over_Btot, harmonic))
pr, pz = Contour.coordinates(line)
@@ -111,7 +122,7 @@ function ech_resonance_layer(eqt::IMAS.equilibrium__time_slice{T}, frequency::T;
return (r=T[], z=T[], harmonic=0)
else
core_layer = layers[minimum(keys(layers))]
- return (r=core_layer[1], z=core_layer[2], harmonic=core_layer[3])
+ return (r=convert(Vector{T}, core_layer[1]), z=convert(Vector{T}, core_layer[2]), harmonic=core_layer[3])
end
end
diff --git a/src/physics/sources.jl b/src/physics/sources.jl
index d7a787cc..ee3991db 100644
--- a/src/physics/sources.jl
+++ b/src/physics/sources.jl
@@ -325,7 +325,7 @@ function total_power_time(core_sources::IMAS.core_sources, include_indexes::Vect
append!(sources, findall(core_sources.source, "identifier.index" => index))
end
time_array = core_sources.time
- total_power = zeros(length(time_array))
+ total_power = zeros(eltype(core_sources), length(time_array))
for source in sources
total_power .+= [total_power_source(source.profiles_1d[t]) for t in time_array]
end
@@ -597,7 +597,12 @@ end
function sawteeth_source!(dd::IMAS.DD{T}, ::Nothing; flat_factor::Real=0.5, exclude_indexes::AbstractVector{Int}=IMASdd.index_no_sawtooth) where {T<:Real}
# no inversion radius, so call with rho0 = 0.0
- return sawteeth_source!(dd, 0.0; flat_factor, exclude_indexes)
+ return sawteeth_source!(dd, zero(T); flat_factor, exclude_indexes)
+end
+
+function sawteeth_source!(dd::IMAS.DD{T}, rho0::AbstractFloat; flat_factor::Real=0.5, exclude_indexes::AbstractVector{Int}=IMASdd.index_no_sawtooth) where {T<:ForwardDiff.Dual}
+ # inversion radius given as a plain float for a dd with dual numbers
+ return sawteeth_source!(dd, T(rho0); flat_factor, exclude_indexes)
end
function sawteeth_source!(dd::IMAS.DD{T}, i_qdes::Int; flat_factor::Real=0.5, exclude_indexes::AbstractVector{Int}=IMASdd.index_no_sawtooth) where {T<:Real}
diff --git a/src/real.jl b/src/real.jl
index 305eb7e0..7302d42c 100644
--- a/src/real.jl
+++ b/src/real.jl
@@ -96,21 +96,6 @@ function Base.setproperty!(ids::IDS{T}, field::Symbol, value::Measurements.Measu
return value
end
-"""
- fill!(@nospecialize(ids_new::IDS{<:T1}), @nospecialize(ids::IDS{<:T2}), field::Symbol) where {T1<:Float64,T2<:ForwardDiff.Dual{Float64,Float64,0}}
-
-Function used to map fields in `IDS{Dual{T,T,0}}` to `IDS{T}`
-"""
-function Base.fill!(@nospecialize(ids_new::IDS{<:T1}), @nospecialize(ids::IDS{<:T2}), field::Symbol) where {T1<:Float64,T2<:ForwardDiff.Dual{Float64,Float64,0}}
- value = getraw(ids, field)
- if eltype(value) <: T2
- _setproperty!(ids_new, field, ForwardDiff.value.(value); from_cocos=internal_cocos)
- else
- _setproperty!(ids_new, field, value; from_cocos=internal_cocos)
- end
- return nothing
-end
-
function Base.setproperty!(ids::IDS{T}, field::Symbol, value::AbstractVector{<:ForwardDiff.Dual}) where {T<:Float64}
setproperty!(ids, field, [ForwardDiff.value(v) for v in value])
return value
@@ -121,6 +106,10 @@ function Base.setproperty!(ids::IDS{T}, field::Symbol, value::ForwardDiff.Dual)
return value
end
+function Base.unsafe_trunc(::Type{Int64}, x::ForwardDiff.Dual)
+ return unsafe_trunc(Int64, ForwardDiff.value(x))
+end
+
function Base.round(::Type{Int64}, x::ForwardDiff.Dual, r::RoundingMode)
return round(Int, ForwardDiff.value(x), r)
end
diff --git a/src/signal.jl b/src/signal.jl
index 5182efa3..7bc40fb5 100644
--- a/src/signal.jl
+++ b/src/signal.jl
@@ -126,7 +126,7 @@ push!(document[Symbol("Signal")], :trap)
Unitary gaussian
"""
-function gaus(t::Float64, order::Float64=1.0)
+function gaus(t::Real, order::Real=1.0)
return exp(-(t^2 / 2.0)^order)
end
@@ -135,7 +135,7 @@ end
Unitary gaussian centered at t_start and with standard deviation Δt
"""
-function gaus(t::Float64, t_start::Float64, Δt::Float64, order::Float64=1.0)
+function gaus(t::Real, t_start::Real, Δt::Real, order::Real=1.0)
return gaus((t - t_start) / Δt, order)
end
diff --git a/test/runtests.jl b/test/runtests.jl
index 55737a78..481f22cd 100644
--- a/test/runtests.jl
+++ b/test/runtests.jl
@@ -35,4 +35,8 @@ else
include("runtests_plot_recipes.jl")
include("runtests_satellite.jl")
+
+ include("runtests_dual.jl")
+
+ include("runtests_profiles.jl")
end
diff --git a/test/runtests_dual.jl b/test/runtests_dual.jl
new file mode 100644
index 00000000..bf6c9180
--- /dev/null
+++ b/test/runtests_dual.jl
@@ -0,0 +1,188 @@
+using IMAS
+using Test
+import IMAS.ForwardDiff
+import IMAS.ForwardDiff: value, partials
+
+# Derivatives carried by dual numbers are compared with central finite differences of the Float64 code
+
+const D2 = IMAS.InputsDual{2}
+
+central(f, h) = (f(+h) .- f(-h)) ./ (2h)
+
+@testset "dual-typed dd: conversion, seeding, value and partials" begin
+ filename = joinpath(dirname(dirname(pathof(IMAS.IMASdd))), "sample", "D3D_eq_ods.json")
+ dd = IMAS.json2imas(filename; show_warnings=false)
+
+ ddd = IMAS.retype(D2, dd)
+ @test eltype(ddd) === D2
+ @test ddd.global_time == dd.global_time
+ @test IMAS.npartials(ddd) == 2
+ @test convert(D2, dd.equilibrium) isa IMAS.equilibrium{D2} # no ambiguity with ForwardDiff's convert
+
+ eqt = ddd.equilibrium.time_slice[]
+ f0 = dd.equilibrium.time_slice[].profiles_1d.f
+ eqt.profiles_1d.f = eqt.profiles_1d.f .* IMAS.seed(D2, 2)
+ @test value.(eqt.profiles_1d.f) == f0
+ @test partials.(eqt.profiles_1d.f, 2) == f0
+ @test all(iszero, partials.(eqt.profiles_1d.f, 1))
+ @test eltype(eqt.profiles_1d.psi) === D2
+ @test eqt.time isa Float64 # times stay plain floats
+
+ back = IMAS.value_dd(ddd)
+ @test eltype(back) === Float64
+ @test back.equilibrium.time_slice[].profiles_1d.f == f0
+ @test back.equilibrium.time_slice[].profiles_2d[1].psi == dd.equilibrium.time_slice[].profiles_2d[1].psi
+
+ d2 = IMAS.partials_dd(ddd, 2)
+ @test d2.equilibrium.time_slice[].profiles_1d.f == f0
+ @test all(iszero, d2.equilibrium.time_slice[].profiles_1d.psi)
+
+ # values are replaced, partials are kept
+ target = deepcopy(dd)
+ target.equilibrium.time_slice[].profiles_1d.f = 2 .* f0
+ @test IMAS.replace_values!(ddd, target) == 0
+ @test value.(eqt.profiles_1d.f) == 2 .* f0
+ @test partials.(eqt.profiles_1d.f, 2) == f0
+
+ # the tag of the inputs nests outside any other ForwardDiff tag
+ g = ForwardDiff.derivative(x -> x^2 * IMAS.seed(D2, 1), 3.0)
+ @test value(g) == 6.0 && partials(g, 1) == 6.0
+
+ # files hold plain numbers: one for the values and one per partial
+ dir = mktempdir()
+ IMAS.imas2json(ddd.equilibrium, joinpath(dir, "eq.json"))
+ @test isfile(joinpath(dir, "eq.json")) && isfile(joinpath(dir, "eq_d1.json")) && isfile(joinpath(dir, "eq_d2.json"))
+end
+
+@testset "derivatives of iterative searches" begin
+ a = 2.0 * IMAS.seed(D2, 1)
+ b = 3.0 * IMAS.seed(D2, 2)
+
+ # root of G(u) = [u1^2 - a, u1*u2 - b]: u1 = sqrt(a), u2 = b/sqrt(a)
+ G = u -> [u[1]^2 - a, u[1] * u[2] - b]
+ u = IMAS.implicit_solution(G, [sqrt(2.0), 3.0 / sqrt(2.0)], D2)
+ @test partials(u[1], 1) ≈ 0.5 * sqrt(2.0) rtol = 1e-6 # d/dln a of sqrt(a)
+ @test partials(u[2], 1) ≈ -0.5 * 3.0 / sqrt(2.0) rtol = 1e-6
+ @test partials(u[2], 2) ≈ 3.0 / sqrt(2.0) rtol = 1e-6
+
+ # a condition that is not met leaves its unknown fixed
+ G2 = u -> [u[1]^2 - a, 1.0 + 0.0 * u[2] + 0.0 * b]
+ u = IMAS.implicit_solution(G2, [sqrt(2.0), 7.0], D2; atol=1e-2)
+ @test partials(u[1], 1) ≈ 0.5 * sqrt(2.0) rtol = 1e-6
+ @test all(iszero, partials(u[2]))
+
+ # minimum of (x1 - a)^2 + (x2 - a*b)^2 + x1*x2*0
+ cost = x -> (x[1] - a)^2 + (x[2] - a * b)^2
+ x = IMAS.implicit_argmin(cost, [2.0, 6.0], D2)
+ @test partials(x[1], 1) ≈ 2.0
+ @test partials(x[1], 2) ≈ 0.0 atol = 1e-12
+ @test partials(x[2], 1) ≈ 6.0
+ @test partials(x[2], 2) ≈ 6.0
+
+ # switched off: values only
+ x = Base.ScopedValues.with(IMAS.IMPLICIT_DERIVATIVES => false) do
+ IMAS.implicit_argmin(cost, [2.0, 6.0], D2)
+ end
+ @test all(iszero, partials(x[1])) && value(x[1]) == 2.0
+
+ # finite derivative parts where the plain function has an infinite derivative
+ @test all(isfinite, partials(IMAS.sqrt0(0.0 * IMAS.seed(D2, 1))))
+ @test all(isfinite, partials(IMAS._chebyshev_T(3, D2(1.0))))
+
+ # a time basis that starts at -Inf: the smoothed power and its derivative with respect to the time constant
+ time = [-Inf, 0.0, 1.0, 2.0]
+ power = [0.0, 1.0, 3.0, 2.0]
+ smooth(tau) = IMAS.smooth_beam_power(time, power, 2.0, tau)
+ p = smooth(0.7 * IMAS.seed(D2, 1))
+ @test value(p) == smooth(0.7)
+ @test partials(p, 1) ≈ 0.7 * (smooth(0.7 + 1e-6) - smooth(0.7 - 1e-6)) / 2e-6 rtol = 1e-6
+end
+
+@testset "pedestal blending with duals" begin
+ rho = collect(range(0.0, 1.0, 101))
+ profile(s) = s .* (200.0 .+ 2800.0 .* (1.0 .- rho .^ 2) .^ 1.5)
+ tb, ts = IMAS.pedestal_search_tolerance.brent[], IMAS.pedestal_search_tolerance.simplex[]
+ IMAS.pedestal_search_tolerance.brent[] = 1e-12
+ IMAS.pedestal_search_tolerance.simplex[] = 1e-14
+ try
+ # H-mode blend: derivatives with respect to the pedestal height and to a scale of the profile
+ blend(ped, s) = IMAS.blend_core_edge_Hmode(profile(s), rho .* one(ped), ped, 0.06 * one(ped), 0.775, 0.8)
+ ad = blend(600.0 + (IMAS.seed(D2, 1) - 1), IMAS.seed(D2, 2))
+ @test value.(ad) ≈ blend(600.0, 1.0) rtol = 1e-10
+ fd1 = central(h -> blend(600.0 + h, 1.0), 0.1) # a step well above the noise of the simplex search
+ fd2 = central(h -> blend(600.0, 1.0 + h), 1e-4)
+ @test partials.(ad, 1) ≈ fd1 rtol = 2e-2
+ @test partials.(ad, 2) ≈ fd2 rtol = 2e-2
+
+ # L-mode blend
+ lblend(ped, s) = IMAS.blend_core_edge_Lmode(profile(s), rho .* one(ped), ped, 0.9)
+ ad = lblend(300.0 + (IMAS.seed(D2, 1) - 1), IMAS.seed(D2, 2))
+ @test value.(ad) ≈ lblend(300.0, 1.0) rtol = 1e-10
+ @test partials.(ad, 1) ≈ central(h -> lblend(300.0 + h, 1.0), 1e-3) rtol = 2e-2 atol = 1e-6
+ @test partials.(ad, 2) ≈ central(h -> lblend(300.0, 1.0 + h), 1e-5) rtol = 2e-2 atol = 1e-3
+ finally
+ IMAS.pedestal_search_tolerance.brent[] = tb
+ IMAS.pedestal_search_tolerance.simplex[] = ts
+ end
+end
+
+@testset "flux surfaces with duals" begin
+ filename = joinpath(dirname(dirname(pathof(IMAS.IMASdd))), "sample", "D3D_eq_ods.json")
+ dd0 = IMAS.json2imas(filename; show_warnings=false)
+ fw = IMAS.first_wall(dd0.wall)
+
+ # perturbations: (1) toroidal field scale, (2) a change of shape of ψ(R,Z)
+ function perturb!(dd, s)
+ eqt = dd.equilibrium.time_slice[]
+ e1 = eqt.profiles_1d
+ e2 = eqt.profiles_2d[1]
+ R = Float64[IMAS.force_float64(x) for x in e2.grid.dim1]
+ Z = Float64[IMAS.force_float64(x) for x in e2.grid.dim2]
+ bump = [((r - 1.7) / 0.6)^2 - 0.5 * (z / 0.6)^2 for r in R, z in Z]
+ dpsi = IMAS.force_float64(e1.psi[end] - e1.psi[1])
+ e2.psi = e2.psi .+ (s[2] - 1) .* dpsi .* bump
+ e1.f_df_dpsi = e1.f_df_dpsi .* s[1]^2
+ e1.f = e1.f .* s[1]
+ eqt.global_quantities.vacuum_toroidal_field.b0 = eqt.global_quantities.vacuum_toroidal_field.b0 * s[1]
+ return dd
+ end
+ function outputs(dd)
+ eqt = dd.equilibrium.time_slice[]
+ e1 = eqt.profiles_1d
+ n = length(e1.psi)
+ idx = [5, n ÷ 3, n ÷ 2, 3n ÷ 4, n - 3]
+ g = eqt.global_quantities
+ return vcat(e1.q[idx], e1.volume[idx], e1.gm1[idx], e1.gm9[idx], e1.elongation[idx], e1.r_outboard[idx], e1.rho_tor[idx], e1.psi[idx],
+ [g.magnetic_axis.r, g.magnetic_axis.z, g.ip, g.beta_normal, eqt.boundary.psi])
+ end
+ function run(s)
+ dd = s isa Vector{Float64} ? deepcopy(dd0) : IMAS.retype(D2, dd0)
+ perturb!(dd, s)
+ w = IMAS.first_wall(dd.wall)
+ IMAS.flux_surfaces(dd.equilibrium.time_slice[], w.r, w.z)
+ return outputs(dd)
+ end
+
+ y0 = run([1.0, 1.0])
+ yd = run([IMAS.seed(D2, 1), IMAS.seed(D2, 2)])
+ @test value.(yd) ≈ y0 rtol = 1e-6
+
+ # The last closed surface is found by a search on the contouring grid, which makes every output a
+ # piecewise function of ψ(R,Z) with small jumps. The finite-difference slope is therefore a fit over
+ # several steps that span many pieces, not a two-point difference inside one of them.
+ function slope(k, H)
+ hs = H .* vcat(-4:-1, 1:4) ./ 4
+ e = zeros(2)
+ e[k] = 1.0
+ Y = [run([1.0, 1.0] .+ h .* e) for h in hs]
+ return [sum(hs[j] * (Y[j][i] - y0[i]) for j in eachindex(hs)) / sum(abs2, hs) for i in eachindex(y0)]
+ end
+ for (k, H) in ((1, 1e-4), (2, 2e-2))
+ fd = slope(k, H)
+ ad = partials.(yd, k)
+ rel = abs.(ad .- fd) ./ max.(abs.(ad), abs.(fd), abs.(y0)) # error per unit change of the input, relative to the output
+ @test count(<(0.02), rel) >= 0.95 * length(rel)
+ @test sort(rel)[end÷2] < 5e-3
+ @test maximum(rel) < 0.1
+ end
+end
diff --git a/test/runtests_profiles.jl b/test/runtests_profiles.jl
new file mode 100644
index 00000000..93d8c3cf
--- /dev/null
+++ b/test/runtests_profiles.jl
@@ -0,0 +1,38 @@
+using IMAS
+using Test
+
+@testset "ion thermal pressure" begin
+ dd = IMAS.dd()
+ resize!(dd.core_profiles.profiles_1d, 1)
+ cp1d = dd.core_profiles.profiles_1d[1]
+ cp1d.time = 0.0
+ dd.global_time = 0.0
+ rho = collect(range(0.0, 1.0, 11))
+ cp1d.grid.rho_tor_norm = rho
+ T = 1000.0 .* (1.0 .- 0.5 .* rho)
+ n = 1E19 .* (1.0 .- 0.5 .* rho .^ 2)
+ cp1d.electrons.temperature = T
+ cp1d.electrons.density_thermal = 4.0 .* n
+ resize!(cp1d.ion, 4)
+ for ion in cp1d.ion
+ ion.temperature = T
+ end
+ # 1: total density stored, thermal density derived from it (state left by quasi-neutrality on an ion without fast density)
+ cp1d.ion[1].density = 2.0 .* n
+ # 2: thermal density stored
+ cp1d.ion[2].density_thermal = 0.1 .* n
+ # 3: total and fast densities stored, thermal density is their difference
+ cp1d.ion[3].density = 1.0 .* n
+ cp1d.ion[3].density_fast = 0.25 .* n
+ # 4: only a fast density: no thermal pressure
+ cp1d.ion[4].density_fast = 0.5 .* n
+
+ @test !IMAS.hasdata(cp1d.ion[1], :density_thermal)
+ @test cp1d.ion[1].density_thermal == 2.0 .* n
+ expected = IMAS.mks.e .* T .* n .* (2.0 + 0.1 + 0.75)
+ @test IMAS.pressure_thermal(cp1d.ion) ≈ expected
+ @test cp1d.pressure_ion_total ≈ expected
+ @test cp1d.pressure_thermal ≈ expected .+ IMAS.mks.e .* T .* 4.0 .* n
+ # the sum over ions equals the sum of the per-ion pressures
+ @test IMAS.pressure_thermal(cp1d.ion) ≈ sum(IMAS.pressure_thermal(ion) for ion in cp1d.ion[1:3])
+end