Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
0a0b2d2
Implement envelope tracker (#112)
austin-hoover Jun 30, 2026
debccaf
Fix order in one-turn matrix calculation
austin-hoover Jul 1, 2026
6ef5b66
Merge pull request #129 from austin-hoover/env-tracker
austin-hoover Jul 2, 2026
2542a7e
Fix path length in track_history
austin-hoover Jul 3, 2026
c90c12c
Merge pull request #130 from austin-hoover/env-tracker
austin-hoover Jul 3, 2026
1e6885c
Merge branch 'main' into env-tracker
austin-hoover Jul 9, 2026
15afa74
Add index_start and index_stop to envelope tracker
austin-hoover Aug 6, 2026
5427c4f
Merge pull request #133 from austin-hoover/env-tracker
austin-hoover Aug 7, 2026
d39c429
Envelope tracker: fix `get_transfer_matrix` and clean up/format examp…
austin-hoover Aug 9, 2026
f68bc9d
Modify get_transfer_matrix function (#135)
austin-hoover Aug 9, 2026
7cf6139
Merge pull request #140 from PyORBIT-Collaboration/main
austin-hoover Sep 3, 2026
317a502
Add getCharge() method to SyncParticle
austin-hoover Sep 3, 2026
4bf3f1b
Move transfer matrix definitions to orbit.utils.matrix
austin-hoover Sep 3, 2026
6511c23
Envelope stores SyncParticle, not Bunch
austin-hoover Sep 3, 2026
18dbc5f
Envelope now takes SyncParticle instead of Bunch in constructor
austin-hoover Sep 3, 2026
888b31c
Move get_matrix function to node method node.getMatrix()
austin-hoover Sep 3, 2026
ac1686a
Track using lattice.trackEnvelope
austin-hoover Sep 3, 2026
3bdda4d
Add to_bunch method and ability to construct Envelope directly from B…
austin-hoover Sep 3, 2026
ee26ce2
Fix charge sign in transfer matrix generator
austin-hoover Sep 3, 2026
2337519
Add charge +- in tests
austin-hoover Sep 3, 2026
9dcb25b
Construct envelope directly from bunch in sns linac example
austin-hoover Sep 3, 2026
f0ceffe
Fix return types and copy cov/centroid when copying envelope
austin-hoover Sep 3, 2026
1715292
Fix typo
austin-hoover Sep 3, 2026
523f3f7
Change default number of turns in sns ring example
austin-hoover Sep 3, 2026
fa09282
Merge branch 'PyORBIT-Collaboration:main' into env-tracker-lattice
austin-hoover Sep 18, 2026
1f1c7a2
Start on including matrix fitting in envelope tracker
austin-hoover Sep 21, 2026
962a8c8
Add `fit` option to `trackEnvelope` function
austin-hoover Oct 6, 2026
1977554
Update examples
austin-hoover Oct 6, 2026
31095ab
Simplify envelope tracking code
austin-hoover Oct 6, 2026
6043f7b
Merge pull request #2 from austin-hoover/env-tracker-lattice-fitting
austin-hoover Oct 6, 2026
9db3eca
Improve envelope history
austin-hoover Oct 6, 2026
8c2a4fa
Clean up envelope history
austin-hoover Oct 6, 2026
df9e158
Add synchronous particle info to cache_key, which determines if matri…
austin-hoover Oct 6, 2026
7ce9974
Copy synchronous particle when copying envelope
austin-hoover Oct 6, 2026
4d96bdc
Only use start-stop indices when checking lattice before envelope tra…
austin-hoover Oct 6, 2026
5bd57a5
Merge pull request #141 from austin-hoover/env-tracker-lattice
austin-hoover Oct 9, 2026
d41cee9
Merge pull request #156 from PyORBIT-Collaboration/main
austin-hoover Oct 12, 2026
502bd34
Merge pull request #161 from PyORBIT-Collaboration/main
austin-hoover Nov 3, 2026
c830de2
Merge pull request #165 from PyORBIT-Collaboration/main
austin-hoover Nov 10, 2026
64c9471
Refactor envelope tracking code (#170)
austin-hoover Nov 12, 2026
cc3cfd6
Merge pull request #171 from PyORBIT-Collaboration/main
austin-hoover Nov 12, 2026
4bd1a24
Temporary fix: openmp dependency
austin-hoover Nov 12, 2026
d459ef6
Merge branch 'main' into env-tracker
austin-hoover Nov 13, 2026
79a9448
Merge pull request #173 from austin-hoover/env-tracker
austin-hoover Nov 13, 2026
8385f20
`Envelope` no longer stores `SyncParticle` or `Bunch` (#175)
austin-hoover Nov 14, 2026
3998ff2
Add envelope tracker examples (#176)
austin-hoover Nov 15, 2026
7adec3d
Raise error if SC_Base_AccNode is encountered in envelope tracking
austin-hoover Nov 15, 2026
4474003
Remove test_sync_part.py
austin-hoover Nov 15, 2026
54d574f
Undo changes to syncpart.cc
austin-hoover Nov 15, 2026
b532f4a
Undo changes to syncpart.hh
austin-hoover Nov 15, 2026
60c5495
Pass already created lostbunch and matrix to fitting function
austin-hoover Nov 15, 2026
08a1592
Stored maps should increment envelope time/energy
austin-hoover Nov 15, 2026
8156f1d
fit and fallback should be false by default
austin-hoover Nov 15, 2026
ccb4aec
Add from_bunch function to Envelope
austin-hoover Nov 17, 2026
adab3ce
Update tests
austin-hoover Nov 17, 2026
3a7ce92
Update examples that construct envelope from bunch
austin-hoover Nov 17, 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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.DS_Store
.idea
build
PyORBIT.egg-info
.vscode
Expand Down
315 changes: 315 additions & 0 deletions examples/Envelope/fodo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,315 @@
"""Test 2D envelope tracker in FODO lattice."""

import argparse
import copy
import math
import os
import time
from pathlib import Path

import numpy as np
import matplotlib.pyplot as plt

from orbit.core.bunch import Bunch
from orbit.core.bunch import BunchTwissAnalysis
from orbit.core.spacecharge import SpaceChargeCalc2p5D
from orbit.bunch_utils import collect_bunch
from orbit.envelope import Envelope
from orbit.envelope import EnvelopeAnalysis
from orbit.lattice import AccLattice
from orbit.lattice import AccNode
from orbit.core.spacecharge import SpaceChargeCalc2p5D
from orbit.space_charge.sc2p5d import setSC2p5DAccNodes
from orbit.teapot import DriftTEAPOT
from orbit.teapot import QuadTEAPOT
from orbit.teapot import TEAPOT_Lattice
from orbit.teapot import TEAPOT_MATRIX_Lattice
from orbit.utils.consts import mass_proton

from plot import plot_rms_ellipse
from plot import plot_corner
from utils import sample_distribution
from utils import build_rotation_matrix_xy
from utils import project_cov_matrix

plt.style.use("style.mplstyle")


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--bunch-length", type=float, default=5.0)
parser.add_argument("--kin-energy", type=float, default=0.0025)
parser.add_argument("--intensity", type=float, default=5e9)

parser.add_argument("--dist", type=str, default="kv", choices=["kv", "waterbag", "gauss"])
parser.add_argument("--mismatch-x", type=float, default=0.0)
parser.add_argument("--mismatch-y", type=float, default=0.0)
parser.add_argument("--offset-x", type=float, default=0.0)
parser.add_argument("--offset-y", type=float, default=0.0)
parser.add_argument("--tilt", type=float, default=0)

parser.add_argument("--nslice", type=int, default=10)
parser.add_argument("--kq", type=float, default=0.25)

parser.add_argument("--nparts", type=int, default=100_000)
parser.add_argument("--turns", type=int, default=25)
parser.add_argument("--sc", type=int, default=0)
parser.add_argument("--fit", type=int, default=1)
return parser.parse_args()


def main(args: argparse.Namespace) -> None:
output_dir = os.path.join("outputs", Path(__file__).stem, time.strftime("%Y%m%d_%H%M%S"))
os.makedirs(output_dir, exist_ok=True)

# Create lattice
# ------------------------------------------------------------------------------

nodes = [
QuadTEAPOT(length=0.5, kq=+args.kq),
DriftTEAPOT(length=1.0),
QuadTEAPOT(length=1.0, kq=-args.kq),
DriftTEAPOT(length=1.0),
QuadTEAPOT(length=0.5, kq=+args.kq),
]

lattice = TEAPOT_Lattice()
for node in nodes:
node.setnParts(args.nslice)
node.setUsageFringeFieldIN(False)
node.setUsageFringeFieldOUT(False)
lattice.addNode(node)

lattice.initialize()

# Create envelope
# ------------------------------------------------------------------------------

# Create bunch
bunch = Bunch()
bunch.mass(mass_proton)
sync_part = bunch.getSyncParticle()
sync_part.kinEnergy(args.kin_energy)

# Find periodic lattice parameters
matrix_lattice = TEAPOT_MATRIX_Lattice(lattice, bunch)
matrix_lattice_params = matrix_lattice.getRingParametersDict()
alpha_x = matrix_lattice_params["alpha x"]
alpha_y = matrix_lattice_params["alpha y"]
beta_x = matrix_lattice_params["beta x [m]"]
beta_y = matrix_lattice_params["beta y [m]"]
eps_x = 0.25e-06
eps_y = eps_x

# Generate covariance matrix
cov_matrix = np.zeros((6, 6))
cov_matrix[0, 0] = eps_x * beta_x
cov_matrix[2, 2] = eps_y * beta_y
cov_matrix[0, 1] = cov_matrix[1, 0] = -eps_x * alpha_x
cov_matrix[2, 3] = cov_matrix[3, 2] = -eps_y * alpha_y
cov_matrix[1, 1] = eps_x * (1.0 + alpha_x**2) / beta_x
cov_matrix[3, 3] = eps_y * (1.0 + alpha_y**2) / beta_y
cov_matrix[4, 4] = args.bunch_length**2 / 12.0
cov_matrix[5, 5] = 0.0

# Tilt
if args.tilt:
rot_matrix = np.identity(6)
rot_matrix[:4, :4] = build_rotation_matrix_xy(angle=np.radians(args.tilt))
cov_matrix = np.linalg.multi_dot([rot_matrix, cov_matrix, rot_matrix.T])

# Mismatch
cov_matrix[0, 0] *= (1.0 + args.mismatch_x) ** 2
cov_matrix[2, 2] *= (1.0 + args.mismatch_y) ** 2
cov_matrix_init = np.copy(cov_matrix)

# Offset
centroid_init = np.zeros(6)
centroid_init[0] += args.offset_x
centroid_init[2] += args.offset_y

# Create envelope
envelope = Envelope(
kin_energy=sync_part.kinEnergy(),
mass=bunch.mass(),
charge=bunch.charge(),
time=sync_part.time(),
cov_matrix=cov_matrix_init,
centroid=centroid_init,
intensity=args.intensity,
)

# Track envelope
# ------------------------------------------------------------------------------

print("TRACK ENVELOPE")

envelope_sc = "2d" if args.sc else None

analysis = EnvelopeAnalysis(envelope)
history = {key: [] for key in ("xrms", "yrms", "xavg", "yavg")}
for turn in range(args.turns):
if turn > 0:
lattice.trackEnvelope(
envelope,
sc=envelope_sc,
fit=args.fit,
static=True,
)

rms = 1000.0 * analysis.rms()
mean = 1000.0 * analysis.centroid()
parameters = {"xrms": rms[0], "yrms": rms[1], "xavg": mean[0], "yavg": mean[2]}
for key, value in parameters.items():
history[key].append(value)
print(f"turn={turn}", parameters)

histories = {"envelope": history}

# Track bunch
# ------------------------------------------------------------------------------

print("TRACK BUNCH")

rng = np.random.default_rng()

particles = np.zeros((args.nparts, 6))
particles[:, :4] = sample_distribution(
size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name=args.dist
)
particles[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts)
particles += centroid_init[None, :6]

for i in range(particles.shape[0]):
bunch.addParticle(*particles[i])

if args.sc:
sc_calc = SpaceChargeCalc2p5D(128, 128, 1)
sc_path_length_min = 1.00e-06
sc_nodes = setSC2p5DAccNodes(lattice, sc_path_length_min, sc_calc)

bunch_size = bunch.getSizeGlobal()
bunch.macroSize(args.intensity / bunch_size)

history = {"xrms": [], "yrms": [], "xavg": [], "yavg": []}
for turn in range(args.turns):
if turn > 0:
lattice.trackBunch(bunch)

twiss_calc = BunchTwissAnalysis()
twiss_calc.computeBunchMoments(bunch, 2, 0, 0)

cov_matrix = np.zeros((6, 6))
for i in range(6):
for j in range(i + 1):
cov_matrix[i, j] = twiss_calc.getCorrelation(j, i)
cov_matrix[j, i] = cov_matrix[i, j]

xrms = 1000.0 * math.sqrt(cov_matrix[0, 0])
yrms = 1000.0 * math.sqrt(cov_matrix[2, 2])
xavg = 1000.0 * twiss_calc.getAverage(0)
yavg = 1000.0 * twiss_calc.getAverage(2)

print(f"turn={turn} xrms={xrms:0.3f} yrms={yrms:0.3f} xavg={xavg:0.3f} yavg={yavg:0.3f}")

history["xrms"].append(xrms)
history["yrms"].append(yrms)
history["xavg"].append(xavg)
history["yavg"].append(yavg)

histories["bunch"] = copy.deepcopy(history)

# Analysis
# ------------------------------------------------------------------------------

for history in histories.values():
for key in history:
history[key] = np.array(history[key])

# Print errors
for key in histories["envelope"]:
deltas = histories["bunch"][key] - histories["envelope"][key]
print("key:", key)
print("max_abs_delta:", np.max(np.abs(deltas)))
print("avg_abs_delta:", np.mean(np.abs(deltas)))

# Plot rms bunch sizes
for key in ["xrms", "yrms"]:
fig, ax = plt.subplots(figsize=(5, 3))
for i, model in enumerate(["envelope", "bunch"]):
color = ["black", "red"][i]
lw = [None, 0][i]
ax.plot(histories[model][key], marker=".", lw=lw, color=color, label=model)
ax.set_ylim(0.0, ax.get_ylim()[1] * 2.0)
ax.set_xlabel("Turn")
ax.set_ylabel("RMS [mm]")
ax.legend(loc="upper right")
plt.savefig(os.path.join(output_dir, f"fig_{key}"))
plt.close()

# Plot centroids
for key in ["xavg", "yavg"]:
fig, ax = plt.subplots(figsize=(5, 3))
for i, model in enumerate(["envelope", "bunch"]):
color = ["black", "red"][i]
lw = [None, 0][i]
ax.plot(histories[model][key], marker=".", lw=lw, color=color, label=model)
ax.set_ylim(-5.0, 5.0)
ax.set_xlabel("Turn")
ax.set_ylabel("AVG [mm]")
ax.legend(loc="upper right")
plt.savefig(os.path.join(output_dir, f"fig_{key}"))
plt.close()

# Collect bunch/envelope data on final turn.
particles = collect_bunch(bunch)["coords"]
particles[:, :4] *= 1000.0

env_cov_matrix = EnvelopeAnalysis(envelope).covariance()
env_cov_matrix[:4, :4] *= 1000.0**2

env_centroid = envelope.centroid
env_centroid[:4] *= 1000.0

xmax = 4.0 * np.std(particles, axis=0)
limits = list(zip(-xmax, xmax))
labels = ["x [mm]", "xp [mrad]", "y [mm]", "yp [mrad]", "z [m]", "dE [GeV]"]

# Plot x-x'
fig, ax = plt.subplots(figsize=(4, 4))
ax.hist2d(particles[:, 0], particles[:, 1], bins=100, range=[limits[0], limits[1]])
plot_rms_ellipse(
env_cov_matrix[0:2, 0:2],
center=(env_centroid[0], env_centroid[1]),
level=2.0,
color="red",
ax=ax,
)
ax.set_xlabel(labels[0])
ax.set_ylabel(labels[1])
plt.savefig(os.path.join(output_dir, "fig_dist_x_xp"))
plt.close()

# Plot corner
fig, axs = plot_corner(
particles,
limits=limits,
bins=100,
labels=labels,
)
for i in range(6):
for j in range(i):
env_cov_matrix_proj = project_cov_matrix(env_cov_matrix, axis=(j, i))
plot_rms_ellipse(
env_cov_matrix_proj,
center=(env_centroid[j], env_centroid[i]),
level=2.0,
color="red",
ax=axs[i, j],
)
plt.savefig(os.path.join(output_dir, "fig_dist_corner"))
plt.close()


if __name__ == "__main__":
main(parse_args())
51 changes: 51 additions & 0 deletions examples/Envelope/fodo_match.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Compute periodic KV envelope in FODO lattice."""

import argparse
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

from utils import make_fodo
from utils import matched_envelope
from utils import make_output_dir
from utils import track_history
from utils import sample_distribution


def main(args: argparse.Namespace) -> None:
output_dir = make_output_dir(__file__)
np.random.seed(23)
plt.style.use("style.mplstyle")

lattice, _ = make_fodo(args.kq, args.nslice)
envelope, residual = matched_envelope(lattice, args.intensity)

initial = envelope.copy()
history, _ = track_history(lattice, envelope.copy(), sc="2d", static=True)

closure = []
for _ in range(args.turns):
lattice.trackEnvelope(envelope, sc="2d", fit=False, static=True)
closure.append(
np.linalg.norm(envelope.cov_matrix[:4, :4] - initial.cov_matrix[:4, :4])
/ np.linalg.norm(initial.cov_matrix[:4, :4])
)
print(f"Matching residual: {residual:.3g}; maximum relative closure error: {max(closure):.3g}")

fig, ax = plt.subplots(figsize=(4, 3))
ax.plot(history["s"], 1e3 * np.sqrt(history["covariance"][:, 0, 0]), label="x")
ax.plot(history["s"], 1e3 * np.sqrt(history["covariance"][:, 2, 2]), label="y")
ax.set(xlabel="s [m]", ylabel="RMS size [mm]")
fig.savefig(output_dir / "matching.png")
plt.close(fig)


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--kq", type=float, default=0.25)
parser.add_argument("--intensity", type=float, default=5e9)
parser.add_argument("--nslice", type=int, default=20)
parser.add_argument("--nparts", type=int, default=10000)
parser.add_argument("--turns", type=int, default=20)
main(parser.parse_args())
Loading
Loading