Repository navigation
New Features
- Adds
desc.external.agni.AgniStability, the squared growth rate of the most unstable finite-n ideal MHD mode computed by the external AGNI solver (pip install agnimhd), with its gradient for optimization. - Added warning for when
deriv_mode="batched"is used in anObjectiveFunctionwhere one or more sub-objectives is usingrevmode differentiation. Also adds more info about the derivative mode and Jacobian chunk sizes when building the objective withverbose>1. - Adds
scale_invariantargument to quasi-symmetry objectives (i.e.QuasisymmetryTwoTerm,QuasisymmetryTripleProductandQuasisymmetryBoozer) that introduces the normalized alternatives for the objective functions with the actual evaluated local magnetic field information instead of the precomputed constant normalization. Similarly, the definition off_Candf_Tofplot_qs_erroris changed, the flux surface average is now take over the normalized quantity whereas previously the flux surface average was applied to each term separately before normalization. For more details on these quantities, see Basic Optimization tutorial. - Adds
NeutronWallLoadingobjective to compute the neutron wall loading (MW/m²) on a chosen/optimized surface. - Adds Python type hints for many API functions. Allows for better autocomplete and error checking when writing DESC scripts in common IDEs.
Performance Improvements
- Avoids numerous small JAX compilations when building and solving an equilibrium at a new resolution, by doing index and mode bookkeeping in
Grid,Optimizable.x_idxandcompute_scaling_factorswith NumPy instead of eager JAX operations. - Reduces memory use of Boozer harmonic projections and their derivatives by contracting the poloidal and toroidal Fourier factors separately.
- Improves memory management to reduce the base memory used during optimization while using
lsq-exact,lsq-auglagandfmin-auglagoptimizers. - Sparse reverse-mode differentiation was introduced to yield significant performance improvements #2170
- Speeds up
field_line_integrateandtrace_particlesfor filamentary coils (Coil,CoilSet,MixedCoilSet) by precomputing the constant source information, so that the ODE right-hand side only evaluates a single fused Biot-Savart kernel instead of recomputing the coil geometry at every solver step. - Improves the non-singular Biot-Savart kernel which should give a speed/memory improvement to objectives that compute magnetic field from coils such as
QuadraticFlux. ideal ballooning lambdanow computes only the requestedNeigvalslargest eigenpairs of each tridiagonal ballooning matrix (bisection + twisted factorization) instead of a denseeighof every matrix. Memory of the eigensolve drops from O(N²) to O(N) per field line (peak GPU memory of the ballooning tutorial's evaluation: 14.5 GB -> 0.16 GB); results are unchanged and run times are about the same (the eigensolve is a small part of the total).- More efficient
ProximalProjectionjacobians if theForceBalanceconstraint uses a smalljac_chunk_sizeand if there are many non-equilibrium degrees of freedom (i.e. single stage optimization). - Additional memory reductions for
LinearConstraintProjectionbase memory usage. - Reduces the compilation time of custom
qr_multiplyalgorithm. - Removes a temporary copy of the full output in chunked computations (e.g. Jacobians with
jac_chunk_size) when the chunk size does not evenly divide the batched dimension. lsq-exact(andproximal-lsq-exact) stops when a rejected step is already smaller thanxtolinstead of shrinking the trust region until a step of negligible size is accepted. This saves many function evaluations at the end of an optimization when the objective is only evaluated approximately, as withProximalProjection.field_line_integrateno longer recompiles its ODE solver on every call: repeated calls with the same inputs reuse the compiled solver.- Stores the surface labels
rhoandzetaas floats, so that surfaces labelled with an int or a float share compiled code.
Important
Recent jax versions (particularly after 0.10.0) can negatively impact DESC optimization performance. While the improvements in this release should result in a net speedup and memory reduction, we recommend benchmarking your workload across different jax versions rather than defaulting to the latest release. To mitigate known slowdowns, DESC now sets the following XLA flags by default:
--xla_cpu_experimental_ynn_fusion_type=-reduce--xla_gpu_enable_triton_gemm=false
User-defined values for these flags will be respected and will not be overridden by DESC.
Breaking Changes and Deprecations
- The parameter
num_transitinEffectiveRipple,Gamma_c,Bounce2Dand related functions has been changed tofield_period_transits. This should make using a consistent resolution across different equilibria easier. The now-deprecatednum_transitmay still be used but note the equivalencefield_period_transits = num_transit * grid.NFP. - The parameter
Y_BinEffectiveRipple,Gamma_c,Bounce2Dis now the resolution over a single field period rather than a full toroidal transit. This should make using a consistent resolution across different equilibria easier. - Objectives using
Bounce2Dnow do not support forward ("fwd") mode differentiation for JAX versions <0.11.0. desc.utils.rotation_matrixutility function now accepts either an axis and an angle as arguments (previous behavior), OR a vector and a vector. In the latter case, the rotation matrix returned will rotate the first vector onto the second, using quaternions which avoids the NaN gradient issue that the axis-angle form can have at vertical normals. Note that these are positional arguments, and the kwargsaxisandangleare now deprecated.- Public modules now define
__all__matching the API documentation, which makes the public API explicit for IDEs, type checkers and other tools. Note thatfrom desc.<module> import *now only imports the documented public names.
Bug Fixes
- Fixes 2nd and 3rd order terms of
perturb(and so ofEquilibrium.perturb,solve_continuationandProximalProjection) being evaluated along a tangent that included the full value of any fixed parameter of magnitude above 100 (eg pressure, density, temperature or current profiles in SI units), which made the higher order terms worse than no correction. Note that this did not make old results incorrect, rather it just made the optimizations inefficient - Fixes
VMECIO.load(profile="current")fitting VMEC's half-meshbucoon the full radial mesh, which shifted the current profile and its edge value. - Fixes
solve_continuation(verbose=0)raisingUnboundLocalErroron its first step. - Fixes the
Curve.rotmatsetter, which crashed for list input and silently accepted arrays that were not 3x3 or of length 9. - Fixes two sign errors in
c ballooningthat madeideal ballooning lambdawrong for equilibria with ψ < 0 or ι < 0 #2342: an extrasign(ψ)made the result depend on the direction of B, and for ι < 0 thezeta0shift of ∇α inc ballooninghad the opposite sign fromgds2, so the growth rate grew without bound withzeta0. Results for ψ > 0 and ι > 0 are unchanged. - Fixes
VMECIO.loadfitting lambda as iflmnswere on the full radial mesh. VMEC stores lambda on the half mesh, so the fitted lambda was shifted by half a radial cell and pulled towards the zero placeholder row at the axis, which gave errors of order 0.1% in|B|of loaded equilibria. See #2351. Note that theVMECIO.loadguidance remains the same as before: re-solving the equilibrium in DESC after loading from a VMEC wout is recommended given the representation differences between the two codes. - Fixes
SplineMagneticFieldwith a single toroidal plane (axisymmetric mgrid): the cubic 2D interpolation now uses the Z derivatives instead of the zero phi derivatives, so its error between nodes falls from about 1e-3 to the expected cubic level #2357. - Corrects the labels of
e^helicalande^helical*sqrt(g)(and their magnitudes), which showed the opposite sign to the computed vectors, and the units of the Jacobian-weighted quantities fromT m^2toT m. - Fixes bug in
auglagoptimizers which prevented them from accepting solver hyperparameters. - Improves planar coil representation (
desc.coils.FourierPlanarCoilanddesc.coils.FourierXYCoil) internal rotation methods to avoid potential NaNs which could occur when the normal is parallel or antiparallel to Z-axis( to within machine epsilon), and also ensure the gradient at those edge cases is not only not NaN but also non-zero to avoid optimizer stalls at those cases. - Fixes potential scaling-based issue in DESC-based optimization methods which use adaptive Hessian scaling (e.g.
"fmintr") that could occur when the problem size was small and there were directions of near-zero derivative in the problem. - Fixes computation of
CoilSetLinkingNumberto exclude coil writhe. - Adjusts the
quad_weightsof coil objectives of type_broadcast_input = "node"to ensure their outputs are roughly independent of grid resolution. - Fixes bug in modified Cholesky factorization used by the trust-region subproblems when the Gershgorin lower bound of the Hessian was exactly zero (e.g. a Hessian with an all-zero row), producing NaN steps in
fmintrandfmin-auglagwith the defaulttr_method="exact", and inlsq-exact/lsq-auglagwithtr_method="cho". - Fixes the Levenberg-Marquardt parameter update in the Cholesky trust-region subproblem, which often failed to converge and returned inexact steps in
fmintrandfmin-auglagwith the defaulttr_method="exact", and inlsq-exact/lsq-auglagwithtr_method="cho". - Stops
ProximalProjectionfrom mutatingsolve_optionsduring iterations. - Fixes
FourierRZCoil,SplineXYZCoiland other coils'compute_magnetic_fieldandcompute_magnetic_vector_potentialremovingcurrentfrom the caller'sparamsdictionary when it was used to override the coil current, which made repeated calls with the sameparamssilently use the coil's stored current instead. - Fixes bug that occured when passing in
_surf_batch_sizekwarg toOmnigenityandQuasisymmetryBoozerobjectives - Fixes
pitch_batch_sizeargument getting ignored in compute functions. - Stopped wiping the
CUDA_VISIBLE_DEVICESenvironment variable whenset_device("cpu")is used, which should now allow DESC to be used on CPU concurrently with e.g. pytorch or some other code using the GPU. - Improves the handling of failed Cholesky factorizations in the
"cho"trust-region method. - Adds a warning when sub-objectives with
boundscan make the Jacobian rank-deficient, since the default"qr"trust-region method may then fail to solve the subproblem, suggestingoptions={"tr_method": "svd"}instead. - Fixes
InputReaderrejecting DESC input files whose lines are indented, which previously failed withThe following line is not a valid input. - Fixes wrong signs in
w_Boozer_mnfor non-stellarator-symmetric equilibria, which made the Boozer transform (nu,theta_B,zeta_B, the Boozer harmonics such as|B|_mn_B,QuasisymmetryBoozer,make_boozmn_outputetc.) incorrect for asymmetric equilibria. Results for stellarator-symmetric equilibria are unchanged. Asymmetricmake_boozmn_outputoutputs (includingpmnc_b) now agree with the hidden symmetriesbooz_xform, so the warning about the sign ofnumnchas been removed. - Ensures that
SurfaceCurrentRegularization.normalizationhas the correct units for everyregularizationoption. - Fixes inaccuracy in derivative when equilibrium boundary sheet current is present and non-negligible in
BoundaryErrorobjective.
New Contributors
- @Mandelbr0t made their first contribution in #2279
- @AdemVessell made their first contribution in #2330
- @arpitjain099 made their first contribution in #2338
- @akalita26-Thea made their first contribution in #2376
- @A-Sill made their first contribution in #2378
- @davrens101 made their first contribution in #2395
- @tokamaster made their first contribution in #2076
- @philippbogdan made their first contribution in #2415
Full Changelog: v0.17.3...v0.17.4