Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
0dbb8bb
Refine example of multi objective optimization to run with more trial…
rogeriojorge Aug 15, 2025
ae5904c
add qfm
Aug 18, 2025
9690c22
add toroidal flux as qfm label and vector potential in BiotSavart
Aug 19, 2025
a41766c
update qfm and example to solve some bugs; add toroidal field in surf…
Aug 21, 2025
60df536
delete input that we dont need actually
Aug 21, 2025
4198c3c
add jaxopt in requirements
Aug 21, 2025
d2f21ca
add stellarator_coils.json in input_files
Aug 21, 2025
0f3aa15
write better example
Sep 12, 2025
756fb3c
Merge remote-tracking branch 'origin/main' into para_op
Sep 12, 2025
9649563
change suggested weight
Sep 16, 2025
5bba340
change qfm class to a better structure for jax; normalize constrain;
Sep 25, 2025
393ca8f
delete unused code
Sep 25, 2025
3de61c3
comment fieldlinetracing
Sep 25, 2025
07dc3e0
comment in english; change callback method
Sep 25, 2025
4220559
comment in english; change callback method
Sep 25, 2025
c63debe
add qfm test
Sep 25, 2025
4c30c61
add qfm test
Sep 25, 2025
8a1760b
add qfm test
Sep 25, 2025
08b27d2
add qfm test
Sep 25, 2025
3215e2e
Merge main into para_op
rogeriojorge Oct 7, 2026
050b094
Merge branch 'main' into para_op
rogeriojorge Oct 7, 2026
66f911d
Merge branch 'main' into para_op
rogeriojorge Oct 8, 2026
2daf2ac
Merge branch 'main' into para_op
rogeriojorge Oct 8, 2026
be4d525
Merge remote-tracking branch 'origin/main' into HEAD
rogeriojorge Oct 9, 2026
ef0cd0e
Merge main
rogeriojorge Oct 19, 2026
aa14d37
Merge remote-tracking branch 'origin/main' into para_op
rogeriojorge Oct 19, 2026
029f219
Merge remote-tracking branch 'origin/main' into m27
rogeriojorge Oct 26, 2026
f494d2f
Merge remote-tracking branch 'origin/main' into para_op
rogeriojorge Oct 31, 2026
95cd676
Use SciPy L-BFGS-B in QfmSurface and pass gradients to SLSQP
rogeriojorge Oct 31, 2026
05da006
Merge current target and reconcile field and tracing interfaces
rogeriojorge Nov 18, 2026
74bae4d
Restore the complete target tree after branch synchronization
rogeriojorge Nov 18, 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
3 changes: 0 additions & 3 deletions essos/multiobjectiveoptimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@
from functools import partial
from essos.coils import Coils, Curves, CreateEquallySpacedCurves
from essos.fields import BiotSavart
import numpy as np
from pandas.plotting import parallel_coordinates
import pandas as pd


def _require_plotly():
Expand Down
206 changes: 206 additions & 0 deletions essos/qfm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import copy
import numpy as np
import jax
from jax import vmap, grad, device_get
import jax.numpy as jnp
from essos.surfaces import SurfaceRZFourier
from scipy.optimize import minimize


class QfmSurface:
def __init__(self, field, surface: SurfaceRZFourier, label: str, targetlabel: float = None,
toroidal_flux_idx: int = 0):
assert label in ["area", "volume", "toroidal_flux"], f"Unsupported label: {label}"

self.field = field
self.surface = surface
self.surface_optimize = self._build_surface_with_x(surface, surface.x)
self.label = label
self.toroidal_flux_idx = int(toroidal_flux_idx)
self.name = str(id(self))

if targetlabel is None:
self.targetlabel = {
"volume": surface.volume,
"area": surface.area,
"toroidal_flux": self._toroidal_flux(surface)
}[label]
else:
self.targetlabel = targetlabel

def _toroidal_flux(self, surf: SurfaceRZFourier):
curve = surf.gamma[self.toroidal_flux_idx]
dl = jnp.roll(curve, -1, axis=0) - curve
A_vals = vmap(self.field.A)(curve)
return jnp.sum(jnp.sum(A_vals * dl, axis=1))

def _build_surface_with_x(self, surface, x):
rc_safe = device_get(surface.rc)
zs_safe = device_get(surface.zs)
x_safe = device_get(x)

s = SurfaceRZFourier(
rc=rc_safe,
zs=zs_safe,
nfp=int(surface.nfp),
mpol=int(surface.mpol),
ntor=int(surface.ntor),
ntheta=int(surface.ntheta),
nphi=int(surface.nphi),
range_torus=surface.range_torus,
close=True
)
s.x = x_safe
return s

def _surface_at(self, x):
# A shallow copy keeps traced dofs and geometry caches off the shared surface.
surf = copy.copy(self.surface_optimize)
surf.x = x
return surf

def objective(self, x):
surf = self._surface_at(x)
N = surf.unitnormal
norm_N = jnp.linalg.norm(surf.normal, axis=2)
points = surf.gamma.reshape(-1, 3)
B = vmap(self.field.B)(points).reshape(N.shape)
B_n = jnp.sum(B * N, axis=2)
norm_B = jnp.linalg.norm(B, axis=2)
value = jnp.sum(B_n**2 * norm_N) / jnp.sum(norm_B**2 * norm_N)
return value

def constraint(self, x):
surf = self._surface_at(x)

raw_c = {
"volume": surf.volume - self.targetlabel,
"area": surf.area - self.targetlabel,
"toroidal_flux": self._toroidal_flux(surf) - self.targetlabel
}[self.label]

c = raw_c / jnp.abs(self.targetlabel)
return c

def penalty_objective(self, x, constraint_weight=1.0):
r = self.objective(x)
c = self.constraint(x)
return r + 0.5 * constraint_weight * c**2

def _callback(self, info, printlog=True):
if isinstance(info, dict):
# LBFGS
it = info.get("iter", -1)
r = info["objective"]
c = info["constraint"]
penalty = info["penalty"]
grad_norm = info["grad_norm"]

# Print logs if printlog is True
if printlog:
print(f"[LBFGS iter {it}] objective={r:.6e} constraint={c:.3e} "
f"penalty={penalty:.6e} grad_norm={grad_norm:.3e}")
else:
# SLSQP
it = getattr(self, "_slsqp_iter", 0) + 1
setattr(self, "_slsqp_iter", it)

obj = float(self.objective(info))
cst = float(self.constraint(info))
penalty = float(self.penalty_objective(info))
grad_norm = float(jnp.linalg.norm(grad(lambda z: self.penalty_objective(z))(info)))

# Print logs if printlog is True
if printlog:
print(f"[SLSQP iter {it}] objective={obj:.6e} constraint={cst:.3e} "
f"penalty={penalty:.6e} grad_norm={grad_norm:.3e}")


def minimize_lbfgs(self, x0=None, tol=1e-6, maxiter=1000, constraint_weight=1e4,
printlog=True, **kwargs):
x0 = self.surface_optimize.x if x0 is None else x0

penalty = jax.jit(jax.value_and_grad(lambda x: self.penalty_objective(x, constraint_weight)))
iterations = []

def callback(x):
iterations.append(1)
value, gradient = penalty(x)
self._callback({"iter": len(iterations), "objective": float(self.objective(x)),
"constraint": float(self.constraint(x)),
"penalty": float(value), "grad_norm": float(jnp.linalg.norm(gradient))}, printlog)

res = minimize(lambda x: tuple(map(np.asarray, penalty(x))), np.asarray(x0), jac=True,
method="L-BFGS-B", tol=tol, options={"maxiter": maxiter}, callback=callback)
self.surface_optimize = self._build_surface_with_x(self.surface_optimize, res.x)
return {
"fun": float(res.fun),
"gradient": jnp.array(res.jac),
"iter": res.nit,
"info": res,
"success": res.success,
"s": self.surface_optimize,
}

def minimize_slsqp(self, x0=None, tol=1e-6, maxiter=1000, printlog=True, **kwargs):
x0 = jnp.array(self.surface_optimize.x if x0 is None else x0)

# Run the SLSQP optimizer
res = minimize(
fun=lambda x: float(self.objective(x)),
x0=x0,
jac=lambda x: np.asarray(grad(self.objective)(x)),
method="SLSQP",
constraints={"type": "eq", "fun": lambda x: float(self.constraint(x)),
"jac": lambda x: np.asarray(grad(self.constraint)(x))},
tol=tol,
options={"maxiter": maxiter, "disp": False},
callback=lambda x: self._callback(x, printlog) # Use internal callback directly
)

# Store the optimized x in the surface
x_safe = device_get(res.x)
self.surface_optimize = self._build_surface_with_x(self.surface_optimize, x_safe)

# Return the result with optimization trace
return {
"fun": res.fun,
"gradient": jnp.array(jax.grad(self.objective)(res.x)),
"iter": res.nit,
"info": res,
"success": res.success,
"s": self.surface_optimize
}

def run(
self,
method: str = "SLSQP",
tol: float = 1e-6,
maxiter: int = 1000,
x0=None,
constraint_weight: float = 1e-3,
printlog: bool = True,
**kwargs
):

method_up = method.upper()

if method_up == "SLSQP":
return self.minimize_slsqp(
x0=x0,
tol=tol,
maxiter=maxiter,
printlog=printlog,
**kwargs
)
elif method_up == "LBFGS":
return self.minimize_lbfgs(
x0=x0,
tol=tol,
maxiter=maxiter,
constraint_weight=constraint_weight,
printlog=printlog,
**kwargs
)
else:
raise ValueError(f"Unknown method '{method}'")
7 changes: 2 additions & 5 deletions examples/coil_optimization/optimize_multiple_objectives.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"tolerance_optimization": 1e-5,
"optimizer_choices": ["adam", "amsgrad", "sgd"],
"num_coils": 4,
"order_Fourier": 6,
"order_Fourier": 3,
}
)

Expand All @@ -47,13 +47,10 @@
print(f"Maximum BdotN/B before optimization: {jnp.max(BdotN_over_B_initial):.2e}")
print(f"Maximum BdotN/B after optimization: {jnp.max(BdotN_over_B_optimized):.2e}")




manager.plot_pareto_fronts(z_thresh=3, save= True)
try: # the interactive figures need the optional plotly dependency
manager.plot_optimization_history(z_thresh=3, save=True)
manager.plot_param_importances(save=True)
manager.plot_parallel_coordinates(z_thresh=3, save=True)
# manager.plot_parallel_coordinates(z_thresh=3, save=True)
except ImportError as err:
print(err)
1 change: 1 addition & 0 deletions examples/input_files/stellarator_coils.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"nfp": 2, "stellsym": true, "order": 3, "n_segments": 45, "dofs_curves": [[[11.622700935298976, 0.021162524110782358, 4.969310302793117, 0.21619524408779187, 1.0480524616370408, 0.28649150353772795, -0.28257357882380735], [2.650045608829704, 1.3195115302904592, 2.0655255644324324, -0.9222231514058897, -0.6185897653334609, -0.029257891517016514, -0.4689941563806397], [0.5736288312625168, -6.124609285728119, -0.25270656488797033, -0.7494953058315302, -0.5577484125670837, 0.41280301860103114, 0.49815152814320796]], [[8.270668252860887, 0.3665817338447269, 3.1105370020049437, -1.1258699831006203, 1.3263614203440663, 0.2102848349841804, -0.49142766630482954], [7.030418225942375, 0.6256285318976378, 4.821568953388758, -0.3255223631956292, -0.5563748261863908, 0.5699454535195534, 0.4766999014677532], [1.1730264767378422, -5.641665411926324, -0.3776722058863022, -0.22889203846752135, -0.37533249101718297, -0.13615989719970903, 0.2925684224469988]], [[2.870219295136962, 1.011171856312114, 1.0052842269429074, -1.616205601094772, 0.4568093873850295, 0.8322530493441007, -0.47523615678931685], [9.19851171039639, 0.15301426329616008, 6.079831607393782, -0.1245216794618166, -0.5264330665117136, 0.028667523169553216, 0.4360349874253642], [0.5149651564138196, -5.068527850344334, -0.2765171026569377, -0.4083657568321486, -0.061669206943173696, -0.01678957665952365, 0.08107054639495188]]], "dofs_currents": [0.9714976808550443, 1.0086510674635079, 1.019851251681448]}
Loading
Loading