How a thermodynamic state evaluation flows through the legacy mutable Gas/Gas1D path on public main versus the pure, immutable FrozenGas core on cleanup_arch — with measured per-call cost at every step.
| Scenario | legacy Gas{N} | legacy Gas1D | FrozenGas core | speedup* |
|---|---|---|---|---|
| Set T, read cp + h + ϕ (cycle-deck inner pattern) | 71.9 ns | 69.8 ns | 9.0 ns | 7.8× |
| Set T, read cp only (1000-point sweep) | 75.3 ns | 66.5 ns | 0.83 ns† | 80׆ |
| Enthalpy inversion (set_h! vs T_of_h) | 249.2 ns | 224.2 ns | 135.6 ns | 1.7× |
| Isentropic compression, PR = 12 | 709 ns (49 allocs) | 625 ns (49 allocs) | 146.3 ns (0 allocs) | 4.3× |
| dh/dT under ForwardDiff, 12 partials | MethodError | MethodError | 11.3 ns | ∞ / 2.8ׇ |
| T_of_h under ForwardDiff, 8 partials | MethodError | MethodError | 131.9 ns | ∞ / 2.1ׇ |
* vs the faster legacy column.
† the pure cp(gas,T) compiles to SIMD-vectorizable code across the sweep — exactly what the mutable write-back forbids; a single isolated call measures ~2.7 ns (~25×).
‡ ∞ because the legacy path throws MethodError under Dual numbers (measured: legacy_forwarddiff_supported = false); the finite factor compares the extension's analytic rule against generic Dual arithmetic through the same pure code.
Source data: benchmark/arch_comparison/benchdata.json, generated by benchmark/arch_comparison/bench_compare.jl. Each value is BenchmarkTools minimum over a shuffled sweep (1000 T ∈ [250, 2200] K or 200 inversion targets), total time ÷ calls.
Mutable mixture gas. Setting T re-sums NASA polynomials over every nonzero species, every time. Properties are cached fields, valid only for the last T/P written.
P::Float64 # [Pa]
T::Float64 # [K]
Tarray::MVector{8, Float64} # Temperature array to make calcs allocation free
cp::Float64 #[J/mol/K]
cp_T::Float64 # derivative dcp/dT
h::Float64 #[J/mol]
ϕ::Float64 #[J/mol/K] Entropy complement fn ϕ(T) = ∫ cp(T)/T dT from Tref to T
Y::MVector{N, Float64} # Mass fraction of species
MW::Float64 # Molecular weight [g/mol]
Source: src/Gas.jl:L8-L20 (main)
Mutable single-pseudo-species gas: the fast legacy path. Avoids the species sum by evaluating the composite's equivalent polynomial, but keeps the mutable cache architecture and the Float64 pins.
comp_sp::composite_species
P::Float64 # [Pa]
T::Float64 # [K]
Tarray::MVector{8, Float64} # Temperature array to make calcs allocation free
cp::Float64 #[J/kg/K]
cp_T::Float64 # derivative dcp/dT
h::Float64 #[J/kg]
ϕ::Float64 #[J/kg/K] Entropy complement fn ϕ(T) = ∫ cp(T)/T dT from Tref to T
Source: src/Gas1D.jl:L6-L18 (main)
The package's core idea on both branches: a fixed-composition mixture collapsed to one equivalent NASA-9 coefficient set at construction (entropy of mixing folded into the integration constant). FrozenGas is its isbits, mass-scaled successor for the hot path.
name::String
Tmid::Float64
alow::Array{Float64,1}
ahigh::Array{Float64,1}
MW::Float64
Hf::Float64
composition::Dict{String, Float64}
Source: src/species.jl:L23-L31 (main)
Immutable isbits frozen-composition gas. Coefficients are mass-scaled at construction (premultiplied by 1000/MW) so property polynomials evaluate directly in J/kg-based SI with no per-call division or species summation. All property functions are pure in (gas, T), generic over Real, zero-allocation, thread-safe by construction.
alow::SVector{9,Float64} # mass-scaled coefficients, T < Tmid (1000 K)
ahigh::SVector{9,Float64} # mass-scaled coefficients, T ≥ Tmid
MW::Float64 # molecular weight [g/mol]
R::Float64 # specific gas constant [J/kg/K]
Hf::Float64 # formation enthalpy at 298.15 K [J/mol]
FrozenGas(sp::AbstractSpecies) FrozenGas(X::AbstractVector, name::AbstractString = "frozen gas")
cp(gas, T) h(gas, T) s0(gas, T) props(gas, T) R(gas) gamma(gas, T) T_of_h(gas, hspec; Tguess) T_isentropic(gas, T1, PR; ηp) pressure_ratio(gas, T1, T2)
gas.T = val
▶
Every property evaluation begins as an assignment. The interface is Base.setproperty! — pinned to val::Float64, which is what makes Dual numbers a MethodError on this path.
L138function Base.setproperty!(gas::Gas, sym::Symbol, val::Float64) L139 ## Setting Temperature L140 if sym === :T
Source: src/Gas.jl:L138-L140 (main)
The assignment triggers four hidden writes. First the temperature-power cache Tarray is rebuilt in place; then the polynomial sum runs over every nonzero species via views into the global spdict, and four cached fields are overwritten — including cp_T, computed whether or not anyone reads it.
L141 setfield!(gas, :T, val) # first set T L142 setfield!(gas, :Tarray, Tarray!(val, getfield(gas, :Tarray))) # update Tarray L147 if val<1000.0 #Value given is the desired temperature L148 A = view(spdict.alow, :) L162 @inbounds for (Yᵢ,a, m) in zip(Y, A, MW) L163 if Yᵢ != 0.0 L164 cptemp = cptemp + Yᵢ * Cp(TT, a) /m L165 htemp = htemp + Yᵢ * h(TT, a) /m L166 ϕtemp = ϕtemp + Yᵢ * 𝜙(TT, a) /m L167 cp_Ttemp = cp_Ttemp + Yᵢ * dCpdT(TT, a) /m L171 setfield!(gas, :cp, cptemp*1000.0) L172 setfield!(gas, :h, htemp*1000.0) L173 setfield!(gas, :ϕ, ϕtemp*1000.0) L174 setfield!(gas, :cp_T, cp_Ttemp*1000.0)
spdict.alow spdict.ahigh spdict.MW (global database, on the hot path) · gas.Y
Writesgas.T gas.Tarray gas.cp gas.h gas.ϕ gas.cp_T
Measured: 71.9 ns per update + all-property read (scoreboard row 1). The cached read itself is nearly free (g.cp ≈ 0.7 ns) — the cost lives in this cascade.
Source: src/Gas.jl:L138-L174 (main)
Gas1D replaces the species sum with one equivalent-polynomial evaluation of its composite_species — the right idea, still inside the mutable cache architecture: heap-Vector coefficients behind views, an MVector write-back, and the always-computed cp_T. Measured, it buys almost nothing over Gas{N} for dry air (69.8 vs 71.9 ns).
L55 setfield!(gas, :T, val) # first set T L56 setfield!(gas, :Tarray, Tarray!(val, getfield(gas, :Tarray))) # update Tarray L62 if val<1000.0 #Value given is the desired temperature L63 A = view(sp.alow, :) L71 setfield!(gas, :cp, Cp(TT,A)/MW) L72 setfield!(gas, :h, h(TT, A)/MW) L73 setfield!(gas, :ϕ, 𝜙(TT, A)/MW) L74 setfield!(gas, :cp_T, dCpdT(TT, A)/MW)
gas.comp_sp.alow/.ahigh (heap Vectors via view)
Writesgas.T gas.Tarray gas.cp gas.h gas.ϕ gas.cp_T
Source: src/Gas1D.jl:L52-L89 (main)
The residual reads the cached gas.h and gas.cp — values only valid because the previous iteration's mutation refreshed them.
L307 res = gas.h - hspec # Residual L308 res_t = gas.cp # ∂R/∂T = ∂h/∂T = cp L309 dT = -res/res_t # Newton step
Source: src/Gas.jl:L302-L325 (main)
gas.T = T — full cascade re-runs every iteration
▶
Each Newton iteration pays the entire ≈72 ns cascade above — species sum, ϕ it doesn't need until convergence, cp_T it never needs. This is why the architecture, not the algorithm, sets the price: the new core runs the same Newton iteration at 135.6 ns total.
L315 T = T + dT L316 gas.T = T
gas.T → cascade → gas.Tarray gas.cp gas.h gas.ϕ gas.cp_T
Source: src/Gas.jl:L315-L316 (main)
if abs(dT) ≤ ϵ ?break; the gas object now is the answer (T readable as gas.T).
No → mutate gas.T again and repeat. After the loop, if abs(dT) > ϵ raises an error (src/Gas.jl:L319-L322, main).
Note this function is not on public main at all — turbo.jl was added on this branch; main has no isentropic compression capability. It is shown here as the best available representative of the legacy architecture doing turbomachinery work, and it is what the legacy columns of the scoreboard measure. The 49 allocations per call come from getproperty conveniences on the hot path (e.g. gas.R for Gas{N} computes mole fractions through allocating broadcasts).
L22 for i = 1:20# abs(dT)>ϵ L23 res = (gas.ϕ - ϕ0) / R - logPR_ηp L24 res_dT = gas.ϕ_T / R L25 dT = -res / res_dT L31 Tfinal = Tfinal + dT L32 gas.T = Tfinal
if abs(dT) ≤ ϵ ?P0*PR before the loop.
No → gas.T = Tfinal re-runs the full cascade; repeat.
All database lookups and unit conversions happen here, once. The molar→mass scale factor is folded into the coefficients themselves, so no property call ever divides by MW or touches the global spdict.
L33function FrozenGas(sp::AbstractSpecies) L34 scale = 1000.0 / sp.MW # molar (J/mol) → mass-specific (J/kg) L35 FrozenGas( L36 SVector{9,Float64}(sp.alow) * scale, L37 SVector{9,Float64}(sp.ahigh) * scale, L38 sp.MW, L39 Runiv / sp.MW * 1000.0, L40 sp.Hf, L41 ) L42end
props(gas, T) — shared powers, one log, no state
::FrozenGas
9.0 ns/call
▶
All three temperature-dependent properties in one pure call. The Horner-form kernels share the coefficient lookup and the single log(T) — the benefit the mutable Tarray cache was reaching for, with no mutation. Generic over Real, zero allocations (tested), thread-safe by construction. Individual cp/h/s0 use the same kernels, so the two paths are bit-identical.
L64@inline coeffs(gas::FrozenGas, T) = T < 1000.0 ? gas.alow : gas.ahigh L114@inline function props(gas::FrozenGas, T) L115 a = coeffs(gas, T) L116 lnT = log(T) L117 ( L118 cp = Runiv * poly_cp_R(a, T), L119 h = Runiv * poly_h_R(a, T, lnT), L120 s0 = Runiv * poly_s0_R(a, T, lnT), L121 ) L122end
gas.alow / gas.ahigh (stack-resident SVectors)
Writesnothing — returns a NamedTuple
Measured: 9.0 ns for all three properties (vs ≈70 ns legacy update); a lone cp(gas,T) call is ~2.7 ns and SIMD-vectorizes across sweeps to 0.83 ns amortized.
Identical mathematics to legacy set_h! (dh/dT = cp), but the iterate is a local; each iteration calls the pure h and cp instead of re-running a state cascade that also computes ϕ and cp_T it doesn't need.
L150function T_of_h(gas::FrozenGas, hspec; Tguess = 500.0) L151 T = one(hspec / oneunit(hspec)) * Tguess # promote to eltype of hspec L152 for _ = 1:NEWTON_MAXITER L153 dT = (hspec - h(gas, T)) / cp(gas, T) L154 T += dT
if abs(dT) ≤ NEWTON_RTOL * abs(T) ?return T (a value — the caller's gas object is untouched).
No → next local iteration. Falling out of the loop raises an error (frozengas.jl:L159).
Solves the same isentrope relation as legacy PressureRatio, as a pure function of (gas, T1, PR). The constant-γ closed form seeds Newton so close that typical solves converge in a few iterations.
L182function T_isentropic(gas::FrozenGas, T1, PR; ηp = 1.0) L183 target = s0(gas, T1) + gas.R * log(PR) / ηp L184 T = T1 * PR^(gas.R / cp(gas, T1) / ηp) # constant-γ initial guess L185 for _ = 1:NEWTON_MAXITER L186 dT = (target - s0(gas, T)) * T / cp(gas, T) # ds0/dT = cp/T L187 T += dT
Source: src/frozengas.jl:L182-L192 (cleanup_arch) | pressure_ratio: L169-L170
if abs(dT) ≤ NEWTON_RTOL * abs(T) ?return T. No → next local iteration; error after 30 (frozengas.jl:L192).
ForwardDiff.derivative(t -> (g.T = t; g.h), 600.0) ?MethodError — measured in the benchmark harness as legacy_forwarddiff_supported = false. Two structural blocks: the setter pin val::Float64 (src/Gas.jl:L138, main) rejects Dual, and the cache field Tarray::MVector{8, Float64} (src/Gas1D.jl:L10, main) cannot hold one. On the pure core, generic-over-Real code accepts Duals as-is; the extension below makes them fast.
ForwardDiff replaces a plain number $T$ with a dual number — a value carrying a tangent — built on a nilpotent $\varepsilon$:
Every arithmetic primitive is overloaded to propagate the tangent exactly (no truncation error, unlike finite differences). Because $\varepsilon^2$ vanishes, each overload is a differentiation rule in disguise — and composing them yields the chain rule mechanically:
In a cycle solver the tangent is a vector: the Newton solver seeds $\partial T = \nabla_{\!x} T \in \mathbb{R}^N$, the sensitivity of this temperature to all $N$ solver unknowns ($N \approx 8$–$12$ in a PowerCycles-style residual program). Then $h(\tilde T)$ automatically emerges carrying $\nabla_{\!x} h = c_p(T)\,\nabla_{\!x} T$ — a full Jacobian row block per call.
The cost model behind the scoreboard. The NASA-9 enthalpy evaluation costs roughly $K \approx 25$ scalar primitives (Horner chain, one divide, one $\ln$). Generic Dual arithmetic makes every one of them also do $N$ tangent operations; the analytic rule collapses all of that into two plain-Float64 evaluations and a single $N$-wide scaling:
Measured exactly so (scoreboard harness, dh/dT per call): generic Dual grows 11.5 ns → 26.0 ns → 31.4 ns as $N$ goes $1 \to 8 \to 12$; the analytic rule stays flat at 10.9–11.3 ns, because the only $N$-dependent work left is one multiply of the partials vector.
Measured data: benchmark/arch_comparison/benchdata.json (rows "dh/dT, N partials")
The ForwardDiff package extension (a weakdep — the base package stays AD-free) replaces Dual arithmetic through the polynomials with closed forms: one Float64 evaluation of the value, one of the derivative, one N-wide multiply. Measured at 12 partials: 11.3 ns vs 31.4 ns generic Dual (2.8×) — and within 1.6× of the plain Float64 call.
L28h(gas::FrozenGas, d::Dual{Tag}) where {Tag} = L29 Dual{Tag}(h(gas, value(d)), cp(gas, value(d)) * partials(d)) L31s0(gas::FrozenGas, d::Dual{Tag}) where {Tag} = L32 Dual{Tag}(s0(gas, value(d)), cp(gas, value(d)) / value(d) * partials(d))
Worked example — dry air at 600 K, two solver unknowns. Suppose the solver's current iterate makes this temperature depend on two unknowns $x_1, x_2$ with sensitivities $\partial T/\partial x_1 = 1.0$ and $\partial T/\partial x_2 = 0.5$, so the seeded input is
The rule needs exactly two plain evaluations (all values below computed with this package; reproduce with the snippet in the provenance note):
and one tangent scaling — the entire derivative computation is the last line:
ForwardDiff through the extension returns exactly value = 304461.1954092776, partials = (1050.9992733427, 525.4996366714) — i.e. $\partial h/\partial x_1 = c_p$ and $\partial h/\partial x_2 = c_p/2$, the chain rule done once at the seam. The entropy-complement rule works identically with the closed form $\mathrm{d}s_0/\mathrm{d}T = c_p/T$:
measured back from ForwardDiff as partials = (1.7516654556, 0.8758327278) with $c_p(600)/600 = 1.7516654556$ — agreement to the last printed digit, because the rule is the analytic derivative, not an approximation of it.
Source: ext/IdealGasThermoForwardDiffExt.jl:L19-L43 (cleanup_arch)
Differentiating a Newton loop drags Duals through every iteration (measured 282 ns at 8 partials). The implicit function theorem says you never have to: the converged solution defines $T(h_\text{spec})$ implicitly through the residual $F(T, h_\text{spec}) = h(T) - h_\text{spec} = 0$, so differentiating the equation (not the algorithm) gives the exact sensitivity:
The rule therefore solves the primal in plain Float64 and attaches the partials in one division at the converged $T^\star$:
L50function T_of_h(gas::FrozenGas, hd::Dual{Tag}; Tguess = 500.0) where {Tag} L51 T = T_of_h(gas, value(hd); Tguess = Tguess) L52 Dual{Tag}(T, partials(hd) / cp(gas, T))
Measured: 131.9 ns at 8 partials — 2.1× faster than Duals-through-the-loop, only ~1.1× above the underived 121 ns solve.
Worked example — invert dry-air enthalpy back to 1200 K. Take the target $h_\text{spec} = h(1200) = 975{,}268.911\ \mathrm{J/kg}$ and seed it with a unit tangent, $\tilde h = h_\text{spec} + \varepsilon \cdot 1$. Step 1: the primal Newton solve runs in pure Float64 from Tguess = 500 (trace reproduced by running the loop at frozengas.jl L152–L156 with printing — note the quadratic convergence, the digits of accuracy roughly doubling each step):
it1dT = +7.5257394966e+02 → T = 1252.5739496582 it2dT = -5.2411201933e+01 → T = 1200.1627477252 it3dT = -1.6274608153e-01 → T = 1200.0000016437 it4dT = -1.6436749141e-06 → T = 1200.0000000000 it5dT = -1.9821747642e-13 → T = 1200.0000000000 (abs(dT) ≤ 1e-12·T → return)
Step 2: one extra evaluation at the solution, $c_p(1200) = 1174.6222\ \mathrm{J/(kg\,K)}$, and the partial is a single division:
Sanity-checked three ways with this package: the IFT rule returns 8.5133757872e-4; a central finite difference $\big(T(h\!+\!1) - T(h\!-\!1)\big)/2$ gives 8.5133757864e-4 (agreeing to 9 digits — the residual difference is the FD truncation error, not ours); and the physical reading is sensible: raising the target enthalpy by 1 kJ/kg raises the answer by $\approx 0.85$ K, the reciprocal of the local heat capacity. Note what the loop trace didn't contribute: none of the five iterations carried a tangent. Differentiating the loop would have paid Dual arithmetic in all five — and converged to the same number, because Newton's converged result depends only on the equation, not the path.
The isentrope, with two seeded inputs. T_isentropic defines $T_2$ implicitly through $G(T_2, T_1, \mathrm{PR}) = s_0(T_2) - s_0(T_1) - \tfrac{R}{\eta_p}\ln(\mathrm{PR}) = 0$. Total differential, using $\mathrm{d}s_0/\mathrm{d}T = c_p/T$:
Hand calculation at the scoreboard's compression point ($T_1 = 288.15$ K, $\mathrm{PR} = 12$, $\eta_p = 1$), where the primal solve gives $T_2 = 580.5592$ K, $c_p(T_1) = 1004.278$, $c_p(T_2) = 1046.545$, $R = 287.052$:
ForwardDiff through the extension returns dT2/dPR = 13.2699242259 — matching the hand calculation exactly. (Physical reading: one more unit of pressure ratio buys ≈13.3 K of compressor exit temperature at this point; inlet sensitivity is amplified ≈1.93× across the isentrope.) The three Dual methods at ext L57–L74 implement exactly these formulas for $T_1$ seeded, $\mathrm{PR}$ seeded, or both — in the both-seeded case the two tangent contributions simply add, as the total differential says they must.
L69function T_isentropic(gas::FrozenGas, T1::Dual{Tag}, PR::Dual{Tag}; ηp = 1.0) where {Tag} L70 T2 = T_isentropic(gas, value(T1), value(PR); ηp = ηp) L71 ∂ = cp(gas, value(T1)) / value(T1) * partials(T1) + L72 gas.R / (ηp * value(PR)) * partials(PR) L73 Dual{Tag}(T2, T2 / cp(gas, T2) * ∂)
Source: ext/IdealGasThermoForwardDiffExt.jl:L50-L74 (cleanup_arch)
The new interface is guarded by behavioral tests, not implementation tests — they survive any internal refactor:
Gas1D to rtol 1e-10 across 250–2200 K (cp, h, ϕ)@allocated == 0 after warmup for every property function and inversionBase.get_extension(...) !== nothing) — not just generic fallbacked344f8dede22d4d96430f814b2a9951eb6282d0; new-core nodes pinned to cleanup_arch @ 6ca8deab3914533bfce89c881d10556429158cbc. Links into 6ca8dea resolve once the branch is pushed to the remote. KaTeX is loaded from CDN; everything else is self-contained.