Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
7d00d0f
dual-typed data dictionaries: conversion, seeding, value/partials spl…
tomneiser Nov 10, 2026
a53a3a4
dual numbers: zero-safe sqrt for on-axis quantities, closed-form stea…
tomneiser Nov 10, 2026
90b16f2
pedestal blending with dual numbers: implicit derivatives of the sear…
tomneiser Nov 10, 2026
742caf2
flux surfaces of an equilibrium that carries derivatives
tomneiser Nov 10, 2026
a9460b7
axis search and boundary bisection with dual numbers; shared boundary…
tomneiser Nov 10, 2026
e148f57
dual numbers: contouring tolerances in the element type, integer trun…
tomneiser Nov 10, 2026
3bd60ef
level of the last closed surface: derivative of the node value or cel…
tomneiser Nov 10, 2026
7b99e1f
dual numbers through source helpers: scoped switch for implicit deriv…
tomneiser Nov 10, 2026
ac704a5
pedestal blend derivative taken at a tightly converged minimum; impli…
tomneiser Nov 10, 2026
80fbb3d
tests: dual-typed dd helpers, implicit derivatives, pedestal blends a…
tomneiser Nov 10, 2026
261e609
convert to a dual element type: signature that resolves the ambiguity…
tomneiser Nov 10, 2026
a9ccc67
flux surfaces with duals: the last closed surface follows the flux at…
tomneiser Nov 10, 2026
d24bb14
beam power smoothing: finite derivative for an infinite time step
tomneiser Nov 10, 2026
74baba1
Thermal pressure summed over ions: include ions whose thermal density…
tomneiser Nov 10, 2026
bc5ca9b
Merge master into forward-ad-plasma
tomneiser Nov 13, 2026
3320e74
Require IMASdd 8.6.4
tomneiser Nov 14, 2026
ad18132
Merge branch 'master' into forward-ad-plasma
tomneiser Nov 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions src/IMAS.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
378 changes: 378 additions & 0 deletions src/dual.jl

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions src/expressions/onetime.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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"] =
Expand All @@ -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"] =
Expand All @@ -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


Expand Down
9 changes: 9 additions & 0 deletions src/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
1 change: 1 addition & 0 deletions src/physics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down
12 changes: 6 additions & 6 deletions src/physics/boundary.jl
Original file line number Diff line number Diff line change
Expand Up @@ -357,15 +357,15 @@ 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]
dz = pz[i] - pz[i-1]
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]
Expand All @@ -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]
Expand All @@ -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]
Expand All @@ -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]
Expand All @@ -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]
Expand Down
7 changes: 7 additions & 0 deletions src/physics/build.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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}

Expand Down
14 changes: 12 additions & 2 deletions src/physics/currents.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions src/physics/equilibrium.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 15 additions & 5 deletions src/physics/fast.jl
Original file line number Diff line number Diff line change
Expand Up @@ -494,22 +494,22 @@ 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]
for i in 2:n
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)
Expand All @@ -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]
Expand All @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions src/physics/fields.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
52 changes: 34 additions & 18 deletions src/physics/fluxsurfaces.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
Loading
Loading