Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
54 changes: 38 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,22 +64,22 @@ curvature. Losses compose with `+`, and `L.grad` is the exact gradient.
![Coils fitted to a QA boundary](docs/readme_coil_optimization.png)

```python
from essos.coils import Coils, CreateEquallySpacedCurves
from essos.coils import Coils, create_equally_spaced_curves
from essos.fields import BiotSavart
from essos.losses import custom_loss
from essos.surfaces import BdotN_over_B, SurfaceRZFourier
from essos.losses import CustomLoss
from essos.surfaces import bdotn_over_b, SurfaceRZFourier
from scipy.optimize import least_squares

surface = SurfaceRZFourier.from_wout_file("wout.nc", s=1, ntheta=30, nphi=30,
range_torus="half period")
coils = Coils(curves=CreateEquallySpacedCurves(3, 3, 10.0, 5.6, n_segments=45,
coils = Coils(curves=create_equally_spaced_curves(3, 3, 10.0, 5.6, n_segments=45,
nfp=2, stellsym=True),
currents=[1.0] * 3)

L = (custom_loss(lambda field, surface: abs(BdotN_over_B(surface, field)).sum(),
L = (CustomLoss(lambda field, surface: abs(bdotn_over_b(surface, field)).sum(),
"field", surface=surface)
+ custom_loss(lambda field: (field.coils.length - 32.0).clip(0).mean(), "field")
+ custom_loss(lambda field: (field.coils.curvature - 0.1).clip(0).mean(), "field"))
+ CustomLoss(lambda field: (field.coils.length - 32.0).clip(0).mean(), "field")
+ CustomLoss(lambda field: (field.coils.curvature - 0.1).clip(0).mean(), "field"))
L.dependencies = {"field": BiotSavart(coils)}

result = least_squares(L, L.starting_dofs, L.grad, max_nfev=400)
Expand All @@ -102,7 +102,7 @@ field = BiotSavart(Coils.from_json("coils.json"))
R0 = jnp.linspace(1.21, 1.40, 8)
seeds = jnp.array([R0, jnp.zeros_like(R0), jnp.zeros_like(R0)]).T

tracing = Tracing(field=field, model="FieldLineAdaptative", initial_conditions=seeds,
tracing = Tracing(field=field, model="FieldLineAdaptive", initial_conditions=seeds,
tmax=8000, n_save=40000, atol=1e-8, rtol=1e-8)
tracing.poincare_plot(shifts=[0.0])
```
Expand Down Expand Up @@ -132,7 +132,7 @@ from essos.dynamics import Particles, Tracing

particles = Particles(initial_xyz=seeds, mass=ALPHA_PARTICLE_MASS,
charge=ALPHA_PARTICLE_CHARGE, energy=4000 * ONE_EV)
tracing = Tracing(field=field, model="GuidingCenterAdaptative", particles=particles,
tracing = Tracing(field=field, model="GuidingCenterAdaptive", particles=particles,
tmax=1e-4, n_save=800, atol=1e-7, rtol=1e-7)
tracing.plot()
print(tracing.loss_fractions)
Expand All @@ -155,7 +155,7 @@ with a wall 3 cm outside the LCFS.
```python
vmec = vmex.essos_vmec_field(wout) # or Vmec("wout_*.nc")
outside = vmex.VmecExtender.from_wout(wout, external_field=coil_grid)
tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles,
tracing = Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles,
tmax=4e-5, exterior_field=outside, wall=0.03) # gap [m] or a surface
print(tracing.wall_hits.mean(), tracing.wall_positions[tracing.wall_hits])
```
Expand Down Expand Up @@ -266,17 +266,17 @@ the `wout` directly and DESC fits it. ± is the binomial standard error.
off outside the LCFS. Supplying `stopping_criteria` replaces these events; it is
evaluated on `(s, theta, phi, ...)`. See
[`examples/particle_tracing/trace_particles_vmec_to_wall.py`](examples/particle_tracing/trace_particles_vmec_to_wall.py).
- **Stopping coil-field traces.** Pass `stopping_criteria=LevelsetStoppingCriterion(...)`
to end Cartesian traces once they leave a prescribed distance from a surface,
and read the per-line mask from `tracing.boundary_hits`.
- **Stopping coil-field traces.** Pass `stopping_criteria` (a level-set callable or
`LevelsetStoppingCriterion(...)`, positive inside) to end a trace at the
boundary and read the per-line mask from `tracing.boundary_hits`.
- **Step budget and defaults.** `max_steps` (default 16 times the steps of a fixed-step solve) bounds every
Diffrax solve and a `RuntimeWarning` reports orbits that did not finish. `timestep` defaults to 1/400 of the
transit time `R0 / v` (1/100 on a VMEC field), `rtol` to `1e-8` and `atol` to `rtol`.
- **Progress bars** are off by default; pass `progress=True` when interactive.
With `particle_batch_size=n` particles are traced `n` at a time and the bar
counts completed particles (batches are bypassed under `jax.jit`/`grad`).
- **Model choice.** `FieldLineArclength` traces a fixed physical length so
rescaling `B` does not change the run; `FieldLineToroidal` sets coverage
- **Model choice.** `field_line_arclength` traces a fixed physical length so
rescaling `B` does not change the run; `field_line_toroidal` sets coverage
directly in toroidal angle for flux-coordinate fields.

## Optional: near-axis fields
Expand Down Expand Up @@ -304,7 +304,6 @@ These renames are breaking and have no aliases. Tracing options are keyword-only
| `optimize_loss_function(maximum_function_evaluations=...)`, `MultiObjectiveOptimizer` option of the same name | `max_nfev` |
| `optimize_loss_function(tolerance_optimization=...)`, `MultiObjectiveOptimizer` option of the same name | `tol` |
| `loss_BdotN`, `loss_BdotN_constraint` | `loss_bdotn`, `loss_bdotn_constraint` |
| `Tracing(condition=...)` | `stopping_criteria` (one callable or a list) |

`max_steps` was already the step-cap name and is unchanged; the loss functions now accept it too.

Expand All @@ -327,6 +326,29 @@ These renames are breaking and have no aliases. Tracing options are keyword-only
pytest
```

## API changes: names

The PEP 8 renames below are breaking; update calls as shown.

| Old | New |
| --- | --- |
| `Electric_field_flux` | `ElectricFieldFlux` |
| `Electric_field_zero` | `ElectricFieldZero` |
| `BackgroundSpecies.species_indeces` | `BackgroundSpecies.species_indices` |
| `ALM_model_lbfgs` | `alm_model_lbfgs` |
| `ALM_model_jaxopt_lbfgsb` (alias) | `alm_model_lbfgs` |
| `CreateEquallySpacedCurves`, `RotatedCurve` | `create_equally_spaced_curves`, `rotated_curve` |
| `BdotN`, `BdotN_over_B`, `B_on_surface`, `SquaredFlux` | `bdotn`, `bdotn_over_b`, `b_on_surface`, `squared_flux` |
| `loss_B_difference_coils_near_axis`, `loss_gradB_difference_coils_near_axis`, `loss_particle_Br` | `loss_b_difference_coils_near_axis`, `loss_gradb_difference_coils_near_axis`, `loss_particle_br` |
| `normB_axis`, `loss_normB_axis_average` | `norm_b_axis`, `loss_norm_b_axis_average` |
| `B_regularized_singularity_term`, `B_regularized_pure` | `b_regularized_singularity_term`, `b_regularized_pure` |
| `GuidingCenter*`, `LorentzCollisions*`, `Lorentz`, `FieldLine*` vector-field functions in `essos.dynamics` | snake_case (`guiding_center`, `lorentz`, `field_line_arclength`, ...); the `model=` strings are unchanged |
| `BiotSavart_from_gamma` | `BiotSavartFromGamma` |
| `base_loss`, `custom_loss`, `composite_loss` | `BaseLoss`, `CustomLoss`, `CompositeLoss` |
| `essos.fields.near_axis` (stub that raised `ImportError`) | removed; use `pyqsc_jax.near_axis` |
| `x` property of coils and surfaces | removed; use `dofs` |
| `Coils.from_json` for files with `dofs_curves` / `dofs_currents` | files written by `Coils.to_json` only (keys `dofs_curves_raw`, `dofs_currents_raw`) |

## License

MIT, see [LICENSE](LICENSE).
Expand Down
20 changes: 10 additions & 10 deletions docs/make_readme_figures.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
matplotlib.use("Agg")
import matplotlib.pyplot as plt

from essos.coils import Coils, CreateEquallySpacedCurves
from essos.coils import Coils, create_equally_spaced_curves
from essos.constants import ALPHA_PARTICLE_CHARGE, ALPHA_PARTICLE_MASS, ONE_EV
from essos.dynamics import Particles, Tracing
from essos.fields import BiotSavart
Expand All @@ -33,21 +33,21 @@ def coil_optimization() -> None:
"""Fit coils to a VMEC boundary: normal field, length and curvature."""
from scipy.optimize import least_squares

from essos.losses import custom_loss
from essos.surfaces import BdotN_over_B, SurfaceRZFourier
from essos.losses import CustomLoss
from essos.surfaces import bdotn_over_b, SurfaceRZFourier

surface = SurfaceRZFourier.from_wout_file(
str(INPUTS / "wout_LandremanPaul2021_QA_reactorScale_lowres.nc"),
s=1, ntheta=30, nphi=30, range_torus="half period")
init_coils = Coils(curves=CreateEquallySpacedCurves(3, 3, 10.0, 5.6, n_segments=45,
init_coils = Coils(curves=create_equally_spaced_curves(3, 3, 10.0, 5.6, n_segments=45,
nfp=2, stellsym=True),
currents=[1.0] * 3)
init_field = BiotSavart(init_coils)

L = (custom_loss(lambda field, surface: jnp.sum(jnp.abs(BdotN_over_B(surface, field))),
L = (CustomLoss(lambda field, surface: jnp.sum(jnp.abs(bdotn_over_b(surface, field))),
"field", surface=surface)
+ custom_loss(lambda field: jnp.mean(jnp.maximum(0, field.coils.length - 32.0)), "field")
+ custom_loss(lambda field: jnp.mean(jnp.maximum(0, field.coils.curvature - 0.1)), "field"))
+ CustomLoss(lambda field: jnp.mean(jnp.maximum(0, field.coils.length - 32.0)), "field")
+ CustomLoss(lambda field: jnp.mean(jnp.maximum(0, field.coils.curvature - 0.1)), "field"))
L.dependencies = {"field": init_field}

before = float(L(L.starting_dofs))
Expand Down Expand Up @@ -76,7 +76,7 @@ def field_line_tracing() -> None:
zeros = jnp.zeros_like(R0)
seeds = jnp.array([R0, zeros, zeros]).T

tracing = Tracing(field=field, model="FieldLineAdaptative", initial_conditions=seeds,
tracing = Tracing(field=field, model="FieldLineAdaptive", initial_conditions=seeds,
tmax=8000, n_save=40000, atol=1e-8, rtol=1e-8)

fig, ax = plt.subplots(figsize=(4.4, 4.4))
Expand All @@ -97,7 +97,7 @@ def particle_tracing() -> None:
mass=ALPHA_PARTICLE_MASS, charge=ALPHA_PARTICLE_CHARGE,
energy=4000 * ONE_EV)

tracing = Tracing(field=field, model="GuidingCenterAdaptative", particles=particles,
tracing = Tracing(field=field, model="GuidingCenterAdaptive", particles=particles,
tmax=1e-4, n_save=800, atol=1e-7, rtol=1e-7)

fig = plt.figure(figsize=(5.0, 4.0))
Expand Down Expand Up @@ -144,7 +144,7 @@ def wall_tracing() -> None:
particles = Particles(initial_xyz=seeds, mass=PROTON_MASS, charge=ELEMENTARY_CHARGE,
energy=WALL_ENERGY_EV * ONE_EV,
initial_vparallel_over_v=jax.random.uniform(kv, (n,), minval=-1, maxval=1))
tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles,
tracing = Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles,
tmax=4e-5, timestep=1e-9, n_save=2000, atol=1e-8, rtol=1e-8,
exterior_field=outside, wall=gap)

Expand Down
2 changes: 1 addition & 1 deletion docs/tracing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fixed-step defaults; orange is the old setting and blue the current one.
Adaptive or fixed
-----------------

* Use the adaptive models (``GuidingCenterAdaptative``, ``FullOrbitAdaptative``) unless a fixed step is required. Their
* Use the adaptive models (``GuidingCenterAdaptive``, ``FullOrbitAdaptive``) unless a fixed step is required. Their
cost follows the tolerance and, on a coil field, they reach a given energy error about 4 times faster than a fixed step (4e-8 in 2.4 s against 9.4 s).
* The fixed-step models need a step small enough for the field: on a coil field the energy error is 3e-2 at 100 steps
per transit and 4e-8 at 400. A smooth VMEC field is converged from about 100.
Expand Down
12 changes: 6 additions & 6 deletions essos/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from time import time
import jax.numpy as jnp
import matplotlib.pyplot as plt
from essos.coils import Coils, CreateEquallySpacedCurves
from essos.coils import Coils, create_equally_spaced_curves
from essos.fields import BiotSavart

from essos.dynamics import Tracing
Expand All @@ -27,8 +27,8 @@ def main(cl_args=sys.argv[1:]):
# Optimization parameters
max_coil_length = 5.0
max_coil_curvature = 4
order_Fourier_series_coils = 5
number_coil_points = order_Fourier_series_coils*10
fourier_order = 5
number_coil_points = fourier_order*10
max_nfev = 100
number_coils_per_half_field_period = 3
tol = 1e-8
Expand All @@ -52,8 +52,8 @@ def main(cl_args=sys.argv[1:]):
number_of_field_periods = nfp
major_radius_coils = field.R0[0]
minor_radius_coils = major_radius_coils/1.5
curves = CreateEquallySpacedCurves(n_curves=number_coils_per_half_field_period,
order=order_Fourier_series_coils,
curves = create_equally_spaced_curves(n_curves=number_coils_per_half_field_period,
order=fourier_order,
R=major_radius_coils, r=minor_radius_coils,
n_segments=number_coil_points,
nfp=number_of_field_periods, stellsym=True)
Expand All @@ -62,7 +62,7 @@ def main(cl_args=sys.argv[1:]):
# Optimize coils
print(f'Optimizing coils with {max_nfev} function evaluations.')
time0 = time()
coils_optimized = optimize_loss_function(loss_coils_for_nearaxis, initial_dofs=coils_initial.x,
coils_optimized = optimize_loss_function(loss_coils_for_nearaxis, initial_dofs=coils_initial.dofs,
coils=coils_initial, tol=tol,
max_nfev=max_nfev, field_nearaxis=field,
max_coil_length=max_coil_length, max_coil_curvature=max_coil_curvature,)
Expand Down
Loading
Loading