Skip to content

Implement envelope tracker - #177

Open
austin-hoover wants to merge 56 commits into
mainfrom
env-tracker
Open

austin-hoover wants to merge 56 commits into
mainfrom
env-tracker

Conversation

@austin-hoover

@austin-hoover austin-hoover commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds envelope tracking capabilities to PyORBIT. The main additions are:

  • orbit.envelope.Envelope stores the beam covariance/centroid arrays and synchronous particle properties (mass, charge, time, energy). It has no dependence on Bunch, but it can be created from an existing bunch: envelope = Envelope.from_bunch(bunch).
  • orbit.envelope.EnvelopeTracker tracks the envelope through the lattice, updating the covariance matrix, centroid, and synchronous particle time/energy.
  • orbit.lattice.AccLattice.trackEnvelope creates an EnvelopeTracker and calls it.
  • examples/Envelope contains a set of examples and benchmarks.

The call signature of AccLattice.trackEnvelope is similar to trackBunch, which some additional options.

 def trackEnvelope(
      self,
      envelope: Envelope,
      index_start: int = 0,
      index_stop: int | None = None,
      sc: str | None = None,
      params_dict: dict | None = None,
      action_container: AccActionsContainer | None = None,
      fit: bool = False,
      fallback: bool = False,
      static: bool = False,
      return_matrix: bool = False,
  ) -> np.ndarray | None:
  • sc switches space charge on/off (2D or 3D). Rather than adding child nodes to the lattice, the space charge kicks are applied before every tracking step.
  • params_dict and action_container should behave the same as in trackBunch and can be used to evaluate the results at each step of the simulation.
  • fit=False uses analytic transfer matrices, while fit=True uses best-fit transfer matrices. The latter is slower but is a convenient way to linearize elements.
  • fallback=False will raise an error for nodes without analytic transfer matrix definitions. fallback=True will fall back to best-fit matrices for these nodes.
  • static=True will store the matrices and use them on the next trackEnvelope call. This speeds up tracking when there are no time-dependent nodes in the lattice.
  • return_matrix=True returns the total transfer matrix for the lattice.

These commits can be squashed.

austin-hoover and others added 30 commits June 30, 2026 10:30
* Start envelope 2D module

* Envelope stores empty Bunch object

This will be used to set the correct particle mass and energy.

* Add track method to Envelope2D

This method applies the linear transformation S -> M S M^T.

* Start test script for envelope2D tracker

* Add empty spaceChargeMatrix method

* Add .idea to .gitignore

* Change Envelope2D to Envelope

* Update example

* Docstrings

* Add envelope/matrix.py

* Add MatrixFactory class

* Add several classes to teapot __init__

* Add node types to ignore in matrix factory

Replace these with identity matrix

* Add envelope tracker

* Delete test script

* Format

* Format

* Fix error in centroid coordinates in example

* Add space charge calculation

* Add space charge in PIC test + visual comparison of distribution

* Plot dots

* Fix factor of 2 in perveance calculation

* Add kv/waterbag/gauss dist

* Add tilt to 2D envelope space charge calculation

* Add corner plot and tilt test

* Format

* Format

* Add comment on cholesky issue

* Delete commented line

* Edit .gitignore

* Docstrings

* Plot centroid offset for envelope comparison

* Remove print

* Start fixing centroid issue

* Fix centroid issue

* Use eigenvector decomposition

* Start 3D envelope

* Move envelope space charge transfer matrix calculations

Move to Envelope class

* Add helper functions

* Set perveance_3d to 0

* Keep trying to implement 3D space charge

* Add 3D drift test

* Add comment

* Clarify attempt to calculate 3D sc matrix

* Add comment

* Correct formula for 3D space charge matrix

* Update matrices

* Fix plotting

* Format

* Add comments

* Delete a few unused lines

* Add test_env_sns_ring

* Add options for handling matrix elements without known matrix

* Add tests

Dipole is incorrect

* Typo

* Fix type

* Check dipole matrix

* Update tests_sns_ring.py

* Fix dipole matrix calculation for parts

* Typo

* Test sns ring

* Scale last column of matrix by dp_p coeff

* Update tests

* Modify atol and rtol in np.isclose

* Add energy spread and rms z to cov matrix tests

* Fix dp/p to dE correction in transfer matrices

* Fix kick matrix

Drift then kick (node has a length param)

* Fix atol/rtol in tests

Comparison is |a - b| <= atol + rtol * |b|

* Fix confusion on covariance vs. moments matrix

* Clean up script

* Clean up script

* Fix test

* Add simplified SNS ring example

Keep only quads, drifts, bends

* Add test_tilt

* Add nparts to tests

* Remove docstring

* Add NodeTEAPOT to ignore list

* Replace MultipoleTEAPOT with drift if all strengths are zero

* Don't change sync particle time in matrixfactor

That should happen by tracking syncparticle through node

* Add solenoid to envelope tracker

* Fix drift replacement

Drift length needs to be calculated for the part of the node, not
the whole node

* Start adding nodes from orbit.py_linac

Quad element needs to calculate Brho, which requires the bunch
charge. The bunch charge is stored in the Bunch object, not
SyncParticle. So I changed the Envelope class to store reference
to Bunch object rather than SyncParticle. The bunch is copied +
emptied in the constructor.

This might make sense anyway because we may want to track test
particles. It could also be easier to create an envelope directly
from the Bunch: the covariance matrix and centroid can be calculated
from the bunch macroparticles.

* Fix x-axis label in 3d drift example

* Start 3D drift with rotation example

Seems to be working for x-y rotations but not y-z. Need to investigate

* Fix longitudinal coordinate of 3D space charge matrix

Transfer matrix was written for z' = dz/ds. Added conversion from
z' to dE.

* Change argument in gen_dist examples

* Move functions out of MatrixFactory

* Remove funcs

* Write `matrix` function for each node

This function returns the transfer matrix from the synchronous particle
and the node part index. This way we don't have to check the type of
the node during tracking, and we could also store the transfer matrix
as a node attribute if we want.

* Print node when matrix function not implemented

* Clean up

* Move matrix calculation to new module

The new module is under orbit.matrix_lattice.analytic. It is a set
of functions that return transfer matrices dipoles, quads, etc. It
is used for envelope tracking but could also be used elsewhere.

* Fix lorentz transform of xyz cov matrix in example

* Fix arg in gen_dist

* Remove comment

* Remove skip line

* Rename self.perveance to self.sc_factor

The perveance involves the line density: perveance = sc_factor / bunch_length.

* Add empty test function test_sc_3d_cold_expansion

* Lorentz transform was not used in 3D space charge

Results are still incorrect at high energy...

* Add comments

* Use matrix for lorentz transform of cov matrix

* Remove comments

* Fix gamma factor in 3D space charge

Factor was double counted in transverse kick. Things are now working
when gamma >> 1, but not when there are x-z or y-z correlations

* Looking good for upright beams relativistic + nonrelativistic

Not working with x-z tilt when gamma >> 1

* Fix lorentz boost for x' and y'

This fixes space charge kick for x and y when there are x-z or y-z
correlations in the bunch ellipsoid.

* Use eigh instead of eig for cov matrix eigvectors

* Formatting and comments

* Remove commented lines

* Add rf_gap_matrix function

* Remove setting sync part time (does nothing in MatrixRFGap)

* Print time when tracking through sns ring

* Return drift or none if params are zero in TEAPOT nodes

* Remove comment

* Add decimal to time per turm when printing

* Add profiler

* Small speedup: conversion from dp_p to dE

* Remove handle_unknown

* Longer lines

* Add test_env_sns_ring_speed.py

* Remove old argument handle-unknown

Right now every unknown element will throw an error except
MultipoleTEAPOT if all k are zero

* Formatting

* Change defaults in test_env_sns_ring_speed.py

* Add checks for linac node transfer matrices

* Run tests at different energies

* Split lattice in test_env_sns_ring_speed

* Use @Property for accessing cov_matrix and mean attributes

* Reduce default turns

* Avoid using np.linalg.inv

* Use -1 instead of dim

* Use cov matrix for bunch length calculation

* Use rotation instead of eigenvector calc for 2D space charge

* Track cov and mean instead of 7 x 7 moment matrix

No time saved because to get cov you need to call outer(mu, mu) and
subtract from moment matrix. This is more straightforward

* Add charge as argument everywhere

SyncPart does not have charge

* Start SNS linac envelope tracking example

* Add charge param to tests

* Turn off fringe fields in sns linac example

* Change default seq stop

* Start linac benchmark

* Copy bunch in envelope constructor

Also correct node position calculation in track_history

* track kin energy

* Improve sns linac benchmark

* Fix envelope tracker position

* Add show arg

* SNS linac benchmark working

Results are pretty close when space charge is off. Beam size and energy
is correct through the linac.

Results diverge when space charge is turned on. Agreement is pretty good
in the MEBT but starts to get worse in the DTL.

* Don't connect dots when plotting rms history

* Fix space charge factor: make dynamic

* Decrease step size for diagnostics

* Move all envelope tracking code to orbit.envelope module

The functions in orbit.envelope.matrix will calculate the 7 x 7
transfer matrix from common elements and, at the same time, update
the synchronous particle time + kinetic energy.

There is now a big series of if else statements to determine which
of these functions to various AccNodes, including in orbit.teapot
and orbit.py_linac modules. This check doesn't have much impact
on the runtime. I don't know if this is the best way to do it
but it is working.

* Rename examples

* Format tests

* Undo old changes to modules outside orbit.envelope

The only changes are to make some nodes importable

* Use covariance matrix from initial bunch in sns ring example

This ensures envelope and bunch have exact same initial covariance
matrix.

* Documentation

* Change bend nparts to match teapot

* Increase nparts in bend test

* Change axis label in yrms and yavg plots

* Set edge angles to zero with warning

This took a while to track down. The fringe field function for
BendTEAPOT (and all TEAPOT nodes) is called even if fringe field
calculations are disabled. The actual fringe field kick is not
applied, but wedgerotate is applied. Setting the ea1 and ea2
parameters to zero makes things agree without space charge. Added
a warning and set these to zero automatically.

This is for the dh_a11, dh_a12, etc. dipoles in the sns ring.

* Combine space charge and body transfer matrices by transform

Small speedup

* Zero ea1 ea2 in sns_ring script

* Fix bunch length calculation in 2D space charge

Was assuming L = 4 * z_rms but really L = sqrt(12) * z_rms for
1D uniform distribution! Finally fixed sns ring space charge
agreement.

* SNS linac default

* Calculate space charge matrix before calculating transfer matrix

Want to calculate space charge matrix before possible energy change.

* Fix comment

* Use rest length in space charge kick

* Typo: remove self

* Formatting

* Add choice of phase space distribution for sns linac benchmark

* Format

* Add to-do comment

* Add continuous linear focusing element to envelope tracking

* Add continous linear focusing element to envelope tests

* Add envelope.copy function

* Pre-calculate matrices for ring tracking

Added method `track_ring` to EnvelopeTracker. It will pre-calculate the
transfer matrices in the ring and mark the locations of space charge kicks.
If tracking without space charge, it will compute and apply the one-turn
matrix. Otherwise it will step through each element.

This assumes there is no change of the synchronous particle energy and that
all nodes in the lattice are static.

* Fix bunch length in 2D fodo example; use track_ring

* Move tests to /tests folder for use with pytest

* Add to-do comment

* Rename track_sync_part_ to get_matrix_

* Remove comment

* Add docstring

* Organize orbit.envelope module

Separate files:
- envelopy.py has Envelope class definition.
- track.py has EnvelopeTracker class definition.
- matrix.py has functions to get transfer matrices from AccNode

* Clean up examples

* Fix tests

* Move get_classical_radius to utils.py
Fix order in one-turn matrix calculation
Improve `track_history` function
Add start and stop index to envelope tracker
…les (#134)

* Change get_effective_matrix to get_transfer_matrix

Also add index_start and index_stop

* Format

* Format examples and add run.sh

* Make get_transfer_matrix always transform envelope
* Change get_effective_matrix to get_transfer_matrix

Also add index_start and index_stop

* Format

* Format examples and add run.sh

* Make get_transfer_matrix always transform envelope

* Always recompute matrices in get_transfer_matrix
Merge branch main into env-tracker
Also deal with ea1 ea2 parameters in bend elements, which are
called as part of the fringe method for dipoles even when fringe
field usage is turned off. An approximate matrix was suggested by
an LLM and has not been checked, although it looks like it agrees
with best-fit matrix for that element.

Fitting appears to be very fast, so maybe we should just default
to that?
Include transfer matrix fitting as default option and simplify code
Merge branch main into env-tracker
Merge branch main into env-tracker
Merge branch 'main' into env-tracker
Comment thread py/orbit/envelope/envelope.py Resolved

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants