From 0a0b2d2bed4ca3926e6a08e99d88d0164c691db6 Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Tue, 30 Jun 2026 10:30:58 -0400 Subject: [PATCH 01/42] Implement envelope tracker (#112) * 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 --- .gitignore | 2 + examples/Envelope/plot.py | 129 + examples/Envelope/sns_linac/diagnostics.py | 56 + .../Envelope/sns_linac/inputs/sns_linac.xml | 13475 ++++++++++++++++ examples/Envelope/sns_linac/style.mplstyle | 8 + examples/Envelope/sns_linac/test_sns_linac.py | 297 + .../Envelope/sns_ring/inputs/sns_ring.lat | 768 + examples/Envelope/sns_ring/style.mplstyle | 8 + examples/Envelope/sns_ring/test_sns_ring.py | 389 + .../Envelope/sns_ring/test_sns_ring_speed.py | 143 + examples/Envelope/style.mplstyle | 8 + examples/Envelope/test_env_2d_fodo.py | 316 + examples/Envelope/test_env_2d_fodo_speed.py | 145 + examples/Envelope/test_env_3d_drift.py | 275 + examples/Envelope/utils.py | 60 + py/orbit/envelope/__init__.py | 2 + py/orbit/envelope/envelope.py | 235 + py/orbit/envelope/matrix.py | 443 + py/orbit/envelope/meson.build | 14 + py/orbit/envelope/track.py | 232 + py/orbit/envelope/utils.py | 99 + py/orbit/meson.build | 1 + py/orbit/py_linac/lattice/__init__.py | 7 +- py/orbit/teapot/__init__.py | 6 + tests/py/orbit/test_env.py | 383 + 25 files changed, 17499 insertions(+), 2 deletions(-) create mode 100644 examples/Envelope/plot.py create mode 100644 examples/Envelope/sns_linac/diagnostics.py create mode 100644 examples/Envelope/sns_linac/inputs/sns_linac.xml create mode 100644 examples/Envelope/sns_linac/style.mplstyle create mode 100755 examples/Envelope/sns_linac/test_sns_linac.py create mode 100644 examples/Envelope/sns_ring/inputs/sns_ring.lat create mode 100644 examples/Envelope/sns_ring/style.mplstyle create mode 100644 examples/Envelope/sns_ring/test_sns_ring.py create mode 100644 examples/Envelope/sns_ring/test_sns_ring_speed.py create mode 100644 examples/Envelope/style.mplstyle create mode 100644 examples/Envelope/test_env_2d_fodo.py create mode 100644 examples/Envelope/test_env_2d_fodo_speed.py create mode 100644 examples/Envelope/test_env_3d_drift.py create mode 100644 examples/Envelope/utils.py create mode 100644 py/orbit/envelope/__init__.py create mode 100644 py/orbit/envelope/envelope.py create mode 100644 py/orbit/envelope/matrix.py create mode 100644 py/orbit/envelope/meson.build create mode 100644 py/orbit/envelope/track.py create mode 100644 py/orbit/envelope/utils.py create mode 100644 tests/py/orbit/test_env.py diff --git a/.gitignore b/.gitignore index 4bd2411b..8545b3b7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +.DS_Store +.idea build PyORBIT.egg-info .vscode diff --git a/examples/Envelope/plot.py b/examples/Envelope/plot.py new file mode 100644 index 00000000..f493b108 --- /dev/null +++ b/examples/Envelope/plot.py @@ -0,0 +1,129 @@ +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.patches as patches + + +def calc_rms_ellipse_params(cov_matrix: np.ndarray) -> tuple[float, float, float]: + """Return rms ellipse dimensions and orientation.""" + i, j = (0, 1) + + sii = cov_matrix[i, i] + sjj = cov_matrix[j, j] + sij = cov_matrix[i, j] + + angle = -0.5 * np.arctan2(2.0 * sij, sii - sjj) + + _sin = np.sin(angle) + _cos = np.cos(angle) + _sin2 = _sin**2 + _cos2 = _cos**2 + + c1 = np.sqrt(abs(sii * _cos2 + sjj * _sin2 - 2 * sij * _sin * _cos)) + c2 = np.sqrt(abs(sii * _sin2 + sjj * _cos2 + 2 * sij * _sin * _cos)) + + return (c1, c2, angle) + + +def plot_ellipse( + r1: float = 1.0, + r2: float = 1.0, + angle: float = 0.0, + center: tuple[float, float] = None, + ax=None, + **kws, +): + kws.setdefault("fill", False) + kws.setdefault("color", "black") + kws.setdefault("lw", 1.25) + + if center is None: + center = (0.0, 0.0) + + d1 = r1 * 2.0 + d2 = r2 * 2.0 + angle = -np.degrees(angle) + + ax.add_patch(patches.Ellipse(center, d1, d2, angle=angle, **kws)) + return ax + + +def plot_rms_ellipse( + cov_matrix: np.ndarray, + level: float = 1.0, + ax=None, + **ellipse_kws, +): + """Plot rms ellipse from 2 x 2 covariance matrix.""" + r1, r2, angle = calc_rms_ellipse_params(cov_matrix) + plot_ellipse(r1 * level, r2 * level, angle=angle, ax=ax, **ellipse_kws) + return ax + + +def plot_corner( + particles: np.ndarray, + limits: list[tuple[float, float]] = None, + bins: int = 64, + labels: list[str] = None, + blur: float = None, +) -> tuple: + """Generate corner plot.""" + ndim = particles.shape[1] + + if limits is None: + xmax = np.max(particles, axis=0) + xmin = np.min(particles, axis=0) + limits = list(zip(xmin, xmax)) + + if labels is None: + labels = ndim * [""] + + fig, axs = plt.subplots(ncols=ndim, nrows=ndim, sharex=None, sharey=None, figsize=(8, 8)) + for i in range(ndim): + for j in range(ndim): + axis = (j, i) + ax = axs[i, j] + if i > j: + values, edges = np.histogramdd( + particles[:, axis], bins=bins, range=[limits[k] for k in axis] + ) + if blur: + values = scipy.ndimage.gaussian_filter(values, sigma=blur) + ax.pcolormesh( + edges[0], + edges[1], + values.T, + linewidth=0.0, + rasterized=True, + shading="auto", + ) + elif i == j: + values, edges = np.histogram(particles[:, i], bins=bins, range=limits[i]) + if blur: + values = scipy.ndimage.gaussian_filter(values, sigma=blur) + ax.stairs(values, edges, lw=1.5, color="black") + else: + ax.axis("off") + + for i in range(0, ndim - 1): + for j in range(0, ndim): + axs[i, j].set_xticklabels([]) + for i in range(0, ndim): + for j in range(1, ndim): + axs[i, j].set_yticklabels([]) + + for ax in axs.flat: + for loc in ["top", "right"]: + ax.spines[loc].set_visible(False) + + for i, label in enumerate(labels): + axs[-1, i].set_xlabel(label) + for i, label in enumerate(labels[1:], start=1): + axs[i, 0].set_ylabel(label) + + axs[0, 0].set_yticklabels([]) + axs[0, 0].set_ylabel(None) + + fig.align_ylabels() + fig.align_xlabels() + + return fig, axs diff --git a/examples/Envelope/sns_linac/diagnostics.py b/examples/Envelope/sns_linac/diagnostics.py new file mode 100644 index 00000000..7edfebdd --- /dev/null +++ b/examples/Envelope/sns_linac/diagnostics.py @@ -0,0 +1,56 @@ +import numpy as np + +from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis + + +class BunchMonitor: + def __init__(self) -> None: + self.twiss_calc = BunchTwissAnalysis() + self.position_start = 0.0 + + self.history = {} + self.history["position"] = [] + self.history["rms_x"] = [] + self.history["rms_y"] = [] + self.history["rms_z"] = [] + self.history["kin_energy"] = [] + + def __call__(self, params_dict: dict) -> None: + bunch = params_dict["bunch"] + node = params_dict["node"] + position = params_dict["path_length"] + + if params_dict["old_pos"] == position: + return + if params_dict["old_pos"] + params_dict["pos_step"] > position: + return + params_dict["old_pos"] = position + params_dict["count"] += 1 + + sync_part = bunch.getSyncParticle() + + self.twiss_calc.analyzeBunch(bunch) + + cov_matrix = np.zeros((6, 6)) + for i in range(6): + for j in range(6): + cov_matrix[i, j] = cov_matrix[j, i] = self.twiss_calc.getCorrelation(i, j) + + xrms = 1000.0 * np.sqrt(cov_matrix[0, 0]) + yrms = 1000.0 * np.sqrt(cov_matrix[2, 2]) + zrms = 1000.0 * np.sqrt(cov_matrix[4, 4]) + + message = "" + message += " s={:0.3f}".format(position + self.position_start) + message += " xrms={:0.3f}".format(xrms) + message += " yrms={:0.3f}".format(yrms) + message += " zrms={:0.3f}".format(zrms) + message += " node={}".format(node.getName()) + print(message) + + self.history["position"].append(position + self.position_start) + self.history["rms_x"].append(xrms) + self.history["rms_y"].append(yrms) + self.history["rms_z"].append(zrms) + self.history["kin_energy"].append(sync_part.kinEnergy()) diff --git a/examples/Envelope/sns_linac/inputs/sns_linac.xml b/examples/Envelope/sns_linac/inputs/sns_linac.xml new file mode 100644 index 00000000..62cdbf41 --- /dev/null +++ b/examples/Envelope/sns_linac/inputs/sns_linac.xml @@ -0,0 +1,13475 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Envelope/sns_linac/style.mplstyle b/examples/Envelope/sns_linac/style.mplstyle new file mode 100644 index 00000000..71f36605 --- /dev/null +++ b/examples/Envelope/sns_linac/style.mplstyle @@ -0,0 +1,8 @@ +axes.linewidth: 1.25 +axes.titlesize: "medium" +image.cmap: "Greys" +figure.constrained_layout.use: True +savefig.dpi: 300 +savefig.format: "png" +xtick.minor.visible: True +ytick.minor.visible: True diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py new file mode 100755 index 00000000..045e6155 --- /dev/null +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -0,0 +1,297 @@ +"""SNS linac benchmark. + +Note that there is no analytic benchmark with 3D space charge since there +is no 3D KV equilibrium distribution. For comparison to particle tracking, +we use the `SpaceChargeCalcUnifEllipse` space charge calculator, which +approximates the charge distribution as a uniform-density ellipsoid with +the same x-y-z covariance matrix as the real charge distribution. (It +currently assumes an upright ellipsoid.) +""" + +import argparse +import math +import os +import random +import sys + +import numpy as np +import matplotlib.pyplot as plt + +from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis +from orbit.core.bunch import SyncParticle +from orbit.core.linac import BaseRfGap +from orbit.core.linac import MatrixRfGap +from orbit.core.spacecharge import SpaceChargeCalcUnifEllipse +from orbit.core.spacecharge import SpaceChargeCalc3D +from orbit.bunch_generators import TwissContainer +from orbit.bunch_generators import WaterBagDist3D +from orbit.bunch_generators import GaussDist3D +from orbit.bunch_generators import KVDist3D +from orbit.bunch_utils import collect_bunch +from orbit.envelope import Envelope +from orbit.envelope import EnvelopeTracker +from orbit.lattice import AccLattice +from orbit.lattice import AccNode +from orbit.lattice import AccActionsContainer +from orbit.py_linac.linac_parsers import SNS_LinacLatticeFactory +from orbit.py_linac.lattice import LinacAccLattice +from orbit.space_charge.sc3d import setSC3DAccNodes +from orbit.space_charge.sc3d import setUniformEllipsesSCAccNodes +from orbit.utils.consts import mass_proton +from orbit.utils.consts import mass_electron +from orbit.utils.consts import charge_electron + +# local +from diagnostics import BunchMonitor + +sys.path.append("..") +from plot import plot_corner +from plot import plot_rms_ellipse +from utils import project_cov_matrix + +plt.style.use("style.mplstyle") + + +# Parse arguments +# -------------------------------------------------------------------------------- + +parser = argparse.ArgumentParser() +parser.add_argument("--dist", type=str, default="kv") +parser.add_argument("--nparts", type=int, default=20_000) +parser.add_argument("--sc", type=int, default=0) +parser.add_argument("--sc-model", type=str, default="ellipsoid") +parser.add_argument("--sc-path-length-min", type=float, default=0.01) +parser.add_argument("--current", type=float, default=0.038) +parser.add_argument("--show", type=int, default=0) +parser.add_argument("--seq-stop", type=str, default="CCL2") +args = parser.parse_args() + + +# Setup +# -------------------------------------------------------------------------------- + +output_dir = "outputs" +os.makedirs(output_dir, exist_ok=True) + +random.seed(23) + + +# Bunch +# -------------------------------------------------------------------------------- + +kin_energy = 0.0025 # [GeV] +mass = mass_proton + 2.0 * mass_electron +frequency = 402.5e06 +charge = -1.0 +intensity = args.current / frequency / (math.fabs(charge) * charge_electron) + +bunch = Bunch() +bunch.mass(mass) +bunch.macroSize(intensity / args.nparts) +bunch.charge(charge) + +sync_part = bunch.getSyncParticle() +sync_part.kinEnergy(kin_energy) +sync_part.time(0.0) + +alpha_x, beta_x, eps_x = (-1.962, 0.183, 2.874e-06) +alpha_y, beta_y, eps_y = (+1.768, 0.162, 2.874e-06) +alpha_z, beta_z, eps_z = (-0.0196, 116.414, 1.651e-08) + +twiss_x = TwissContainer(alpha_x, beta_x, eps_x) +twiss_y = TwissContainer(alpha_y, beta_y, eps_y) +twiss_z = TwissContainer(alpha_z, beta_z, eps_z) + +if args.dist == "waterbag": + dist = WaterBagDist3D(twiss_x, twiss_y, twiss_z) +elif args.dist == "kv": + dist = KVDist3D(twiss_x, twiss_y, twiss_z) +elif args.dist == "gauss": + dist = GaussDist3D(twiss_x, twiss_y, twiss_z) +else: + raise ValueError("Unknown distribution '{}'".format(args.dist)) + +for _ in range(args.nparts): + bunch.addParticle(*dist.getCoordinates()) + +# Lattice +# -------------------------------------------------------------------------------- + +seq_names = [ + "MEBT", + "DTL1", + "DTL2", + "DTL3", + "DTL4", + "DTL5", + "DTL6", + "CCL1", + "CCL2", + "CCL3", + "CCL4", + "SCLMed", + "SCLHigh", + "HEBT1", + "HEBT2", +] +if args.seq_stop: + index = seq_names.index(args.seq_stop) + 1 + seq_names = seq_names[:index] + +sns_linac_factory = SNS_LinacLatticeFactory() +sns_linac_factory.setMaxDriftLength(args.sc_path_length_min) +lattice = sns_linac_factory.getLinacAccLattice(seq_names, "inputs/sns_linac.xml") + +for node in lattice.getNodes(): + try: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + except: + pass + +rf_gaps = lattice.getRF_Gaps() +for rf_gap in rf_gaps: + rf_gap.setCppGapModel(MatrixRfGap()) + +for index, node in enumerate(lattice.getNodes()): + print(index, type(node), node.getName()) + +lattice.trackDesignBunch(bunch) + + +# Track envelope +# -------------------------------------------------------------------------------- + +twiss_calc = BunchTwissAnalysis() +twiss_calc.analyzeBunch(bunch) + +cov_matrix = np.zeros((6, 6)) +for i in range(6): + for j in range(6): + cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) + +envelope = Envelope(bunch=bunch, cov_matrix=cov_matrix, intensity=intensity) + +tracker = EnvelopeTracker(lattice, sc=("3d" if args.sc else None)) + +histories = {} +histories["envelope"] = tracker.track_history(envelope) + + +# Track bunch +# -------------------------------------------------------------------------------- + +lattice.trackDesignBunch(bunch) + +if args.sc: + if args.sc_model == "ellipsoid": + n_ellipsoids = 1 + sc_calc = SpaceChargeCalcUnifEllipse(n_ellipsoids) + sc_nodes = setUniformEllipsesSCAccNodes(lattice, args.sc_path_length_min, sc_calc) + if args.sc_model == "3d": + sc_calc = SpaceChargeCalc3D(64, 64, 64) + sc_nodes = setSC3DAccNodes(lattice, args.sc_path_length_min, sc_calc) + + +monitor = BunchMonitor() + +action_container = AccActionsContainer() +action_container.addAction(monitor, AccActionsContainer.ENTRANCE) +action_container.addAction(monitor, AccActionsContainer.EXIT) + +params_dict = {"old_pos": -1.0, "count": 0, "pos_step": args.sc_path_length_min} + +lattice.trackBunch(bunch, paramsDict=params_dict, actionContainer=action_container) + +histories["bunch"] = monitor.history + + +# Analysis +# -------------------------------------------------------------------------------- + + +# History: rms +for mode in histories: + for key in histories[mode]: + histories[mode][key] = np.array(histories[mode][key]) + +plot_kws = {} +plot_kws["bunch"] = dict(color="black", lw=0, marker=".", ms=2) +plot_kws["envelope"] = dict(color="red", lw=0, marker=".", ms=1) + +fig, axs = plt.subplots(nrows=3, figsize=(10, 5), sharex=True, constrained_layout=True) +for mode in ["bunch", "envelope"]: + history = histories[mode] + for ax, key in zip(axs, ["rms_x", "rms_y", "rms_z"]): + ax.plot(history["position"], history[key], **plot_kws[mode], label=mode) +for ax in axs: + ax.legend(loc="lower right") +axs[0].set_ylabel("x rms [mm]") +axs[1].set_ylabel("y rms [mm]") +axs[2].set_ylabel("z rms [mm]") +axs[2].set_xlabel("s [m]") +plt.savefig(os.path.join(output_dir, "fig_history_rms.png")) +if args.show: + plt.show() +plt.close() + +# History: energy +fig, ax = plt.subplots(figsize=(5, 3)) +for mode in ["bunch", "envelope"]: + history = histories[mode] + ax.plot(history["position"], history["kin_energy"], **plot_kws[mode], label=mode) +ax.legend(loc="lower right") +ax.set_ylabel("energy [GeV]") +ax.set_xlabel("s [m]") +plt.savefig(os.path.join(output_dir, "fig_history_energy.png")) +plt.close() + +# Collect bunch/envelope data +particles = collect_bunch(bunch)["coords"] +particles *= 1e3 + +env_cov_matrix = envelope.cov_matrix +env_cov_matrix *= 1e6 + +env_centroid = envelope.centroid +env_centroid *= 1e3 + +xmax = 4.0 * np.std(particles, axis=0) +limits = list(zip(-xmax, xmax)) +labels = ["x [mm]", "xp [mrad]", "y [mm]", "yp [mrad]", "z [mm]", "dE [MeV]"] + +# 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() diff --git a/examples/Envelope/sns_ring/inputs/sns_ring.lat b/examples/Envelope/sns_ring/inputs/sns_ring.lat new file mode 100644 index 00000000..cbfb8df1 --- /dev/null +++ b/examples/Envelope/sns_ring/inputs/sns_ring.lat @@ -0,0 +1,768 @@ +kvx12 := kdc; +kdc = -3.412580596; +kta11c12 := 0; +brho := 1e9*(pc/c); +pc := sqrt(ek*(ek+2*e0)); +ek := 0.8; +e0 := 0.93827231; +c := 299792458; +khx13 := kfc; +kfc = 3.161218767; +kta10b13 := 0; +kdhta13 := 0; +kdvta13 := 0; +vkck12 := 0; +hkck12 := 0; +vkck13 := 0; +hkck13 := 0; +kdvtb1 := 0; +ksc_b01 := 0; +kssb1_9 = 0; +kvx1 := kdee; +kdee = -2.579970923; +ktb1_9 := 0; +ksv1 := 0; +ksc_b02 := 0; +kssb2_8 = 0; +khx2 := kf; +kf = 3.388342139; +ktb2d8 := 0; +ksh2 := 0; +kdvtb3 := 0; +ksc_b03 := 0; +kvx3 := kd; +kd = -3.731394588; +ktb357 := 0; +ksv3 := chrm3; +chrm3 := 0; +kdhtb4 := 0; +khx4 := kf26; +kf26 := kf*(lf/lf26); +lf := 0.25; +lf26 := 0.2705; +kta4b6 := 0; +ksh4 := chrm4; +chrm4 := 0; +ksv5 := chrm5; +chrm5 := 0; +kvx5 := kd; +kdvtb5 := 0; +ksc_b05 := 0; +ksh6 := chrm6; +chrm6 := 0; +khx6 := kf26; +kdhtb6 := 0; +ksv7 := chrm7; +chrm7 := chrm3; +kvx7 := kd; +kdvtb7 := 0; +ksc_b07 := 0; +ko_b08 := 0; +khx8 := kf; +kdhtb8 := 0; +ksc_b08 := 0; +ko_b09 := 0; +kvx9 := kdee; +kdvtb9 := 0; +ksc_b09 := 0; +kdhtb10 := 0; +kdvtb10 := 0; +khx10 := kfc; +kvx11 := kdc; +ktb11d12 := 0; +kdhtb13 := 0; +kdvtb13 := 0; +kdvtc1 := 0; +ksc_c01 := 0; +kssc1_9 = 0; +ktc1_9 := 0; +kdhtc2 := 0; +kssc2_8 = 0; +ksc_c02 := 0; +kta2c8 := 0; +kdvtc3 := 0; +ksc_c03 := 0; +ktc357 := 0; +kdhtc4 := 0; +ktc4d6 := 0; +kdvtc5 := 0; +ksc_c05 := 0; +kdhtc6 := 0; +kdvtc7 := 0; +ksc_c07 := 0; +ko_c08 := 0; +kdhtc8 := 0; +ksc_c08 := 0; +ko_c09 := 0; +kdvtc9 := 0; +ksc_c09 := 0; +kdhtc10 := 0; +kdvtc10 := 0; +ktc10d13 := 0; +kdhtc13 := 0; +kdvtc13 := 0; +ksisol := 1.22174*kssol; +kssol := solfield/brho; +solfield = 0; +kdvtd1 := 0; +ksc_d01 := 0; +kssd1_9 = 0; +ktd1_9 := 0; +kdhtd2 := 0; +ksc_d02 := 0; +kssd2_8 = 0; +kdvtd3 := 0; +ksc_d03 := 0; +ktd357 := 0; +lsv3 := lsxt; +lsxt := 0.317; +kdhtd4 := 0; +kdvtd5 := 0; +ksc_d05 := 0; +kdhtd6 := 0; +kdvtd7 := 0; +ksc_d07 := 0; +ko_d08 := 0; +kdhtd8 := 0; +ksc_d08 := 0; +ko_d09 := 0; +kdvtd9 := 0; +ksc_d09 := 0; +kdhtd10 := 0; +kdvtd10 := 0; +kdhtd13 := 0; +kdvtd13 := 0; +kdvta1 := 0; +ksc_a01 := 0; +kssa1_9 = 0; +kta1_9 := 0; +kdhta2 := 0; +ksc_a02 := 0; +kssa2_8 = 0; +kdvta3 := 0; +ksc_a03 := 0; +kta357 := 0; +kdhta4 := 0; +kdvta5 := 0; +kdhta6 := 0; +kdvta7 := 0; +ksc_a07 := 0; +ko_a08 := 0; +kdhta8 := 0; +ksc_a08 := 0; +ko_a09 := 0; +kdvta9 := 0; +ksc_a09 := 0; +hkck10 := 0; +vkck10 := 0; +hkck11 := 0; +vkck11 := 0; +kdhta10 := 0; +kdvta10 := 0; +injm1: marker; +dh_a12: sbend,l:= 0.9903829659,angle:= 0.0436,e1:= -0.003,e2:= 0.0466; +dh_a13: sbend,l:= 0.8903221964,angle:= -0.0466,e1:= -0.0466,e2:= -6.938893904e-18; +qtv_a12: quadrupole,l:= 0.533,k1:=( kvx12 + kta11c12 ) / brho ; +injm4: marker; +qth_a13: quadrupole,l:= 0.673,k1:=( khx13 + kta10b13 ) / brho ; +bpm_a13: monitor; +dchv_a13: kicker,l:= 0,hkick:=kdhta13 ,vkick:=kdvta13 ; +ikickv_a12: vkicker,l:= 0.428,kick:=vkck12 ; +ikickh_a12: hkicker,l:= 0.428,kick:=hkck12 ; +ikickv_a13: vkicker,l:= 0.839,kick:=vkck13 ; +ikickh_a13: hkicker,l:= 0.839,kick:=hkck13 ; +injm2: marker; +dmcv_b01: vkicker,l:= 0,kick:=kdvtb1 ; +qsc_b01: multipole,knl:={ 0,ksc_b01 }; +ssxc_b01: multipole,ksl:={ 0, 0,kssb1_9 }; +bpm_b01: monitor; +qtv_b01: quadrupole,l:= 0.5,k1:=( kvx1 + ktb1_9 ) / brho ; +scv_b01: sextupole,l:= 0.354,k2:=ksv1 ; +dh_b01: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmch_b02: hkicker,l:= 0,kick:= 0; +qsc_b02: multipole,knl:={ 0,ksc_b02 }; +ssxc_b02: multipole,ksl:={ 0, 0,kssb2_8 }; +bpm_b02: monitor; +qth_b02: quadrupole,l:= 0.5,k1:=( khx2 + ktb2d8 ) / brho ; +sch_b02: sextupole,l:= 0.354,k2:=ksh2 ; +dh_b02: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmcv_b03: vkicker,l:= 0,kick:=kdvtb3 ; +qsc_b03: multipole,knl:={ 0,ksc_b03 }; +bpm_b03: monitor; +qtv_b03: quadrupole,l:= 0.5,k1:=( kvx3 + ktb357 ) / brho ; +sv_b03: sextupole,l:= 0.317,k2:=ksv3 ; +dh_b03: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmch_b04: hkicker,l:= 0,kick:=kdhtb4 ; +bpm_b04: monitor; +qth_b04: quadrupole,l:= 0.541,k1:=( khx4 - kta4b6 ) / brho ; +sh_b04: sextupole,l:= 0.33,k2:=ksh4 ; +dh_b04: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sv_b05: sextupole,l:= 0.317,k2:=ksv5 ; +qtv_b05: quadrupole,l:= 0.5,k1:=( kvx5 + ktb357 ) / brho ; +bpm_b05: monitor; +dmcv_b05: vkicker,l:= 0,kick:=kdvtb5 ; +qsc_b05: multipole,knl:={ 0,ksc_b05 }; +dh_b06: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sh_b06: sextupole,l:= 0.33,k2:=ksh6 ; +qth_b06: quadrupole,l:= 0.541,k1:=( khx6 - kta4b6 ) / brho ; +bpm_b06: monitor; +dmch_b06: hkicker,l:= 0,kick:=kdhtb6 ; +dh_b07: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sv_b07: sextupole,l:= 0.317,k2:=ksv7 ; +qtv_b07: quadrupole,l:= 0.5,k1:=( kvx7 + ktb357 ) / brho ; +bpm_b07: monitor; +dmcv_b07: vkicker,l:= 0,kick:=kdvtb7 ; +qsc_b07: multipole,knl:={ 0,ksc_b07 }; +dh_b08: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +oct_b08: octupole,l:= 0.33,k3:=ko_b08 ; +qth_b08: quadrupole,l:= 0.5,k1:=( khx8 + ktb2d8 ) / brho ; +bpm_b08: monitor; +dmch_b08: hkicker,l:= 0,kick:=kdhtb8 ; +qsc_b08: multipole,knl:={ 0,ksc_b08 }; +ssxc_b08: multipole,ksl:={ 0, 0,kssb2_8 }; +dh_b09: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +oct_b09: octupole,l:= 0.33,k3:=ko_b09 ; +qtv_b09: quadrupole,l:= 0.5,k1:=( kvx9 + ktb1_9 ) / brho ; +bpm_b09: monitor; +dmcv_b09: vkicker,l:= 0,kick:=kdvtb9 ; +qsc_b09: multipole,knl:={ 0,ksc_b09 }; +ssxc_b09: multipole,ksl:={ 0, 0,kssb1_9 }; +dchv_b10: kicker,l:= 0,hkick:=kdhtb10 ,vkick:=kdvtb10 ; +bpm_b10: monitor; +qth_b10: quadrupole,l:= 0.673,k1:=( khx10 - kta10b13 ) / brho ; +qtv_b11: quadrupole,l:= 0.533,k1:=( kvx11 + ktb11d12 ) / brho ; +qtv_b12: quadrupole,l:= 0.533,k1:=( kvx12 + ktb11d12 ) / brho ; +qth_b13: quadrupole,l:= 0.673,k1:=( khx13 - kta10b13 ) / brho ; +bpm_b13: monitor; +dchv_b13: kicker,l:= 0,hkick:=kdhtb13 ,vkick:=kdvtb13 ; +dampkicker1: marker; +dampkicker2: marker; +qmmkicker: marker; +tunekicker: marker; +dmcv_c01: vkicker,l:= 0,kick:=kdvtc1 ; +qsc_c01: multipole,knl:={ 0,ksc_c01 }; +ssxc_c01: multipole,ksl:={ 0, 0,kssc1_9 }; +bpm_c01: monitor; +qtv_c01: quadrupole,l:= 0.5,k1:=( kvx1 + ktc1_9 ) / brho ; +scv_c01: sextupole,l:= 0.354,k2:=ksv1 ; +dh_c01: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmch_c02: hkicker,l:= 0,kick:=kdhtc2 ; +ssxc_c02: multipole,ksl:={ 0, 0,kssc2_8 }; +qsc_c02: multipole,knl:={ 0,ksc_c02 }; +bpm_c02: monitor; +qth_c02: quadrupole,l:= 0.5,k1:=( khx2 + kta2c8 ) / brho ; +sch_c02: sextupole,l:= 0.354,k2:=ksh2 ; +dh_c02: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmcv_c03: vkicker,l:= 0,kick:=kdvtc3 ; +qsc_c03: multipole,knl:={ 0,ksc_c03 }; +bpm_c03: monitor; +qtv_c03: quadrupole,l:= 0.5,k1:=( kvx3 + ktc357 ) / brho ; +sv_c03: sextupole,l:= 0.317,k2:=ksv3 ; +dh_c03: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmch_c04: hkicker,l:= 0,kick:=kdhtc4 ; +bpm_c04: monitor; +qth_c04: quadrupole,l:= 0.541,k1:=( khx4 + ktc4d6 ) / brho ; +sh_c04: sextupole,l:= 0.33,k2:=ksh4 ; +dh_c04: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sv_c05: sextupole,l:= 0.317,k2:=ksv5 ; +qtv_c05: quadrupole,l:= 0.5,k1:=( kvx5 + ktc357 ) / brho ; +bpm_c05: monitor; +dmcv_c05: vkicker,l:= 0,kick:=kdvtc5 ; +qsc_c05: multipole,knl:={ 0,ksc_c05 }; +dh_c06: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sh_c06: sextupole,l:= 0.33,k2:=ksh6 ; +qth_c06: quadrupole,l:= 0.541,k1:=( khx6 + ktc4d6 ) / brho ; +bpm_c06: monitor; +dmch_c06: hkicker,l:= 0,kick:=kdhtc6 ; +dh_c07: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sv_c07: sextupole,l:= 0.317,k2:=ksv7 ; +qtv_c07: quadrupole,l:= 0.5,k1:=( kvx7 + ktc357 ) / brho ; +bpm_c07: monitor; +dmcv_c07: vkicker,l:= 0,kick:=kdvtc7 ; +qsc_c07: multipole,knl:={ 0,ksc_c07 }; +dh_c08: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +oct_c08: octupole,l:= 0.33,k3:=ko_c08 ; +qth_c08: quadrupole,l:= 0.5,k1:=( khx8 + kta2c8 ) / brho ; +bpm_c08: monitor; +dmch_c08: hkicker,l:= 0,kick:=kdhtc8 ; +qsc_c08: multipole,knl:={ 0,ksc_c08 }; +ssxc_c08: multipole,ksl:={ 0,kssc2_8 }; +dh_c09: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +oct_c09: octupole,l:= 0.33,k3:=ko_c09 ; +qtv_c09: quadrupole,l:= 0.5,k1:=( kvx9 + ktc1_9 ) / brho ; +bpm_c09: monitor; +dmcv_c09: vkicker,l:= 0,kick:=kdvtc9 ; +qsc_c09: multipole,knl:={ 0,ksc_c09 }; +ssxc_c09: multipole,ksl:={ 0, 0,kssc1_9 }; +ekick01: vkicker,l:= 0.4; +ekick02: vkicker,l:= 0.4; +ekick03: vkicker,l:= 0.4; +ekick04: vkicker,l:= 0.505; +ekick05: vkicker,l:= 0.505; +ekick06: vkicker,l:= 0.505; +ekick07: vkicker,l:= 0.505; +dchv_c10: kicker,l:= 0,hkick:=kdhtc10 ,vkick:=kdvtc10 ; +bpm_c10: monitor; +qth_c10: quadrupole,l:= 0.673,k1:=( khx10 + ktc10d13 ) / brho ; +qtv_c11: quadrupole,l:= 0.533,k1:=( kvx11 - kta11c12 ) / brho ; +ekick08: vkicker,l:= 0.4275; +ekick09: vkicker,l:= 0.4275; +ekick10: vkicker,l:= 0.4275; +ekick11: vkicker,l:= 0.4275; +ekick12: vkicker,l:= 0.39; +ekick13: vkicker,l:= 0.39; +ekick14: vkicker,l:= 0.39; +qtv_c12: quadrupole,l:= 0.533,k1:=( kvx12 - kta11c12 ) / brho ; +qth_c13: quadrupole,l:= 0.673,k1:=( khx13 + ktc10d13 ) / brho ; +bpm_c13: monitor; +dchv_c13: kicker,l:= 0,hkick:=kdhtc13 ,vkick:=kdvtc13 ; +scbdsol_c13a: solenoid,l:= 1.22174,ks:= 0,ksi:=ksisol ; +scbdsol_c13b: solenoid,l:= 1.22174,ks:= 0,ksi:=ksisol ; +dmcv_d01: vkicker,l:= 0,kick:=kdvtd1 ; +qsc_d01: multipole,knl:={ 0,ksc_d01 }; +ssxc_d01: multipole,ksl:={ 0,kssd1_9 }; +bpm_d01: monitor; +qtv_d01: quadrupole,l:= 0.5,k1:=( kvx1 + ktd1_9 ) / brho ; +scv_d01: sextupole,l:= 0.354,k2:=ksv1 ; +dh_d01: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmch_d02: hkicker,l:= 0,kick:=kdhtd2 ; +qsc_d02: multipole,knl:={ 0,ksc_d02 }; +ssxc_d02: multipole,ksl:={ 0, 0,kssd2_8 }; +bpm_d02: monitor; +qth_d02: quadrupole,l:= 0.5,k1:=( khx2 + ktb2d8 ) / brho ; +sch_d02: sextupole,l:= 0.354,k2:=ksh2 ; +dh_d02: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmcv_d03: vkicker,l:= 0,kick:=kdvtd3 ; +qsc_d03: multipole,knl:={ 0,ksc_d03 }; +bpm_d03: monitor; +qtv_d03: quadrupole,l:= 0.5,k1:=( kvx3 + ktd357 ) / brho ; +sv_d03: sextupole,l:=lsv3 ,k2:=ksv3 ; +dh_d03: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmch_d04: hkicker,l:= 0,kick:=kdhtd4 ; +bpm_d04: monitor; +qth_d04: quadrupole,l:= 0.541,k1:=( khx4 - ktc4d6 ) / brho ; +sh_d04: sextupole,l:= 0.33,k2:=ksh4 ; +dh_d04: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sv_d05: sextupole,l:= 0.317,k2:=ksv5 ; +qtv_d05: quadrupole,l:= 0.5,k1:=( kvx5 + ktd357 ) / brho ; +bpm_d05: monitor; +dmcv_d05: vkicker,l:= 0,kick:=kdvtd5 ; +qsc_d05: multipole,knl:={ 0,ksc_d05 }; +dh_d06: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sh_d06: sextupole,l:= 0.33,k2:=ksh6 ; +qth_d06: quadrupole,l:= 0.541,k1:=( khx6 - ktc4d6 ) / brho ; +bpm_d06: monitor; +dmch_d06: hkicker,l:= 0,kick:=kdhtd6 ; +dh_d07: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sv_d07: sextupole,l:= 0.317,k2:=ksv7 ; +qtv_d07: quadrupole,l:= 0.5,k1:=( kvx7 + ktd357 ) / brho ; +bpm_d07: monitor; +dmcv_d07: vkicker,l:= 0,kick:=kdvtd7 ; +qsc_d07: multipole,knl:={ 0,ksc_d07 }; +dh_d08: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +oct_d08: octupole,l:= 0.33,k3:=ko_d08 ; +qth_d08: quadrupole,l:= 0.5,k1:=( khx8 + ktb2d8 ) / brho ; +bpm_d08: monitor; +dmch_d08: hkicker,l:= 0,kick:=kdhtd8 ; +qsc_d08: multipole,knl:={ 0,ksc_d08 }; +ssxc_d08: multipole,ksl:={ 0, 0,kssd2_8 }; +dh_d09: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +oct_d09: octupole,l:= 0.33,k3:=ko_d09 ; +qtv_d09: quadrupole,l:= 0.5,k1:=( kvx9 + ktd1_9 ) / brho ; +bpm_d09: monitor; +dmcv_d09: vkicker,l:= 0,kick:=kdvtd9 ; +qsc_d09: multipole,knl:={ 0,ksc_d09 }; +ssxc_d09: multipole,ksl:={ 0, 0,kssd1_9 }; +tunepickup: marker; +qmmpickup: marker; +wcm: marker; +bcm: marker; +dchv_d10: kicker,l:= 0,hkick:=kdhtd10 ,vkick:=kdvtd10 ; +bpm_d10: monitor; +qth_d10: quadrupole,l:= 0.673,k1:=( khx10 - ktc10d13 ) / brho ; +qtv_d11: quadrupole,l:= 0.533,k1:=( kvx11 - ktb11d12 ) / brho ; +cav_01: rfcavity,l:= 2.1466,volt:= 0.0133,harmon:= 1; +cav_02: rfcavity,l:= 2.1466,volt:= 0.0133,harmon:= 1; +cav_03: rfcavity,l:= 2.1466,volt:= 0.0133,harmon:= 1; +cav_04: rfcavity,l:= 2.1466,volt:= -0.02,harmon:= 2; +qtv_d12: quadrupole,l:= 0.533,k1:=( kvx12 - ktb11d12 ) / brho ; +qth_d13: quadrupole,l:= 0.673,k1:=( khx13 - ktc10d13 ) / brho ; +bpm_d13: monitor; +dchv_d13: kicker,l:= 0,hkick:=kdhtd13 ,vkick:=kdvtd13 ; +haloscanner1: marker; +wirescanner1: marker; +ipm1: marker; +ipm2: marker; +wirescanner2: marker; +haloscanner2: marker; +dmcv_a01: vkicker,l:= 0,kick:=kdvta1 ; +qsc_a01: multipole,knl:={ 0,ksc_a01 }; +ssxc_a01: multipole,ksl:={ 0, 0,kssa1_9 }; +bpm_a01: monitor; +qtv_a01: quadrupole,l:= 0.5,k1:=( kvx1 + kta1_9 ) / brho ; +scv_a01: sextupole,l:= 0.354,k2:=ksv1 ; +dh_a01: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmch_a02: hkicker,l:= 0,kick:=kdhta2 ; +qsc_a02: multipole,knl:={ 0,ksc_a02 }; +ssxc_a02: multipole,ksl:={ 0, 0,kssa2_8 }; +bpm_a02: monitor; +qth_a02: quadrupole,l:= 0.5,k1:=( khx2 + kta2c8 ) / brho ; +sch_a02: sextupole,l:= 0.354,k2:=ksh2 ; +dh_a02: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmcv_a03: vkicker,l:= 0,kick:=kdvta3 ; +qsc_a03: multipole,knl:={ 0,ksc_a03 }; +bpm_a03: monitor; +qtv_a03: quadrupole,l:= 0.5,k1:=( kvx3 + kta357 ) / brho ; +sv_a03: sextupole,l:= 0.317,k2:=ksv3 ; +dh_a03: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +dmch_a04: hkicker,l:= 0,kick:=kdhta4 ; +bpm_a04: monitor; +qth_a04: quadrupole,l:= 0.541,k1:=( khx4 + kta4b6 ) / brho ; +sh_a04: sextupole,l:= 0.33,k2:=ksh4 ; +dh_a04: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sv_a05: sextupole,l:= 0.317,k2:=ksv5 ; +qtv_a05: quadrupole,l:= 0.5,k1:=( kvx5 + kta357 ) / brho ; +bpm_a05: monitor; +dmcv_a05: vkicker,l:= 0,kick:=kdvta5 ; +qsc_a05: multipole,knl:={ 0}; +dh_a06: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sh_a06: sextupole,l:= 0.33,k2:=ksh6 ; +qth_a06: quadrupole,l:= 0.541,k1:=( khx6 + kta4b6 ) / brho ; +bpm_a06: monitor; +dmch_a06: hkicker,l:= 0,kick:=kdhta6 ; +dh_a07: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +sv_a07: sextupole,l:= 0.317,k2:=ksv7 ; +qtv_a07: quadrupole,l:= 0.5,k1:=( kvx7 + kta357 ) / brho ; +bpm_a07: monitor; +dmcv_a07: vkicker,l:= 0,kick:=kdvta7 ; +qsc_a07: multipole,knl:={ 0,ksc_a07 }; +dh_a08: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +oct_a08: octupole,l:= 0.33,k3:=ko_a08 ; +qth_a08: quadrupole,l:= 0.5,k1:=( khx8 + kta2c8 ) / brho ; +bpm_a08: monitor; +dmch_a08: hkicker,l:= 0,kick:=kdhta8 ; +qsc_a08: multipole,knl:={ 0,ksc_a08 }; +ssxc_a08: multipole,ksl:={ 0, 0,kssa2_8 }; +dh_a09: sbend,l:= 1.4407,angle:= 0.1963495408,e1:= 0,e2:= 0; +oct_a09: octupole,l:= 0.33,k3:=ko_a09 ; +qtv_a09: quadrupole,l:= 0.5,k1:=( kvx9 + kta1_9 ) / brho ; +bpm_a09: monitor; +dmcv_a09: vkicker,l:= 0,kick:=kdvta9 ; +qsc_a09: multipole,knl:={ 0,ksc_a09 }; +ssxc_a09: multipole,ksl:={ 0, 0,kssa1_9 }; +ikickh_a10: hkicker,l:= 0.839,kick:=hkck10 ; +ikickv_a10: vkicker,l:= 0.839,kick:=vkck10 ; +ikickh_a11: hkicker,l:= 0.428,kick:=hkck11 ; +ikickv_a11: vkicker,l:= 0.428,kick:=vkck11 ; +dchv_a10: kicker,l:= 0,hkick:=kdhta10 ,vkick:=kdvta10 ; +bpm_a10: monitor; +qth_a10: quadrupole,l:= 0.673,k1:=( khx10 + kta10b13 ) / brho ; +injm3: marker; +qtv_a11: quadrupole,l:= 0.533,k1:=( kvx11 + kta11c12 ) / brho ; +dh_a10: sbend,l:= 0.8632537742,angle:= -0.042,e1:= 0,e2:= -0.042; +dh_a11: sbend,l:= 0.8722394086,angle:= 0.045,e1:= 0.042,e2:= 0.003; +rnginjsol: sequence, l = 248.0098418; +injm1, at = 0; +dh_a12, at = 1.378195456; +dh_a13, at = 3.408731523; +qtv_a12, at = 7.004892621; +injm4, at = 7.693392621; +qth_a13, at = 8.029892621; +bpm_a13, at = 8.547265121; +dchv_a13, at = 8.683688621; +ikickv_a12, at = 10.59989262; +ikickh_a12, at = 11.13989262; +ikickv_a13, at = 12.66989262; +ikickh_a13, at = 13.82989262; +injm2, at = 14.24939262; +dmcv_b01, at = 14.92668062; +qsc_b01, at = 14.92668062; +ssxc_b01, at = 14.92668062; +bpm_b01, at = 15.12176002; +qtv_b01, at = 15.47989262; +scv_b01, at = 16.03310462; +dh_b01, at = 17.47998825; +dmch_b02, at = 18.92687188; +qsc_b02, at = 18.92687188; +ssxc_b02, at = 18.92687188; +bpm_b02, at = 19.11879438; +bpm_b02, at = 19.23008388; +qth_b02, at = 19.48008388; +sch_b02, at = 20.03329588; +dh_b02, at = 21.4801795; +dmcv_b03, at = 22.92706313; +qsc_b03, at = 22.92706313; +bpm_b03, at = 23.11546513; +qtv_b03, at = 23.48027513; +sv_b03, at = 24.01443713; +dh_b03, at = 25.48037076; +dmch_b04, at = 26.89474238; +bpm_b04, at = 27.11860888; +qth_b04, at = 27.48046638; +sh_b04, at = 28.08524038; +dh_b04, at = 29.48056201; +sv_b05, at = 30.94649564; +qtv_b05, at = 31.48065764; +bpm_b05, at = 31.84546764; +dmcv_b05, at = 32.03386964; +qsc_b05, at = 32.03386964; +dh_b06, at = 33.48075326; +sh_b06, at = 34.87607489; +qth_b06, at = 35.48084889; +bpm_b06, at = 35.84270639; +dmch_b06, at = 36.06657289; +dh_b07, at = 37.48094452; +sv_b07, at = 38.94687815; +qtv_b07, at = 39.48104015; +bpm_b07, at = 39.84585015; +dmcv_b07, at = 40.03425215; +qsc_b07, at = 40.03425215; +dh_b08, at = 41.48113577; +oct_b08, at = 42.9280194; +qth_b08, at = 43.4812314; +bpm_b08, at = 43.8425209; +dmch_b08, at = 44.0344434; +qsc_b08, at = 44.0344434; +ssxc_b08, at = 44.0344434; +dh_b09, at = 45.48132703; +oct_b09, at = 46.92821065; +qtv_b09, at = 47.48142265; +bpm_b09, at = 47.83955525; +dmcv_b09, at = 48.03463465; +qsc_b09, at = 48.03463465; +ssxc_b09, at = 48.03463465; +dchv_b10, at = 54.27762665; +bpm_b10, at = 54.41405015; +qth_b10, at = 54.93142265; +qtv_b11, at = 55.95642265; +qtv_b12, at = 69.00642265; +qth_b13, at = 70.03142265; +bpm_b13, at = 70.54879515; +dchv_b13, at = 70.68521865; +dampkicker1, at = 73.19024865; +dampkicker2, at = 73.69024765; +qmmkicker, at = 74.31523965; +tunekicker, at = 75.44023065; +dmcv_c01, at = 76.92821065; +qsc_c01, at = 76.92821065; +ssxc_c01, at = 76.92821065; +bpm_c01, at = 77.12329005; +qtv_c01, at = 77.48142265; +scv_c01, at = 78.03463465; +dh_c01, at = 79.48151828; +dmch_c02, at = 80.92840191; +ssxc_c02, at = 80.92840191; +qsc_c02, at = 80.92840191; +bpm_c02, at = 81.12032441; +qth_c02, at = 81.48161391; +sch_c02, at = 82.03482591; +dh_c02, at = 83.48170954; +dmcv_c03, at = 84.92859316; +qsc_c03, at = 84.92859316; +bpm_c03, at = 85.11699516; +qtv_c03, at = 85.48180516; +sv_c03, at = 86.01596716; +dh_c03, at = 87.48190079; +dmch_c04, at = 88.89627242; +bpm_c04, at = 89.12013892; +qth_c04, at = 89.48199642; +sh_c04, at = 90.08677042; +dh_c04, at = 91.48209204; +sv_c05, at = 92.94802567; +qtv_c05, at = 93.48218767; +bpm_c05, at = 93.84699767; +dmcv_c05, at = 94.03539967; +qsc_c05, at = 94.03539967; +dh_c06, at = 95.4822833; +sh_c06, at = 96.87760493; +qth_c06, at = 97.48237893; +bpm_c06, at = 97.84423643; +dmch_c06, at = 98.06810293; +dh_c07, at = 99.48247455; +sv_c07, at = 100.9484082; +qtv_c07, at = 101.4825702; +bpm_c07, at = 101.8473802; +dmcv_c07, at = 102.0357822; +qsc_c07, at = 102.0357822; +dh_c08, at = 103.4826658; +oct_c08, at = 104.9295494; +qth_c08, at = 105.4827614; +bpm_c08, at = 105.8440509; +dmch_c08, at = 106.0359734; +qsc_c08, at = 106.0359734; +ssxc_c08, at = 106.0359734; +dh_c09, at = 107.4828571; +oct_c09, at = 108.9297407; +qtv_c09, at = 109.4829527; +bpm_c09, at = 109.8410853; +dmcv_c09, at = 110.0361647; +qsc_c09, at = 110.0361647; +ssxc_c09, at = 110.0361647; +ekick01, at = 112.3299527; +ekick02, at = 112.8099527; +ekick03, at = 113.2899527; +ekick04, at = 113.8229527; +ekick05, at = 114.4079527; +ekick06, at = 114.9929527; +ekick07, at = 115.5779527; +dchv_c10, at = 116.2791567; +bpm_c10, at = 116.4155802; +qth_c10, at = 116.9329527; +qtv_c11, at = 117.9579527; +ekick08, at = 118.9059527; +ekick09, at = 119.4149527; +ekick10, at = 119.9249527; +ekick11, at = 120.4309527; +ekick12, at = 120.9202527; +ekick13, at = 121.3895527; +ekick14, at = 121.8606527; +qtv_c12, at = 131.0079527; +qth_c13, at = 132.0329527; +bpm_c13, at = 132.5503252; +dchv_c13, at = 132.6867487; +scbdsol_c13a, at = 134.3897627; +scbdsol_c13b, at = 138.0255227; +dmcv_d01, at = 138.9297407; +qsc_d01, at = 138.9297407; +ssxc_d01, at = 138.9297407; +bpm_d01, at = 139.1248201; +qtv_d01, at = 139.4829527; +scv_d01, at = 140.0361647; +dh_d01, at = 141.4830483; +dmch_d02, at = 142.9299319; +qsc_d02, at = 142.9299319; +ssxc_d02, at = 142.9299319; +bpm_d02, at = 143.1218544; +qth_d02, at = 143.4831439; +sch_d02, at = 144.0363559; +dh_d02, at = 145.4832396; +dmcv_d03, at = 146.9301232; +qsc_d03, at = 146.9301232; +bpm_d03, at = 147.1185252; +qtv_d03, at = 147.4833352; +sv_d03, at = 148.0174972; +dh_d03, at = 149.4834308; +dmch_d04, at = 150.8978024; +bpm_d04, at = 151.1216689; +qth_d04, at = 151.4835264; +sh_d04, at = 152.0883004; +dh_d04, at = 153.4836221; +sv_d05, at = 154.9495557; +qtv_d05, at = 155.4837177; +bpm_d05, at = 155.8485277; +dmcv_d05, at = 156.0369297; +qsc_d05, at = 156.0369297; +dh_d06, at = 157.4838133; +sh_d06, at = 158.879135; +qth_d06, at = 159.483909; +bpm_d06, at = 159.8457665; +dmch_d06, at = 160.069633; +dh_d07, at = 161.4840046; +sv_d07, at = 162.9499382; +qtv_d07, at = 163.4841002; +bpm_d07, at = 163.8489102; +dmcv_d07, at = 164.0373122; +qsc_d07, at = 164.0373122; +dh_d08, at = 165.4841958; +oct_d08, at = 166.9310795; +qth_d08, at = 167.4842915; +bpm_d08, at = 167.845581; +dmch_d08, at = 168.0375035; +qsc_d08, at = 168.0375035; +ssxc_d08, at = 168.0375035; +dh_d09, at = 169.4843871; +oct_d09, at = 170.9312707; +qtv_d09, at = 171.4844827; +bpm_d09, at = 171.8426153; +dmcv_d09, at = 172.0376947; +qsc_d09, at = 172.0376947; +ssxc_d09, at = 172.0376947; +tunepickup, at = 173.5472277; +qmmpickup, at = 174.6722197; +wcm, at = 175.7778927; +bcm, at = 176.7642687; +dchv_d10, at = 178.2806867; +bpm_d10, at = 178.4171102; +qth_d10, at = 178.9344827; +qtv_d11, at = 179.9594827; +cav_01, at = 183.0386827; +cav_02, at = 185.3358827; +cav_03, at = 187.6330827; +cav_04, at = 189.9302827; +qtv_d12, at = 193.0094827; +qth_d13, at = 194.0344827; +bpm_d13, at = 194.5518552; +dchv_d13, at = 194.6882787; +haloscanner1, at = 196.4528147; +wirescanner1, at = 196.6309197; +ipm1, at = 197.0093417; +ipm2, at = 199.3134267; +wirescanner2, at = 199.6918487; +haloscanner2, at = 199.8699527; +dmcv_a01, at = 200.9312707; +qsc_a01, at = 200.9312707; +ssxc_a01, at = 200.9312707; +bpm_a01, at = 201.1263501; +qtv_a01, at = 201.4844827; +scv_a01, at = 202.0376947; +dh_a01, at = 203.4845783; +dmch_a02, at = 204.931462; +qsc_a02, at = 204.931462; +ssxc_a02, at = 204.931462; +bpm_a02, at = 205.1233845; +qth_a02, at = 205.484674; +sch_a02, at = 206.037886; +dh_a02, at = 207.4847696; +dmcv_a03, at = 208.9316532; +qsc_a03, at = 208.9316532; +bpm_a03, at = 209.1200552; +qtv_a03, at = 209.4848652; +sv_a03, at = 210.0190272; +dh_a03, at = 211.4849609; +dmch_a04, at = 212.8993325; +bpm_a04, at = 213.123199; +qth_a04, at = 213.4850565; +sh_a04, at = 214.0898305; +dh_a04, at = 215.4851521; +sv_a05, at = 216.9510857; +qtv_a05, at = 217.4852477; +bpm_a05, at = 217.8500577; +dmcv_a05, at = 218.0384597; +qsc_a05, at = 218.0384597; +dh_a06, at = 219.4853434; +sh_a06, at = 220.880665; +qth_a06, at = 221.485439; +bpm_a06, at = 221.8472965; +dmch_a06, at = 222.071163; +dh_a07, at = 223.4855346; +sv_a07, at = 224.9514682; +qtv_a07, at = 225.4856302; +bpm_a07, at = 225.8504402; +dmcv_a07, at = 226.0388422; +qsc_a07, at = 226.0388422; +dh_a08, at = 227.4857259; +oct_a08, at = 228.9326095; +qth_a08, at = 229.4858215; +bpm_a08, at = 229.847111; +dmch_a08, at = 230.0390335; +qsc_a08, at = 230.0390335; +ssxc_a08, at = 230.0390335; +dh_a09, at = 231.4859171; +oct_a09, at = 232.9328008; +qtv_a09, at = 233.4860128; +bpm_a09, at = 233.8441454; +dmcv_a09, at = 234.0392248; +qsc_a09, at = 234.0392248; +ssxc_a09, at = 234.0392248; +ikickh_a10, at = 235.1360128; +ikickv_a10, at = 236.2960128; +ikickh_a11, at = 237.8260128; +ikickv_a11, at = 238.3660128; +dchv_a10, at = 240.2822168; +bpm_a10, at = 240.4186403; +qth_a10, at = 240.9360128; +injm3, at = 241.2725128; +qtv_a11, at = 241.9610128; +dh_a10, at = 245.1911396; +dh_a11, at = 247.5737221; +endsequence; diff --git a/examples/Envelope/sns_ring/style.mplstyle b/examples/Envelope/sns_ring/style.mplstyle new file mode 100644 index 00000000..71f36605 --- /dev/null +++ b/examples/Envelope/sns_ring/style.mplstyle @@ -0,0 +1,8 @@ +axes.linewidth: 1.25 +axes.titlesize: "medium" +image.cmap: "Greys" +figure.constrained_layout.use: True +savefig.dpi: 300 +savefig.format: "png" +xtick.minor.visible: True +ytick.minor.visible: True diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring/test_sns_ring.py new file mode 100644 index 00000000..b7e74716 --- /dev/null +++ b/examples/Envelope/sns_ring/test_sns_ring.py @@ -0,0 +1,389 @@ +"""Test envelope tracker in SNS ring.""" + +import argparse +import copy +import math +import os +import pathlib +import time +import sys + +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 EnvelopeTracker +from orbit.core.spacecharge import SpaceChargeCalc2p5D +from orbit.space_charge.sc2p5d import setSC2p5DAccNodes +from orbit.teapot import TEAPOT_Ring +from orbit.teapot import TEAPOT_MATRIX_Lattice +from orbit.teapot import teapot +from orbit.utils.consts import mass_proton + +sys.path.append("..") +from plot import plot_rms_ellipse +from plot import plot_corner +from utils import gen_dist +from utils import build_rotation_matrix_xy +from utils import project_cov_matrix + +plt.style.use("style.mplstyle") + + +# Arguments +# ------------------------------------------------------------------------------ + +parser = argparse.ArgumentParser() +parser.add_argument("--bunch-length", type=float, default=120.0) +parser.add_argument("--kin-energy", type=float, default=1.300) +parser.add_argument("--intensity", type=float, default=2e14) + +parser.add_argument("--dist", type=str, default="kv", choices=["kv", "waterbag", "gauss"]) +parser.add_argument("--eps-x", type=float, default=25.0) +parser.add_argument("--eps-y", type=float, default=25.0) +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("--nparts", type=int, default=100_000) +parser.add_argument("--turns", type=int, default=25) +parser.add_argument("--sol", type=int, default=0) +parser.add_argument("--sc", type=int, default=0) +parser.add_argument("--sc-grid", type=int, default=64) + +parser.add_argument("--handle-unknown", type=str, default=None, choices=["drift", "fit"]) +args = parser.parse_args() + +# Setup +# ------------------------------------------------------------------------------ + +path = pathlib.Path(__file__) +output_dir = os.path.join("outputs", path.stem) +os.makedirs(output_dir, exist_ok=True) + +# Lattice +# ------------------------------------------------------------------------------ + +lattice = TEAPOT_Ring() +lattice.readMADX("inputs/sns_ring.lat", "rnginjsol") +lattice.initialize() + +for node in lattice.getNodes(): + if type(node) != teapot.TurnCounterTEAPOT: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + if type(node) is teapot.BendTEAPOT: + node.setParam("ea1", 0.0) + node.setParam("ea2", 0.0) + +if args.sol: + for name in ["scbdsol_c13a", "scbdsol_c13b"]: + node = lattice.getNodeForName(name) + node.setParam("B", 0.15) + +for node in lattice.getNodes(): + max_length = 1.0 + if node.getLength() > max_length: + node.setnParts(1 + int(node.getLength() / max_length)) + +# Bunch +# ------------------------------------------------------------------------------ + +bunch = Bunch() +bunch.mass(mass_proton) +sync_part = bunch.getSyncParticle() +sync_part.kinEnergy(args.kin_energy) + +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 = args.eps_x * 1e-6 +eps_y = args.eps_y * 1e-6 + +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 / 4.0) ** 2 +cov_matrix[5, 5] = 0.0 + +if args.tilt: + rot_matrix = np.identity(6) + rot_matrix[:4, :4] = build_rotation_matrix_xy(angle=(args.tilt * math.pi)) + cov_matrix = np.linalg.multi_dot([rot_matrix, cov_matrix, rot_matrix.T]) + +if args.mismatch_x or args.mismatch_y: + cov_matrix[0, 0] *= (1.0 + args.mismatch_x) ** 2 + cov_matrix[2, 2] *= (1.0 + args.mismatch_y) ** 2 + +centroid = np.zeros(6) +centroid[0] += args.offset_x +centroid[2] += args.offset_y + +rng = np.random.default_rng() +bunch_coords = np.zeros((args.nparts, 6)) +bunch_coords[:, :4] = gen_dist(size=args.nparts, cov_matrix=cov_matrix[0:4, 0:4], name=args.dist) +bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) +bunch_coords[:, 5] *= 0.0 +bunch_coords += centroid[None, :6] + +for i in range(bunch_coords.shape[0]): + bunch.addParticle(*bunch_coords[i]) + +# Use covariance matrix from initial bunch, which is slightly +# different from the one used to generate the bunch due to +# finite statistics. +cov_matrix_init = np.cov(bunch_coords, rowvar=False) +centroid_init = np.mean(bunch_coords, axis=0) + +# Track envelope +# ------------------------------------------------------------------------------ + +print("TRACK ENVELOPE") + +envelope = Envelope( + bunch=bunch, + cov_matrix=cov_matrix_init, + centroid=centroid_init, + intensity=args.intensity, +) +tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) + +history_keys = [ + "rms_x", + "rms_y", + "avg_x", + "avg_y", + "eps_x", + "eps_y", +] +history = {key: [] for key in history_keys} + +start_time = time.time() + +for turn in range(args.turns + 1): + if turn > 0: + tracker.track_ring(envelope) + + cov_matrix = envelope.cov_matrix + centroid = envelope.centroid + + rms_x = 1000.0 * math.sqrt(cov_matrix[0, 0]) + rms_y = 1000.0 * math.sqrt(cov_matrix[2, 2]) + avg_x = 1000.0 * centroid[0] + avg_y = 1000.0 * centroid[2] + eps_x = 1e6 * np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) + eps_y = 1e6 * np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) + + message = "" + message += " turn={}".format(turn) + message += " time={:0.3f}".format(time.time() - start_time) + message += " eps_x={:0.2f}".format(eps_x) + message += " eps_y={:0.2f}".format(eps_y) + message += " xrms={:0.2f}".format(rms_x) + message += " yrms={:0.2f}".format(rms_y) + message += " xavg={:0.2f}".format(avg_x) + message += " yavg={:0.2f}".format(avg_y) + print(message) + + history["rms_x"].append(rms_x) + history["rms_y"].append(rms_y) + history["avg_x"].append(avg_x) + history["avg_y"].append(avg_y) + history["eps_x"].append(eps_x) + history["eps_y"].append(eps_y) + +histories = {} +histories["envelope"] = copy.deepcopy(history) + +# Track bunch +# ------------------------------------------------------------------------------ + +print("TRACK BUNCH") + +if args.sc: + sc_calc = SpaceChargeCalc2p5D(64, 64, 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_keys = [ + "rms_x", + "rms_y", + "avg_x", + "avg_y", + "eps_x", + "eps_y", +] +history = {key: [] for key in history_keys} + +start_time = time.time() + +for turn in range(args.turns + 1): + 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] + + centroid = np.zeros(6) + for i in range(6): + centroid[i] = twiss_calc.getAverage(i) + + rms_x = 1000.0 * math.sqrt(cov_matrix[0, 0]) + rms_y = 1000.0 * math.sqrt(cov_matrix[2, 2]) + avg_x = 1000.0 * centroid[0] + avg_y = 1000.0 * centroid[2] + eps_x = 1e6 * np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) + eps_y = 1e6 * np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) + + message = "" + message += " turn={}".format(turn) + message += " time={:0.3f}".format(time.time() - start_time) + message += " eps_x={:0.2f}".format(eps_x) + message += " eps_y={:0.2f}".format(eps_y) + message += " xrms={:0.2f}".format(rms_x) + message += " yrms={:0.2f}".format(rms_y) + message += " xavg={:0.2f}".format(avg_x) + message += " yavg={:0.2f}".format(avg_y) + print(message) + + history["rms_x"].append(rms_x) + history["rms_y"].append(rms_y) + history["avg_x"].append(avg_x) + history["avg_y"].append(avg_y) + history["eps_x"].append(eps_x) + history["eps_y"].append(eps_y) + +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 ["rms_x", "rms_y"]: + 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(key + " [mm]") + ax.legend(loc="upper right") + plt.savefig(os.path.join(output_dir, f"fig_{key}")) + plt.close() + +# Plot rms emittances +color_cycle = plt.rcParams["axes.prop_cycle"].by_key()["color"] + +fig, ax = plt.subplots(figsize=(5, 3)) +for key, color in zip(["eps_x", "eps_y"], color_cycle): + for i, model in enumerate(["envelope", "bunch"]): + if model == "envelope": + plot_kws = dict() + else: + plot_kws = dict(marker=".", lw=0) + label = key + "_" + model + ax.plot(histories[model][key], color=color, label=label, **plot_kws) + +ymax = 2.0 * np.mean(histories["envelope"]["eps_x"]) +ax.set_ylim(0.0, ymax) +ax.set_xlabel("Turn") +ax.set_ylabel("[mm mrad]") +plt.savefig(os.path.join(output_dir, f"fig_emittances")) +plt.close() + +# Plot centroids +for key in ["avg_x", "avg_y"]: + 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(key + " [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 = envelope.cov_matrix +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() diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring/test_sns_ring_speed.py new file mode 100644 index 00000000..73b84ff0 --- /dev/null +++ b/examples/Envelope/sns_ring/test_sns_ring_speed.py @@ -0,0 +1,143 @@ +"""Test envelope tracker speed in SNS ring.""" + +import argparse +import time +import cProfile +import pstats +import sys + +import numpy as np +from tqdm import trange + +from orbit.core.bunch import Bunch +from orbit.core.spacecharge import SpaceChargeCalc2p5D +from orbit.envelope import Envelope +from orbit.envelope import EnvelopeTracker +from orbit.core.spacecharge import SpaceChargeCalc2p5D +from orbit.space_charge.sc2p5d import setSC2p5DAccNodes +from orbit.teapot import TEAPOT_Ring +from orbit.teapot import TEAPOT_MATRIX_Lattice +from orbit.utils.consts import mass_proton + +sys.path.append("..") +from utils import gen_dist + +parser = argparse.ArgumentParser() +parser.add_argument("--bunch-length", type=float, default=120.0) +parser.add_argument("--kin-energy", type=float, default=1.300) +parser.add_argument("--intensity", type=float, default=2e14) + +parser.add_argument("--nparts", type=int, default=10_000) +parser.add_argument("--turns", type=int, default=25) +parser.add_argument("--sc", type=int, default=0) +parser.add_argument("--sc-grid", type=int, default=64) +args = parser.parse_args() + + +lattice = TEAPOT_Ring() +lattice.readMADX("inputs/sns_ring.lat", "rnginjsol") +lattice.initialize() + +for node in lattice.getNodes(): + try: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + except: + pass + +for node in lattice.getNodes(): + max_length = 1.0 + if node.getLength() > max_length: + node.setnParts(1 + int(node.getLength() / max_length)) + +bunch = Bunch() +bunch.mass(mass_proton) +sync_part = bunch.getSyncParticle() +sync_part.kinEnergy(args.kin_energy) + +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 = 25.0e-06 +eps_y = eps_x + +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 / 4.0) ** 2 +cov_matrix[5, 5] = 0.0 + +cov_matrix_init = np.copy(cov_matrix) + +# Track envelope +print("ENVELOPE") + +envelope = Envelope( + bunch=bunch, + cov_matrix=cov_matrix_init, + intensity=args.intensity, +) +tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) + +start_time = time.time() + +profiler = cProfile.Profile() +profiler.enable() + +for turn in trange(args.turns): + tracker.track_ring(envelope) + +time_per_turn = (time.time() - start_time) / args.turns + +profiler.disable() + +print("Time per turn:", time_per_turn) + +profiler_stats = pstats.Stats(profiler) +profiler_stats.sort_stats(pstats.SortKey.TIME) +profiler_stats.print_stats(10) + +# Track bunch +print("BUNCH") + +rng = np.random.default_rng() + +bunch_coords = np.zeros((args.nparts, 6)) +bunch_coords[:, :4] = gen_dist(size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv") +bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) + +for i in range(bunch_coords.shape[0]): + bunch.addParticle(*bunch_coords[i]) + +if args.sc: + sc_calc = SpaceChargeCalc2p5D(64, 64, 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) + +start_time = time.time() + +profiler = cProfile.Profile() +profiler.enable() + +for turn in trange(args.turns): + lattice.trackBunch(bunch) + +time_per_turn = (time.time() - start_time) / args.turns + +profiler.disable() + +print("Time per turn:", time_per_turn) + +profiler_stats = pstats.Stats(profiler) +profiler_stats.sort_stats(pstats.SortKey.TIME) +profiler_stats.print_stats(10) diff --git a/examples/Envelope/style.mplstyle b/examples/Envelope/style.mplstyle new file mode 100644 index 00000000..71f36605 --- /dev/null +++ b/examples/Envelope/style.mplstyle @@ -0,0 +1,8 @@ +axes.linewidth: 1.25 +axes.titlesize: "medium" +image.cmap: "Greys" +figure.constrained_layout.use: True +savefig.dpi: 300 +savefig.format: "png" +xtick.minor.visible: True +ytick.minor.visible: True diff --git a/examples/Envelope/test_env_2d_fodo.py b/examples/Envelope/test_env_2d_fodo.py new file mode 100644 index 00000000..de5a4444 --- /dev/null +++ b/examples/Envelope/test_env_2d_fodo.py @@ -0,0 +1,316 @@ +"""Test 2D envelope tracker in FODO lattice.""" + +import argparse +import copy +import math +import os +import pathlib + +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 EnvelopeTracker +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 gen_dist +from utils import build_rotation_matrix_xy +from utils import project_cov_matrix + +plt.style.use("style.mplstyle") + + +def main(args: argparse.Namespace) -> None: + + # Setup + # ------------------------------------------------------------------------------ + + path = pathlib.Path(__file__) + output_dir = os.path.join("outputs", path.stem) + 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=(args.tilt * math.pi)) + 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( + bunch=bunch, + cov_matrix=cov_matrix_init, + centroid=centroid_init, + intensity=args.intensity, + ) + + # Track envelope + # ------------------------------------------------------------------------------ + + print("TRACK ENVELOPE") + + tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) + + history = {"xrms": [], "yrms": [], "xavg": [], "yavg": []} + for turn in range(args.turns): + if turn > 0: + tracker.track_ring(envelope) + + cov_matrix = envelope.cov_matrix + centroid = envelope.centroid + + xrms = 1000.0 * math.sqrt(cov_matrix[0, 0]) + yrms = 1000.0 * math.sqrt(cov_matrix[2, 2]) + xavg = 1000.0 * centroid[0] + yavg = 1000.0 * centroid[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 = {} + histories["envelope"] = copy.deepcopy(history) + + # Track bunch + # ------------------------------------------------------------------------------ + + print("TRACK BUNCH") + + rng = np.random.default_rng() + + bunch_coords = np.zeros((args.nparts, 6)) + bunch_coords[:, :4] = gen_dist( + size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name=args.dist + ) + bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) + bunch_coords += centroid_init[None, :6] + + for i in range(bunch_coords.shape[0]): + bunch.addParticle(*bunch_coords[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 = envelope.cov_matrix + 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__": + 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) + args = parser.parse_args() + + main(args) diff --git a/examples/Envelope/test_env_2d_fodo_speed.py b/examples/Envelope/test_env_2d_fodo_speed.py new file mode 100644 index 00000000..2b85d185 --- /dev/null +++ b/examples/Envelope/test_env_2d_fodo_speed.py @@ -0,0 +1,145 @@ +"""Test envelope tracker speed in SNS ring.""" + +import argparse +import time +import cProfile +import pstats + +import numpy as np +from tqdm import trange + +from orbit.core.bunch import Bunch +from orbit.core.spacecharge import SpaceChargeCalc2p5D +from orbit.envelope import Envelope +from orbit.envelope import EnvelopeTracker +from orbit.core.spacecharge import SpaceChargeCalc2p5D +from orbit.space_charge.sc2p5d import setSC2p5DAccNodes +from orbit.teapot import QuadTEAPOT +from orbit.teapot import DriftTEAPOT +from orbit.teapot import TEAPOT_Lattice +from orbit.teapot import TEAPOT_MATRIX_Lattice +from orbit.utils.consts import mass_proton + +from utils import gen_dist + +parser = argparse.ArgumentParser() +parser.add_argument("--bunch-length", type=float, default=5.0) +parser.add_argument("--kin-energy", type=float, default=1.300) +parser.add_argument("--intensity", type=float, default=2e14) + +parser.add_argument("--nslice", type=int, default=10) +parser.add_argument("--kq", type=float, default=0.25) + +parser.add_argument("--nparts", type=int, default=10_000) +parser.add_argument("--turns", type=int, default=5000) +parser.add_argument("--sc", type=int, default=0) +parser.add_argument("--sc-grid", type=int, default=64) +args = parser.parse_args() + +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() + +bunch = Bunch() +bunch.mass(mass_proton) +sync_part = bunch.getSyncParticle() +sync_part.kinEnergy(args.kin_energy) + +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 = 25.0e-06 +eps_y = eps_x + +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 + +cov_matrix_init = np.copy(cov_matrix) + +# Track envelope +print("ENVELOPE") + +envelope = Envelope( + bunch=bunch, + cov_matrix=cov_matrix_init, + intensity=args.intensity, +) +tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) + +start_time = time.time() + +profiler = cProfile.Profile() +profiler.enable() + +for turn in trange(args.turns): + tracker.track_ring(envelope) + +time_per_turn = (time.time() - start_time) / args.turns + +profiler.disable() + +print("Time per turn:", time_per_turn) + +profiler_stats = pstats.Stats(profiler) +profiler_stats.sort_stats(pstats.SortKey.TIME) +profiler_stats.print_stats(10) + +# Track bunch +print("BUNCH") + +rng = np.random.default_rng() + +bunch_coords = np.zeros((args.nparts, 6)) +bunch_coords[:, :4] = gen_dist(size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv") +bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) + +for i in range(bunch_coords.shape[0]): + bunch.addParticle(*bunch_coords[i]) + +if args.sc: + sc_calc = SpaceChargeCalc2p5D(64, 64, 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) + +start_time = time.time() + +profiler = cProfile.Profile() +profiler.enable() + +for turn in trange(args.turns): + lattice.trackBunch(bunch) + +time_per_turn = (time.time() - start_time) / args.turns + +profiler.disable() + +print("Time per turn:", time_per_turn) + +profiler_stats = pstats.Stats(profiler) +profiler_stats.sort_stats(pstats.SortKey.TIME) +profiler_stats.print_stats(10) diff --git a/examples/Envelope/test_env_3d_drift.py b/examples/Envelope/test_env_3d_drift.py new file mode 100644 index 00000000..d66e592b --- /dev/null +++ b/examples/Envelope/test_env_3d_drift.py @@ -0,0 +1,275 @@ +"""Test 3D envelope tracker in drift + +The initial beam is a uniform-density ellipsoid in the x-y-z plane, with zero initial velocity. +The ellipsoid can have arbitrary size and orientation. +""" + +import argparse +import copy +import math +import os +import pathlib + +import numpy as np +import matplotlib.pyplot as plt +import scipy.spatial + +from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis +from orbit.core.spacecharge import SpaceChargeCalc3D +from orbit.bunch_utils import collect_bunch +from orbit.envelope import Envelope +from orbit.envelope import EnvelopeTracker +from orbit.space_charge.sc3d import setSC3DAccNodes +from orbit.teapot import DriftTEAPOT +from orbit.teapot import TEAPOT_Lattice +from orbit.utils.consts import mass_proton + +from plot import plot_rms_ellipse +from plot import plot_corner +from utils import gen_dist +from utils import project_cov_matrix + +plt.style.use("style.mplstyle") + + +def rotation_matrix_3d(angle_x: float, angle_y: float, angle_z: float) -> np.ndarray: + return scipy.spatial.transform.Rotation.from_euler( + "xyz", [angle_x, angle_y, angle_z] + ).as_matrix() + + +def build_cov_matrix_xyz(rms_sizes: np.ndarray, rotation_matrix: np.ndarray = None) -> np.ndarray: + cov_matrix = np.diag(np.square(rms_sizes)) + if rotation_matrix is None: + return cov_matrix + return rotation_matrix @ cov_matrix @ rotation_matrix.T + + +def main(args: argparse.Namespace) -> None: + + # Setup + # ------------------------------------------------------------------------------ + path = pathlib.Path(__file__) + output_dir = os.path.join("outputs", path.stem) + os.makedirs(output_dir, exist_ok=True) + + # Create lattice + # ------------------------------------------------------------------------------ + node = DriftTEAPOT(length=args.length) + node.setLength(args.length) + node.setnParts(args.nslice) + + lattice = TEAPOT_Lattice() + lattice.addNode(node) + lattice.initialize() + + # Create envelope + # ------------------------------------------------------------------------------ + bunch = Bunch() + bunch.mass(mass_proton) + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(args.kin_energy) + + cov_matrix_init = np.zeros((6, 6)) + + rotation_matrix = rotation_matrix_3d( + math.radians(args.rot_x), math.radians(args.rot_y), math.radians(args.rot_z) + ) + print(rotation_matrix) + + cov_matrix_xyz = build_cov_matrix_xyz( + [args.rms_x, args.rms_y, args.rms_z], rotation_matrix=rotation_matrix + ) + + lorentz_matrix = np.diag([1.0, 1.0, 1.0 / sync_part.gamma()]) + cov_matrix_xyz = lorentz_matrix @ cov_matrix_xyz @ lorentz_matrix.T + + spatial_idx = np.ix_([0, 2, 4], [0, 2, 4]) + cov_matrix_init[spatial_idx] = cov_matrix_xyz + + print(cov_matrix_xyz * 1e6) + print() + print(cov_matrix_init * 1e6) + + centroid_init = np.zeros(6) + + envelope = Envelope( + bunch=bunch, + cov_matrix=cov_matrix_init, + centroid=centroid_init, + intensity=args.intensity, + ) + + # Track envelope + # ------------------------------------------------------------------------------ + print("TRACK ENVELOPE") + + tracker = EnvelopeTracker(lattice, sc=("3d" if args.sc else None)) + + history = {"xrms": [], "yrms": [], "zrms": []} + for turn in range(args.turns): + if turn > 0: + tracker.track(envelope) + + cov_matrix = envelope.cov_matrix + + xrms = 1000.0 * math.sqrt(cov_matrix[0, 0]) + yrms = 1000.0 * math.sqrt(cov_matrix[2, 2]) + zrms = 1000.0 * math.sqrt(cov_matrix[4, 4]) * envelope.gamma + + history["xrms"].append(xrms) + history["yrms"].append(yrms) + history["zrms"].append(zrms) + + print(f"turn={turn} xrms={xrms:0.3f} yrms={yrms:0.3f} zrms={zrms:0.3f}") + + histories = {} + histories["envelope"] = copy.deepcopy(history) + + # Track bunch + # ------------------------------------------------------------------------------ + print("TRACK BUNCH") + + bunch_coords = np.zeros((args.nparts, 6)) + bunch_coords[:, (0, 2, 4)] = gen_dist( + size=args.nparts, cov_matrix=cov_matrix_xyz, name="waterbag" + ) + + for x, xp, y, yp, z, dE in bunch_coords: + bunch.addParticle(x, xp, y, yp, z, dE) + + size_global = bunch.getSizeGlobal() + bunch.macroSize(args.intensity / size_global) + + if args.sc: + sc_calc = SpaceChargeCalc3D(args.sc_grid, args.sc_grid, args.sc_grid) + sc_path_length_min = 0.01 + sc_nodes = setSC3DAccNodes(lattice, sc_path_length_min, sc_calc) + + history = {"xrms": [], "yrms": [], "zrms": []} + 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]) + zrms = 1000.0 * math.sqrt(cov_matrix[4, 4]) * bunch.getSyncParticle().gamma() + + history["xrms"].append(xrms) + history["yrms"].append(yrms) + history["zrms"].append(zrms) + + print(f"turn={turn} xrms={xrms:0.3f} yrms={yrms:0.3f} zrms={zrms:0.3f}") + + 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", "zrms"]: + fig, ax = plt.subplots(figsize=(4, 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] * 1.2) + ax.set_xlabel("s [mm]") + ax.set_ylabel("rms size [mm]") + ax.legend(loc="upper left") + 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 *= 1e3 + + env_cov_matrix = envelope.cov_matrix + env_cov_matrix *= 1e6 + + env_centroid = envelope.centroid + env_centroid *= 1e3 + + xmax = 4.0 * np.std(particles, axis=0) + limits = list(zip(-xmax, xmax)) + labels = ["x [mm]", "xp [mrad]", "y [mm]", "yp [mrad]", "z [mm]", "dE [MeV]"] + + # 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__": + parser = argparse.ArgumentParser() + parser.add_argument("--kin-energy", type=float, default=0.0025) + parser.add_argument("--intensity", type=float, default=3e10) + + parser.add_argument("--rms-x", type=float, default=0.010) + parser.add_argument("--rms-y", type=float, default=0.010) + parser.add_argument("--rms-z", type=float, default=0.010) + + parser.add_argument("--rot-x", type=float, default=0.0) + parser.add_argument("--rot-y", type=float, default=0.0) + parser.add_argument("--rot-z", type=float, default=0.0) + + parser.add_argument("--nslice", type=int, default=10) + parser.add_argument("--length", type=float, default=0.1) + parser.add_argument("--turns", type=int, default=20) + parser.add_argument("--sc-grid", type=int, default=64) + + parser.add_argument("--nparts", type=int, default=100_000) + parser.add_argument("--sc", type=int, default=0) + args = parser.parse_args() + + main(args) diff --git a/examples/Envelope/utils.py b/examples/Envelope/utils.py new file mode 100644 index 00000000..daf2a6c7 --- /dev/null +++ b/examples/Envelope/utils.py @@ -0,0 +1,60 @@ +import numpy as np + + +def gen_dist_gauss(size: int, dim: np.ndarray) -> np.ndarray: + return np.random.multivariate_normal( + mean=np.zeros(dim), + cov=np.eye(dim), + size=size, + ) + + +def gen_dist_kv(size: int, dim: int) -> np.ndarray: + X = np.random.normal(size=(size, dim)) + X /= np.linalg.norm(X, axis=1)[:, None] + X /= np.std(X, axis=0) + return X + + +def gen_dist_waterbag(size: int, dim: int) -> np.ndarray: + X = gen_dist_kv(size, dim) + dim = X.shape[1] + r = np.random.uniform(size=size) ** (1.0 / dim) + X *= r[:, None] + X /= np.std(X, axis=0) + return X + + +def gen_dist(size: int, cov_matrix: np.ndarray, name: str) -> np.ndarray: + dim = cov_matrix.shape[0] + if name == "kv": + X = gen_dist_kv(size, dim) + elif name == "waterbag": + X = gen_dist_waterbag(size, dim) + elif name == "gauss": + X = gen_dist_gauss(size, dim) + else: + raise ValueError(f"Invalid distribution name: {name}") + + L = np.linalg.cholesky(cov_matrix) + return np.matmul(X, L.T) + + +def build_rotation_matrix_xy(angle: float) -> np.ndarray: + cs = np.cos(angle) + sn = np.sin(angle) + + matrix = np.identity(4) + matrix[0, 0] = matrix[1, 1] = +cs + matrix[0, 2] = matrix[1, 3] = +sn + matrix[2, 0] = matrix[3, 1] = -sn + matrix[2, 2] = matrix[3, 3] = +cs + return matrix + + +def project_cov_matrix(cov_matrix: np.ndarray, axis: tuple[int, ...]) -> np.ndarray: + cov_matrix_proj = np.zeros((len(axis), len(axis))) + for i in range(len(axis)): + for j in range(len(axis)): + cov_matrix_proj[i, j] = cov_matrix[axis[i], axis[j]] + return cov_matrix_proj diff --git a/py/orbit/envelope/__init__.py b/py/orbit/envelope/__init__.py new file mode 100644 index 00000000..7a4586ae --- /dev/null +++ b/py/orbit/envelope/__init__.py @@ -0,0 +1,2 @@ +from .envelope import Envelope +from .track import EnvelopeTracker \ No newline at end of file diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py new file mode 100644 index 00000000..2c181626 --- /dev/null +++ b/py/orbit/envelope/envelope.py @@ -0,0 +1,235 @@ +import numpy as np +import scipy.constants +import scipy.special + +from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis +from orbit.core.bunch import SyncParticle + +from .utils import convert_matrix_zp_to_dE +from .utils import gen_dist +from .utils import get_classical_radius +from .utils import proj_cov_matrix + + +def build_diag_matrix_from_xyz_eig(eigenvectors: np.ndarray) -> np.ndarray: + A = np.eye(7) + for i in range(eigenvectors.shape[0]): + for j in range(eigenvectors.shape[1]): + row = i * 2 + col = j * 2 + A[row, col] = A[row + 1, col + 1] = eigenvectors[i, j] + return A + + +class Envelope: + """Represents beam envelope/centroid. + + Attributes: + bunch: Bunch containing synchronous particle and (optionally) test particles. + cov_matrix: 6 x 6 covariance matrix + centroid: 6 x 1 centroid vector. + intensity: Total number of particles. + """ + + def __init__( + self, + bunch: Bunch, + cov_matrix: np.ndarray = None, + centroid: np.ndarray = None, + intensity: float = 0.0, + ) -> None: + + empty_bunch = Bunch() + bunch.copyEmptyBunchTo(empty_bunch) + + self.bunch = empty_bunch + self.sync_part = self.bunch.getSyncParticle() + + self.centroid = centroid + if self.centroid is None: + if bunch.getSize(): + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) + self.centroid = np.zeros(6) + for i in range(6): + self.centroid[i] = twiss_calc.getAverage(i) + else: + self.centroid = np.zeros(6) + + self.cov_matrix = cov_matrix + if self.cov_matrix is None: + if bunch.getSize(): + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) + self.cov_matrix = np.zeros((6, 6)) + for i in range(6): + for j in range(6): + self.cov_matrix[i, j] = twiss_calc.getCorrelation(i, j) + self.cov_matrix[j, i] = self.cov_matrix[i, j] + else: + self.cov_matrix = np.eye(6) + + self.intensity = intensity + self.classical_radius = get_classical_radius(self.charge, self.mass) + self.charge_sign = self.charge / abs(self.charge) + + # For a uniform one-dimensional distribution over length L, the standard + # deviation is L * sqrt(12). This quantity is used to calculate the line + # density for two-dimensional space charge kicks. + self.rms_bunch_length_factor = np.sqrt(12.0) + + def copy(self): + return Envelope( + bunch=self.bunch, + cov_matrix=self.cov_matrix, + centroid=self.centroid, + intensity=self.intensity + ) + + @property + def gamma(self) -> float: + return self.sync_part.gamma() + + @property + def beta(self) -> float: + return self.sync_part.beta() + + @property + def mass(self) -> float: + return self.sync_part.mass() + + @property + def charge(self) -> float: + return self.bunch.charge() + + @property + def momentum(self) -> float: + return self.sync_part.momentum() + + @property + def sc_factor(self) -> float: + return 2.0 * self.intensity * self.classical_radius / (self.beta ** 2 * self.gamma ** 3) + + def rms(self, axis: int = None) -> float | np.ndarray: + rms_arr = np.sqrt(np.diag(self.cov_matrix)) + return rms_arr[axis] + + def transform(self, matrix: np.ndarray) -> None: + m = matrix[:-1, :-1] + u = matrix[:-1, -1] + self.cov_matrix = m @ self.cov_matrix @ m.T + self.centroid = np.matmul(m, self.centroid) + u + + def sample(self, size: int, dist: str = "kv") -> np.ndarray: + particles = gen_dist(size=size, cov_matrix=self.cov_matrix, name=dist) + particles = particles + self.centroid + return particles + + def sc_matrix_2d(self, length: float) -> np.ndarray: + centroid = self.centroid + cov_matrix = self.cov_matrix + + # Calculate transfer matrix in normalized (upright) frame. + cov_xx = cov_matrix[0, 0] + cov_yy = cov_matrix[2, 2] + cov_xy = cov_matrix[0, 2] + + phi = -0.5 * np.arctan2(2 * cov_xy, cov_xx - cov_yy) + sin_phi = np.sin(phi) + cos_phi = np.cos(phi) + rx = 2.0 * np.sqrt(abs(cov_xx * cos_phi**2 + cov_yy * sin_phi**2 - 2.0 * cov_xy * sin_phi * cos_phi)) + ry = 2.0 * np.sqrt(abs(cov_xx * sin_phi**2 + cov_yy * cos_phi**2 + 2.0 * cov_xy * sin_phi * cos_phi)) + + bunch_length = self.rms_bunch_length_factor * np.sqrt(cov_matrix[4, 4]) + perveance = self.sc_factor / bunch_length + kappa_factor = 2.0 * perveance / (rx + ry) + + M = np.identity(7) + M[1, 0] = kappa_factor * length / rx + M[3, 2] = kappa_factor * length / ry + + # Build matrix A to transform out of normalized frame. + A = np.eye(7) + A[0, 0] = A[1, 1] = +cos_phi + A[0, 2] = A[1, 3] = +sin_phi + A[2, 0] = A[3, 1] = -sin_phi + A[2, 2] = A[3, 3] = +cos_phi + + A_inv = A.T + + # Build matrix T to shift to beam centroid. + T = np.identity(7) + T[0, -1] = centroid[0] + T[2, -1] = centroid[2] + + T_inv = np.copy(T) + T_inv[:-1, -1] = -T[:-1, -1] + + # Compute transfer matrix in lab frame. + return T @ A @ M @ A_inv @ T_inv + + def sc_matrix_3d(self, length: float) -> np.ndarray: + # Build Lorentz matrix: rest frame to lab frame. + # x -> x + # y -> y + # z -> z / gamma + # x' = dx/ds -> x' * gamma + # y' = dy/ds -> y' * gamma + # z' = dz/ds -> z' + gamma = self.gamma + gamma_inv = 1.0 / gamma + + L = np.identity(7) + L[1, 1] = gamma + L[3, 3] = gamma + L[4, 4] = gamma_inv + L_inv = np.diag(1.0 / np.diag(L)) + + # Get centroid in rest frame. + centroid = np.matmul(L_inv[:-1, :-1], self.centroid) + + # Get covariance matrix in rest frame. + cov_matrix = L_inv[:-1, :-1] @ self.cov_matrix @ L_inv[:-1, :-1].T + + # Project covariance matrix onto x-y-z plane. + cov_matrix_proj = proj_cov_matrix(cov_matrix, axis=(0, 2, 4)) + + # Compute eigenvalues and eigenvectors of x-y-z covariance matrix. + cov_eig_res = np.linalg.eigh(cov_matrix_proj) + cov_eig_vals = cov_eig_res.eigenvalues + cov_eig_vecs = cov_eig_res.eigenvectors + + # Build transfer matrix in upright frame. + cov_xx, cov_yy, cov_zz = cov_eig_vals + RDx = scipy.special.elliprd(cov_yy, cov_zz, cov_xx) + RDy = scipy.special.elliprd(cov_xx, cov_zz, cov_yy) + RDz = scipy.special.elliprd(cov_xx, cov_yy, cov_zz) + + factor = 0.5 * self.sc_factor * ((1.0 / 5.0) ** 1.5) + kappa_x = factor * RDx + kappa_y = factor * RDy + kappa_z = factor * RDz + + M = np.identity(7) + M[1, 0] = kappa_x * length + M[3, 2] = kappa_y * length + M[5, 4] = kappa_z * length + + # Build matrix to undo x-y-z diagonalization. + A = build_diag_matrix_from_xyz_eig(cov_eig_vecs) + A_inv = A.T + + # Build matrix for translation to centroid. + T = np.identity(7) + for i in (0, 2, 4): + T[i, -1] = centroid[i] + + T_inv = np.copy(T) + T_inv[:-1, -1] = -T[:-1, -1] + + # Compute transfer matrix in lab frame. + M = L @ T @ A @ M @ A_inv @ T_inv @ L_inv + + # Convert from z' to dE + return convert_matrix_zp_to_dE(M, self.sync_part) diff --git a/py/orbit/envelope/matrix.py b/py/orbit/envelope/matrix.py new file mode 100644 index 00000000..ee0cebdb --- /dev/null +++ b/py/orbit/envelope/matrix.py @@ -0,0 +1,443 @@ +import math + +import numpy as np + +from orbit.core.bunch import Bunch +from orbit.core.bunch import SyncParticle +from orbit.lattice import AccNode +from orbit.teapot import ApertureTEAPOT +from orbit.teapot import DriftTEAPOT +from orbit.teapot import BendTEAPOT +from orbit.teapot import KickTEAPOT +from orbit.teapot import MonitorTEAPOT +from orbit.teapot import MultipoleTEAPOT +from orbit.teapot import NodeTEAPOT +from orbit.teapot import QuadTEAPOT +from orbit.teapot import SolenoidTEAPOT +from orbit.teapot import FringeFieldTEAPOT +from orbit.teapot import BunchWrapTEAPOT +from orbit.teapot import TiltTEAPOT +from orbit.teapot import ContinuousLinearFocusingTEAPOT +from orbit.teapot import TurnCounterTEAPOT +from orbit.py_linac.lattice import MarkerLinacNode as MarkerLINAC +from orbit.py_linac.lattice import Drift as DriftLINAC +from orbit.py_linac.lattice import Quad as QuadLINAC +from orbit.py_linac.lattice import Bend as BendLINAC +from orbit.py_linac.lattice import DCorrectorH as DCorrectorHLINAC +from orbit.py_linac.lattice import DCorrectorV as DCorrectorVLINAC +from orbit.py_linac.lattice import Solenoid as SolenoidLINAC +from orbit.py_linac.lattice import TiltElement as TiltLINAC +from orbit.py_linac.lattice import FringeField as FringeFieldLINAC +from orbit.py_linac.lattice import BaseRF_Gap as BaseRF_Gap +from orbit.py_linac.lattice import LinacApertureNode as ApertureLINAC +from orbit.utils.consts import speed_of_light + +from .envelope import Envelope +from .utils import get_dp_p_coeff + + +IGNORE_NODE_TYPES = [ + NodeTEAPOT, + MonitorTEAPOT, + FringeFieldTEAPOT, + ApertureTEAPOT, + BunchWrapTEAPOT, + TurnCounterTEAPOT, + MarkerLINAC, + FringeFieldLINAC, +] + + +def get_matrix_tilt(angle: float) -> np.ndarray: + cos_phi = math.cos(angle) + sin_phi = math.sin(angle) + + M = np.identity(7) + M[0, 0] = M[1, 1] = +cos_phi + M[0, 2] = M[1, 3] = -sin_phi + M[2, 0] = M[3, 1] = +sin_phi + M[2, 2] = M[3, 3] = +cos_phi + return M + + +def get_matrix_kick(kx: float = 0.0, ky: float = 0.0, kE: float = 0.0) -> np.ndarray: + M = np.identity(7) + M[1, -1] = kx + M[3, -1] = ky + M[5, -1] = kE + return M + + +def get_matrix_drift(envelope: Envelope, length: float) -> np.ndarray: + sync_part = envelope.sync_part + + M = np.identity(7) + M[0, 1] = length + M[2, 3] = length + M[4, 5] = length / (sync_part.gamma() ** 2) + M[4, 5] *= get_dp_p_coeff(sync_part) # convert_matrix_dp_p_to_dE(M, sync_part) + + sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + return M + + +def get_matrix_quad(envelope: Envelope, length: float, kq: float) -> np.ndarray: + if abs(kq) == 0: + return get_matrix_drift(envelope=envelope, length=length) + + sync_part = envelope.sync_part + + sqrt_abs_kq = math.sqrt(abs(kq)) + + M = np.identity(7) + if kq > 0: + cx = np.cos(sqrt_abs_kq * length) + sx = np.sin(sqrt_abs_kq * length) + cy = np.cosh(sqrt_abs_kq * length) + sy = np.sinh(sqrt_abs_kq * length) + M[0, 0] = cx + M[0, 1] = +sx / sqrt_abs_kq + M[1, 0] = -sx * sqrt_abs_kq + M[1, 1] = cx + M[2, 2] = cy + M[2, 3] = sy / sqrt_abs_kq + M[3, 2] = sy * sqrt_abs_kq + M[3, 3] = cy + elif kq < 0: + cx = np.cosh(sqrt_abs_kq * length) + sx = np.sinh(sqrt_abs_kq * length) + cy = np.cos(sqrt_abs_kq * length) + sy = np.sin(sqrt_abs_kq * length) + M[0, 0] = cx + M[0, 1] = sx / sqrt_abs_kq + M[1, 0] = sx * sqrt_abs_kq + M[1, 1] = cx + M[2, 2] = cy + M[2, 3] = +sy / sqrt_abs_kq + M[3, 2] = -sy * sqrt_abs_kq + M[3, 3] = cy + + M[4, 5] = length / (sync_part.gamma()**2) + M[4, 5] *= get_dp_p_coeff(sync_part) # convert_matrix_dp_p_to_dE(M, sync_part) + + sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + return M + + +def get_matrix_bend(envelope: Envelope, length: float, theta: float) -> np.ndarray: + sync_part = envelope.sync_part + + rho = length / theta + cx = math.cos(theta) + sx = math.sin(theta) + + M = np.identity(7) + M[0, 0] = cx + M[0, 1] = rho * sx + M[0, 5] = rho * (1.0 - cx) + M[1, 0] = -sx / rho + M[1, 1] = cx + M[1, 5] = sx + M[2, 3] = length + M[4, 0] = -sx + M[4, 1] = -rho * (1.0 - cx) + M[4, 5] = -(sync_part.beta() ** 2) * length + rho * sx + M[:5, 5] *= get_dp_p_coeff(sync_part) # convert_matrix_dp_p_to_dE(M, sync_part) + + sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + return M + + +def get_matrix_solenoid(envelope: Envelope, length: float, B: float) -> np.ndarray: + if B == 0: + return get_matrix_drift(envelope=envelope, length=length) + + sync_part = envelope.sync_part + + phase = B * length + + V = np.identity(7) + V[:4, :4] = 0.0 + V[0, 1] = -1.0 / B + V[0, 2] = 0.5 + V[1, 0] = 0.5 * B + V[1, 3] = 1.0 + V[2, 1] = 1.0 / B + V[2, 2] = 0.5 + V[3, 0] = -0.5 * B + V[3, 3] = 1.0 + + M = np.identity(7) + M[0, 0] = +1.0 + M[1, 1] = -1.0 + M[2, 2] = math.cos(phase) + M[2, 3] = math.sin(phase) / B + M[3, 2] = math.sin(phase) * B * -1.0 + M[3, 3] = math.cos(phase) + M[4, 5] = length / (sync_part.gamma()**2) + + M = np.linalg.inv(V) @ M @ V + M[4, 5] *= get_dp_p_coeff(sync_part) # convert_matrix_dp_p_to_dE(M, sync_part) + + sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + return M + + +def get_matrix_cf(envelope: Envelope, length: float, kq: float) -> np.ndarray: + if kq == 0: + return get_matrix_drift(envelope=envelope, length=length) + + sync_part = envelope.sync_part + + sqrt_abs_kq = math.sqrt(abs(kq)) + + cx = math.cos(sqrt_abs_kq * length) + sx = math.sin(sqrt_abs_kq * length) + + M = np.identity(7) + M[0, 0] = M[2, 2] = cx + M[0, 1] = M[2, 3] = +sx / sqrt_abs_kq + M[1, 0] = M[3, 2] = -sx * sqrt_abs_kq + M[1, 1] = M[3, 3] = cx + M[4, 5] = length / (sync_part.gamma()**2) + M[4, 5] *= get_dp_p_coeff(sync_part) + + sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + return M + + +def get_matrix_rf_gap(envelope: Envelope, frequency: float, E0TL: float, phase: float) -> np.ndarray: + sync_part = envelope.sync_part + + gamma = sync_part.gamma() + beta = sync_part.beta() + mass = sync_part.mass() + charge = envelope.charge + + kin_energy_in = sync_part.kinEnergy() + charge_E0TL_sin = charge * E0TL * math.sin(phase) + kin_energy_delta = charge * E0TL * math.cos(phase) + + # Calculate parameters in the center of the gap. + sync_part.momentum(sync_part.energyToMomentum(kin_energy_in + kin_energy_delta / 2.0)) + gamma_gap = sync_part.gamma() + beta_gap = sync_part.beta() + + # Move to the end of the gap. + kin_energy_out = kin_energy_in + kin_energy_delta + sync_part.momentum(sync_part.energyToMomentum(kin_energy_out)) + + # The base RF gap is simple - no phase correction. + gamma_out = sync_part.gamma() + beta_out = sync_part.beta() + prime_coeff = (beta * gamma) / (beta_out * gamma_out) + + # Wave momentum + k = 2.0 * math.pi * frequency / speed_of_light + phase_time_coeff = k / beta + + # Transverse focusing coefficient + kappa = -charge * E0TL * k / (2.0 * mass * beta_gap**2 * beta_out * gamma_gap**2 * gamma_out) + d_rp = kappa * math.sin(phase) + + M = np.eye(7) + M[5, 4] = charge_E0TL_sin * phase_time_coeff + M[4, 4] = beta_out / beta + M[1, 1] = prime_coeff + M[3, 3] = prime_coeff + M[1, 0] = d_rp + M[3, 2] = d_rp + return M + + +def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + """Calculate transfer matrix and update synchronous particle. + + This function maps various accelerator nodes to 7 x 7 transfer matrices + for envelope tracking. For non-accelerating, finite-length nodes, the + synchronous particle time is updated as in a drift. Accelerating nodes + such as RF gaps will update the synchronous particle energy. + + Args: + node: The accelerator node. + envelope: The beam envelope. + part_index: Index of the part within the node. An index of -1 returns + the transfer matrix for the entire node. + Returns: + 7 x 7 transfer matrix or None. If None, the node can be ignored during + envelope tracking. + """ + + node_type = type(node) + if node_type in IGNORE_NODE_TYPES: + return None + + length = node.getLength(part_index) + nparts = node.getnParts() + + if node_type is DriftTEAPOT: + if length <= 0: + return None + return get_matrix_drift(envelope=envelope, length=length) + + elif node_type is SolenoidTEAPOT: + if length <= 0: + return None + + B = node.getParam("B") + if node.waveform: + B *= node.waveform.getStrength() + B *= envelope.charge_sign + + return get_matrix_solenoid(envelope=envelope, length=length, B=B) + + elif node_type is MultipoleTEAPOT: + if length <= 0: + return None + + if np.all(np.abs(node.getParam("kls")) == 0): + return get_matrix_drift(envelope=envelope, length=length) + + elif node_type is QuadTEAPOT: + if length <= 0: + return None + + kq = node.getParam("kq") + if node.waveform: + kq *= node.waveform.getStrength() + kq *= envelope.charge_sign + + return get_matrix_quad(envelope=envelope, length=length, kq=kq) + + elif node_type is BendTEAPOT: + if length <= 0: + return None + + theta = node.getParam("theta") / (nparts - 1) + if part_index == 0 or part_index == nparts - 1: + theta *= 0.5 + theta *= envelope.charge_sign + + return get_matrix_bend(envelope=envelope, length=length, theta=theta) + + elif node_type is KickTEAPOT: + scale = 1.0 + if node.waveform is not None: + scale = node.waveform.getStrength() + + scale /= (nparts - 1) + kx = scale * node.getParam("kx") + ky = scale * node.getParam("ky") + kE = node.getParam("dE") + + if abs(kx) > 0 or abs(ky) > 0 or abs(kE) > 0: + return np.matmul( + get_matrix_kick(kx=kx, ky=ky, kE=kE), + get_matrix_drift(envelope=envelope, length=length), + ) + else: + return get_matrix_drift(envelope=envelope, length=length) + + elif node_type is TiltTEAPOT: + angle = node.getTiltAngle() + if angle == 0: + return None + return get_matrix_tilt(angle) + + elif node_type is ContinuousLinearFocusingTEAPOT: + if length <= 0: + return None + + kq = node.getParam("kq") + kq *= envelope.charge_sign + if node.waveform: + kq *= node.waveform.getStrength() + + return get_matrix_cf(envelope=envelope, length=length, kq=kq) + + elif node_type is DriftLINAC: + if length <= 0: + return None + return get_matrix_drift(envelope=envelope, length=length) + + elif node_type is QuadLINAC: + if length <= 0: + return None + + brho = 3.335640952 * envelope.momentum / envelope.charge + kq = node.getParam("dB/dr") / brho + return get_matrix_quad(envelope=envelope, length=length, kq=kq) + + elif node_type is BendLINAC: + if length <= 0: + return None + + theta = node.getParam("theta") / (nparts - 1) + if part_index == 0 or part_index == nparts - 1: + theta *= 0.5 + theta *= envelope.charge_sign + + return get_matrix_bend(envelope=envelope, length=length, theta=theta) + + elif node_type is DCorrectorHLINAC: + length = node.getParam("effLength") / nparts + field = node.getParam("B") + delta_xp = -field * envelope.charge * length * 0.299792 / envelope.momentum + if delta_xp == 0: + return None + return get_matrix_kick(kx=delta_xp, ky=0.0, kE=0.0) + + elif node_type is DCorrectorVLINAC: + length = node.getParam("effLength") / nparts + field = node.getParam("B") + delta_yp = -field * envelope.charge * length * 0.299792 / envelope.momentum + if delta_yp == 0: + return None + return get_matrix_kick(kx=0.0, ky=delta_yp, kE=0.0) + + elif node_type is SolenoidLINAC: + if length <= 0: + return None + B = node.getParam("B") * envelope.charge_sign + return get_matrix_solenoid(envelope=envelope, length=length, B=B) + + elif node_type is TiltLINAC: + angle = node.getTiltAngle() + if angle == 0: + return None + return get_matrix_tilt(angle=angle) + + elif node_type is BaseRF_Gap: + E0TL = node.getParam("E0TL") + mode_phase = node.getParam("mode") * math.pi + + cavity = node.getRF_Cavity() + frequency = cavity.getFrequency() + phase = cavity.getPhase() + mode_phase + amplitude = cavity.getAmp() + + sync_part = envelope.sync_part + arrival_time = sync_part.time() + arrival_time_design = cavity.getDesignArrivalTime() + + if node.isFirstRFGap(): + if cavity.isDesignSetUp(): + phase = math.fmod(frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, 2.0 * math.pi) + else: + orbitFinalize("Run `trackDesign` first to initialize cavity phases.") + else: + phase = math.fmod(frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase,2.0 * math.pi) + + node.setGapPhase(phase) + + if amplitude == 0.0: + return None + + return get_matrix_rf_gap( + envelope=envelope, + frequency=frequency, + E0TL=(E0TL * amplitude), + phase=phase, + ) + + raise NotImplementedError(str(node)) \ No newline at end of file diff --git a/py/orbit/envelope/meson.build b/py/orbit/envelope/meson.build new file mode 100644 index 00000000..90eab844 --- /dev/null +++ b/py/orbit/envelope/meson.build @@ -0,0 +1,14 @@ +py_sources = files([ + '__init__.py', + 'envelope.py', + 'matrix.py', + 'track.py', + 'utils.py' +]) + +python.install_sources( + py_sources, + subdir: 'orbit/envelope', + # pure: true, +) + diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py new file mode 100644 index 00000000..98653fe9 --- /dev/null +++ b/py/orbit/envelope/track.py @@ -0,0 +1,232 @@ +import numpy as np +import warnings + +from orbit.core.bunch import Bunch +from orbit.core.bunch import SyncParticle +from orbit.lattice import AccNode +from orbit.lattice import AccLattice +from orbit.teapot import BendTEAPOT +from orbit.py_linac.lattice import Bend as BendLINAC + +from .matrix import get_matrix +from .envelope import Envelope + + +ENTRANCE = AccNode.ENTRANCE +BODY = AccNode.BODY +EXIT = AccNode.EXIT + +BEFORE = AccNode.BEFORE +AFTER = AccNode.AFTER + + +class EnvelopeTracker: + def __init__(self, lattice: AccLattice, sc: str | None = None) -> None: + """Constructor. + + Args: + lattice: The accelerator lattice. + sc: Envelope space charge model {"2d", "3d", None}. + """ + self.lattice = lattice + self.sc = sc + + # For pre-computing elements + self.elements = [] + self.one_turn_matrix = None + # [TO DO] option to return one-turn matrix including linear space charge + + for node in self.lattice.getNodes(): + if type(node) in (BendTEAPOT, BendLINAC): + if node.getParam("ea1") != 0.0 or node.getParam("ea2") != 0.0: + message = f"Found bend ea1 or ea2 != 0.0 ({node.getName()}.)" + message += " Nonzero edge angles are not yet supported in envelope tracking." + message += " Setting ea1 and ea2 to 0.0." + warnings.warn(message) + + node.setParam("ea1", 0.0) + node.setParam("ea2", 0.0) + + def track(self, envelope: Envelope) -> None: + """Track envelope through lattice. + + This is not recursive, so grandchild nodes are not tracked. + """ + for node_index, node in enumerate(self.lattice.getNodes()): + for child_node in node.getChildNodes(ENTRANCE): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + envelope.transform(matrix) + + for part_index in range(node.getnParts()): + for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + envelope.transform(matrix) + + matrix_sc = None + if self.sc: + length = node.getLength(part_index) + if length > 0: + if self.sc == "2d": + matrix_sc = envelope.sc_matrix_2d(length) + elif self.sc == "3d": + matrix_sc = envelope.sc_matrix_3d(length) + else: + raise ValueError + + matrix = get_matrix(node, envelope=envelope, part_index=part_index) + if matrix is not None: + if matrix_sc is not None: + matrix = matrix @ matrix_sc + envelope.transform(matrix) + + for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + envelope.transform(matrix) + + for child_node in node.getChildNodes(EXIT): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + envelope.transform(matrix) + + def track_history(self, envelope: Envelope) -> dict[str, list]: + """Track and return envelope parameters vs. position in lattice.""" + history = {} + history["position"] = [] + history["rms_x"] = [] + history["rms_y"] = [] + history["rms_z"] = [] + history["kin_energy"] = [] + + node_positions = self.lattice.getNodePositionsDict() + + history["position"].append(0.0) + history["rms_x"].append(1000.0 * envelope.rms(0)) + history["rms_y"].append(1000.0 * envelope.rms(2)) + history["rms_z"].append(1000.0 * envelope.rms(4)) + history["kin_energy"].append(envelope.sync_part.kinEnergy()) + + for node_index, node in enumerate(self.lattice.getNodes()): + for child_node in node.getChildNodes(ENTRANCE): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + envelope.transform(matrix) + + for part_index in range(node.getnParts()): + for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + envelope.transform(matrix) + + matrix_sc = None + if self.sc: + length = node.getLength(part_index) + if length > 0: + if self.sc == "2d": + matrix_sc = envelope.sc_matrix_2d(length) + elif self.sc == "3d": + matrix_sc = envelope.sc_matrix_3d(length) + else: + raise ValueError + + matrix = get_matrix(node, envelope=envelope, part_index=part_index) + if matrix is not None: + if matrix_sc is not None: + matrix = matrix @ matrix_sc + envelope.transform(matrix) + + position_start, position_stop = node_positions[node] + position = position_start + node.getLength(part_index) * (part_index + 1) + + history["position"].append(position) + history["rms_x"].append(1000.0 * envelope.rms(0)) + history["rms_y"].append(1000.0 * envelope.rms(2)) + history["rms_z"].append(1000.0 * envelope.rms(4)) + history["kin_energy"].append(envelope.sync_part.kinEnergy()) + + for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + envelope.transform(matrix) + + for child_node in node.getChildNodes(EXIT): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + envelope.transform(matrix) + + return history + + def precompute_matrices(self, envelope: Envelope) -> None: + """Pre-compute transfer matrices for each node. + + For each node, return tuple (node, matrix). Mark space charge kicks as ("sc", length). + """ + self.elements = [] + for node_index, node in enumerate(self.lattice.getNodes()): + for child_node in node.getChildNodes(ENTRANCE): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + self.elements.append((child_node, matrix)) + + for part_index in range(node.getnParts()): + for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + self.elements.append((child_node, matrix)) + + if self.sc: + length = node.getLength(part_index) + if length > 0: + self.elements.append(("sc", length)) + + matrix = get_matrix(node, envelope=envelope, part_index=part_index) + if matrix is not None: + self.elements.append((node, matrix)) + + for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + self.elements.append((node, matrix)) + + for child_node in node.getChildNodes(EXIT): + matrix = get_matrix(child_node, envelope=envelope) + if matrix is not None: + self.elements.append((node, matrix)) + + def track_ring(self, envelope: Envelope) -> None: + """Track using pre-computed transfer matrices. + + The method assumes that all nodes are static and that there is no + change in the synchronous particle energy. In this case the matrices + can be computed once and reused on each turn. If there is no space charge, + we track using the one-turn matrix. + """ + + # Pre-compute transfer matrices on the first turn. + if not self.elements: + self.precompute_matrices(envelope) + self.one_turn_matrix = None + + # If there is no space charge, apply the one-turn transfer matrix. + if not self.sc: + if self.one_turn_matrix is None: + self.one_turn_matrix = np.identity(7) + for (node, matrix) in self.elements: + self.one_turn_matrix = np.matmul(self.one_turn_matrix, matrix) + return envelope.transform(self.one_turn_matrix) + + # If there is space charge, apply the matrices one-by-one. + for element in self.elements: + if element[0] == "sc": + length = element[1] + if self.sc == "2d": + envelope.transform(envelope.sc_matrix_2d(length)) + elif self.sc == "3d": + envelope.transform(envelope.sc_matrix_3d(length)) + else: + raise ValueError + else: + node, matrix = element + envelope.transform(matrix) diff --git a/py/orbit/envelope/utils.py b/py/orbit/envelope/utils.py new file mode 100644 index 00000000..71499e31 --- /dev/null +++ b/py/orbit/envelope/utils.py @@ -0,0 +1,99 @@ +import math +import numpy as np +from scipy.constants import epsilon_0 + +from orbit.core.bunch import SyncParticle +from orbit.utils.consts import charge_electron + + +def get_classical_radius(charge: float, mass: float) -> float: + q = charge * charge_electron # [C] + rest_energy = mass * 1e9 * charge_electron # [J] + return q**2 / (4.0 * math.pi * epsilon_0 * rest_energy) + + +def get_dp_p_coeff(sync_part: SyncParticle) -> float: + # dE/E = (beta^2) * dp/p + # dE = (beta^2 * E) * dp/p + # dE = (beta^2 * gamma * m * c^2) * dp/p + beta = sync_part.beta() + gamma = sync_part.gamma() + rest_energy = sync_part.mass() # GeV + return 1.0 / (beta**2 * gamma * rest_energy) + + +def get_zp_coeff(sync_part: SyncParticle) -> float: + # dE/E = (beta^2) * dp/p = (beta^2) * (gamma^2) z' + # dE = (beta^2 * gamma^2 * E) * z' + # dE = (beta^2 * gamma^3 * m * c^2) * z' + beta = sync_part.beta() + gamma = sync_part.gamma() + rest_energy = sync_part.mass() + return 1.0 / (beta**2 * gamma**3 * rest_energy) + + +def convert_matrix_dp_p_to_dE(matrix: np.ndarray, sync_part: SyncParticle) -> np.ndarray: + # v = [x, x', y, y', z, dp/p] + # w = [x, x', y, y', z, dE] + # v = A w + # v -> M v + # w -> A M A^-1 + dp_p_coeff = get_dp_p_coeff(sync_part) + matrix[:5, 5] *= dp_p_coeff + matrix[5, :5] /= dp_p_coeff + matrix[5, 6] /= dp_p_coeff # driving term + return matrix + + +def convert_matrix_zp_to_dE(matrix: np.ndarray, sync_part: SyncParticle) -> np.ndarray: + zp_coeff = get_zp_coeff(sync_part) + matrix[:5, 5] *= zp_coeff + matrix[5, :5] /= zp_coeff + matrix[5, 6] /= zp_coeff # driving term + return matrix + + +def gen_dist_gauss(size: int, cov_matrix: np.ndarray) -> np.ndarray: + return np.random.multivariate_normal( + mean=np.zeros(cov_matrix.shape[0]), + cov=cov_matrix, + size=size, + ) + + +def gen_dist_kv(size: int, cov_matrix: np.ndarray) -> np.ndarray: + X = np.random.normal(size=(size, cov_matrix.shape[0])) + X /= np.linalg.norm(X, axis=1)[:, None] + X /= np.std(X, axis=0) + return X + + +def gen_dist_waterbag(size: int, cov_matrix: np.ndarray) -> np.ndarray: + X = gen_dist_kv(size, cov_matrix) + dim = X.shape[1] + r = np.random.uniform(size=size) ** (1.0 / dim) + X *= r[:, None] + X /= np.std(X, axis=0) + return X + + +def gen_dist(size: int, cov_matrix: np.ndarray, name: str) -> np.ndarray: + if name == "kv": + X = gen_dist_kv(size, cov_matrix) + elif name == "waterbag": + X = gen_dist_waterbag(size, cov_matrix) + elif name == "gauss": + X = gen_dist_gauss(size, cov_matrix) + else: + raise ValueError(f"Invalid distribution name: {name}") + + L = np.linalg.cholesky(cov_matrix) + return np.matmul(X, L.T) + + +def proj_cov_matrix(cov_matrix: np.ndarray, axis: tuple[int, ...]) -> np.ndarray: + cov_matrix_proj = np.zeros((len(axis), len(axis))) + for i in range(len(axis)): + for j in range(len(axis)): + cov_matrix_proj[i, j] = cov_matrix[axis[i], axis[j]] + return cov_matrix_proj diff --git a/py/orbit/meson.build b/py/orbit/meson.build index 2ba16e73..651b14d5 100644 --- a/py/orbit/meson.build +++ b/py/orbit/meson.build @@ -24,6 +24,7 @@ subdir('space_charge') subdir('errors') subdir('matrix_lattice') subdir('teapot') +subdir('envelope') py_sources = files([ diff --git a/py/orbit/py_linac/lattice/__init__.py b/py/orbit/py_linac/lattice/__init__.py index 85a9df80..eb9ed985 100644 --- a/py/orbit/py_linac/lattice/__init__.py +++ b/py/orbit/py_linac/lattice/__init__.py @@ -13,6 +13,8 @@ from orbit.py_linac.lattice.LinacAccNodes import Solenoid from orbit.py_linac.lattice.LinacAccNodes import DCorrectorH, DCorrectorV from orbit.py_linac.lattice.LinacAccNodes import ThickKick +from orbit.py_linac.lattice.LinacAccNodes import TiltElement +from orbit.py_linac.lattice.LinacAccNodes import FringeField from orbit.py_linac.lattice.LinacRfGapNodes import BaseRF_Gap, AxisFieldRF_Gap, RF_AxisFieldsStore @@ -56,7 +58,6 @@ __all__.append("Bend") __all__.append("Solenoid") - __all__.append("LinacApertureNode") __all__.append("CircleLinacApertureNode") __all__.append("EllipseLinacApertureNode") @@ -64,7 +65,6 @@ __all__.append("LinacPhaseApertureNode") __all__.append("LinacEnergyApertureNode") - __all__.append("RF_Cavity") __all__.append("Sequence") @@ -91,3 +91,6 @@ __all__.append("LinacTrMatricesController") __all__.append("LinacBPM") + +__all__.append("FringeField") +__all__.append("TiltElement") diff --git a/py/orbit/teapot/__init__.py b/py/orbit/teapot/__init__.py index b77d9cc8..9f62adfc 100644 --- a/py/orbit/teapot/__init__.py +++ b/py/orbit/teapot/__init__.py @@ -18,6 +18,9 @@ from .teapot import TiltTEAPOT from .teapot import NodeTEAPOT from .teapot import ContinuousLinearFocusingTEAPOT +from .teapot import ApertureTEAPOT +from .teapot import MonitorTEAPOT +from .teapot import TurnCounterTEAPOT from .teapot import TPB @@ -41,3 +44,6 @@ __all__.append("ContinuousLinearFocusingTEAPOT") __all__.append("TPB") __all__.append("TEAPOT_MATRIX_Lattice") +__all__.append("ApertureTEAPOT") +__all__.append("MonitorTEAPOT") +__all__.append("TurnCounterTEAPOT") \ No newline at end of file diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py new file mode 100644 index 00000000..16f1e5c7 --- /dev/null +++ b/tests/py/orbit/test_env.py @@ -0,0 +1,383 @@ +import numpy as np + +from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis +from orbit.core.linac import MatrixRfGap +from orbit.bunch_utils import collect_bunch +from orbit.envelope import Envelope +from orbit.envelope import EnvelopeTracker +from orbit.lattice import AccNode +from orbit.lattice import AccLattice +from orbit.py_linac.lattice import Drift +from orbit.py_linac.lattice import Quad +from orbit.py_linac.lattice import Bend +from orbit.py_linac.lattice import TiltElement +from orbit.py_linac.lattice import Solenoid +from orbit.teapot import BendTEAPOT +from orbit.teapot import ContinuousLinearFocusingTEAPOT +from orbit.teapot import DriftTEAPOT +from orbit.teapot import KickTEAPOT +from orbit.teapot import QuadTEAPOT +from orbit.teapot import SolenoidTEAPOT +from orbit.teapot import TiltTEAPOT +from orbit.teapot import TEAPOT_Lattice +from orbit.utils.consts import mass_proton + + +def get_lorentz_factors(kin_energy: float, mass: float) -> tuple[float, float]: + gamma = 1.0 + kin_energy / mass + beta = np.sqrt(1.0 - (1.0 / gamma) ** 2) + return (gamma, beta) + + +def calc_bunch_cov(bunch: Bunch) -> np.ndarray: + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) + + 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] + return cov_matrix + + +def make_lattice(nodes: list[AccNode]) -> AccLattice: + lattice = TEAPOT_Lattice() + for node in nodes: + lattice.addNode(node) + + lattice.initialize() + + for node in lattice.getNodes(): + try: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + except: + pass + + return lattice + + +def track_and_compare_rms( + lattice: AccLattice, + kin_energy: float, + cov_matrix: np.ndarray, + nparts: int = 100_000, + verbose: int = 1, +) -> dict: + """Track bunch/envelope and compare rms beam sizes. + + Args: + lattice: Accelerator lattice. + kin_energy: Synchronous particle kinetic energy [GeV]. + cov_matrix: 6 x 6 covariance matrix. + nparts: Number of particles in bunch. + verbose: Whether to print results. + """ + cov_scale = 1e6 + + data = {} + for k1 in ["env", "bunch"]: + data[k1] = {} + for k2 in ["rms", "cov"]: + data[k1][k2] = {} + for k3 in ["env", "bunch"]: + data[k1][k2][k3] = {} + + # Initialize bunch + bunch = Bunch() + bunch.mass(mass_proton) + bunch.getSyncParticle().kinEnergy(kin_energy) + + # Track bunch + particles = np.random.multivariate_normal(np.zeros(6), cov_matrix, size=nparts) + for x in particles: + bunch.addParticle(*x) + + # Covariance matrix calculated from particles will be slightly different. + cov_matrix = calc_bunch_cov(bunch) + + data["bunch"]["cov"]["in"] = cov_scale * calc_bunch_cov(bunch) + lattice.trackBunch(bunch) + data["bunch"]["cov"]["out"] = cov_scale * calc_bunch_cov(bunch) + + # Track envelope + envelope = Envelope(bunch=bunch, cov_matrix=cov_matrix) + envelope_tracker = EnvelopeTracker(lattice=lattice) + + data["env"]["cov"]["in"] = cov_scale * envelope.cov_matrix + envelope_tracker.track(envelope) + data["env"]["cov"]["out"] = cov_scale * envelope.cov_matrix + + # Compare + for mode in ["env", "bunch"]: + for loc in ["in", "out"]: + data[mode]["rms"][loc] = np.sqrt(np.diag(data[mode]["cov"][loc])) + + if verbose: + dims = ["x", "xp", "y", "yp", "z", "dE"] + for key in ["in", "out"]: + print(key.upper()) + for i in range(6): + print(" rms {}:".format(dims[i])) + print(" env: {}".format(data["env"]["rms"][key][i])) + print(" bunch: {}".format(data["bunch"]["rms"][key][i])) + + assert np.all(np.isclose(data["env"]["cov"]["in"], data["bunch"]["cov"]["in"])) + + atol = np.ones(6) + atol[0:4] = 1e-3 # [mm mrad] + atol[4] = 1e-3 # [mm] + atol[5] = 1e-3 # [MeV] + + for i in range(6): + x = data["env"]["rms"]["out"][i] + y = data["bunch"]["rms"]["out"][i] + assert np.abs(x - y) <= atol[i] + + +def make_default_cov_matrix( + rms_x: float = 1e-3, + rms_xp: float = 1e-3, + rms_y: float = 1e-3, + rms_yp: float = 1e-3, + rms_z: float = 1e-3, + rms_dE: float = 1e-5, +) -> np.ndarray: + return np.diag(np.square([rms_x, rms_xp, rms_y, rms_yp, rms_z, rms_dE])) + + +def test_drift_teapot( + kin_energy: float = 0.0025, + length: float = 1.0, + cov_matrix: np.ndarray = None, + nparts: int = 6, +) -> None: + node = DriftTEAPOT(length=length, nparts=nparts) + lattice = make_lattice([node]) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_drift_linac( + kin_energy: float = 0.0025, + length: float = 1.0, + cov_matrix: np.ndarray = None, + nparts: int = 6, +) -> None: + node = Drift() + node.setLength(length) + node.setnParts(nparts) + nodes = [node] + + lattice = make_lattice(nodes) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_quad_teapot( + kin_energy: float = 0.0025, + length: float = 1.0, + kq: float = 1.0, + cov_matrix: np.ndarray = None, + nparts: int = 10, +) -> None: + node = QuadTEAPOT(length=length, kq=kq, nparts=nparts) + lattice = make_lattice([node]) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_cf_teapot( + kin_energy: float = 0.0025, + length: float = 10.0, + kq: float = 1.0, + nparts: int = 10, +) -> None: + node = ContinuousLinearFocusingTEAPOT(length=length, kq=kq, nparts=nparts) + lattice = make_lattice([node]) + cov_matrix = np.diag(np.square([1e-3, 0, 1e-3, 0.0, 0.0, 0.0])) + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_quad_linac( + kin_energy: float = 0.0025, + length: float = 1.0, + field_grad: float = 0.23, + cov_matrix: np.ndarray = None, + nparts: int = 10, +) -> None: + node = Quad() + node.setLength(length) + node.setnParts(nparts) + node.setParam("dB/dr", field_grad) + nodes = [node] + + lattice = make_lattice(nodes) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_bend_teapot( + kin_energy: float = 0.0025, + length: float = 1.0, + theta: float = 20.0, + cov_matrix: np.ndarray = None, + nparts: int = 5, +) -> None: + node = BendTEAPOT(length=length, theta=np.radians(theta), nparts=nparts) + lattice = make_lattice([node]) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_bend_linac( + kin_energy: float = 0.0025, + length: float = 1.0, + theta: float = 20.0, + cov_matrix: np.ndarray = None, + nparts: int = 5, +) -> None: + node = Bend() + node.setLength(length) + node.setnParts(nparts) + node.setParam("theta", np.radians(theta)) + nodes = [node] + + lattice = make_lattice(nodes) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_kick_teapot( + kin_energy: float = 0.0025, + length: float = 0.1, + kx: float = 0.001, + ky: float = 0.001, + dE: float = 0.00001, + cov_matrix: np.ndarray = None, + nparts: int = 4, +) -> None: + node = KickTEAPOT(kx=kx, ky=ky, dE=dE, length=length, nparts=nparts) + lattice = make_lattice([node]) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_tilt_teapot( + kin_energy: float = 0.0025, + angle: float = 0.25 * np.pi, + cov_matrix: np.ndarray = None, +) -> None: + node = TiltTEAPOT(angle=angle) + lattice = make_lattice([node]) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_tilt_linac( + kin_energy: float = 0.0025, + angle: float = 0.25 * np.pi, + cov_matrix: np.ndarray = None, +) -> None: + node = TiltElement() + node.setTiltAngle(angle) + nodes = [node] + lattice = make_lattice(nodes) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_solenoid_teapot( + kin_energy: float = 0.0025, + length: float = 2.0, + B: float = 1.0, + cov_matrix: np.ndarray = None, + nparts: int = 10, +) -> None: + node = SolenoidTEAPOT(length=length, B=B, nparts=nparts) + lattice = make_lattice([node]) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_solenoid_linac( + kin_energy: float = 0.0025, + length: float = 2.0, + B: float = 1.0, + cov_matrix: np.ndarray = None, + nparts: int = 10, +) -> None: + node = Solenoid() + node.setLength(length) + node.setnParts(nparts) + node.setParam("B", B) + nodes = [node] + + lattice = make_lattice(nodes) + if cov_matrix is None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy, cov_matrix) + + +def test_rf_gap_matrix( + kin_energy: float = 0.0025, + frequency: float = 402.5e06, + E0TL: float = 0.001, + phase: float = 0.0, + charge: float = -1.0, +) -> None: + cov_matrix = make_default_cov_matrix() + + bunch_in = Bunch() + bunch_in.mass(mass_proton) + bunch_in.charge(charge) + bunch_in.getSyncParticle().kinEnergy(kin_energy) + + coords_in = np.random.multivariate_normal(np.zeros(6), cov_matrix, size=10) + for x in coords_in: + bunch_in.addParticle(*x) + + bunch_out_1 = Bunch() + bunch_in.copyBunchTo(bunch_out_1) + + matrix_rf_gap = MatrixRfGap() + matrix_rf_gap.trackBunch(bunch_out_1, frequency, E0TL, phase) + + coords_out_1 = collect_bunch(bunch_out_1)["coords"] + + from orbit.envelope.matrix import get_matrix_rf_gap + + bunch_out_2 = Bunch() + bunch_in.copyBunchTo(bunch_out_2) + + envelope = Envelope(bunch=bunch_in) + matrix = get_matrix_rf_gap( + envelope=envelope, + frequency=frequency, + E0TL=E0TL, + phase=phase, + ) + coords_in = np.column_stack([coords_in, np.ones(coords_in.shape[0])]) + coords_out_2 = np.matmul(coords_in, matrix.T) + coords_out_2 = coords_out_2[:, :-1] + assert np.allclose(coords_out_1, coords_out_2) + + +def test_sc_3d_cold_expansion(): + # This should test expansion of cold uniform-density sphere + # (in rest frame). We can calculate the time to expand to + # twice the initial size. (See examples from A. Shishlo or + # from the ImpactX repo.) + pass From debccafe3885292440c61c7b5274aa0f28118567 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Wed, 1 Jul 2026 15:53:56 -0400 Subject: [PATCH 02/42] Fix order in one-turn matrix calculation --- py/orbit/envelope/track.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py index 98653fe9..9b6840d3 100644 --- a/py/orbit/envelope/track.py +++ b/py/orbit/envelope/track.py @@ -214,7 +214,7 @@ def track_ring(self, envelope: Envelope) -> None: if self.one_turn_matrix is None: self.one_turn_matrix = np.identity(7) for (node, matrix) in self.elements: - self.one_turn_matrix = np.matmul(self.one_turn_matrix, matrix) + self.one_turn_matrix = matrix @ self.one_turn_matrix return envelope.transform(self.one_turn_matrix) # If there is space charge, apply the matrices one-by-one. @@ -230,3 +230,31 @@ def track_ring(self, envelope: Envelope) -> None: else: node, matrix = element envelope.transform(matrix) + + def get_effective_matrix(self, envelope: Envelope) -> np.ndarray: + if not self.elements: + self.precompute_matrices(envelope) + + if not self.sc: + one_turn_matrix = np.identity(7) + for (node, matrix) in self.elements: + one_turn_matrix = matrix @ one_turn_matrix + return one_turn_matrix + + one_turn_matrix = np.identity(7) + for element in self.elements: + if element[0] == "sc": + length = element[1] + if self.sc == "2d": + matrix = envelope.sc_matrix_2d(length) + elif self.sc == "3d": + matrix = envelope.sc_matrix_3d(length) + else: + raise ValueError + envelope.transform(matrix) + one_turn_matrix = matrix @ one_turn_matrix + else: + node, matrix = element + envelope.transform(matrix) + one_turn_matrix = matrix @ one_turn_matrix + return one_turn_matrix \ No newline at end of file From 2542a7ee291660aeaee5f1e347ed44d0bda2843b Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Fri, 3 Jul 2026 16:36:04 -0400 Subject: [PATCH 03/42] Fix path length in track_history --- examples/Envelope/sns_linac/diagnostics.py | 16 ++--- examples/Envelope/sns_linac/test_sns_linac.py | 9 +-- py/orbit/envelope/envelope.py | 4 ++ py/orbit/envelope/track.py | 59 ++++++++++++------- 4 files changed, 51 insertions(+), 37 deletions(-) diff --git a/examples/Envelope/sns_linac/diagnostics.py b/examples/Envelope/sns_linac/diagnostics.py index 7edfebdd..72904f51 100644 --- a/examples/Envelope/sns_linac/diagnostics.py +++ b/examples/Envelope/sns_linac/diagnostics.py @@ -10,7 +10,7 @@ def __init__(self) -> None: self.position_start = 0.0 self.history = {} - self.history["position"] = [] + self.history["s"] = [] self.history["rms_x"] = [] self.history["rms_y"] = [] self.history["rms_z"] = [] @@ -37,19 +37,19 @@ def __call__(self, params_dict: dict) -> None: for j in range(6): cov_matrix[i, j] = cov_matrix[j, i] = self.twiss_calc.getCorrelation(i, j) - xrms = 1000.0 * np.sqrt(cov_matrix[0, 0]) - yrms = 1000.0 * np.sqrt(cov_matrix[2, 2]) - zrms = 1000.0 * np.sqrt(cov_matrix[4, 4]) + xrms = np.sqrt(cov_matrix[0, 0]) + yrms = np.sqrt(cov_matrix[2, 2]) + zrms = np.sqrt(cov_matrix[4, 4]) message = "" message += " s={:0.3f}".format(position + self.position_start) - message += " xrms={:0.3f}".format(xrms) - message += " yrms={:0.3f}".format(yrms) - message += " zrms={:0.3f}".format(zrms) + message += " xrms={:0.3f}".format(1000.0 * xrms) + message += " yrms={:0.3f}".format(1000.0 * yrms) + message += " zrms={:0.3f}".format(1000.0 * zrms) message += " node={}".format(node.getName()) print(message) - self.history["position"].append(position + self.position_start) + self.history["s"].append(position + self.position_start) self.history["rms_x"].append(xrms) self.history["rms_y"].append(yrms) self.history["rms_z"].append(zrms) diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index 045e6155..2d5c5128 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -52,7 +52,6 @@ plt.style.use("style.mplstyle") - # Parse arguments # -------------------------------------------------------------------------------- @@ -67,7 +66,6 @@ parser.add_argument("--seq-stop", type=str, default="CCL2") args = parser.parse_args() - # Setup # -------------------------------------------------------------------------------- @@ -76,7 +74,6 @@ random.seed(23) - # Bunch # -------------------------------------------------------------------------------- @@ -159,7 +156,6 @@ lattice.trackDesignBunch(bunch) - # Track envelope # -------------------------------------------------------------------------------- @@ -210,7 +206,6 @@ # Analysis # -------------------------------------------------------------------------------- - # History: rms for mode in histories: for key in histories[mode]: @@ -224,7 +219,7 @@ for mode in ["bunch", "envelope"]: history = histories[mode] for ax, key in zip(axs, ["rms_x", "rms_y", "rms_z"]): - ax.plot(history["position"], history[key], **plot_kws[mode], label=mode) + ax.plot(history["s"], history[key], **plot_kws[mode], label=mode) for ax in axs: ax.legend(loc="lower right") axs[0].set_ylabel("x rms [mm]") @@ -240,7 +235,7 @@ fig, ax = plt.subplots(figsize=(5, 3)) for mode in ["bunch", "envelope"]: history = histories[mode] - ax.plot(history["position"], history["kin_energy"], **plot_kws[mode], label=mode) + ax.plot(history["s"], history["kin_energy"], **plot_kws[mode], label=mode) ax.legend(loc="lower right") ax.set_ylabel("energy [GeV]") ax.set_xlabel("s [m]") diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index 2c181626..003c24ab 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -87,6 +87,10 @@ def copy(self): intensity=self.intensity ) + @property + def kin_energy(self) -> float: + return self.sync_part.kinEnergy() + @property def gamma(self) -> float: return self.sync_part.gamma() diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py index 9b6840d3..d17f908a 100644 --- a/py/orbit/envelope/track.py +++ b/py/orbit/envelope/track.py @@ -93,20 +93,41 @@ def track(self, envelope: Envelope) -> None: def track_history(self, envelope: Envelope) -> dict[str, list]: """Track and return envelope parameters vs. position in lattice.""" - history = {} - history["position"] = [] - history["rms_x"] = [] - history["rms_y"] = [] - history["rms_z"] = [] - history["kin_energy"] = [] - - node_positions = self.lattice.getNodePositionsDict() - - history["position"].append(0.0) - history["rms_x"].append(1000.0 * envelope.rms(0)) - history["rms_y"].append(1000.0 * envelope.rms(2)) - history["rms_z"].append(1000.0 * envelope.rms(4)) - history["kin_energy"].append(envelope.sync_part.kinEnergy()) + history_keys = [ + "s", + "kin_energy", + "gamma", + "beta", + "mean", + "cov", + "rms_x", + "rms_y", + "rms_z", + "eps_x", + "eps_y", + ] + history = {key: [] for key in history_keys} + + def observe(envelope: Envelope) -> None: + parameters = {} + parameters["gamma"] = envelope.gamma + parameters["beta"] = envelope.beta + parameters["kin_energy"] = envelope.kin_energy + parameters["mean"] = envelope.centroid.copy() + parameters["cov"] = envelope.cov_matrix.copy() + parameters["rms_x"] = np.sqrt(parameters["cov"][0, 0]) + parameters["rms_y"] = np.sqrt(parameters["cov"][2, 2]) + parameters["rms_z"] = np.sqrt(parameters["cov"][4, 4]) + return parameters + + def update_history(envelope: Envelope, position: float) -> None: + history["s"].append(position) + parameters = observe(envelope) + for key in parameters: + history[key].append(parameters[key]) + + path_length = 0.0 + update_history(envelope, path_length) for node_index, node in enumerate(self.lattice.getNodes()): for child_node in node.getChildNodes(ENTRANCE): @@ -137,14 +158,8 @@ def track_history(self, envelope: Envelope) -> dict[str, list]: matrix = matrix @ matrix_sc envelope.transform(matrix) - position_start, position_stop = node_positions[node] - position = position_start + node.getLength(part_index) * (part_index + 1) - - history["position"].append(position) - history["rms_x"].append(1000.0 * envelope.rms(0)) - history["rms_y"].append(1000.0 * envelope.rms(2)) - history["rms_z"].append(1000.0 * envelope.rms(4)) - history["kin_energy"].append(envelope.sync_part.kinEnergy()) + path_length += node.getLength(part_index) + update_history(envelope, path_length) for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): matrix = get_matrix(child_node, envelope=envelope) From 15afa74cd67de125869048d73779fe4e726e06eb Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 6 Aug 2026 17:49:32 -0400 Subject: [PATCH 04/42] Add index_start and index_stop to envelope tracker --- py/orbit/envelope/track.py | 15 +++++++++++---- tests/py/orbit/test_env.py | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py index d17f908a..f3776b6d 100644 --- a/py/orbit/envelope/track.py +++ b/py/orbit/envelope/track.py @@ -3,6 +3,7 @@ from orbit.core.bunch import Bunch from orbit.core.bunch import SyncParticle + from orbit.lattice import AccNode from orbit.lattice import AccLattice from orbit.teapot import BendTEAPOT @@ -47,12 +48,15 @@ def __init__(self, lattice: AccLattice, sc: str | None = None) -> None: node.setParam("ea1", 0.0) node.setParam("ea2", 0.0) - def track(self, envelope: Envelope) -> None: + def track(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> None: """Track envelope through lattice. This is not recursive, so grandchild nodes are not tracked. """ - for node_index, node in enumerate(self.lattice.getNodes()): + nodes = self.lattice.getNodes() + nodes = nodes[index_start : index_stop] + + for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): matrix = get_matrix(child_node, envelope=envelope) if matrix is not None: @@ -91,7 +95,7 @@ def track(self, envelope: Envelope) -> None: if matrix is not None: envelope.transform(matrix) - def track_history(self, envelope: Envelope) -> dict[str, list]: + def track_history(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> dict[str, list]: """Track and return envelope parameters vs. position in lattice.""" history_keys = [ "s", @@ -129,7 +133,10 @@ def update_history(envelope: Envelope, position: float) -> None: path_length = 0.0 update_history(envelope, path_length) - for node_index, node in enumerate(self.lattice.getNodes()): + nodes = self.lattice.getNodes() + nodes = nodes[index_start : index_stop] + + for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): matrix = get_matrix(child_node, envelope=envelope) if matrix is not None: diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index 16f1e5c7..660dbe5a 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -381,3 +381,23 @@ def test_sc_3d_cold_expansion(): # twice the initial size. (See examples from A. Shishlo or # from the ImpactX repo.) pass + + +def test_track_sublattice_no_error(): + bunch = Bunch() + bunch.mass(mass_proton) + bunch.getSyncParticle().kinEnergy(0.001) + + cov_matrix = np.diag(np.square([1e-3, 0, 1e-3, 0.0, 1e-3, 0.0])) + envelope = Envelope(bunch, cov_matrix=cov_matrix) + + lattice = TEAPOT_Lattice() + + n = 5 + for _ in range(n): + lattice.addNode(DriftTEAPOT(length=0.1)) + + tracker = EnvelopeTracker(lattice) + for i in range(n): + tracker.track(envelope, index_start=i) + tracker.track(envelope, index_stop=-i) From d39c42996876ec2545c843ddae31a97caed3f8c7 Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Sun, 9 Aug 2026 02:19:04 -0400 Subject: [PATCH 05/42] Envelope tracker: fix `get_transfer_matrix` and clean up/format examples (#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 --- examples/Envelope/plot.py | 8 +- examples/Envelope/run.sh | 16 + examples/Envelope/sns_linac/diagnostics.py | 4 +- examples/Envelope/sns_linac/test_sns_linac.py | 476 ++++++------ examples/Envelope/sns_ring/test_sns_ring.py | 693 +++++++++--------- .../Envelope/sns_ring/test_sns_ring_speed.py | 4 +- examples/Envelope/test_env_2d_fodo.py | 54 +- examples/Envelope/test_env_2d_fodo_speed.py | 4 +- examples/Envelope/test_env_3d_drift.py | 57 +- py/orbit/envelope/track.py | 28 +- tests/py/orbit/test_env.py | 21 + 11 files changed, 722 insertions(+), 643 deletions(-) create mode 100755 examples/Envelope/run.sh diff --git a/examples/Envelope/plot.py b/examples/Envelope/plot.py index f493b108..99a77f80 100644 --- a/examples/Envelope/plot.py +++ b/examples/Envelope/plot.py @@ -77,7 +77,9 @@ def plot_corner( if labels is None: labels = ndim * [""] - fig, axs = plt.subplots(ncols=ndim, nrows=ndim, sharex=None, sharey=None, figsize=(8, 8)) + fig, axs = plt.subplots( + ncols=ndim, nrows=ndim, sharex=None, sharey=None, figsize=(8, 8) + ) for i in range(ndim): for j in range(ndim): axis = (j, i) @@ -97,7 +99,9 @@ def plot_corner( shading="auto", ) elif i == j: - values, edges = np.histogram(particles[:, i], bins=bins, range=limits[i]) + values, edges = np.histogram( + particles[:, i], bins=bins, range=limits[i] + ) if blur: values = scipy.ndimage.gaussian_filter(values, sigma=blur) ax.stairs(values, edges, lw=1.5, color="black") diff --git a/examples/Envelope/run.sh b/examples/Envelope/run.sh new file mode 100755 index 00000000..98cf808c --- /dev/null +++ b/examples/Envelope/run.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -x + +python test_env_2d_fodo.py +python test_env_2d_fodo_speed.py +python test_env_3d_drift.py + +cd sns_linac +python test_sns_linac.py +cd .. + +cd sns_ring +python test_sns_ring.py +python test_sns_ring_speed.py +cd .. diff --git a/examples/Envelope/sns_linac/diagnostics.py b/examples/Envelope/sns_linac/diagnostics.py index 72904f51..7a4eeee4 100644 --- a/examples/Envelope/sns_linac/diagnostics.py +++ b/examples/Envelope/sns_linac/diagnostics.py @@ -35,7 +35,9 @@ def __call__(self, params_dict: dict) -> None: cov_matrix = np.zeros((6, 6)) for i in range(6): for j in range(6): - cov_matrix[i, j] = cov_matrix[j, i] = self.twiss_calc.getCorrelation(i, j) + cov_matrix[i, j] = cov_matrix[j, i] = self.twiss_calc.getCorrelation( + i, j + ) xrms = np.sqrt(cov_matrix[0, 0]) yrms = np.sqrt(cov_matrix[2, 2]) diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index 2d5c5128..7614d54f 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -52,241 +52,245 @@ plt.style.use("style.mplstyle") -# Parse arguments -# -------------------------------------------------------------------------------- - -parser = argparse.ArgumentParser() -parser.add_argument("--dist", type=str, default="kv") -parser.add_argument("--nparts", type=int, default=20_000) -parser.add_argument("--sc", type=int, default=0) -parser.add_argument("--sc-model", type=str, default="ellipsoid") -parser.add_argument("--sc-path-length-min", type=float, default=0.01) -parser.add_argument("--current", type=float, default=0.038) -parser.add_argument("--show", type=int, default=0) -parser.add_argument("--seq-stop", type=str, default="CCL2") -args = parser.parse_args() - -# Setup -# -------------------------------------------------------------------------------- - -output_dir = "outputs" -os.makedirs(output_dir, exist_ok=True) - -random.seed(23) - -# Bunch -# -------------------------------------------------------------------------------- - -kin_energy = 0.0025 # [GeV] -mass = mass_proton + 2.0 * mass_electron -frequency = 402.5e06 -charge = -1.0 -intensity = args.current / frequency / (math.fabs(charge) * charge_electron) - -bunch = Bunch() -bunch.mass(mass) -bunch.macroSize(intensity / args.nparts) -bunch.charge(charge) - -sync_part = bunch.getSyncParticle() -sync_part.kinEnergy(kin_energy) -sync_part.time(0.0) - -alpha_x, beta_x, eps_x = (-1.962, 0.183, 2.874e-06) -alpha_y, beta_y, eps_y = (+1.768, 0.162, 2.874e-06) -alpha_z, beta_z, eps_z = (-0.0196, 116.414, 1.651e-08) - -twiss_x = TwissContainer(alpha_x, beta_x, eps_x) -twiss_y = TwissContainer(alpha_y, beta_y, eps_y) -twiss_z = TwissContainer(alpha_z, beta_z, eps_z) - -if args.dist == "waterbag": - dist = WaterBagDist3D(twiss_x, twiss_y, twiss_z) -elif args.dist == "kv": - dist = KVDist3D(twiss_x, twiss_y, twiss_z) -elif args.dist == "gauss": - dist = GaussDist3D(twiss_x, twiss_y, twiss_z) -else: - raise ValueError("Unknown distribution '{}'".format(args.dist)) - -for _ in range(args.nparts): - bunch.addParticle(*dist.getCoordinates()) - -# Lattice -# -------------------------------------------------------------------------------- -seq_names = [ - "MEBT", - "DTL1", - "DTL2", - "DTL3", - "DTL4", - "DTL5", - "DTL6", - "CCL1", - "CCL2", - "CCL3", - "CCL4", - "SCLMed", - "SCLHigh", - "HEBT1", - "HEBT2", -] -if args.seq_stop: - index = seq_names.index(args.seq_stop) + 1 - seq_names = seq_names[:index] - -sns_linac_factory = SNS_LinacLatticeFactory() -sns_linac_factory.setMaxDriftLength(args.sc_path_length_min) -lattice = sns_linac_factory.getLinacAccLattice(seq_names, "inputs/sns_linac.xml") - -for node in lattice.getNodes(): - try: - node.setUsageFringeFieldIN(False) - node.setUsageFringeFieldOUT(False) - except: - pass - -rf_gaps = lattice.getRF_Gaps() -for rf_gap in rf_gaps: - rf_gap.setCppGapModel(MatrixRfGap()) - -for index, node in enumerate(lattice.getNodes()): - print(index, type(node), node.getName()) - -lattice.trackDesignBunch(bunch) - -# Track envelope -# -------------------------------------------------------------------------------- - -twiss_calc = BunchTwissAnalysis() -twiss_calc.analyzeBunch(bunch) - -cov_matrix = np.zeros((6, 6)) -for i in range(6): - for j in range(6): - cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) - -envelope = Envelope(bunch=bunch, cov_matrix=cov_matrix, intensity=intensity) - -tracker = EnvelopeTracker(lattice, sc=("3d" if args.sc else None)) - -histories = {} -histories["envelope"] = tracker.track_history(envelope) - - -# Track bunch -# -------------------------------------------------------------------------------- - -lattice.trackDesignBunch(bunch) - -if args.sc: - if args.sc_model == "ellipsoid": - n_ellipsoids = 1 - sc_calc = SpaceChargeCalcUnifEllipse(n_ellipsoids) - sc_nodes = setUniformEllipsesSCAccNodes(lattice, args.sc_path_length_min, sc_calc) - if args.sc_model == "3d": - sc_calc = SpaceChargeCalc3D(64, 64, 64) - sc_nodes = setSC3DAccNodes(lattice, args.sc_path_length_min, sc_calc) - - -monitor = BunchMonitor() - -action_container = AccActionsContainer() -action_container.addAction(monitor, AccActionsContainer.ENTRANCE) -action_container.addAction(monitor, AccActionsContainer.EXIT) - -params_dict = {"old_pos": -1.0, "count": 0, "pos_step": args.sc_path_length_min} - -lattice.trackBunch(bunch, paramsDict=params_dict, actionContainer=action_container) - -histories["bunch"] = monitor.history - - -# Analysis -# -------------------------------------------------------------------------------- - -# History: rms -for mode in histories: - for key in histories[mode]: - histories[mode][key] = np.array(histories[mode][key]) - -plot_kws = {} -plot_kws["bunch"] = dict(color="black", lw=0, marker=".", ms=2) -plot_kws["envelope"] = dict(color="red", lw=0, marker=".", ms=1) - -fig, axs = plt.subplots(nrows=3, figsize=(10, 5), sharex=True, constrained_layout=True) -for mode in ["bunch", "envelope"]: - history = histories[mode] - for ax, key in zip(axs, ["rms_x", "rms_y", "rms_z"]): - ax.plot(history["s"], history[key], **plot_kws[mode], label=mode) -for ax in axs: +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--dist", type=str, default="kv") + parser.add_argument("--nparts", type=int, default=20_000) + parser.add_argument("--sc", type=int, default=0) + parser.add_argument("--sc-model", type=str, default="ellipsoid") + parser.add_argument("--sc-path-length-min", type=float, default=0.01) + parser.add_argument("--current", type=float, default=0.038) + parser.add_argument("--show", type=int, default=0) + parser.add_argument("--seq-stop", type=str, default="CCL2") + return parser.parse_args() + + +def main(args: argparse.Namespace) -> None: + + output_dir = "outputs" + os.makedirs(output_dir, exist_ok=True) + + random.seed(23) + + # Bunch + # -------------------------------------------------------------------------------- + + kin_energy = 0.0025 # [GeV] + mass = mass_proton + 2.0 * mass_electron + frequency = 402.5e06 + charge = -1.0 + intensity = args.current / frequency / (math.fabs(charge) * charge_electron) + + bunch = Bunch() + bunch.mass(mass) + bunch.macroSize(intensity / args.nparts) + bunch.charge(charge) + + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(kin_energy) + sync_part.time(0.0) + + alpha_x, beta_x, eps_x = (-1.962, 0.183, 2.874e-06) + alpha_y, beta_y, eps_y = (+1.768, 0.162, 2.874e-06) + alpha_z, beta_z, eps_z = (-0.0196, 116.414, 1.651e-08) + + twiss_x = TwissContainer(alpha_x, beta_x, eps_x) + twiss_y = TwissContainer(alpha_y, beta_y, eps_y) + twiss_z = TwissContainer(alpha_z, beta_z, eps_z) + + if args.dist == "waterbag": + dist = WaterBagDist3D(twiss_x, twiss_y, twiss_z) + elif args.dist == "kv": + dist = KVDist3D(twiss_x, twiss_y, twiss_z) + elif args.dist == "gauss": + dist = GaussDist3D(twiss_x, twiss_y, twiss_z) + else: + raise ValueError("Unknown distribution '{}'".format(args.dist)) + + for _ in range(args.nparts): + bunch.addParticle(*dist.getCoordinates()) + + # Lattice + # -------------------------------------------------------------------------------- + + seq_names = [ + "MEBT", + "DTL1", + "DTL2", + "DTL3", + "DTL4", + "DTL5", + "DTL6", + "CCL1", + "CCL2", + "CCL3", + "CCL4", + "SCLMed", + "SCLHigh", + "HEBT1", + "HEBT2", + ] + if args.seq_stop: + index = seq_names.index(args.seq_stop) + 1 + seq_names = seq_names[:index] + + sns_linac_factory = SNS_LinacLatticeFactory() + sns_linac_factory.setMaxDriftLength(args.sc_path_length_min) + lattice = sns_linac_factory.getLinacAccLattice(seq_names, "inputs/sns_linac.xml") + + for node in lattice.getNodes(): + try: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + except: + pass + + rf_gaps = lattice.getRF_Gaps() + for rf_gap in rf_gaps: + rf_gap.setCppGapModel(MatrixRfGap()) + + for index, node in enumerate(lattice.getNodes()): + print(index, type(node), node.getName()) + + lattice.trackDesignBunch(bunch) + + # Track envelope + # -------------------------------------------------------------------------------- + + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) + + cov_matrix = np.zeros((6, 6)) + for i in range(6): + for j in range(6): + cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) + + envelope = Envelope(bunch=bunch, cov_matrix=cov_matrix, intensity=intensity) + + tracker = EnvelopeTracker(lattice, sc=("3d" if args.sc else None)) + + histories = {} + histories["envelope"] = tracker.track_history(envelope) + + # Track bunch + # -------------------------------------------------------------------------------- + + lattice.trackDesignBunch(bunch) + + if args.sc: + if args.sc_model == "ellipsoid": + n_ellipsoids = 1 + sc_calc = SpaceChargeCalcUnifEllipse(n_ellipsoids) + sc_nodes = setUniformEllipsesSCAccNodes( + lattice, args.sc_path_length_min, sc_calc + ) + if args.sc_model == "3d": + sc_calc = SpaceChargeCalc3D(64, 64, 64) + sc_nodes = setSC3DAccNodes(lattice, args.sc_path_length_min, sc_calc) + + monitor = BunchMonitor() + + action_container = AccActionsContainer() + action_container.addAction(monitor, AccActionsContainer.ENTRANCE) + action_container.addAction(monitor, AccActionsContainer.EXIT) + + params_dict = {"old_pos": -1.0, "count": 0, "pos_step": args.sc_path_length_min} + + lattice.trackBunch(bunch, paramsDict=params_dict, actionContainer=action_container) + + histories["bunch"] = monitor.history + + # Analysis + # -------------------------------------------------------------------------------- + + # History: rms + for mode in histories: + for key in histories[mode]: + histories[mode][key] = np.array(histories[mode][key]) + + plot_kws = {} + plot_kws["bunch"] = dict(color="black", lw=0, marker=".", ms=2) + plot_kws["envelope"] = dict(color="red", lw=0, marker=".", ms=1) + + fig, axs = plt.subplots( + nrows=3, figsize=(10, 5), sharex=True, constrained_layout=True + ) + for mode in ["bunch", "envelope"]: + history = histories[mode] + for ax, key in zip(axs, ["rms_x", "rms_y", "rms_z"]): + ax.plot(history["s"], history[key], **plot_kws[mode], label=mode) + for ax in axs: + ax.legend(loc="lower right") + axs[0].set_ylabel("x rms [mm]") + axs[1].set_ylabel("y rms [mm]") + axs[2].set_ylabel("z rms [mm]") + axs[2].set_xlabel("s [m]") + plt.savefig(os.path.join(output_dir, "fig_history_rms.png")) + if args.show: + plt.show() + plt.close() + + # History: energy + fig, ax = plt.subplots(figsize=(5, 3)) + for mode in ["bunch", "envelope"]: + history = histories[mode] + ax.plot(history["s"], history["kin_energy"], **plot_kws[mode], label=mode) ax.legend(loc="lower right") -axs[0].set_ylabel("x rms [mm]") -axs[1].set_ylabel("y rms [mm]") -axs[2].set_ylabel("z rms [mm]") -axs[2].set_xlabel("s [m]") -plt.savefig(os.path.join(output_dir, "fig_history_rms.png")) -if args.show: - plt.show() -plt.close() - -# History: energy -fig, ax = plt.subplots(figsize=(5, 3)) -for mode in ["bunch", "envelope"]: - history = histories[mode] - ax.plot(history["s"], history["kin_energy"], **plot_kws[mode], label=mode) -ax.legend(loc="lower right") -ax.set_ylabel("energy [GeV]") -ax.set_xlabel("s [m]") -plt.savefig(os.path.join(output_dir, "fig_history_energy.png")) -plt.close() - -# Collect bunch/envelope data -particles = collect_bunch(bunch)["coords"] -particles *= 1e3 - -env_cov_matrix = envelope.cov_matrix -env_cov_matrix *= 1e6 - -env_centroid = envelope.centroid -env_centroid *= 1e3 - -xmax = 4.0 * np.std(particles, axis=0) -limits = list(zip(-xmax, xmax)) -labels = ["x [mm]", "xp [mrad]", "y [mm]", "yp [mrad]", "z [mm]", "dE [MeV]"] - -# 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() + ax.set_ylabel("energy [GeV]") + ax.set_xlabel("s [m]") + plt.savefig(os.path.join(output_dir, "fig_history_energy.png")) + plt.close() + + # Collect bunch/envelope data + particles = collect_bunch(bunch)["coords"] + particles *= 1e3 + + env_cov_matrix = envelope.cov_matrix + env_cov_matrix *= 1e6 + + env_centroid = envelope.centroid + env_centroid *= 1e3 + + xmax = 4.0 * np.std(particles, axis=0) + limits = list(zip(-xmax, xmax)) + labels = ["x [mm]", "xp [mrad]", "y [mm]", "yp [mrad]", "z [mm]", "dE [MeV]"] + + # 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()) diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring/test_sns_ring.py index b7e74716..4efe4289 100644 --- a/examples/Envelope/sns_ring/test_sns_ring.py +++ b/examples/Envelope/sns_ring/test_sns_ring.py @@ -34,356 +34,363 @@ plt.style.use("style.mplstyle") -# Arguments -# ------------------------------------------------------------------------------ - -parser = argparse.ArgumentParser() -parser.add_argument("--bunch-length", type=float, default=120.0) -parser.add_argument("--kin-energy", type=float, default=1.300) -parser.add_argument("--intensity", type=float, default=2e14) - -parser.add_argument("--dist", type=str, default="kv", choices=["kv", "waterbag", "gauss"]) -parser.add_argument("--eps-x", type=float, default=25.0) -parser.add_argument("--eps-y", type=float, default=25.0) -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("--nparts", type=int, default=100_000) -parser.add_argument("--turns", type=int, default=25) -parser.add_argument("--sol", type=int, default=0) -parser.add_argument("--sc", type=int, default=0) -parser.add_argument("--sc-grid", type=int, default=64) - -parser.add_argument("--handle-unknown", type=str, default=None, choices=["drift", "fit"]) -args = parser.parse_args() - -# Setup -# ------------------------------------------------------------------------------ - -path = pathlib.Path(__file__) -output_dir = os.path.join("outputs", path.stem) -os.makedirs(output_dir, exist_ok=True) - -# Lattice -# ------------------------------------------------------------------------------ - -lattice = TEAPOT_Ring() -lattice.readMADX("inputs/sns_ring.lat", "rnginjsol") -lattice.initialize() - -for node in lattice.getNodes(): - if type(node) != teapot.TurnCounterTEAPOT: - node.setUsageFringeFieldIN(False) - node.setUsageFringeFieldOUT(False) - if type(node) is teapot.BendTEAPOT: - node.setParam("ea1", 0.0) - node.setParam("ea2", 0.0) - -if args.sol: - for name in ["scbdsol_c13a", "scbdsol_c13b"]: - node = lattice.getNodeForName(name) - node.setParam("B", 0.15) - -for node in lattice.getNodes(): - max_length = 1.0 - if node.getLength() > max_length: - node.setnParts(1 + int(node.getLength() / max_length)) - -# Bunch -# ------------------------------------------------------------------------------ - -bunch = Bunch() -bunch.mass(mass_proton) -sync_part = bunch.getSyncParticle() -sync_part.kinEnergy(args.kin_energy) - -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 = args.eps_x * 1e-6 -eps_y = args.eps_y * 1e-6 - -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 / 4.0) ** 2 -cov_matrix[5, 5] = 0.0 - -if args.tilt: - rot_matrix = np.identity(6) - rot_matrix[:4, :4] = build_rotation_matrix_xy(angle=(args.tilt * math.pi)) - cov_matrix = np.linalg.multi_dot([rot_matrix, cov_matrix, rot_matrix.T]) - -if args.mismatch_x or args.mismatch_y: - cov_matrix[0, 0] *= (1.0 + args.mismatch_x) ** 2 - cov_matrix[2, 2] *= (1.0 + args.mismatch_y) ** 2 - -centroid = np.zeros(6) -centroid[0] += args.offset_x -centroid[2] += args.offset_y - -rng = np.random.default_rng() -bunch_coords = np.zeros((args.nparts, 6)) -bunch_coords[:, :4] = gen_dist(size=args.nparts, cov_matrix=cov_matrix[0:4, 0:4], name=args.dist) -bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) -bunch_coords[:, 5] *= 0.0 -bunch_coords += centroid[None, :6] - -for i in range(bunch_coords.shape[0]): - bunch.addParticle(*bunch_coords[i]) - -# Use covariance matrix from initial bunch, which is slightly -# different from the one used to generate the bunch due to -# finite statistics. -cov_matrix_init = np.cov(bunch_coords, rowvar=False) -centroid_init = np.mean(bunch_coords, axis=0) - -# Track envelope -# ------------------------------------------------------------------------------ - -print("TRACK ENVELOPE") - -envelope = Envelope( - bunch=bunch, - cov_matrix=cov_matrix_init, - centroid=centroid_init, - intensity=args.intensity, -) -tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) - -history_keys = [ - "rms_x", - "rms_y", - "avg_x", - "avg_y", - "eps_x", - "eps_y", -] -history = {key: [] for key in history_keys} - -start_time = time.time() - -for turn in range(args.turns + 1): - if turn > 0: - tracker.track_ring(envelope) - - cov_matrix = envelope.cov_matrix - centroid = envelope.centroid - - rms_x = 1000.0 * math.sqrt(cov_matrix[0, 0]) - rms_y = 1000.0 * math.sqrt(cov_matrix[2, 2]) - avg_x = 1000.0 * centroid[0] - avg_y = 1000.0 * centroid[2] - eps_x = 1e6 * np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) - eps_y = 1e6 * np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) - - message = "" - message += " turn={}".format(turn) - message += " time={:0.3f}".format(time.time() - start_time) - message += " eps_x={:0.2f}".format(eps_x) - message += " eps_y={:0.2f}".format(eps_y) - message += " xrms={:0.2f}".format(rms_x) - message += " yrms={:0.2f}".format(rms_y) - message += " xavg={:0.2f}".format(avg_x) - message += " yavg={:0.2f}".format(avg_y) - print(message) - - history["rms_x"].append(rms_x) - history["rms_y"].append(rms_y) - history["avg_x"].append(avg_x) - history["avg_y"].append(avg_y) - history["eps_x"].append(eps_x) - history["eps_y"].append(eps_y) - -histories = {} -histories["envelope"] = copy.deepcopy(history) - -# Track bunch -# ------------------------------------------------------------------------------ - -print("TRACK BUNCH") - -if args.sc: - sc_calc = SpaceChargeCalc2p5D(64, 64, 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_keys = [ - "rms_x", - "rms_y", - "avg_x", - "avg_y", - "eps_x", - "eps_y", -] -history = {key: [] for key in history_keys} - -start_time = time.time() - -for turn in range(args.turns + 1): - if turn > 0: - lattice.trackBunch(bunch) - - twiss_calc = BunchTwissAnalysis() - twiss_calc.computeBunchMoments(bunch, 2, 0, 0) +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--bunch-length", type=float, default=120.0) + parser.add_argument("--kin-energy", type=float, default=1.300) + parser.add_argument("--intensity", type=float, default=2e14) + + parser.add_argument( + "--dist", type=str, default="kv", choices=["kv", "waterbag", "gauss"] + ) + parser.add_argument("--eps-x", type=float, default=25.0) + parser.add_argument("--eps-y", type=float, default=25.0) + 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("--nparts", type=int, default=100_000) + parser.add_argument("--turns", type=int, default=25) + parser.add_argument("--sol", type=int, default=0) + parser.add_argument("--sc", type=int, default=0) + parser.add_argument("--sc-grid", type=int, default=64) + + parser.add_argument( + "--handle-unknown", type=str, default=None, choices=["drift", "fit"] + ) + return parser.parse_args() + + +def main(args: argparse.Namespace) -> None: + path = pathlib.Path(__file__) + output_dir = os.path.join("outputs", path.stem) + os.makedirs(output_dir, exist_ok=True) + + # Lattice + # ------------------------------------------------------------------------------ + + lattice = TEAPOT_Ring() + lattice.readMADX("inputs/sns_ring.lat", "rnginjsol") + lattice.initialize() + + for node in lattice.getNodes(): + if type(node) != teapot.TurnCounterTEAPOT: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + if type(node) is teapot.BendTEAPOT: + node.setParam("ea1", 0.0) + node.setParam("ea2", 0.0) + + if args.sol: + for name in ["scbdsol_c13a", "scbdsol_c13b"]: + node = lattice.getNodeForName(name) + node.setParam("B", 0.15) + + for node in lattice.getNodes(): + max_length = 1.0 + if node.getLength() > max_length: + node.setnParts(1 + int(node.getLength() / max_length)) + + # Bunch + # ------------------------------------------------------------------------------ + + bunch = Bunch() + bunch.mass(mass_proton) + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(args.kin_energy) + + 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 = args.eps_x * 1e-6 + eps_y = args.eps_y * 1e-6 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] + 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 / 4.0) ** 2 + cov_matrix[5, 5] = 0.0 + + if args.tilt: + rot_matrix = np.identity(6) + rot_matrix[:4, :4] = build_rotation_matrix_xy(angle=(args.tilt * math.pi)) + cov_matrix = np.linalg.multi_dot([rot_matrix, cov_matrix, rot_matrix.T]) + + if args.mismatch_x or args.mismatch_y: + cov_matrix[0, 0] *= (1.0 + args.mismatch_x) ** 2 + cov_matrix[2, 2] *= (1.0 + args.mismatch_y) ** 2 centroid = np.zeros(6) - for i in range(6): - centroid[i] = twiss_calc.getAverage(i) - - rms_x = 1000.0 * math.sqrt(cov_matrix[0, 0]) - rms_y = 1000.0 * math.sqrt(cov_matrix[2, 2]) - avg_x = 1000.0 * centroid[0] - avg_y = 1000.0 * centroid[2] - eps_x = 1e6 * np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) - eps_y = 1e6 * np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) - - message = "" - message += " turn={}".format(turn) - message += " time={:0.3f}".format(time.time() - start_time) - message += " eps_x={:0.2f}".format(eps_x) - message += " eps_y={:0.2f}".format(eps_y) - message += " xrms={:0.2f}".format(rms_x) - message += " yrms={:0.2f}".format(rms_y) - message += " xavg={:0.2f}".format(avg_x) - message += " yavg={:0.2f}".format(avg_y) - print(message) - - history["rms_x"].append(rms_x) - history["rms_y"].append(rms_y) - history["avg_x"].append(avg_x) - history["avg_y"].append(avg_y) - history["eps_x"].append(eps_x) - history["eps_y"].append(eps_y) - -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 ["rms_x", "rms_y"]: + centroid[0] += args.offset_x + centroid[2] += args.offset_y + + rng = np.random.default_rng() + bunch_coords = np.zeros((args.nparts, 6)) + bunch_coords[:, :4] = gen_dist( + size=args.nparts, cov_matrix=cov_matrix[0:4, 0:4], name=args.dist + ) + bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) + bunch_coords[:, 5] *= 0.0 + bunch_coords += centroid[None, :6] + + for i in range(bunch_coords.shape[0]): + bunch.addParticle(*bunch_coords[i]) + + # Use covariance matrix from initial bunch, which is slightly + # different from the one used to generate the bunch due to + # finite statistics. + cov_matrix_init = np.cov(bunch_coords, rowvar=False) + centroid_init = np.mean(bunch_coords, axis=0) + + # Track envelope + # ------------------------------------------------------------------------------ + + print("TRACK ENVELOPE") + + envelope = Envelope( + bunch=bunch, + cov_matrix=cov_matrix_init, + centroid=centroid_init, + intensity=args.intensity, + ) + tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) + + history_keys = [ + "rms_x", + "rms_y", + "avg_x", + "avg_y", + "eps_x", + "eps_y", + ] + history = {key: [] for key in history_keys} + + start_time = time.time() + + for turn in range(args.turns + 1): + if turn > 0: + tracker.track_ring(envelope) + + cov_matrix = envelope.cov_matrix + centroid = envelope.centroid + + rms_x = 1000.0 * math.sqrt(cov_matrix[0, 0]) + rms_y = 1000.0 * math.sqrt(cov_matrix[2, 2]) + avg_x = 1000.0 * centroid[0] + avg_y = 1000.0 * centroid[2] + eps_x = 1e6 * np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) + eps_y = 1e6 * np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) + + message = "" + message += " turn={}".format(turn) + message += " time={:0.3f}".format(time.time() - start_time) + message += " eps_x={:0.2f}".format(eps_x) + message += " eps_y={:0.2f}".format(eps_y) + message += " xrms={:0.2f}".format(rms_x) + message += " yrms={:0.2f}".format(rms_y) + message += " xavg={:0.2f}".format(avg_x) + message += " yavg={:0.2f}".format(avg_y) + print(message) + + history["rms_x"].append(rms_x) + history["rms_y"].append(rms_y) + history["avg_x"].append(avg_x) + history["avg_y"].append(avg_y) + history["eps_x"].append(eps_x) + history["eps_y"].append(eps_y) + + histories = {} + histories["envelope"] = copy.deepcopy(history) + + # Track bunch + # ------------------------------------------------------------------------------ + + print("TRACK BUNCH") + + if args.sc: + sc_calc = SpaceChargeCalc2p5D(64, 64, 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_keys = [ + "rms_x", + "rms_y", + "avg_x", + "avg_y", + "eps_x", + "eps_y", + ] + history = {key: [] for key in history_keys} + + start_time = time.time() + + for turn in range(args.turns + 1): + 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] + + centroid = np.zeros(6) + for i in range(6): + centroid[i] = twiss_calc.getAverage(i) + + rms_x = 1000.0 * math.sqrt(cov_matrix[0, 0]) + rms_y = 1000.0 * math.sqrt(cov_matrix[2, 2]) + avg_x = 1000.0 * centroid[0] + avg_y = 1000.0 * centroid[2] + eps_x = 1e6 * np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) + eps_y = 1e6 * np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) + + message = "" + message += " turn={}".format(turn) + message += " time={:0.3f}".format(time.time() - start_time) + message += " eps_x={:0.2f}".format(eps_x) + message += " eps_y={:0.2f}".format(eps_y) + message += " xrms={:0.2f}".format(rms_x) + message += " yrms={:0.2f}".format(rms_y) + message += " xavg={:0.2f}".format(avg_x) + message += " yavg={:0.2f}".format(avg_y) + print(message) + + history["rms_x"].append(rms_x) + history["rms_y"].append(rms_y) + history["avg_x"].append(avg_x) + history["avg_y"].append(avg_y) + history["eps_x"].append(eps_x) + history["eps_y"].append(eps_y) + + 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 ["rms_x", "rms_y"]: + 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(key + " [mm]") + ax.legend(loc="upper right") + plt.savefig(os.path.join(output_dir, f"fig_{key}")) + plt.close() + + # Plot rms emittances + color_cycle = plt.rcParams["axes.prop_cycle"].by_key()["color"] + 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) + for key, color in zip(["eps_x", "eps_y"], color_cycle): + for i, model in enumerate(["envelope", "bunch"]): + if model == "envelope": + plot_kws = dict() + else: + plot_kws = dict(marker=".", lw=0) + label = key + "_" + model + ax.plot(histories[model][key], color=color, label=label, **plot_kws) + + ymax = 2.0 * np.mean(histories["envelope"]["eps_x"]) + ax.set_ylim(0.0, ymax) ax.set_xlabel("Turn") - ax.set_ylabel(key + " [mm]") - ax.legend(loc="upper right") - plt.savefig(os.path.join(output_dir, f"fig_{key}")) + ax.set_ylabel("[mm mrad]") + plt.savefig(os.path.join(output_dir, f"fig_emittances")) plt.close() -# Plot rms emittances -color_cycle = plt.rcParams["axes.prop_cycle"].by_key()["color"] - -fig, ax = plt.subplots(figsize=(5, 3)) -for key, color in zip(["eps_x", "eps_y"], color_cycle): - for i, model in enumerate(["envelope", "bunch"]): - if model == "envelope": - plot_kws = dict() - else: - plot_kws = dict(marker=".", lw=0) - label = key + "_" + model - ax.plot(histories[model][key], color=color, label=label, **plot_kws) - -ymax = 2.0 * np.mean(histories["envelope"]["eps_x"]) -ax.set_ylim(0.0, ymax) -ax.set_xlabel("Turn") -ax.set_ylabel("[mm mrad]") -plt.savefig(os.path.join(output_dir, f"fig_emittances")) -plt.close() - -# Plot centroids -for key in ["avg_x", "avg_y"]: - 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(key + " [mm]") - ax.legend(loc="upper right") - plt.savefig(os.path.join(output_dir, f"fig_{key}")) + # Plot centroids + for key in ["avg_x", "avg_y"]: + 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(key + " [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 = envelope.cov_matrix + 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() -# Collect bunch/envelope data on final turn. -particles = collect_bunch(bunch)["coords"] -particles[:, :4] *= 1000.0 - -env_cov_matrix = envelope.cov_matrix -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() + # 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()) diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring/test_sns_ring_speed.py index 73b84ff0..773febc6 100644 --- a/examples/Envelope/sns_ring/test_sns_ring_speed.py +++ b/examples/Envelope/sns_ring/test_sns_ring_speed.py @@ -110,7 +110,9 @@ rng = np.random.default_rng() bunch_coords = np.zeros((args.nparts, 6)) -bunch_coords[:, :4] = gen_dist(size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv") +bunch_coords[:, :4] = gen_dist( + size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv" +) bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) for i in range(bunch_coords.shape[0]): diff --git a/examples/Envelope/test_env_2d_fodo.py b/examples/Envelope/test_env_2d_fodo.py index de5a4444..824cc3b7 100644 --- a/examples/Envelope/test_env_2d_fodo.py +++ b/examples/Envelope/test_env_2d_fodo.py @@ -34,6 +34,30 @@ 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) + return parser.parse_args() + + def main(args: argparse.Namespace) -> None: # Setup @@ -137,7 +161,9 @@ def main(args: argparse.Namespace) -> None: xavg = 1000.0 * centroid[0] yavg = 1000.0 * centroid[2] - print(f"turn={turn} xrms={xrms:0.3f} yrms={yrms:0.3f} xavg={xavg:0.3f} yavg={yavg:0.3f}") + 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) @@ -191,7 +217,9 @@ def main(args: argparse.Namespace) -> None: 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}") + 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) @@ -293,24 +321,4 @@ def main(args: argparse.Namespace) -> None: if __name__ == "__main__": - 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) - args = parser.parse_args() - - main(args) + main(parse_args()) diff --git a/examples/Envelope/test_env_2d_fodo_speed.py b/examples/Envelope/test_env_2d_fodo_speed.py index 2b85d185..063ddfaf 100644 --- a/examples/Envelope/test_env_2d_fodo_speed.py +++ b/examples/Envelope/test_env_2d_fodo_speed.py @@ -112,7 +112,9 @@ rng = np.random.default_rng() bunch_coords = np.zeros((args.nparts, 6)) -bunch_coords[:, :4] = gen_dist(size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv") +bunch_coords[:, :4] = gen_dist( + size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv" +) bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) for i in range(bunch_coords.shape[0]): diff --git a/examples/Envelope/test_env_3d_drift.py b/examples/Envelope/test_env_3d_drift.py index d66e592b..798d4448 100644 --- a/examples/Envelope/test_env_3d_drift.py +++ b/examples/Envelope/test_env_3d_drift.py @@ -33,13 +33,38 @@ plt.style.use("style.mplstyle") +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--kin-energy", type=float, default=0.0025) + parser.add_argument("--intensity", type=float, default=3e10) + + parser.add_argument("--rms-x", type=float, default=0.010) + parser.add_argument("--rms-y", type=float, default=0.010) + parser.add_argument("--rms-z", type=float, default=0.010) + + parser.add_argument("--rot-x", type=float, default=0.0) + parser.add_argument("--rot-y", type=float, default=0.0) + parser.add_argument("--rot-z", type=float, default=0.0) + + parser.add_argument("--nslice", type=int, default=10) + parser.add_argument("--length", type=float, default=0.1) + parser.add_argument("--turns", type=int, default=20) + parser.add_argument("--sc-grid", type=int, default=64) + + parser.add_argument("--nparts", type=int, default=100_000) + parser.add_argument("--sc", type=int, default=0) + return parser.parse_args() + + def rotation_matrix_3d(angle_x: float, angle_y: float, angle_z: float) -> np.ndarray: return scipy.spatial.transform.Rotation.from_euler( "xyz", [angle_x, angle_y, angle_z] ).as_matrix() -def build_cov_matrix_xyz(rms_sizes: np.ndarray, rotation_matrix: np.ndarray = None) -> np.ndarray: +def build_cov_matrix_xyz( + rms_sizes: np.ndarray, rotation_matrix: np.ndarray = None +) -> np.ndarray: cov_matrix = np.diag(np.square(rms_sizes)) if rotation_matrix is None: return cov_matrix @@ -48,14 +73,13 @@ def build_cov_matrix_xyz(rms_sizes: np.ndarray, rotation_matrix: np.ndarray = No def main(args: argparse.Namespace) -> None: - # Setup - # ------------------------------------------------------------------------------ path = pathlib.Path(__file__) output_dir = os.path.join("outputs", path.stem) os.makedirs(output_dir, exist_ok=True) # Create lattice # ------------------------------------------------------------------------------ + node = DriftTEAPOT(length=args.length) node.setLength(args.length) node.setnParts(args.nslice) @@ -66,6 +90,7 @@ def main(args: argparse.Namespace) -> None: # Create envelope # ------------------------------------------------------------------------------ + bunch = Bunch() bunch.mass(mass_proton) sync_part = bunch.getSyncParticle() @@ -103,6 +128,7 @@ def main(args: argparse.Namespace) -> None: # Track envelope # ------------------------------------------------------------------------------ + print("TRACK ENVELOPE") tracker = EnvelopeTracker(lattice, sc=("3d" if args.sc else None)) @@ -129,6 +155,7 @@ def main(args: argparse.Namespace) -> None: # Track bunch # ------------------------------------------------------------------------------ + print("TRACK BUNCH") bunch_coords = np.zeros((args.nparts, 6)) @@ -175,6 +202,7 @@ def main(args: argparse.Namespace) -> None: # Analysis # ------------------------------------------------------------------------------ + for history in histories.values(): for key in history: history[key] = np.array(history[key]) @@ -251,25 +279,4 @@ def main(args: argparse.Namespace) -> None: if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--kin-energy", type=float, default=0.0025) - parser.add_argument("--intensity", type=float, default=3e10) - - parser.add_argument("--rms-x", type=float, default=0.010) - parser.add_argument("--rms-y", type=float, default=0.010) - parser.add_argument("--rms-z", type=float, default=0.010) - - parser.add_argument("--rot-x", type=float, default=0.0) - parser.add_argument("--rot-y", type=float, default=0.0) - parser.add_argument("--rot-z", type=float, default=0.0) - - parser.add_argument("--nslice", type=int, default=10) - parser.add_argument("--length", type=float, default=0.1) - parser.add_argument("--turns", type=int, default=20) - parser.add_argument("--sc-grid", type=int, default=64) - - parser.add_argument("--nparts", type=int, default=100_000) - parser.add_argument("--sc", type=int, default=0) - args = parser.parse_args() - - main(args) + main(parse_args()) diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py index f3776b6d..91d0223d 100644 --- a/py/orbit/envelope/track.py +++ b/py/orbit/envelope/track.py @@ -35,7 +35,6 @@ def __init__(self, lattice: AccLattice, sc: str | None = None) -> None: # For pre-computing elements self.elements = [] self.one_turn_matrix = None - # [TO DO] option to return one-turn matrix including linear space charge for node in self.lattice.getNodes(): if type(node) in (BendTEAPOT, BendLINAC): @@ -253,18 +252,25 @@ def track_ring(self, envelope: Envelope) -> None: node, matrix = element envelope.transform(matrix) - def get_effective_matrix(self, envelope: Envelope) -> np.ndarray: + def get_transfer_matrix(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> np.ndarray: + """Return total transfer matrix (including linear space charge).""" if not self.elements: self.precompute_matrices(envelope) + if index_stop is None: + index_stop = len(self.elements) + + elements = self.elements[index_start : index_stop] + if not self.sc: - one_turn_matrix = np.identity(7) - for (node, matrix) in self.elements: - one_turn_matrix = matrix @ one_turn_matrix - return one_turn_matrix + total_matrix = np.identity(7) + for (node, matrix) in elements: + envelope.transform(matrix) + total_matrix = matrix @ total_matrix + return total_matrix - one_turn_matrix = np.identity(7) - for element in self.elements: + total_matrix = np.identity(7) + for element in elements: if element[0] == "sc": length = element[1] if self.sc == "2d": @@ -274,9 +280,9 @@ def get_effective_matrix(self, envelope: Envelope) -> np.ndarray: else: raise ValueError envelope.transform(matrix) - one_turn_matrix = matrix @ one_turn_matrix + total_matrix = matrix @ total_matrix else: node, matrix = element envelope.transform(matrix) - one_turn_matrix = matrix @ one_turn_matrix - return one_turn_matrix \ No newline at end of file + total_matrix = matrix @ total_matrix + return total_matrix \ No newline at end of file diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index 660dbe5a..5275ab6c 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -401,3 +401,24 @@ def test_track_sublattice_no_error(): for i in range(n): tracker.track(envelope, index_start=i) tracker.track(envelope, index_stop=-i) + +def test_get_total_matrix() -> None: + node = DriftTEAPOT(length=2.0, nparts=50) + lattice = make_lattice([node]) + + bunch = Bunch() + bunch.mass(mass_proton) + bunch.getSyncParticle().kinEnergy(0.001) + + cov_matrix = make_default_cov_matrix() + envelope = Envelope(bunch, cov_matrix=cov_matrix, intensity=1e7) + + tracker = EnvelopeTracker(lattice, sc="2d") + + envelope_out_a = envelope.copy() + tracker.track(envelope_out_a) + + matrix = tracker.get_transfer_matrix(envelope.copy()) + envelope_out_b = envelope.copy() + envelope_out_b.transform(matrix) + assert np.all(np.isclose(envelope_out_a.cov_matrix, envelope_out_b.cov_matrix)) From f68bc9d7e755bb6b56818f90000a8f317697004a Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Sun, 9 Aug 2026 13:38:47 -0400 Subject: [PATCH 06/42] Modify get_transfer_matrix function (#135) * 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 --- py/orbit/envelope/track.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py index 91d0223d..16b62b9d 100644 --- a/py/orbit/envelope/track.py +++ b/py/orbit/envelope/track.py @@ -179,13 +179,16 @@ def update_history(envelope: Envelope, position: float) -> None: return history - def precompute_matrices(self, envelope: Envelope) -> None: + def precompute_matrices(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> None: """Pre-compute transfer matrices for each node. For each node, return tuple (node, matrix). Mark space charge kicks as ("sc", length). """ + nodes = self.lattice.getNodes() + nodes = nodes[index_start : index_stop] + self.elements = [] - for node_index, node in enumerate(self.lattice.getNodes()): + for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): matrix = get_matrix(child_node, envelope=envelope) if matrix is not None: @@ -254,8 +257,7 @@ def track_ring(self, envelope: Envelope) -> None: def get_transfer_matrix(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> np.ndarray: """Return total transfer matrix (including linear space charge).""" - if not self.elements: - self.precompute_matrices(envelope) + self.precompute_matrices(envelope, index_start, index_stop) if index_stop is None: index_stop = len(self.elements) @@ -264,13 +266,13 @@ def get_transfer_matrix(self, envelope: Envelope, index_start: int = 0, index_st if not self.sc: total_matrix = np.identity(7) - for (node, matrix) in elements: + for (node, matrix) in self.elements: envelope.transform(matrix) total_matrix = matrix @ total_matrix return total_matrix total_matrix = np.identity(7) - for element in elements: + for element in self.elements: if element[0] == "sc": length = element[1] if self.sc == "2d": From 317a502a7a52af1618bac4b25aba8c722930c10a Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Wed, 2 Sep 2026 21:26:24 -0400 Subject: [PATCH 07/42] Add getCharge() method to SyncParticle --- src/orbit/SyncPart.cc | 4 +++ src/orbit/SyncPart.hh | 5 +++ src/orbit/wrap_syncpart.cc | 61 ++++++++++++++++++++------------ tests/py/orbit/test_sync_part.py | 18 ++++++++++ 4 files changed, 65 insertions(+), 23 deletions(-) create mode 100644 tests/py/orbit/test_sync_part.py diff --git a/src/orbit/SyncPart.cc b/src/orbit/SyncPart.cc index 6494ecbf..320f9850 100644 --- a/src/orbit/SyncPart.cc +++ b/src/orbit/SyncPart.cc @@ -320,6 +320,10 @@ double SyncPart::getMass(){ return bunch->getMass(); } +double SyncPart::getCharge(){ + return bunch->getCharge(); +} + void SyncPart::readSyncPart(const char* fileName){ //for MPI diff --git a/src/orbit/SyncPart.hh b/src/orbit/SyncPart.hh index d14aa9ba..2081e4bf 100644 --- a/src/orbit/SyncPart.hh +++ b/src/orbit/SyncPart.hh @@ -68,6 +68,11 @@ class SyncPart */ double getMass(); + /** + Charge in elementary charge units + */ + double getCharge(); + /** time in seconds */ diff --git a/src/orbit/wrap_syncpart.cc b/src/orbit/wrap_syncpart.cc index 787c00a7..419ae556 100644 --- a/src/orbit/wrap_syncpart.cc +++ b/src/orbit/wrap_syncpart.cc @@ -129,6 +129,20 @@ extern "C" { return Py_BuildValue("d",val); } + // charge() - returns charge in elementary charge units + static PyObject* SyncPart_charge(PyObject *self, PyObject *args){ + pyORBIT_Object* pySyncPart = (pyORBIT_Object*) self; + int nVars = PyTuple_Size(args); + if(nVars > 0){ + error("PySyncPart - charge() - you should use bunch.charge(charge_value) instead!"); + } + double val = 0.; + SyncPart* cpp_SyncPart = (SyncPart*) pySyncPart->cpp_obj; + val = cpp_SyncPart->getCharge(); + return Py_BuildValue("d",val); + } + + //Sets or returns the momentum for the SyncPart object // the action is depended on the number of arguments // momentum() - returns momentum @@ -543,37 +557,38 @@ extern "C" { return Py_BuildValue("d",val); } - // defenition of the methods of the python SyncPart wrapper class - // they will be vailable from python level + // Definition of the methods of the python SyncPart wrapper class. + // They will be available from the Python level. static PyMethodDef SyncPartClassMethods[] = { - { "mass", SyncPart_mass ,METH_VARARGS,"Returns mass in GeV"}, - { "momentum", SyncPart_momentum ,METH_VARARGS,"Returns or sets momentum in GeV/c."}, - { "beta", SyncPart_beta ,METH_VARARGS,"Returns beta=v/c"}, - { "gamma", SyncPart_gamma ,METH_VARARGS,"Returns gamma=1/sqrt(1-(v/c)**2)"}, - { "kinEnergy", SyncPart_kinEnergy ,METH_VARARGS,"Returns or sets kinetic energy of the synchronous particle in MeV"}, - { "time", SyncPart_time ,METH_VARARGS,"Sets or returns time in sec"}, - { "x", SyncPart_x ,METH_VARARGS,"Sets or returns the x-coordinate"}, - { "y", SyncPart_y ,METH_VARARGS,"Sets or returns the y-coordinate"}, - { "z", SyncPart_z ,METH_VARARGS,"Sets or returns the z-coordinate"}, - { "px", SyncPart_px ,METH_VARARGS,"Sets or returns the x-momentum"}, - { "py", SyncPart_py ,METH_VARARGS,"Sets or returns the y-momentum"}, - { "pz", SyncPart_pz ,METH_VARARGS,"Sets or returns the z-momentum"}, - { "pVector", SyncPart_pVector ,METH_VARARGS,"Sets or returns the momentum vector as a tuple"}, - { "rVector", SyncPart_rVector ,METH_VARARGS,"Sets or returns the position vector as a tuple"}, - { "nxVector", SyncPart_nxVector ,METH_VARARGS,"Sets or returns the x-axis vector as a tuple"}, - { "nyVector", SyncPart_nyVector ,METH_VARARGS,"Returns the y-axis vector as a tuple"}, - { "energyToMomentum", SyncPart_eToP ,METH_VARARGS,"Transforms the kinetic energy to momentum"}, - { "momentumToEnergy", SyncPart_pToE ,METH_VARARGS,"Transforms the momentum to kinetic energy"}, + { "mass", SyncPart_mass, METH_VARARGS,"Returns mass in GeV"}, + { "charge", SyncPart_charge, METH_VARARGS,"Returns charge in elementary charge units"}, + { "momentum", SyncPart_momentum, METH_VARARGS,"Returns or sets momentum in GeV/c."}, + { "beta", SyncPart_beta, METH_VARARGS,"Returns beta=v/c"}, + { "gamma", SyncPart_gamma, METH_VARARGS,"Returns gamma=1/sqrt(1-(v/c)**2)"}, + { "kinEnergy", SyncPart_kinEnergy, METH_VARARGS,"Returns or sets kinetic energy of the synchronous particle in MeV"}, + { "time", SyncPart_time, METH_VARARGS,"Sets or returns time in sec"}, + { "x", SyncPart_x, METH_VARARGS,"Sets or returns the x-coordinate"}, + { "y", SyncPart_y, METH_VARARGS,"Sets or returns the y-coordinate"}, + { "z", SyncPart_z, METH_VARARGS,"Sets or returns the z-coordinate"}, + { "px", SyncPart_px, METH_VARARGS,"Sets or returns the x-momentum"}, + { "py", SyncPart_py, METH_VARARGS,"Sets or returns the y-momentum"}, + { "pz", SyncPart_pz, METH_VARARGS,"Sets or returns the z-momentum"}, + { "pVector", SyncPart_pVector, METH_VARARGS,"Sets or returns the momentum vector as a tuple"}, + { "rVector", SyncPart_rVector, METH_VARARGS,"Sets or returns the position vector as a tuple"}, + { "nxVector", SyncPart_nxVector, METH_VARARGS,"Sets or returns the x-axis vector as a tuple"}, + { "nyVector", SyncPart_nyVector, METH_VARARGS,"Returns the y-axis vector as a tuple"}, + { "energyToMomentum", SyncPart_eToP, METH_VARARGS,"Transforms the kinetic energy to momentum"}, + { "momentumToEnergy", SyncPart_pToE, METH_VARARGS,"Transforms the momentum to kinetic energy"}, {NULL} }; - // defenition of the memebers of the python SyncPart wrapper class - // they will be vailable from python level + // Definition of the members of the python SyncPart wrapper class. + // They will be available from python level. static PyMemberDef SyncPartClassMembers [] = { {NULL} }; - //new python SyncPart wrapper type definition + // New Python SyncPart wrapper type definition. static PyTypeObject pyORBIT_SyncPart_Type = { PyVarObject_HEAD_INIT(NULL, 0) "SyncParticle", /*tp_name*/ diff --git a/tests/py/orbit/test_sync_part.py b/tests/py/orbit/test_sync_part.py new file mode 100644 index 00000000..f0b0ee7b --- /dev/null +++ b/tests/py/orbit/test_sync_part.py @@ -0,0 +1,18 @@ +from orbit.core.bunch import Bunch +from orbit.core.bunch import SyncParticle + + +def make_bunch(): + bunch = Bunch() + bunch.mass(0.938272) + bunch.charge(1.0) + bunch.getSyncParticle().kinEnergy(1.0) + return bunch + + +def test_get_mass_charge(): + bunch = make_bunch() + sync_part = bunch.getSyncParticle() + + assert sync_part.mass() == bunch.mass() + assert sync_part.charge() == bunch.charge() From 4bf3f1b5a4c4f56eb6b61441a2e686bfdd551816 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Wed, 2 Sep 2026 21:34:15 -0400 Subject: [PATCH 08/42] Move transfer matrix definitions to orbit.utils.matrix --- py/orbit/envelope/envelope.py | 2 +- py/orbit/envelope/meson.build | 1 - py/orbit/envelope/track.py | 38 +++--- py/orbit/envelope/utils.py | 42 ------- py/orbit/{envelope => utils}/matrix.py | 154 +++++++++++++++---------- py/orbit/utils/meson.build | 3 +- tests/py/orbit/test_env.py | 6 +- 7 files changed, 124 insertions(+), 122 deletions(-) rename py/orbit/{envelope => utils}/matrix.py (71%) diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index 003c24ab..a837b994 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -5,8 +5,8 @@ from orbit.core.bunch import Bunch from orbit.core.bunch import BunchTwissAnalysis from orbit.core.bunch import SyncParticle +from orbit.utils.matrix import convert_matrix_zp_to_dE -from .utils import convert_matrix_zp_to_dE from .utils import gen_dist from .utils import get_classical_radius from .utils import proj_cov_matrix diff --git a/py/orbit/envelope/meson.build b/py/orbit/envelope/meson.build index 90eab844..9be34b6b 100644 --- a/py/orbit/envelope/meson.build +++ b/py/orbit/envelope/meson.build @@ -1,7 +1,6 @@ py_sources = files([ '__init__.py', 'envelope.py', - 'matrix.py', 'track.py', 'utils.py' ]) diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py index 16b62b9d..e9e952c6 100644 --- a/py/orbit/envelope/track.py +++ b/py/orbit/envelope/track.py @@ -8,8 +8,8 @@ from orbit.lattice import AccLattice from orbit.teapot import BendTEAPOT from orbit.py_linac.lattice import Bend as BendLINAC +from orbit.utils.matrix import get_matrix -from .matrix import get_matrix from .envelope import Envelope @@ -55,15 +55,17 @@ def track(self, envelope: Envelope, index_start: int = 0, index_stop: int = None nodes = self.lattice.getNodes() nodes = nodes[index_start : index_stop] + sync_part = envelope.sync_part + for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: envelope.transform(matrix) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: envelope.transform(matrix) @@ -78,19 +80,19 @@ def track(self, envelope: Envelope, index_start: int = 0, index_stop: int = None else: raise ValueError - matrix = get_matrix(node, envelope=envelope, part_index=part_index) + matrix = get_matrix(node, sync_part, part_index=part_index) if matrix is not None: if matrix_sc is not None: matrix = matrix @ matrix_sc envelope.transform(matrix) for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: envelope.transform(matrix) for child_node in node.getChildNodes(EXIT): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: envelope.transform(matrix) @@ -135,15 +137,17 @@ def update_history(envelope: Envelope, position: float) -> None: nodes = self.lattice.getNodes() nodes = nodes[index_start : index_stop] + sync_part = envelope.sync_part + for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: envelope.transform(matrix) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: envelope.transform(matrix) @@ -158,7 +162,7 @@ def update_history(envelope: Envelope, position: float) -> None: else: raise ValueError - matrix = get_matrix(node, envelope=envelope, part_index=part_index) + matrix = get_matrix(node, sync_part, part_index=part_index) if matrix is not None: if matrix_sc is not None: matrix = matrix @ matrix_sc @@ -168,12 +172,12 @@ def update_history(envelope: Envelope, position: float) -> None: update_history(envelope, path_length) for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: envelope.transform(matrix) for child_node in node.getChildNodes(EXIT): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: envelope.transform(matrix) @@ -187,16 +191,18 @@ def precompute_matrices(self, envelope: Envelope, index_start: int = 0, index_st nodes = self.lattice.getNodes() nodes = nodes[index_start : index_stop] + sync_part = envelope.sync_part + self.elements = [] for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: self.elements.append((child_node, matrix)) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: self.elements.append((child_node, matrix)) @@ -205,17 +211,17 @@ def precompute_matrices(self, envelope: Envelope, index_start: int = 0, index_st if length > 0: self.elements.append(("sc", length)) - matrix = get_matrix(node, envelope=envelope, part_index=part_index) + matrix = get_matrix(node, sync_part, part_index=part_index) if matrix is not None: self.elements.append((node, matrix)) for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: self.elements.append((node, matrix)) for child_node in node.getChildNodes(EXIT): - matrix = get_matrix(child_node, envelope=envelope) + matrix = get_matrix(child_node, sync_part) if matrix is not None: self.elements.append((node, matrix)) diff --git a/py/orbit/envelope/utils.py b/py/orbit/envelope/utils.py index 71499e31..9102794e 100644 --- a/py/orbit/envelope/utils.py +++ b/py/orbit/envelope/utils.py @@ -2,7 +2,6 @@ import numpy as np from scipy.constants import epsilon_0 -from orbit.core.bunch import SyncParticle from orbit.utils.consts import charge_electron @@ -12,47 +11,6 @@ def get_classical_radius(charge: float, mass: float) -> float: return q**2 / (4.0 * math.pi * epsilon_0 * rest_energy) -def get_dp_p_coeff(sync_part: SyncParticle) -> float: - # dE/E = (beta^2) * dp/p - # dE = (beta^2 * E) * dp/p - # dE = (beta^2 * gamma * m * c^2) * dp/p - beta = sync_part.beta() - gamma = sync_part.gamma() - rest_energy = sync_part.mass() # GeV - return 1.0 / (beta**2 * gamma * rest_energy) - - -def get_zp_coeff(sync_part: SyncParticle) -> float: - # dE/E = (beta^2) * dp/p = (beta^2) * (gamma^2) z' - # dE = (beta^2 * gamma^2 * E) * z' - # dE = (beta^2 * gamma^3 * m * c^2) * z' - beta = sync_part.beta() - gamma = sync_part.gamma() - rest_energy = sync_part.mass() - return 1.0 / (beta**2 * gamma**3 * rest_energy) - - -def convert_matrix_dp_p_to_dE(matrix: np.ndarray, sync_part: SyncParticle) -> np.ndarray: - # v = [x, x', y, y', z, dp/p] - # w = [x, x', y, y', z, dE] - # v = A w - # v -> M v - # w -> A M A^-1 - dp_p_coeff = get_dp_p_coeff(sync_part) - matrix[:5, 5] *= dp_p_coeff - matrix[5, :5] /= dp_p_coeff - matrix[5, 6] /= dp_p_coeff # driving term - return matrix - - -def convert_matrix_zp_to_dE(matrix: np.ndarray, sync_part: SyncParticle) -> np.ndarray: - zp_coeff = get_zp_coeff(sync_part) - matrix[:5, 5] *= zp_coeff - matrix[5, :5] /= zp_coeff - matrix[5, 6] /= zp_coeff # driving term - return matrix - - def gen_dist_gauss(size: int, cov_matrix: np.ndarray) -> np.ndarray: return np.random.multivariate_normal( mean=np.zeros(cov_matrix.shape[0]), diff --git a/py/orbit/envelope/matrix.py b/py/orbit/utils/matrix.py similarity index 71% rename from py/orbit/envelope/matrix.py rename to py/orbit/utils/matrix.py index ee0cebdb..885c85b4 100644 --- a/py/orbit/envelope/matrix.py +++ b/py/orbit/utils/matrix.py @@ -1,9 +1,13 @@ +"""Transfer matrix definitions.""" import math import numpy as np from orbit.core.bunch import Bunch from orbit.core.bunch import SyncParticle +from orbit.core.orbit_utils import Matrix +from orbit.core.teapot_base import MatrixGenerator +from orbit.lattice import AccLattice from orbit.lattice import AccNode from orbit.teapot import ApertureTEAPOT from orbit.teapot import DriftTEAPOT @@ -29,12 +33,8 @@ from orbit.py_linac.lattice import TiltElement as TiltLINAC from orbit.py_linac.lattice import FringeField as FringeFieldLINAC from orbit.py_linac.lattice import BaseRF_Gap as BaseRF_Gap -from orbit.py_linac.lattice import LinacApertureNode as ApertureLINAC from orbit.utils.consts import speed_of_light -from .envelope import Envelope -from .utils import get_dp_p_coeff - IGNORE_NODE_TYPES = [ NodeTEAPOT, @@ -48,6 +48,47 @@ ] +def get_dp_p_coeff(sync_part: SyncParticle) -> float: + # dE/E = (beta^2) * dp/p + # dE = (beta^2 * E) * dp/p + # dE = (beta^2 * gamma * m * c^2) * dp/p + beta = sync_part.beta() + gamma = sync_part.gamma() + rest_energy = sync_part.mass() # GeV + return 1.0 / (beta**2 * gamma * rest_energy) + + +def get_zp_coeff(sync_part: SyncParticle) -> float: + # dE/E = (beta^2) * dp/p = (beta^2) * (gamma^2) z' + # dE = (beta^2 * gamma^2 * E) * z' + # dE = (beta^2 * gamma^3 * m * c^2) * z' + beta = sync_part.beta() + gamma = sync_part.gamma() + rest_energy = sync_part.mass() + return 1.0 / (beta**2 * gamma**3 * rest_energy) + + +def convert_matrix_dp_p_to_dE(matrix: np.ndarray, sync_part: SyncParticle) -> np.ndarray: + # v = [x, x', y, y', z, dp/p] + # w = [x, x', y, y', z, dE] + # v = A w + # v -> M v + # w -> A M A^-1 + dp_p_coeff = get_dp_p_coeff(sync_part) + matrix[:5, 5] *= dp_p_coeff + matrix[5, :5] /= dp_p_coeff + matrix[5, 6] /= dp_p_coeff # driving term + return matrix + + +def convert_matrix_zp_to_dE(matrix: np.ndarray, sync_part: SyncParticle) -> np.ndarray: + zp_coeff = get_zp_coeff(sync_part) + matrix[:5, 5] *= zp_coeff + matrix[5, :5] /= zp_coeff + matrix[5, 6] /= zp_coeff # driving term + return matrix + + def get_matrix_tilt(angle: float) -> np.ndarray: cos_phi = math.cos(angle) sin_phi = math.sin(angle) @@ -68,9 +109,7 @@ def get_matrix_kick(kx: float = 0.0, ky: float = 0.0, kE: float = 0.0) -> np.nda return M -def get_matrix_drift(envelope: Envelope, length: float) -> np.ndarray: - sync_part = envelope.sync_part - +def get_matrix_drift(sync_part: SyncParticle, length: float) -> np.ndarray: M = np.identity(7) M[0, 1] = length M[2, 3] = length @@ -81,11 +120,9 @@ def get_matrix_drift(envelope: Envelope, length: float) -> np.ndarray: return M -def get_matrix_quad(envelope: Envelope, length: float, kq: float) -> np.ndarray: +def get_matrix_quad(sync_part: SyncParticle, length: float, kq: float) -> np.ndarray: if abs(kq) == 0: - return get_matrix_drift(envelope=envelope, length=length) - - sync_part = envelope.sync_part + return get_matrix_drift(sync_part, length) sqrt_abs_kq = math.sqrt(abs(kq)) @@ -124,9 +161,7 @@ def get_matrix_quad(envelope: Envelope, length: float, kq: float) -> np.ndarray: return M -def get_matrix_bend(envelope: Envelope, length: float, theta: float) -> np.ndarray: - sync_part = envelope.sync_part - +def get_matrix_bend(sync_part: SyncParticle, length: float, theta: float) -> np.ndarray: rho = length / theta cx = math.cos(theta) sx = math.sin(theta) @@ -148,11 +183,9 @@ def get_matrix_bend(envelope: Envelope, length: float, theta: float) -> np.ndarr return M -def get_matrix_solenoid(envelope: Envelope, length: float, B: float) -> np.ndarray: +def get_matrix_solenoid(sync_part: SyncParticle, length: float, B: float) -> np.ndarray: if B == 0: - return get_matrix_drift(envelope=envelope, length=length) - - sync_part = envelope.sync_part + return get_matrix_drift(sync_part, length) phase = B * length @@ -183,11 +216,9 @@ def get_matrix_solenoid(envelope: Envelope, length: float, B: float) -> np.ndarr return M -def get_matrix_cf(envelope: Envelope, length: float, kq: float) -> np.ndarray: +def get_matrix_cf(sync_part: SyncParticle, length: float, kq: float) -> np.ndarray: if kq == 0: - return get_matrix_drift(envelope=envelope, length=length) - - sync_part = envelope.sync_part + return get_matrix_drift(sync_part, length) sqrt_abs_kq = math.sqrt(abs(kq)) @@ -206,13 +237,11 @@ def get_matrix_cf(envelope: Envelope, length: float, kq: float) -> np.ndarray: return M -def get_matrix_rf_gap(envelope: Envelope, frequency: float, E0TL: float, phase: float) -> np.ndarray: - sync_part = envelope.sync_part - +def get_matrix_rf_gap(sync_part: SyncParticle, frequency: float, E0TL: float, phase: float) -> np.ndarray: gamma = sync_part.gamma() beta = sync_part.beta() mass = sync_part.mass() - charge = envelope.charge + charge = sync_part.charge() kin_energy_in = sync_part.kinEnergy() charge_E0TL_sin = charge * E0TL * math.sin(phase) @@ -250,23 +279,33 @@ def get_matrix_rf_gap(envelope: Envelope, frequency: float, E0TL: float, phase: return M -def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: +def orbit_matrix_to_numpy(matrix: Matrix) -> np.ndarray: + matrix_out = np.zeros(matrix.size()) + for i in range(matrix_out.shape[0]): + for j in range(matrix_out.shape[1]): + matrix_out[i, j] = matrix.get(i, j) + return matrix_out + + +def get_matrix(node: AccNode, sync_part: SyncParticle, part_index: int = -1, fit: bool = False) -> np.ndarray | None: """Calculate transfer matrix and update synchronous particle. - This function maps various accelerator nodes to 7 x 7 transfer matrices - for envelope tracking. For non-accelerating, finite-length nodes, the - synchronous particle time is updated as in a drift. Accelerating nodes - such as RF gaps will update the synchronous particle energy. + This function maps various accelerator nodes to 7 x 7 transfer matrices. + For non-accelerating, finite-length nodes, the synchronous particle time + is updated as in a drift. Accelerating nodes such as RF gaps will update + the synchronous particle energy. Args: node: The accelerator node. - envelope: The beam envelope. + sync_part: Synchronous particle part_index: Index of the part within the node. An index of -1 returns the transfer matrix for the entire node. + fit: Whether to fit matrix to tracking data. Returns: - 7 x 7 transfer matrix or None. If None, the node can be ignored during - envelope tracking. + 7 x 7 transfer matrix or None. """ + if fit: + raise NotImplementedError node_type = type(node) if node_type in IGNORE_NODE_TYPES: @@ -278,7 +317,7 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd if node_type is DriftTEAPOT: if length <= 0: return None - return get_matrix_drift(envelope=envelope, length=length) + return get_matrix_drift(sync_part, length) elif node_type is SolenoidTEAPOT: if length <= 0: @@ -287,16 +326,16 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd B = node.getParam("B") if node.waveform: B *= node.waveform.getStrength() - B *= envelope.charge_sign + B *= np.sign(sync_part.charge()) - return get_matrix_solenoid(envelope=envelope, length=length, B=B) + return get_matrix_solenoid(sync_part, length=length, B=B) elif node_type is MultipoleTEAPOT: if length <= 0: return None if np.all(np.abs(node.getParam("kls")) == 0): - return get_matrix_drift(envelope=envelope, length=length) + return get_matrix_drift(sync_part, length) elif node_type is QuadTEAPOT: if length <= 0: @@ -305,9 +344,9 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd kq = node.getParam("kq") if node.waveform: kq *= node.waveform.getStrength() - kq *= envelope.charge_sign + kq *= np.sign(sync_part.charge()) - return get_matrix_quad(envelope=envelope, length=length, kq=kq) + return get_matrix_quad(sync_part, length=length, kq=kq) elif node_type is BendTEAPOT: if length <= 0: @@ -316,9 +355,9 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd theta = node.getParam("theta") / (nparts - 1) if part_index == 0 or part_index == nparts - 1: theta *= 0.5 - theta *= envelope.charge_sign + theta *= np.sign(sync_part.charge()) - return get_matrix_bend(envelope=envelope, length=length, theta=theta) + return get_matrix_bend(sync_part, length=length, theta=theta) elif node_type is KickTEAPOT: scale = 1.0 @@ -333,10 +372,10 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd if abs(kx) > 0 or abs(ky) > 0 or abs(kE) > 0: return np.matmul( get_matrix_kick(kx=kx, ky=ky, kE=kE), - get_matrix_drift(envelope=envelope, length=length), + get_matrix_drift(sync_part, length), ) else: - return get_matrix_drift(envelope=envelope, length=length) + return get_matrix_drift(sync_part, length) elif node_type is TiltTEAPOT: angle = node.getTiltAngle() @@ -349,24 +388,24 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd return None kq = node.getParam("kq") - kq *= envelope.charge_sign + kq *= np.sign(sync_part.charge()) if node.waveform: kq *= node.waveform.getStrength() - return get_matrix_cf(envelope=envelope, length=length, kq=kq) + return get_matrix_cf(sync_part, length=length, kq=kq) elif node_type is DriftLINAC: if length <= 0: return None - return get_matrix_drift(envelope=envelope, length=length) + return get_matrix_drift(sync_part, length) elif node_type is QuadLINAC: if length <= 0: return None - brho = 3.335640952 * envelope.momentum / envelope.charge + brho = 3.335640952 * sync_part.momentum() / sync_part.charge() kq = node.getParam("dB/dr") / brho - return get_matrix_quad(envelope=envelope, length=length, kq=kq) + return get_matrix_quad(sync_part, length=length, kq=kq) elif node_type is BendLINAC: if length <= 0: @@ -375,14 +414,14 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd theta = node.getParam("theta") / (nparts - 1) if part_index == 0 or part_index == nparts - 1: theta *= 0.5 - theta *= envelope.charge_sign + theta *= np.sign(sync_part.charge()) - return get_matrix_bend(envelope=envelope, length=length, theta=theta) + return get_matrix_bend(sync_part, length=length, theta=theta) elif node_type is DCorrectorHLINAC: length = node.getParam("effLength") / nparts field = node.getParam("B") - delta_xp = -field * envelope.charge * length * 0.299792 / envelope.momentum + delta_xp = -field * sync_part.charge() * length * 0.299792 / sync_part.momentum() if delta_xp == 0: return None return get_matrix_kick(kx=delta_xp, ky=0.0, kE=0.0) @@ -390,7 +429,7 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd elif node_type is DCorrectorVLINAC: length = node.getParam("effLength") / nparts field = node.getParam("B") - delta_yp = -field * envelope.charge * length * 0.299792 / envelope.momentum + delta_yp = -field * sync_part.charge() * length * 0.299792 / sync_part.momentum() if delta_yp == 0: return None return get_matrix_kick(kx=0.0, ky=delta_yp, kE=0.0) @@ -398,8 +437,8 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd elif node_type is SolenoidLINAC: if length <= 0: return None - B = node.getParam("B") * envelope.charge_sign - return get_matrix_solenoid(envelope=envelope, length=length, B=B) + B = node.getParam("B") * np.sign(sync_part.charge()) + return get_matrix_solenoid(sync_part, length=length, B=B) elif node_type is TiltLINAC: angle = node.getTiltAngle() @@ -416,7 +455,6 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd phase = cavity.getPhase() + mode_phase amplitude = cavity.getAmp() - sync_part = envelope.sync_part arrival_time = sync_part.time() arrival_time_design = cavity.getDesignArrivalTime() @@ -424,7 +462,7 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd if cavity.isDesignSetUp(): phase = math.fmod(frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, 2.0 * math.pi) else: - orbitFinalize("Run `trackDesign` first to initialize cavity phases.") + raise ValueError("Run `trackDesign` first to initialize cavity phases.") else: phase = math.fmod(frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase,2.0 * math.pi) @@ -434,7 +472,7 @@ def get_matrix(node: AccNode, envelope: Envelope, part_index: int = -1) -> np.nd return None return get_matrix_rf_gap( - envelope=envelope, + sync_part=sync_part, frequency=frequency, E0TL=(E0TL * amplitude), phase=phase, diff --git a/py/orbit/utils/meson.build b/py/orbit/utils/meson.build index 6d969897..7ada54d2 100644 --- a/py/orbit/utils/meson.build +++ b/py/orbit/utils/meson.build @@ -12,7 +12,8 @@ py_sources = files([ 'consts.py', 'multiDimArray.py', 'NamedObject.py', - 'orbitFinalize.py' + 'orbitFinalize.py', + 'matrix.py' ]) python.install_sources( diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index 5275ab6c..403293fc 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -357,14 +357,14 @@ def test_rf_gap_matrix( coords_out_1 = collect_bunch(bunch_out_1)["coords"] - from orbit.envelope.matrix import get_matrix_rf_gap + from orbit.utils.matrix import get_matrix_rf_gap bunch_out_2 = Bunch() bunch_in.copyBunchTo(bunch_out_2) - envelope = Envelope(bunch=bunch_in) + sync_part = bunch_in.getSyncParticle() matrix = get_matrix_rf_gap( - envelope=envelope, + sync_part, frequency=frequency, E0TL=E0TL, phase=phase, From 6511c23e81509168a6e87d2fdd29eeccd526f591 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Wed, 2 Sep 2026 21:36:32 -0400 Subject: [PATCH 09/42] Envelope stores SyncParticle, not Bunch --- py/orbit/envelope/envelope.py | 36 +++++++++-------------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index a837b994..ab994800 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -1,3 +1,5 @@ +from multiprocessing.sharedctypes import Synchronized + import numpy as np import scipy.constants import scipy.special @@ -26,7 +28,7 @@ class Envelope: """Represents beam envelope/centroid. Attributes: - bunch: Bunch containing synchronous particle and (optionally) test particles. + sync_part: Synchronous particle. cov_matrix: 6 x 6 covariance matrix centroid: 6 x 1 centroid vector. intensity: Total number of particles. @@ -34,41 +36,21 @@ class Envelope: def __init__( self, - bunch: Bunch, + sync_part: SynchParticle, cov_matrix: np.ndarray = None, centroid: np.ndarray = None, intensity: float = 0.0, ) -> None: - empty_bunch = Bunch() - bunch.copyEmptyBunchTo(empty_bunch) - - self.bunch = empty_bunch - self.sync_part = self.bunch.getSyncParticle() + self.sync_part = sync_part self.centroid = centroid if self.centroid is None: - if bunch.getSize(): - twiss_calc = BunchTwissAnalysis() - twiss_calc.analyzeBunch(bunch) - self.centroid = np.zeros(6) - for i in range(6): - self.centroid[i] = twiss_calc.getAverage(i) - else: - self.centroid = np.zeros(6) + self.centroid = np.zeros(6) self.cov_matrix = cov_matrix if self.cov_matrix is None: - if bunch.getSize(): - twiss_calc = BunchTwissAnalysis() - twiss_calc.analyzeBunch(bunch) - self.cov_matrix = np.zeros((6, 6)) - for i in range(6): - for j in range(6): - self.cov_matrix[i, j] = twiss_calc.getCorrelation(i, j) - self.cov_matrix[j, i] = self.cov_matrix[i, j] - else: - self.cov_matrix = np.eye(6) + self.cov_matrix = np.eye(6) self.intensity = intensity self.classical_radius = get_classical_radius(self.charge, self.mass) @@ -81,7 +63,7 @@ def __init__( def copy(self): return Envelope( - bunch=self.bunch, + sync_part=self.sync_part, cov_matrix=self.cov_matrix, centroid=self.centroid, intensity=self.intensity @@ -105,7 +87,7 @@ def mass(self) -> float: @property def charge(self) -> float: - return self.bunch.charge() + return self.sync_part.charge() @property def momentum(self) -> float: From 18dbc5f78673a0b64d0800e9dc5444a7b36bbee6 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Wed, 2 Sep 2026 21:42:39 -0400 Subject: [PATCH 10/42] Envelope now takes SyncParticle instead of Bunch in constructor --- examples/Envelope/sns_linac/test_sns_linac.py | 2 +- examples/Envelope/sns_ring/test_sns_ring.py | 2 +- .../Envelope/sns_ring/test_sns_ring_speed.py | 2 +- examples/Envelope/test_env_2d_fodo.py | 2 +- examples/Envelope/test_env_2d_fodo_speed.py | 2 +- examples/Envelope/test_env_3d_drift.py | 2 +- py/orbit/envelope/envelope.py | 4 +--- tests/py/orbit/test_env.py | 18 ++++++++++++------ 8 files changed, 19 insertions(+), 15 deletions(-) diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index 7614d54f..d057a77f 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -166,7 +166,7 @@ def main(args: argparse.Namespace) -> None: for j in range(6): cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) - envelope = Envelope(bunch=bunch, cov_matrix=cov_matrix, intensity=intensity) + envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix, intensity=intensity) tracker = EnvelopeTracker(lattice, sc=("3d" if args.sc else None)) diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring/test_sns_ring.py index 4efe4289..7518c4e4 100644 --- a/examples/Envelope/sns_ring/test_sns_ring.py +++ b/examples/Envelope/sns_ring/test_sns_ring.py @@ -157,7 +157,7 @@ def main(args: argparse.Namespace) -> None: print("TRACK ENVELOPE") envelope = Envelope( - bunch=bunch, + sync_part=sync_part, cov_matrix=cov_matrix_init, centroid=centroid_init, intensity=args.intensity, diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring/test_sns_ring_speed.py index 773febc6..8ce6a63c 100644 --- a/examples/Envelope/sns_ring/test_sns_ring_speed.py +++ b/examples/Envelope/sns_ring/test_sns_ring_speed.py @@ -80,7 +80,7 @@ print("ENVELOPE") envelope = Envelope( - bunch=bunch, + sync_part=sync_part, cov_matrix=cov_matrix_init, intensity=args.intensity, ) diff --git a/examples/Envelope/test_env_2d_fodo.py b/examples/Envelope/test_env_2d_fodo.py index 824cc3b7..0a4079ac 100644 --- a/examples/Envelope/test_env_2d_fodo.py +++ b/examples/Envelope/test_env_2d_fodo.py @@ -135,7 +135,7 @@ def main(args: argparse.Namespace) -> None: # Create envelope envelope = Envelope( - bunch=bunch, + sync_part=sync_part, cov_matrix=cov_matrix_init, centroid=centroid_init, intensity=args.intensity, diff --git a/examples/Envelope/test_env_2d_fodo_speed.py b/examples/Envelope/test_env_2d_fodo_speed.py index 063ddfaf..6882c210 100644 --- a/examples/Envelope/test_env_2d_fodo_speed.py +++ b/examples/Envelope/test_env_2d_fodo_speed.py @@ -82,7 +82,7 @@ print("ENVELOPE") envelope = Envelope( - bunch=bunch, + sync_part=sync_part, cov_matrix=cov_matrix_init, intensity=args.intensity, ) diff --git a/examples/Envelope/test_env_3d_drift.py b/examples/Envelope/test_env_3d_drift.py index 798d4448..c4ec8107 100644 --- a/examples/Envelope/test_env_3d_drift.py +++ b/examples/Envelope/test_env_3d_drift.py @@ -120,7 +120,7 @@ def main(args: argparse.Namespace) -> None: centroid_init = np.zeros(6) envelope = Envelope( - bunch=bunch, + sync_part=sync_part, cov_matrix=cov_matrix_init, centroid=centroid_init, intensity=args.intensity, diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index ab994800..6c4e962c 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -4,8 +4,6 @@ import scipy.constants import scipy.special -from orbit.core.bunch import Bunch -from orbit.core.bunch import BunchTwissAnalysis from orbit.core.bunch import SyncParticle from orbit.utils.matrix import convert_matrix_zp_to_dE @@ -36,7 +34,7 @@ class Envelope: def __init__( self, - sync_part: SynchParticle, + sync_part: SyncParticle, cov_matrix: np.ndarray = None, centroid: np.ndarray = None, intensity: float = 0.0, diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index 403293fc..f4367cb7 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -88,7 +88,9 @@ def track_and_compare_rms( # Initialize bunch bunch = Bunch() bunch.mass(mass_proton) - bunch.getSyncParticle().kinEnergy(kin_energy) + + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(kin_energy) # Track bunch particles = np.random.multivariate_normal(np.zeros(6), cov_matrix, size=nparts) @@ -103,7 +105,7 @@ def track_and_compare_rms( data["bunch"]["cov"]["out"] = cov_scale * calc_bunch_cov(bunch) # Track envelope - envelope = Envelope(bunch=bunch, cov_matrix=cov_matrix) + envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix) envelope_tracker = EnvelopeTracker(lattice=lattice) data["env"]["cov"]["in"] = cov_scale * envelope.cov_matrix @@ -386,10 +388,12 @@ def test_sc_3d_cold_expansion(): def test_track_sublattice_no_error(): bunch = Bunch() bunch.mass(mass_proton) - bunch.getSyncParticle().kinEnergy(0.001) + + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(0.001) cov_matrix = np.diag(np.square([1e-3, 0, 1e-3, 0.0, 1e-3, 0.0])) - envelope = Envelope(bunch, cov_matrix=cov_matrix) + envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix) lattice = TEAPOT_Lattice() @@ -408,10 +412,12 @@ def test_get_total_matrix() -> None: bunch = Bunch() bunch.mass(mass_proton) - bunch.getSyncParticle().kinEnergy(0.001) + + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(0.001) cov_matrix = make_default_cov_matrix() - envelope = Envelope(bunch, cov_matrix=cov_matrix, intensity=1e7) + envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix, intensity=1e7) tracker = EnvelopeTracker(lattice, sc="2d") From 888b31c00f92867dc6037e68dadde5d8af86e09a Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Wed, 2 Sep 2026 22:24:57 -0400 Subject: [PATCH 11/42] Move get_matrix function to node method node.getMatrix() --- py/orbit/envelope/track.py | 31 ++- py/orbit/lattice/AccNode.py | 15 +- py/orbit/py_linac/lattice/LinacAccNodes.py | 73 ++++++ py/orbit/py_linac/lattice/LinacRfGapNodes.py | 42 ++++ py/orbit/teapot/teapot.py | 140 ++++++++++- py/orbit/utils/matrix.py | 234 ------------------- 6 files changed, 274 insertions(+), 261 deletions(-) diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py index e9e952c6..0ccc4844 100644 --- a/py/orbit/envelope/track.py +++ b/py/orbit/envelope/track.py @@ -8,7 +8,6 @@ from orbit.lattice import AccLattice from orbit.teapot import BendTEAPOT from orbit.py_linac.lattice import Bend as BendLINAC -from orbit.utils.matrix import get_matrix from .envelope import Envelope @@ -59,13 +58,13 @@ def track(self, envelope: Envelope, index_start: int = 0, index_stop: int = None for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: envelope.transform(matrix) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: envelope.transform(matrix) @@ -80,19 +79,19 @@ def track(self, envelope: Envelope, index_start: int = 0, index_stop: int = None else: raise ValueError - matrix = get_matrix(node, sync_part, part_index=part_index) + matrix = node.getMatrix(sync_part, part_index=part_index) if matrix is not None: if matrix_sc is not None: matrix = matrix @ matrix_sc envelope.transform(matrix) for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: envelope.transform(matrix) for child_node in node.getChildNodes(EXIT): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: envelope.transform(matrix) @@ -141,13 +140,13 @@ def update_history(envelope: Envelope, position: float) -> None: for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: envelope.transform(matrix) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: envelope.transform(matrix) @@ -162,7 +161,7 @@ def update_history(envelope: Envelope, position: float) -> None: else: raise ValueError - matrix = get_matrix(node, sync_part, part_index=part_index) + matrix = node.getMatrix(sync_part, part_index=part_index) if matrix is not None: if matrix_sc is not None: matrix = matrix @ matrix_sc @@ -172,12 +171,12 @@ def update_history(envelope: Envelope, position: float) -> None: update_history(envelope, path_length) for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: envelope.transform(matrix) for child_node in node.getChildNodes(EXIT): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: envelope.transform(matrix) @@ -196,13 +195,13 @@ def precompute_matrices(self, envelope: Envelope, index_start: int = 0, index_st self.elements = [] for node_index, node in enumerate(nodes): for child_node in node.getChildNodes(ENTRANCE): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: self.elements.append((child_node, matrix)) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: self.elements.append((child_node, matrix)) @@ -211,17 +210,17 @@ def precompute_matrices(self, envelope: Envelope, index_start: int = 0, index_st if length > 0: self.elements.append(("sc", length)) - matrix = get_matrix(node, sync_part, part_index=part_index) + matrix = node.getMatrix(sync_part, part_index=part_index) if matrix is not None: self.elements.append((node, matrix)) for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: self.elements.append((node, matrix)) for child_node in node.getChildNodes(EXIT): - matrix = get_matrix(child_node, sync_part) + matrix = child_node.getMatrix(sync_part) if matrix is not None: self.elements.append((node, matrix)) diff --git a/py/orbit/lattice/AccNode.py b/py/orbit/lattice/AccNode.py index fdc145dc..1926ff9c 100644 --- a/py/orbit/lattice/AccNode.py +++ b/py/orbit/lattice/AccNode.py @@ -1,13 +1,20 @@ +from __future__ import annotations + import sys import os import math +from typing import TYPE_CHECKING from ..utils import orbitFinalize from ..utils import NamedObject from ..utils import TypedObject from ..utils import ParamsDictObject -from ..lattice import AccActionsContainer +from .AccActionsContainer import AccActionsContainer + +if TYPE_CHECKING: + import numpy as np + from orbit.core.bunch import SyncParticle class AccNode(NamedObject, TypedObject, ParamsDictObject): @@ -145,6 +152,12 @@ def initialize(self): """ pass + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + """ + Return the transfer matrix for this node and update the synchronous particle. + """ + raise NotImplementedError(str(self)) + def getNumberOfChildren(self): """ Returns the total number of direct children diff --git a/py/orbit/py_linac/lattice/LinacAccNodes.py b/py/orbit/py_linac/lattice/LinacAccNodes.py index ba72fef5..4186353f 100755 --- a/py/orbit/py_linac/lattice/LinacAccNodes.py +++ b/py/orbit/py_linac/lattice/LinacAccNodes.py @@ -8,16 +8,26 @@ import os import math +import numpy as np # import the finalization function from orbit.utils import orbitFinalize # import general accelerator elements and lattice from orbit.lattice import AccNode, AccActionsContainer, AccNodeBunchTracker +from orbit.core.bunch import SyncParticle # import teapot base functions from wrapper around C++ functions from orbit.teapot_base import TPB +from orbit.utils.matrix import get_matrix_bend +from orbit.utils.matrix import get_matrix_cf +from orbit.utils.matrix import get_matrix_drift +from orbit.utils.matrix import get_matrix_kick +from orbit.utils.matrix import get_matrix_quad +from orbit.utils.matrix import get_matrix_solenoid +from orbit.utils.matrix import get_matrix_tilt + # Import the linac specific tracking from linac_tracking. This module has # the following functions duplicated the original TEAPOT functions # drift - linac drift tracking @@ -137,6 +147,9 @@ def __init__(self, name="none"): BaseLinacNode.__init__(self, name) self.setType("markerLinacNode") + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + return None + class LinacNode(BaseLinacNode): """ @@ -304,6 +317,12 @@ def track(self, paramsDict): bunch = paramsDict["bunch"] self.tracking_module.drift(bunch, length) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + return get_matrix_drift(sync_part, length) + class Quad(LinacMagnetNode): """ @@ -513,6 +532,15 @@ def getTotalField(self, z): G = self.getParam("dB/dr") return G + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + + brho = 3.335640952 * sync_part.momentum() / sync_part.charge() + kq = self.getParam("dB/dr") / brho + return get_matrix_quad(sync_part, length=length, kq=kq) + class Bend(LinacMagnetNode): """ @@ -705,6 +733,19 @@ def track(self, paramsDict): TPB.bend1(bunch, length, theta / 2.0) return + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + + nparts = self.getnParts() + theta = self.getParam("theta") / (nparts - 1) + if part_index == 0 or part_index == nparts - 1: + theta *= 0.5 + theta *= np.sign(sync_part.charge()) + + return get_matrix_bend(sync_part, length=length, theta=theta) + class DCorrectorH(LinacMagnetNode): """ @@ -750,6 +791,14 @@ def track(self, paramsDict): kick = -field * charge * length * 0.299792 / momentum self.tracking_module.kick(bunch, kick, 0.0, 0.0) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getParam("effLength") / self.getnParts() + field = self.getParam("B") + delta_xp = -field * sync_part.charge() * length * 0.299792 / sync_part.momentum() + if delta_xp == 0: + return None + return get_matrix_kick(kx=delta_xp, ky=0.0, kE=0.0) + class DCorrectorV(LinacMagnetNode): """ @@ -795,6 +844,14 @@ def track(self, paramsDict): kick = field * charge * length * 0.299792 / momentum self.tracking_module.kick(bunch, 0, kick, 0.0) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getParam("effLength") / self.getnParts() + field = self.getParam("B") + delta_yp = -field * sync_part.charge() * length * 0.299792 / sync_part.momentum() + if delta_yp == 0: + return None + return get_matrix_kick(kx=0.0, ky=delta_yp, kE=0.0) + class ThickKick(LinacMagnetNode): """ @@ -892,6 +949,13 @@ def track(self, paramsDict): useCharge = paramsDict["useCharge"] TPB.soln(bunch, length, B, useCharge) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + B = self.getParam("B") * np.sign(sync_part.charge()) + return get_matrix_solenoid(sync_part, length=length, B=B) + class AbstractRF_Gap(BaseLinacNode): """ This is an abstarct class for all RF Gap classes. @@ -1010,6 +1074,12 @@ def track(self, paramsDict): bunch = paramsDict["bunch"] TPB.rotatexy(bunch, self.__angle) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + angle = self.getTiltAngle() + if angle == 0: + return None + return get_matrix_tilt(angle=angle) + class FringeField(BaseLinacNode): """ @@ -1034,6 +1104,9 @@ def track(self, paramsDict): if self.__trackFunc != None and self.__usage == True: self.__trackFunc(self, paramsDict) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + return None + def setFringeFieldFunction(self, trackFunction=None): """ Sets the fringe field function that will track the bunch through the fringe. diff --git a/py/orbit/py_linac/lattice/LinacRfGapNodes.py b/py/orbit/py_linac/lattice/LinacRfGapNodes.py index 30b1fbe8..6f482f39 100644 --- a/py/orbit/py_linac/lattice/LinacRfGapNodes.py +++ b/py/orbit/py_linac/lattice/LinacRfGapNodes.py @@ -5,6 +5,7 @@ import os import math +import numpy as np # ---- MPI module function and classes from orbit.core.orbit_mpi import mpi_comm, mpi_datatype, MPI_Comm_rank, MPI_Bcast @@ -26,6 +27,8 @@ # The abstract RF gap import from orbit.py_linac.lattice.LinacAccNodes import AbstractRF_Gap +from orbit.utils.matrix import get_matrix_rf_gap + # import teapot base functions from wrapper around C++ functions # Import the linac specific tracking from linac_tracking. This module has @@ -35,6 +38,7 @@ # quad2 - linac quad non-linear part of tracking from orbit.core.bunch import Bunch +from orbit.core.bunch import SyncParticle class BaseRF_Gap(AbstractRF_Gap): @@ -251,6 +255,44 @@ def track(self, paramsDict): # print "debug delta_time in deg=",frequency*(arrival_time - designArrivalTime)*380. # print "debug RF =",self.getName()," E0TL=",E0TL," phase=",(phase*180./math.pi - 180.)," eKin[MeV]=",bunch.getSyncParticle().kinEnergy()*1.0e+3 + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + E0TL = self.getParam("E0TL") + mode_phase = self.getParam("mode") * math.pi + + cavity = self.getRF_Cavity() + frequency = cavity.getFrequency() + phase = cavity.getPhase() + mode_phase + amplitude = cavity.getAmp() + + arrival_time = sync_part.time() + arrival_time_design = cavity.getDesignArrivalTime() + + if self.isFirstRFGap(): + if cavity.isDesignSetUp(): + phase = math.fmod( + frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, + 2.0 * math.pi, + ) + else: + raise ValueError("Run `trackDesign` first to initialize cavity phases.") + else: + phase = math.fmod( + frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, + 2.0 * math.pi, + ) + + self.setGapPhase(phase) + + if amplitude == 0.0: + return None + + return get_matrix_rf_gap( + sync_part=sync_part, + frequency=frequency, + E0TL=(E0TL * amplitude), + phase=phase, + ) + def trackDesign(self, paramsDict): """ The RF First Gap node setups the design time of passage diff --git a/py/orbit/teapot/teapot.py b/py/orbit/teapot/teapot.py index 63a09b27..1d64ec67 100644 --- a/py/orbit/teapot/teapot.py +++ b/py/orbit/teapot/teapot.py @@ -19,23 +19,32 @@ import sys import os import math +import numpy as np from typing import Any from typing import Callable from typing import Union -from ..lattice import AccLattice -from ..lattice import AccNode -from ..lattice import AccActionsContainer -from ..lattice import AccNodeBunchTracker -from ..teapot_base import TPB -from ..utils import orbitFinalize -from ..parsers.mad_parser import MAD_Parser -from ..parsers.mad_parser import MAD_LattElement -from ..parsers.madx_parser import MADX_Parser -from ..parsers.madx_parser import MADX_LattElement +from orbit.lattice import AccLattice +from orbit.lattice import AccNode +from orbit.lattice import AccActionsContainer +from orbit.lattice import AccNodeBunchTracker +from orbit.teapot_base import TPB +from orbit.utils import orbitFinalize +from orbit.parsers.mad_parser import MAD_Parser +from orbit.parsers.mad_parser import MAD_LattElement +from orbit.parsers.madx_parser import MADX_Parser +from orbit.parsers.madx_parser import MADX_LattElement +from orbit.utils.matrix import get_matrix_bend +from orbit.utils.matrix import get_matrix_cf +from orbit.utils.matrix import get_matrix_drift +from orbit.utils.matrix import get_matrix_kick +from orbit.utils.matrix import get_matrix_quad +from orbit.utils.matrix import get_matrix_solenoid +from orbit.utils.matrix import get_matrix_tilt from orbit.core.aperture import Aperture from orbit.core.bunch import Bunch +from orbit.core.bunch import SyncParticle from orbit.core.bunch import BunchTwissAnalysis @@ -440,6 +449,9 @@ def track(self, paramsDict: dict) -> None: turn = bunch.bunchAttrInt("TurnNumber") bunch.bunchAttrInt("TurnNumber", turn + 1) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + return None + class NodeTEAPOT(BaseTEAPOT): def __init__(self, name: str = "no name") -> None: @@ -464,6 +476,11 @@ def __init__(self, name: str = "no name") -> None: self.addParam("tilt", self.__tiltNodeIN.getTiltAngle()) self.setType("node teapot") + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + if type(self) is NodeTEAPOT: + return None + return super().getMatrix(sync_part, part_index=part_index) + def setTiltAngle(self, angle: float = 0.0) -> None: """ Sets the tilt angle for the tilt operation. @@ -582,6 +599,12 @@ def track(self, paramsDict: dict) -> None: bunch = paramsDict["bunch"] TPB.drift(bunch, length) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + return get_matrix_drift(sync_part, length) + class ApertureTEAPOT(NodeTEAPOT): """ @@ -622,6 +645,9 @@ def track(self, paramsDict: dict) -> None: lostbunch = paramsDict["lostbunch"] self.aperture.checkBunch(bunch, lostbunch) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + return None + class MonitorTEAPOT(NodeTEAPOT): """ @@ -649,6 +675,9 @@ def track(self, paramsDict: dict) -> None: self.addParam("yAvg", self.twiss.getAverage(2)) self.addParam("ypAvg", self.twiss.getAverage(3)) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + return None + class BunchWrapTEAPOT(NodeTEAPOT): """ @@ -673,6 +702,9 @@ def track(self, paramsDict: dict) -> None: length = self.getParam("ring_length") TPB.wrapbunch(bunch, length) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + return None + class SolenoidTEAPOT(NodeTEAPOT): """ @@ -721,6 +753,18 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + + B = self.getParam("B") + if self.waveform: + B *= self.waveform.getStrength() + B *= np.sign(sync_part.charge()) + + return get_matrix_solenoid(sync_part, length=length, B=B) + class MultipoleTEAPOT(NodeTEAPOT): """ @@ -871,6 +915,16 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + + if np.all(np.abs(self.getParam("kls")) == 0): + return get_matrix_drift(sync_part, length) + + raise NotImplementedError(str(self)) + class QuadTEAPOT(NodeTEAPOT): """ @@ -1034,6 +1088,18 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + + kq = self.getParam("kq") + if self.waveform: + kq *= self.waveform.getStrength() + kq *= np.sign(sync_part.charge()) + + return get_matrix_quad(sync_part, length=length, kq=kq) + class BendTEAPOT(NodeTEAPOT): """ @@ -1248,6 +1314,19 @@ def track(self, paramsDict: dict) -> None: TPB.bend1(bunch, length, theta / 2.0) return + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + + nparts = self.getnParts() + theta = self.getParam("theta") / (nparts - 1) + if part_index == 0 or part_index == nparts - 1: + theta *= 0.5 + theta *= np.sign(sync_part.charge()) + + return get_matrix_bend(sync_part, length=length, theta=theta) + class RingRFTEAPOT(NodeTEAPOT): """ @@ -1414,6 +1493,26 @@ def setWaveform(self, waveform): """ self.waveform = waveform + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + nparts = self.getnParts() + + scale = 1.0 + if self.waveform is not None: + scale = self.waveform.getStrength() + + scale /= nparts - 1 + kx = scale * self.getParam("kx") + ky = scale * self.getParam("ky") + kE = self.getParam("dE") + + if abs(kx) > 0 or abs(ky) > 0 or abs(kE) > 0: + return np.matmul( + get_matrix_kick(kx=kx, ky=ky, kE=kE), + get_matrix_drift(sync_part, length), + ) + return get_matrix_drift(sync_part, length) + class TiltTEAPOT(BaseTEAPOT): """ @@ -1449,6 +1548,12 @@ def track(self, paramsDict: dict) -> None: bunch = paramsDict["bunch"] TPB.rotatexy(bunch, self.__angle) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + angle = self.getTiltAngle() + if angle == 0: + return None + return get_matrix_tilt(angle) + class FringeFieldTEAPOT(BaseTEAPOT): """ @@ -1478,6 +1583,9 @@ def track(self, paramsDict: dict) -> None: if self.__trackFunc != None: self.__trackFunc(self, paramsDict) + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + return None + def setFringeFieldFunction(self, trackFunction: Callable) -> None: """ Sets the fringe field function that will track the bunch through the fringe. @@ -1595,3 +1703,15 @@ def track(self, paramsDict): def setWaveform(self, waveform): self.waveform = waveform + + def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + length = self.getLength(part_index) + if length <= 0: + return None + + kq = self.getParam("kq") + kq *= np.sign(sync_part.charge()) + if self.waveform: + kq *= self.waveform.getStrength() + + return get_matrix_cf(sync_part, length=length, kq=kq) diff --git a/py/orbit/utils/matrix.py b/py/orbit/utils/matrix.py index 885c85b4..0f884f2f 100644 --- a/py/orbit/utils/matrix.py +++ b/py/orbit/utils/matrix.py @@ -3,51 +3,11 @@ import numpy as np -from orbit.core.bunch import Bunch from orbit.core.bunch import SyncParticle from orbit.core.orbit_utils import Matrix -from orbit.core.teapot_base import MatrixGenerator -from orbit.lattice import AccLattice -from orbit.lattice import AccNode -from orbit.teapot import ApertureTEAPOT -from orbit.teapot import DriftTEAPOT -from orbit.teapot import BendTEAPOT -from orbit.teapot import KickTEAPOT -from orbit.teapot import MonitorTEAPOT -from orbit.teapot import MultipoleTEAPOT -from orbit.teapot import NodeTEAPOT -from orbit.teapot import QuadTEAPOT -from orbit.teapot import SolenoidTEAPOT -from orbit.teapot import FringeFieldTEAPOT -from orbit.teapot import BunchWrapTEAPOT -from orbit.teapot import TiltTEAPOT -from orbit.teapot import ContinuousLinearFocusingTEAPOT -from orbit.teapot import TurnCounterTEAPOT -from orbit.py_linac.lattice import MarkerLinacNode as MarkerLINAC -from orbit.py_linac.lattice import Drift as DriftLINAC -from orbit.py_linac.lattice import Quad as QuadLINAC -from orbit.py_linac.lattice import Bend as BendLINAC -from orbit.py_linac.lattice import DCorrectorH as DCorrectorHLINAC -from orbit.py_linac.lattice import DCorrectorV as DCorrectorVLINAC -from orbit.py_linac.lattice import Solenoid as SolenoidLINAC -from orbit.py_linac.lattice import TiltElement as TiltLINAC -from orbit.py_linac.lattice import FringeField as FringeFieldLINAC -from orbit.py_linac.lattice import BaseRF_Gap as BaseRF_Gap from orbit.utils.consts import speed_of_light -IGNORE_NODE_TYPES = [ - NodeTEAPOT, - MonitorTEAPOT, - FringeFieldTEAPOT, - ApertureTEAPOT, - BunchWrapTEAPOT, - TurnCounterTEAPOT, - MarkerLINAC, - FringeFieldLINAC, -] - - def get_dp_p_coeff(sync_part: SyncParticle) -> float: # dE/E = (beta^2) * dp/p # dE = (beta^2 * E) * dp/p @@ -285,197 +245,3 @@ def orbit_matrix_to_numpy(matrix: Matrix) -> np.ndarray: for j in range(matrix_out.shape[1]): matrix_out[i, j] = matrix.get(i, j) return matrix_out - - -def get_matrix(node: AccNode, sync_part: SyncParticle, part_index: int = -1, fit: bool = False) -> np.ndarray | None: - """Calculate transfer matrix and update synchronous particle. - - This function maps various accelerator nodes to 7 x 7 transfer matrices. - For non-accelerating, finite-length nodes, the synchronous particle time - is updated as in a drift. Accelerating nodes such as RF gaps will update - the synchronous particle energy. - - Args: - node: The accelerator node. - sync_part: Synchronous particle - part_index: Index of the part within the node. An index of -1 returns - the transfer matrix for the entire node. - fit: Whether to fit matrix to tracking data. - Returns: - 7 x 7 transfer matrix or None. - """ - if fit: - raise NotImplementedError - - node_type = type(node) - if node_type in IGNORE_NODE_TYPES: - return None - - length = node.getLength(part_index) - nparts = node.getnParts() - - if node_type is DriftTEAPOT: - if length <= 0: - return None - return get_matrix_drift(sync_part, length) - - elif node_type is SolenoidTEAPOT: - if length <= 0: - return None - - B = node.getParam("B") - if node.waveform: - B *= node.waveform.getStrength() - B *= np.sign(sync_part.charge()) - - return get_matrix_solenoid(sync_part, length=length, B=B) - - elif node_type is MultipoleTEAPOT: - if length <= 0: - return None - - if np.all(np.abs(node.getParam("kls")) == 0): - return get_matrix_drift(sync_part, length) - - elif node_type is QuadTEAPOT: - if length <= 0: - return None - - kq = node.getParam("kq") - if node.waveform: - kq *= node.waveform.getStrength() - kq *= np.sign(sync_part.charge()) - - return get_matrix_quad(sync_part, length=length, kq=kq) - - elif node_type is BendTEAPOT: - if length <= 0: - return None - - theta = node.getParam("theta") / (nparts - 1) - if part_index == 0 or part_index == nparts - 1: - theta *= 0.5 - theta *= np.sign(sync_part.charge()) - - return get_matrix_bend(sync_part, length=length, theta=theta) - - elif node_type is KickTEAPOT: - scale = 1.0 - if node.waveform is not None: - scale = node.waveform.getStrength() - - scale /= (nparts - 1) - kx = scale * node.getParam("kx") - ky = scale * node.getParam("ky") - kE = node.getParam("dE") - - if abs(kx) > 0 or abs(ky) > 0 or abs(kE) > 0: - return np.matmul( - get_matrix_kick(kx=kx, ky=ky, kE=kE), - get_matrix_drift(sync_part, length), - ) - else: - return get_matrix_drift(sync_part, length) - - elif node_type is TiltTEAPOT: - angle = node.getTiltAngle() - if angle == 0: - return None - return get_matrix_tilt(angle) - - elif node_type is ContinuousLinearFocusingTEAPOT: - if length <= 0: - return None - - kq = node.getParam("kq") - kq *= np.sign(sync_part.charge()) - if node.waveform: - kq *= node.waveform.getStrength() - - return get_matrix_cf(sync_part, length=length, kq=kq) - - elif node_type is DriftLINAC: - if length <= 0: - return None - return get_matrix_drift(sync_part, length) - - elif node_type is QuadLINAC: - if length <= 0: - return None - - brho = 3.335640952 * sync_part.momentum() / sync_part.charge() - kq = node.getParam("dB/dr") / brho - return get_matrix_quad(sync_part, length=length, kq=kq) - - elif node_type is BendLINAC: - if length <= 0: - return None - - theta = node.getParam("theta") / (nparts - 1) - if part_index == 0 or part_index == nparts - 1: - theta *= 0.5 - theta *= np.sign(sync_part.charge()) - - return get_matrix_bend(sync_part, length=length, theta=theta) - - elif node_type is DCorrectorHLINAC: - length = node.getParam("effLength") / nparts - field = node.getParam("B") - delta_xp = -field * sync_part.charge() * length * 0.299792 / sync_part.momentum() - if delta_xp == 0: - return None - return get_matrix_kick(kx=delta_xp, ky=0.0, kE=0.0) - - elif node_type is DCorrectorVLINAC: - length = node.getParam("effLength") / nparts - field = node.getParam("B") - delta_yp = -field * sync_part.charge() * length * 0.299792 / sync_part.momentum() - if delta_yp == 0: - return None - return get_matrix_kick(kx=0.0, ky=delta_yp, kE=0.0) - - elif node_type is SolenoidLINAC: - if length <= 0: - return None - B = node.getParam("B") * np.sign(sync_part.charge()) - return get_matrix_solenoid(sync_part, length=length, B=B) - - elif node_type is TiltLINAC: - angle = node.getTiltAngle() - if angle == 0: - return None - return get_matrix_tilt(angle=angle) - - elif node_type is BaseRF_Gap: - E0TL = node.getParam("E0TL") - mode_phase = node.getParam("mode") * math.pi - - cavity = node.getRF_Cavity() - frequency = cavity.getFrequency() - phase = cavity.getPhase() + mode_phase - amplitude = cavity.getAmp() - - arrival_time = sync_part.time() - arrival_time_design = cavity.getDesignArrivalTime() - - if node.isFirstRFGap(): - if cavity.isDesignSetUp(): - phase = math.fmod(frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, 2.0 * math.pi) - else: - raise ValueError("Run `trackDesign` first to initialize cavity phases.") - else: - phase = math.fmod(frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase,2.0 * math.pi) - - node.setGapPhase(phase) - - if amplitude == 0.0: - return None - - return get_matrix_rf_gap( - sync_part=sync_part, - frequency=frequency, - E0TL=(E0TL * amplitude), - phase=phase, - ) - - raise NotImplementedError(str(node)) \ No newline at end of file From ac1686a1ecfa1ccd04269c94aba6ea3fe248ff01 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Wed, 2 Sep 2026 23:53:34 -0400 Subject: [PATCH 12/42] Track using lattice.trackEnvelope --- examples/Envelope/run.sh | 25 +- examples/Envelope/sns_linac/test_sns_linac.py | 140 +++++---- examples/Envelope/sns_ring/test_sns_ring.py | 11 +- .../Envelope/sns_ring/test_sns_ring_speed.py | 11 +- examples/Envelope/test_env_2d_fodo.py | 14 +- examples/Envelope/test_env_2d_fodo_speed.py | 5 +- examples/Envelope/test_env_3d_drift.py | 16 +- py/orbit/envelope/__init__.py | 1 - py/orbit/envelope/envelope.py | 1 + py/orbit/envelope/meson.build | 1 - py/orbit/envelope/track.py | 295 ------------------ py/orbit/lattice/AccLattice.py | 287 ++++++++++++++++- tests/py/orbit/test_env.py | 17 +- 13 files changed, 421 insertions(+), 403 deletions(-) delete mode 100644 py/orbit/envelope/track.py diff --git a/examples/Envelope/run.sh b/examples/Envelope/run.sh index 98cf808c..31054736 100755 --- a/examples/Envelope/run.sh +++ b/examples/Envelope/run.sh @@ -2,15 +2,28 @@ set -x -python test_env_2d_fodo.py -python test_env_2d_fodo_speed.py -python test_env_3d_drift.py +python test_env_2d_fodo.py --sc 0 +python test_env_2d_fodo.py --sc 1 +python test_env_2d_fodo.py --sc 1 --offset-x 0.001 +python test_env_2d_fodo.py --sc 1 --tilt 45.0 +python test_env_2d_fodo_speed.py --sc 0 +python test_env_2d_fodo_speed.py --sc 1 +python test_env_3d_drift.py --sc 0 +python test_env_3d_drift.py --sc 1 +python test_env_3d_drift.py --sc 1 --rms-y 0.002 --tilt-z 45.0 +python test_env_3d_drift.py --sc 1 --rms-z 0.002 --tilt-x 45.0 cd sns_linac -python test_sns_linac.py +python test_sns_linac.py --sc 0 +python test_sns_linac.py --sc 1 --dist gauss +python test_sns_linac.py --sc 1 --dist waterbag +python test_sns_linac.py --sc 1 --dist kv cd .. cd sns_ring -python test_sns_ring.py -python test_sns_ring_speed.py +python test_sns_ring.py --sc 0 +python test_sns_ring.py --sc 1 +python test_sns_ring.py --sc 1 --tilt 45.0 +python test_sns_ring_speed.py --sc 0 +python test_sns_ring_speed.py --sc 1 cd .. diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index d057a77f..ee644659 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -11,8 +11,10 @@ import argparse import math import os +import pathlib import random import sys +import time import numpy as np import matplotlib.pyplot as plt @@ -30,7 +32,6 @@ from orbit.bunch_generators import KVDist3D from orbit.bunch_utils import collect_bunch from orbit.envelope import Envelope -from orbit.envelope import EnvelopeTracker from orbit.lattice import AccLattice from orbit.lattice import AccNode from orbit.lattice import AccActionsContainer @@ -66,16 +67,47 @@ def parse_args() -> argparse.Namespace: return parser.parse_args() -def main(args: argparse.Namespace) -> None: +def make_lattice(args: argparse.Namespace) -> LinacAccLattice: + seq_names = [ + "MEBT", + "DTL1", + "DTL2", + "DTL3", + "DTL4", + "DTL5", + "DTL6", + "CCL1", + "CCL2", + "CCL3", + "CCL4", + "SCLMed", + "SCLHigh", + "HEBT1", + "HEBT2", + ] + if args.seq_stop: + index = seq_names.index(args.seq_stop) + 1 + seq_names = seq_names[:index] - output_dir = "outputs" - os.makedirs(output_dir, exist_ok=True) + sns_linac_factory = SNS_LinacLatticeFactory() + sns_linac_factory.setMaxDriftLength(args.sc_path_length_min) + lattice = sns_linac_factory.getLinacAccLattice(seq_names, "inputs/sns_linac.xml") - random.seed(23) + for node in lattice.getNodes(): + try: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + except: + pass + + rf_gaps = lattice.getRF_Gaps() + for rf_gap in rf_gaps: + rf_gap.setCppGapModel(MatrixRfGap()) + + return lattice - # Bunch - # -------------------------------------------------------------------------------- +def make_bunch(args: argparse.Namespace) -> Bunch: kin_energy = 0.0025 # [GeV] mass = mass_proton + 2.0 * mass_electron frequency = 402.5e06 @@ -110,72 +142,64 @@ def main(args: argparse.Namespace) -> None: for _ in range(args.nparts): bunch.addParticle(*dist.getCoordinates()) + return bunch - # Lattice - # -------------------------------------------------------------------------------- - seq_names = [ - "MEBT", - "DTL1", - "DTL2", - "DTL3", - "DTL4", - "DTL5", - "DTL6", - "CCL1", - "CCL2", - "CCL3", - "CCL4", - "SCLMed", - "SCLHigh", - "HEBT1", - "HEBT2", - ] - if args.seq_stop: - index = seq_names.index(args.seq_stop) + 1 - seq_names = seq_names[:index] +def get_bunch_cov_matrix(bunch: Bunch) -> Bunch: + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) - sns_linac_factory = SNS_LinacLatticeFactory() - sns_linac_factory.setMaxDriftLength(args.sc_path_length_min) - lattice = sns_linac_factory.getLinacAccLattice(seq_names, "inputs/sns_linac.xml") + cov_matrix = np.zeros((6, 6)) + for i in range(6): + for j in range(6): + cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) + return cov_matrix - for node in lattice.getNodes(): - try: - node.setUsageFringeFieldIN(False) - node.setUsageFringeFieldOUT(False) - except: - pass - rf_gaps = lattice.getRF_Gaps() - for rf_gap in rf_gaps: - rf_gap.setCppGapModel(MatrixRfGap()) +def get_bunch_centroid(bunch: Bunch) -> Bunch: + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) - for index, node in enumerate(lattice.getNodes()): - print(index, type(node), node.getName()) + centroid = np.zeros(6) + for i in range(6): + centroid[i] = twiss_calc.getAverage(i) + return centroid - lattice.trackDesignBunch(bunch) - # Track envelope - # -------------------------------------------------------------------------------- +def make_envelope(bunch: Bunch) -> Envelope: + sync_part = bunch.getSyncParticle() + cov_matrix = get_bunch_cov_matrix(bunch) + centroid = get_bunch_centroid(bunch) + intensity = bunch.getSize() + return Envelope( + sync_part, + cov_matrix=cov_matrix, + centroid=centroid, + intensity=intensity + ) - twiss_calc = BunchTwissAnalysis() - twiss_calc.analyzeBunch(bunch) - cov_matrix = np.zeros((6, 6)) - for i in range(6): - for j in range(6): - cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) +def main(args: argparse.Namespace) -> None: + + path = pathlib.Path(__file__) + output_dir = os.path.join("outputs", path.stem, time.strftime("%Y%m%d_%H%M%S")) + os.makedirs(output_dir, exist_ok=True) - envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix, intensity=intensity) + random.seed(23) + + # Track envelope + bunch = make_bunch(args) + envelope = make_envelope(bunch) - tracker = EnvelopeTracker(lattice, sc=("3d" if args.sc else None)) + lattice = make_lattice(args) + lattice.trackDesignBunch(bunch) histories = {} - histories["envelope"] = tracker.track_history(envelope) + histories["envelope"] = lattice.trackEnvelopeHistory(envelope) # Track bunch - # -------------------------------------------------------------------------------- - + bunch = make_bunch(args) + lattice = make_lattice(args) lattice.trackDesignBunch(bunch) if args.sc: @@ -293,4 +317,4 @@ def main(args: argparse.Namespace) -> None: if __name__ == "__main__": - main(parse_args()) + main(parse_args()) \ No newline at end of file diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring/test_sns_ring.py index 7518c4e4..3fafa636 100644 --- a/examples/Envelope/sns_ring/test_sns_ring.py +++ b/examples/Envelope/sns_ring/test_sns_ring.py @@ -5,8 +5,8 @@ import math import os import pathlib -import time import sys +import time import numpy as np import matplotlib.pyplot as plt @@ -16,12 +16,12 @@ from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.bunch_utils import collect_bunch from orbit.envelope import Envelope -from orbit.envelope import EnvelopeTracker from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.space_charge.sc2p5d import setSC2p5DAccNodes from orbit.teapot import TEAPOT_Ring from orbit.teapot import TEAPOT_MATRIX_Lattice from orbit.teapot import teapot +from orbit.teapot import BendTEAPOT from orbit.utils.consts import mass_proton sys.path.append("..") @@ -65,7 +65,7 @@ def parse_args() -> argparse.Namespace: def main(args: argparse.Namespace) -> None: path = pathlib.Path(__file__) - output_dir = os.path.join("outputs", path.stem) + output_dir = os.path.join("outputs", path.stem, time.strftime("%Y%m%d_%H%M%S")) os.makedirs(output_dir, exist_ok=True) # Lattice @@ -122,7 +122,7 @@ def main(args: argparse.Namespace) -> None: if args.tilt: rot_matrix = np.identity(6) - rot_matrix[:4, :4] = build_rotation_matrix_xy(angle=(args.tilt * math.pi)) + 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]) if args.mismatch_x or args.mismatch_y: @@ -162,7 +162,6 @@ def main(args: argparse.Namespace) -> None: centroid=centroid_init, intensity=args.intensity, ) - tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) history_keys = [ "rms_x", @@ -178,7 +177,7 @@ def main(args: argparse.Namespace) -> None: for turn in range(args.turns + 1): if turn > 0: - tracker.track_ring(envelope) + lattice.trackEnvelopeRing(envelope, sc=("2d" if args.sc else None)) cov_matrix = envelope.cov_matrix centroid = envelope.centroid diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring/test_sns_ring_speed.py index 8ce6a63c..124d3f75 100644 --- a/examples/Envelope/sns_ring/test_sns_ring_speed.py +++ b/examples/Envelope/sns_ring/test_sns_ring_speed.py @@ -12,11 +12,11 @@ from orbit.core.bunch import Bunch from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.envelope import Envelope -from orbit.envelope import EnvelopeTracker from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.space_charge.sc2p5d import setSC2p5DAccNodes from orbit.teapot import TEAPOT_Ring from orbit.teapot import TEAPOT_MATRIX_Lattice +from orbit.teapot import BendTEAPOT from orbit.utils.consts import mass_proton sys.path.append("..") @@ -45,6 +45,11 @@ except: pass +for node in lattice.getNodes(): + if type(node) is BendTEAPOT: + node.setParam("ea1", 0.0) + node.setParam("ea2", 0.0) + for node in lattice.getNodes(): max_length = 1.0 if node.getLength() > max_length: @@ -84,7 +89,7 @@ cov_matrix=cov_matrix_init, intensity=args.intensity, ) -tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) +envelope_sc = "2d" if args.sc else None start_time = time.time() @@ -92,7 +97,7 @@ profiler.enable() for turn in trange(args.turns): - tracker.track_ring(envelope) + lattice.trackEnvelopeRing(envelope, sc=envelope_sc) time_per_turn = (time.time() - start_time) / args.turns diff --git a/examples/Envelope/test_env_2d_fodo.py b/examples/Envelope/test_env_2d_fodo.py index 0a4079ac..969e99ff 100644 --- a/examples/Envelope/test_env_2d_fodo.py +++ b/examples/Envelope/test_env_2d_fodo.py @@ -5,6 +5,7 @@ import math import os import pathlib +import time import numpy as np import matplotlib.pyplot as plt @@ -14,7 +15,6 @@ from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.bunch_utils import collect_bunch from orbit.envelope import Envelope -from orbit.envelope import EnvelopeTracker from orbit.lattice import AccLattice from orbit.lattice import AccNode from orbit.core.spacecharge import SpaceChargeCalc2p5D @@ -59,12 +59,8 @@ def parse_args() -> argparse.Namespace: def main(args: argparse.Namespace) -> None: - - # Setup - # ------------------------------------------------------------------------------ - path = pathlib.Path(__file__) - output_dir = os.path.join("outputs", path.stem) + output_dir = os.path.join("outputs", path.stem, time.strftime("%Y%m%d_%H%M%S")) os.makedirs(output_dir, exist_ok=True) # Create lattice @@ -120,7 +116,7 @@ def main(args: argparse.Namespace) -> None: # Tilt if args.tilt: rot_matrix = np.identity(6) - rot_matrix[:4, :4] = build_rotation_matrix_xy(angle=(args.tilt * math.pi)) + 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 @@ -146,12 +142,12 @@ def main(args: argparse.Namespace) -> None: print("TRACK ENVELOPE") - tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) + envelope_sc = "2d" if args.sc else None history = {"xrms": [], "yrms": [], "xavg": [], "yavg": []} for turn in range(args.turns): if turn > 0: - tracker.track_ring(envelope) + lattice.trackEnvelopeRing(envelope, sc=envelope_sc) cov_matrix = envelope.cov_matrix centroid = envelope.centroid diff --git a/examples/Envelope/test_env_2d_fodo_speed.py b/examples/Envelope/test_env_2d_fodo_speed.py index 6882c210..e1fb5f12 100644 --- a/examples/Envelope/test_env_2d_fodo_speed.py +++ b/examples/Envelope/test_env_2d_fodo_speed.py @@ -11,7 +11,6 @@ from orbit.core.bunch import Bunch from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.envelope import Envelope -from orbit.envelope import EnvelopeTracker from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.space_charge.sc2p5d import setSC2p5DAccNodes from orbit.teapot import QuadTEAPOT @@ -86,7 +85,7 @@ cov_matrix=cov_matrix_init, intensity=args.intensity, ) -tracker = EnvelopeTracker(lattice, sc=("2d" if args.sc else None)) +envelope_sc = "2d" if args.sc else None start_time = time.time() @@ -94,7 +93,7 @@ profiler.enable() for turn in trange(args.turns): - tracker.track_ring(envelope) + lattice.trackEnvelopeRing(envelope, sc=envelope_sc) time_per_turn = (time.time() - start_time) / args.turns diff --git a/examples/Envelope/test_env_3d_drift.py b/examples/Envelope/test_env_3d_drift.py index c4ec8107..992ec27d 100644 --- a/examples/Envelope/test_env_3d_drift.py +++ b/examples/Envelope/test_env_3d_drift.py @@ -9,6 +9,7 @@ import math import os import pathlib +import time import numpy as np import matplotlib.pyplot as plt @@ -19,7 +20,6 @@ from orbit.core.spacecharge import SpaceChargeCalc3D from orbit.bunch_utils import collect_bunch from orbit.envelope import Envelope -from orbit.envelope import EnvelopeTracker from orbit.space_charge.sc3d import setSC3DAccNodes from orbit.teapot import DriftTEAPOT from orbit.teapot import TEAPOT_Lattice @@ -42,9 +42,9 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--rms-y", type=float, default=0.010) parser.add_argument("--rms-z", type=float, default=0.010) - parser.add_argument("--rot-x", type=float, default=0.0) - parser.add_argument("--rot-y", type=float, default=0.0) - parser.add_argument("--rot-z", type=float, default=0.0) + parser.add_argument("--tilt-x", type=float, default=0.0) + parser.add_argument("--tilt-y", type=float, default=0.0) + parser.add_argument("--tilt-z", type=float, default=0.0) parser.add_argument("--nslice", type=int, default=10) parser.add_argument("--length", type=float, default=0.1) @@ -74,7 +74,7 @@ def build_cov_matrix_xyz( def main(args: argparse.Namespace) -> None: path = pathlib.Path(__file__) - output_dir = os.path.join("outputs", path.stem) + output_dir = os.path.join("outputs", path.stem, time.strftime("%Y%m%d_%H%M%S")) os.makedirs(output_dir, exist_ok=True) # Create lattice @@ -99,7 +99,7 @@ def main(args: argparse.Namespace) -> None: cov_matrix_init = np.zeros((6, 6)) rotation_matrix = rotation_matrix_3d( - math.radians(args.rot_x), math.radians(args.rot_y), math.radians(args.rot_z) + math.radians(args.tilt_x), math.radians(args.tilt_y), math.radians(args.tilt_z) ) print(rotation_matrix) @@ -131,12 +131,12 @@ def main(args: argparse.Namespace) -> None: print("TRACK ENVELOPE") - tracker = EnvelopeTracker(lattice, sc=("3d" if args.sc else None)) + envelope_sc = "3d" if args.sc else None history = {"xrms": [], "yrms": [], "zrms": []} for turn in range(args.turns): if turn > 0: - tracker.track(envelope) + lattice.trackEnvelope(envelope, sc=envelope_sc) cov_matrix = envelope.cov_matrix diff --git a/py/orbit/envelope/__init__.py b/py/orbit/envelope/__init__.py index 7a4586ae..e2a3e379 100644 --- a/py/orbit/envelope/__init__.py +++ b/py/orbit/envelope/__init__.py @@ -1,2 +1 @@ from .envelope import Envelope -from .track import EnvelopeTracker \ No newline at end of file diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index 6c4e962c..0379818b 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -4,6 +4,7 @@ import scipy.constants import scipy.special +from orbit.core.bunch import Bunch from orbit.core.bunch import SyncParticle from orbit.utils.matrix import convert_matrix_zp_to_dE diff --git a/py/orbit/envelope/meson.build b/py/orbit/envelope/meson.build index 9be34b6b..1e9fe35c 100644 --- a/py/orbit/envelope/meson.build +++ b/py/orbit/envelope/meson.build @@ -1,7 +1,6 @@ py_sources = files([ '__init__.py', 'envelope.py', - 'track.py', 'utils.py' ]) diff --git a/py/orbit/envelope/track.py b/py/orbit/envelope/track.py deleted file mode 100644 index 0ccc4844..00000000 --- a/py/orbit/envelope/track.py +++ /dev/null @@ -1,295 +0,0 @@ -import numpy as np -import warnings - -from orbit.core.bunch import Bunch -from orbit.core.bunch import SyncParticle - -from orbit.lattice import AccNode -from orbit.lattice import AccLattice -from orbit.teapot import BendTEAPOT -from orbit.py_linac.lattice import Bend as BendLINAC - -from .envelope import Envelope - - -ENTRANCE = AccNode.ENTRANCE -BODY = AccNode.BODY -EXIT = AccNode.EXIT - -BEFORE = AccNode.BEFORE -AFTER = AccNode.AFTER - - -class EnvelopeTracker: - def __init__(self, lattice: AccLattice, sc: str | None = None) -> None: - """Constructor. - - Args: - lattice: The accelerator lattice. - sc: Envelope space charge model {"2d", "3d", None}. - """ - self.lattice = lattice - self.sc = sc - - # For pre-computing elements - self.elements = [] - self.one_turn_matrix = None - - for node in self.lattice.getNodes(): - if type(node) in (BendTEAPOT, BendLINAC): - if node.getParam("ea1") != 0.0 or node.getParam("ea2") != 0.0: - message = f"Found bend ea1 or ea2 != 0.0 ({node.getName()}.)" - message += " Nonzero edge angles are not yet supported in envelope tracking." - message += " Setting ea1 and ea2 to 0.0." - warnings.warn(message) - - node.setParam("ea1", 0.0) - node.setParam("ea2", 0.0) - - def track(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> None: - """Track envelope through lattice. - - This is not recursive, so grandchild nodes are not tracked. - """ - nodes = self.lattice.getNodes() - nodes = nodes[index_start : index_stop] - - sync_part = envelope.sync_part - - for node_index, node in enumerate(nodes): - for child_node in node.getChildNodes(ENTRANCE): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - envelope.transform(matrix) - - for part_index in range(node.getnParts()): - for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - envelope.transform(matrix) - - matrix_sc = None - if self.sc: - length = node.getLength(part_index) - if length > 0: - if self.sc == "2d": - matrix_sc = envelope.sc_matrix_2d(length) - elif self.sc == "3d": - matrix_sc = envelope.sc_matrix_3d(length) - else: - raise ValueError - - matrix = node.getMatrix(sync_part, part_index=part_index) - if matrix is not None: - if matrix_sc is not None: - matrix = matrix @ matrix_sc - envelope.transform(matrix) - - for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - envelope.transform(matrix) - - for child_node in node.getChildNodes(EXIT): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - envelope.transform(matrix) - - def track_history(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> dict[str, list]: - """Track and return envelope parameters vs. position in lattice.""" - history_keys = [ - "s", - "kin_energy", - "gamma", - "beta", - "mean", - "cov", - "rms_x", - "rms_y", - "rms_z", - "eps_x", - "eps_y", - ] - history = {key: [] for key in history_keys} - - def observe(envelope: Envelope) -> None: - parameters = {} - parameters["gamma"] = envelope.gamma - parameters["beta"] = envelope.beta - parameters["kin_energy"] = envelope.kin_energy - parameters["mean"] = envelope.centroid.copy() - parameters["cov"] = envelope.cov_matrix.copy() - parameters["rms_x"] = np.sqrt(parameters["cov"][0, 0]) - parameters["rms_y"] = np.sqrt(parameters["cov"][2, 2]) - parameters["rms_z"] = np.sqrt(parameters["cov"][4, 4]) - return parameters - - def update_history(envelope: Envelope, position: float) -> None: - history["s"].append(position) - parameters = observe(envelope) - for key in parameters: - history[key].append(parameters[key]) - - path_length = 0.0 - update_history(envelope, path_length) - - nodes = self.lattice.getNodes() - nodes = nodes[index_start : index_stop] - - sync_part = envelope.sync_part - - for node_index, node in enumerate(nodes): - for child_node in node.getChildNodes(ENTRANCE): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - envelope.transform(matrix) - - for part_index in range(node.getnParts()): - for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - envelope.transform(matrix) - - matrix_sc = None - if self.sc: - length = node.getLength(part_index) - if length > 0: - if self.sc == "2d": - matrix_sc = envelope.sc_matrix_2d(length) - elif self.sc == "3d": - matrix_sc = envelope.sc_matrix_3d(length) - else: - raise ValueError - - matrix = node.getMatrix(sync_part, part_index=part_index) - if matrix is not None: - if matrix_sc is not None: - matrix = matrix @ matrix_sc - envelope.transform(matrix) - - path_length += node.getLength(part_index) - update_history(envelope, path_length) - - for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - envelope.transform(matrix) - - for child_node in node.getChildNodes(EXIT): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - envelope.transform(matrix) - - return history - - def precompute_matrices(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> None: - """Pre-compute transfer matrices for each node. - - For each node, return tuple (node, matrix). Mark space charge kicks as ("sc", length). - """ - nodes = self.lattice.getNodes() - nodes = nodes[index_start : index_stop] - - sync_part = envelope.sync_part - - self.elements = [] - for node_index, node in enumerate(nodes): - for child_node in node.getChildNodes(ENTRANCE): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - self.elements.append((child_node, matrix)) - - for part_index in range(node.getnParts()): - for child_node in node.getChildNodes(BODY, part_index, place_in_part=BEFORE): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - self.elements.append((child_node, matrix)) - - if self.sc: - length = node.getLength(part_index) - if length > 0: - self.elements.append(("sc", length)) - - matrix = node.getMatrix(sync_part, part_index=part_index) - if matrix is not None: - self.elements.append((node, matrix)) - - for child_node in node.getChildNodes(BODY, part_index, place_in_part=AFTER): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - self.elements.append((node, matrix)) - - for child_node in node.getChildNodes(EXIT): - matrix = child_node.getMatrix(sync_part) - if matrix is not None: - self.elements.append((node, matrix)) - - def track_ring(self, envelope: Envelope) -> None: - """Track using pre-computed transfer matrices. - - The method assumes that all nodes are static and that there is no - change in the synchronous particle energy. In this case the matrices - can be computed once and reused on each turn. If there is no space charge, - we track using the one-turn matrix. - """ - - # Pre-compute transfer matrices on the first turn. - if not self.elements: - self.precompute_matrices(envelope) - self.one_turn_matrix = None - - # If there is no space charge, apply the one-turn transfer matrix. - if not self.sc: - if self.one_turn_matrix is None: - self.one_turn_matrix = np.identity(7) - for (node, matrix) in self.elements: - self.one_turn_matrix = matrix @ self.one_turn_matrix - return envelope.transform(self.one_turn_matrix) - - # If there is space charge, apply the matrices one-by-one. - for element in self.elements: - if element[0] == "sc": - length = element[1] - if self.sc == "2d": - envelope.transform(envelope.sc_matrix_2d(length)) - elif self.sc == "3d": - envelope.transform(envelope.sc_matrix_3d(length)) - else: - raise ValueError - else: - node, matrix = element - envelope.transform(matrix) - - def get_transfer_matrix(self, envelope: Envelope, index_start: int = 0, index_stop: int = None) -> np.ndarray: - """Return total transfer matrix (including linear space charge).""" - self.precompute_matrices(envelope, index_start, index_stop) - - if index_stop is None: - index_stop = len(self.elements) - - elements = self.elements[index_start : index_stop] - - if not self.sc: - total_matrix = np.identity(7) - for (node, matrix) in self.elements: - envelope.transform(matrix) - total_matrix = matrix @ total_matrix - return total_matrix - - total_matrix = np.identity(7) - for element in self.elements: - if element[0] == "sc": - length = element[1] - if self.sc == "2d": - matrix = envelope.sc_matrix_2d(length) - elif self.sc == "3d": - matrix = envelope.sc_matrix_3d(length) - else: - raise ValueError - envelope.transform(matrix) - total_matrix = matrix @ total_matrix - else: - node, matrix = element - envelope.transform(matrix) - total_matrix = matrix @ total_matrix - return total_matrix \ No newline at end of file diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index 84a466f8..d7ef944c 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -1,12 +1,19 @@ -import sys +from __future__ import annotations + import os +from typing import TYPE_CHECKING + +import numpy as np from ..utils import orbitFinalize from ..utils import NamedObject from ..utils import TypedObject -from ..lattice import AccActionsContainer -from ..lattice import AccNode +from .AccActionsContainer import AccActionsContainer +from .AccNode import AccNode + +if TYPE_CHECKING: + from orbit.envelope.envelope import Envelope class AccLattice(NamedObject, TypedObject): @@ -31,6 +38,9 @@ def __init__(self, name="no name"): self.__isInitialized = False self.__children = [] self.__childPositions = {} + self.__envelopeElements = [] + self.__envelopeOneTurnMatrix = None + self.__envelopeSpaceCharge = None def initialize(self): """ @@ -261,3 +271,274 @@ def trackActions(self, actionsContainer, paramsDict={}, index_start=-1, index_st paramsDict["node"] = node paramsDict["parentNode"] = self node.trackActions(actionsContainer, paramsDict) + + def _getNodesInRange(self, index_start: int = 0, index_stop: int = None): + if index_stop is None: + index_stop = len(self.__children) - 1 + return self.__children[index_start : index_stop + 1] + + def _prepareEnvelopeTracking(self) -> None: + for node in self.__children: + node_type = type(node) + is_teapot_bend = node_type.__name__ == "BendTEAPOT" and node_type.__module__ == "orbit.teapot.teapot" + is_linac_bend = node_type.__name__ == "Bend" and node_type.__module__ == "orbit.py_linac.lattice.LinacAccNodes" + if is_teapot_bend or is_linac_bend: + if node.getParam("ea1") != 0.0 or node.getParam("ea2") != 0.0: + message = f"Found bend ea1 or ea2 != 0.0 ({node.getName()}.)" + message += " Nonzero edge angles are not yet supported in envelope tracking." + message += " Please set them to zero:" + message += " `node.setParam('ea1', 0.0)`" + message += " `node.setParam('ea2', 0.0)`" + raise RuntimeError(message) + + def _getEnvelopeSpaceChargeMatrix(self, envelope: Envelope, length: float, sc: str | None) -> np.ndarray | None: + if not sc or length <= 0: + return None + if sc == "2d": + return envelope.sc_matrix_2d(length) + if sc == "3d": + return envelope.sc_matrix_3d(length) + raise ValueError(f"Invalid envelope space charge option `{sc}`") + + def setEnvelopeSpaceCharge(self, sc: str | None) -> None: + self.__envelopeSpaceCharge = sc + + def trackEnvelope( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int = None, + sc: str | None = None, + history: bool = False, + ) -> None | dict[str, list]: + """ + Track envelope through lattice. + """ + if history: + return self.trackEnvelopeHistory( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc + ) + + self._prepareEnvelopeTracking() + self.setEnvelopeSpaceCharge(sc) + sync_part = envelope.sync_part + + for node in self._getNodesInRange(index_start, index_stop): + for child_node in node.getChildNodes(AccNode.ENTRANCE): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + envelope.transform(matrix) + + for part_index in range(node.getnParts()): + for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + envelope.transform(matrix) + + matrix_sc = self._getEnvelopeSpaceChargeMatrix(envelope, node.getLength(part_index), sc) + matrix = node.getMatrix(sync_part, part_index=part_index) + if matrix is not None: + if matrix_sc is not None: + matrix = matrix @ matrix_sc + envelope.transform(matrix) + + for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + envelope.transform(matrix) + + for child_node in node.getChildNodes(AccNode.EXIT): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + envelope.transform(matrix) + + def trackEnvelopeHistory( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int = None, + sc: str | None = None, + ) -> dict[str, list]: + """ + Track envelope and return parameters vs. position in lattice. + """ + self._prepareEnvelopeTracking() + self.setEnvelopeSpaceCharge(sc) + sync_part = envelope.sync_part + + history_keys = [ + "s", + "kin_energy", + "gamma", + "beta", + "mean", + "cov", + "rms_x", + "rms_y", + "rms_z", + "eps_x", + "eps_y", + ] + history = {key: [] for key in history_keys} + + def observe(envelope: Envelope) -> dict: + parameters = {} + parameters["gamma"] = envelope.gamma + parameters["beta"] = envelope.beta + parameters["kin_energy"] = envelope.kin_energy + parameters["mean"] = envelope.centroid.copy() + parameters["cov"] = envelope.cov_matrix.copy() + parameters["rms_x"] = np.sqrt(parameters["cov"][0, 0]) + parameters["rms_y"] = np.sqrt(parameters["cov"][2, 2]) + parameters["rms_z"] = np.sqrt(parameters["cov"][4, 4]) + return parameters + + def update_history(envelope: Envelope, position: float) -> None: + history["s"].append(position) + parameters = observe(envelope) + for key in parameters: + history[key].append(parameters[key]) + + path_length = 0.0 + update_history(envelope, path_length) + + for node in self._getNodesInRange(index_start, index_stop): + for child_node in node.getChildNodes(AccNode.ENTRANCE): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + envelope.transform(matrix) + + for part_index in range(node.getnParts()): + for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + envelope.transform(matrix) + + matrix_sc = self._getEnvelopeSpaceChargeMatrix(envelope, node.getLength(part_index), sc) + matrix = node.getMatrix(sync_part, part_index=part_index) + if matrix is not None: + if matrix_sc is not None: + matrix = matrix @ matrix_sc + envelope.transform(matrix) + + path_length += node.getLength(part_index) + update_history(envelope, path_length) + + for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + envelope.transform(matrix) + + for child_node in node.getChildNodes(AccNode.EXIT): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + envelope.transform(matrix) + return history + + def precomputeEnvelopeMatrices( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int = None, + sc: str | None = None, + ) -> list: + """ + Pre-compute transfer matrices for each node. + + For each node, store tuple (node, matrix). Space charge kicks are + stored as ("sc", length). + """ + self._prepareEnvelopeTracking() + sync_part = envelope.sync_part + + self.__envelopeElements = [] + self.__envelopeOneTurnMatrix = None + self.__envelopeSpaceCharge = sc + + for node in self._getNodesInRange(index_start, index_stop): + for child_node in node.getChildNodes(AccNode.ENTRANCE): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + self.__envelopeElements.append((child_node, matrix)) + + for part_index in range(node.getnParts()): + for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + self.__envelopeElements.append((child_node, matrix)) + + if sc: + length = node.getLength(part_index) + if length > 0: + self.__envelopeElements.append(("sc", length)) + + matrix = node.getMatrix(sync_part, part_index=part_index) + if matrix is not None: + self.__envelopeElements.append((node, matrix)) + + for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + self.__envelopeElements.append((node, matrix)) + + for child_node in node.getChildNodes(AccNode.EXIT): + matrix = child_node.getMatrix(sync_part) + if matrix is not None: + self.__envelopeElements.append((node, matrix)) + + return self.__envelopeElements + + def trackEnvelopeRing(self, envelope: Envelope, sc: str | None = None) -> None: + """ + Track using pre-computed transfer matrices. + + The method assumes that all nodes are static and that there is no + change in the synchronous particle energy. In this case the matrices + can be computed once and reused on each turn. If there is no space charge, + we track using the one-turn matrix. + """ + if not self.__envelopeElements or self.__envelopeSpaceCharge != sc: + self.precomputeEnvelopeMatrices(envelope, sc=sc) + + if not sc: + if self.__envelopeOneTurnMatrix is None: + self.__envelopeOneTurnMatrix = np.identity(7) + for node, matrix in self.__envelopeElements: + self.__envelopeOneTurnMatrix = matrix @ self.__envelopeOneTurnMatrix + envelope.transform(self.__envelopeOneTurnMatrix) + return + + for element in self.__envelopeElements: + if element[0] == "sc": + length = element[1] + matrix = self._getEnvelopeSpaceChargeMatrix(envelope, length, sc) + envelope.transform(matrix) + else: + node, matrix = element + envelope.transform(matrix) + + def getEnvelopeTransferMatrix( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int = None, + sc: str | None = None, + ) -> np.ndarray: + """ + Return total transfer matrix, including linear space charge when requested. + """ + elements = self.precomputeEnvelopeMatrices(envelope, index_start, index_stop, sc=sc) + + total_matrix = np.identity(7) + for element in elements: + if element[0] == "sc": + length = element[1] + matrix = self._getEnvelopeSpaceChargeMatrix(envelope, length, sc) + else: + node, matrix = element + envelope.transform(matrix) + total_matrix = matrix @ total_matrix + return total_matrix diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index f4367cb7..647b4855 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -5,7 +5,6 @@ from orbit.core.linac import MatrixRfGap from orbit.bunch_utils import collect_bunch from orbit.envelope import Envelope -from orbit.envelope import EnvelopeTracker from orbit.lattice import AccNode from orbit.lattice import AccLattice from orbit.py_linac.lattice import Drift @@ -82,7 +81,7 @@ def track_and_compare_rms( data[k1] = {} for k2 in ["rms", "cov"]: data[k1][k2] = {} - for k3 in ["env", "bunch"]: + for k3 in ["in", "out"]: data[k1][k2][k3] = {} # Initialize bunch @@ -106,10 +105,9 @@ def track_and_compare_rms( # Track envelope envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix) - envelope_tracker = EnvelopeTracker(lattice=lattice) data["env"]["cov"]["in"] = cov_scale * envelope.cov_matrix - envelope_tracker.track(envelope) + lattice.trackEnvelope(envelope) data["env"]["cov"]["out"] = cov_scale * envelope.cov_matrix # Compare @@ -401,10 +399,9 @@ def test_track_sublattice_no_error(): for _ in range(n): lattice.addNode(DriftTEAPOT(length=0.1)) - tracker = EnvelopeTracker(lattice) for i in range(n): - tracker.track(envelope, index_start=i) - tracker.track(envelope, index_stop=-i) + lattice.trackEnvelope(envelope, index_start=i) + lattice.trackEnvelope(envelope, index_stop=-i) def test_get_total_matrix() -> None: node = DriftTEAPOT(length=2.0, nparts=50) @@ -419,12 +416,12 @@ def test_get_total_matrix() -> None: cov_matrix = make_default_cov_matrix() envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix, intensity=1e7) - tracker = EnvelopeTracker(lattice, sc="2d") + sc = "2d" envelope_out_a = envelope.copy() - tracker.track(envelope_out_a) + lattice.trackEnvelope(envelope_out_a, sc=sc) - matrix = tracker.get_transfer_matrix(envelope.copy()) + matrix = lattice.getEnvelopeTransferMatrix(envelope.copy(), sc=sc) envelope_out_b = envelope.copy() envelope_out_b.transform(matrix) assert np.all(np.isclose(envelope_out_a.cov_matrix, envelope_out_b.cov_matrix)) From 3bdda4d5a61ac8e62ecf9b8b7b2fef3a31aba24b Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 3 Sep 2026 00:54:38 -0400 Subject: [PATCH 13/42] Add to_bunch method and ability to construct Envelope directly from Bunch --- py/orbit/envelope/envelope.py | 53 +++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index 0379818b..95e45d31 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -5,6 +5,7 @@ import scipy.special from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis from orbit.core.bunch import SyncParticle from orbit.utils.matrix import convert_matrix_zp_to_dE @@ -13,6 +14,27 @@ from .utils import proj_cov_matrix +def get_bunch_cov_matrix(bunch: Bunch) -> Bunch: + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) + + cov_matrix = np.zeros((6, 6)) + for i in range(6): + for j in range(6): + cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) + return cov_matrix + + +def get_bunch_centroid(bunch: Bunch) -> Bunch: + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) + + centroid = np.zeros(6) + for i in range(6): + centroid[i] = twiss_calc.getAverage(i) + return centroid + + def build_diag_matrix_from_xyz_eig(eigenvectors: np.ndarray) -> np.ndarray: A = np.eye(7) for i in range(eigenvectors.shape[0]): @@ -35,11 +57,27 @@ class Envelope: def __init__( self, - sync_part: SyncParticle, + sync_part: SyncParticle = None, cov_matrix: np.ndarray = None, centroid: np.ndarray = None, intensity: float = 0.0, + bunch: Bunch = None, ) -> None: + """Constructor. + + Args: + sync_part: Synchronous particle. + cov_matrix: 6 x 6 covariance matrix. + centroid: 6 x 1 centroid vector. + intensity: Total number of particles. + bunch: If provided, the parameters above are calculated from the bunch particles. + """ + + if bunch is not None: + sync_part = bunch.getSyncParticle() + cov_matrix = get_bunch_cov_matrix(bunch) + centroid = get_bunch_centroid(bunch) + intensity = bunch.getSize() * bunch.macroSize() self.sync_part = sync_part @@ -53,7 +91,6 @@ def __init__( self.intensity = intensity self.classical_radius = get_classical_radius(self.charge, self.mass) - self.charge_sign = self.charge / abs(self.charge) # For a uniform one-dimensional distribution over length L, the standard # deviation is L * sqrt(12). This quantity is used to calculate the line @@ -111,6 +148,18 @@ def sample(self, size: int, dist: str = "kv") -> np.ndarray: particles = particles + self.centroid return particles + def to_bunch(self, size: int, dist: str = "gauss") -> Bunch: + bunch = Bunch() + bunch.mass(self.mass) + bunch.charge(self.charge) + bunch.getSyncParticle().kinEnergy(self.kin_energy) + bunch.macroSize(self.intensity / size) + + particles = self.sample(size=size, dist=dist) + for i in range(particles.shape[0]): + bunch.addParticle(*particles[i]) + return bunch + def sc_matrix_2d(self, length: float) -> np.ndarray: centroid = self.centroid cov_matrix = self.cov_matrix From ee26ce2cd760eb06a45249241ad75108d65ec7b1 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 3 Sep 2026 00:55:19 -0400 Subject: [PATCH 14/42] Fix charge sign in transfer matrix generator --- py/orbit/py_linac/lattice/LinacAccNodes.py | 1 - py/orbit/teapot/teapot.py | 3 --- 2 files changed, 4 deletions(-) diff --git a/py/orbit/py_linac/lattice/LinacAccNodes.py b/py/orbit/py_linac/lattice/LinacAccNodes.py index 4186353f..1d4e2a7e 100755 --- a/py/orbit/py_linac/lattice/LinacAccNodes.py +++ b/py/orbit/py_linac/lattice/LinacAccNodes.py @@ -742,7 +742,6 @@ def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray theta = self.getParam("theta") / (nparts - 1) if part_index == 0 or part_index == nparts - 1: theta *= 0.5 - theta *= np.sign(sync_part.charge()) return get_matrix_bend(sync_part, length=length, theta=theta) diff --git a/py/orbit/teapot/teapot.py b/py/orbit/teapot/teapot.py index 1d64ec67..cd216b8d 100644 --- a/py/orbit/teapot/teapot.py +++ b/py/orbit/teapot/teapot.py @@ -1096,7 +1096,6 @@ def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray kq = self.getParam("kq") if self.waveform: kq *= self.waveform.getStrength() - kq *= np.sign(sync_part.charge()) return get_matrix_quad(sync_part, length=length, kq=kq) @@ -1323,7 +1322,6 @@ def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray theta = self.getParam("theta") / (nparts - 1) if part_index == 0 or part_index == nparts - 1: theta *= 0.5 - theta *= np.sign(sync_part.charge()) return get_matrix_bend(sync_part, length=length, theta=theta) @@ -1710,7 +1708,6 @@ def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray return None kq = self.getParam("kq") - kq *= np.sign(sync_part.charge()) if self.waveform: kq *= self.waveform.getStrength() From 2337519a3f159de0718a76cc9adff62ac592f23c Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 3 Sep 2026 00:57:36 -0400 Subject: [PATCH 15/42] Add charge +- in tests --- tests/py/orbit/test_env.py | 259 ++++++++++++++----------------------- 1 file changed, 96 insertions(+), 163 deletions(-) diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index 647b4855..337c18db 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -1,4 +1,5 @@ import numpy as np +import pytest from orbit.core.bunch import Bunch from orbit.core.bunch import BunchTwissAnalysis @@ -63,6 +64,7 @@ def track_and_compare_rms( kin_energy: float, cov_matrix: np.ndarray, nparts: int = 100_000, + charge: float = 1.0, verbose: int = 1, ) -> dict: """Track bunch/envelope and compare rms beam sizes. @@ -87,6 +89,7 @@ def track_and_compare_rms( # Initialize bunch bunch = Bunch() bunch.mass(mass_proton) + bunch.charge(charge) sync_part = bunch.getSyncParticle() sync_part.kinEnergy(kin_energy) @@ -148,196 +151,125 @@ def make_default_cov_matrix( return np.diag(np.square([rms_x, rms_xp, rms_y, rms_yp, rms_z, rms_dE])) -def test_drift_teapot( - kin_energy: float = 0.0025, - length: float = 1.0, - cov_matrix: np.ndarray = None, - nparts: int = 6, -) -> None: - node = DriftTEAPOT(length=length, nparts=nparts) +def test_drift_teapot(): + node = DriftTEAPOT(length=1.0, nparts=6) lattice = make_lattice([node]) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) -def test_drift_linac( - kin_energy: float = 0.0025, - length: float = 1.0, - cov_matrix: np.ndarray = None, - nparts: int = 6, -) -> None: +def test_drift_linac(): node = Drift() - node.setLength(length) - node.setnParts(nparts) + node.setLength(1.0) + node.setnParts(6) nodes = [node] lattice = make_lattice(nodes) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) - - -def test_quad_teapot( - kin_energy: float = 0.0025, - length: float = 1.0, - kq: float = 1.0, - cov_matrix: np.ndarray = None, - nparts: int = 10, -) -> None: - node = QuadTEAPOT(length=length, kq=kq, nparts=nparts) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_quad_teapot(charge: float): + node = QuadTEAPOT(length=1.0, kq=1.0, nparts=10) lattice = make_lattice([node]) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) - - -def test_cf_teapot( - kin_energy: float = 0.0025, - length: float = 10.0, - kq: float = 1.0, - nparts: int = 10, -) -> None: - node = ContinuousLinearFocusingTEAPOT(length=length, kq=kq, nparts=nparts) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_cf_teapot(charge: float): + node = ContinuousLinearFocusingTEAPOT(length=10.0, kq=1.0, nparts=10) lattice = make_lattice([node]) - cov_matrix = np.diag(np.square([1e-3, 0, 1e-3, 0.0, 0.0, 0.0])) - track_and_compare_rms(lattice, kin_energy, cov_matrix) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) -def test_quad_linac( - kin_energy: float = 0.0025, - length: float = 1.0, - field_grad: float = 0.23, - cov_matrix: np.ndarray = None, - nparts: int = 10, -) -> None: +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_quad_linac(charge: float): node = Quad() - node.setLength(length) - node.setnParts(nparts) - node.setParam("dB/dr", field_grad) + node.setLength(1.0) + node.setnParts(10) + node.setParam("dB/dr", 0.23) nodes = [node] lattice = make_lattice(nodes) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) - - -def test_bend_teapot( - kin_energy: float = 0.0025, - length: float = 1.0, - theta: float = 20.0, - cov_matrix: np.ndarray = None, - nparts: int = 5, -) -> None: - node = BendTEAPOT(length=length, theta=np.radians(theta), nparts=nparts) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_bend_teapot(charge: float): + node = BendTEAPOT(length=1.0, theta=np.radians(20.0), nparts=5) lattice = make_lattice([node]) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) - - -def test_bend_linac( - kin_energy: float = 0.0025, - length: float = 1.0, - theta: float = 20.0, - cov_matrix: np.ndarray = None, - nparts: int = 5, -) -> None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_bend_linac(charge: float): node = Bend() - node.setLength(length) - node.setnParts(nparts) - node.setParam("theta", np.radians(theta)) + node.setLength(1.0) + node.setnParts(5) + node.setParam("theta", np.radians(20.0)) nodes = [node] lattice = make_lattice(nodes) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) - - -def test_kick_teapot( - kin_energy: float = 0.0025, - length: float = 0.1, - kx: float = 0.001, - ky: float = 0.001, - dE: float = 0.00001, - cov_matrix: np.ndarray = None, - nparts: int = 4, -) -> None: - node = KickTEAPOT(kx=kx, ky=ky, dE=dE, length=length, nparts=nparts) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_kick_teapot(charge: float): + node = KickTEAPOT(kx=0.001, ky=0.001, dE=0.00001, length=0.1, nparts=4) lattice = make_lattice([node]) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) -def test_tilt_teapot( - kin_energy: float = 0.0025, - angle: float = 0.25 * np.pi, - cov_matrix: np.ndarray = None, -) -> None: - node = TiltTEAPOT(angle=angle) +def test_tilt_teapot(): + node = TiltTEAPOT(angle=(0.25 * np.pi)) lattice = make_lattice([node]) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) -def test_tilt_linac( - kin_energy: float = 0.0025, - angle: float = 0.25 * np.pi, - cov_matrix: np.ndarray = None, -) -> None: +def test_tilt_linac(): node = TiltElement() - node.setTiltAngle(angle) - nodes = [node] - lattice = make_lattice(nodes) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) - - -def test_solenoid_teapot( - kin_energy: float = 0.0025, - length: float = 2.0, - B: float = 1.0, - cov_matrix: np.ndarray = None, - nparts: int = 10, -) -> None: - node = SolenoidTEAPOT(length=length, B=B, nparts=nparts) + node.setTiltAngle(0.25 * np.pi) lattice = make_lattice([node]) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) - - -def test_solenoid_linac( - kin_energy: float = 0.0025, - length: float = 2.0, - B: float = 1.0, - cov_matrix: np.ndarray = None, - nparts: int = 10, -) -> None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_solenoid_teapot(charge: float): + node = SolenoidTEAPOT(length=2.0, B=1.0, nparts=10) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_solenoid_linac(charge: float): node = Solenoid() - node.setLength(length) - node.setnParts(nparts) - node.setParam("B", B) + node.setLength(2.0) + node.setnParts(10) + node.setParam("B", 1.0) nodes = [node] lattice = make_lattice(nodes) - if cov_matrix is None: - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy, cov_matrix) - - -def test_rf_gap_matrix( - kin_energy: float = 0.0025, - frequency: float = 402.5e06, - E0TL: float = 0.001, - phase: float = 0.0, - charge: float = -1.0, -) -> None: + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_rf_gap_matrix(charge: float): + kin_energy = 0.0025 + frequency = 402.5e06 + E0TL = 0.001 + phase = 0.0 + cov_matrix = make_default_cov_matrix() bunch_in = Bunch() @@ -403,12 +335,15 @@ def test_track_sublattice_no_error(): lattice.trackEnvelope(envelope, index_start=i) lattice.trackEnvelope(envelope, index_stop=-i) -def test_get_total_matrix() -> None: + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_get_total_matrix(charge: float) -> None: node = DriftTEAPOT(length=2.0, nparts=50) lattice = make_lattice([node]) bunch = Bunch() bunch.mass(mass_proton) + bunch.charge(charge) sync_part = bunch.getSyncParticle() sync_part.kinEnergy(0.001) @@ -416,12 +351,10 @@ def test_get_total_matrix() -> None: cov_matrix = make_default_cov_matrix() envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix, intensity=1e7) - sc = "2d" - envelope_out_a = envelope.copy() - lattice.trackEnvelope(envelope_out_a, sc=sc) + lattice.trackEnvelope(envelope_out_a, sc="2d") - matrix = lattice.getEnvelopeTransferMatrix(envelope.copy(), sc=sc) + matrix = lattice.getEnvelopeTransferMatrix(envelope.copy(), sc="2d") envelope_out_b = envelope.copy() envelope_out_b.transform(matrix) assert np.all(np.isclose(envelope_out_a.cov_matrix, envelope_out_b.cov_matrix)) From 9dcb25bfcbbf0fc2ec2d77e2f14fe88d83d53b21 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 3 Sep 2026 00:58:09 -0400 Subject: [PATCH 16/42] Construct envelope directly from bunch in sns linac example --- examples/Envelope/run.sh | 4 +- examples/Envelope/sns_linac/test_sns_linac.py | 44 +++---------------- 2 files changed, 9 insertions(+), 39 deletions(-) diff --git a/examples/Envelope/run.sh b/examples/Envelope/run.sh index 31054736..078af457 100755 --- a/examples/Envelope/run.sh +++ b/examples/Envelope/run.sh @@ -15,9 +15,9 @@ python test_env_3d_drift.py --sc 1 --rms-z 0.002 --tilt-x 45.0 cd sns_linac python test_sns_linac.py --sc 0 -python test_sns_linac.py --sc 1 --dist gauss -python test_sns_linac.py --sc 1 --dist waterbag python test_sns_linac.py --sc 1 --dist kv +python test_sns_linac.py --sc 1 --dist waterbag +python test_sns_linac.py --sc 1 --dist gauss cd .. cd sns_ring diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index ee644659..11cccdd9 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -145,40 +145,6 @@ def make_bunch(args: argparse.Namespace) -> Bunch: return bunch -def get_bunch_cov_matrix(bunch: Bunch) -> Bunch: - twiss_calc = BunchTwissAnalysis() - twiss_calc.analyzeBunch(bunch) - - cov_matrix = np.zeros((6, 6)) - for i in range(6): - for j in range(6): - cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) - return cov_matrix - - -def get_bunch_centroid(bunch: Bunch) -> Bunch: - twiss_calc = BunchTwissAnalysis() - twiss_calc.analyzeBunch(bunch) - - centroid = np.zeros(6) - for i in range(6): - centroid[i] = twiss_calc.getAverage(i) - return centroid - - -def make_envelope(bunch: Bunch) -> Envelope: - sync_part = bunch.getSyncParticle() - cov_matrix = get_bunch_cov_matrix(bunch) - centroid = get_bunch_centroid(bunch) - intensity = bunch.getSize() - return Envelope( - sync_part, - cov_matrix=cov_matrix, - centroid=centroid, - intensity=intensity - ) - - def main(args: argparse.Namespace) -> None: path = pathlib.Path(__file__) @@ -189,13 +155,17 @@ def main(args: argparse.Namespace) -> None: # Track envelope bunch = make_bunch(args) - envelope = make_envelope(bunch) + envelope = Envelope(bunch=bunch) lattice = make_lattice(args) lattice.trackDesignBunch(bunch) histories = {} - histories["envelope"] = lattice.trackEnvelopeHistory(envelope) + histories["envelope"] = lattice.trackEnvelope( + envelope, + history=True, + sc=("3d" if args.sc else None) + ) # Track bunch bunch = make_bunch(args) @@ -317,4 +287,4 @@ def main(args: argparse.Namespace) -> None: if __name__ == "__main__": - main(parse_args()) \ No newline at end of file + main(parse_args()) From f0ceffe62703fa1f63c929e77a225869c2c90f29 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 3 Sep 2026 01:08:26 -0400 Subject: [PATCH 17/42] Fix return types and copy cov/centroid when copying envelope --- py/orbit/envelope/envelope.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index 95e45d31..3aeab4a9 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -1,5 +1,3 @@ -from multiprocessing.sharedctypes import Synchronized - import numpy as np import scipy.constants import scipy.special @@ -14,7 +12,7 @@ from .utils import proj_cov_matrix -def get_bunch_cov_matrix(bunch: Bunch) -> Bunch: +def get_bunch_cov_matrix(bunch: Bunch) -> np.ndarray: twiss_calc = BunchTwissAnalysis() twiss_calc.analyzeBunch(bunch) @@ -25,7 +23,7 @@ def get_bunch_cov_matrix(bunch: Bunch) -> Bunch: return cov_matrix -def get_bunch_centroid(bunch: Bunch) -> Bunch: +def get_bunch_centroid(bunch: Bunch) -> np.ndarray: twiss_calc = BunchTwissAnalysis() twiss_calc.analyzeBunch(bunch) @@ -100,8 +98,8 @@ def __init__( def copy(self): return Envelope( sync_part=self.sync_part, - cov_matrix=self.cov_matrix, - centroid=self.centroid, + cov_matrix=self.cov_matrix.copy(), + centroid=self.centroid.copy(), intensity=self.intensity ) From 171529221180bd4aafe8098cff65d64291312020 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 3 Sep 2026 01:08:50 -0400 Subject: [PATCH 18/42] Fix typo --- py/orbit/lattice/AccLattice.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index d7ef944c..b16da010 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -482,12 +482,12 @@ def precomputeEnvelopeMatrices( for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): matrix = child_node.getMatrix(sync_part) if matrix is not None: - self.__envelopeElements.append((node, matrix)) + self.__envelopeElements.append((child_node, matrix)) for child_node in node.getChildNodes(AccNode.EXIT): matrix = child_node.getMatrix(sync_part) if matrix is not None: - self.__envelopeElements.append((node, matrix)) + self.__envelopeElements.append((child_node, matrix)) return self.__envelopeElements From 523f3f7c6a135dfa54cf512bd0793033ada978f3 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 3 Sep 2026 01:18:33 -0400 Subject: [PATCH 19/42] Change default number of turns in sns ring example --- examples/Envelope/sns_ring/test_sns_ring_speed.py | 1 + examples/Envelope/test_env_2d_fodo_speed.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring/test_sns_ring_speed.py index 124d3f75..ea119c71 100644 --- a/examples/Envelope/sns_ring/test_sns_ring_speed.py +++ b/examples/Envelope/sns_ring/test_sns_ring_speed.py @@ -22,6 +22,7 @@ sys.path.append("..") from utils import gen_dist + parser = argparse.ArgumentParser() parser.add_argument("--bunch-length", type=float, default=120.0) parser.add_argument("--kin-energy", type=float, default=1.300) diff --git a/examples/Envelope/test_env_2d_fodo_speed.py b/examples/Envelope/test_env_2d_fodo_speed.py index e1fb5f12..7462d289 100644 --- a/examples/Envelope/test_env_2d_fodo_speed.py +++ b/examples/Envelope/test_env_2d_fodo_speed.py @@ -30,7 +30,7 @@ parser.add_argument("--kq", type=float, default=0.25) parser.add_argument("--nparts", type=int, default=10_000) -parser.add_argument("--turns", type=int, default=5000) +parser.add_argument("--turns", type=int, default=500) parser.add_argument("--sc", type=int, default=0) parser.add_argument("--sc-grid", type=int, default=64) args = parser.parse_args() From 1f1c7a265f0484686c035862726dcb9ba4b30cdf Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Mon, 21 Sep 2026 16:53:07 -0400 Subject: [PATCH 20/42] Start on including matrix fitting in envelope 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? --- examples/Envelope/sns_ring/test_sns_ring.py | 22 ++- py/orbit/envelope/__init__.py | 2 + py/orbit/envelope/matrix_fitting.py | 114 +++++++++++ py/orbit/envelope/meson.build | 2 +- py/orbit/lattice/AccLattice.py | 202 +++++++++++++++++--- py/orbit/teapot/teapot.py | 46 ++++- tests/py/orbit/test_env.py | 44 +++++ 7 files changed, 392 insertions(+), 40 deletions(-) create mode 100644 py/orbit/envelope/matrix_fitting.py diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring/test_sns_ring.py index 3fafa636..300f0f6d 100644 --- a/examples/Envelope/sns_ring/test_sns_ring.py +++ b/examples/Envelope/sns_ring/test_sns_ring.py @@ -21,7 +21,6 @@ from orbit.teapot import TEAPOT_Ring from orbit.teapot import TEAPOT_MATRIX_Lattice from orbit.teapot import teapot -from orbit.teapot import BendTEAPOT from orbit.utils.consts import mass_proton sys.path.append("..") @@ -57,8 +56,14 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--sc", type=int, default=0) parser.add_argument("--sc-grid", type=int, default=64) + parser.add_argument("--fit-matrices", action="store_true") + parser.add_argument("--fringe", action="store_true") parser.add_argument( - "--handle-unknown", type=str, default=None, choices=["drift", "fit"] + "--handle-unknown", + type=str, + default=None, + choices=["drift", "fit"], + help=argparse.SUPPRESS, ) return parser.parse_args() @@ -77,11 +82,8 @@ def main(args: argparse.Namespace) -> None: for node in lattice.getNodes(): if type(node) != teapot.TurnCounterTEAPOT: - node.setUsageFringeFieldIN(False) - node.setUsageFringeFieldOUT(False) - if type(node) is teapot.BendTEAPOT: - node.setParam("ea1", 0.0) - node.setParam("ea2", 0.0) + node.setUsageFringeFieldIN(args.fringe) + node.setUsageFringeFieldOUT(args.fringe) if args.sol: for name in ["scbdsol_c13a", "scbdsol_c13b"]: @@ -177,7 +179,11 @@ def main(args: argparse.Namespace) -> None: for turn in range(args.turns + 1): if turn > 0: - lattice.trackEnvelopeRing(envelope, sc=("2d" if args.sc else None)) + lattice.trackEnvelopeRing( + envelope, + sc=("2d" if args.sc else None), + fit=(args.fit_matrices or args.handle_unknown == "fit"), + ) cov_matrix = envelope.cov_matrix centroid = envelope.centroid diff --git a/py/orbit/envelope/__init__.py b/py/orbit/envelope/__init__.py index e2a3e379..febf3854 100644 --- a/py/orbit/envelope/__init__.py +++ b/py/orbit/envelope/__init__.py @@ -1 +1,3 @@ from .envelope import Envelope +from .matrix_fitting import fit_transfer_matrix +from .matrix_fitting import orbit_matrix_to_numpy diff --git a/py/orbit/envelope/matrix_fitting.py b/py/orbit/envelope/matrix_fitting.py new file mode 100644 index 00000000..5de882c9 --- /dev/null +++ b/py/orbit/envelope/matrix_fitting.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np + +from orbit.core.bunch import Bunch +from orbit.core.bunch import SyncParticle +from orbit.core.orbit_utils import Matrix +from orbit.core.teapot_base import MatrixGenerator + +if TYPE_CHECKING: + from orbit.lattice import AccLattice + from orbit.lattice import AccNode + + +def orbit_matrix_to_numpy(matrix: Matrix) -> np.ndarray: + """Convert an ORBIT matrix to a NumPy array.""" + matrix_out = np.zeros(matrix.size()) + for i in range(matrix_out.shape[0]): + for j in range(matrix_out.shape[1]): + matrix_out[i, j] = matrix.get(i, j) + return matrix_out + + +def copy_sync_particle(source: SyncParticle, target: SyncParticle) -> None: + """Copy the mutable synchronous-particle state.""" + target.rVector(source.rVector()) + target.pVector(source.pVector()) + target.nxVector(source.nxVector()) + target.time(source.time()) + + +def bunch_from_sync_particle(sync_part: SyncParticle) -> Bunch: + """Create an empty bunch with a copy of a synchronous particle.""" + bunch = Bunch() + bunch.mass(sync_part.mass()) + bunch.charge(sync_part.charge()) + copy_sync_particle(sync_part, bunch.getSyncParticle()) + return bunch + + +def fit_node_transfer_matrix( + node: AccNode, + bunch: Bunch, + part_index: int = -1, + parent_node: AccNode | AccLattice | None = None, + matrix_generator: MatrixGenerator | None = None, + lost_bunch: Bunch | None = None, + params_dict: dict | None = None, +) -> np.ndarray: + """Fit the local linear map of one node operation by particle tracking. + + The input ``bunch`` is used as reusable workspace. Its synchronous particle + advances through the node, which lets a caller fit successive operations at + the correct energy and time. + """ + if matrix_generator is None: + matrix_generator = MatrixGenerator() + if lost_bunch is None: + lost_bunch = Bunch() + bunch.copyEmptyBunchTo(lost_bunch) + + matrix = Matrix(7, 7) + matrix.unit() + matrix_generator.initBunch(bunch) + + params = {} if params_dict is None else params_dict.copy() + params["bunch"] = bunch + params["lostbunch"] = lost_bunch + params["node"] = node + if parent_node is not None: + params["parentNode"] = parent_node + + active_part_index = node.getActivePartIndex() + if part_index >= 0: + node.setActivePartIndex(part_index) + try: + node.track(params) + finally: + node.setActivePartIndex(active_part_index) + + matrix_generator.calculateMatrix(bunch, matrix) + return orbit_matrix_to_numpy(matrix) + + +def fit_transfer_matrix( + lattice: AccLattice, + bunch: Bunch, + index_start: int = 0, + index_stop: int | None = None, +) -> np.ndarray: + """Fit a lattice transfer matrix by tracking finite-difference probes.""" + if index_stop is None: + index_stop = -1 + + matrix = Matrix(7, 7) + matrix.unit() + + bunch_out = Bunch() + lost_bunch = Bunch() + bunch.copyEmptyBunchTo(bunch_out) + bunch.copyEmptyBunchTo(lost_bunch) + + matrix_generator = MatrixGenerator() + matrix_generator.initBunch(bunch_out) + lattice.trackBunch( + bunch_out, + paramsDict={"lostbunch": lost_bunch}, + index_start=index_start, + index_stop=index_stop, + ) + matrix_generator.calculateMatrix(bunch_out, matrix) + return orbit_matrix_to_numpy(matrix) diff --git a/py/orbit/envelope/meson.build b/py/orbit/envelope/meson.build index 1e9fe35c..c5d3846b 100644 --- a/py/orbit/envelope/meson.build +++ b/py/orbit/envelope/meson.build @@ -1,6 +1,7 @@ py_sources = files([ '__init__.py', 'envelope.py', + 'matrix_fitting.py', 'utils.py' ]) @@ -9,4 +10,3 @@ python.install_sources( subdir: 'orbit/envelope', # pure: true, ) - diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index b16da010..78e6c581 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -41,6 +41,7 @@ def __init__(self, name="no name"): self.__envelopeElements = [] self.__envelopeOneTurnMatrix = None self.__envelopeSpaceCharge = None + self.__envelopeFit = False def initialize(self): """ @@ -277,12 +278,25 @@ def _getNodesInRange(self, index_start: int = 0, index_stop: int = None): index_stop = len(self.__children) - 1 return self.__children[index_start : index_stop + 1] - def _prepareEnvelopeTracking(self) -> None: + def _prepareEnvelopeTracking(self, fit: bool = False) -> None: + if fit: + return for node in self.__children: node_type = type(node) is_teapot_bend = node_type.__name__ == "BendTEAPOT" and node_type.__module__ == "orbit.teapot.teapot" is_linac_bend = node_type.__name__ == "Bend" and node_type.__module__ == "orbit.py_linac.lattice.LinacAccNodes" - if is_teapot_bend or is_linac_bend: + if is_teapot_bend: + uses_unsupported_fringe = ( + node.getParam("ea1") != 0.0 and node.getUsageFringeFieldIN() + ) or ( + node.getParam("ea2") != 0.0 and node.getUsageFringeFieldOUT() + ) + if uses_unsupported_fringe: + message = f"Found an enabled fringe field with a nonzero edge angle ({node.getName()})." + message += " Analytic envelope tracking supports the wedge transformations only." + message += " Disable the bend fringe field or use `fit=True`." + raise RuntimeError(message) + if is_linac_bend: if node.getParam("ea1") != 0.0 or node.getParam("ea2") != 0.0: message = f"Found bend ea1 or ea2 != 0.0 ({node.getName()}.)" message += " Nonzero edge angles are not yet supported in envelope tracking." @@ -291,6 +305,52 @@ def _prepareEnvelopeTracking(self) -> None: message += " `node.setParam('ea2', 0.0)`" raise RuntimeError(message) + def _createEnvelopeFitState(self, sync_part): + from orbit.core.bunch import Bunch + from orbit.core.teapot_base import MatrixGenerator + from orbit.envelope.matrix_fitting import bunch_from_sync_particle + + bunch = bunch_from_sync_particle(sync_part) + lost_bunch = Bunch() + bunch.copyEmptyBunchTo(lost_bunch) + params_dict = {} + if hasattr(self, "getUseRealCharge"): + params_dict["useCharge"] = self.getUseRealCharge() + return { + "bunch": bunch, + "lost_bunch": lost_bunch, + "matrix_generator": MatrixGenerator(), + "params_dict": params_dict, + } + + def _getEnvelopeNodeMatrix( + self, + node, + sync_part, + part_index: int | None = None, + parent_node=None, + fit_state: dict | None = None, + ) -> np.ndarray | None: + if fit_state is None: + if part_index is None: + return node.getMatrix(sync_part) + return node.getMatrix(sync_part, part_index=part_index) + + from orbit.envelope.matrix_fitting import copy_sync_particle + from orbit.envelope.matrix_fitting import fit_node_transfer_matrix + + matrix = fit_node_transfer_matrix( + node, + fit_state["bunch"], + part_index=0 if part_index is None else part_index, + parent_node=parent_node, + matrix_generator=fit_state["matrix_generator"], + lost_bunch=fit_state["lost_bunch"], + params_dict=fit_state["params_dict"], + ) + copy_sync_particle(fit_state["bunch"].getSyncParticle(), sync_part) + return matrix + def _getEnvelopeSpaceChargeMatrix(self, envelope: Envelope, length: float, sc: str | None) -> np.ndarray | None: if not sc or length <= 0: return None @@ -310,48 +370,80 @@ def trackEnvelope( index_stop: int = None, sc: str | None = None, history: bool = False, + fit: bool = False, ) -> None | dict[str, list]: """ - Track envelope through lattice. + Track envelope through the lattice. + + If ``fit`` is true, obtain each linear map from tracking probes rather + than from the node's analytic ``getMatrix`` implementation. """ if history: return self.trackEnvelopeHistory( envelope, index_start=index_start, index_stop=index_stop, - sc=sc + sc=sc, + fit=fit, ) - self._prepareEnvelopeTracking() + self._prepareEnvelopeTracking(fit=fit) self.setEnvelopeSpaceCharge(sc) sync_part = envelope.sync_part + fit_state = self._createEnvelopeFitState(sync_part) if fit else None for node in self._getNodesInRange(index_start, index_stop): for child_node in node.getChildNodes(AccNode.ENTRANCE): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: envelope.transform(matrix) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: envelope.transform(matrix) matrix_sc = self._getEnvelopeSpaceChargeMatrix(envelope, node.getLength(part_index), sc) - matrix = node.getMatrix(sync_part, part_index=part_index) + matrix = self._getEnvelopeNodeMatrix( + node, + sync_part, + part_index=part_index, + parent_node=self, + fit_state=fit_state, + ) if matrix is not None: if matrix_sc is not None: matrix = matrix @ matrix_sc envelope.transform(matrix) for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: envelope.transform(matrix) for child_node in node.getChildNodes(AccNode.EXIT): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: envelope.transform(matrix) @@ -361,13 +453,15 @@ def trackEnvelopeHistory( index_start: int = 0, index_stop: int = None, sc: str | None = None, + fit: bool = False, ) -> dict[str, list]: """ Track envelope and return parameters vs. position in lattice. """ - self._prepareEnvelopeTracking() + self._prepareEnvelopeTracking(fit=fit) self.setEnvelopeSpaceCharge(sc) sync_part = envelope.sync_part + fit_state = self._createEnvelopeFitState(sync_part) if fit else None history_keys = [ "s", @@ -407,18 +501,34 @@ def update_history(envelope: Envelope, position: float) -> None: for node in self._getNodesInRange(index_start, index_stop): for child_node in node.getChildNodes(AccNode.ENTRANCE): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: envelope.transform(matrix) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: envelope.transform(matrix) matrix_sc = self._getEnvelopeSpaceChargeMatrix(envelope, node.getLength(part_index), sc) - matrix = node.getMatrix(sync_part, part_index=part_index) + matrix = self._getEnvelopeNodeMatrix( + node, + sync_part, + part_index=part_index, + parent_node=self, + fit_state=fit_state, + ) if matrix is not None: if matrix_sc is not None: matrix = matrix @ matrix_sc @@ -428,12 +538,22 @@ def update_history(envelope: Envelope, position: float) -> None: update_history(envelope, path_length) for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: envelope.transform(matrix) for child_node in node.getChildNodes(AccNode.EXIT): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: envelope.transform(matrix) return history @@ -444,6 +564,7 @@ def precomputeEnvelopeMatrices( index_start: int = 0, index_stop: int = None, sc: str | None = None, + fit: bool = False, ) -> list: """ Pre-compute transfer matrices for each node. @@ -451,22 +572,34 @@ def precomputeEnvelopeMatrices( For each node, store tuple (node, matrix). Space charge kicks are stored as ("sc", length). """ - self._prepareEnvelopeTracking() + self._prepareEnvelopeTracking(fit=fit) sync_part = envelope.sync_part self.__envelopeElements = [] self.__envelopeOneTurnMatrix = None self.__envelopeSpaceCharge = sc + self.__envelopeFit = fit + fit_state = self._createEnvelopeFitState(sync_part) if fit else None for node in self._getNodesInRange(index_start, index_stop): for child_node in node.getChildNodes(AccNode.ENTRANCE): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: self.__envelopeElements.append((child_node, matrix)) for part_index in range(node.getnParts()): for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: self.__envelopeElements.append((child_node, matrix)) @@ -475,23 +608,39 @@ def precomputeEnvelopeMatrices( if length > 0: self.__envelopeElements.append(("sc", length)) - matrix = node.getMatrix(sync_part, part_index=part_index) + matrix = self._getEnvelopeNodeMatrix( + node, + sync_part, + part_index=part_index, + parent_node=self, + fit_state=fit_state, + ) if matrix is not None: self.__envelopeElements.append((node, matrix)) for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: self.__envelopeElements.append((child_node, matrix)) for child_node in node.getChildNodes(AccNode.EXIT): - matrix = child_node.getMatrix(sync_part) + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=node, + fit_state=fit_state, + ) if matrix is not None: self.__envelopeElements.append((child_node, matrix)) return self.__envelopeElements - def trackEnvelopeRing(self, envelope: Envelope, sc: str | None = None) -> None: + def trackEnvelopeRing(self, envelope: Envelope, sc: str | None = None, fit: bool = False) -> None: """ Track using pre-computed transfer matrices. @@ -500,8 +649,8 @@ def trackEnvelopeRing(self, envelope: Envelope, sc: str | None = None) -> None: can be computed once and reused on each turn. If there is no space charge, we track using the one-turn matrix. """ - if not self.__envelopeElements or self.__envelopeSpaceCharge != sc: - self.precomputeEnvelopeMatrices(envelope, sc=sc) + if not self.__envelopeElements or self.__envelopeSpaceCharge != sc or self.__envelopeFit != fit: + self.precomputeEnvelopeMatrices(envelope, sc=sc, fit=fit) if not sc: if self.__envelopeOneTurnMatrix is None: @@ -526,11 +675,12 @@ def getEnvelopeTransferMatrix( index_start: int = 0, index_stop: int = None, sc: str | None = None, + fit: bool = False, ) -> np.ndarray: """ Return total transfer matrix, including linear space charge when requested. """ - elements = self.precomputeEnvelopeMatrices(envelope, index_start, index_stop, sc=sc) + elements = self.precomputeEnvelopeMatrices(envelope, index_start, index_stop, sc=sc, fit=fit) total_matrix = np.identity(7) for element in elements: diff --git a/py/orbit/teapot/teapot.py b/py/orbit/teapot/teapot.py index cd216b8d..865e1ff4 100644 --- a/py/orbit/teapot/teapot.py +++ b/py/orbit/teapot/teapot.py @@ -1319,11 +1319,47 @@ def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray return None nparts = self.getnParts() - theta = self.getParam("theta") / (nparts - 1) - if part_index == 0 or part_index == nparts - 1: - theta *= 0.5 - - return get_matrix_bend(sync_part, length=length, theta=theta) + if part_index < 0: + theta = self.getParam("theta") + else: + theta = self.getParam("theta") / (nparts - 1) + if part_index == 0 or part_index == nparts - 1: + theta *= 0.5 + + matrix = get_matrix_bend(sync_part, length=length, theta=theta) + + def get_wedge_matrix(edge_angle: float) -> np.ndarray: + # ``wedgedrift`` has an identity Jacobian on the reference orbit. + # ``wedgebendCF`` acts as a thin edge kick to first order. Only + # pole-zero multipoles survive the linearization because the path + # length through the wedge is itself proportional to x. + edge_matrix = np.identity(7) + normal_dipole = 0.0 + skew_dipole = 0.0 + if sync_part.charge() != 0.0: + for pole, kl, skew in zip( + self.getParam("poles"), + self.getParam("kls"), + self.getParam("skews"), + ): + if pole == 0: + if skew: + skew_dipole += kl + else: + normal_dipole += kl + + tan_edge = np.tan(edge_angle) + edge_matrix[1, 0] = tan_edge * ((1.0 / self.getParam("rho")) + normal_dipole) + edge_matrix[3, 0] = -tan_edge * skew_dipole + return edge_matrix + + is_first_part = part_index < 0 or part_index == 0 + is_last_part = part_index < 0 or part_index == nparts - 1 + if is_first_part and self.getParam("ea1") != 0.0: + matrix = matrix @ get_wedge_matrix(self.getParam("ea1")) + if is_last_part and self.getParam("ea2") != 0.0: + matrix = get_wedge_matrix(self.getParam("ea2")) @ matrix + return matrix class RingRFTEAPOT(NodeTEAPOT): diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index 337c18db..d8b3976a 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -6,6 +6,7 @@ from orbit.core.linac import MatrixRfGap from orbit.bunch_utils import collect_bunch from orbit.envelope import Envelope +from orbit.envelope import fit_transfer_matrix from orbit.lattice import AccNode from orbit.lattice import AccLattice from orbit.py_linac.lattice import Drift @@ -17,6 +18,7 @@ from orbit.teapot import ContinuousLinearFocusingTEAPOT from orbit.teapot import DriftTEAPOT from orbit.teapot import KickTEAPOT +from orbit.teapot import MultipoleTEAPOT from orbit.teapot import QuadTEAPOT from orbit.teapot import SolenoidTEAPOT from orbit.teapot import TiltTEAPOT @@ -206,6 +208,48 @@ def test_bend_teapot(charge: float): track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_bend_teapot_edge_matrix(charge: float): + node = BendTEAPOT( + length=1.0, + theta=np.radians(20.0), + nparts=5, + ea1=np.radians(8.0), + ea2=np.radians(-3.0), + ) + lattice = make_lattice([node]) + + bunch = Bunch() + bunch.mass(mass_proton) + bunch.charge(charge) + bunch.getSyncParticle().kinEnergy(1.3) + + matrix_fit = fit_transfer_matrix(lattice, bunch) + envelope = Envelope(sync_part=bunch.getSyncParticle()) + matrix_analytic = lattice.getEnvelopeTransferMatrix(envelope) + assert np.allclose(matrix_analytic, matrix_fit, atol=1.0e-10) + + +def test_fitted_envelope_matrices(): + node = MultipoleTEAPOT( + length=0.4, + nparts=3, + poles=[2], + kls=[0.2], + skews=[0], + ) + lattice = make_lattice([node]) + + bunch = Bunch() + bunch.mass(mass_proton) + bunch.getSyncParticle().kinEnergy(1.3) + + matrix_expected = fit_transfer_matrix(lattice, bunch) + envelope = Envelope(sync_part=bunch.getSyncParticle()) + matrix_actual = lattice.getEnvelopeTransferMatrix(envelope, fit=True) + assert np.allclose(matrix_actual, matrix_expected, atol=1.0e-12) + + @pytest.mark.parametrize("charge", [1.0, -1.0]) def test_bend_linac(charge: float): node = Bend() From 962a8c89bd84ac3c088d00c5b822e6e07229c92a Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Mon, 5 Oct 2026 23:11:28 -0400 Subject: [PATCH 21/42] Add `fit` option to `trackEnvelope` function --- py/orbit/envelope/matrix_fitting.py | 10 +-- py/orbit/lattice/AccLattice.py | 111 +++++++++++++++++++--------- 2 files changed, 78 insertions(+), 43 deletions(-) diff --git a/py/orbit/envelope/matrix_fitting.py b/py/orbit/envelope/matrix_fitting.py index 5de882c9..ad0b90fa 100644 --- a/py/orbit/envelope/matrix_fitting.py +++ b/py/orbit/envelope/matrix_fitting.py @@ -15,7 +15,6 @@ def orbit_matrix_to_numpy(matrix: Matrix) -> np.ndarray: - """Convert an ORBIT matrix to a NumPy array.""" matrix_out = np.zeros(matrix.size()) for i in range(matrix_out.shape[0]): for j in range(matrix_out.shape[1]): @@ -24,7 +23,6 @@ def orbit_matrix_to_numpy(matrix: Matrix) -> np.ndarray: def copy_sync_particle(source: SyncParticle, target: SyncParticle) -> None: - """Copy the mutable synchronous-particle state.""" target.rVector(source.rVector()) target.pVector(source.pVector()) target.nxVector(source.nxVector()) @@ -32,7 +30,6 @@ def copy_sync_particle(source: SyncParticle, target: SyncParticle) -> None: def bunch_from_sync_particle(sync_part: SyncParticle) -> Bunch: - """Create an empty bunch with a copy of a synchronous particle.""" bunch = Bunch() bunch.mass(sync_part.mass()) bunch.charge(sync_part.charge()) @@ -49,12 +46,7 @@ def fit_node_transfer_matrix( lost_bunch: Bunch | None = None, params_dict: dict | None = None, ) -> np.ndarray: - """Fit the local linear map of one node operation by particle tracking. - The input ``bunch`` is used as reusable workspace. Its synchronous particle - advances through the node, which lets a caller fit successive operations at - the correct energy and time. - """ if matrix_generator is None: matrix_generator = MatrixGenerator() if lost_bunch is None: @@ -90,7 +82,7 @@ def fit_transfer_matrix( index_start: int = 0, index_stop: int | None = None, ) -> np.ndarray: - """Fit a lattice transfer matrix by tracking finite-difference probes.""" + if index_stop is None: index_stop = -1 diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index 78e6c581..748bcbb0 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -1,20 +1,22 @@ -from __future__ import annotations - import os -from typing import TYPE_CHECKING import numpy as np -from ..utils import orbitFinalize -from ..utils import NamedObject -from ..utils import TypedObject +from orbit.core.bunch import Bunch +from orbit.core.bunch import SyncParticle +from orbit.core.teapot_base import MatrixGenerator +from orbit.envelope import Envelope +from orbit.envelope.matrix_fitting import bunch_from_sync_particle +from orbit.envelope.matrix_fitting import copy_sync_particle +from orbit.envelope.matrix_fitting import fit_node_transfer_matrix + +from orbit.utils import orbitFinalize +from orbit.utils import NamedObject +from orbit.utils import TypedObject from .AccActionsContainer import AccActionsContainer from .AccNode import AccNode -if TYPE_CHECKING: - from orbit.envelope.envelope import Envelope - class AccLattice(NamedObject, TypedObject): """ @@ -41,7 +43,8 @@ def __init__(self, name="no name"): self.__envelopeElements = [] self.__envelopeOneTurnMatrix = None self.__envelopeSpaceCharge = None - self.__envelopeFit = False + self.__envelopeFit = True + self.__envelopeRange = None def initialize(self): """ @@ -278,7 +281,7 @@ def _getNodesInRange(self, index_start: int = 0, index_stop: int = None): index_stop = len(self.__children) - 1 return self.__children[index_start : index_stop + 1] - def _prepareEnvelopeTracking(self, fit: bool = False) -> None: + def _prepareEnvelopeTracking(self, fit: bool = True) -> None: if fit: return for node in self.__children: @@ -306,10 +309,6 @@ def _prepareEnvelopeTracking(self, fit: bool = False) -> None: raise RuntimeError(message) def _createEnvelopeFitState(self, sync_part): - from orbit.core.bunch import Bunch - from orbit.core.teapot_base import MatrixGenerator - from orbit.envelope.matrix_fitting import bunch_from_sync_particle - bunch = bunch_from_sync_particle(sync_part) lost_bunch = Bunch() bunch.copyEmptyBunchTo(lost_bunch) @@ -325,20 +324,23 @@ def _createEnvelopeFitState(self, sync_part): def _getEnvelopeNodeMatrix( self, - node, - sync_part, + node: AccNode, + sync_part: SyncParticle, part_index: int | None = None, - parent_node=None, + parent_node: AccNode = None, fit_state: dict | None = None, ) -> np.ndarray | None: + """Return 7 x 7 transfer matrix from node and synchonous particle. + + If `fit_state` is provided, the matrix will be fit to input/output + coordinates of a particle near the origin. Otherwise the analytic + matrix will be used (if implemented). + """ if fit_state is None: if part_index is None: return node.getMatrix(sync_part) return node.getMatrix(sync_part, part_index=part_index) - from orbit.envelope.matrix_fitting import copy_sync_particle - from orbit.envelope.matrix_fitting import fit_node_transfer_matrix - matrix = fit_node_transfer_matrix( node, fit_state["bunch"], @@ -370,22 +372,42 @@ def trackEnvelope( index_stop: int = None, sc: str | None = None, history: bool = False, - fit: bool = False, + fit: bool = True, + static: bool = False, ) -> None | dict[str, list]: """ Track envelope through the lattice. - If ``fit`` is true, obtain each linear map from tracking probes rather - than from the node's analytic ``getMatrix`` implementation. + Args: + envelope: Envelope to track. + index_start: Index of first node in sublattice. + index_stop: Index of last node in sublattice. + sc: Whether to include space charge kicks. + history: Whether to return beam parameters vs. position in lattice. + fit: Whether to use best-fit transfer matrices or analytic + transfer matrices. + static: Whether to pre-compute transfer matrices before + tracking. This works for as long as there are no time-dependent + nodes in the lattice. """ if history: - return self.trackEnvelopeHistory( + return self._trackEnvelopeHistory( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + static=static, + ) + if static: + self._trackEnvelopeStatic( envelope, index_start=index_start, index_stop=index_stop, sc=sc, fit=fit, ) + return None self._prepareEnvelopeTracking(fit=fit) self.setEnvelopeSpaceCharge(sc) @@ -447,13 +469,14 @@ def trackEnvelope( if matrix is not None: envelope.transform(matrix) - def trackEnvelopeHistory( + def _trackEnvelopeHistory( self, envelope: Envelope, index_start: int = 0, index_stop: int = None, sc: str | None = None, - fit: bool = False, + fit: bool = True, + static: bool = False, ) -> dict[str, list]: """ Track envelope and return parameters vs. position in lattice. @@ -558,13 +581,13 @@ def update_history(envelope: Envelope, position: float) -> None: envelope.transform(matrix) return history - def precomputeEnvelopeMatrices( + def _precomputeEnvelopeMatrices( self, envelope: Envelope, index_start: int = 0, index_stop: int = None, sc: str | None = None, - fit: bool = False, + fit: bool = True, ) -> list: """ Pre-compute transfer matrices for each node. @@ -579,6 +602,7 @@ def precomputeEnvelopeMatrices( self.__envelopeOneTurnMatrix = None self.__envelopeSpaceCharge = sc self.__envelopeFit = fit + self.__envelopeRange = (index_start, index_stop) fit_state = self._createEnvelopeFitState(sync_part) if fit else None for node in self._getNodesInRange(index_start, index_stop): @@ -640,7 +664,14 @@ def precomputeEnvelopeMatrices( return self.__envelopeElements - def trackEnvelopeRing(self, envelope: Envelope, sc: str | None = None, fit: bool = False) -> None: + def _trackEnvelopeStatic( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int = None, + sc: str | None = None, + fit: bool = True, + ) -> None: """ Track using pre-computed transfer matrices. @@ -649,8 +680,20 @@ def trackEnvelopeRing(self, envelope: Envelope, sc: str | None = None, fit: bool can be computed once and reused on each turn. If there is no space charge, we track using the one-turn matrix. """ - if not self.__envelopeElements or self.__envelopeSpaceCharge != sc or self.__envelopeFit != fit: - self.precomputeEnvelopeMatrices(envelope, sc=sc, fit=fit) + envelope_range = (index_start, index_stop) + if ( + not self.__envelopeElements + or self.__envelopeSpaceCharge != sc + or self.__envelopeFit != fit + or self.__envelopeRange != envelope_range + ): + self._precomputeEnvelopeMatrices( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + ) if not sc: if self.__envelopeOneTurnMatrix is None: @@ -675,12 +718,12 @@ def getEnvelopeTransferMatrix( index_start: int = 0, index_stop: int = None, sc: str | None = None, - fit: bool = False, + fit: bool = True, ) -> np.ndarray: """ Return total transfer matrix, including linear space charge when requested. """ - elements = self.precomputeEnvelopeMatrices(envelope, index_start, index_stop, sc=sc, fit=fit) + elements = self._precomputeEnvelopeMatrices(envelope, index_start, index_stop, sc=sc, fit=fit) total_matrix = np.identity(7) for element in elements: From 197755461553ac103eb166860d72f6c0f3a5841f Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Mon, 5 Oct 2026 23:11:46 -0400 Subject: [PATCH 22/42] Update examples --- examples/Envelope/sns_linac/test_sns_linac.py | 3 +- examples/Envelope/sns_ring/test_sns_ring.py | 16 +- .../Envelope/sns_ring/test_sns_ring_speed.py | 203 +++++++++--------- examples/Envelope/test_env_2d_fodo.py | 3 +- examples/Envelope/test_env_2d_fodo_speed.py | 3 +- examples/Envelope/test_env_3d_drift.py | 11 +- tests/py/orbit/test_env.py | 39 ++++ 7 files changed, 162 insertions(+), 116 deletions(-) diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index 11cccdd9..03197dfb 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -164,7 +164,8 @@ def main(args: argparse.Namespace) -> None: histories["envelope"] = lattice.trackEnvelope( envelope, history=True, - sc=("3d" if args.sc else None) + sc=("3d" if args.sc else None), + fit=True, ) # Track bunch diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring/test_sns_ring.py index 300f0f6d..8e9d5323 100644 --- a/examples/Envelope/sns_ring/test_sns_ring.py +++ b/examples/Envelope/sns_ring/test_sns_ring.py @@ -56,15 +56,8 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--sc", type=int, default=0) parser.add_argument("--sc-grid", type=int, default=64) - parser.add_argument("--fit-matrices", action="store_true") - parser.add_argument("--fringe", action="store_true") - parser.add_argument( - "--handle-unknown", - type=str, - default=None, - choices=["drift", "fit"], - help=argparse.SUPPRESS, - ) + parser.add_argument("--fit", type=int, default=1) + parser.add_argument("--fringe", type=int, default=0) return parser.parse_args() @@ -179,10 +172,11 @@ def main(args: argparse.Namespace) -> None: for turn in range(args.turns + 1): if turn > 0: - lattice.trackEnvelopeRing( + lattice.trackEnvelope( envelope, sc=("2d" if args.sc else None), - fit=(args.fit_matrices or args.handle_unknown == "fit"), + fit=args.fit, + static=True, ) cov_matrix = envelope.cov_matrix diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring/test_sns_ring_speed.py index ea119c71..c7dfa176 100644 --- a/examples/Envelope/sns_ring/test_sns_ring_speed.py +++ b/examples/Envelope/sns_ring/test_sns_ring_speed.py @@ -23,129 +23,138 @@ from utils import gen_dist -parser = argparse.ArgumentParser() -parser.add_argument("--bunch-length", type=float, default=120.0) -parser.add_argument("--kin-energy", type=float, default=1.300) -parser.add_argument("--intensity", type=float, default=2e14) - -parser.add_argument("--nparts", type=int, default=10_000) -parser.add_argument("--turns", type=int, default=25) -parser.add_argument("--sc", type=int, default=0) -parser.add_argument("--sc-grid", type=int, default=64) -args = parser.parse_args() +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--bunch-length", type=float, default=120.0) + parser.add_argument("--kin-energy", type=float, default=1.300) + parser.add_argument("--intensity", type=float, default=2e14) + + parser.add_argument("--nparts", type=int, default=10_000) + parser.add_argument("--turns", type=int, default=25) + parser.add_argument("--sc", type=int, default=0) + parser.add_argument("--sc-grid", type=int, default=64) + parser.add_argument("--fringe", type=int, default=0) + parser.add_argument("--fit", type=int, default=1) + return parser.parse_args() + + +def main(args: argparse.Namespace) -> None: + + lattice = TEAPOT_Ring() + lattice.readMADX("inputs/sns_ring.lat", "rnginjsol") + lattice.initialize() + + for node in lattice.getNodes(): + try: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + except: + pass + for node in lattice.getNodes(): + if type(node) is BendTEAPOT: + node.setParam("ea1", 0.0) + node.setParam("ea2", 0.0) -lattice = TEAPOT_Ring() -lattice.readMADX("inputs/sns_ring.lat", "rnginjsol") -lattice.initialize() - -for node in lattice.getNodes(): - try: - node.setUsageFringeFieldIN(False) - node.setUsageFringeFieldOUT(False) - except: - pass - -for node in lattice.getNodes(): - if type(node) is BendTEAPOT: - node.setParam("ea1", 0.0) - node.setParam("ea2", 0.0) + for node in lattice.getNodes(): + max_length = 1.0 + if node.getLength() > max_length: + node.setnParts(1 + int(node.getLength() / max_length)) -for node in lattice.getNodes(): - max_length = 1.0 - if node.getLength() > max_length: - node.setnParts(1 + int(node.getLength() / max_length)) + bunch = Bunch() + bunch.mass(mass_proton) + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(args.kin_energy) -bunch = Bunch() -bunch.mass(mass_proton) -sync_part = bunch.getSyncParticle() -sync_part.kinEnergy(args.kin_energy) + 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 = 25.0e-06 + eps_y = eps_x -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 = 25.0e-06 -eps_y = eps_x + 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 / 4.0) ** 2 + cov_matrix[5, 5] = 0.0 -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 / 4.0) ** 2 -cov_matrix[5, 5] = 0.0 + cov_matrix_init = np.copy(cov_matrix) -cov_matrix_init = np.copy(cov_matrix) + # Track envelope + print("ENVELOPE") -# Track envelope -print("ENVELOPE") + envelope = Envelope( + sync_part=sync_part, + cov_matrix=cov_matrix_init, + intensity=args.intensity, + ) + envelope_sc = "2d" if args.sc else None -envelope = Envelope( - sync_part=sync_part, - cov_matrix=cov_matrix_init, - intensity=args.intensity, -) -envelope_sc = "2d" if args.sc else None + start_time = time.time() -start_time = time.time() + profiler = cProfile.Profile() + profiler.enable() -profiler = cProfile.Profile() -profiler.enable() + for turn in trange(args.turns): + lattice.trackEnvelope(envelope, sc=envelope_sc, fit=args.fit, static=True) -for turn in trange(args.turns): - lattice.trackEnvelopeRing(envelope, sc=envelope_sc) + time_per_turn = (time.time() - start_time) / args.turns -time_per_turn = (time.time() - start_time) / args.turns + profiler.disable() -profiler.disable() + print("Time per turn:", time_per_turn) -print("Time per turn:", time_per_turn) + profiler_stats = pstats.Stats(profiler) + profiler_stats.sort_stats(pstats.SortKey.TIME) + profiler_stats.print_stats(10) -profiler_stats = pstats.Stats(profiler) -profiler_stats.sort_stats(pstats.SortKey.TIME) -profiler_stats.print_stats(10) + # Track bunch + print("BUNCH") -# Track bunch -print("BUNCH") + rng = np.random.default_rng() -rng = np.random.default_rng() + bunch_coords = np.zeros((args.nparts, 6)) + bunch_coords[:, :4] = gen_dist( + size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv" + ) + bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) -bunch_coords = np.zeros((args.nparts, 6)) -bunch_coords[:, :4] = gen_dist( - size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv" -) -bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) + for i in range(bunch_coords.shape[0]): + bunch.addParticle(*bunch_coords[i]) -for i in range(bunch_coords.shape[0]): - bunch.addParticle(*bunch_coords[i]) + if args.sc: + sc_calc = SpaceChargeCalc2p5D(64, 64, 1) + sc_path_length_min = 1.00e-06 + sc_nodes = setSC2p5DAccNodes(lattice, sc_path_length_min, sc_calc) -if args.sc: - sc_calc = SpaceChargeCalc2p5D(64, 64, 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) - bunch_size = bunch.getSizeGlobal() - bunch.macroSize(args.intensity / bunch_size) + start_time = time.time() -start_time = time.time() + profiler = cProfile.Profile() + profiler.enable() -profiler = cProfile.Profile() -profiler.enable() + for turn in trange(args.turns): + lattice.trackBunch(bunch) -for turn in trange(args.turns): - lattice.trackBunch(bunch) + time_per_turn = (time.time() - start_time) / args.turns -time_per_turn = (time.time() - start_time) / args.turns + profiler.disable() -profiler.disable() + print("Time per turn:", time_per_turn) -print("Time per turn:", time_per_turn) + profiler_stats = pstats.Stats(profiler) + profiler_stats.sort_stats(pstats.SortKey.TIME) + profiler_stats.print_stats(10) -profiler_stats = pstats.Stats(profiler) -profiler_stats.sort_stats(pstats.SortKey.TIME) -profiler_stats.print_stats(10) + +if __name__ == "__main__": + main(parse_args()) \ No newline at end of file diff --git a/examples/Envelope/test_env_2d_fodo.py b/examples/Envelope/test_env_2d_fodo.py index 969e99ff..b7f34a7a 100644 --- a/examples/Envelope/test_env_2d_fodo.py +++ b/examples/Envelope/test_env_2d_fodo.py @@ -55,6 +55,7 @@ def parse_args() -> argparse.Namespace: 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() @@ -147,7 +148,7 @@ def main(args: argparse.Namespace) -> None: history = {"xrms": [], "yrms": [], "xavg": [], "yavg": []} for turn in range(args.turns): if turn > 0: - lattice.trackEnvelopeRing(envelope, sc=envelope_sc) + lattice.trackEnvelope(envelope, sc=envelope_sc, fit=args.fit, static=True) cov_matrix = envelope.cov_matrix centroid = envelope.centroid diff --git a/examples/Envelope/test_env_2d_fodo_speed.py b/examples/Envelope/test_env_2d_fodo_speed.py index 7462d289..dc4e261b 100644 --- a/examples/Envelope/test_env_2d_fodo_speed.py +++ b/examples/Envelope/test_env_2d_fodo_speed.py @@ -33,6 +33,7 @@ parser.add_argument("--turns", type=int, default=500) parser.add_argument("--sc", type=int, default=0) parser.add_argument("--sc-grid", type=int, default=64) +parser.add_argument("--fit", type=int, default=1) args = parser.parse_args() nodes = [ @@ -93,7 +94,7 @@ profiler.enable() for turn in trange(args.turns): - lattice.trackEnvelopeRing(envelope, sc=envelope_sc) + lattice.trackEnvelope(envelope, sc=envelope_sc, fit=args.fit, static=True) time_per_turn = (time.time() - start_time) / args.turns diff --git a/examples/Envelope/test_env_3d_drift.py b/examples/Envelope/test_env_3d_drift.py index 992ec27d..0f9ca51f 100644 --- a/examples/Envelope/test_env_3d_drift.py +++ b/examples/Envelope/test_env_3d_drift.py @@ -42,9 +42,9 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--rms-y", type=float, default=0.010) parser.add_argument("--rms-z", type=float, default=0.010) - parser.add_argument("--tilt-x", type=float, default=0.0) - parser.add_argument("--tilt-y", type=float, default=0.0) - parser.add_argument("--tilt-z", type=float, default=0.0) + parser.add_argument("--rot-x", type=float, default=0.0) + parser.add_argument("--rot-y", type=float, default=0.0) + parser.add_argument("--rot-z", type=float, default=0.0) parser.add_argument("--nslice", type=int, default=10) parser.add_argument("--length", type=float, default=0.1) @@ -53,6 +53,7 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--nparts", type=int, default=100_000) parser.add_argument("--sc", type=int, default=0) + parser.add_argument("--fit", type=int, default=0) return parser.parse_args() @@ -99,7 +100,7 @@ def main(args: argparse.Namespace) -> None: cov_matrix_init = np.zeros((6, 6)) rotation_matrix = rotation_matrix_3d( - math.radians(args.tilt_x), math.radians(args.tilt_y), math.radians(args.tilt_z) + math.radians(args.rot_x), math.radians(args.rot_y), math.radians(args.rot_z) ) print(rotation_matrix) @@ -136,7 +137,7 @@ def main(args: argparse.Namespace) -> None: history = {"xrms": [], "yrms": [], "zrms": []} for turn in range(args.turns): if turn > 0: - lattice.trackEnvelope(envelope, sc=envelope_sc) + lattice.trackEnvelope(envelope, sc=envelope_sc, fit=args.fit) cov_matrix = envelope.cov_matrix diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index d8b3976a..613b17fd 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -380,6 +380,45 @@ def test_track_sublattice_no_error(): lattice.trackEnvelope(envelope, index_stop=-i) +def test_track_static_sublattice(): + lattice = make_lattice( + [ + DriftTEAPOT(length=0.1), + DriftTEAPOT(length=0.2), + DriftTEAPOT(length=0.3), + ] + ) + + bunch = Bunch() + bunch.mass(mass_proton) + bunch.getSyncParticle().kinEnergy(0.001) + envelope = Envelope( + sync_part=bunch.getSyncParticle(), + cov_matrix=make_default_cov_matrix(), + ) + + for index_start, index_stop in [(0, 0), (1, 2)]: + expected = envelope.copy() + lattice.trackEnvelope( + expected, + index_start=index_start, + index_stop=index_stop, + fit=False, + ) + + actual = envelope.copy() + lattice.trackEnvelope( + actual, + index_start=index_start, + index_stop=index_stop, + fit=False, + static=True, + ) + + assert np.allclose(actual.cov_matrix, expected.cov_matrix) + assert np.allclose(actual.centroid, expected.centroid) + + @pytest.mark.parametrize("charge", [1.0, -1.0]) def test_get_total_matrix(charge: float) -> None: node = DriftTEAPOT(length=2.0, nparts=50) From 31095abd1ff7fdde490eb3539cec191f81d6edef Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Mon, 5 Oct 2026 23:33:35 -0400 Subject: [PATCH 23/42] Simplify envelope tracking code --- py/orbit/lattice/AccLattice.py | 503 +++++++++++++++------------------ tests/py/orbit/test_env.py | 29 ++ 2 files changed, 257 insertions(+), 275 deletions(-) diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index 748bcbb0..e6fa9269 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -1,4 +1,5 @@ import os +from typing import Any import numpy as np @@ -40,11 +41,9 @@ def __init__(self, name="no name"): self.__isInitialized = False self.__children = [] self.__childPositions = {} - self.__envelopeElements = [] - self.__envelopeOneTurnMatrix = None - self.__envelopeSpaceCharge = None - self.__envelopeFit = True - self.__envelopeRange = None + self._envelope_elements = [] + self._envelope_one_turn_matrix = None + self._envelope_cache_key = None def initialize(self): """ @@ -276,12 +275,13 @@ def trackActions(self, actionsContainer, paramsDict={}, index_start=-1, index_st paramsDict["parentNode"] = self node.trackActions(actionsContainer, paramsDict) - def _getNodesInRange(self, index_start: int = 0, index_stop: int = None): + def _getNodesInRange(self, index_start: int = 0, index_stop: int = None) -> list[AccNode]: if index_stop is None: index_stop = len(self.__children) - 1 return self.__children[index_start : index_stop + 1] def _prepareEnvelopeTracking(self, fit: bool = True) -> None: + """Check lattice before tracking envelope.""" if fit: return for node in self.__children: @@ -289,9 +289,7 @@ def _prepareEnvelopeTracking(self, fit: bool = True) -> None: is_teapot_bend = node_type.__name__ == "BendTEAPOT" and node_type.__module__ == "orbit.teapot.teapot" is_linac_bend = node_type.__name__ == "Bend" and node_type.__module__ == "orbit.py_linac.lattice.LinacAccNodes" if is_teapot_bend: - uses_unsupported_fringe = ( - node.getParam("ea1") != 0.0 and node.getUsageFringeFieldIN() - ) or ( + uses_unsupported_fringe = (node.getParam("ea1") != 0.0 and node.getUsageFringeFieldIN()) or ( node.getParam("ea2") != 0.0 and node.getUsageFringeFieldOUT() ) if uses_unsupported_fringe: @@ -308,7 +306,8 @@ def _prepareEnvelopeTracking(self, fit: bool = True) -> None: message += " `node.setParam('ea2', 0.0)`" raise RuntimeError(message) - def _createEnvelopeFitState(self, sync_part): + def _createEnvelopeFitState(self, sync_part) -> dict[str, Any]: + """Return items needed to compute best-fit transfer matrix.""" bunch = bunch_from_sync_particle(sync_part) lost_bunch = Bunch() bunch.copyEmptyBunchTo(lost_bunch) @@ -330,11 +329,11 @@ def _getEnvelopeNodeMatrix( parent_node: AccNode = None, fit_state: dict | None = None, ) -> np.ndarray | None: - """Return 7 x 7 transfer matrix from node and synchonous particle. + """Return 7 x 7 transfer matrix from node and synchronous particle. If `fit_state` is provided, the matrix will be fit to input/output - coordinates of a particle near the origin. Otherwise the analytic - matrix will be used (if implemented). + coordinates of a particle launched near the origin. Otherwise the + analytic matrix will be used (if implemented). """ if fit_state is None: if part_index is None: @@ -354,6 +353,7 @@ def _getEnvelopeNodeMatrix( return matrix def _getEnvelopeSpaceChargeMatrix(self, envelope: Envelope, length: float, sc: str | None) -> np.ndarray | None: + """Return transfer matrix for linear space charge kick.""" if not sc or length <= 0: return None if sc == "2d": @@ -362,8 +362,146 @@ def _getEnvelopeSpaceChargeMatrix(self, envelope: Envelope, length: float, sc: s return envelope.sc_matrix_3d(length) raise ValueError(f"Invalid envelope space charge option `{sc}`") - def setEnvelopeSpaceCharge(self, sc: str | None) -> None: - self.__envelopeSpaceCharge = sc + def _iterEnvelopeElements( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int = None, + sc: str | None = None, + fit: bool = True, + ): + """Yield matrices, space charge kicks, and position updates in tracking order.""" + self._prepareEnvelopeTracking(fit=fit) + sync_part = envelope.sync_part + fit_state = self._createEnvelopeFitState(sync_part) if fit else None + + def iter_child_elements(child_nodes, parent_node): + for child_node in child_nodes: + matrix = self._getEnvelopeNodeMatrix( + child_node, + sync_part, + parent_node=parent_node, + fit_state=fit_state, + ) + if matrix is not None: + yield child_node, matrix + + for node in self._getNodesInRange(index_start, index_stop): + yield from iter_child_elements( + node.getChildNodes(AccNode.ENTRANCE), + node, + ) + + for part_index in range(node.getnParts()): + yield from iter_child_elements( + node.getChildNodes( + AccNode.BODY, + part_index, + place_in_part=AccNode.BEFORE, + ), + node, + ) + + length = node.getLength(part_index) + if sc and length > 0: + yield "sc", length + + matrix = self._getEnvelopeNodeMatrix( + node, + sync_part, + part_index=part_index, + parent_node=self, + fit_state=fit_state, + ) + if matrix is not None: + yield node, matrix + + yield "position", length + + yield from iter_child_elements( + node.getChildNodes( + AccNode.BODY, + part_index, + place_in_part=AccNode.AFTER, + ), + node, + ) + + yield from iter_child_elements( + node.getChildNodes(AccNode.EXIT), + node, + ) + + def _applyEnvelopeElements( + self, + envelope: Envelope, + elements, + sc: str | None = None, + update_history=None, + calculate_matrix: bool = False, + ) -> np.ndarray | None: + """Apply envelope operations and optionally return their combined matrix.""" + total_matrix = np.identity(7) if calculate_matrix else None + path_length = 0.0 + + for element_type, value in elements: + if element_type == "position": + path_length += value + if update_history is not None: + update_history(path_length) + continue + + if element_type == "sc": + matrix = self._getEnvelopeSpaceChargeMatrix(envelope, value, sc) + else: + matrix = value + + envelope.transform(matrix) + if calculate_matrix: + total_matrix = matrix @ total_matrix + + return total_matrix + + def _precomputeEnvelopeElements( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int = None, + sc: str | None = None, + fit: bool = True, + ) -> list: + """Precompute envelope operations for a static lattice.""" + self._envelope_elements = list( + self._iterEnvelopeElements( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + ) + ) + self._envelope_cache_key = (index_start, index_stop, sc, fit) + self._envelope_one_turn_matrix = None + return self._envelope_elements + + def _getStaticEnvelopeElements( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int = None, + sc: str | None = None, + fit: bool = True, + ) -> list: + cache_key = (index_start, index_stop, sc, fit) + if self._envelope_cache_key != cache_key: + self._precomputeEnvelopeElements( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + ) + return self._envelope_elements def trackEnvelope( self, @@ -409,65 +547,14 @@ def trackEnvelope( ) return None - self._prepareEnvelopeTracking(fit=fit) - self.setEnvelopeSpaceCharge(sc) - sync_part = envelope.sync_part - fit_state = self._createEnvelopeFitState(sync_part) if fit else None - - for node in self._getNodesInRange(index_start, index_stop): - for child_node in node.getChildNodes(AccNode.ENTRANCE): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - envelope.transform(matrix) - - for part_index in range(node.getnParts()): - for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - envelope.transform(matrix) - - matrix_sc = self._getEnvelopeSpaceChargeMatrix(envelope, node.getLength(part_index), sc) - matrix = self._getEnvelopeNodeMatrix( - node, - sync_part, - part_index=part_index, - parent_node=self, - fit_state=fit_state, - ) - if matrix is not None: - if matrix_sc is not None: - matrix = matrix @ matrix_sc - envelope.transform(matrix) - - for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - envelope.transform(matrix) - - for child_node in node.getChildNodes(AccNode.EXIT): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - envelope.transform(matrix) + elements = self._iterEnvelopeElements( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + ) + self._applyEnvelopeElements(envelope, elements, sc=sc) def _trackEnvelopeHistory( self, @@ -481,11 +568,6 @@ def _trackEnvelopeHistory( """ Track envelope and return parameters vs. position in lattice. """ - self._prepareEnvelopeTracking(fit=fit) - self.setEnvelopeSpaceCharge(sc) - sync_part = envelope.sync_part - fit_state = self._createEnvelopeFitState(sync_part) if fit else None - history_keys = [ "s", "kin_energy", @@ -502,168 +584,51 @@ def _trackEnvelopeHistory( history = {key: [] for key in history_keys} def observe(envelope: Envelope) -> dict: - parameters = {} - parameters["gamma"] = envelope.gamma - parameters["beta"] = envelope.beta - parameters["kin_energy"] = envelope.kin_energy - parameters["mean"] = envelope.centroid.copy() - parameters["cov"] = envelope.cov_matrix.copy() - parameters["rms_x"] = np.sqrt(parameters["cov"][0, 0]) - parameters["rms_y"] = np.sqrt(parameters["cov"][2, 2]) - parameters["rms_z"] = np.sqrt(parameters["cov"][4, 4]) - return parameters - - def update_history(envelope: Envelope, position: float) -> None: + cov_matrix = envelope.cov_matrix.copy() + return { + "gamma": envelope.gamma, + "beta": envelope.beta, + "kin_energy": envelope.kin_energy, + "mean": envelope.centroid.copy(), + "cov": cov_matrix, + "rms_x": np.sqrt(cov_matrix[0, 0]), + "rms_y": np.sqrt(cov_matrix[2, 2]), + "rms_z": np.sqrt(cov_matrix[4, 4]), + "eps_x": np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])), + "eps_y": np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])), + } + + def update_history(position: float) -> None: history["s"].append(position) parameters = observe(envelope) - for key in parameters: - history[key].append(parameters[key]) - - path_length = 0.0 - update_history(envelope, path_length) - - for node in self._getNodesInRange(index_start, index_stop): - for child_node in node.getChildNodes(AccNode.ENTRANCE): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - envelope.transform(matrix) + for key, value in parameters.items(): + history[key].append(value) - for part_index in range(node.getnParts()): - for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - envelope.transform(matrix) - - matrix_sc = self._getEnvelopeSpaceChargeMatrix(envelope, node.getLength(part_index), sc) - matrix = self._getEnvelopeNodeMatrix( - node, - sync_part, - part_index=part_index, - parent_node=self, - fit_state=fit_state, - ) - if matrix is not None: - if matrix_sc is not None: - matrix = matrix @ matrix_sc - envelope.transform(matrix) - - path_length += node.getLength(part_index) - update_history(envelope, path_length) - - for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - envelope.transform(matrix) - - for child_node in node.getChildNodes(AccNode.EXIT): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - envelope.transform(matrix) + update_history(0.0) + if static: + elements = self._getStaticEnvelopeElements( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + ) + else: + elements = self._iterEnvelopeElements( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + ) + self._applyEnvelopeElements( + envelope, + elements, + sc=sc, + update_history=update_history, + ) return history - def _precomputeEnvelopeMatrices( - self, - envelope: Envelope, - index_start: int = 0, - index_stop: int = None, - sc: str | None = None, - fit: bool = True, - ) -> list: - """ - Pre-compute transfer matrices for each node. - - For each node, store tuple (node, matrix). Space charge kicks are - stored as ("sc", length). - """ - self._prepareEnvelopeTracking(fit=fit) - sync_part = envelope.sync_part - - self.__envelopeElements = [] - self.__envelopeOneTurnMatrix = None - self.__envelopeSpaceCharge = sc - self.__envelopeFit = fit - self.__envelopeRange = (index_start, index_stop) - fit_state = self._createEnvelopeFitState(sync_part) if fit else None - - for node in self._getNodesInRange(index_start, index_stop): - for child_node in node.getChildNodes(AccNode.ENTRANCE): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - self.__envelopeElements.append((child_node, matrix)) - - for part_index in range(node.getnParts()): - for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.BEFORE): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - self.__envelopeElements.append((child_node, matrix)) - - if sc: - length = node.getLength(part_index) - if length > 0: - self.__envelopeElements.append(("sc", length)) - - matrix = self._getEnvelopeNodeMatrix( - node, - sync_part, - part_index=part_index, - parent_node=self, - fit_state=fit_state, - ) - if matrix is not None: - self.__envelopeElements.append((node, matrix)) - - for child_node in node.getChildNodes(AccNode.BODY, part_index, place_in_part=AccNode.AFTER): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - self.__envelopeElements.append((child_node, matrix)) - - for child_node in node.getChildNodes(AccNode.EXIT): - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=node, - fit_state=fit_state, - ) - if matrix is not None: - self.__envelopeElements.append((child_node, matrix)) - - return self.__envelopeElements - def _trackEnvelopeStatic( self, envelope: Envelope, @@ -680,37 +645,24 @@ def _trackEnvelopeStatic( can be computed once and reused on each turn. If there is no space charge, we track using the one-turn matrix. """ - envelope_range = (index_start, index_stop) - if ( - not self.__envelopeElements - or self.__envelopeSpaceCharge != sc - or self.__envelopeFit != fit - or self.__envelopeRange != envelope_range - ): - self._precomputeEnvelopeMatrices( - envelope, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - ) + elements = self._getStaticEnvelopeElements( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + ) if not sc: - if self.__envelopeOneTurnMatrix is None: - self.__envelopeOneTurnMatrix = np.identity(7) - for node, matrix in self.__envelopeElements: - self.__envelopeOneTurnMatrix = matrix @ self.__envelopeOneTurnMatrix - envelope.transform(self.__envelopeOneTurnMatrix) + if self._envelope_one_turn_matrix is None: + self._envelope_one_turn_matrix = np.identity(7) + for element_type, matrix in elements: + if element_type != "position": + self._envelope_one_turn_matrix = matrix @ self._envelope_one_turn_matrix + envelope.transform(self._envelope_one_turn_matrix) return - for element in self.__envelopeElements: - if element[0] == "sc": - length = element[1] - matrix = self._getEnvelopeSpaceChargeMatrix(envelope, length, sc) - envelope.transform(matrix) - else: - node, matrix = element - envelope.transform(matrix) + self._applyEnvelopeElements(envelope, elements, sc=sc) def getEnvelopeTransferMatrix( self, @@ -723,15 +675,16 @@ def getEnvelopeTransferMatrix( """ Return total transfer matrix, including linear space charge when requested. """ - elements = self._precomputeEnvelopeMatrices(envelope, index_start, index_stop, sc=sc, fit=fit) - - total_matrix = np.identity(7) - for element in elements: - if element[0] == "sc": - length = element[1] - matrix = self._getEnvelopeSpaceChargeMatrix(envelope, length, sc) - else: - node, matrix = element - envelope.transform(matrix) - total_matrix = matrix @ total_matrix - return total_matrix + elements = self._precomputeEnvelopeElements( + envelope, + index_start=index_start, + index_stop=index_stop, + sc=sc, + fit=fit, + ) + return self._applyEnvelopeElements( + envelope, + elements, + sc=sc, + calculate_matrix=True, + ) diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py index 613b17fd..1a9b6d78 100644 --- a/tests/py/orbit/test_env.py +++ b/tests/py/orbit/test_env.py @@ -419,6 +419,35 @@ def test_track_static_sublattice(): assert np.allclose(actual.centroid, expected.centroid) +def test_track_static_history(): + lattice = make_lattice( + [ + DriftTEAPOT(length=0.1, nparts=1), + DriftTEAPOT(length=0.2, nparts=2), + ] + ) + + bunch = Bunch() + bunch.mass(mass_proton) + bunch.getSyncParticle().kinEnergy(0.001) + envelope = Envelope( + sync_part=bunch.getSyncParticle(), + cov_matrix=make_default_cov_matrix(), + ) + + expected = lattice.trackEnvelope(envelope.copy(), history=True, fit=False) + actual = lattice.trackEnvelope( + envelope.copy(), + history=True, + fit=False, + static=True, + ) + + assert actual.keys() == expected.keys() + for key in actual: + assert np.allclose(actual[key], expected[key]) + + @pytest.mark.parametrize("charge", [1.0, -1.0]) def test_get_total_matrix(charge: float) -> None: node = DriftTEAPOT(length=2.0, nparts=50) From 9db3ecaee603c4b5b58b93cd7089a10327344444 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Tue, 6 Oct 2026 11:29:11 -0400 Subject: [PATCH 24/42] Improve envelope history --- examples/Envelope/run.sh | 4 +- examples/Envelope/sns_linac/diagnostics.py | 78 +++++++++++----- examples/Envelope/sns_linac/test_sns_linac.py | 27 +++++- py/orbit/lattice/AccLattice.py | 91 ++++++++++++------- 4 files changed, 138 insertions(+), 62 deletions(-) diff --git a/examples/Envelope/run.sh b/examples/Envelope/run.sh index 078af457..b5487b7b 100755 --- a/examples/Envelope/run.sh +++ b/examples/Envelope/run.sh @@ -10,8 +10,8 @@ python test_env_2d_fodo_speed.py --sc 0 python test_env_2d_fodo_speed.py --sc 1 python test_env_3d_drift.py --sc 0 python test_env_3d_drift.py --sc 1 -python test_env_3d_drift.py --sc 1 --rms-y 0.002 --tilt-z 45.0 -python test_env_3d_drift.py --sc 1 --rms-z 0.002 --tilt-x 45.0 +python test_env_3d_drift.py --sc 1 --rms-y 0.002 --rot-z 45.0 +python test_env_3d_drift.py --sc 1 --rms-z 0.002 --rot-x 45.0 cd sns_linac python test_sns_linac.py --sc 0 diff --git a/examples/Envelope/sns_linac/diagnostics.py b/examples/Envelope/sns_linac/diagnostics.py index 7a4eeee4..d9e1323d 100644 --- a/examples/Envelope/sns_linac/diagnostics.py +++ b/examples/Envelope/sns_linac/diagnostics.py @@ -9,12 +9,25 @@ def __init__(self) -> None: self.twiss_calc = BunchTwissAnalysis() self.position_start = 0.0 - self.history = {} - self.history["s"] = [] - self.history["rms_x"] = [] - self.history["rms_y"] = [] - self.history["rms_z"] = [] - self.history["kin_energy"] = [] + keys = [ + "s", + "kin_energy", + "gamma", + "beta", + "rms_x", + "rms_y", + "rms_z", + "eps_x", + "eps_x_n", + "eps_y", + "eps_y_n", + "eps_z", + "eps_z_n", + "eps_1", + "eps_2", + "eps_3", + ] + self.history = {key: [] for key in keys} def __call__(self, params_dict: dict) -> None: bunch = params_dict["bunch"] @@ -35,24 +48,47 @@ def __call__(self, params_dict: dict) -> None: cov_matrix = np.zeros((6, 6)) for i in range(6): for j in range(6): - cov_matrix[i, j] = cov_matrix[j, i] = self.twiss_calc.getCorrelation( - i, j - ) + cov_matrix[i, j] = self.twiss_calc.getCorrelation(i, j) + cov_matrix[j, i] = cov_matrix[i, j] - xrms = np.sqrt(cov_matrix[0, 0]) - yrms = np.sqrt(cov_matrix[2, 2]) - zrms = np.sqrt(cov_matrix[4, 4]) + centroid = np.zeros(6) + for i in range(6): + centroid[i] = self.twiss_calc.getAverage(i) + + results = {} + results["s"] = position + results["gamma"] = sync_part.gamma() + results["beta"] = sync_part.beta() + results["kin_energy"] = sync_part.kinEnergy() + results["rms_x"] = np.sqrt(cov_matrix[0, 0]) + results["rms_y"] = np.sqrt(cov_matrix[2, 2]) + results["rms_z"] = np.sqrt(cov_matrix[4, 4]) + results["eps_x"] = np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) + results["eps_y"] = np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) + results["eps_z"] = np.sqrt(np.linalg.det(cov_matrix[4:6, 4:6])) + + poisson_matrix = np.zeros_like(cov_matrix) + for i in range(0, 6, 2): + poisson_matrix[i, i + 1] = +1.0 + poisson_matrix[i + 1, i] = -1.0 + eigvals = np.linalg.eigvals(cov_matrix @ poisson_matrix) + eigvals = np.imag(eigvals) + eigvals = eigvals[eigvals > 0] + results["eps_1"] = eigvals[0] + results["eps_2"] = eigvals[1] + results["eps_3"] = eigvals[2] + + results["eps_x_n"] = results["eps_x"] * results["gamma"] * results["beta"] + results["eps_y_n"] = results["eps_y"] * results["gamma"] * results["beta"] + results["eps_z_n"] = results["eps_z"] / results["beta"] + + for key in results: + self.history[key].append(results[key]) message = "" message += " s={:0.3f}".format(position + self.position_start) - message += " xrms={:0.3f}".format(1000.0 * xrms) - message += " yrms={:0.3f}".format(1000.0 * yrms) - message += " zrms={:0.3f}".format(1000.0 * zrms) + message += " rms_x={:0.3f}".format(1000.0 * results["rms_x"]) + message += " rms_y={:0.3f}".format(1000.0 * results["rms_y"]) + message += " rms_z={:0.3f}".format(1000.0 * results["rms_z"]) message += " node={}".format(node.getName()) print(message) - - self.history["s"].append(position + self.position_start) - self.history["rms_x"].append(xrms) - self.history["rms_y"].append(yrms) - self.history["rms_z"].append(zrms) - self.history["kin_energy"].append(sync_part.kinEnergy()) diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index 03197dfb..f4c9e5df 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -191,19 +191,18 @@ def main(args: argparse.Namespace) -> None: action_container.addAction(monitor, AccActionsContainer.EXIT) params_dict = {"old_pos": -1.0, "count": 0, "pos_step": args.sc_path_length_min} - lattice.trackBunch(bunch, paramsDict=params_dict, actionContainer=action_container) - histories["bunch"] = monitor.history # Analysis # -------------------------------------------------------------------------------- - # History: rms + # Process history arrays for mode in histories: for key in histories[mode]: histories[mode][key] = np.array(histories[mode][key]) + # History: rms size plot_kws = {} plot_kws["bunch"] = dict(color="black", lw=0, marker=".", ms=2) plot_kws["envelope"] = dict(color="red", lw=0, marker=".", ms=1) @@ -221,7 +220,27 @@ def main(args: argparse.Namespace) -> None: axs[1].set_ylabel("y rms [mm]") axs[2].set_ylabel("z rms [mm]") axs[2].set_xlabel("s [m]") - plt.savefig(os.path.join(output_dir, "fig_history_rms.png")) + plt.savefig(os.path.join(output_dir, "fig_history_rms_size.png")) + if args.show: + plt.show() + plt.close() + + # History: rms emittance + fig, axs = plt.subplots( + nrows=3, figsize=(10, 5), sharex=True, constrained_layout=True + ) + for mode in ["bunch", "envelope"]: + history = histories[mode] + for ax, key in zip(axs, ["eps_x_n", "eps_y_n", "eps_z_n"]): + ax.plot(history["s"], history[key], **plot_kws[mode], label=mode) + for ax in axs: + ax.legend(loc="lower right") + ax.set_ylim(0.0, ax.get_ylim()[1] * 2.0) + axs[0].set_ylabel(r"$\gamma \beta \varepsilon_x$ [m rad]") + axs[1].set_ylabel(r"$\gamma \beta \varepsilon_y$ [m rad]") + axs[2].set_ylabel(r"$\varepsilon_z / \beta$ [m GeV]") + axs[2].set_xlabel("s [m]") + plt.savefig(os.path.join(output_dir, "fig_history_rms_emittance.png")) if args.show: plt.show() plt.close() diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index e6fa9269..148787d6 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -1,5 +1,6 @@ import os from typing import Any +from typing import Callable import numpy as np @@ -42,7 +43,7 @@ def __init__(self, name="no name"): self.__children = [] self.__childPositions = {} self._envelope_elements = [] - self._envelope_one_turn_matrix = None + self._envelope_total_matrix = None self._envelope_cache_key = None def initialize(self): @@ -362,7 +363,7 @@ def _getEnvelopeSpaceChargeMatrix(self, envelope: Envelope, length: float, sc: s return envelope.sc_matrix_3d(length) raise ValueError(f"Invalid envelope space charge option `{sc}`") - def _iterEnvelopeElements( + def _iterateEnvelopeElements( self, envelope: Envelope, index_start: int = 0, @@ -435,9 +436,9 @@ def iter_child_elements(child_nodes, parent_node): def _applyEnvelopeElements( self, envelope: Envelope, - elements, + elements: list, sc: str | None = None, - update_history=None, + update_history: Callable = None, calculate_matrix: bool = False, ) -> np.ndarray | None: """Apply envelope operations and optionally return their combined matrix.""" @@ -470,9 +471,9 @@ def _precomputeEnvelopeElements( sc: str | None = None, fit: bool = True, ) -> list: - """Precompute envelope operations for a static lattice.""" + """Precompute envelope elements in lattice.""" self._envelope_elements = list( - self._iterEnvelopeElements( + self._iterateEnvelopeElements( envelope, index_start=index_start, index_stop=index_stop, @@ -481,7 +482,7 @@ def _precomputeEnvelopeElements( ) ) self._envelope_cache_key = (index_start, index_stop, sc, fit) - self._envelope_one_turn_matrix = None + self._envelope_total_matrix = None return self._envelope_elements def _getStaticEnvelopeElements( @@ -513,8 +514,7 @@ def trackEnvelope( fit: bool = True, static: bool = False, ) -> None | dict[str, list]: - """ - Track envelope through the lattice. + """Track envelope through the lattice. Args: envelope: Envelope to track. @@ -547,7 +547,7 @@ def trackEnvelope( ) return None - elements = self._iterEnvelopeElements( + elements = self._iterateEnvelopeElements( envelope, index_start=index_start, index_stop=index_stop, @@ -565,10 +565,8 @@ def _trackEnvelopeHistory( fit: bool = True, static: bool = False, ) -> dict[str, list]: - """ - Track envelope and return parameters vs. position in lattice. - """ - history_keys = [ + """Track envelope and return parameters vs. position in lattice.""" + keys = [ "s", "kin_energy", "gamma", @@ -579,24 +577,49 @@ def _trackEnvelopeHistory( "rms_y", "rms_z", "eps_x", + "eps_x_n", "eps_y", + "eps_y_n", + "eps_z", + "eps_z_n", + "eps_1", + "eps_2", + "eps_3", ] - history = {key: [] for key in history_keys} + history = {key: [] for key in keys} def observe(envelope: Envelope) -> dict: cov_matrix = envelope.cov_matrix.copy() - return { - "gamma": envelope.gamma, - "beta": envelope.beta, - "kin_energy": envelope.kin_energy, - "mean": envelope.centroid.copy(), - "cov": cov_matrix, - "rms_x": np.sqrt(cov_matrix[0, 0]), - "rms_y": np.sqrt(cov_matrix[2, 2]), - "rms_z": np.sqrt(cov_matrix[4, 4]), - "eps_x": np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])), - "eps_y": np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])), - } + + results = {} + results["gamma"] = envelope.gamma + results["beta"] = envelope.beta + results["kin_energy"] = envelope.kin_energy + results["mean"] = envelope.centroid.copy() + results["cov"] = cov_matrix + results["rms_x"] = np.sqrt(cov_matrix[0, 0]) + results["rms_y"] = np.sqrt(cov_matrix[2, 2]) + results["rms_z"] = np.sqrt(cov_matrix[4, 4]) + results["eps_x"] = np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) + results["eps_y"] = np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) + results["eps_z"] = np.sqrt(np.linalg.det(cov_matrix[4:6, 4:6])) + + poisson_matrix = np.zeros_like(cov_matrix) + for i in range(0, 6, 2): + poisson_matrix[i, i + 1] = +1.0 + poisson_matrix[i + 1, i] = -1.0 + + eigvals = np.linalg.eigvals(cov_matrix @ poisson_matrix) + eigvals = np.imag(eigvals) + eigvals = eigvals[eigvals > 0] + results["eps_1"] = eigvals[0] + results["eps_2"] = eigvals[1] + results["eps_3"] = eigvals[2] + + results["eps_x_n"] = results["eps_x"] * results["gamma"] * results["beta"] + results["eps_y_n"] = results["eps_y"] * results["gamma"] * results["beta"] + results["eps_z_n"] = results["eps_z"] / results["beta"] + return results def update_history(position: float) -> None: history["s"].append(position) @@ -614,7 +637,7 @@ def update_history(position: float) -> None: fit=fit, ) else: - elements = self._iterEnvelopeElements( + elements = self._iterateEnvelopeElements( envelope, index_start=index_start, index_stop=index_stop, @@ -654,12 +677,12 @@ def _trackEnvelopeStatic( ) if not sc: - if self._envelope_one_turn_matrix is None: - self._envelope_one_turn_matrix = np.identity(7) + if self._envelope_total_matrix is None: + self._envelope_total_matrix = np.identity(7) for element_type, matrix in elements: if element_type != "position": - self._envelope_one_turn_matrix = matrix @ self._envelope_one_turn_matrix - envelope.transform(self._envelope_one_turn_matrix) + self._envelope_total_matrix = matrix @ self._envelope_total_matrix + envelope.transform(self._envelope_total_matrix) return self._applyEnvelopeElements(envelope, elements, sc=sc) @@ -672,9 +695,7 @@ def getEnvelopeTransferMatrix( sc: str | None = None, fit: bool = True, ) -> np.ndarray: - """ - Return total transfer matrix, including linear space charge when requested. - """ + """Return total transfer matrix, including linear space charge when requested.""" elements = self._precomputeEnvelopeElements( envelope, index_start=index_start, From 8c2a4faf6214452dcfa34addc7c3ade27142b936 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Tue, 6 Oct 2026 11:43:00 -0400 Subject: [PATCH 25/42] Clean up envelope history --- py/orbit/lattice/AccLattice.py | 54 ++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index 148787d6..05336c71 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -590,36 +590,40 @@ def _trackEnvelopeHistory( def observe(envelope: Envelope) -> dict: cov_matrix = envelope.cov_matrix.copy() - - results = {} - results["gamma"] = envelope.gamma - results["beta"] = envelope.beta - results["kin_energy"] = envelope.kin_energy - results["mean"] = envelope.centroid.copy() - results["cov"] = cov_matrix - results["rms_x"] = np.sqrt(cov_matrix[0, 0]) - results["rms_y"] = np.sqrt(cov_matrix[2, 2]) - results["rms_z"] = np.sqrt(cov_matrix[4, 4]) - results["eps_x"] = np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) - results["eps_y"] = np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) - results["eps_z"] = np.sqrt(np.linalg.det(cov_matrix[4:6, 4:6])) - poisson_matrix = np.zeros_like(cov_matrix) for i in range(0, 6, 2): - poisson_matrix[i, i + 1] = +1.0 + poisson_matrix[i, i + 1] = 1.0 poisson_matrix[i + 1, i] = -1.0 eigvals = np.linalg.eigvals(cov_matrix @ poisson_matrix) - eigvals = np.imag(eigvals) - eigvals = eigvals[eigvals > 0] - results["eps_1"] = eigvals[0] - results["eps_2"] = eigvals[1] - results["eps_3"] = eigvals[2] - - results["eps_x_n"] = results["eps_x"] * results["gamma"] * results["beta"] - results["eps_y_n"] = results["eps_y"] * results["gamma"] * results["beta"] - results["eps_z_n"] = results["eps_z"] / results["beta"] - return results + eigenemittances = np.imag(eigvals) + eigenemittances = eigenemittances[eigenemittances > 0] + + gamma = envelope.gamma + beta = envelope.beta + emittances = [ + np.sqrt(np.linalg.det(cov_matrix[i : i + 2, i : i + 2])) + for i in (0, 2, 4) + ] + return { + "gamma": gamma, + "beta": beta, + "kin_energy": envelope.kin_energy, + "mean": envelope.centroid.copy(), + "cov": cov_matrix, + "rms_x": np.sqrt(cov_matrix[0, 0]), + "rms_y": np.sqrt(cov_matrix[2, 2]), + "rms_z": np.sqrt(cov_matrix[4, 4]), + "eps_x": emittances[0], + "eps_y": emittances[1], + "eps_z": emittances[2], + "eps_x_n": emittances[0] * gamma * beta, + "eps_y_n": emittances[1] * gamma * beta, + "eps_z_n": emittances[2] / beta, + "eps_1": eigenemittances[0], + "eps_2": eigenemittances[1], + "eps_3": eigenemittances[2], + } def update_history(position: float) -> None: history["s"].append(position) From df9e15842a39d225a2463f98512c94a1c0230ef5 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Tue, 6 Oct 2026 11:52:28 -0400 Subject: [PATCH 26/42] Add synchronous particle info to cache_key, which determines if matrices are pre-computed --- py/orbit/lattice/AccLattice.py | 53 ++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 18 deletions(-) diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index 05336c71..9686d47c 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -281,24 +281,27 @@ def _getNodesInRange(self, index_start: int = 0, index_stop: int = None) -> list index_stop = len(self.__children) - 1 return self.__children[index_start : index_stop + 1] - def _prepareEnvelopeTracking(self, fit: bool = True) -> None: + def _prepareEnvelopeTracking(self, index_start: int, index_stop: int, fit: bool = True) -> None: """Check lattice before tracking envelope.""" if fit: return + + from orbit.py_linac.lattice.LinacAccNodes import Bend + from orbit.teapot.teapot import BendTEAPOT + for node in self.__children: - node_type = type(node) - is_teapot_bend = node_type.__name__ == "BendTEAPOT" and node_type.__module__ == "orbit.teapot.teapot" - is_linac_bend = node_type.__name__ == "Bend" and node_type.__module__ == "orbit.py_linac.lattice.LinacAccNodes" - if is_teapot_bend: - uses_unsupported_fringe = (node.getParam("ea1") != 0.0 and node.getUsageFringeFieldIN()) or ( - node.getParam("ea2") != 0.0 and node.getUsageFringeFieldOUT() - ) + if isinstance(node, BendTEAPOT): + uses_unsupported_fringe = ( + node.getParam("ea1") != 0.0 and node.getUsageFringeFieldIN() + ) or (node.getParam("ea2") != 0.0 and node.getUsageFringeFieldOUT()) if uses_unsupported_fringe: message = f"Found an enabled fringe field with a nonzero edge angle ({node.getName()})." - message += " Analytic envelope tracking supports the wedge transformations only." + message += ( + " Analytic envelope tracking supports the wedge transformations only." + ) message += " Disable the bend fringe field or use `fit=True`." raise RuntimeError(message) - if is_linac_bend: + if isinstance(node, Bend): if node.getParam("ea1") != 0.0 or node.getParam("ea2") != 0.0: message = f"Found bend ea1 or ea2 != 0.0 ({node.getName()}.)" message += " Nonzero edge angles are not yet supported in envelope tracking." @@ -307,6 +310,17 @@ def _prepareEnvelopeTracking(self, fit: bool = True) -> None: message += " `node.setParam('ea2', 0.0)`" raise RuntimeError(message) + @staticmethod + def _getEnvelopeCacheKey(envelope: Envelope, index_start: int, index_stop: int, sc: bool, fit: bool): + sync_part = envelope.sync_part + sync_state = ( + sync_part.kinEnergy(), + sync_part.time(), + sync_part.mass(), + sync_part.charge(), + ) + return index_start, index_stop, sc, fit, sync_state + def _createEnvelopeFitState(self, sync_part) -> dict[str, Any]: """Return items needed to compute best-fit transfer matrix.""" bunch = bunch_from_sync_particle(sync_part) @@ -353,7 +367,9 @@ def _getEnvelopeNodeMatrix( copy_sync_particle(fit_state["bunch"].getSyncParticle(), sync_part) return matrix - def _getEnvelopeSpaceChargeMatrix(self, envelope: Envelope, length: float, sc: str | None) -> np.ndarray | None: + def _getEnvelopeSpaceChargeMatrix( + self, envelope: Envelope, length: float, sc: str | None + ) -> np.ndarray | None: """Return transfer matrix for linear space charge kick.""" if not sc or length <= 0: return None @@ -372,7 +388,7 @@ def _iterateEnvelopeElements( fit: bool = True, ): """Yield matrices, space charge kicks, and position updates in tracking order.""" - self._prepareEnvelopeTracking(fit=fit) + self._prepareEnvelopeTracking(index_start, index_stop, fit=fit) sync_part = envelope.sync_part fit_state = self._createEnvelopeFitState(sync_part) if fit else None @@ -472,6 +488,7 @@ def _precomputeEnvelopeElements( fit: bool = True, ) -> list: """Precompute envelope elements in lattice.""" + cache_key = self._getEnvelopeCacheKey(envelope, index_start, index_stop, sc, fit) self._envelope_elements = list( self._iterateEnvelopeElements( envelope, @@ -481,7 +498,7 @@ def _precomputeEnvelopeElements( fit=fit, ) ) - self._envelope_cache_key = (index_start, index_stop, sc, fit) + self._envelope_cache_key = cache_key self._envelope_total_matrix = None return self._envelope_elements @@ -493,7 +510,7 @@ def _getStaticEnvelopeElements( sc: str | None = None, fit: bool = True, ) -> list: - cache_key = (index_start, index_stop, sc, fit) + cache_key = self._getEnvelopeCacheKey(envelope, index_start, index_stop, sc, fit) if self._envelope_cache_key != cache_key: self._precomputeEnvelopeElements( envelope, @@ -602,8 +619,7 @@ def observe(envelope: Envelope) -> dict: gamma = envelope.gamma beta = envelope.beta emittances = [ - np.sqrt(np.linalg.det(cov_matrix[i : i + 2, i : i + 2])) - for i in (0, 2, 4) + np.sqrt(np.linalg.det(cov_matrix[i : i + 2, i : i + 2])) for i in (0, 2, 4) ] return { "gamma": gamma, @@ -700,15 +716,16 @@ def getEnvelopeTransferMatrix( fit: bool = True, ) -> np.ndarray: """Return total transfer matrix, including linear space charge when requested.""" + envelope_out = envelope.copy() elements = self._precomputeEnvelopeElements( - envelope, + envelope_out, index_start=index_start, index_stop=index_stop, sc=sc, fit=fit, ) return self._applyEnvelopeElements( - envelope, + envelope_out, elements, sc=sc, calculate_matrix=True, From 7ce9974b6091a704d44a4fc0fa4626c34d58e876 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Tue, 6 Oct 2026 12:03:10 -0400 Subject: [PATCH 27/42] Copy synchronous particle when copying envelope --- py/orbit/envelope/envelope.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index 3aeab4a9..148c62ed 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -10,6 +10,8 @@ from .utils import gen_dist from .utils import get_classical_radius from .utils import proj_cov_matrix +from .matrix_fitting import bunch_from_sync_particle +from .matrix_fitting import copy_sync_particle def get_bunch_cov_matrix(bunch: Bunch) -> np.ndarray: @@ -96,8 +98,11 @@ def __init__( self.rms_bunch_length_factor = np.sqrt(12.0) def copy(self): + new_bunch = bunch_from_sync_particle(self.sync_part) + new_sync_part = new_bunch.getSyncParticle() + copy_sync_particle(self.sync_part, new_sync_part) return Envelope( - sync_part=self.sync_part, + sync_part=new_sync_part, cov_matrix=self.cov_matrix.copy(), centroid=self.centroid.copy(), intensity=self.intensity From 4d96bdc5ff85925d77dd4ccad5ad6a64f3994157 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Tue, 6 Oct 2026 12:03:24 -0400 Subject: [PATCH 28/42] Only use start-stop indices when checking lattice before envelope tracking --- py/orbit/lattice/AccLattice.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index 9686d47c..b1219e3f 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -289,7 +289,7 @@ def _prepareEnvelopeTracking(self, index_start: int, index_stop: int, fit: bool from orbit.py_linac.lattice.LinacAccNodes import Bend from orbit.teapot.teapot import BendTEAPOT - for node in self.__children: + for node in self._getNodesInRange(index_start, index_stop): if isinstance(node, BendTEAPOT): uses_unsupported_fringe = ( node.getParam("ea1") != 0.0 and node.getUsageFringeFieldIN() From 64c94719805fb4e84034e80ae3287bc23d427b66 Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Thu, 12 Nov 2026 00:11:50 -0500 Subject: [PATCH 29/42] Refactor envelope tracking code (#170) --- examples/Envelope/sns_linac/diagnostics.py | 52 +- examples/Envelope/sns_linac/test_sns_linac.py | 32 +- examples/Envelope/sns_ring/test_sns_ring.py | 64 +- .../Envelope/sns_ring/test_sns_ring_speed.py | 18 +- examples/Envelope/test_env_2d_fodo.py | 40 +- examples/Envelope/test_env_2d_fodo_speed.py | 1 + examples/Envelope/test_env_3d_drift.py | 40 +- py/orbit/envelope/__init__.py | 2 + py/orbit/envelope/analysis.py | 63 ++ py/orbit/envelope/envelope.py | 23 +- py/orbit/envelope/matrix_fitting.py | 13 +- py/orbit/envelope/meson.build | 2 + py/orbit/envelope/tracking.py | 197 +++++ py/orbit/lattice/AccLattice.py | 493 ++----------- py/orbit/py_linac/lattice/LinacAccNodes.py | 6 + py/orbit/teapot/teapot.py | 41 +- tests/py/orbit/test_env.py | 472 ------------ tests/py/orbit/test_envelope.py | 689 ++++++++++++++++++ 18 files changed, 1135 insertions(+), 1113 deletions(-) create mode 100644 py/orbit/envelope/analysis.py create mode 100644 py/orbit/envelope/tracking.py delete mode 100644 tests/py/orbit/test_env.py create mode 100644 tests/py/orbit/test_envelope.py diff --git a/examples/Envelope/sns_linac/diagnostics.py b/examples/Envelope/sns_linac/diagnostics.py index d9e1323d..9016b7b1 100644 --- a/examples/Envelope/sns_linac/diagnostics.py +++ b/examples/Envelope/sns_linac/diagnostics.py @@ -1,12 +1,9 @@ -import numpy as np - -from orbit.core.bunch import Bunch -from orbit.core.bunch import BunchTwissAnalysis +from orbit.envelope import Envelope +from orbit.envelope import EnvelopeAnalysis class BunchMonitor: def __init__(self) -> None: - self.twiss_calc = BunchTwissAnalysis() self.position_start = 0.0 keys = [ @@ -41,48 +38,9 @@ def __call__(self, params_dict: dict) -> None: params_dict["old_pos"] = position params_dict["count"] += 1 - sync_part = bunch.getSyncParticle() - - self.twiss_calc.analyzeBunch(bunch) - - cov_matrix = np.zeros((6, 6)) - for i in range(6): - for j in range(6): - cov_matrix[i, j] = self.twiss_calc.getCorrelation(i, j) - cov_matrix[j, i] = cov_matrix[i, j] - - centroid = np.zeros(6) - for i in range(6): - centroid[i] = self.twiss_calc.getAverage(i) - - results = {} - results["s"] = position - results["gamma"] = sync_part.gamma() - results["beta"] = sync_part.beta() - results["kin_energy"] = sync_part.kinEnergy() - results["rms_x"] = np.sqrt(cov_matrix[0, 0]) - results["rms_y"] = np.sqrt(cov_matrix[2, 2]) - results["rms_z"] = np.sqrt(cov_matrix[4, 4]) - results["eps_x"] = np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) - results["eps_y"] = np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) - results["eps_z"] = np.sqrt(np.linalg.det(cov_matrix[4:6, 4:6])) - - poisson_matrix = np.zeros_like(cov_matrix) - for i in range(0, 6, 2): - poisson_matrix[i, i + 1] = +1.0 - poisson_matrix[i + 1, i] = -1.0 - eigvals = np.linalg.eigvals(cov_matrix @ poisson_matrix) - eigvals = np.imag(eigvals) - eigvals = eigvals[eigvals > 0] - results["eps_1"] = eigvals[0] - results["eps_2"] = eigvals[1] - results["eps_3"] = eigvals[2] - - results["eps_x_n"] = results["eps_x"] * results["gamma"] * results["beta"] - results["eps_y_n"] = results["eps_y"] * results["gamma"] * results["beta"] - results["eps_z_n"] = results["eps_z"] / results["beta"] - - for key in results: + analysis = EnvelopeAnalysis(Envelope(bunch=bunch)) + results = {"s": position, **analysis.to_dict()} + for key in self.history: self.history[key].append(results[key]) message = "" diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index f4c9e5df..3e3f42f8 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -32,6 +32,7 @@ from orbit.bunch_generators import KVDist3D 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.lattice import AccActionsContainer @@ -64,6 +65,7 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--current", type=float, default=0.038) parser.add_argument("--show", type=int, default=0) parser.add_argument("--seq-stop", type=str, default="CCL2") + parser.add_argument("--fit", type=int, default=1) return parser.parse_args() @@ -145,6 +147,22 @@ def make_bunch(args: argparse.Namespace) -> Bunch: return bunch +class EnvelopeMonitor: + """Collect envelope parameters versus position for plotting.""" + + def __init__(self) -> None: + self.history = {} + + def __call__(self, params_dict: dict) -> None: + envelope = params_dict["envelope"] + s = params_dict["path_length"] + if self.history and self.history["s"][-1] == s: + return + parameters = {"s": s, **EnvelopeAnalysis(envelope).to_dict()} + for key, value in parameters.items(): + self.history.setdefault(key, []).append(value) + + def main(args: argparse.Namespace) -> None: path = pathlib.Path(__file__) @@ -160,13 +178,17 @@ def main(args: argparse.Namespace) -> None: lattice = make_lattice(args) lattice.trackDesignBunch(bunch) - histories = {} - histories["envelope"] = lattice.trackEnvelope( + envelope_monitor = EnvelopeMonitor() + envelope_actions = AccActionsContainer() + envelope_actions.addAction(envelope_monitor, AccActionsContainer.ENTRANCE) + envelope_actions.addAction(envelope_monitor, AccActionsContainer.EXIT) + lattice.trackEnvelope( envelope, - history=True, + action_container=envelope_actions, sc=("3d" if args.sc else None), - fit=True, + fit=args.fit, ) + histories = {"envelope": envelope_monitor.history} # Track bunch bunch = make_bunch(args) @@ -260,7 +282,7 @@ def main(args: argparse.Namespace) -> None: particles = collect_bunch(bunch)["coords"] particles *= 1e3 - env_cov_matrix = envelope.cov_matrix + env_cov_matrix = EnvelopeAnalysis(envelope).covariance() env_cov_matrix *= 1e6 env_centroid = envelope.centroid diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring/test_sns_ring.py index 8e9d5323..15ba2519 100644 --- a/examples/Envelope/sns_ring/test_sns_ring.py +++ b/examples/Envelope/sns_ring/test_sns_ring.py @@ -16,6 +16,7 @@ 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.core.spacecharge import SpaceChargeCalc2p5D from orbit.space_charge.sc2p5d import setSC2p5DAccNodes from orbit.teapot import TEAPOT_Ring @@ -58,6 +59,7 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--fit", type=int, default=1) parser.add_argument("--fringe", type=int, default=0) + parser.add_argument("--static", type=int, default=1) return parser.parse_args() @@ -158,57 +160,27 @@ def main(args: argparse.Namespace) -> None: intensity=args.intensity, ) - history_keys = [ - "rms_x", - "rms_y", - "avg_x", - "avg_y", - "eps_x", - "eps_y", - ] - history = {key: [] for key in history_keys} - - start_time = time.time() - + analysis = EnvelopeAnalysis(envelope) + history = {key: [] for key in ('rms_x', 'rms_y', 'avg_x', 'avg_y', 'eps_x', 'eps_y')} for turn in range(args.turns + 1): if turn > 0: lattice.trackEnvelope( - envelope, - sc=("2d" if args.sc else None), - fit=args.fit, - static=True, + envelope, sc=("2d" if args.sc else None), fit=args.fit, static=args.static, ) - cov_matrix = envelope.cov_matrix - centroid = envelope.centroid - - rms_x = 1000.0 * math.sqrt(cov_matrix[0, 0]) - rms_y = 1000.0 * math.sqrt(cov_matrix[2, 2]) - avg_x = 1000.0 * centroid[0] - avg_y = 1000.0 * centroid[2] - eps_x = 1e6 * np.sqrt(np.linalg.det(cov_matrix[0:2, 0:2])) - eps_y = 1e6 * np.sqrt(np.linalg.det(cov_matrix[2:4, 2:4])) - - message = "" - message += " turn={}".format(turn) - message += " time={:0.3f}".format(time.time() - start_time) - message += " eps_x={:0.2f}".format(eps_x) - message += " eps_y={:0.2f}".format(eps_y) - message += " xrms={:0.2f}".format(rms_x) - message += " yrms={:0.2f}".format(rms_y) - message += " xavg={:0.2f}".format(avg_x) - message += " yavg={:0.2f}".format(avg_y) - print(message) - - history["rms_x"].append(rms_x) - history["rms_y"].append(rms_y) - history["avg_x"].append(avg_x) - history["avg_y"].append(avg_y) - history["eps_x"].append(eps_x) - history["eps_y"].append(eps_y) + rms = 1000.0 * analysis.rms() + mean = 1000.0 * analysis.centroid() + eps = 1e6 * analysis.emittances() + parameters = { + "rms_x": rms[0], "rms_y": rms[1], + "avg_x": mean[0], "avg_y": mean[2], + "eps_x": eps[0], "eps_y": eps[1], + } + for key, value in parameters.items(): + history[key].append(value) + print(f"turn={turn}", parameters) - histories = {} - histories["envelope"] = copy.deepcopy(history) + histories = {"envelope": history} # Track bunch # ------------------------------------------------------------------------------ @@ -345,7 +317,7 @@ def main(args: argparse.Namespace) -> None: particles = collect_bunch(bunch)["coords"] particles[:, :4] *= 1000.0 - env_cov_matrix = envelope.cov_matrix + env_cov_matrix = EnvelopeAnalysis(envelope).covariance() env_cov_matrix[:4, :4] *= 1000.0**2 env_centroid = envelope.centroid diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring/test_sns_ring_speed.py index c7dfa176..d081f250 100644 --- a/examples/Envelope/sns_ring/test_sns_ring_speed.py +++ b/examples/Envelope/sns_ring/test_sns_ring_speed.py @@ -29,12 +29,13 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--kin-energy", type=float, default=1.300) parser.add_argument("--intensity", type=float, default=2e14) - parser.add_argument("--nparts", type=int, default=10_000) + parser.add_argument("--nparts", type=int, default=25_000) parser.add_argument("--turns", type=int, default=25) parser.add_argument("--sc", type=int, default=0) parser.add_argument("--sc-grid", type=int, default=64) parser.add_argument("--fringe", type=int, default=0) parser.add_argument("--fit", type=int, default=1) + parser.add_argument("--static", type=int, default=1) return parser.parse_args() @@ -51,11 +52,6 @@ def main(args: argparse.Namespace) -> None: except: pass - for node in lattice.getNodes(): - if type(node) is BendTEAPOT: - node.setParam("ea1", 0.0) - node.setParam("ea2", 0.0) - for node in lattice.getNodes(): max_length = 1.0 if node.getLength() > max_length: @@ -95,7 +91,6 @@ def main(args: argparse.Namespace) -> None: cov_matrix=cov_matrix_init, intensity=args.intensity, ) - envelope_sc = "2d" if args.sc else None start_time = time.time() @@ -103,7 +98,12 @@ def main(args: argparse.Namespace) -> None: profiler.enable() for turn in trange(args.turns): - lattice.trackEnvelope(envelope, sc=envelope_sc, fit=args.fit, static=True) + lattice.trackEnvelope( + envelope, + static=args.static, + fit=args.fit, + sc=("2d" if args.sc else None) + ) time_per_turn = (time.time() - start_time) / args.turns @@ -157,4 +157,4 @@ def main(args: argparse.Namespace) -> None: if __name__ == "__main__": - main(parse_args()) \ No newline at end of file + main(parse_args()) diff --git a/examples/Envelope/test_env_2d_fodo.py b/examples/Envelope/test_env_2d_fodo.py index b7f34a7a..494190c0 100644 --- a/examples/Envelope/test_env_2d_fodo.py +++ b/examples/Envelope/test_env_2d_fodo.py @@ -4,8 +4,8 @@ import copy import math import os -import pathlib import time +from pathlib import Path import numpy as np import matplotlib.pyplot as plt @@ -15,6 +15,7 @@ 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 @@ -60,8 +61,7 @@ def parse_args() -> argparse.Namespace: def main(args: argparse.Namespace) -> None: - path = pathlib.Path(__file__) - output_dir = os.path.join("outputs", path.stem, time.strftime("%Y%m%d_%H%M%S")) + 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 @@ -145,30 +145,22 @@ def main(args: argparse.Namespace) -> None: envelope_sc = "2d" if args.sc else None - history = {"xrms": [], "yrms": [], "xavg": [], "yavg": []} + 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) - - cov_matrix = envelope.cov_matrix - centroid = envelope.centroid - - xrms = 1000.0 * math.sqrt(cov_matrix[0, 0]) - yrms = 1000.0 * math.sqrt(cov_matrix[2, 2]) - xavg = 1000.0 * centroid[0] - yavg = 1000.0 * centroid[2] - - print( - f"turn={turn} xrms={xrms:0.3f} yrms={yrms:0.3f} xavg={xavg:0.3f} yavg={yavg:0.3f}" - ) + lattice.trackEnvelope( + envelope, sc=envelope_sc, fit=args.fit, static=True, + ) - history["xrms"].append(xrms) - history["yrms"].append(yrms) - history["xavg"].append(xavg) - history["yavg"].append(yavg) + 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 = {} - histories["envelope"] = copy.deepcopy(history) + histories = {"envelope": history} # Track bunch # ------------------------------------------------------------------------------ @@ -271,7 +263,7 @@ def main(args: argparse.Namespace) -> None: particles = collect_bunch(bunch)["coords"] particles[:, :4] *= 1000.0 - env_cov_matrix = envelope.cov_matrix + env_cov_matrix = EnvelopeAnalysis(envelope).covariance() env_cov_matrix[:4, :4] *= 1000.0**2 env_centroid = envelope.centroid diff --git a/examples/Envelope/test_env_2d_fodo_speed.py b/examples/Envelope/test_env_2d_fodo_speed.py index dc4e261b..ec6c4f1a 100644 --- a/examples/Envelope/test_env_2d_fodo_speed.py +++ b/examples/Envelope/test_env_2d_fodo_speed.py @@ -94,6 +94,7 @@ profiler.enable() for turn in trange(args.turns): + # No observer: measure tracking without collecting diagnostics. lattice.trackEnvelope(envelope, sc=envelope_sc, fit=args.fit, static=True) time_per_turn = (time.time() - start_time) / args.turns diff --git a/examples/Envelope/test_env_3d_drift.py b/examples/Envelope/test_env_3d_drift.py index 0f9ca51f..ff471a58 100644 --- a/examples/Envelope/test_env_3d_drift.py +++ b/examples/Envelope/test_env_3d_drift.py @@ -20,6 +20,7 @@ from orbit.core.spacecharge import SpaceChargeCalc3D from orbit.bunch_utils import collect_bunch from orbit.envelope import Envelope +from orbit.envelope import EnvelopeAnalysis from orbit.space_charge.sc3d import setSC3DAccNodes from orbit.teapot import DriftTEAPOT from orbit.teapot import TEAPOT_Lattice @@ -134,25 +135,24 @@ def main(args: argparse.Namespace) -> None: envelope_sc = "3d" if args.sc else None - history = {"xrms": [], "yrms": [], "zrms": []} + analysis = EnvelopeAnalysis(envelope) + history = {key: [] for key in ('s', 'xrms', 'yrms', 'zrms')} for turn in range(args.turns): if turn > 0: - lattice.trackEnvelope(envelope, sc=envelope_sc, fit=args.fit) - - cov_matrix = envelope.cov_matrix - - xrms = 1000.0 * math.sqrt(cov_matrix[0, 0]) - yrms = 1000.0 * math.sqrt(cov_matrix[2, 2]) - zrms = 1000.0 * math.sqrt(cov_matrix[4, 4]) * envelope.gamma - - history["xrms"].append(xrms) - history["yrms"].append(yrms) - history["zrms"].append(zrms) + lattice.trackEnvelope( + envelope, sc=envelope_sc, fit=args.fit, + ) - print(f"turn={turn} xrms={xrms:0.3f} yrms={yrms:0.3f} zrms={zrms:0.3f}") + rms = 1000.0 * analysis.rms() + parameters = { + "s": turn * lattice.getLength(), + "xrms": rms[0], "yrms": rms[1], "zrms": rms[2] * envelope.gamma, + } + for key, value in parameters.items(): + history[key].append(value) + print(f"turn={turn}", parameters) - histories = {} - histories["envelope"] = copy.deepcopy(history) + histories = {"envelope": history} # Track bunch # ------------------------------------------------------------------------------ @@ -175,7 +175,7 @@ def main(args: argparse.Namespace) -> None: sc_path_length_min = 0.01 sc_nodes = setSC3DAccNodes(lattice, sc_path_length_min, sc_calc) - history = {"xrms": [], "yrms": [], "zrms": []} + history = {"s": [], "xrms": [], "yrms": [], "zrms": []} for turn in range(args.turns): if turn > 0: lattice.trackBunch(bunch) @@ -193,6 +193,7 @@ def main(args: argparse.Namespace) -> None: yrms = 1000.0 * math.sqrt(cov_matrix[2, 2]) zrms = 1000.0 * math.sqrt(cov_matrix[4, 4]) * bunch.getSyncParticle().gamma() + history["s"].append(turn * lattice.getLength()) history["xrms"].append(xrms) history["yrms"].append(yrms) history["zrms"].append(zrms) @@ -221,9 +222,10 @@ def main(args: argparse.Namespace) -> None: 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.plot(histories[model]["s"], histories[model][key], + marker=".", lw=lw, color=color, label=model) ax.set_ylim(0.0, ax.get_ylim()[1] * 1.2) - ax.set_xlabel("s [mm]") + ax.set_xlabel("s [m]") ax.set_ylabel("rms size [mm]") ax.legend(loc="upper left") plt.savefig(os.path.join(output_dir, f"fig_{key}")) @@ -233,7 +235,7 @@ def main(args: argparse.Namespace) -> None: particles = collect_bunch(bunch)["coords"] particles *= 1e3 - env_cov_matrix = envelope.cov_matrix + env_cov_matrix = EnvelopeAnalysis(envelope).covariance() env_cov_matrix *= 1e6 env_centroid = envelope.centroid diff --git a/py/orbit/envelope/__init__.py b/py/orbit/envelope/__init__.py index febf3854..031a5fbd 100644 --- a/py/orbit/envelope/__init__.py +++ b/py/orbit/envelope/__init__.py @@ -1,3 +1,5 @@ from .envelope import Envelope +from .analysis import EnvelopeAnalysis from .matrix_fitting import fit_transfer_matrix from .matrix_fitting import orbit_matrix_to_numpy +from .tracking import EnvelopeTracker diff --git a/py/orbit/envelope/analysis.py b/py/orbit/envelope/analysis.py new file mode 100644 index 00000000..7bd06898 --- /dev/null +++ b/py/orbit/envelope/analysis.py @@ -0,0 +1,63 @@ +from typing import Any + +import numpy as np + +from .envelope import Envelope + + +class EnvelopeAnalysis: + def __init__(self, envelope: Envelope) -> None: + self.envelope = envelope + + def centroid(self) -> np.ndarray: + return self.envelope.centroid.copy() + + def covariance(self) -> np.ndarray: + return self.envelope.cov_matrix.copy() + + def rms(self, axis: int | None = None) -> np.ndarray | float: + sizes = np.sqrt(np.diag(self.envelope.cov_matrix)[::2]) + return sizes if axis is None else sizes[axis] + + def emittances(self, normalized: bool = False) -> np.ndarray: + cov = self.envelope.cov_matrix + values = np.array( + [np.sqrt(np.linalg.det(cov[i : i + 2, i : i + 2])) for i in (0, 2, 4)] + ) + if normalized: + beta = self.envelope.beta + values *= np.array([beta * self.envelope.gamma] * 2 + [1.0 / beta]) + return values + + def eigenemittances(self) -> np.ndarray: + poisson = np.zeros((6, 6)) + for i in (0, 2, 4): + poisson[i, i + 1] = 1.0 + poisson[i + 1, i] = -1.0 + eigenvalues = np.linalg.eigvals(self.envelope.cov_matrix @ poisson) + return np.sort(np.abs(eigenvalues.imag))[::2] + + def to_dict(self) -> dict[str, Any]: + rms = self.rms() + eps = self.emittances() + eps_n = self.emittances(normalized=True) + eigen = self.eigenemittances() + return { + "kin_energy": self.envelope.kin_energy, + "gamma": self.envelope.gamma, + "beta": self.envelope.beta, + "mean": self.centroid(), + "cov": self.covariance(), + "rms_x": rms[0], + "rms_y": rms[1], + "rms_z": rms[2], + "eps_x": eps[0], + "eps_y": eps[1], + "eps_z": eps[2], + "eps_x_n": eps_n[0], + "eps_y_n": eps_n[1], + "eps_z_n": eps_n[2], + "eps_1": eigen[0], + "eps_2": eigen[1], + "eps_3": eigen[2], + } diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index 148c62ed..931ca5c1 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -11,7 +11,6 @@ from .utils import get_classical_radius from .utils import proj_cov_matrix from .matrix_fitting import bunch_from_sync_particle -from .matrix_fitting import copy_sync_particle def get_bunch_cov_matrix(bunch: Bunch) -> np.ndarray: @@ -46,7 +45,7 @@ def build_diag_matrix_from_xyz_eig(eigenvectors: np.ndarray) -> np.ndarray: class Envelope: - """Represents beam envelope/centroid. + """Represents the phase space covariance matrix and centroid. Attributes: sync_part: Synchronous particle. @@ -80,6 +79,7 @@ def __init__( intensity = bunch.getSize() * bunch.macroSize() self.sync_part = sync_part + self._reference_bunch = bunch self.centroid = centroid if self.centroid is None: @@ -100,13 +100,16 @@ def __init__( def copy(self): new_bunch = bunch_from_sync_particle(self.sync_part) new_sync_part = new_bunch.getSyncParticle() - copy_sync_particle(self.sync_part, new_sync_part) - return Envelope( + new_envelope = Envelope( sync_part=new_sync_part, cov_matrix=self.cov_matrix.copy(), centroid=self.centroid.copy(), - intensity=self.intensity + intensity=self.intensity, ) + new_envelope._reference_bunch = new_bunch + new_envelope.rms_bunch_length_factor = self.rms_bunch_length_factor + new_envelope.classical_radius = self.classical_radius + return new_envelope @property def kin_energy(self) -> float: @@ -136,7 +139,7 @@ def momentum(self) -> float: def sc_factor(self) -> float: return 2.0 * self.intensity * self.classical_radius / (self.beta ** 2 * self.gamma ** 3) - def rms(self, axis: int = None) -> float | np.ndarray: + def rms(self, axis: int | None = None) -> float | np.ndarray: rms_arr = np.sqrt(np.diag(self.cov_matrix)) return rms_arr[axis] @@ -270,3 +273,11 @@ def sc_matrix_3d(self, length: float) -> np.ndarray: # Convert from z' to dE return convert_matrix_zp_to_dE(M, self.sync_part) + + def sc_matrix(self, length: float, model: str) -> np.ndarray: + if model == "2d": + return self.sc_matrix_2d(length) + elif model == "3d": + return self.sc_matrix_3d(length) + else: + raise ValueError(f"Unknown space charge model {model}") \ No newline at end of file diff --git a/py/orbit/envelope/matrix_fitting.py b/py/orbit/envelope/matrix_fitting.py index ad0b90fa..83a7435e 100644 --- a/py/orbit/envelope/matrix_fitting.py +++ b/py/orbit/envelope/matrix_fitting.py @@ -49,6 +49,7 @@ def fit_node_transfer_matrix( if matrix_generator is None: matrix_generator = MatrixGenerator() + if lost_bunch is None: lost_bunch = Bunch() bunch.copyEmptyBunchTo(lost_bunch) @@ -57,18 +58,18 @@ def fit_node_transfer_matrix( matrix.unit() matrix_generator.initBunch(bunch) - params = {} if params_dict is None else params_dict.copy() - params["bunch"] = bunch - params["lostbunch"] = lost_bunch - params["node"] = node + params_dict = {} if params_dict is None else params_dict.copy() + params_dict["bunch"] = bunch + params_dict["lostbunch"] = lost_bunch + params_dict["node"] = node if parent_node is not None: - params["parentNode"] = parent_node + params_dict["parentNode"] = parent_node active_part_index = node.getActivePartIndex() if part_index >= 0: node.setActivePartIndex(part_index) try: - node.track(params) + node.track(params_dict) finally: node.setActivePartIndex(active_part_index) diff --git a/py/orbit/envelope/meson.build b/py/orbit/envelope/meson.build index c5d3846b..be25a806 100644 --- a/py/orbit/envelope/meson.build +++ b/py/orbit/envelope/meson.build @@ -1,6 +1,8 @@ py_sources = files([ '__init__.py', 'envelope.py', + 'analysis.py', + 'tracking.py', 'matrix_fitting.py', 'utils.py' ]) diff --git a/py/orbit/envelope/tracking.py b/py/orbit/envelope/tracking.py new file mode 100644 index 00000000..84b4cdc2 --- /dev/null +++ b/py/orbit/envelope/tracking.py @@ -0,0 +1,197 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any +from typing import TYPE_CHECKING + +import numpy as np + +from orbit.core.bunch import Bunch +from orbit.core.bunch import SyncParticle +from orbit.core.teapot_base import MatrixGenerator + +from .envelope import Envelope +from .matrix_fitting import bunch_from_sync_particle +from .matrix_fitting import copy_sync_particle +from .matrix_fitting import fit_node_transfer_matrix + +if TYPE_CHECKING: + from orbit.lattice import AccActionsContainer + from orbit.lattice import AccLattice + from orbit.lattice import AccNode + + +ParamsDict = dict[str, Any] + + +@dataclass +class NodeMap: + matrix: np.ndarray | None + reference_position: tuple[float, float, float] + reference_momentum: tuple[float, float, float] + reference_x_axis: tuple[float, float, float] + time_advance: float + + def update_sync_particle(self, sync_part: SyncParticle) -> None: + current_time = sync_part.time() + sync_part.rVector(self.reference_position) + sync_part.pVector(self.reference_momentum) + sync_part.nxVector(self.reference_x_axis) + sync_part.time(current_time + self.time_advance) + + +class EnvelopeTracker: + def __init__( + self, + lattice: AccLattice, + index_start: int = 0, + index_stop: int | None = None, + fit: bool = True, + fallback: bool = True, + ) -> None: + self.lattice = lattice + + self.index_start = index_start + self.index_start = max(self.index_start, 0) + + self.index_stop = index_stop + if self.index_stop is None or self.index_stop < 0: + self.index_stop = len(self.lattice.getNodes()) + else: + self.index_stop = min(self.index_stop + 1, len(self.lattice.getNodes())) + + self.fit = fit + self.fallback = fallback + + self._node_maps = None + self._reference_bunch = None + self._matrix_generator = None + + def track( + self, + envelope: Envelope, + sc: str | None = None, + params_dict: ParamsDict | None = None, + action_container: AccActionsContainer | None = None, + return_matrix: bool = False, + store_maps: bool = False, + ) -> np.ndarray | None: + + from orbit.lattice import AccActionsContainer + from orbit.lattice import AccLattice + from orbit.lattice import AccNode + + if sc not in (None, False, "2d", "3d"): + raise ValueError(f"Invalid envelope space charge option `{sc}`") + + if params_dict is None: + params_dict = {} + + if action_container is None: + action_container = AccActionsContainer() + + params_dict.update( + envelope=envelope, + lattice=self.lattice, + action_container=action_container + ) + params_dict.setdefault("path_length", 0.0) + if hasattr(self.lattice, "getUseRealCharge"): + params_dict.setdefault("useCharge", self.lattice.getUseRealCharge()) + + total_matrix = None + if return_matrix: + total_matrix = np.eye(7) + + self._reference_bunch = None + self._matrix_generator = None + + node_maps = {} if store_maps else self._node_maps + identity_matrix = np.eye(7) if store_maps else None + + def apply_matrix(matrix: np.ndarray | None) -> None: + nonlocal total_matrix + if matrix is not None: + envelope.transform(matrix) + if total_matrix is not None: + total_matrix = matrix @ total_matrix + + def push_envelope(params_dict: ParamsDict) -> None: + node = params_dict["node"] + part_index = node.getActivePartIndex() + if sc: + length = node.getLength(part_index) + if length > 0: + apply_matrix(envelope.sc_matrix(length, model=sc)) + if node_maps is not None and not store_maps: + node_map = node_maps[node, part_index] + else: + node_map = self._get_node_map(params_dict) + if store_maps: + if node_map.matrix is not None and np.array_equal(node_map.matrix, identity_matrix): + node_map.matrix = None + node_maps[node, part_index] = node_map + node_map.update_sync_particle(envelope.sync_part) + apply_matrix(node_map.matrix) + + action_container.addAction(push_envelope, AccNode.BODY) + try: + if self.index_start < self.index_stop: + self.lattice.trackActions( + action_container, + params_dict, + self.index_start, + self.index_stop - 1, + ) + finally: + action_container.removeAction(push_envelope, AccNode.BODY) + if store_maps: + self._node_maps = node_maps + return total_matrix + + def precompute(self, envelope: Envelope, params_dict: ParamsDict | None = None) -> None: + self.track( + envelope=envelope.copy(), + params_dict=None if params_dict is None else params_dict.copy(), + store_maps=True, + ) + + def _get_node_map(self, params_dict: ParamsDict) -> NodeMap: + node = params_dict["node"] + sync_part = params_dict["envelope"].sync_part + if self._reference_bunch is None: + self._reference_bunch = bunch_from_sync_particle(sync_part) + reference_sync_part = self._reference_bunch.getSyncParticle() + copy_sync_particle(sync_part, reference_sync_part) + start_time = sync_part.time() + part_index = node.getActivePartIndex() + use_fit = self.fit + + if not use_fit: + try: + matrix = node.getMatrix(reference_sync_part, part_index=part_index) + except NotImplementedError: + if not self.fallback: + raise + copy_sync_particle(sync_part, reference_sync_part) + use_fit = True + + if use_fit: + if self._matrix_generator is None: + self._matrix_generator = MatrixGenerator() + matrix = fit_node_transfer_matrix( + node=node, + bunch=self._reference_bunch, + part_index=part_index, + parent_node=params_dict["parentNode"], + matrix_generator=self._matrix_generator, + params_dict=params_dict, + ) + + return NodeMap( + matrix=matrix, + reference_position=tuple(reference_sync_part.rVector()), + reference_momentum=tuple(reference_sync_part.pVector()), + reference_x_axis=tuple(reference_sync_part.nxVector()), + time_advance=reference_sync_part.time() - start_time, + ) diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index b1219e3f..d7007025 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -1,16 +1,9 @@ import os -from typing import Any -from typing import Callable import numpy as np -from orbit.core.bunch import Bunch -from orbit.core.bunch import SyncParticle -from orbit.core.teapot_base import MatrixGenerator from orbit.envelope import Envelope -from orbit.envelope.matrix_fitting import bunch_from_sync_particle -from orbit.envelope.matrix_fitting import copy_sync_particle -from orbit.envelope.matrix_fitting import fit_node_transfer_matrix +from orbit.envelope import EnvelopeTracker from orbit.utils import orbitFinalize from orbit.utils import NamedObject @@ -42,9 +35,7 @@ def __init__(self, name="no name"): self.__isInitialized = False self.__children = [] self.__childPositions = {} - self._envelope_elements = [] - self._envelope_total_matrix = None - self._envelope_cache_key = None + self._envelope_tracker: EnvelopeTracker | None = None def initialize(self): """ @@ -72,6 +63,8 @@ def initialize(self): d = [0.0] posn = {} + self._envelope_tracker = None + def accNodeExitAction(paramsDict): """ Nonbound function. Sets lattice length and node @@ -276,457 +269,67 @@ def trackActions(self, actionsContainer, paramsDict={}, index_start=-1, index_st paramsDict["parentNode"] = self node.trackActions(actionsContainer, paramsDict) - def _getNodesInRange(self, index_start: int = 0, index_stop: int = None) -> list[AccNode]: - if index_stop is None: - index_stop = len(self.__children) - 1 - return self.__children[index_start : index_stop + 1] - - def _prepareEnvelopeTracking(self, index_start: int, index_stop: int, fit: bool = True) -> None: - """Check lattice before tracking envelope.""" - if fit: - return - - from orbit.py_linac.lattice.LinacAccNodes import Bend - from orbit.teapot.teapot import BendTEAPOT - - for node in self._getNodesInRange(index_start, index_stop): - if isinstance(node, BendTEAPOT): - uses_unsupported_fringe = ( - node.getParam("ea1") != 0.0 and node.getUsageFringeFieldIN() - ) or (node.getParam("ea2") != 0.0 and node.getUsageFringeFieldOUT()) - if uses_unsupported_fringe: - message = f"Found an enabled fringe field with a nonzero edge angle ({node.getName()})." - message += ( - " Analytic envelope tracking supports the wedge transformations only." - ) - message += " Disable the bend fringe field or use `fit=True`." - raise RuntimeError(message) - if isinstance(node, Bend): - if node.getParam("ea1") != 0.0 or node.getParam("ea2") != 0.0: - message = f"Found bend ea1 or ea2 != 0.0 ({node.getName()}.)" - message += " Nonzero edge angles are not yet supported in envelope tracking." - message += " Please set them to zero:" - message += " `node.setParam('ea1', 0.0)`" - message += " `node.setParam('ea2', 0.0)`" - raise RuntimeError(message) - - @staticmethod - def _getEnvelopeCacheKey(envelope: Envelope, index_start: int, index_stop: int, sc: bool, fit: bool): - sync_part = envelope.sync_part - sync_state = ( - sync_part.kinEnergy(), - sync_part.time(), - sync_part.mass(), - sync_part.charge(), - ) - return index_start, index_stop, sc, fit, sync_state - - def _createEnvelopeFitState(self, sync_part) -> dict[str, Any]: - """Return items needed to compute best-fit transfer matrix.""" - bunch = bunch_from_sync_particle(sync_part) - lost_bunch = Bunch() - bunch.copyEmptyBunchTo(lost_bunch) - params_dict = {} - if hasattr(self, "getUseRealCharge"): - params_dict["useCharge"] = self.getUseRealCharge() - return { - "bunch": bunch, - "lost_bunch": lost_bunch, - "matrix_generator": MatrixGenerator(), - "params_dict": params_dict, - } - - def _getEnvelopeNodeMatrix( - self, - node: AccNode, - sync_part: SyncParticle, - part_index: int | None = None, - parent_node: AccNode = None, - fit_state: dict | None = None, - ) -> np.ndarray | None: - """Return 7 x 7 transfer matrix from node and synchronous particle. - - If `fit_state` is provided, the matrix will be fit to input/output - coordinates of a particle launched near the origin. Otherwise the - analytic matrix will be used (if implemented). - """ - if fit_state is None: - if part_index is None: - return node.getMatrix(sync_part) - return node.getMatrix(sync_part, part_index=part_index) - - matrix = fit_node_transfer_matrix( - node, - fit_state["bunch"], - part_index=0 if part_index is None else part_index, - parent_node=parent_node, - matrix_generator=fit_state["matrix_generator"], - lost_bunch=fit_state["lost_bunch"], - params_dict=fit_state["params_dict"], - ) - copy_sync_particle(fit_state["bunch"].getSyncParticle(), sync_part) - return matrix - - def _getEnvelopeSpaceChargeMatrix( - self, envelope: Envelope, length: float, sc: str | None - ) -> np.ndarray | None: - """Return transfer matrix for linear space charge kick.""" - if not sc or length <= 0: - return None - if sc == "2d": - return envelope.sc_matrix_2d(length) - if sc == "3d": - return envelope.sc_matrix_3d(length) - raise ValueError(f"Invalid envelope space charge option `{sc}`") - - def _iterateEnvelopeElements( - self, - envelope: Envelope, - index_start: int = 0, - index_stop: int = None, - sc: str | None = None, - fit: bool = True, - ): - """Yield matrices, space charge kicks, and position updates in tracking order.""" - self._prepareEnvelopeTracking(index_start, index_stop, fit=fit) - sync_part = envelope.sync_part - fit_state = self._createEnvelopeFitState(sync_part) if fit else None - - def iter_child_elements(child_nodes, parent_node): - for child_node in child_nodes: - matrix = self._getEnvelopeNodeMatrix( - child_node, - sync_part, - parent_node=parent_node, - fit_state=fit_state, - ) - if matrix is not None: - yield child_node, matrix - - for node in self._getNodesInRange(index_start, index_stop): - yield from iter_child_elements( - node.getChildNodes(AccNode.ENTRANCE), - node, - ) - - for part_index in range(node.getnParts()): - yield from iter_child_elements( - node.getChildNodes( - AccNode.BODY, - part_index, - place_in_part=AccNode.BEFORE, - ), - node, - ) - - length = node.getLength(part_index) - if sc and length > 0: - yield "sc", length - - matrix = self._getEnvelopeNodeMatrix( - node, - sync_part, - part_index=part_index, - parent_node=self, - fit_state=fit_state, - ) - if matrix is not None: - yield node, matrix - - yield "position", length - - yield from iter_child_elements( - node.getChildNodes( - AccNode.BODY, - part_index, - place_in_part=AccNode.AFTER, - ), - node, - ) - - yield from iter_child_elements( - node.getChildNodes(AccNode.EXIT), - node, - ) - - def _applyEnvelopeElements( - self, - envelope: Envelope, - elements: list, - sc: str | None = None, - update_history: Callable = None, - calculate_matrix: bool = False, - ) -> np.ndarray | None: - """Apply envelope operations and optionally return their combined matrix.""" - total_matrix = np.identity(7) if calculate_matrix else None - path_length = 0.0 - - for element_type, value in elements: - if element_type == "position": - path_length += value - if update_history is not None: - update_history(path_length) - continue - - if element_type == "sc": - matrix = self._getEnvelopeSpaceChargeMatrix(envelope, value, sc) - else: - matrix = value - - envelope.transform(matrix) - if calculate_matrix: - total_matrix = matrix @ total_matrix - - return total_matrix - - def _precomputeEnvelopeElements( - self, - envelope: Envelope, - index_start: int = 0, - index_stop: int = None, - sc: str | None = None, - fit: bool = True, - ) -> list: - """Precompute envelope elements in lattice.""" - cache_key = self._getEnvelopeCacheKey(envelope, index_start, index_stop, sc, fit) - self._envelope_elements = list( - self._iterateEnvelopeElements( - envelope, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - ) - ) - self._envelope_cache_key = cache_key - self._envelope_total_matrix = None - return self._envelope_elements - - def _getStaticEnvelopeElements( - self, - envelope: Envelope, - index_start: int = 0, - index_stop: int = None, - sc: str | None = None, - fit: bool = True, - ) -> list: - cache_key = self._getEnvelopeCacheKey(envelope, index_start, index_stop, sc, fit) - if self._envelope_cache_key != cache_key: - self._precomputeEnvelopeElements( - envelope, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - ) - return self._envelope_elements - def trackEnvelope( self, envelope: Envelope, index_start: int = 0, - index_stop: int = None, + index_stop: int | None = None, sc: str | None = None, - history: bool = False, + params_dict: dict | None = None, + action_container: AccActionsContainer | None = None, fit: bool = True, + fallback: bool = True, static: bool = False, - ) -> None | dict[str, list]: - """Track envelope through the lattice. + return_matrix: bool = False, + ) -> np.ndarray | None: + """Tracks envelope through the lattice. Args: - envelope: Envelope to track. - index_start: Index of first node in sublattice. - index_stop: Index of last node in sublattice. - sc: Whether to include space charge kicks. - history: Whether to return beam parameters vs. position in lattice. - fit: Whether to use best-fit transfer matrices or analytic - transfer matrices. - static: Whether to pre-compute transfer matrices before - tracking. This works for as long as there are no time-dependent - nodes in the lattice. - """ - if history: - return self._trackEnvelopeHistory( - envelope, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - static=static, - ) - if static: - self._trackEnvelopeStatic( - envelope, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - ) - return None - - elements = self._iterateEnvelopeElements( - envelope, + envelope: Beam envelope. + index_start: First node index. + index_stop: Last node index. + sc: Space charge model {None, "2d", "3d"}. + params_dict: Parameter dictionary. + action_container: AccActions container. + fit: Whether to use best-fit transfer matrices instead of analytic matrices. + fallback: When fit=False, fall back to best-fit transfer matrix for nodes + without analytic matrix. + static: If True, precompute transfer matrices and reuse on future calls. + This assumes there are no time-dependent nodes in the lattice and + no acceleration. Call initialize() or track once with static=False + to clear matrices after changing the lattice or reference beam. + return_matrix: Whether to compute total transfer matrix. + + Returns: + If `return_matrix`, returns the total transfer matrix (including linear + space charge). Otherwise, returns None. + """ + tracker = EnvelopeTracker( + self, index_start=index_start, index_stop=index_stop, - sc=sc, fit=fit, + fallback=fallback, ) - self._applyEnvelopeElements(envelope, elements, sc=sc) - def _trackEnvelopeHistory( - self, - envelope: Envelope, - index_start: int = 0, - index_stop: int = None, - sc: str | None = None, - fit: bool = True, - static: bool = False, - ) -> dict[str, list]: - """Track envelope and return parameters vs. position in lattice.""" - keys = [ - "s", - "kin_energy", - "gamma", - "beta", - "mean", - "cov", - "rms_x", - "rms_y", - "rms_z", - "eps_x", - "eps_x_n", - "eps_y", - "eps_y_n", - "eps_z", - "eps_z_n", - "eps_1", - "eps_2", - "eps_3", - ] - history = {key: [] for key in keys} - - def observe(envelope: Envelope) -> dict: - cov_matrix = envelope.cov_matrix.copy() - poisson_matrix = np.zeros_like(cov_matrix) - for i in range(0, 6, 2): - poisson_matrix[i, i + 1] = 1.0 - poisson_matrix[i + 1, i] = -1.0 - - eigvals = np.linalg.eigvals(cov_matrix @ poisson_matrix) - eigenemittances = np.imag(eigvals) - eigenemittances = eigenemittances[eigenemittances > 0] - - gamma = envelope.gamma - beta = envelope.beta - emittances = [ - np.sqrt(np.linalg.det(cov_matrix[i : i + 2, i : i + 2])) for i in (0, 2, 4) - ] - return { - "gamma": gamma, - "beta": beta, - "kin_energy": envelope.kin_energy, - "mean": envelope.centroid.copy(), - "cov": cov_matrix, - "rms_x": np.sqrt(cov_matrix[0, 0]), - "rms_y": np.sqrt(cov_matrix[2, 2]), - "rms_z": np.sqrt(cov_matrix[4, 4]), - "eps_x": emittances[0], - "eps_y": emittances[1], - "eps_z": emittances[2], - "eps_x_n": emittances[0] * gamma * beta, - "eps_y_n": emittances[1] * gamma * beta, - "eps_z_n": emittances[2] / beta, - "eps_1": eigenemittances[0], - "eps_2": eigenemittances[1], - "eps_3": eigenemittances[2], - } - - def update_history(position: float) -> None: - history["s"].append(position) - parameters = observe(envelope) - for key, value in parameters.items(): - history[key].append(value) - - update_history(0.0) if static: - elements = self._getStaticEnvelopeElements( - envelope, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - ) + if self._envelope_tracker is None or ( + self._envelope_tracker.index_start != tracker.index_start + or self._envelope_tracker.index_stop != tracker.index_stop + or self._envelope_tracker.fit != fit + or self._envelope_tracker.fallback != fallback + ): + tracker.precompute(envelope, params_dict=params_dict) + self._envelope_tracker = tracker + else: + tracker = self._envelope_tracker else: - elements = self._iterateEnvelopeElements( - envelope, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - ) - self._applyEnvelopeElements( - envelope, - elements, - sc=sc, - update_history=update_history, - ) - return history + self._envelope_tracker = None - def _trackEnvelopeStatic( - self, - envelope: Envelope, - index_start: int = 0, - index_stop: int = None, - sc: str | None = None, - fit: bool = True, - ) -> None: - """ - Track using pre-computed transfer matrices. - - The method assumes that all nodes are static and that there is no - change in the synchronous particle energy. In this case the matrices - can be computed once and reused on each turn. If there is no space charge, - we track using the one-turn matrix. - """ - elements = self._getStaticEnvelopeElements( + return tracker.track( envelope, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - ) - - if not sc: - if self._envelope_total_matrix is None: - self._envelope_total_matrix = np.identity(7) - for element_type, matrix in elements: - if element_type != "position": - self._envelope_total_matrix = matrix @ self._envelope_total_matrix - envelope.transform(self._envelope_total_matrix) - return - - self._applyEnvelopeElements(envelope, elements, sc=sc) - - def getEnvelopeTransferMatrix( - self, - envelope: Envelope, - index_start: int = 0, - index_stop: int = None, - sc: str | None = None, - fit: bool = True, - ) -> np.ndarray: - """Return total transfer matrix, including linear space charge when requested.""" - envelope_out = envelope.copy() - elements = self._precomputeEnvelopeElements( - envelope_out, - index_start=index_start, - index_stop=index_stop, - sc=sc, - fit=fit, - ) - return self._applyEnvelopeElements( - envelope_out, - elements, sc=sc, - calculate_matrix=True, + params_dict=params_dict, + action_container=action_container, + return_matrix=return_matrix, ) diff --git a/py/orbit/py_linac/lattice/LinacAccNodes.py b/py/orbit/py_linac/lattice/LinacAccNodes.py index 1d4e2a7e..b9a0619b 100755 --- a/py/orbit/py_linac/lattice/LinacAccNodes.py +++ b/py/orbit/py_linac/lattice/LinacAccNodes.py @@ -734,6 +734,9 @@ def track(self, paramsDict): return def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + if self.getParam("ea1") != 0.0 or self.getParam("ea2") != 0.0: + raise NotImplementedError("Bends with edge angles require a fitted matrix") + length = self.getLength(part_index) if length <= 0: return None @@ -1104,6 +1107,9 @@ def track(self, paramsDict): self.__trackFunc(self, paramsDict) def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + params_dict = self.getParamsDict() + if params_dict.get("ea1", 0.0) != 0.0 or params_dict.get("ea2", 0.0) != 0.0: + raise NotImplementedError("Bend edge fringes require a fitted matrix") return None def setFringeFieldFunction(self, trackFunction=None): diff --git a/py/orbit/teapot/teapot.py b/py/orbit/teapot/teapot.py index 865e1ff4..77cc0276 100644 --- a/py/orbit/teapot/teapot.py +++ b/py/orbit/teapot/teapot.py @@ -1314,6 +1314,9 @@ def track(self, paramsDict: dict) -> None: return def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + if self.getParam("ea1") != 0.0 or self.getParam("ea2") != 0.0: + raise NotImplementedError("Bends with edge angles require a fitted matrix") + length = self.getLength(part_index) if length <= 0: return None @@ -1326,40 +1329,7 @@ def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray if part_index == 0 or part_index == nparts - 1: theta *= 0.5 - matrix = get_matrix_bend(sync_part, length=length, theta=theta) - - def get_wedge_matrix(edge_angle: float) -> np.ndarray: - # ``wedgedrift`` has an identity Jacobian on the reference orbit. - # ``wedgebendCF`` acts as a thin edge kick to first order. Only - # pole-zero multipoles survive the linearization because the path - # length through the wedge is itself proportional to x. - edge_matrix = np.identity(7) - normal_dipole = 0.0 - skew_dipole = 0.0 - if sync_part.charge() != 0.0: - for pole, kl, skew in zip( - self.getParam("poles"), - self.getParam("kls"), - self.getParam("skews"), - ): - if pole == 0: - if skew: - skew_dipole += kl - else: - normal_dipole += kl - - tan_edge = np.tan(edge_angle) - edge_matrix[1, 0] = tan_edge * ((1.0 / self.getParam("rho")) + normal_dipole) - edge_matrix[3, 0] = -tan_edge * skew_dipole - return edge_matrix - - is_first_part = part_index < 0 or part_index == 0 - is_last_part = part_index < 0 or part_index == nparts - 1 - if is_first_part and self.getParam("ea1") != 0.0: - matrix = matrix @ get_wedge_matrix(self.getParam("ea1")) - if is_last_part and self.getParam("ea2") != 0.0: - matrix = get_wedge_matrix(self.getParam("ea2")) @ matrix - return matrix + return get_matrix_bend(sync_part, length=length, theta=theta) class RingRFTEAPOT(NodeTEAPOT): @@ -1618,6 +1588,9 @@ def track(self, paramsDict: dict) -> None: self.__trackFunc(self, paramsDict) def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: + params_dict = self.getParamsDict() + if params_dict.get("ea1", 0.0) != 0.0 or params_dict.get("ea2", 0.0) != 0.0: + raise NotImplementedError("Bend edge fringes require a fitted matrix") return None def setFringeFieldFunction(self, trackFunction: Callable) -> None: diff --git a/tests/py/orbit/test_env.py b/tests/py/orbit/test_env.py deleted file mode 100644 index 1a9b6d78..00000000 --- a/tests/py/orbit/test_env.py +++ /dev/null @@ -1,472 +0,0 @@ -import numpy as np -import pytest - -from orbit.core.bunch import Bunch -from orbit.core.bunch import BunchTwissAnalysis -from orbit.core.linac import MatrixRfGap -from orbit.bunch_utils import collect_bunch -from orbit.envelope import Envelope -from orbit.envelope import fit_transfer_matrix -from orbit.lattice import AccNode -from orbit.lattice import AccLattice -from orbit.py_linac.lattice import Drift -from orbit.py_linac.lattice import Quad -from orbit.py_linac.lattice import Bend -from orbit.py_linac.lattice import TiltElement -from orbit.py_linac.lattice import Solenoid -from orbit.teapot import BendTEAPOT -from orbit.teapot import ContinuousLinearFocusingTEAPOT -from orbit.teapot import DriftTEAPOT -from orbit.teapot import KickTEAPOT -from orbit.teapot import MultipoleTEAPOT -from orbit.teapot import QuadTEAPOT -from orbit.teapot import SolenoidTEAPOT -from orbit.teapot import TiltTEAPOT -from orbit.teapot import TEAPOT_Lattice -from orbit.utils.consts import mass_proton - - -def get_lorentz_factors(kin_energy: float, mass: float) -> tuple[float, float]: - gamma = 1.0 + kin_energy / mass - beta = np.sqrt(1.0 - (1.0 / gamma) ** 2) - return (gamma, beta) - - -def calc_bunch_cov(bunch: Bunch) -> np.ndarray: - twiss_calc = BunchTwissAnalysis() - twiss_calc.analyzeBunch(bunch) - - 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] - return cov_matrix - - -def make_lattice(nodes: list[AccNode]) -> AccLattice: - lattice = TEAPOT_Lattice() - for node in nodes: - lattice.addNode(node) - - lattice.initialize() - - for node in lattice.getNodes(): - try: - node.setUsageFringeFieldIN(False) - node.setUsageFringeFieldOUT(False) - except: - pass - - return lattice - - -def track_and_compare_rms( - lattice: AccLattice, - kin_energy: float, - cov_matrix: np.ndarray, - nparts: int = 100_000, - charge: float = 1.0, - verbose: int = 1, -) -> dict: - """Track bunch/envelope and compare rms beam sizes. - - Args: - lattice: Accelerator lattice. - kin_energy: Synchronous particle kinetic energy [GeV]. - cov_matrix: 6 x 6 covariance matrix. - nparts: Number of particles in bunch. - verbose: Whether to print results. - """ - cov_scale = 1e6 - - data = {} - for k1 in ["env", "bunch"]: - data[k1] = {} - for k2 in ["rms", "cov"]: - data[k1][k2] = {} - for k3 in ["in", "out"]: - data[k1][k2][k3] = {} - - # Initialize bunch - bunch = Bunch() - bunch.mass(mass_proton) - bunch.charge(charge) - - sync_part = bunch.getSyncParticle() - sync_part.kinEnergy(kin_energy) - - # Track bunch - particles = np.random.multivariate_normal(np.zeros(6), cov_matrix, size=nparts) - for x in particles: - bunch.addParticle(*x) - - # Covariance matrix calculated from particles will be slightly different. - cov_matrix = calc_bunch_cov(bunch) - - data["bunch"]["cov"]["in"] = cov_scale * calc_bunch_cov(bunch) - lattice.trackBunch(bunch) - data["bunch"]["cov"]["out"] = cov_scale * calc_bunch_cov(bunch) - - # Track envelope - envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix) - - data["env"]["cov"]["in"] = cov_scale * envelope.cov_matrix - lattice.trackEnvelope(envelope) - data["env"]["cov"]["out"] = cov_scale * envelope.cov_matrix - - # Compare - for mode in ["env", "bunch"]: - for loc in ["in", "out"]: - data[mode]["rms"][loc] = np.sqrt(np.diag(data[mode]["cov"][loc])) - - if verbose: - dims = ["x", "xp", "y", "yp", "z", "dE"] - for key in ["in", "out"]: - print(key.upper()) - for i in range(6): - print(" rms {}:".format(dims[i])) - print(" env: {}".format(data["env"]["rms"][key][i])) - print(" bunch: {}".format(data["bunch"]["rms"][key][i])) - - assert np.all(np.isclose(data["env"]["cov"]["in"], data["bunch"]["cov"]["in"])) - - atol = np.ones(6) - atol[0:4] = 1e-3 # [mm mrad] - atol[4] = 1e-3 # [mm] - atol[5] = 1e-3 # [MeV] - - for i in range(6): - x = data["env"]["rms"]["out"][i] - y = data["bunch"]["rms"]["out"][i] - assert np.abs(x - y) <= atol[i] - - -def make_default_cov_matrix( - rms_x: float = 1e-3, - rms_xp: float = 1e-3, - rms_y: float = 1e-3, - rms_yp: float = 1e-3, - rms_z: float = 1e-3, - rms_dE: float = 1e-5, -) -> np.ndarray: - return np.diag(np.square([rms_x, rms_xp, rms_y, rms_yp, rms_z, rms_dE])) - - -def test_drift_teapot(): - node = DriftTEAPOT(length=1.0, nparts=6) - lattice = make_lattice([node]) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) - - -def test_drift_linac(): - node = Drift() - node.setLength(1.0) - node.setnParts(6) - nodes = [node] - - lattice = make_lattice(nodes) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_quad_teapot(charge: float): - node = QuadTEAPOT(length=1.0, kq=1.0, nparts=10) - lattice = make_lattice([node]) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_cf_teapot(charge: float): - node = ContinuousLinearFocusingTEAPOT(length=10.0, kq=1.0, nparts=10) - lattice = make_lattice([node]) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_quad_linac(charge: float): - node = Quad() - node.setLength(1.0) - node.setnParts(10) - node.setParam("dB/dr", 0.23) - nodes = [node] - - lattice = make_lattice(nodes) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_bend_teapot(charge: float): - node = BendTEAPOT(length=1.0, theta=np.radians(20.0), nparts=5) - lattice = make_lattice([node]) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_bend_teapot_edge_matrix(charge: float): - node = BendTEAPOT( - length=1.0, - theta=np.radians(20.0), - nparts=5, - ea1=np.radians(8.0), - ea2=np.radians(-3.0), - ) - lattice = make_lattice([node]) - - bunch = Bunch() - bunch.mass(mass_proton) - bunch.charge(charge) - bunch.getSyncParticle().kinEnergy(1.3) - - matrix_fit = fit_transfer_matrix(lattice, bunch) - envelope = Envelope(sync_part=bunch.getSyncParticle()) - matrix_analytic = lattice.getEnvelopeTransferMatrix(envelope) - assert np.allclose(matrix_analytic, matrix_fit, atol=1.0e-10) - - -def test_fitted_envelope_matrices(): - node = MultipoleTEAPOT( - length=0.4, - nparts=3, - poles=[2], - kls=[0.2], - skews=[0], - ) - lattice = make_lattice([node]) - - bunch = Bunch() - bunch.mass(mass_proton) - bunch.getSyncParticle().kinEnergy(1.3) - - matrix_expected = fit_transfer_matrix(lattice, bunch) - envelope = Envelope(sync_part=bunch.getSyncParticle()) - matrix_actual = lattice.getEnvelopeTransferMatrix(envelope, fit=True) - assert np.allclose(matrix_actual, matrix_expected, atol=1.0e-12) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_bend_linac(charge: float): - node = Bend() - node.setLength(1.0) - node.setnParts(5) - node.setParam("theta", np.radians(20.0)) - nodes = [node] - - lattice = make_lattice(nodes) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_kick_teapot(charge: float): - node = KickTEAPOT(kx=0.001, ky=0.001, dE=0.00001, length=0.1, nparts=4) - lattice = make_lattice([node]) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) - - -def test_tilt_teapot(): - node = TiltTEAPOT(angle=(0.25 * np.pi)) - lattice = make_lattice([node]) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) - - -def test_tilt_linac(): - node = TiltElement() - node.setTiltAngle(0.25 * np.pi) - lattice = make_lattice([node]) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_solenoid_teapot(charge: float): - node = SolenoidTEAPOT(length=2.0, B=1.0, nparts=10) - lattice = make_lattice([node]) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_solenoid_linac(charge: float): - node = Solenoid() - node.setLength(2.0) - node.setnParts(10) - node.setParam("B", 1.0) - nodes = [node] - - lattice = make_lattice(nodes) - cov_matrix = make_default_cov_matrix() - track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_rf_gap_matrix(charge: float): - kin_energy = 0.0025 - frequency = 402.5e06 - E0TL = 0.001 - phase = 0.0 - - cov_matrix = make_default_cov_matrix() - - bunch_in = Bunch() - bunch_in.mass(mass_proton) - bunch_in.charge(charge) - bunch_in.getSyncParticle().kinEnergy(kin_energy) - - coords_in = np.random.multivariate_normal(np.zeros(6), cov_matrix, size=10) - for x in coords_in: - bunch_in.addParticle(*x) - - bunch_out_1 = Bunch() - bunch_in.copyBunchTo(bunch_out_1) - - matrix_rf_gap = MatrixRfGap() - matrix_rf_gap.trackBunch(bunch_out_1, frequency, E0TL, phase) - - coords_out_1 = collect_bunch(bunch_out_1)["coords"] - - from orbit.utils.matrix import get_matrix_rf_gap - - bunch_out_2 = Bunch() - bunch_in.copyBunchTo(bunch_out_2) - - sync_part = bunch_in.getSyncParticle() - matrix = get_matrix_rf_gap( - sync_part, - frequency=frequency, - E0TL=E0TL, - phase=phase, - ) - coords_in = np.column_stack([coords_in, np.ones(coords_in.shape[0])]) - coords_out_2 = np.matmul(coords_in, matrix.T) - coords_out_2 = coords_out_2[:, :-1] - assert np.allclose(coords_out_1, coords_out_2) - - -def test_sc_3d_cold_expansion(): - # This should test expansion of cold uniform-density sphere - # (in rest frame). We can calculate the time to expand to - # twice the initial size. (See examples from A. Shishlo or - # from the ImpactX repo.) - pass - - -def test_track_sublattice_no_error(): - bunch = Bunch() - bunch.mass(mass_proton) - - sync_part = bunch.getSyncParticle() - sync_part.kinEnergy(0.001) - - cov_matrix = np.diag(np.square([1e-3, 0, 1e-3, 0.0, 1e-3, 0.0])) - envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix) - - lattice = TEAPOT_Lattice() - - n = 5 - for _ in range(n): - lattice.addNode(DriftTEAPOT(length=0.1)) - - for i in range(n): - lattice.trackEnvelope(envelope, index_start=i) - lattice.trackEnvelope(envelope, index_stop=-i) - - -def test_track_static_sublattice(): - lattice = make_lattice( - [ - DriftTEAPOT(length=0.1), - DriftTEAPOT(length=0.2), - DriftTEAPOT(length=0.3), - ] - ) - - bunch = Bunch() - bunch.mass(mass_proton) - bunch.getSyncParticle().kinEnergy(0.001) - envelope = Envelope( - sync_part=bunch.getSyncParticle(), - cov_matrix=make_default_cov_matrix(), - ) - - for index_start, index_stop in [(0, 0), (1, 2)]: - expected = envelope.copy() - lattice.trackEnvelope( - expected, - index_start=index_start, - index_stop=index_stop, - fit=False, - ) - - actual = envelope.copy() - lattice.trackEnvelope( - actual, - index_start=index_start, - index_stop=index_stop, - fit=False, - static=True, - ) - - assert np.allclose(actual.cov_matrix, expected.cov_matrix) - assert np.allclose(actual.centroid, expected.centroid) - - -def test_track_static_history(): - lattice = make_lattice( - [ - DriftTEAPOT(length=0.1, nparts=1), - DriftTEAPOT(length=0.2, nparts=2), - ] - ) - - bunch = Bunch() - bunch.mass(mass_proton) - bunch.getSyncParticle().kinEnergy(0.001) - envelope = Envelope( - sync_part=bunch.getSyncParticle(), - cov_matrix=make_default_cov_matrix(), - ) - - expected = lattice.trackEnvelope(envelope.copy(), history=True, fit=False) - actual = lattice.trackEnvelope( - envelope.copy(), - history=True, - fit=False, - static=True, - ) - - assert actual.keys() == expected.keys() - for key in actual: - assert np.allclose(actual[key], expected[key]) - - -@pytest.mark.parametrize("charge", [1.0, -1.0]) -def test_get_total_matrix(charge: float) -> None: - node = DriftTEAPOT(length=2.0, nparts=50) - lattice = make_lattice([node]) - - bunch = Bunch() - bunch.mass(mass_proton) - bunch.charge(charge) - - sync_part = bunch.getSyncParticle() - sync_part.kinEnergy(0.001) - - cov_matrix = make_default_cov_matrix() - envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix, intensity=1e7) - - envelope_out_a = envelope.copy() - lattice.trackEnvelope(envelope_out_a, sc="2d") - - matrix = lattice.getEnvelopeTransferMatrix(envelope.copy(), sc="2d") - envelope_out_b = envelope.copy() - envelope_out_b.transform(matrix) - assert np.all(np.isclose(envelope_out_a.cov_matrix, envelope_out_b.cov_matrix)) diff --git a/tests/py/orbit/test_envelope.py b/tests/py/orbit/test_envelope.py new file mode 100644 index 00000000..5c8eff8d --- /dev/null +++ b/tests/py/orbit/test_envelope.py @@ -0,0 +1,689 @@ +import numpy as np +import pytest + +from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis +from orbit.core.linac import MatrixRfGap +from orbit.bunch_utils import collect_bunch +from orbit.envelope import Envelope +from orbit.envelope import fit_transfer_matrix +from orbit.lattice import AccNode +from orbit.lattice import AccActionsContainer +from orbit.lattice import AccNodeBunchTracker +from orbit.lattice import AccLattice +from orbit.py_linac.lattice import Drift +from orbit.py_linac.lattice import Quad +from orbit.py_linac.lattice import Bend +from orbit.py_linac.lattice import TiltElement +from orbit.py_linac.lattice import Solenoid +from orbit.teapot import BendTEAPOT +from orbit.teapot import ContinuousLinearFocusingTEAPOT +from orbit.teapot import DriftTEAPOT +from orbit.teapot import KickTEAPOT +from orbit.teapot import MultipoleTEAPOT +from orbit.teapot import QuadTEAPOT +from orbit.teapot import SolenoidTEAPOT +from orbit.teapot import TiltTEAPOT +from orbit.teapot import TEAPOT_Lattice +from orbit.utils.consts import mass_proton + + +def get_lorentz_factors(kin_energy: float, mass: float) -> tuple[float, float]: + gamma = 1.0 + kin_energy / mass + beta = np.sqrt(1.0 - (1.0 / gamma) ** 2) + return (gamma, beta) + + +def calc_bunch_cov(bunch: Bunch) -> np.ndarray: + twiss_calc = BunchTwissAnalysis() + twiss_calc.analyzeBunch(bunch) + + 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] + return cov_matrix + + +def make_lattice(nodes: list[AccNode]) -> AccLattice: + lattice = TEAPOT_Lattice() + for node in nodes: + lattice.addNode(node) + + lattice.initialize() + + for node in lattice.getNodes(): + try: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + except: + pass + + return lattice + + +def track_and_compare_rms( + lattice: AccLattice, + kin_energy: float, + cov_matrix: np.ndarray, + nparts: int = 100_000, + charge: float = 1.0, + verbose: int = 1, +) -> dict: + """Track bunch/envelope and compare rms beam sizes. + + Args: + lattice: Accelerator lattice. + kin_energy: Synchronous particle kinetic energy [GeV]. + cov_matrix: 6 x 6 covariance matrix. + nparts: Number of particles in bunch. + verbose: Whether to print results. + """ + cov_scale = 1e6 + + data = {} + for k1 in ["env", "bunch"]: + data[k1] = {} + for k2 in ["rms", "cov"]: + data[k1][k2] = {} + for k3 in ["in", "out"]: + data[k1][k2][k3] = {} + + # Initialize bunch + bunch = Bunch() + bunch.mass(mass_proton) + bunch.charge(charge) + + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(kin_energy) + + # Track bunch + particles = np.random.default_rng(42).multivariate_normal(np.zeros(6), cov_matrix, size=nparts) + for x in particles: + bunch.addParticle(*x) + + # Covariance matrix calculated from particles will be slightly different. + cov_matrix = calc_bunch_cov(bunch) + + envelope = Envelope(bunch=bunch).copy() + data["bunch"]["cov"]["in"] = cov_scale * calc_bunch_cov(bunch) + lattice.trackBunch(bunch) + data["bunch"]["cov"]["out"] = cov_scale * calc_bunch_cov(bunch) + + # Track envelope + analysis = BunchTwissAnalysis() + analysis.analyzeBunch(bunch) + bunch_centroid = np.array([analysis.getAverage(i) for i in range(6)]) + + data["env"]["cov"]["in"] = cov_scale * envelope.cov_matrix + lattice.trackEnvelope(envelope) + data["env"]["cov"]["out"] = cov_scale * envelope.cov_matrix + + # Compare + for mode in ["env", "bunch"]: + for loc in ["in", "out"]: + data[mode]["rms"][loc] = np.sqrt(np.diag(data[mode]["cov"][loc])) + + if verbose: + dims = ["x", "xp", "y", "yp", "z", "dE"] + for key in ["in", "out"]: + print(key.upper()) + for i in range(6): + print(" rms {}:".format(dims[i])) + print(" env: {}".format(data["env"]["rms"][key][i])) + print(" bunch: {}".format(data["bunch"]["rms"][key][i])) + + assert np.all(np.isclose(data["env"]["cov"]["in"], data["bunch"]["cov"]["in"])) + + atol = np.ones(6) + atol[0:4] = 1e-3 # [mm mrad] + atol[4] = 1e-3 # [mm] + atol[5] = 1e-3 # [MeV] + + for i in range(6): + x = data["env"]["rms"]["out"][i] + y = data["bunch"]["rms"]["out"][i] + assert np.abs(x - y) <= atol[i] + + output_scale = np.sqrt(np.diag(data["bunch"]["cov"]["out"])) + covariance_error = data["env"]["cov"]["out"] - data["bunch"]["cov"]["out"] + assert np.max(np.abs(covariance_error) / np.outer(output_scale, output_scale)) < 0.01 + assert np.max(np.abs(envelope.centroid - bunch_centroid) / (output_scale / 1000.0)) < 0.01 + + +def make_default_cov_matrix( + rms_x: float = 1e-3, + rms_xp: float = 1e-3, + rms_y: float = 1e-3, + rms_yp: float = 1e-3, + rms_z: float = 1e-3, + rms_dE: float = 1e-5, +) -> np.ndarray: + return np.diag(np.square([rms_x, rms_xp, rms_y, rms_yp, rms_z, rms_dE])) + + +def test_drift_teapot(): + node = DriftTEAPOT(length=1.0, nparts=6) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) + + +def test_drift_linac(): + node = Drift() + node.setLength(1.0) + node.setnParts(6) + nodes = [node] + + lattice = make_lattice(nodes) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_quad_teapot(charge: float): + node = QuadTEAPOT(length=1.0, kq=1.0, nparts=10) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_cf_teapot(charge: float): + node = ContinuousLinearFocusingTEAPOT(length=10.0, kq=1.0, nparts=10) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_quad_linac(charge: float): + node = Quad() + node.setLength(1.0) + node.setnParts(10) + node.setParam("dB/dr", 0.23) + nodes = [node] + + lattice = make_lattice(nodes) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_bend_teapot(charge: float): + node = BendTEAPOT(length=1.0, theta=np.radians(20.0), nparts=5) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_bend_teapot_edge_matrix(charge: float): + node = BendTEAPOT( + length=1.0, + theta=np.radians(20.0), + nparts=5, + ea1=np.radians(8.0), + ea2=np.radians(-3.0), + ) + lattice = make_lattice([node]) + + bunch = Bunch() + bunch.mass(mass_proton) + bunch.charge(charge) + bunch.getSyncParticle().kinEnergy(1.3) + + matrix_fit = fit_transfer_matrix(lattice, bunch) + envelope = Envelope(sync_part=bunch.getSyncParticle()) + matrix_analytic = lattice.trackEnvelope(envelope.copy(), fit=False, return_matrix=True) + assert np.allclose(matrix_analytic, matrix_fit, atol=1.0e-10) + + +def test_fitted_envelope_matrices(): + node = MultipoleTEAPOT( + length=0.4, + nparts=3, + poles=[2], + kls=[0.2], + skews=[0], + ) + lattice = make_lattice([node]) + + bunch = Bunch() + bunch.mass(mass_proton) + bunch.getSyncParticle().kinEnergy(1.3) + + matrix_expected = fit_transfer_matrix(lattice, bunch) + envelope = Envelope(sync_part=bunch.getSyncParticle()) + matrix_actual = lattice.trackEnvelope(envelope.copy(), return_matrix=True, fit=True) + assert np.allclose(matrix_actual, matrix_expected, atol=1.0e-12) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_bend_linac(charge: float): + node = Bend() + node.setLength(1.0) + node.setnParts(5) + node.setParam("theta", np.radians(20.0)) + nodes = [node] + + lattice = make_lattice(nodes) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_kick_teapot(charge: float): + node = KickTEAPOT(kx=0.001, ky=0.001, dE=0.00001, length=0.1, nparts=4) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +def test_tilt_teapot(): + node = TiltTEAPOT(angle=(0.25 * np.pi)) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) + + +def test_tilt_linac(): + node = TiltElement() + node.setTiltAngle(0.25 * np.pi) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_solenoid_teapot(charge: float): + node = SolenoidTEAPOT(length=2.0, B=1.0, nparts=10) + lattice = make_lattice([node]) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_solenoid_linac(charge: float): + node = Solenoid() + node.setLength(2.0) + node.setnParts(10) + node.setParam("B", 1.0) + nodes = [node] + + lattice = make_lattice(nodes) + cov_matrix = make_default_cov_matrix() + track_and_compare_rms(lattice, kin_energy=0.0025, cov_matrix=cov_matrix, charge=charge) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +def test_rf_gap_matrix(charge: float): + kin_energy = 0.0025 + frequency = 402.5e06 + E0TL = 0.001 + phase = 0.0 + + cov_matrix = make_default_cov_matrix() + + bunch_in = Bunch() + bunch_in.mass(mass_proton) + bunch_in.charge(charge) + bunch_in.getSyncParticle().kinEnergy(kin_energy) + + coords_in = np.random.multivariate_normal(np.zeros(6), cov_matrix, size=10) + for x in coords_in: + bunch_in.addParticle(*x) + + bunch_out_1 = Bunch() + bunch_in.copyBunchTo(bunch_out_1) + + matrix_rf_gap = MatrixRfGap() + matrix_rf_gap.trackBunch(bunch_out_1, frequency, E0TL, phase) + + coords_out_1 = collect_bunch(bunch_out_1)["coords"] + + from orbit.utils.matrix import get_matrix_rf_gap + + bunch_out_2 = Bunch() + bunch_in.copyBunchTo(bunch_out_2) + + sync_part = bunch_in.getSyncParticle() + matrix = get_matrix_rf_gap( + sync_part, + frequency=frequency, + E0TL=E0TL, + phase=phase, + ) + coords_in = np.column_stack([coords_in, np.ones(coords_in.shape[0])]) + coords_out_2 = np.matmul(coords_in, matrix.T) + coords_out_2 = coords_out_2[:, :-1] + assert np.allclose(coords_out_1, coords_out_2) + + +def test_sc_3d_cold_expansion(): + # A cold uniform sphere obeys R'' = C/R**2, C = N*r0/(beta*gamma)**2. + # Integrating this equation gives the distance at which its radius doubles. + bunch = Bunch() + bunch.getSyncParticle().kinEnergy(0.01) + radius = 0.01 + gamma = bunch.getSyncParticle().gamma() + covariance = np.diag([radius**2 / 5, 0, radius**2 / 5, 0, radius**2 / (5 * gamma**2), 0]) + envelope = Envelope(sync_part=bunch.getSyncParticle(), cov_matrix=covariance, intensity=1e8) + coefficient = envelope.intensity * envelope.classical_radius / (envelope.beta * gamma)**2 + distance = np.sqrt(radius**3 / (2 * coefficient)) * (np.sqrt(2) + np.arcsinh(1)) + lattice = make_lattice([DriftTEAPOT(length=distance, nparts=1000)]) + lattice.trackEnvelope(envelope, sc="3d", fit=False, static=True) + radii = np.sqrt(5 * np.diag(envelope.cov_matrix)[[0, 2, 4]]) * [1, 1, gamma] + np.testing.assert_allclose(radii, 2 * radius, rtol=0.002) + + +def test_track_sublattice_no_error(): + bunch = Bunch() + bunch.mass(mass_proton) + + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(0.001) + + cov_matrix = np.diag(np.square([1e-3, 0, 1e-3, 0.0, 1e-3, 0.0])) + envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix) + + lattice = TEAPOT_Lattice() + + n = 5 + for _ in range(n): + lattice.addNode(DriftTEAPOT(length=0.1)) + + for i in range(n): + lattice.trackEnvelope(envelope, index_start=i) + lattice.trackEnvelope(envelope, index_stop=-i) + + +@pytest.mark.parametrize("charge", [1.0, -1.0]) +@pytest.mark.parametrize("static", [False, True]) +def test_get_total_matrix(charge: float, static: bool) -> None: + node = DriftTEAPOT(length=2.0, nparts=50) + lattice = make_lattice([node]) + + bunch = Bunch() + bunch.mass(mass_proton) + bunch.charge(charge) + + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(0.001) + + cov_matrix = make_default_cov_matrix() + envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix, intensity=1e7) + + envelope_out_a = envelope.copy() + lattice.trackEnvelope(envelope_out_a, sc="2d") + + matrix = lattice.trackEnvelope(envelope.copy(), return_matrix=True, sc="2d", static=static) + envelope_out_b = envelope.copy() + envelope_out_b.transform(matrix) + assert np.all(np.isclose(envelope_out_a.cov_matrix, envelope_out_b.cov_matrix)) + + +def make_test_envelope(): + bunch = Bunch() + bunch.getSyncParticle().kinEnergy(1.3) + bunch.getSyncParticle().time(10.0) + return Envelope(sync_part=bunch.getSyncParticle(), cov_matrix=make_default_cov_matrix()).copy() + + +@pytest.mark.parametrize("fit", [False, True]) +def test_static_reuse_options_and_reset(monkeypatch, fit): + from orbit.envelope import EnvelopeTracker + + lattice = make_lattice([DriftTEAPOT(length=0.2), DriftTEAPOT(length=0.7)]) + envelope = make_test_envelope() + calls = [] + original = EnvelopeTracker.precompute + + def precompute(self, envelope, params_dict=None): + calls.append((self.index_start, self.index_stop, self.fit, self.fallback)) + return original(self, envelope, params_dict=params_dict) + + monkeypatch.setattr(EnvelopeTracker, "precompute", precompute) + expected = envelope.copy() + for _ in range(3): + lattice.trackEnvelope(expected, fit=fit) + for _ in range(3): + lattice.trackEnvelope(envelope, static=True, fit=fit) + assert len(calls) == 1 + assert envelope.sync_part.time() == pytest.approx(expected.sync_part.time(), rel=0, abs=1e-14) + np.testing.assert_allclose(envelope.cov_matrix, expected.cov_matrix) + for options in [dict(index_stop=0, fit=fit), dict(index_stop=0, fit=not fit), + dict(index_stop=0, fit=not fit, fallback=False)]: + actual = make_test_envelope() + reference = actual.copy() + reference_lattice = make_lattice([DriftTEAPOT(length=0.2), DriftTEAPOT(length=0.7)]) + reference_lattice.trackEnvelope(reference, **options) + lattice.trackEnvelope(actual, static=True, **options) + np.testing.assert_allclose(actual.cov_matrix, reference.cov_matrix) + assert len(calls) == 4 + lattice.initialize() + lattice.trackEnvelope(envelope, static=True) + assert len(calls) == 5 + lattice.trackEnvelope(envelope, static=False) + lattice.trackEnvelope(envelope, static=True) + assert len(calls) == 6 + + +@pytest.mark.parametrize("static", [False, True]) +@pytest.mark.parametrize("start,stop,length", [(0, 0, .1), (1, 1, .2), (1, 2, .5), + (0, -1, .6), (0, -2, .6), (-1, None, .6), (3, None, 0), (2, 0, 0)]) +def test_sublattice_results(static, start, stop, length): + from orbit.utils.matrix import get_matrix_drift + + lattice = make_lattice([DriftTEAPOT(length=x) for x in [.1, .2, .3]]) + envelope = make_test_envelope() + reference = envelope.copy() + expected_matrix = get_matrix_drift(reference.sync_part, length) + matrix = lattice.trackEnvelope(envelope, index_start=start, index_stop=stop, + static=static, fit=False, return_matrix=True) + np.testing.assert_allclose(matrix, expected_matrix, atol=1e-14) + assert envelope.sync_part.time() == pytest.approx(reference.sync_part.time(), rel=0, abs=1e-14) + + +@pytest.mark.parametrize("static", [False, True]) +@pytest.mark.parametrize("fit", [False, True]) +def test_actions_match_bunch_traversal(static, fit): + parent = DriftTEAPOT(name="parent", length=.4, nparts=2) + for place, part, location in [(AccNode.ENTRANCE, 0, AccNode.AFTER), + (AccNode.BODY, 0, AccNode.BEFORE), (AccNode.BODY, 1, AccNode.AFTER), + (AccNode.EXIT, 0, AccNode.AFTER)]: + parent.addChildNode(DriftTEAPOT(name=f"child-{place}-{part}", length=.1), + place, part_index=part, place_in_part=location) + lattice = make_lattice([parent]) + envelope = make_test_envelope() + envelope.centroid[1] = .001 + bunch = Bunch() + bunch.mass(envelope.mass) + bunch.charge(envelope.charge) + bunch.getSyncParticle().kinEnergy(envelope.kin_energy) + bunch.getSyncParticle().time(10) + bunch.addParticle(*envelope.centroid) + + def observe(beam_key): + actions = AccActionsContainer() + events = [] + for place in [AccNode.ENTRANCE, AccNode.BODY, AccNode.EXIT]: + def action(params_dict, place=place): + assert params_dict["actions"] is actions + assert params_dict["custom"] == "retained" + beam = params_dict[beam_key] + sync_part = beam.sync_part if beam_key == "envelope" else beam.getSyncParticle() + x = beam.centroid[0] if beam_key == "envelope" else beam.x(0) + events.append((params_dict["node"].getName(), params_dict["parentNode"].getName(), + place, params_dict["node"].getActivePartIndex(), params_dict["path_length"], + sync_part.time(), x)) + actions.addAction(action, place) + return actions, events + + bunch_actions, expected = observe("bunch") + lattice.trackBunch(bunch, paramsDict={"custom": "retained"}, actionContainer=bunch_actions) + actions, actual = observe("envelope") + original = [list(actions.getActions(place)) for place in range(3)] + lattice.trackEnvelope(envelope, params_dict={"custom": "retained"}, action_container=actions, + static=static, fit=fit) + assert len(actual) == len(expected) + for observed, reference in zip(actual, expected): + assert observed[:4] == reference[:4] + np.testing.assert_allclose(observed[4:], reference[4:], rtol=0, atol=1e-12) + assert [actions.getActions(place) for place in range(3)] == original + + +@pytest.mark.parametrize("failure", ["action", "matrix"]) +def test_actions_removed_after_failure(failure): + class FailingDrift(DriftTEAPOT): + def getMatrix(self, sync_part, part_index=-1): + raise RuntimeError("matrix failure") + + node = FailingDrift(length=.1) if failure == "matrix" else DriftTEAPOT(length=.1) + lattice = make_lattice([node]) + actions = AccActionsContainer() + def fail(params_dict): + raise RuntimeError("action failure") + if failure == "action": + actions.addAction(fail, AccNode.EXIT) + original = [list(actions.getActions(place)) for place in range(3)] + with pytest.raises(RuntimeError, match=f"{failure} failure"): + lattice.trackEnvelope(make_test_envelope(), fit=False, action_container=actions) + assert [actions.getActions(place) for place in range(3)] == original + if failure == "action": + actions.removeAction(fail, AccNode.EXIT) + healthy = make_lattice([DriftTEAPOT(length=.1)]) + healthy.trackEnvelope(make_test_envelope(), action_container=actions) + assert all(not actions.getActions(place) for place in range(3)) + + +@pytest.mark.parametrize("static", [False, True]) +@pytest.mark.parametrize("fallback", [False, True]) +def test_missing_matrix_fallback(static, fallback): + class UnsupportedDrift(DriftTEAPOT): + def getMatrix(self, sync_part, part_index=-1): + raise NotImplementedError("missing matrix") + lattice = make_lattice([UnsupportedDrift(length=.3)]) + envelope = make_test_envelope() + if not fallback: + with pytest.raises(NotImplementedError, match="missing matrix"): + lattice.trackEnvelope(envelope, fit=False, fallback=False, static=static) + else: + expected = envelope.copy() + lattice.trackEnvelope(expected, fit=True) + lattice.trackEnvelope(envelope, fit=False, fallback=True, static=static) + np.testing.assert_allclose(envelope.cov_matrix, expected.cov_matrix) + + +@pytest.mark.parametrize("result", [None, ValueError("invalid matrix")]) +def test_fallback_respects_none_and_other_errors(result): + class CustomNode(AccNode): + def getMatrix(self, sync_part, part_index=-1): + if isinstance(result, Exception): + raise result + return result + def track(self, params_dict): + pytest.fail("Unexpected fitting") + lattice = make_lattice([CustomNode()]) + envelope = make_test_envelope() + if isinstance(result, Exception): + with pytest.raises(ValueError, match="invalid matrix"): + lattice.trackEnvelope(envelope, fit=False) + else: + expected = envelope.copy() + lattice.trackEnvelope(envelope, fit=False) + np.testing.assert_array_equal(envelope.cov_matrix, expected.cov_matrix) + + +@pytest.mark.parametrize("fit", [False, True]) +def test_reference_updates_and_preparation_independence(fit): + from orbit.envelope import EnvelopeTracker + class AcceleratingNode(AccNode): + def update(self, sync_part): + sync_part.kinEnergy(sync_part.kinEnergy() + .1) + sync_part.time(sync_part.time() + .25) + sync_part.rVector(tuple(x + .1 for x in sync_part.rVector())) + sync_part.nxVector((0, 1, 0)) + def getMatrix(self, sync_part, part_index=-1): + self.update(sync_part) + return np.eye(7) + def track(self, params_dict): + self.update(params_dict["bunch"].getSyncParticle()) + lattice = make_lattice([AcceleratingNode(), AcceleratingNode()]) + envelope = make_test_envelope() + tracker = EnvelopeTracker(lattice, fit=fit) + params_dict = {"path_length": 5} + tracker.precompute(envelope, params_dict=params_dict) + assert params_dict == {"path_length": 5} + assert envelope.sync_part.time() == 10 + assert envelope.kin_energy == pytest.approx(1.3) + np.testing.assert_array_equal(envelope.sync_part.rVector(), (0, 0, 0)) + # Dynamic transport must recalculate at the updated energy on each turn. + lattice.trackEnvelope(envelope, fit=fit) + lattice.trackEnvelope(envelope, fit=fit) + assert envelope.kin_energy == pytest.approx(1.7) + assert envelope.sync_part.time() == pytest.approx(11) + np.testing.assert_allclose(envelope.sync_part.rVector(), (.4, .4, .4)) + np.testing.assert_allclose(envelope.sync_part.nxVector(), (0, 1, 0)) + + +def test_envelope_copy_owns_reference_state(): + import gc + original = make_test_envelope() + original.sync_part.rVector((1, 2, 3)) + original.sync_part.nxVector((0, 1, 0)) + original.centroid[:] = np.arange(6) + original.intensity = 123 + original.rms_bunch_length_factor = 4 + copied = original.copy() + for attr in ["mass", "charge", "kinEnergy", "time", "rVector", "pVector", "nxVector"]: + np.testing.assert_allclose(getattr(copied.sync_part, attr)(), getattr(original.sync_part, attr)()) + assert copied.intensity == original.intensity + assert copied.classical_radius == original.classical_radius + assert copied.rms_bunch_length_factor == 4 + copied.centroid[0] = 99 + copied.cov_matrix[0, 0] = 99 + copied.sync_part.time(20) + copied.sync_part.kinEnergy(.5) + assert original.centroid[0] == 0 + assert original.cov_matrix[0, 0] != 99 + assert original.sync_part.time() == 10 + assert original.kin_energy == pytest.approx(1.3) + del original + gc.collect() + assert copied.copy().kin_energy == pytest.approx(.5) + + +@pytest.mark.parametrize("kind", ["teapot", "linac"]) +@pytest.mark.parametrize("fringe", [False, True]) +@pytest.mark.parametrize("static", [False, True]) +@pytest.mark.parametrize("ea1,ea2", [(0.1, 0), (0, -.05), (.1, -.05)]) +def test_edge_bends_with_fringe(kind, fringe, static, ea1, ea2): + if kind == "teapot": + node = BendTEAPOT(length=1, theta=.2, ea1=ea1, ea2=ea2, nparts=5) + else: + node = Bend() + node.setLength(1) + node.setnParts(5) + for name, value in [("theta", .2), ("ea1", ea1), ("ea2", ea2)]: + node.setParam(name, value) + lattice = make_lattice([node]) + if hasattr(node, "setUsageFringeFieldIN"): + node.setUsageFringeFieldIN(fringe) + node.setUsageFringeFieldOUT(fringe) + envelope = make_test_envelope() + bunch = Bunch() + bunch.mass(envelope.mass) + bunch.charge(envelope.charge) + bunch.getSyncParticle().kinEnergy(envelope.kin_energy) + expected = fit_transfer_matrix(lattice, bunch) + actual = lattice.trackEnvelope(envelope, fit=False, static=static, return_matrix=True) + np.testing.assert_allclose(actual, expected, atol=1e-10) + with pytest.raises(NotImplementedError, match="edge angles"): + node.getMatrix(envelope.sync_part, part_index=0) + for fringe_node in (node.getNodeFringeFieldIN(), node.getNodeFringeFieldOUT()): + with pytest.raises(NotImplementedError, match="edge fringes"): + fringe_node.getMatrix(envelope.sync_part) + with pytest.raises(NotImplementedError): + lattice.trackEnvelope(envelope.copy(), fit=False, fallback=False) From 4bd1a248ca2341e0f2ced468bcc3b9c7473019bf Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Thu, 12 Nov 2026 12:31:32 -0500 Subject: [PATCH 30/42] Temporary fix: openmp dependency --- src/meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/meson.build b/src/meson.build index 8f1e08f0..8cc4385c 100644 --- a/src/meson.build +++ b/src/meson.build @@ -16,7 +16,7 @@ dep_fftw = dependency('fftw3', version: '>= 3.0.0', required: true) dependencies += dep_fftw # Enable OpenMP if available -dep_openmp = dependency('openmp') +dep_openmp = dependency('openmp', required: get_option('USE_OPENMP')) if get_option('USE_OPENMP') and dep_openmp.found() add_global_arguments('-DWITH_OPENMP', language : 'cpp') dependencies += dep_openmp From 8385f20622a9d6a0dd2c0c546c9808e4e464f450 Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Sat, 14 Nov 2026 18:24:26 -0500 Subject: [PATCH 31/42] `Envelope` no longer stores `SyncParticle` or `Bunch` (#175) --- examples/Envelope/run.sh | 21 +- examples/Envelope/sns_linac/diagnostics.py | 52 --- examples/Envelope/sns_linac/test_sns_linac.py | 100 +++-- .../sns_linac/test_sns_linac_speed.py | 155 ++++++++ examples/Envelope/sns_ring/test_sns_ring.py | 38 +- .../Envelope/sns_ring/test_sns_ring_speed.py | 66 ++-- ...{test_env_3d_drift.py => test_drift_3d.py} | 14 +- .../{test_env_2d_fodo.py => test_fodo_2d.py} | 5 +- ...2d_fodo_speed.py => test_fodo_2d_speed.py} | 5 +- py/orbit/envelope/__init__.py | 2 - py/orbit/envelope/envelope.py | 304 ++++++--------- py/orbit/{utils => envelope}/matrix.py | 120 +++--- py/orbit/envelope/matrix_fitting.py | 30 +- py/orbit/envelope/meson.build | 6 +- py/orbit/envelope/node_matrices.py | 279 ++++++++++++++ py/orbit/envelope/tracking.py | 121 +++--- py/orbit/envelope/utils.py | 20 +- py/orbit/lattice/AccLattice.py | 14 +- py/orbit/lattice/AccNode.py | 11 - py/orbit/py_linac/lattice/LinacAccNodes.py | 86 +---- py/orbit/py_linac/lattice/LinacRfGapNodes.py | 41 -- py/orbit/teapot/teapot.py | 139 +------ py/orbit/utils/meson.build | 3 +- src/utils/matrix/wrap_matrix.cc | 31 ++ tests/py/orbit/test_envelope.py | 352 +++++------------- 25 files changed, 963 insertions(+), 1052 deletions(-) delete mode 100644 examples/Envelope/sns_linac/diagnostics.py create mode 100644 examples/Envelope/sns_linac/test_sns_linac_speed.py rename examples/Envelope/{test_env_3d_drift.py => test_drift_3d.py} (97%) rename examples/Envelope/{test_env_2d_fodo.py => test_fodo_2d.py} (98%) rename examples/Envelope/{test_env_2d_fodo_speed.py => test_fodo_2d_speed.py} (97%) rename py/orbit/{utils => envelope}/matrix.py (56%) create mode 100644 py/orbit/envelope/node_matrices.py diff --git a/examples/Envelope/run.sh b/examples/Envelope/run.sh index b5487b7b..bde5b25d 100755 --- a/examples/Envelope/run.sh +++ b/examples/Envelope/run.sh @@ -2,16 +2,16 @@ set -x -python test_env_2d_fodo.py --sc 0 -python test_env_2d_fodo.py --sc 1 -python test_env_2d_fodo.py --sc 1 --offset-x 0.001 -python test_env_2d_fodo.py --sc 1 --tilt 45.0 -python test_env_2d_fodo_speed.py --sc 0 -python test_env_2d_fodo_speed.py --sc 1 -python test_env_3d_drift.py --sc 0 -python test_env_3d_drift.py --sc 1 -python test_env_3d_drift.py --sc 1 --rms-y 0.002 --rot-z 45.0 -python test_env_3d_drift.py --sc 1 --rms-z 0.002 --rot-x 45.0 +python test_fodo_2d.py --sc 0 +python test_fodo_2d.py --sc 1 +python test_fodo_2d.py --sc 1 --offset-x 0.001 +python test_fodo_2d.py --sc 1 --tilt 45.0 +python test_fodo_2d_speed.py --sc 0 +python test_fodo_2d_speed.py --sc 1 +python test_drift_3d.py --sc 0 +python test_drift_3d.py --sc 1 +python test_drift_3d.py --sc 1 --rms-y 0.002 --rot-z 45.0 +python test_drift_3d.py --sc 1 --rms-z 0.002 --rot-x 45.0 cd sns_linac python test_sns_linac.py --sc 0 @@ -24,6 +24,7 @@ cd sns_ring python test_sns_ring.py --sc 0 python test_sns_ring.py --sc 1 python test_sns_ring.py --sc 1 --tilt 45.0 +python test_sns_ring.py --sc 1 --sol 1 python test_sns_ring_speed.py --sc 0 python test_sns_ring_speed.py --sc 1 cd .. diff --git a/examples/Envelope/sns_linac/diagnostics.py b/examples/Envelope/sns_linac/diagnostics.py deleted file mode 100644 index 9016b7b1..00000000 --- a/examples/Envelope/sns_linac/diagnostics.py +++ /dev/null @@ -1,52 +0,0 @@ -from orbit.envelope import Envelope -from orbit.envelope import EnvelopeAnalysis - - -class BunchMonitor: - def __init__(self) -> None: - self.position_start = 0.0 - - keys = [ - "s", - "kin_energy", - "gamma", - "beta", - "rms_x", - "rms_y", - "rms_z", - "eps_x", - "eps_x_n", - "eps_y", - "eps_y_n", - "eps_z", - "eps_z_n", - "eps_1", - "eps_2", - "eps_3", - ] - self.history = {key: [] for key in keys} - - def __call__(self, params_dict: dict) -> None: - bunch = params_dict["bunch"] - node = params_dict["node"] - position = params_dict["path_length"] - - if params_dict["old_pos"] == position: - return - if params_dict["old_pos"] + params_dict["pos_step"] > position: - return - params_dict["old_pos"] = position - params_dict["count"] += 1 - - analysis = EnvelopeAnalysis(Envelope(bunch=bunch)) - results = {"s": position, **analysis.to_dict()} - for key in self.history: - self.history[key].append(results[key]) - - message = "" - message += " s={:0.3f}".format(position + self.position_start) - message += " rms_x={:0.3f}".format(1000.0 * results["rms_x"]) - message += " rms_y={:0.3f}".format(1000.0 * results["rms_y"]) - message += " rms_z={:0.3f}".format(1000.0 * results["rms_z"]) - message += " node={}".format(node.getName()) - print(message) diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac/test_sns_linac.py index 3e3f42f8..cd54b006 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac/test_sns_linac.py @@ -11,17 +11,16 @@ import argparse import math import os -import pathlib import random import sys 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.bunch import SyncParticle from orbit.core.linac import BaseRfGap from orbit.core.linac import MatrixRfGap from orbit.core.spacecharge import SpaceChargeCalcUnifEllipse @@ -44,9 +43,6 @@ from orbit.utils.consts import mass_electron from orbit.utils.consts import charge_electron -# local -from diagnostics import BunchMonitor - sys.path.append("..") from plot import plot_corner from plot import plot_rms_ellipse @@ -60,12 +56,13 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--dist", type=str, default="kv") parser.add_argument("--nparts", type=int, default=20_000) parser.add_argument("--sc", type=int, default=0) - parser.add_argument("--sc-model", type=str, default="ellipsoid") + parser.add_argument("--sc-model", type=str, default="ellipsoid", choices=("ellipsoid", "fft")) + parser.add_argument("--sc-ellipsoid-n", type=int, default=1) parser.add_argument("--sc-path-length-min", type=float, default=0.01) parser.add_argument("--current", type=float, default=0.038) parser.add_argument("--show", type=int, default=0) parser.add_argument("--seq-stop", type=str, default="CCL2") - parser.add_argument("--fit", type=int, default=1) + parser.add_argument("--fit", type=int, default=1, help="Use best-fit transfer matrices") return parser.parse_args() @@ -148,8 +145,6 @@ def make_bunch(args: argparse.Namespace) -> Bunch: class EnvelopeMonitor: - """Collect envelope parameters versus position for plotting.""" - def __init__(self) -> None: self.history = {} @@ -162,13 +157,74 @@ def __call__(self, params_dict: dict) -> None: for key, value in parameters.items(): self.history.setdefault(key, []).append(value) + message = "" + message += " s={:0.3f}".format(s) + message += " rms_x={:0.3f}".format(1000.0 * parameters["rms_x"]) + message += " rms_y={:0.3f}".format(1000.0 * parameters["rms_y"]) + message += " rms_z={:0.3f}".format(1000.0 * parameters["rms_z"]) + message += " node={}".format(params_dict["node"].getName()) + print(message) -def main(args: argparse.Namespace) -> None: - path = pathlib.Path(__file__) - output_dir = os.path.join("outputs", path.stem, time.strftime("%Y%m%d_%H%M%S")) +class BunchMonitor: + def __init__(self) -> None: + self.position_start = 0.0 + + keys = [ + "s", + "kin_energy", + "gamma", + "beta", + "rms_x", + "rms_y", + "rms_z", + "eps_x", + "eps_x_n", + "eps_y", + "eps_y_n", + "eps_z", + "eps_z_n", + "eps_1", + "eps_2", + "eps_3", + ] + self.history = {key: [] for key in keys} + + def __call__(self, params_dict: dict) -> None: + bunch = params_dict["bunch"] + node = params_dict["node"] + position = params_dict["path_length"] + + if params_dict["old_pos"] == position: + return + if params_dict["old_pos"] + params_dict["pos_step"] > position: + return + params_dict["old_pos"] = position + params_dict["count"] += 1 + + analysis = EnvelopeAnalysis(Envelope(bunch=bunch)) + results = {"s": position, **analysis.to_dict()} + for key in self.history: + self.history[key].append(results[key]) + + message = "" + message += " s={:0.3f}".format(position + self.position_start) + message += " rms_x={:0.3f}".format(1000.0 * results["rms_x"]) + message += " rms_y={:0.3f}".format(1000.0 * results["rms_y"]) + message += " rms_z={:0.3f}".format(1000.0 * results["rms_z"]) + message += " node={}".format(node.getName()) + print(message) + + +def make_output_dir(args: argparse.Namespace) -> str: + output_dir = time.strftime("%Y%m%d_%H%M%S") + output_dir = os.path.join("outputs", Path(__file__).stem, output_dir) os.makedirs(output_dir, exist_ok=True) + return output_dir + +def main(args: argparse.Namespace) -> None: + output_dir = make_output_dir(args) random.seed(23) # Track envelope @@ -178,40 +234,37 @@ def main(args: argparse.Namespace) -> None: lattice = make_lattice(args) lattice.trackDesignBunch(bunch) - envelope_monitor = EnvelopeMonitor() - envelope_actions = AccActionsContainer() - envelope_actions.addAction(envelope_monitor, AccActionsContainer.ENTRANCE) - envelope_actions.addAction(envelope_monitor, AccActionsContainer.EXIT) + monitor = EnvelopeMonitor() + action_container = AccActionsContainer() + action_container.addAction(monitor, AccActionsContainer.ENTRANCE) + action_container.addAction(monitor, AccActionsContainer.EXIT) lattice.trackEnvelope( envelope, - action_container=envelope_actions, + action_container=action_container, sc=("3d" if args.sc else None), fit=args.fit, ) - histories = {"envelope": envelope_monitor.history} + histories = {"envelope": monitor.history} # Track bunch bunch = make_bunch(args) lattice = make_lattice(args) lattice.trackDesignBunch(bunch) - if args.sc: if args.sc_model == "ellipsoid": - n_ellipsoids = 1 + n_ellipsoids = args.sc_ellipsoid_n sc_calc = SpaceChargeCalcUnifEllipse(n_ellipsoids) sc_nodes = setUniformEllipsesSCAccNodes( lattice, args.sc_path_length_min, sc_calc ) - if args.sc_model == "3d": + if args.sc_model == "fft": sc_calc = SpaceChargeCalc3D(64, 64, 64) sc_nodes = setSC3DAccNodes(lattice, args.sc_path_length_min, sc_calc) monitor = BunchMonitor() - action_container = AccActionsContainer() action_container.addAction(monitor, AccActionsContainer.ENTRANCE) action_container.addAction(monitor, AccActionsContainer.EXIT) - params_dict = {"old_pos": -1.0, "count": 0, "pos_step": args.sc_path_length_min} lattice.trackBunch(bunch, paramsDict=params_dict, actionContainer=action_container) histories["bunch"] = monitor.history @@ -219,7 +272,6 @@ def main(args: argparse.Namespace) -> None: # Analysis # -------------------------------------------------------------------------------- - # Process history arrays for mode in histories: for key in histories[mode]: histories[mode][key] = np.array(histories[mode][key]) diff --git a/examples/Envelope/sns_linac/test_sns_linac_speed.py b/examples/Envelope/sns_linac/test_sns_linac_speed.py new file mode 100644 index 00000000..3569126c --- /dev/null +++ b/examples/Envelope/sns_linac/test_sns_linac_speed.py @@ -0,0 +1,155 @@ +"""Time envelope and particle tracking through the SNS linac.""" + +import argparse +import cProfile +import pstats +import random +import time + +from orbit.bunch_generators import GaussDist3D +from orbit.bunch_generators import KVDist3D +from orbit.bunch_generators import TwissContainer +from orbit.bunch_generators import WaterBagDist3D +from orbit.core.bunch import Bunch +from orbit.core.linac import MatrixRfGap +from orbit.core.spacecharge import SpaceChargeCalc3D +from orbit.core.spacecharge import SpaceChargeCalcUnifEllipse +from orbit.envelope import Envelope +from orbit.py_linac.lattice import LinacAccLattice +from orbit.py_linac.linac_parsers import SNS_LinacLatticeFactory +from orbit.space_charge.sc3d import setSC3DAccNodes +from orbit.space_charge.sc3d import setUniformEllipsesSCAccNodes +from orbit.utils.consts import charge_electron +from orbit.utils.consts import mass_electron +from orbit.utils.consts import mass_proton + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dist", choices=("kv", "waterbag", "gauss"), default="kv") + parser.add_argument("--nparts", type=int, default=20_000) + parser.add_argument("--current", type=float, default=0.038) + parser.add_argument("--turns", type=int, default=5) + parser.add_argument("--seq-stop", default="CCL2") + parser.add_argument("--sc", type=int, default=0) + parser.add_argument("--sc-model", choices=("ellipsoid", "fft"), default="ellipsoid") + parser.add_argument("--sc-grid", type=int, default=64) + parser.add_argument("--sc-ellipsoid-n", type=int, default=1) + parser.add_argument("--sc-path-length-min", type=float, default=0.01) + parser.add_argument("--fit", type=int, default=0) + parser.add_argument("--fallback", type=int, default=0) + parser.add_argument("--static", type=int, default=0) + parser.add_argument("--bunch", action="store_true", help="Also benchmark particle tracking") + return parser.parse_args() + + +def make_lattice(args: argparse.Namespace) -> LinacAccLattice: + sequences = [ + "MEBT", "DTL1", "DTL2", "DTL3", "DTL4", "DTL5", "DTL6", + "CCL1", "CCL2", "CCL3", "CCL4", "SCLMed", "SCLHigh", "HEBT1", "HEBT2", + ] + if args.seq_stop: + sequences = sequences[:sequences.index(args.seq_stop) + 1] + + factory = SNS_LinacLatticeFactory() + factory.setMaxDriftLength(args.sc_path_length_min) + lattice = factory.getLinacAccLattice(sequences, "inputs/sns_linac.xml") + for node in lattice.getNodes(): + try: + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + except AttributeError: + pass + for gap in lattice.getRF_Gaps(): + gap.setCppGapModel(MatrixRfGap()) + return lattice + + +def make_bunch(args: argparse.Namespace) -> Bunch: + kinetic_energy = 0.0025 + mass = mass_proton + 2 * mass_electron + charge = -1.0 + intensity = args.current / 402.5e6 / (abs(charge) * charge_electron) + bunch = Bunch() + bunch.mass(mass) + bunch.charge(charge) + bunch.macroSize(intensity / args.nparts) + bunch.getSyncParticle().kinEnergy(kinetic_energy) + bunch.getSyncParticle().time(0.0) + + twiss = [ + TwissContainer(-1.962, 0.183, 2.874e-06), + TwissContainer(+1.768, 0.162, 2.874e-06), + TwissContainer(-0.0196, 116.414, 1.651e-08), + ] + distribution = { + "kv": KVDist3D, + "waterbag": WaterBagDist3D, + "gauss": GaussDist3D, + }[args.dist](*twiss) + for _ in range(args.nparts): + bunch.addParticle(*distribution.getCoordinates()) + return bunch + + +def configure_space_charge(lattice, bunch, args): + if not args.sc: + return + if args.sc_model == "ellipsoid": + calculator = SpaceChargeCalcUnifEllipse(args.sc_ellipsoid_n) + setUniformEllipsesSCAccNodes(lattice, args.sc_path_length_min, calculator) + else: + calculator = SpaceChargeCalc3D(args.sc_grid, args.sc_grid, args.sc_grid) + setSC3DAccNodes(lattice, args.sc_path_length_min, calculator) + + +def time_tracking(track, turns: int) -> float: + track() # warm-up outside the timed interval + start = time.perf_counter() + for _ in range(turns): + track() + return (time.perf_counter() - start) / turns + + +def main(args: argparse.Namespace) -> None: + random.seed(23) + lattice = make_lattice(args) + + envelope_bunch = make_bunch(args) + lattice.trackDesignBunch(envelope_bunch) + envelope = Envelope(bunch=envelope_bunch) + configure_space_charge(lattice, envelope_bunch, args) + track_envelope = lambda: lattice.trackEnvelope( + envelope, sc=("3d" if args.sc else None), fit=args.fit, static=args.static, fallback=args.fallback + ) + track_envelope() # warm-up outside the timed interval + profiler = cProfile.Profile() + profiler.enable() + start = time.perf_counter() + for _ in range(args.turns): + track_envelope() + envelope_time = (time.perf_counter() - start) / args.turns + profiler.disable() + + particle_lattice = None + bunch_time = None + if args.bunch: + particle_lattice = make_lattice(args) + bunch = make_bunch(args) + particle_lattice.trackDesignBunch(bunch) + configure_space_charge(particle_lattice, bunch, args) + bunch_time = time_tracking(lambda: particle_lattice.trackBunch(bunch), args.turns) + + print(f"lattice nodes: {len(lattice.getNodes())}") + print(f"particles: {args.nparts}") + print(f"turns: {args.turns}") + print(f"fit: {args.fit}; static: {args.static}; space charge: {args.sc_model if args.sc else 'off'}") + print(f"envelope: {envelope_time:.6f} s/turn") + if bunch_time is not None: + print(f"bunch: {bunch_time:.6f} s/turn") + print("\nEnvelope profile (top 10 by cumulative time):") + pstats.Stats(profiler).strip_dirs().sort_stats(pstats.SortKey.CUMULATIVE).print_stats(10) + + +if __name__ == "__main__": + main(parse_args()) diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring/test_sns_ring.py index 15ba2519..2708087a 100644 --- a/examples/Envelope/sns_ring/test_sns_ring.py +++ b/examples/Envelope/sns_ring/test_sns_ring.py @@ -57,7 +57,8 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--sc", type=int, default=0) parser.add_argument("--sc-grid", type=int, default=64) - parser.add_argument("--fit", type=int, default=1) + parser.add_argument("--fit", type=int, default=0) + parser.add_argument("--fallback", type=int, default=0) parser.add_argument("--fringe", type=int, default=0) parser.add_argument("--static", type=int, default=1) return parser.parse_args() @@ -154,7 +155,10 @@ def main(args: argparse.Namespace) -> None: print("TRACK ENVELOPE") envelope = Envelope( - sync_part=sync_part, + 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, @@ -165,7 +169,7 @@ def main(args: argparse.Namespace) -> None: for turn in range(args.turns + 1): if turn > 0: lattice.trackEnvelope( - envelope, sc=("2d" if args.sc else None), fit=args.fit, static=args.static, + envelope, sc=("2d" if args.sc else None), fit=args.fit, static=args.static, fallback=args.fallback ) rms = 1000.0 * analysis.rms() @@ -280,24 +284,18 @@ def main(args: argparse.Namespace) -> None: plt.close() # Plot rms emittances - color_cycle = plt.rcParams["axes.prop_cycle"].by_key()["color"] - - fig, ax = plt.subplots(figsize=(5, 3)) - for key, color in zip(["eps_x", "eps_y"], color_cycle): + for key in ["eps_x", "eps_y"]: + fig, ax = plt.subplots(figsize=(5, 3)) for i, model in enumerate(["envelope", "bunch"]): - if model == "envelope": - plot_kws = dict() - else: - plot_kws = dict(marker=".", lw=0) - label = key + "_" + model - ax.plot(histories[model][key], color=color, label=label, **plot_kws) - - ymax = 2.0 * np.mean(histories["envelope"]["eps_x"]) - ax.set_ylim(0.0, ymax) - ax.set_xlabel("Turn") - ax.set_ylabel("[mm mrad]") - plt.savefig(os.path.join(output_dir, f"fig_emittances")) - plt.close() + 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(key + " [mm mrad]") + ax.legend(loc="upper right") + plt.savefig(os.path.join(output_dir, f"fig_{key}")) + plt.close() # Plot centroids for key in ["avg_x", "avg_y"]: diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring/test_sns_ring_speed.py index d081f250..3260ad9a 100644 --- a/examples/Envelope/sns_ring/test_sns_ring_speed.py +++ b/examples/Envelope/sns_ring/test_sns_ring_speed.py @@ -34,8 +34,11 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--sc", type=int, default=0) parser.add_argument("--sc-grid", type=int, default=64) parser.add_argument("--fringe", type=int, default=0) - parser.add_argument("--fit", type=int, default=1) + parser.add_argument("--fit", type=int, default=0) parser.add_argument("--static", type=int, default=1) + parser.add_argument("--fallback", type=int, default=0) + + parser.add_argument("--bunch", action="store_true") return parser.parse_args() @@ -87,7 +90,10 @@ def main(args: argparse.Namespace) -> None: print("ENVELOPE") envelope = Envelope( - sync_part=sync_part, + kin_energy=sync_part.kinEnergy(), + mass=bunch.mass(), + charge=bunch.charge(), + time=sync_part.time(), cov_matrix=cov_matrix_init, intensity=args.intensity, ) @@ -102,7 +108,8 @@ def main(args: argparse.Namespace) -> None: envelope, static=args.static, fit=args.fit, - sc=("2d" if args.sc else None) + fallback=args.fallback, + sc=("2d" if args.sc else None), ) time_per_turn = (time.time() - start_time) / args.turns @@ -116,44 +123,45 @@ def main(args: argparse.Namespace) -> None: profiler_stats.print_stats(10) # Track bunch - print("BUNCH") + if args.bunch: + print("BUNCH") - rng = np.random.default_rng() + rng = np.random.default_rng() - bunch_coords = np.zeros((args.nparts, 6)) - bunch_coords[:, :4] = gen_dist( - size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv" - ) - bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) + bunch_coords = np.zeros((args.nparts, 6)) + bunch_coords[:, :4] = gen_dist( + size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv" + ) + bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) - for i in range(bunch_coords.shape[0]): - bunch.addParticle(*bunch_coords[i]) + for i in range(bunch_coords.shape[0]): + bunch.addParticle(*bunch_coords[i]) - if args.sc: - sc_calc = SpaceChargeCalc2p5D(64, 64, 1) - sc_path_length_min = 1.00e-06 - sc_nodes = setSC2p5DAccNodes(lattice, sc_path_length_min, sc_calc) + if args.sc: + sc_calc = SpaceChargeCalc2p5D(64, 64, 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) + bunch_size = bunch.getSizeGlobal() + bunch.macroSize(args.intensity / bunch_size) - start_time = time.time() + start_time = time.time() - profiler = cProfile.Profile() - profiler.enable() + profiler = cProfile.Profile() + profiler.enable() - for turn in trange(args.turns): - lattice.trackBunch(bunch) + for turn in trange(args.turns): + lattice.trackBunch(bunch) - time_per_turn = (time.time() - start_time) / args.turns + time_per_turn = (time.time() - start_time) / args.turns - profiler.disable() + profiler.disable() - print("Time per turn:", time_per_turn) + print("Time per turn:", time_per_turn) - profiler_stats = pstats.Stats(profiler) - profiler_stats.sort_stats(pstats.SortKey.TIME) - profiler_stats.print_stats(10) + profiler_stats = pstats.Stats(profiler) + profiler_stats.sort_stats(pstats.SortKey.TIME) + profiler_stats.print_stats(10) if __name__ == "__main__": diff --git a/examples/Envelope/test_env_3d_drift.py b/examples/Envelope/test_drift_3d.py similarity index 97% rename from examples/Envelope/test_env_3d_drift.py rename to examples/Envelope/test_drift_3d.py index ff471a58..d739022d 100644 --- a/examples/Envelope/test_env_3d_drift.py +++ b/examples/Envelope/test_drift_3d.py @@ -93,10 +93,7 @@ def main(args: argparse.Namespace) -> None: # Create envelope # ------------------------------------------------------------------------------ - bunch = Bunch() - bunch.mass(mass_proton) - sync_part = bunch.getSyncParticle() - sync_part.kinEnergy(args.kin_energy) + gamma = 1.0 + args.kin_energy / mass_proton cov_matrix_init = np.zeros((6, 6)) @@ -109,7 +106,7 @@ def main(args: argparse.Namespace) -> None: [args.rms_x, args.rms_y, args.rms_z], rotation_matrix=rotation_matrix ) - lorentz_matrix = np.diag([1.0, 1.0, 1.0 / sync_part.gamma()]) + lorentz_matrix = np.diag([1.0, 1.0, 1.0 / gamma]) cov_matrix_xyz = lorentz_matrix @ cov_matrix_xyz @ lorentz_matrix.T spatial_idx = np.ix_([0, 2, 4], [0, 2, 4]) @@ -122,7 +119,8 @@ def main(args: argparse.Namespace) -> None: centroid_init = np.zeros(6) envelope = Envelope( - sync_part=sync_part, + kin_energy=args.kin_energy, + mass=mass_proton, cov_matrix=cov_matrix_init, centroid=centroid_init, intensity=args.intensity, @@ -159,6 +157,10 @@ def main(args: argparse.Namespace) -> None: print("TRACK BUNCH") + bunch = Bunch() + bunch.mass(mass_proton) + bunch.getSyncParticle().kinEnergy(args.kin_energy) + bunch_coords = np.zeros((args.nparts, 6)) bunch_coords[:, (0, 2, 4)] = gen_dist( size=args.nparts, cov_matrix=cov_matrix_xyz, name="waterbag" diff --git a/examples/Envelope/test_env_2d_fodo.py b/examples/Envelope/test_fodo_2d.py similarity index 98% rename from examples/Envelope/test_env_2d_fodo.py rename to examples/Envelope/test_fodo_2d.py index 494190c0..41fd0c5f 100644 --- a/examples/Envelope/test_env_2d_fodo.py +++ b/examples/Envelope/test_fodo_2d.py @@ -132,7 +132,10 @@ def main(args: argparse.Namespace) -> None: # Create envelope envelope = Envelope( - sync_part=sync_part, + 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, diff --git a/examples/Envelope/test_env_2d_fodo_speed.py b/examples/Envelope/test_fodo_2d_speed.py similarity index 97% rename from examples/Envelope/test_env_2d_fodo_speed.py rename to examples/Envelope/test_fodo_2d_speed.py index ec6c4f1a..1bebae8e 100644 --- a/examples/Envelope/test_env_2d_fodo_speed.py +++ b/examples/Envelope/test_fodo_2d_speed.py @@ -82,7 +82,10 @@ print("ENVELOPE") envelope = Envelope( - sync_part=sync_part, + kin_energy=sync_part.kinEnergy(), + mass=bunch.mass(), + charge=bunch.charge(), + time=sync_part.time(), cov_matrix=cov_matrix_init, intensity=args.intensity, ) diff --git a/py/orbit/envelope/__init__.py b/py/orbit/envelope/__init__.py index 031a5fbd..38001c9e 100644 --- a/py/orbit/envelope/__init__.py +++ b/py/orbit/envelope/__init__.py @@ -1,5 +1,3 @@ from .envelope import Envelope from .analysis import EnvelopeAnalysis -from .matrix_fitting import fit_transfer_matrix -from .matrix_fitting import orbit_matrix_to_numpy from .tracking import EnvelopeTracker diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index 931ca5c1..e0b2a14c 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -1,22 +1,27 @@ +import copy +import math + import numpy as np import scipy.constants import scipy.special from orbit.core.bunch import Bunch from orbit.core.bunch import BunchTwissAnalysis -from orbit.core.bunch import SyncParticle -from orbit.utils.matrix import convert_matrix_zp_to_dE -from .utils import gen_dist +from .matrix import get_zp_coeff from .utils import get_classical_radius -from .utils import proj_cov_matrix -from .matrix_fitting import bunch_from_sync_particle +from .utils import sample_distribution + + +# For a uniform one-dimensional distribution over length L, the standard +# deviation is L / sqrt(12). This quantity is used to calculate the line +# density for two-dimensional space charge kicks. +RMS_BUNCH_LENGTH_FACTOR = math.sqrt(12.0) -def get_bunch_cov_matrix(bunch: Bunch) -> np.ndarray: +def get_bunch_covariance(bunch: Bunch) -> np.ndarray: twiss_calc = BunchTwissAnalysis() twiss_calc.analyzeBunch(bunch) - cov_matrix = np.zeros((6, 6)) for i in range(6): for j in range(6): @@ -27,130 +32,92 @@ def get_bunch_cov_matrix(bunch: Bunch) -> np.ndarray: def get_bunch_centroid(bunch: Bunch) -> np.ndarray: twiss_calc = BunchTwissAnalysis() twiss_calc.analyzeBunch(bunch) - centroid = np.zeros(6) for i in range(6): centroid[i] = twiss_calc.getAverage(i) return centroid -def build_diag_matrix_from_xyz_eig(eigenvectors: np.ndarray) -> np.ndarray: - A = np.eye(7) - for i in range(eigenvectors.shape[0]): - for j in range(eigenvectors.shape[1]): - row = i * 2 - col = j * 2 - A[row, col] = A[row + 1, col + 1] = eigenvectors[i, j] - return A - - class Envelope: - """Represents the phase space covariance matrix and centroid. - - Attributes: - sync_part: Synchronous particle. - cov_matrix: 6 x 6 covariance matrix - centroid: 6 x 1 centroid vector. - intensity: Total number of particles. - """ - + """Represents the first and second moments of a phase-space distribution..""" def __init__( self, - sync_part: SyncParticle = None, - cov_matrix: np.ndarray = None, - centroid: np.ndarray = None, + cov_matrix: np.ndarray | None = None, + centroid: np.ndarray | None = None, + kin_energy: float | None = None, + mass: float | None = None, + charge: float = 1.0, + time: float = 0.0, intensity: float = 0.0, - bunch: Bunch = None, + bunch: Bunch | None = None, ) -> None: """Constructor. - Args: - sync_part: Synchronous particle. + Args: cov_matrix: 6 x 6 covariance matrix. centroid: 6 x 1 centroid vector. - intensity: Total number of particles. - bunch: If provided, the parameters above are calculated from the bunch particles. + kin_energy: Synchronous particle kinetic energy [GeV]. + mass: Particle mass [GeV / c^2]. + charge: Particle charge [e]. + time: Synchronous particle time [s]. + intensity: Total number of particles in bunch. + bunch: If provided, the parameters above are calculated + from the bunch parameters and macroparticle coordiantes. """ - if bunch is not None: - sync_part = bunch.getSyncParticle() - cov_matrix = get_bunch_cov_matrix(bunch) + cov_matrix = get_bunch_covariance(bunch) centroid = get_bunch_centroid(bunch) - intensity = bunch.getSize() * bunch.macroSize() - - self.sync_part = sync_part - self._reference_bunch = bunch - - self.centroid = centroid - if self.centroid is None: - self.centroid = np.zeros(6) - - self.cov_matrix = cov_matrix - if self.cov_matrix is None: - self.cov_matrix = np.eye(6) - + mass = bunch.mass() + charge = bunch.charge() + sync_part = bunch.getSyncParticle() + kin_energy = sync_part.kinEnergy() + time = sync_part.time() + intensity = bunch.macroSize() * bunch.getSizeGlobal() + + self.centroid = np.zeros(6) if centroid is None else centroid + self.cov_matrix = np.eye(6) if cov_matrix is None else cov_matrix + self.kin_energy = kin_energy + self.mass = mass + self.charge = charge + self.time = time self.intensity = intensity self.classical_radius = get_classical_radius(self.charge, self.mass) + self.rms_bunch_length_factor = RMS_BUNCH_LENGTH_FACTOR - # For a uniform one-dimensional distribution over length L, the standard - # deviation is L * sqrt(12). This quantity is used to calculate the line - # density for two-dimensional space charge kicks. - self.rms_bunch_length_factor = np.sqrt(12.0) - - def copy(self): - new_bunch = bunch_from_sync_particle(self.sync_part) - new_sync_part = new_bunch.getSyncParticle() - new_envelope = Envelope( - sync_part=new_sync_part, - cov_matrix=self.cov_matrix.copy(), - centroid=self.centroid.copy(), - intensity=self.intensity, - ) - new_envelope._reference_bunch = new_bunch - new_envelope.rms_bunch_length_factor = self.rms_bunch_length_factor - new_envelope.classical_radius = self.classical_radius - return new_envelope - - @property - def kin_energy(self) -> float: - return self.sync_part.kinEnergy() + def copy(self) -> "Envelope": + return copy.deepcopy(self) @property def gamma(self) -> float: - return self.sync_part.gamma() + return 1.0 + self.kin_energy / self.mass @property def beta(self) -> float: - return self.sync_part.beta() - - @property - def mass(self) -> float: - return self.sync_part.mass() + return self.momentum / (self.kin_energy + self.mass) @property - def charge(self) -> float: - return self.sync_part.charge() + def momentum(self) -> float: + return math.sqrt(self.kin_energy * (self.kin_energy + 2.0 * self.mass)) @property - def momentum(self) -> float: - return self.sync_part.momentum() + def rigidity(self) -> float: + return 3.335640952 * self.momentum / self.charge @property def sc_factor(self) -> float: return 2.0 * self.intensity * self.classical_radius / (self.beta ** 2 * self.gamma ** 3) def rms(self, axis: int | None = None) -> float | np.ndarray: - rms_arr = np.sqrt(np.diag(self.cov_matrix)) - return rms_arr[axis] + return np.sqrt(np.diag(self.cov_matrix))[axis] - def transform(self, matrix: np.ndarray) -> None: + def apply_matrix(self, matrix: np.ndarray) -> None: m = matrix[:-1, :-1] u = matrix[:-1, -1] self.cov_matrix = m @ self.cov_matrix @ m.T - self.centroid = np.matmul(m, self.centroid) + u + self.centroid = m @ self.centroid + u def sample(self, size: int, dist: str = "kv") -> np.ndarray: - particles = gen_dist(size=size, cov_matrix=self.cov_matrix, name=dist) + particles = sample_distribution(size=size, cov_matrix=self.cov_matrix, name=dist) particles = particles + self.centroid return particles @@ -159,120 +126,77 @@ def to_bunch(self, size: int, dist: str = "gauss") -> Bunch: bunch.mass(self.mass) bunch.charge(self.charge) bunch.getSyncParticle().kinEnergy(self.kin_energy) + bunch.getSyncParticle().time(self.time) bunch.macroSize(self.intensity / size) - - particles = self.sample(size=size, dist=dist) - for i in range(particles.shape[0]): - bunch.addParticle(*particles[i]) + if size > 0: + particles = self.sample(size=size, dist=dist) + for i in range(particles.shape[0]): + bunch.addParticle(*particles[i]) return bunch def sc_matrix_2d(self, length: float) -> np.ndarray: - centroid = self.centroid cov_matrix = self.cov_matrix - - # Calculate transfer matrix in normalized (upright) frame. cov_xx = cov_matrix[0, 0] cov_yy = cov_matrix[2, 2] cov_xy = cov_matrix[0, 2] - phi = -0.5 * np.arctan2(2 * cov_xy, cov_xx - cov_yy) - sin_phi = np.sin(phi) - cos_phi = np.cos(phi) - rx = 2.0 * np.sqrt(abs(cov_xx * cos_phi**2 + cov_yy * sin_phi**2 - 2.0 * cov_xy * sin_phi * cos_phi)) - ry = 2.0 * np.sqrt(abs(cov_xx * sin_phi**2 + cov_yy * cos_phi**2 + 2.0 * cov_xy * sin_phi * cos_phi)) - - bunch_length = self.rms_bunch_length_factor * np.sqrt(cov_matrix[4, 4]) - perveance = self.sc_factor / bunch_length - kappa_factor = 2.0 * perveance / (rx + ry) - - M = np.identity(7) - M[1, 0] = kappa_factor * length / rx - M[3, 2] = kappa_factor * length / ry - - # Build matrix A to transform out of normalized frame. - A = np.eye(7) - A[0, 0] = A[1, 1] = +cos_phi - A[0, 2] = A[1, 3] = +sin_phi - A[2, 0] = A[3, 1] = -sin_phi - A[2, 2] = A[3, 3] = +cos_phi - - A_inv = A.T - - # Build matrix T to shift to beam centroid. - T = np.identity(7) - T[0, -1] = centroid[0] - T[2, -1] = centroid[2] - - T_inv = np.copy(T) - T_inv[:-1, -1] = -T[:-1, -1] - - # Compute transfer matrix in lab frame. - return T @ A @ M @ A_inv @ T_inv + # Calculate kick strengths in upright frame. + phi = -0.5 * math.atan2(2.0 * cov_xy, cov_xx - cov_yy) + sin_phi = math.sin(phi) + cos_phi = math.cos(phi) + rx = 2.0 * math.sqrt(abs(cov_xx * cos_phi**2 + cov_yy * sin_phi**2 - 2.0 * cov_xy * sin_phi * cos_phi)) + ry = 2.0 * math.sqrt(abs(cov_xx * sin_phi**2 + cov_yy * cos_phi**2 + 2.0 * cov_xy * sin_phi * cos_phi)) + + bunch_length = self.rms_bunch_length_factor * math.sqrt(cov_matrix[4, 4]) + factor = 2.0 * self.sc_factor * length / (bunch_length * (rx + ry)) + kx = factor / rx + ky = factor / ry + + # Rotate to lab frame. + kxx = kx * cos_phi**2 + ky * sin_phi**2 + kxy = (ky - kx) * sin_phi * cos_phi + kyy = kx * sin_phi**2 + ky * cos_phi**2 + matrix = np.eye(7) + matrix[1, 0] = kxx + matrix[1, 2] = matrix[3, 0] = kxy + matrix[3, 2] = kyy + + # Account for nonzero centroid. + x = self.centroid[0] + y = self.centroid[2] + matrix[1, 6] = -kxx * x - kxy * y + matrix[3, 6] = -kxy * x - kyy * y + return matrix def sc_matrix_3d(self, length: float) -> np.ndarray: - # Build Lorentz matrix: rest frame to lab frame. - # x -> x - # y -> y - # z -> z / gamma - # x' = dx/ds -> x' * gamma - # y' = dy/ds -> y' * gamma - # z' = dz/ds -> z' gamma = self.gamma - gamma_inv = 1.0 / gamma - - L = np.identity(7) - L[1, 1] = gamma - L[3, 3] = gamma - L[4, 4] = gamma_inv - L_inv = np.diag(1.0 / np.diag(L)) - - # Get centroid in rest frame. - centroid = np.matmul(L_inv[:-1, :-1], self.centroid) - - # Get covariance matrix in rest frame. - cov_matrix = L_inv[:-1, :-1] @ self.cov_matrix @ L_inv[:-1, :-1].T - - # Project covariance matrix onto x-y-z plane. - cov_matrix_proj = proj_cov_matrix(cov_matrix, axis=(0, 2, 4)) - - # Compute eigenvalues and eigenvectors of x-y-z covariance matrix. - cov_eig_res = np.linalg.eigh(cov_matrix_proj) - cov_eig_vals = cov_eig_res.eigenvalues - cov_eig_vecs = cov_eig_res.eigenvectors - - # Build transfer matrix in upright frame. - cov_xx, cov_yy, cov_zz = cov_eig_vals - RDx = scipy.special.elliprd(cov_yy, cov_zz, cov_xx) - RDy = scipy.special.elliprd(cov_xx, cov_zz, cov_yy) - RDz = scipy.special.elliprd(cov_xx, cov_yy, cov_zz) - - factor = 0.5 * self.sc_factor * ((1.0 / 5.0) ** 1.5) - kappa_x = factor * RDx - kappa_y = factor * RDy - kappa_z = factor * RDz - - M = np.identity(7) - M[1, 0] = kappa_x * length - M[3, 2] = kappa_y * length - M[5, 4] = kappa_z * length - - # Build matrix to undo x-y-z diagonalization. - A = build_diag_matrix_from_xyz_eig(cov_eig_vecs) - A_inv = A.T - - # Build matrix for translation to centroid. - T = np.identity(7) - for i in (0, 2, 4): - T[i, -1] = centroid[i] - - T_inv = np.copy(T) - T_inv[:-1, -1] = -T[:-1, -1] - - # Compute transfer matrix in lab frame. - M = L @ T @ A @ M @ A_inv @ T_inv @ L_inv - # Convert from z' to dE - return convert_matrix_zp_to_dE(M, self.sync_part) + # Get position covariance with z boosted to rest frame. + cov_position = self.cov_matrix[::2, ::2].copy() + cov_position[2, :] *= gamma + cov_position[:, 2] *= gamma + eigenvalues, eigenvectors = np.linalg.eigh(cov_position) + cov_xx, cov_yy, cov_zz = eigenvalues + + strengths = np.array([ + scipy.special.elliprd(cov_yy, cov_zz, cov_xx), + scipy.special.elliprd(cov_xx, cov_zz, cov_yy), + scipy.special.elliprd(cov_xx, cov_yy, cov_zz), + ]) + strengths *= 0.5 * self.sc_factor * (0.2**1.5) * length + + # Rotate out of upright frame. + kick = (eigenvectors * strengths) @ eigenvectors.T + + # Transform to lab frame and convert z' to dE. + kick[:2, :] *= gamma + kick[:, 2] *= gamma + kick[2, :] /= get_zp_coeff(self) + + matrix = np.eye(7) + matrix[1:6:2, :6:2] = kick + matrix[1:6:2, 6] = -kick @ self.centroid[::2] + return matrix def sc_matrix(self, length: float, model: str) -> np.ndarray: if model == "2d": @@ -280,4 +204,4 @@ def sc_matrix(self, length: float, model: str) -> np.ndarray: elif model == "3d": return self.sc_matrix_3d(length) else: - raise ValueError(f"Unknown space charge model {model}") \ No newline at end of file + raise ValueError(f"Unknown space charge model {model}") diff --git a/py/orbit/utils/matrix.py b/py/orbit/envelope/matrix.py similarity index 56% rename from py/orbit/utils/matrix.py rename to py/orbit/envelope/matrix.py index 0f884f2f..40b7d19b 100644 --- a/py/orbit/utils/matrix.py +++ b/py/orbit/envelope/matrix.py @@ -1,48 +1,45 @@ -"""Transfer matrix definitions.""" +from __future__ import annotations + import math +from typing import TYPE_CHECKING import numpy as np -from orbit.core.bunch import SyncParticle -from orbit.core.orbit_utils import Matrix from orbit.utils.consts import speed_of_light +if TYPE_CHECKING: + from .envelope import Envelope + -def get_dp_p_coeff(sync_part: SyncParticle) -> float: +def get_dp_p_coeff(envelope: Envelope) -> float: # dE/E = (beta^2) * dp/p # dE = (beta^2 * E) * dp/p # dE = (beta^2 * gamma * m * c^2) * dp/p - beta = sync_part.beta() - gamma = sync_part.gamma() - rest_energy = sync_part.mass() # GeV - return 1.0 / (beta**2 * gamma * rest_energy) + return 1.0 / (envelope.beta**2 * envelope.gamma * envelope.mass) -def get_zp_coeff(sync_part: SyncParticle) -> float: +def get_zp_coeff(envelope: Envelope) -> float: # dE/E = (beta^2) * dp/p = (beta^2) * (gamma^2) z' # dE = (beta^2 * gamma^2 * E) * z' # dE = (beta^2 * gamma^3 * m * c^2) * z' - beta = sync_part.beta() - gamma = sync_part.gamma() - rest_energy = sync_part.mass() - return 1.0 / (beta**2 * gamma**3 * rest_energy) + return 1.0 / (envelope.beta**2 * envelope.gamma**3 * envelope.mass) -def convert_matrix_dp_p_to_dE(matrix: np.ndarray, sync_part: SyncParticle) -> np.ndarray: +def convert_matrix_dp_p_to_dE(matrix: np.ndarray, envelope: Envelope) -> np.ndarray: # v = [x, x', y, y', z, dp/p] # w = [x, x', y, y', z, dE] # v = A w # v -> M v # w -> A M A^-1 - dp_p_coeff = get_dp_p_coeff(sync_part) + dp_p_coeff = get_dp_p_coeff(envelope) matrix[:5, 5] *= dp_p_coeff matrix[5, :5] /= dp_p_coeff matrix[5, 6] /= dp_p_coeff # driving term return matrix -def convert_matrix_zp_to_dE(matrix: np.ndarray, sync_part: SyncParticle) -> np.ndarray: - zp_coeff = get_zp_coeff(sync_part) +def convert_matrix_zp_to_dE(matrix: np.ndarray, envelope: Envelope) -> np.ndarray: + zp_coeff = get_zp_coeff(envelope) matrix[:5, 5] *= zp_coeff matrix[5, :5] /= zp_coeff matrix[5, 6] /= zp_coeff # driving term @@ -69,20 +66,19 @@ def get_matrix_kick(kx: float = 0.0, ky: float = 0.0, kE: float = 0.0) -> np.nda return M -def get_matrix_drift(sync_part: SyncParticle, length: float) -> np.ndarray: +def get_matrix_drift(envelope: Envelope, length: float) -> np.ndarray: M = np.identity(7) M[0, 1] = length M[2, 3] = length - M[4, 5] = length / (sync_part.gamma() ** 2) - M[4, 5] *= get_dp_p_coeff(sync_part) # convert_matrix_dp_p_to_dE(M, sync_part) - - sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + M[4, 5] = length / (envelope.gamma ** 2) + M[4, 5] *= get_dp_p_coeff(envelope) # convert_matrix_dp_p_to_dE(M, envelope) + envelope.time += length / (envelope.beta * speed_of_light) return M -def get_matrix_quad(sync_part: SyncParticle, length: float, kq: float) -> np.ndarray: +def get_matrix_quad(envelope: Envelope, length: float, kq: float) -> np.ndarray: if abs(kq) == 0: - return get_matrix_drift(sync_part, length) + return get_matrix_drift(envelope, length) sqrt_abs_kq = math.sqrt(abs(kq)) @@ -114,14 +110,22 @@ def get_matrix_quad(sync_part: SyncParticle, length: float, kq: float) -> np.nda M[3, 2] = -sy * sqrt_abs_kq M[3, 3] = cy - M[4, 5] = length / (sync_part.gamma()**2) - M[4, 5] *= get_dp_p_coeff(sync_part) # convert_matrix_dp_p_to_dE(M, sync_part) - - sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + M[4, 5] = length / (envelope.gamma**2) + M[4, 5] *= get_dp_p_coeff(envelope) # convert_matrix_dp_p_to_dE(M, envelope) + envelope.time += length / (envelope.beta * speed_of_light) return M -def get_matrix_bend(sync_part: SyncParticle, length: float, theta: float) -> np.ndarray: +def get_matrix_bend_edge(angle: float, rho: float, fringe: bool = True) -> np.ndarray: + matrix = np.eye(7) + strength = math.tan(angle) / rho + matrix[1, 0] = strength + if fringe: + matrix[3, 2] = -strength + return matrix + + +def get_matrix_bend(envelope: Envelope, length: float, theta: float) -> np.ndarray: rho = length / theta cx = math.cos(theta) sx = math.sin(theta) @@ -136,16 +140,16 @@ def get_matrix_bend(sync_part: SyncParticle, length: float, theta: float) -> np. M[2, 3] = length M[4, 0] = -sx M[4, 1] = -rho * (1.0 - cx) - M[4, 5] = -(sync_part.beta() ** 2) * length + rho * sx - M[:5, 5] *= get_dp_p_coeff(sync_part) # convert_matrix_dp_p_to_dE(M, sync_part) + M[4, 5] = -(envelope.beta ** 2) * length + rho * sx + M[:5, 5] *= get_dp_p_coeff(envelope) # convert_matrix_dp_p_to_dE(M, envelope) - sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + envelope.time += length / (envelope.beta * speed_of_light) return M -def get_matrix_solenoid(sync_part: SyncParticle, length: float, B: float) -> np.ndarray: +def get_matrix_solenoid(envelope: Envelope, length: float, B: float) -> np.ndarray: if B == 0: - return get_matrix_drift(sync_part, length) + return get_matrix_drift(envelope, length) phase = B * length @@ -167,18 +171,18 @@ def get_matrix_solenoid(sync_part: SyncParticle, length: float, B: float) -> np. M[2, 3] = math.sin(phase) / B M[3, 2] = math.sin(phase) * B * -1.0 M[3, 3] = math.cos(phase) - M[4, 5] = length / (sync_part.gamma()**2) + M[4, 5] = length / (envelope.gamma**2) M = np.linalg.inv(V) @ M @ V - M[4, 5] *= get_dp_p_coeff(sync_part) # convert_matrix_dp_p_to_dE(M, sync_part) + M[4, 5] *= get_dp_p_coeff(envelope) # convert_matrix_dp_p_to_dE(M, envelope) - sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + envelope.time += length / (envelope.beta * speed_of_light) return M -def get_matrix_cf(sync_part: SyncParticle, length: float, kq: float) -> np.ndarray: +def get_matrix_cf(envelope: Envelope, length: float, kq: float) -> np.ndarray: if kq == 0: - return get_matrix_drift(sync_part, length) + return get_matrix_drift(envelope, length) sqrt_abs_kq = math.sqrt(abs(kq)) @@ -190,35 +194,35 @@ def get_matrix_cf(sync_part: SyncParticle, length: float, kq: float) -> np.ndarr M[0, 1] = M[2, 3] = +sx / sqrt_abs_kq M[1, 0] = M[3, 2] = -sx * sqrt_abs_kq M[1, 1] = M[3, 3] = cx - M[4, 5] = length / (sync_part.gamma()**2) - M[4, 5] *= get_dp_p_coeff(sync_part) + M[4, 5] = length / (envelope.gamma**2) + M[4, 5] *= get_dp_p_coeff(envelope) - sync_part.time(sync_part.time() + length / (sync_part.beta() * speed_of_light)) + envelope.time += length / (envelope.beta * speed_of_light) return M -def get_matrix_rf_gap(sync_part: SyncParticle, frequency: float, E0TL: float, phase: float) -> np.ndarray: - gamma = sync_part.gamma() - beta = sync_part.beta() - mass = sync_part.mass() - charge = sync_part.charge() +def get_matrix_rf_gap(envelope: Envelope, frequency: float, E0TL: float, phase: float) -> np.ndarray: + gamma = envelope.gamma + beta = envelope.beta + mass = envelope.mass + charge = envelope.charge - kin_energy_in = sync_part.kinEnergy() + kin_energy_in = envelope.kin_energy charge_E0TL_sin = charge * E0TL * math.sin(phase) kin_energy_delta = charge * E0TL * math.cos(phase) # Calculate parameters in the center of the gap. - sync_part.momentum(sync_part.energyToMomentum(kin_energy_in + kin_energy_delta / 2.0)) - gamma_gap = sync_part.gamma() - beta_gap = sync_part.beta() + envelope.kin_energy = kin_energy_in + kin_energy_delta / 2.0 + gamma_gap = envelope.gamma + beta_gap = envelope.beta # Move to the end of the gap. kin_energy_out = kin_energy_in + kin_energy_delta - sync_part.momentum(sync_part.energyToMomentum(kin_energy_out)) + envelope.kin_energy = kin_energy_out # The base RF gap is simple - no phase correction. - gamma_out = sync_part.gamma() - beta_out = sync_part.beta() + gamma_out = envelope.gamma + beta_out = envelope.beta prime_coeff = (beta * gamma) / (beta_out * gamma_out) # Wave momentum @@ -237,11 +241,3 @@ def get_matrix_rf_gap(sync_part: SyncParticle, frequency: float, E0TL: float, ph M[1, 0] = d_rp M[3, 2] = d_rp return M - - -def orbit_matrix_to_numpy(matrix: Matrix) -> np.ndarray: - matrix_out = np.zeros(matrix.size()) - for i in range(matrix_out.shape[0]): - for j in range(matrix_out.shape[1]): - matrix_out[i, j] = matrix.get(i, j) - return matrix_out diff --git a/py/orbit/envelope/matrix_fitting.py b/py/orbit/envelope/matrix_fitting.py index 83a7435e..b0f811f0 100644 --- a/py/orbit/envelope/matrix_fitting.py +++ b/py/orbit/envelope/matrix_fitting.py @@ -5,43 +5,23 @@ import numpy as np from orbit.core.bunch import Bunch -from orbit.core.bunch import SyncParticle from orbit.core.orbit_utils import Matrix from orbit.core.teapot_base import MatrixGenerator - if TYPE_CHECKING: from orbit.lattice import AccLattice from orbit.lattice import AccNode def orbit_matrix_to_numpy(matrix: Matrix) -> np.ndarray: - matrix_out = np.zeros(matrix.size()) - for i in range(matrix_out.shape[0]): - for j in range(matrix_out.shape[1]): - matrix_out[i, j] = matrix.get(i, j) + matrix_out = np.empty(matrix.size(), dtype=np.float64) + matrix.copyToBuffer(matrix_out) return matrix_out -def copy_sync_particle(source: SyncParticle, target: SyncParticle) -> None: - target.rVector(source.rVector()) - target.pVector(source.pVector()) - target.nxVector(source.nxVector()) - target.time(source.time()) - - -def bunch_from_sync_particle(sync_part: SyncParticle) -> Bunch: - bunch = Bunch() - bunch.mass(sync_part.mass()) - bunch.charge(sync_part.charge()) - copy_sync_particle(sync_part, bunch.getSyncParticle()) - return bunch - - -def fit_node_transfer_matrix( +def fit_node_matrix( node: AccNode, bunch: Bunch, part_index: int = -1, - parent_node: AccNode | AccLattice | None = None, matrix_generator: MatrixGenerator | None = None, lost_bunch: Bunch | None = None, params_dict: dict | None = None, @@ -62,8 +42,6 @@ def fit_node_transfer_matrix( params_dict["bunch"] = bunch params_dict["lostbunch"] = lost_bunch params_dict["node"] = node - if parent_node is not None: - params_dict["parentNode"] = parent_node active_part_index = node.getActivePartIndex() if part_index >= 0: @@ -77,7 +55,7 @@ def fit_node_transfer_matrix( return orbit_matrix_to_numpy(matrix) -def fit_transfer_matrix( +def fit_lattice_matrix( lattice: AccLattice, bunch: Bunch, index_start: int = 0, diff --git a/py/orbit/envelope/meson.build b/py/orbit/envelope/meson.build index be25a806..869cb67b 100644 --- a/py/orbit/envelope/meson.build +++ b/py/orbit/envelope/meson.build @@ -1,9 +1,11 @@ py_sources = files([ '__init__.py', - 'envelope.py', 'analysis.py', - 'tracking.py', + 'envelope.py', + 'matrix.py', 'matrix_fitting.py', + 'node_matrices.py', + 'tracking.py', 'utils.py' ]) diff --git a/py/orbit/envelope/node_matrices.py b/py/orbit/envelope/node_matrices.py new file mode 100644 index 00000000..27600388 --- /dev/null +++ b/py/orbit/envelope/node_matrices.py @@ -0,0 +1,279 @@ +import math +from functools import singledispatch + +import numpy as np + +from orbit.teapot.teapot import TurnCounterTEAPOT +from orbit.teapot.teapot import NodeTEAPOT +from orbit.teapot.teapot import DriftTEAPOT +from orbit.teapot.teapot import ApertureTEAPOT +from orbit.teapot.teapot import MonitorTEAPOT +from orbit.teapot.teapot import BunchWrapTEAPOT +from orbit.teapot.teapot import SolenoidTEAPOT +from orbit.teapot.teapot import MultipoleTEAPOT +from orbit.teapot.teapot import QuadTEAPOT +from orbit.teapot.teapot import BendTEAPOT +from orbit.teapot.teapot import KickTEAPOT +from orbit.teapot.teapot import TiltTEAPOT +from orbit.teapot.teapot import FringeFieldTEAPOT +from orbit.teapot.teapot import ContinuousLinearFocusingTEAPOT +from orbit.py_linac.lattice.LinacAccNodes import MarkerLinacNode +from orbit.py_linac.lattice.LinacAccNodes import Drift +from orbit.py_linac.lattice.LinacAccNodes import Quad +from orbit.py_linac.lattice.LinacAccNodes import Bend +from orbit.py_linac.lattice.LinacAccNodes import DCorrectorH +from orbit.py_linac.lattice.LinacAccNodes import DCorrectorV +from orbit.py_linac.lattice.LinacAccNodes import Solenoid +from orbit.py_linac.lattice.LinacAccNodes import TiltElement +from orbit.py_linac.lattice.LinacAccNodes import FringeField +from orbit.py_linac.lattice.LinacRfGapNodes import BaseRF_Gap + +from .envelope import Envelope +from .matrix import get_matrix_bend +from .matrix import get_matrix_bend_edge +from .matrix import get_matrix_cf +from .matrix import get_matrix_drift +from .matrix import get_matrix_kick +from .matrix import get_matrix_quad +from .matrix import get_matrix_rf_gap +from .matrix import get_matrix_solenoid +from .matrix import get_matrix_tilt + + +@singledispatch +def get_node_matrix(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + raise NotImplementedError(str(node)) + + +@get_node_matrix.register(ApertureTEAPOT) +@get_node_matrix.register(BunchWrapTEAPOT) +@get_node_matrix.register(MonitorTEAPOT) +@get_node_matrix.register(TurnCounterTEAPOT) +@get_node_matrix.register(MarkerLinacNode) +def _matrix_identity(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + return None + + +@get_node_matrix.register(NodeTEAPOT) +def _matrix_node_teapot(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + if type(node) is NodeTEAPOT: + return None + raise NotImplementedError(str(node)) + + +@get_node_matrix.register(DriftTEAPOT) +@get_node_matrix.register(Drift) +def _matrix_drift(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getLength(part_index) + if length <= 0: + return None + return get_matrix_drift(envelope, length) + + +@get_node_matrix.register(SolenoidTEAPOT) +def _matrix_solenoid_teapot(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getLength(part_index) + if length <= 0: + return None + B = node.getParam("B") + if node.waveform: + B *= node.waveform.getStrength() + B *= np.sign(envelope.charge) + return get_matrix_solenoid(envelope, length=length, B=B) + + +@get_node_matrix.register(MultipoleTEAPOT) +def _matrix_multipole_teapot(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getLength(part_index) + if length <= 0: + return None + if np.all(np.abs(node.getParam("kls")) == 0): + return get_matrix_drift(envelope, length) + raise NotImplementedError(str(node)) + + +@get_node_matrix.register(QuadTEAPOT) +def _matrix_quad_teapot(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getLength(part_index) + if length <= 0: + return None + kq = node.getParam("kq") + if node.waveform: + kq *= node.waveform.getStrength() + return get_matrix_quad(envelope, length=length, kq=kq) + + +@get_node_matrix.register(BendTEAPOT) +def _matrix_bend_teapot(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + if np.any(np.asarray(node.getParam("kls")) != 0): + raise NotImplementedError + + length = node.getLength(part_index) + if length <= 0: + return None + + nparts = node.getnParts() + if part_index < 0: + theta = node.getParam("theta") + else: + theta = node.getParam("theta") / (nparts - 1) + if part_index == 0 or part_index == nparts - 1: + theta *= 0.5 + return get_matrix_bend(envelope, length=length, theta=theta) + + +@get_node_matrix.register(KickTEAPOT) +def _matrix_kick_teapot(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getLength(part_index) + nparts = node.getnParts() + + if part_index == nparts - 1: + return get_matrix_drift(envelope, length) if length > 0 else None + + scale = 1.0 + if node.waveform is not None: + scale = node.waveform.getStrength() + + kx = scale * node.getParam("kx") / (nparts - 1) + ky = scale * node.getParam("ky") / (nparts - 1) + kE = node.getParam("dE") / (nparts - 1) + + if abs(kx) == abs(ky) == abs(kE) == 0: + return get_matrix_drift(envelope, length) if length > 0 else None + + matrix_kick = get_matrix_kick(kx=kx, ky=ky, kE=kE) + matrix_drift = get_matrix_drift(envelope, length) + return matrix_kick @ matrix_drift + + +@get_node_matrix.register(TiltTEAPOT) +@get_node_matrix.register(TiltElement) +def _matrix_tilt(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + angle = node.getTiltAngle() + if angle == 0: + return None + return get_matrix_tilt(angle) + + +@get_node_matrix.register(FringeFieldTEAPOT) +@get_node_matrix.register(FringeField) +def _matrix_fringe_field(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + if node.getType() in ("bend fringe in", "bend fringe out"): + usage = node.getUsage() + # Linac fringes skip their entire callback when disabled; TEAPOT + # fringes still apply the geometric wedge transformations. + if isinstance(node, FringeField) and not usage: + return None + if np.any(np.asarray(node.getParam("kls")) != 0): + raise NotImplementedError + angle = node.getParam("ea1" if node.getType() == "bend fringe in" else "ea2") + if angle == 0.0: + return None + return get_matrix_bend_edge(angle, node.getParam("rho"), fringe=usage) + params_dict = node.getParamsDict() + if params_dict.get("ea1", 0.0) != 0.0 or params_dict.get("ea2", 0.0) != 0.0: + raise NotImplementedError("Bend edge fringes require a fitted matrix") + return None + + +@get_node_matrix.register(ContinuousLinearFocusingTEAPOT) +def _matrix_continuous_focusing_teapot(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getLength(part_index) + if length <= 0: + return None + kq = node.getParam("kq") + if node.waveform: + kq *= node.waveform.getStrength() + return get_matrix_cf(envelope, length=length, kq=kq) + + +@get_node_matrix.register(Quad) +def _matrix_quad_linac(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getLength(part_index) + if length <= 0: + return None + kq = node.getParam("dB/dr") / envelope.rigidity + return get_matrix_quad(envelope, length=length, kq=kq) + + +@get_node_matrix.register(Bend) +def _matrix_bend_linac(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + if np.any(np.asarray(node.getParam("kls")) != 0): + raise NotImplementedError("Combined-function bends require a fitted matrix") + length = node.getLength(part_index) + if length <= 0: + return None + nparts = node.getnParts() + theta = node.getParam("theta") / (nparts - 1) + if part_index == 0 or part_index == nparts - 1: + theta *= 0.5 + return get_matrix_bend(envelope, length=length, theta=theta) + + +@get_node_matrix.register(DCorrectorH) +def _matrix_corrector_h(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getParam("effLength") / node.getnParts() + field = node.getParam("B") + delta_xp = -field * envelope.charge * length * 0.299792 / envelope.momentum + if delta_xp == 0: + return None + return get_matrix_kick(kx=delta_xp, ky=0.0, kE=0.0) + + +@get_node_matrix.register(DCorrectorV) +def _matrix_corrector_v(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getParam("effLength") / node.getnParts() + field = node.getParam("B") + delta_yp = -field * envelope.charge * length * 0.299792 / envelope.momentum + if delta_yp == 0: + return None + return get_matrix_kick(kx=0.0, ky=delta_yp, kE=0.0) + + +@get_node_matrix.register(Solenoid) +def _matrix_solenoid_linac(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + length = node.getLength(part_index) + if length <= 0: + return None + B = node.getParam("B") * np.sign(envelope.charge) + return get_matrix_solenoid(envelope, length=length, B=B) + + +@get_node_matrix.register(BaseRF_Gap) +def _matrix_rf_gap(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: + E0TL = node.getParam("E0TL") + mode_phase = node.getParam("mode") * math.pi + + cavity = node.getRF_Cavity() + frequency = cavity.getFrequency() + phase = cavity.getPhase() + mode_phase + amplitude = cavity.getAmp() + + arrival_time = envelope.time + arrival_time_design = cavity.getDesignArrivalTime() + + if node.isFirstRFGap(): + if cavity.isDesignSetUp(): + phase = math.fmod( + frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, + 2.0 * math.pi, + ) + else: + raise ValueError("Run `trackDesign` first to initialize cavity phases.") + else: + phase = math.fmod( + frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, + 2.0 * math.pi, + ) + + node.setGapPhase(phase) + + if amplitude == 0.0: + return None + + return get_matrix_rf_gap( + envelope=envelope, + frequency=frequency, + E0TL=(E0TL * amplitude), + phase=phase, + ) diff --git a/py/orbit/envelope/tracking.py b/py/orbit/envelope/tracking.py index 84b4cdc2..9ca12545 100644 --- a/py/orbit/envelope/tracking.py +++ b/py/orbit/envelope/tracking.py @@ -7,13 +7,11 @@ import numpy as np from orbit.core.bunch import Bunch -from orbit.core.bunch import SyncParticle from orbit.core.teapot_base import MatrixGenerator from .envelope import Envelope -from .matrix_fitting import bunch_from_sync_particle -from .matrix_fitting import copy_sync_particle -from .matrix_fitting import fit_node_transfer_matrix +from .matrix_fitting import fit_node_matrix +from .node_matrices import get_node_matrix if TYPE_CHECKING: from orbit.lattice import AccActionsContainer @@ -27,17 +25,12 @@ @dataclass class NodeMap: matrix: np.ndarray | None - reference_position: tuple[float, float, float] - reference_momentum: tuple[float, float, float] - reference_x_axis: tuple[float, float, float] - time_advance: float + kin_energy: float + time: float - def update_sync_particle(self, sync_part: SyncParticle) -> None: - current_time = sync_part.time() - sync_part.rVector(self.reference_position) - sync_part.pVector(self.reference_momentum) - sync_part.nxVector(self.reference_x_axis) - sync_part.time(current_time + self.time_advance) + def update_envelope(self, envelope: Envelope) -> None: + envelope.kin_energy = self.kin_energy + envelope.time = self.time class EnvelopeTracker: @@ -47,13 +40,10 @@ def __init__( index_start: int = 0, index_stop: int | None = None, fit: bool = True, - fallback: bool = True, + fallback: bool = False, ) -> None: self.lattice = lattice - - self.index_start = index_start - self.index_start = max(self.index_start, 0) - + self.index_start = max(index_start, 0) self.index_stop = index_stop if self.index_stop is None or self.index_stop < 0: self.index_stop = len(self.lattice.getNodes()) @@ -63,9 +53,9 @@ def __init__( self.fit = fit self.fallback = fallback - self._node_maps = None - self._reference_bunch = None + self._bunch = None self._matrix_generator = None + self._node_maps = None def track( self, @@ -74,11 +64,10 @@ def track( params_dict: ParamsDict | None = None, action_container: AccActionsContainer | None = None, return_matrix: bool = False, - store_maps: bool = False, + store: bool = False, ) -> np.ndarray | None: from orbit.lattice import AccActionsContainer - from orbit.lattice import AccLattice from orbit.lattice import AccNode if sc not in (None, False, "2d", "3d"): @@ -90,29 +79,21 @@ def track( if action_container is None: action_container = AccActionsContainer() - params_dict.update( - envelope=envelope, - lattice=self.lattice, - action_container=action_container - ) + params_dict["lattice"] = self.lattice + params_dict["envelope"] = envelope params_dict.setdefault("path_length", 0.0) if hasattr(self.lattice, "getUseRealCharge"): params_dict.setdefault("useCharge", self.lattice.getUseRealCharge()) - total_matrix = None - if return_matrix: - total_matrix = np.eye(7) - - self._reference_bunch = None - self._matrix_generator = None - - node_maps = {} if store_maps else self._node_maps - identity_matrix = np.eye(7) if store_maps else None + total_matrix = np.eye(7) if return_matrix else None + node_maps = {} if store else self._node_maps + identity_matrix = np.eye(7) if store else None + handlers = {} def apply_matrix(matrix: np.ndarray | None) -> None: nonlocal total_matrix if matrix is not None: - envelope.transform(matrix) + envelope.apply_matrix(matrix) if total_matrix is not None: total_matrix = matrix @ total_matrix @@ -123,16 +104,17 @@ def push_envelope(params_dict: ParamsDict) -> None: length = node.getLength(part_index) if length > 0: apply_matrix(envelope.sc_matrix(length, model=sc)) - if node_maps is not None and not store_maps: + if node_maps and not store: node_map = node_maps[node, part_index] + node_map.update_envelope(envelope) + matrix = node_map.matrix else: - node_map = self._get_node_map(params_dict) - if store_maps: - if node_map.matrix is not None and np.array_equal(node_map.matrix, identity_matrix): - node_map.matrix = None - node_maps[node, part_index] = node_map - node_map.update_sync_particle(envelope.sync_part) - apply_matrix(node_map.matrix) + matrix = self._get_node_matrix(params_dict, part_index, handlers) + if store: + if matrix is not None and np.array_equal(matrix, identity_matrix): + matrix = None + node_maps[node, part_index] = NodeMap(matrix, envelope.kin_energy, envelope.time) + apply_matrix(matrix) action_container.addAction(push_envelope, AccNode.BODY) try: @@ -145,7 +127,7 @@ def push_envelope(params_dict: ParamsDict) -> None: ) finally: action_container.removeAction(push_envelope, AccNode.BODY) - if store_maps: + if store: self._node_maps = node_maps return total_matrix @@ -153,45 +135,48 @@ def precompute(self, envelope: Envelope, params_dict: ParamsDict | None = None) self.track( envelope=envelope.copy(), params_dict=None if params_dict is None else params_dict.copy(), - store_maps=True, + store=True, ) - def _get_node_map(self, params_dict: ParamsDict) -> NodeMap: + def _get_node_matrix(self, params_dict: ParamsDict, part_index: int, handlers: dict) -> np.ndarray | None: node = params_dict["node"] - sync_part = params_dict["envelope"].sync_part - if self._reference_bunch is None: - self._reference_bunch = bunch_from_sync_particle(sync_part) - reference_sync_part = self._reference_bunch.getSyncParticle() - copy_sync_particle(sync_part, reference_sync_part) - start_time = sync_part.time() - part_index = node.getActivePartIndex() + envelope = params_dict["envelope"] + initial_kinetic_energy = envelope.kin_energy + initial_time = envelope.time + use_fit = self.fit if not use_fit: + handler = handlers.get(type(node)) + if handler is None: + handler = handlers[type(node)] = get_node_matrix.dispatch(type(node)) try: - matrix = node.getMatrix(reference_sync_part, part_index=part_index) + matrix = handler(node, envelope, part_index=part_index) except NotImplementedError: + envelope.kin_energy = initial_kinetic_energy + envelope.time = initial_time if not self.fallback: raise - copy_sync_particle(sync_part, reference_sync_part) use_fit = True if use_fit: + if self._bunch is None: + self._bunch = Bunch() + self._bunch.mass(envelope.mass) + self._bunch.charge(envelope.charge) + sync_particle = self._bunch.getSyncParticle() + sync_particle.kinEnergy(envelope.kin_energy) + sync_particle.time(envelope.time) if self._matrix_generator is None: self._matrix_generator = MatrixGenerator() - matrix = fit_node_transfer_matrix( + matrix = fit_node_matrix( node=node, - bunch=self._reference_bunch, + bunch=self._bunch, part_index=part_index, - parent_node=params_dict["parentNode"], matrix_generator=self._matrix_generator, params_dict=params_dict, ) + envelope.kin_energy = sync_particle.kinEnergy() + envelope.time = sync_particle.time() - return NodeMap( - matrix=matrix, - reference_position=tuple(reference_sync_part.rVector()), - reference_momentum=tuple(reference_sync_part.pVector()), - reference_x_axis=tuple(reference_sync_part.nxVector()), - time_advance=reference_sync_part.time() - start_time, - ) + return matrix diff --git a/py/orbit/envelope/utils.py b/py/orbit/envelope/utils.py index 9102794e..9876fbcc 100644 --- a/py/orbit/envelope/utils.py +++ b/py/orbit/envelope/utils.py @@ -11,7 +11,7 @@ def get_classical_radius(charge: float, mass: float) -> float: return q**2 / (4.0 * math.pi * epsilon_0 * rest_energy) -def gen_dist_gauss(size: int, cov_matrix: np.ndarray) -> np.ndarray: +def sample_distribution_gauss(size: int, cov_matrix: np.ndarray) -> np.ndarray: return np.random.multivariate_normal( mean=np.zeros(cov_matrix.shape[0]), cov=cov_matrix, @@ -19,15 +19,15 @@ def gen_dist_gauss(size: int, cov_matrix: np.ndarray) -> np.ndarray: ) -def gen_dist_kv(size: int, cov_matrix: np.ndarray) -> np.ndarray: +def sample_distribution_kv(size: int, cov_matrix: np.ndarray) -> np.ndarray: X = np.random.normal(size=(size, cov_matrix.shape[0])) X /= np.linalg.norm(X, axis=1)[:, None] X /= np.std(X, axis=0) return X -def gen_dist_waterbag(size: int, cov_matrix: np.ndarray) -> np.ndarray: - X = gen_dist_kv(size, cov_matrix) +def sample_distribution_waterbag(size: int, cov_matrix: np.ndarray) -> np.ndarray: + X = sample_distribution_kv(size, cov_matrix) dim = X.shape[1] r = np.random.uniform(size=size) ** (1.0 / dim) X *= r[:, None] @@ -35,21 +35,21 @@ def gen_dist_waterbag(size: int, cov_matrix: np.ndarray) -> np.ndarray: return X -def gen_dist(size: int, cov_matrix: np.ndarray, name: str) -> np.ndarray: +def sample_distribution(size: int, cov_matrix: np.ndarray, name: str) -> np.ndarray: if name == "kv": - X = gen_dist_kv(size, cov_matrix) + X = sample_distribution_kv(size, cov_matrix) elif name == "waterbag": - X = gen_dist_waterbag(size, cov_matrix) + X = sample_distribution_waterbag(size, cov_matrix) elif name == "gauss": - X = gen_dist_gauss(size, cov_matrix) + X = sample_distribution_gauss(size, cov_matrix) else: raise ValueError(f"Invalid distribution name: {name}") L = np.linalg.cholesky(cov_matrix) - return np.matmul(X, L.T) + return X @ L.T -def proj_cov_matrix(cov_matrix: np.ndarray, axis: tuple[int, ...]) -> np.ndarray: +def project_covariance_matrix(cov_matrix: np.ndarray, axis: tuple[int, ...]) -> np.ndarray: cov_matrix_proj = np.zeros((len(axis), len(axis))) for i in range(len(axis)): for j in range(len(axis)): diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index d7007025..400dc6f1 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -1,10 +1,10 @@ +from __future__ import annotations + import os +from typing import TYPE_CHECKING import numpy as np -from orbit.envelope import Envelope -from orbit.envelope import EnvelopeTracker - from orbit.utils import orbitFinalize from orbit.utils import NamedObject from orbit.utils import TypedObject @@ -12,6 +12,10 @@ from .AccActionsContainer import AccActionsContainer from .AccNode import AccNode +if TYPE_CHECKING: + from orbit.envelope.envelope import Envelope + from orbit.envelope.tracking import EnvelopeTracker + class AccLattice(NamedObject, TypedObject): """ @@ -63,8 +67,6 @@ def initialize(self): d = [0.0] posn = {} - self._envelope_tracker = None - def accNodeExitAction(paramsDict): """ Nonbound function. Sets lattice length and node @@ -304,6 +306,8 @@ def trackEnvelope( If `return_matrix`, returns the total transfer matrix (including linear space charge). Otherwise, returns None. """ + from orbit.envelope.tracking import EnvelopeTracker + tracker = EnvelopeTracker( self, index_start=index_start, diff --git a/py/orbit/lattice/AccNode.py b/py/orbit/lattice/AccNode.py index 1926ff9c..bc4a2e40 100644 --- a/py/orbit/lattice/AccNode.py +++ b/py/orbit/lattice/AccNode.py @@ -3,7 +3,6 @@ import sys import os import math -from typing import TYPE_CHECKING from ..utils import orbitFinalize from ..utils import NamedObject @@ -12,10 +11,6 @@ from .AccActionsContainer import AccActionsContainer -if TYPE_CHECKING: - import numpy as np - from orbit.core.bunch import SyncParticle - class AccNode(NamedObject, TypedObject, ParamsDictObject): """ @@ -152,12 +147,6 @@ def initialize(self): """ pass - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - """ - Return the transfer matrix for this node and update the synchronous particle. - """ - raise NotImplementedError(str(self)) - def getNumberOfChildren(self): """ Returns the total number of direct children diff --git a/py/orbit/py_linac/lattice/LinacAccNodes.py b/py/orbit/py_linac/lattice/LinacAccNodes.py index 208c2996..2765adf1 100755 --- a/py/orbit/py_linac/lattice/LinacAccNodes.py +++ b/py/orbit/py_linac/lattice/LinacAccNodes.py @@ -8,25 +8,16 @@ import os import math -import numpy as np # import the finalization function from orbit.utils import orbitFinalize # import general accelerator elements and lattice from orbit.lattice import AccNode, AccActionsContainer, AccNodeBunchTracker -from orbit.core.bunch import SyncParticle # import teapot base functions from wrapper around C++ functions from orbit.teapot_base import TPB -from orbit.utils.matrix import get_matrix_bend -from orbit.utils.matrix import get_matrix_cf -from orbit.utils.matrix import get_matrix_drift -from orbit.utils.matrix import get_matrix_kick -from orbit.utils.matrix import get_matrix_quad -from orbit.utils.matrix import get_matrix_solenoid -from orbit.utils.matrix import get_matrix_tilt # Import the linac specific tracking from linac_tracking. This module has # the following functions duplicated the original TEAPOT functions @@ -151,10 +142,6 @@ def __init__(self, name="none"): BaseLinacNode.__init__(self, name) self.setType("markerLinacNode") - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - return None - - class LinacNode(BaseLinacNode): """ The abstract class of the linac accelerator elements hierarchy that can be tilted. @@ -321,13 +308,6 @@ def track(self, paramsDict): bunch = paramsDict["bunch"] self.tracking_module.drift(bunch, length) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - if length <= 0: - return None - return get_matrix_drift(sync_part, length) - - class Quad(LinacMagnetNode): """ Quad Combined Function TEAPOT element. @@ -536,16 +516,6 @@ def getTotalField(self, z): G = self.getParam("dB/dr") return G - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - if length <= 0: - return None - - brho = 3.335640952 * sync_part.momentum() / sync_part.charge() - kq = self.getParam("dB/dr") / brho - return get_matrix_quad(sync_part, length=length, kq=kq) - - class Bend(LinacMagnetNode): """ Bend Combined Functions TEAPOT element. @@ -562,6 +532,8 @@ def __init__(self, name="bend no name"): self.addParam("ea1", 0.0) self.addParam("ea2", 0.0) + self.getNodeFringeFieldIN().setType("bend fringe in") + self.getNodeFringeFieldOUT().setType("bend fringe out") self.addParam("rho", 0.0) self.addParam("theta", 1.0e-36) @@ -737,22 +709,6 @@ def track(self, paramsDict): TPB.bend1(bunch, length, theta / 2.0) return - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - if self.getParam("ea1") != 0.0 or self.getParam("ea2") != 0.0: - raise NotImplementedError("Bends with edge angles require a fitted matrix") - - length = self.getLength(part_index) - if length <= 0: - return None - - nparts = self.getnParts() - theta = self.getParam("theta") / (nparts - 1) - if part_index == 0 or part_index == nparts - 1: - theta *= 0.5 - - return get_matrix_bend(sync_part, length=length, theta=theta) - - class DCorrectorH(LinacMagnetNode): """ The Horizontal Dipole Corrector. @@ -797,15 +753,6 @@ def track(self, paramsDict): kick = -field * charge * length * 0.299792 / momentum self.tracking_module.kick(bunch, kick, 0.0, 0.0) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getParam("effLength") / self.getnParts() - field = self.getParam("B") - delta_xp = -field * sync_part.charge() * length * 0.299792 / sync_part.momentum() - if delta_xp == 0: - return None - return get_matrix_kick(kx=delta_xp, ky=0.0, kE=0.0) - - class DCorrectorV(LinacMagnetNode): """ The Vertical Dipole Corrector. @@ -850,15 +797,6 @@ def track(self, paramsDict): kick = field * charge * length * 0.299792 / momentum self.tracking_module.kick(bunch, 0, kick, 0.0) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getParam("effLength") / self.getnParts() - field = self.getParam("B") - delta_yp = -field * sync_part.charge() * length * 0.299792 / sync_part.momentum() - if delta_yp == 0: - return None - return get_matrix_kick(kx=0.0, ky=delta_yp, kE=0.0) - - class ThickKick(LinacMagnetNode): """ Thick kiker linac node. @@ -955,13 +893,6 @@ def track(self, paramsDict): useCharge = paramsDict["useCharge"] TPB.soln(bunch, length, B, useCharge) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - if length <= 0: - return None - B = self.getParam("B") * np.sign(sync_part.charge()) - return get_matrix_solenoid(sync_part, length=length, B=B) - class AbstractRF_Gap(BaseLinacNode): """ This is an abstarct class for all RF Gap classes. @@ -1080,13 +1011,6 @@ def track(self, paramsDict): bunch = paramsDict["bunch"] TPB.rotatexy(bunch, self.__angle) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - angle = self.getTiltAngle() - if angle == 0: - return None - return get_matrix_tilt(angle=angle) - - class FringeField(BaseLinacNode): """ The class is a base class for the fringe field classes for others elements. @@ -1110,12 +1034,6 @@ def track(self, paramsDict): if self.__trackFunc != None and self.__usage == True: self.__trackFunc(self, paramsDict) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - params_dict = self.getParamsDict() - if params_dict.get("ea1", 0.0) != 0.0 or params_dict.get("ea2", 0.0) != 0.0: - raise NotImplementedError("Bend edge fringes require a fitted matrix") - return None - def setFringeFieldFunction(self, trackFunction=None): """ Sets the fringe field function that will track the bunch through the fringe. diff --git a/py/orbit/py_linac/lattice/LinacRfGapNodes.py b/py/orbit/py_linac/lattice/LinacRfGapNodes.py index 6f482f39..dd28a848 100644 --- a/py/orbit/py_linac/lattice/LinacRfGapNodes.py +++ b/py/orbit/py_linac/lattice/LinacRfGapNodes.py @@ -5,7 +5,6 @@ import os import math -import numpy as np # ---- MPI module function and classes from orbit.core.orbit_mpi import mpi_comm, mpi_datatype, MPI_Comm_rank, MPI_Bcast @@ -27,7 +26,6 @@ # The abstract RF gap import from orbit.py_linac.lattice.LinacAccNodes import AbstractRF_Gap -from orbit.utils.matrix import get_matrix_rf_gap # import teapot base functions from wrapper around C++ functions @@ -38,7 +36,6 @@ # quad2 - linac quad non-linear part of tracking from orbit.core.bunch import Bunch -from orbit.core.bunch import SyncParticle class BaseRF_Gap(AbstractRF_Gap): @@ -255,44 +252,6 @@ def track(self, paramsDict): # print "debug delta_time in deg=",frequency*(arrival_time - designArrivalTime)*380. # print "debug RF =",self.getName()," E0TL=",E0TL," phase=",(phase*180./math.pi - 180.)," eKin[MeV]=",bunch.getSyncParticle().kinEnergy()*1.0e+3 - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - E0TL = self.getParam("E0TL") - mode_phase = self.getParam("mode") * math.pi - - cavity = self.getRF_Cavity() - frequency = cavity.getFrequency() - phase = cavity.getPhase() + mode_phase - amplitude = cavity.getAmp() - - arrival_time = sync_part.time() - arrival_time_design = cavity.getDesignArrivalTime() - - if self.isFirstRFGap(): - if cavity.isDesignSetUp(): - phase = math.fmod( - frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, - 2.0 * math.pi, - ) - else: - raise ValueError("Run `trackDesign` first to initialize cavity phases.") - else: - phase = math.fmod( - frequency * (arrival_time - arrival_time_design) * 2.0 * math.pi + phase, - 2.0 * math.pi, - ) - - self.setGapPhase(phase) - - if amplitude == 0.0: - return None - - return get_matrix_rf_gap( - sync_part=sync_part, - frequency=frequency, - E0TL=(E0TL * amplitude), - phase=phase, - ) - def trackDesign(self, paramsDict): """ The RF First Gap node setups the design time of passage diff --git a/py/orbit/teapot/teapot.py b/py/orbit/teapot/teapot.py index 77cc0276..ce2903d2 100644 --- a/py/orbit/teapot/teapot.py +++ b/py/orbit/teapot/teapot.py @@ -19,7 +19,6 @@ import sys import os import math -import numpy as np from typing import Any from typing import Callable from typing import Union @@ -34,17 +33,9 @@ from orbit.parsers.mad_parser import MAD_LattElement from orbit.parsers.madx_parser import MADX_Parser from orbit.parsers.madx_parser import MADX_LattElement -from orbit.utils.matrix import get_matrix_bend -from orbit.utils.matrix import get_matrix_cf -from orbit.utils.matrix import get_matrix_drift -from orbit.utils.matrix import get_matrix_kick -from orbit.utils.matrix import get_matrix_quad -from orbit.utils.matrix import get_matrix_solenoid -from orbit.utils.matrix import get_matrix_tilt from orbit.core.aperture import Aperture from orbit.core.bunch import Bunch -from orbit.core.bunch import SyncParticle from orbit.core.bunch import BunchTwissAnalysis @@ -449,10 +440,6 @@ def track(self, paramsDict: dict) -> None: turn = bunch.bunchAttrInt("TurnNumber") bunch.bunchAttrInt("TurnNumber", turn + 1) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - return None - - class NodeTEAPOT(BaseTEAPOT): def __init__(self, name: str = "no name") -> None: """ @@ -476,11 +463,6 @@ def __init__(self, name: str = "no name") -> None: self.addParam("tilt", self.__tiltNodeIN.getTiltAngle()) self.setType("node teapot") - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - if type(self) is NodeTEAPOT: - return None - return super().getMatrix(sync_part, part_index=part_index) - def setTiltAngle(self, angle: float = 0.0) -> None: """ Sets the tilt angle for the tilt operation. @@ -599,13 +581,6 @@ def track(self, paramsDict: dict) -> None: bunch = paramsDict["bunch"] TPB.drift(bunch, length) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - if length <= 0: - return None - return get_matrix_drift(sync_part, length) - - class ApertureTEAPOT(NodeTEAPOT): """ Aperture TEAPOT element. @@ -645,10 +620,6 @@ def track(self, paramsDict: dict) -> None: lostbunch = paramsDict["lostbunch"] self.aperture.checkBunch(bunch, lostbunch) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - return None - - class MonitorTEAPOT(NodeTEAPOT): """ Monitor TEAPOT element. @@ -675,10 +646,6 @@ def track(self, paramsDict: dict) -> None: self.addParam("yAvg", self.twiss.getAverage(2)) self.addParam("ypAvg", self.twiss.getAverage(3)) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - return None - - class BunchWrapTEAPOT(NodeTEAPOT): """ Drift TEAPOT element. @@ -702,10 +669,6 @@ def track(self, paramsDict: dict) -> None: length = self.getParam("ring_length") TPB.wrapbunch(bunch, length) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - return None - - class SolenoidTEAPOT(NodeTEAPOT): """ Solenoid TEAPOT element. @@ -753,19 +716,6 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - if length <= 0: - return None - - B = self.getParam("B") - if self.waveform: - B *= self.waveform.getStrength() - B *= np.sign(sync_part.charge()) - - return get_matrix_solenoid(sync_part, length=length, B=B) - - class MultipoleTEAPOT(NodeTEAPOT): """ Multipole Combined Function TEAPOT element. @@ -915,17 +865,6 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - if length <= 0: - return None - - if np.all(np.abs(self.getParam("kls")) == 0): - return get_matrix_drift(sync_part, length) - - raise NotImplementedError(str(self)) - - class QuadTEAPOT(NodeTEAPOT): """ Quad Combined Function TEAPOT element. @@ -1088,18 +1027,6 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - if length <= 0: - return None - - kq = self.getParam("kq") - if self.waveform: - kq *= self.waveform.getStrength() - - return get_matrix_quad(sync_part, length=length, kq=kq) - - class BendTEAPOT(NodeTEAPOT): """ Bend Combined Functions TEAPOT element. @@ -1128,6 +1055,8 @@ def __init__( self.addParam("ea1", ea1) self.addParam("ea2", ea2) + self.getNodeFringeFieldIN().setType("bend fringe in") + self.getNodeFringeFieldOUT().setType("bend fringe out") self.addParam("theta", theta) self.setnParts(nparts) @@ -1313,25 +1242,6 @@ def track(self, paramsDict: dict) -> None: TPB.bend1(bunch, length, theta / 2.0) return - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - if self.getParam("ea1") != 0.0 or self.getParam("ea2") != 0.0: - raise NotImplementedError("Bends with edge angles require a fitted matrix") - - length = self.getLength(part_index) - if length <= 0: - return None - - nparts = self.getnParts() - if part_index < 0: - theta = self.getParam("theta") - else: - theta = self.getParam("theta") / (nparts - 1) - if part_index == 0 or part_index == nparts - 1: - theta *= 0.5 - - return get_matrix_bend(sync_part, length=length, theta=theta) - - class RingRFTEAPOT(NodeTEAPOT): """ Ring RF TEAPOT element. @@ -1497,27 +1407,6 @@ def setWaveform(self, waveform): """ self.waveform = waveform - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - nparts = self.getnParts() - - scale = 1.0 - if self.waveform is not None: - scale = self.waveform.getStrength() - - scale /= nparts - 1 - kx = scale * self.getParam("kx") - ky = scale * self.getParam("ky") - kE = self.getParam("dE") - - if abs(kx) > 0 or abs(ky) > 0 or abs(kE) > 0: - return np.matmul( - get_matrix_kick(kx=kx, ky=ky, kE=kE), - get_matrix_drift(sync_part, length), - ) - return get_matrix_drift(sync_part, length) - - class TiltTEAPOT(BaseTEAPOT): """ The class to do tilt at the entrance of an TEAPOT element. @@ -1552,13 +1441,6 @@ def track(self, paramsDict: dict) -> None: bunch = paramsDict["bunch"] TPB.rotatexy(bunch, self.__angle) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - angle = self.getTiltAngle() - if angle == 0: - return None - return get_matrix_tilt(angle) - - class FringeFieldTEAPOT(BaseTEAPOT): """ The class is a base class for the fringe field classes for others TEAPOT elements. @@ -1587,12 +1469,6 @@ def track(self, paramsDict: dict) -> None: if self.__trackFunc != None: self.__trackFunc(self, paramsDict) - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - params_dict = self.getParamsDict() - if params_dict.get("ea1", 0.0) != 0.0 or params_dict.get("ea2", 0.0) != 0.0: - raise NotImplementedError("Bend edge fringes require a fitted matrix") - return None - def setFringeFieldFunction(self, trackFunction: Callable) -> None: """ Sets the fringe field function that will track the bunch through the fringe. @@ -1710,14 +1586,3 @@ def track(self, paramsDict): def setWaveform(self, waveform): self.waveform = waveform - - def getMatrix(self, sync_part: SyncParticle, part_index: int = -1) -> np.ndarray | None: - length = self.getLength(part_index) - if length <= 0: - return None - - kq = self.getParam("kq") - if self.waveform: - kq *= self.waveform.getStrength() - - return get_matrix_cf(sync_part, length=length, kq=kq) diff --git a/py/orbit/utils/meson.build b/py/orbit/utils/meson.build index 7ada54d2..6d969897 100644 --- a/py/orbit/utils/meson.build +++ b/py/orbit/utils/meson.build @@ -12,8 +12,7 @@ py_sources = files([ 'consts.py', 'multiDimArray.py', 'NamedObject.py', - 'orbitFinalize.py', - 'matrix.py' + 'orbitFinalize.py' ]) python.install_sources( diff --git a/src/utils/matrix/wrap_matrix.cc b/src/utils/matrix/wrap_matrix.cc index eb2bc14d..9b95fd21 100644 --- a/src/utils/matrix/wrap_matrix.cc +++ b/src/utils/matrix/wrap_matrix.cc @@ -6,6 +6,7 @@ #include "wrap_bunch.hh" #include +#include #include "Matrix.hh" #include "PhaseVector.hh" @@ -112,6 +113,34 @@ extern "C" { return Py_BuildValue("(i,i)",cpp_Matrix->rows(),cpp_Matrix->columns()); } + // Copy all elements into a writable, C-contiguous native-double buffer. + static PyObject* Matrix_copyToBuffer(PyObject *self, PyObject *target){ + Matrix* matrix = (Matrix*) ((pyORBIT_Object*) self)->cpp_obj; + Py_buffer buffer; + if(PyObject_GetBuffer(target, &buffer, PyBUF_WRITABLE | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS) < 0){ + return NULL; + } + if(buffer.itemsize != sizeof(double) || buffer.format == NULL || std::strcmp(buffer.format, "d") != 0){ + PyBuffer_Release(&buffer); + PyErr_SetString(PyExc_TypeError, "copyToBuffer requires a native float64 buffer"); + return NULL; + } + if(buffer.ndim != 2 || buffer.shape[0] != matrix->rows() || + buffer.shape[1] != matrix->columns()){ + PyBuffer_Release(&buffer); + PyErr_SetString(PyExc_ValueError, "copyToBuffer requires the same shape as the matrix"); + return NULL; + } + char* destination = (char*) buffer.buf; + const size_t row_bytes = matrix->columns() * sizeof(double); + double** source = matrix->getArray(); + for(int i = 0; i < matrix->rows(); i++){ + std::memcpy(destination + i * row_bytes, source[i], row_bytes); + } + PyBuffer_Release(&buffer); + Py_RETURN_NONE; + } + // copy() - returns the new Matrix that is equal to the parent one static PyObject* Matrix_copy(PyObject *self, PyObject *args){ pyORBIT_Object* pyMatrix = (pyORBIT_Object*) self; @@ -289,6 +318,8 @@ extern "C" { // defenition of the methods of the python Matrix wrapper class // they will be vailable from python level static PyMethodDef MatrixClassMethods[] = { + { "copyToBuffer", Matrix_copyToBuffer, METH_O, + "Copy values into a writable C-contiguous float64 buffer with matching shape."}, { "size", Matrix_size ,METH_VARARGS,"Returns tuple with (n,m)"}, { "get", Matrix_get_set ,METH_VARARGS,"Returns valuie(i,j)"}, { "set", Matrix_get_set ,METH_VARARGS,"Sets the new value to (i,j) element - set (i,j,val)"}, diff --git a/tests/py/orbit/test_envelope.py b/tests/py/orbit/test_envelope.py index 5c8eff8d..ad237147 100644 --- a/tests/py/orbit/test_envelope.py +++ b/tests/py/orbit/test_envelope.py @@ -6,7 +6,10 @@ from orbit.core.linac import MatrixRfGap from orbit.bunch_utils import collect_bunch from orbit.envelope import Envelope -from orbit.envelope import fit_transfer_matrix +from orbit.envelope import EnvelopeTracker +from orbit.envelope.node_matrices import get_node_matrix +from orbit.envelope.node_matrices import get_node_matrix as analytic_node_matrix +from orbit.envelope.matrix_fitting import fit_lattice_matrix from orbit.lattice import AccNode from orbit.lattice import AccActionsContainer from orbit.lattice import AccNodeBunchTracker @@ -234,8 +237,8 @@ def test_bend_teapot_edge_matrix(charge: float): bunch.charge(charge) bunch.getSyncParticle().kinEnergy(1.3) - matrix_fit = fit_transfer_matrix(lattice, bunch) - envelope = Envelope(sync_part=bunch.getSyncParticle()) + matrix_fit = fit_lattice_matrix(lattice, bunch) + envelope = Envelope(bunch=bunch) matrix_analytic = lattice.trackEnvelope(envelope.copy(), fit=False, return_matrix=True) assert np.allclose(matrix_analytic, matrix_fit, atol=1.0e-10) @@ -254,8 +257,8 @@ def test_fitted_envelope_matrices(): bunch.mass(mass_proton) bunch.getSyncParticle().kinEnergy(1.3) - matrix_expected = fit_transfer_matrix(lattice, bunch) - envelope = Envelope(sync_part=bunch.getSyncParticle()) + matrix_expected = fit_lattice_matrix(lattice, bunch) + envelope = Envelope(bunch=bunch) matrix_actual = lattice.trackEnvelope(envelope.copy(), return_matrix=True, fit=True) assert np.allclose(matrix_actual, matrix_expected, atol=1.0e-12) @@ -319,6 +322,8 @@ def test_solenoid_linac(charge: float): @pytest.mark.parametrize("charge", [1.0, -1.0]) def test_rf_gap_matrix(charge: float): + from orbit.envelope.matrix import get_matrix_rf_gap + kin_energy = 0.0025 frequency = 402.5e06 E0TL = 0.001 @@ -343,14 +348,9 @@ def test_rf_gap_matrix(charge: float): coords_out_1 = collect_bunch(bunch_out_1)["coords"] - from orbit.utils.matrix import get_matrix_rf_gap - - bunch_out_2 = Bunch() - bunch_in.copyBunchTo(bunch_out_2) - - sync_part = bunch_in.getSyncParticle() + reference = Envelope(bunch=bunch_in) matrix = get_matrix_rf_gap( - sync_part, + reference, frequency=frequency, E0TL=E0TL, phase=phase, @@ -359,6 +359,8 @@ def test_rf_gap_matrix(charge: float): coords_out_2 = np.matmul(coords_in, matrix.T) coords_out_2 = coords_out_2[:, :-1] assert np.allclose(coords_out_1, coords_out_2) + assert reference.kin_energy == pytest.approx(bunch_out_1.getSyncParticle().kinEnergy()) + assert reference.beta == pytest.approx(bunch_out_1.getSyncParticle().beta()) def test_sc_3d_cold_expansion(): @@ -369,7 +371,12 @@ def test_sc_3d_cold_expansion(): radius = 0.01 gamma = bunch.getSyncParticle().gamma() covariance = np.diag([radius**2 / 5, 0, radius**2 / 5, 0, radius**2 / (5 * gamma**2), 0]) - envelope = Envelope(sync_part=bunch.getSyncParticle(), cov_matrix=covariance, intensity=1e8) + envelope = Envelope( + kin_energy=bunch.getSyncParticle().kinEnergy(), + mass=bunch.mass(), + cov_matrix=covariance, + intensity=1e8, + ) coefficient = envelope.intensity * envelope.classical_radius / (envelope.beta * gamma)**2 distance = np.sqrt(radius**3 / (2 * coefficient)) * (np.sqrt(2) + np.arcsinh(1)) lattice = make_lattice([DriftTEAPOT(length=distance, nparts=1000)]) @@ -386,7 +393,7 @@ def test_track_sublattice_no_error(): sync_part.kinEnergy(0.001) cov_matrix = np.diag(np.square([1e-3, 0, 1e-3, 0.0, 1e-3, 0.0])) - envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix) + envelope = Envelope(kin_energy=sync_part.kinEnergy(), mass=bunch.mass(), cov_matrix=cov_matrix) lattice = TEAPOT_Lattice() @@ -413,277 +420,84 @@ def test_get_total_matrix(charge: float, static: bool) -> None: sync_part.kinEnergy(0.001) cov_matrix = make_default_cov_matrix() - envelope = Envelope(sync_part=sync_part, cov_matrix=cov_matrix, intensity=1e7) + envelope = Envelope( + kin_energy=sync_part.kinEnergy(), + mass=bunch.mass(), + charge=charge, + cov_matrix=cov_matrix, + intensity=1e7, + ) envelope_out_a = envelope.copy() lattice.trackEnvelope(envelope_out_a, sc="2d") matrix = lattice.trackEnvelope(envelope.copy(), return_matrix=True, sc="2d", static=static) envelope_out_b = envelope.copy() - envelope_out_b.transform(matrix) + envelope_out_b.apply_matrix(matrix) assert np.all(np.isclose(envelope_out_a.cov_matrix, envelope_out_b.cov_matrix)) -def make_test_envelope(): - bunch = Bunch() - bunch.getSyncParticle().kinEnergy(1.3) - bunch.getSyncParticle().time(10.0) - return Envelope(sync_part=bunch.getSyncParticle(), cov_matrix=make_default_cov_matrix()).copy() - - -@pytest.mark.parametrize("fit", [False, True]) -def test_static_reuse_options_and_reset(monkeypatch, fit): - from orbit.envelope import EnvelopeTracker - - lattice = make_lattice([DriftTEAPOT(length=0.2), DriftTEAPOT(length=0.7)]) - envelope = make_test_envelope() - calls = [] - original = EnvelopeTracker.precompute - - def precompute(self, envelope, params_dict=None): - calls.append((self.index_start, self.index_stop, self.fit, self.fallback)) - return original(self, envelope, params_dict=params_dict) - - monkeypatch.setattr(EnvelopeTracker, "precompute", precompute) - expected = envelope.copy() - for _ in range(3): - lattice.trackEnvelope(expected, fit=fit) - for _ in range(3): - lattice.trackEnvelope(envelope, static=True, fit=fit) - assert len(calls) == 1 - assert envelope.sync_part.time() == pytest.approx(expected.sync_part.time(), rel=0, abs=1e-14) - np.testing.assert_allclose(envelope.cov_matrix, expected.cov_matrix) - for options in [dict(index_stop=0, fit=fit), dict(index_stop=0, fit=not fit), - dict(index_stop=0, fit=not fit, fallback=False)]: - actual = make_test_envelope() - reference = actual.copy() - reference_lattice = make_lattice([DriftTEAPOT(length=0.2), DriftTEAPOT(length=0.7)]) - reference_lattice.trackEnvelope(reference, **options) - lattice.trackEnvelope(actual, static=True, **options) - np.testing.assert_allclose(actual.cov_matrix, reference.cov_matrix) - assert len(calls) == 4 - lattice.initialize() - lattice.trackEnvelope(envelope, static=True) - assert len(calls) == 5 - lattice.trackEnvelope(envelope, static=False) - lattice.trackEnvelope(envelope, static=True) - assert len(calls) == 6 - - -@pytest.mark.parametrize("static", [False, True]) -@pytest.mark.parametrize("start,stop,length", [(0, 0, .1), (1, 1, .2), (1, 2, .5), - (0, -1, .6), (0, -2, .6), (-1, None, .6), (3, None, 0), (2, 0, 0)]) -def test_sublattice_results(static, start, stop, length): - from orbit.utils.matrix import get_matrix_drift - - lattice = make_lattice([DriftTEAPOT(length=x) for x in [.1, .2, .3]]) - envelope = make_test_envelope() - reference = envelope.copy() - expected_matrix = get_matrix_drift(reference.sync_part, length) - matrix = lattice.trackEnvelope(envelope, index_start=start, index_stop=stop, - static=static, fit=False, return_matrix=True) - np.testing.assert_allclose(matrix, expected_matrix, atol=1e-14) - assert envelope.sync_part.time() == pytest.approx(reference.sync_part.time(), rel=0, abs=1e-14) - - -@pytest.mark.parametrize("static", [False, True]) -@pytest.mark.parametrize("fit", [False, True]) -def test_actions_match_bunch_traversal(static, fit): - parent = DriftTEAPOT(name="parent", length=.4, nparts=2) - for place, part, location in [(AccNode.ENTRANCE, 0, AccNode.AFTER), - (AccNode.BODY, 0, AccNode.BEFORE), (AccNode.BODY, 1, AccNode.AFTER), - (AccNode.EXIT, 0, AccNode.AFTER)]: - parent.addChildNode(DriftTEAPOT(name=f"child-{place}-{part}", length=.1), - place, part_index=part, place_in_part=location) - lattice = make_lattice([parent]) - envelope = make_test_envelope() - envelope.centroid[1] = .001 - bunch = Bunch() - bunch.mass(envelope.mass) - bunch.charge(envelope.charge) - bunch.getSyncParticle().kinEnergy(envelope.kin_energy) - bunch.getSyncParticle().time(10) - bunch.addParticle(*envelope.centroid) - - def observe(beam_key): - actions = AccActionsContainer() - events = [] - for place in [AccNode.ENTRANCE, AccNode.BODY, AccNode.EXIT]: - def action(params_dict, place=place): - assert params_dict["actions"] is actions - assert params_dict["custom"] == "retained" - beam = params_dict[beam_key] - sync_part = beam.sync_part if beam_key == "envelope" else beam.getSyncParticle() - x = beam.centroid[0] if beam_key == "envelope" else beam.x(0) - events.append((params_dict["node"].getName(), params_dict["parentNode"].getName(), - place, params_dict["node"].getActivePartIndex(), params_dict["path_length"], - sync_part.time(), x)) - actions.addAction(action, place) - return actions, events - - bunch_actions, expected = observe("bunch") - lattice.trackBunch(bunch, paramsDict={"custom": "retained"}, actionContainer=bunch_actions) - actions, actual = observe("envelope") - original = [list(actions.getActions(place)) for place in range(3)] - lattice.trackEnvelope(envelope, params_dict={"custom": "retained"}, action_container=actions, - static=static, fit=fit) - assert len(actual) == len(expected) - for observed, reference in zip(actual, expected): - assert observed[:4] == reference[:4] - np.testing.assert_allclose(observed[4:], reference[4:], rtol=0, atol=1e-12) - assert [actions.getActions(place) for place in range(3)] == original - - -@pytest.mark.parametrize("failure", ["action", "matrix"]) -def test_actions_removed_after_failure(failure): - class FailingDrift(DriftTEAPOT): - def getMatrix(self, sync_part, part_index=-1): - raise RuntimeError("matrix failure") - - node = FailingDrift(length=.1) if failure == "matrix" else DriftTEAPOT(length=.1) - lattice = make_lattice([node]) - actions = AccActionsContainer() - def fail(params_dict): - raise RuntimeError("action failure") - if failure == "action": - actions.addAction(fail, AccNode.EXIT) - original = [list(actions.getActions(place)) for place in range(3)] - with pytest.raises(RuntimeError, match=f"{failure} failure"): - lattice.trackEnvelope(make_test_envelope(), fit=False, action_container=actions) - assert [actions.getActions(place) for place in range(3)] == original - if failure == "action": - actions.removeAction(fail, AccNode.EXIT) - healthy = make_lattice([DriftTEAPOT(length=.1)]) - healthy.trackEnvelope(make_test_envelope(), action_container=actions) - assert all(not actions.getActions(place) for place in range(3)) - - -@pytest.mark.parametrize("static", [False, True]) -@pytest.mark.parametrize("fallback", [False, True]) -def test_missing_matrix_fallback(static, fallback): - class UnsupportedDrift(DriftTEAPOT): - def getMatrix(self, sync_part, part_index=-1): - raise NotImplementedError("missing matrix") - lattice = make_lattice([UnsupportedDrift(length=.3)]) - envelope = make_test_envelope() - if not fallback: - with pytest.raises(NotImplementedError, match="missing matrix"): - lattice.trackEnvelope(envelope, fit=False, fallback=False, static=static) - else: - expected = envelope.copy() - lattice.trackEnvelope(expected, fit=True) - lattice.trackEnvelope(envelope, fit=False, fallback=True, static=static) - np.testing.assert_allclose(envelope.cov_matrix, expected.cov_matrix) - - -@pytest.mark.parametrize("result", [None, ValueError("invalid matrix")]) -def test_fallback_respects_none_and_other_errors(result): - class CustomNode(AccNode): - def getMatrix(self, sync_part, part_index=-1): - if isinstance(result, Exception): - raise result - return result - def track(self, params_dict): - pytest.fail("Unexpected fitting") - lattice = make_lattice([CustomNode()]) - envelope = make_test_envelope() - if isinstance(result, Exception): - with pytest.raises(ValueError, match="invalid matrix"): - lattice.trackEnvelope(envelope, fit=False) - else: - expected = envelope.copy() - lattice.trackEnvelope(envelope, fit=False) - np.testing.assert_array_equal(envelope.cov_matrix, expected.cov_matrix) - - -@pytest.mark.parametrize("fit", [False, True]) -def test_reference_updates_and_preparation_independence(fit): - from orbit.envelope import EnvelopeTracker - class AcceleratingNode(AccNode): - def update(self, sync_part): - sync_part.kinEnergy(sync_part.kinEnergy() + .1) - sync_part.time(sync_part.time() + .25) - sync_part.rVector(tuple(x + .1 for x in sync_part.rVector())) - sync_part.nxVector((0, 1, 0)) - def getMatrix(self, sync_part, part_index=-1): - self.update(sync_part) - return np.eye(7) - def track(self, params_dict): - self.update(params_dict["bunch"].getSyncParticle()) - lattice = make_lattice([AcceleratingNode(), AcceleratingNode()]) - envelope = make_test_envelope() - tracker = EnvelopeTracker(lattice, fit=fit) - params_dict = {"path_length": 5} - tracker.precompute(envelope, params_dict=params_dict) - assert params_dict == {"path_length": 5} - assert envelope.sync_part.time() == 10 - assert envelope.kin_energy == pytest.approx(1.3) - np.testing.assert_array_equal(envelope.sync_part.rVector(), (0, 0, 0)) - # Dynamic transport must recalculate at the updated energy on each turn. - lattice.trackEnvelope(envelope, fit=fit) - lattice.trackEnvelope(envelope, fit=fit) - assert envelope.kin_energy == pytest.approx(1.7) - assert envelope.sync_part.time() == pytest.approx(11) - np.testing.assert_allclose(envelope.sync_part.rVector(), (.4, .4, .4)) - np.testing.assert_allclose(envelope.sync_part.nxVector(), (0, 1, 0)) - - -def test_envelope_copy_owns_reference_state(): - import gc - original = make_test_envelope() - original.sync_part.rVector((1, 2, 3)) - original.sync_part.nxVector((0, 1, 0)) - original.centroid[:] = np.arange(6) - original.intensity = 123 - original.rms_bunch_length_factor = 4 - copied = original.copy() - for attr in ["mass", "charge", "kinEnergy", "time", "rVector", "pVector", "nxVector"]: - np.testing.assert_allclose(getattr(copied.sync_part, attr)(), getattr(original.sync_part, attr)()) - assert copied.intensity == original.intensity - assert copied.classical_radius == original.classical_radius - assert copied.rms_bunch_length_factor == 4 - copied.centroid[0] = 99 - copied.cov_matrix[0, 0] = 99 - copied.sync_part.time(20) - copied.sync_part.kinEnergy(.5) - assert original.centroid[0] == 0 - assert original.cov_matrix[0, 0] != 99 - assert original.sync_part.time() == 10 - assert original.kin_energy == pytest.approx(1.3) - del original - gc.collect() - assert copied.copy().kin_energy == pytest.approx(.5) - - @pytest.mark.parametrize("kind", ["teapot", "linac"]) -@pytest.mark.parametrize("fringe", [False, True]) +@pytest.mark.parametrize("fringe_in,fringe_out", [(False, False), (True, False), (False, True), (True, True)]) @pytest.mark.parametrize("static", [False, True]) -@pytest.mark.parametrize("ea1,ea2", [(0.1, 0), (0, -.05), (.1, -.05)]) -def test_edge_bends_with_fringe(kind, fringe, static, ea1, ea2): +@pytest.mark.parametrize("theta", [0.2, -0.2]) +@pytest.mark.parametrize("charge", [1.0, -1.0]) +@pytest.mark.parametrize("ea1,ea2", [(0.1, 0), (0, -0.05), (0.1, -0.05)]) +def test_edge_bends_with_fringe(kind, fringe_in, fringe_out, static, theta, charge, ea1, ea2): if kind == "teapot": - node = BendTEAPOT(length=1, theta=.2, ea1=ea1, ea2=ea2, nparts=5) + node = BendTEAPOT(length=1, theta=theta, ea1=ea1, ea2=ea2, nparts=5) else: node = Bend() node.setLength(1) node.setnParts(5) - for name, value in [("theta", .2), ("ea1", ea1), ("ea2", ea2)]: + for name, value in [("theta", theta), ("ea1", ea1), ("ea2", ea2)]: node.setParam(name, value) + lattice = make_lattice([node]) - if hasattr(node, "setUsageFringeFieldIN"): - node.setUsageFringeFieldIN(fringe) - node.setUsageFringeFieldOUT(fringe) - envelope = make_test_envelope() + node.setUsageFringeFieldIN(fringe_in) + node.setUsageFringeFieldOUT(fringe_out) + bunch = Bunch() - bunch.mass(envelope.mass) - bunch.charge(envelope.charge) - bunch.getSyncParticle().kinEnergy(envelope.kin_energy) - expected = fit_transfer_matrix(lattice, bunch) - actual = lattice.trackEnvelope(envelope, fit=False, static=static, return_matrix=True) - np.testing.assert_allclose(actual, expected, atol=1e-10) - with pytest.raises(NotImplementedError, match="edge angles"): - node.getMatrix(envelope.sync_part, part_index=0) - for fringe_node in (node.getNodeFringeFieldIN(), node.getNodeFringeFieldOUT()): - with pytest.raises(NotImplementedError, match="edge fringes"): - fringe_node.getMatrix(envelope.sync_part) - with pytest.raises(NotImplementedError): - lattice.trackEnvelope(envelope.copy(), fit=False, fallback=False) + bunch.mass(mass_proton) + bunch.charge(charge) + bunch.getSyncParticle().kinEnergy(1.3) + bunch.getSyncParticle().time(2.0) + + # Small amplitudes isolate the linear map from nonlinear wedge/fringe terms. + coords = np.random.default_rng(42).normal(size=(2000, 6)) + coords *= [1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-7] + for coord in coords: + bunch.addParticle(*coord) + + envelope = Envelope(bunch=bunch) + + expected = fit_lattice_matrix(lattice, bunch) + actual = lattice.trackEnvelope( + envelope, fit=False, fallback=False, static=static, return_matrix=True, + ) + + # MatrixGenerator differentiates nonlinear maps at finite amplitudes. + np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=2e-8) + lattice.trackBunch(bunch) + scale = np.sqrt(np.diag(calc_bunch_cov(bunch))) + error = (envelope.cov_matrix - calc_bunch_cov(bunch)) / np.outer(scale, scale) + assert np.max(np.abs(error)) < 1e-5 + + analysis = BunchTwissAnalysis() + analysis.analyzeBunch(bunch) + centroid = np.array([analysis.getAverage(i) for i in range(6)]) + np.testing.assert_allclose(envelope.centroid, centroid, rtol=0, atol=1e-11) + assert envelope.time == pytest.approx(bunch.getSyncParticle().time(), abs=1e-14) + assert envelope.kin_energy == pytest.approx(bunch.getSyncParticle().kinEnergy()) + + for fringe_node, angle, enabled in [ + (node.getNodeFringeFieldIN(), ea1, fringe_in), + (node.getNodeFringeFieldOUT(), ea2, fringe_out), + ]: + edge = get_node_matrix(fringe_node, envelope) + expected_edge = np.eye(7) + if kind == "teapot" or enabled: + expected_edge[1, 0] = np.tan(angle) / node.getParam("rho") + if enabled: + expected_edge[3, 2] = -expected_edge[1, 0] + np.testing.assert_allclose(np.eye(7) if edge is None else edge, expected_edge) From 3998ff26b897e491c8ae09d821ffc2b4f3349d5f Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Sun, 15 Nov 2026 12:39:02 -0500 Subject: [PATCH 32/42] Add envelope tracker examples (#176) --- .../Envelope/{test_fodo_2d.py => fodo.py} | 29 ++- examples/Envelope/fodo_match.py | 51 +++++ examples/Envelope/fodo_optimize.py | 94 +++++++++ .../{test_fodo_2d_speed.py => fodo_speed.py} | 76 +------- .../{sns_linac => }/inputs/sns_linac.xml | 0 .../{sns_ring => }/inputs/sns_ring.lat | 0 examples/Envelope/plot.py | 8 +- examples/Envelope/run.sh | 52 ++--- .../test_sns_linac.py => sns_linac.py} | 23 +-- examples/Envelope/sns_linac/style.mplstyle | 8 - ..._sns_linac_speed.py => sns_linac_speed.py} | 104 ++++------ .../test_sns_ring.py => sns_ring.py} | 26 +-- examples/Envelope/sns_ring/style.mplstyle | 8 - .../Envelope/sns_ring_orbit_correction.py | 104 ++++++++++ ...st_sns_ring_speed.py => sns_ring_speed.py} | 63 +----- examples/Envelope/uniform_ellipsoid.py | 98 ++++++++++ ...t_drift_3d.py => uniform_ellipsoid_pic.py} | 35 ++-- examples/Envelope/utils.py | 179 +++++++++++++++++- py/orbit/envelope/analysis.py | 4 +- py/orbit/envelope/envelope.py | 27 ++- py/orbit/envelope/matrix.py | 8 +- py/orbit/envelope/matrix_fitting.py | 1 + py/orbit/envelope/node_matrices.py | 4 +- py/orbit/envelope/tracking.py | 10 +- 24 files changed, 684 insertions(+), 328 deletions(-) rename examples/Envelope/{test_fodo_2d.py => fodo.py} (93%) create mode 100644 examples/Envelope/fodo_match.py create mode 100644 examples/Envelope/fodo_optimize.py rename examples/Envelope/{test_fodo_2d_speed.py => fodo_speed.py} (55%) rename examples/Envelope/{sns_linac => }/inputs/sns_linac.xml (100%) rename examples/Envelope/{sns_ring => }/inputs/sns_ring.lat (100%) rename examples/Envelope/{sns_linac/test_sns_linac.py => sns_linac.py} (93%) delete mode 100644 examples/Envelope/sns_linac/style.mplstyle rename examples/Envelope/{sns_linac/test_sns_linac_speed.py => sns_linac_speed.py} (53%) rename examples/Envelope/{sns_ring/test_sns_ring.py => sns_ring.py} (95%) delete mode 100644 examples/Envelope/sns_ring/style.mplstyle create mode 100644 examples/Envelope/sns_ring_orbit_correction.py rename examples/Envelope/{sns_ring/test_sns_ring_speed.py => sns_ring_speed.py} (65%) create mode 100644 examples/Envelope/uniform_ellipsoid.py rename examples/Envelope/{test_drift_3d.py => uniform_ellipsoid_pic.py} (91%) diff --git a/examples/Envelope/test_fodo_2d.py b/examples/Envelope/fodo.py similarity index 93% rename from examples/Envelope/test_fodo_2d.py rename to examples/Envelope/fodo.py index 41fd0c5f..58d243b7 100644 --- a/examples/Envelope/test_fodo_2d.py +++ b/examples/Envelope/fodo.py @@ -28,7 +28,7 @@ from plot import plot_rms_ellipse from plot import plot_corner -from utils import gen_dist +from utils import sample_distribution from utils import build_rotation_matrix_xy from utils import project_cov_matrix @@ -41,9 +41,7 @@ def parse_args() -> argparse.Namespace: 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("--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) @@ -149,11 +147,14 @@ def main(args: argparse.Namespace) -> None: envelope_sc = "2d" if args.sc else None analysis = EnvelopeAnalysis(envelope) - history = {key: [] for key in ('xrms', 'yrms', 'xavg', 'yavg')} + 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, + envelope, + sc=envelope_sc, + fit=args.fit, + static=True, ) rms = 1000.0 * analysis.rms() @@ -172,15 +173,15 @@ def main(args: argparse.Namespace) -> None: rng = np.random.default_rng() - bunch_coords = np.zeros((args.nparts, 6)) - bunch_coords[:, :4] = gen_dist( + 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 ) - bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) - bunch_coords += centroid_init[None, :6] + particles[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) + particles += centroid_init[None, :6] - for i in range(bunch_coords.shape[0]): - bunch.addParticle(*bunch_coords[i]) + for i in range(particles.shape[0]): + bunch.addParticle(*particles[i]) if args.sc: sc_calc = SpaceChargeCalc2p5D(128, 128, 1) @@ -209,9 +210,7 @@ def main(args: argparse.Namespace) -> None: 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}" - ) + 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) diff --git a/examples/Envelope/fodo_match.py b/examples/Envelope/fodo_match.py new file mode 100644 index 00000000..d4c2a4c9 --- /dev/null +++ b/examples/Envelope/fodo_match.py @@ -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()) diff --git a/examples/Envelope/fodo_optimize.py b/examples/Envelope/fodo_optimize.py new file mode 100644 index 00000000..a282650f --- /dev/null +++ b/examples/Envelope/fodo_optimize.py @@ -0,0 +1,94 @@ +"""Optimize quadrupoles to minimize RMS size fluctuations in FODO lattice.""" + +import argparse +import matplotlib.pyplot as plt +import numpy as np +import scipy.optimize + +from utils import make_fodo +from utils import make_output_dir +from utils import matched_envelope +from utils import track_history +from utils import twiss_parameters + + +def main(args: argparse.Namespace) -> None: + output_dir = make_output_dir(__file__) + plt.style.use("style.mplstyle") + + cell, _ = make_fodo(args.kq, args.nslice) + envelope, _ = matched_envelope(cell, args.intensity) + lattice, quads = make_fodo(args.kq, args.nslice, args.cells) + signs = np.sign([node.getParam("kq") for node in quads]) + initial = args.kq * np.random.default_rng(23).uniform(0.7, 1.3, len(quads)) + size_scale = np.sqrt(envelope.cov_matrix[[0, 2], [0, 2]]) + target = twiss_parameters(envelope) + + def evaluate(strengths: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + for node, strength, sign in zip(quads, strengths, signs): + node.setParam("kq", sign * strength) + envelope_out = envelope.copy() + history, _ = track_history(lattice, envelope_out, sc="2d") + sizes = np.sqrt(history["covariance"][:, [0, 2], [0, 2]]) + return history["s"], sizes, twiss_parameters(envelope_out) + + def residual(strengths: np.ndarray) -> np.ndarray: + _, sizes, endpoint = evaluate(strengths) + fluctuations = (sizes - sizes.mean(axis=0)) / size_scale + return np.r_[ + fluctuations.ravel() / np.sqrt(len(sizes)), + args.match_weight * (endpoint - target), + ] + + def objective(strengths: np.ndarray) -> float: + return 0.5 * np.mean(np.abs(residual(strengths))) + + s, before, endpoint_before = evaluate(initial) + result = scipy.optimize.least_squares( + residual, + initial, + bounds=(0.05 * args.kq, 3 * args.kq), + max_nfev=args.max_nfev, + ftol=1e-12, + gtol=1e-12, + verbose=2, + ) + _, after, endpoint_after = evaluate(result.x) + + print(result.message) + for label, sizes, endpoint in [ + ("Before", before, endpoint_before), + ("After", after, endpoint_after), + ]: + print( + f"{label}: normalized size fluctuation={np.linalg.norm(np.std(sizes / size_scale, axis=0)):.4g}; " + f"endpoint Twiss residual={np.linalg.norm(endpoint - target):.4g}" + ) + print("Signed quadrupole strengths [1/m²]:", signs * result.x) + + fig, ax = plt.subplots() + for i, name in enumerate(("x", "y")): + (line,) = ax.plot(s, 1e3 * after[:, i], label=f"{name}: optimized") + ax.plot( + s, + 1e3 * before[:, i], + "--", + color=line.get_color(), + label=f"{name}: initial", + ) + ax.set(xlabel="s [m]", ylabel="RMS size [mm]") + ax.legend() + fig.savefig(output_dir / "optimization.png") + plt.close(fig) + print(output_dir) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cells", type=int, default=4) + parser.add_argument("--kq", type=float, default=0.25) + parser.add_argument("--intensity", type=float, default=5e9) + parser.add_argument("--nslice", type=int, default=10) + parser.add_argument("--match-weight", type=float, default=1.0) + parser.add_argument("--max-nfev", type=int, default=120) + main(parser.parse_args()) diff --git a/examples/Envelope/test_fodo_2d_speed.py b/examples/Envelope/fodo_speed.py similarity index 55% rename from examples/Envelope/test_fodo_2d_speed.py rename to examples/Envelope/fodo_speed.py index 1bebae8e..0467a03d 100644 --- a/examples/Envelope/test_fodo_2d_speed.py +++ b/examples/Envelope/fodo_speed.py @@ -1,4 +1,4 @@ -"""Test envelope tracker speed in SNS ring.""" +"""Profile envelope tracking in FODO lattice.""" import argparse import time @@ -9,17 +9,13 @@ from tqdm import trange from orbit.core.bunch import Bunch -from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.envelope import Envelope -from orbit.core.spacecharge import SpaceChargeCalc2p5D -from orbit.space_charge.sc2p5d import setSC2p5DAccNodes from orbit.teapot import QuadTEAPOT from orbit.teapot import DriftTEAPOT from orbit.teapot import TEAPOT_Lattice from orbit.teapot import TEAPOT_MATRIX_Lattice from orbit.utils.consts import mass_proton -from utils import gen_dist parser = argparse.ArgumentParser() parser.add_argument("--bunch-length", type=float, default=5.0) @@ -29,11 +25,10 @@ parser.add_argument("--nslice", type=int, default=10) parser.add_argument("--kq", type=float, default=0.25) -parser.add_argument("--nparts", type=int, default=10_000) parser.add_argument("--turns", type=int, default=500) parser.add_argument("--sc", type=int, default=0) -parser.add_argument("--sc-grid", type=int, default=64) parser.add_argument("--fit", type=int, default=1) +parser.add_argument("--static", type=int, default=1) args = parser.parse_args() nodes = [ @@ -76,76 +71,21 @@ cov_matrix[4, 4] = args.bunch_length**2 / 12.0 cov_matrix[5, 5] = 0.0 -cov_matrix_init = np.copy(cov_matrix) - -# Track envelope -print("ENVELOPE") - envelope = Envelope( + cov_matrix=cov_matrix, kin_energy=sync_part.kinEnergy(), mass=bunch.mass(), charge=bunch.charge(), - time=sync_part.time(), - cov_matrix=cov_matrix_init, intensity=args.intensity, ) -envelope_sc = "2d" if args.sc else None - -start_time = time.time() +sc = "2d" if args.sc else None profiler = cProfile.Profile() profiler.enable() - for turn in trange(args.turns): - # No observer: measure tracking without collecting diagnostics. - lattice.trackEnvelope(envelope, sc=envelope_sc, fit=args.fit, static=True) - -time_per_turn = (time.time() - start_time) / args.turns - + lattice.trackEnvelope(envelope, sc=sc, fit=args.fit, static=args.static) profiler.disable() -print("Time per turn:", time_per_turn) - -profiler_stats = pstats.Stats(profiler) -profiler_stats.sort_stats(pstats.SortKey.TIME) -profiler_stats.print_stats(10) - -# Track bunch -print("BUNCH") - -rng = np.random.default_rng() - -bunch_coords = np.zeros((args.nparts, 6)) -bunch_coords[:, :4] = gen_dist( - size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv" -) -bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) - -for i in range(bunch_coords.shape[0]): - bunch.addParticle(*bunch_coords[i]) - -if args.sc: - sc_calc = SpaceChargeCalc2p5D(64, 64, 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) - -start_time = time.time() - -profiler = cProfile.Profile() -profiler.enable() - -for turn in trange(args.turns): - lattice.trackBunch(bunch) - -time_per_turn = (time.time() - start_time) / args.turns - -profiler.disable() - -print("Time per turn:", time_per_turn) - -profiler_stats = pstats.Stats(profiler) -profiler_stats.sort_stats(pstats.SortKey.TIME) -profiler_stats.print_stats(10) +stats = pstats.Stats(profiler) +stats.sort_stats(pstats.SortKey.TIME) +stats.print_stats(10) diff --git a/examples/Envelope/sns_linac/inputs/sns_linac.xml b/examples/Envelope/inputs/sns_linac.xml similarity index 100% rename from examples/Envelope/sns_linac/inputs/sns_linac.xml rename to examples/Envelope/inputs/sns_linac.xml diff --git a/examples/Envelope/sns_ring/inputs/sns_ring.lat b/examples/Envelope/inputs/sns_ring.lat similarity index 100% rename from examples/Envelope/sns_ring/inputs/sns_ring.lat rename to examples/Envelope/inputs/sns_ring.lat diff --git a/examples/Envelope/plot.py b/examples/Envelope/plot.py index 99a77f80..f493b108 100644 --- a/examples/Envelope/plot.py +++ b/examples/Envelope/plot.py @@ -77,9 +77,7 @@ def plot_corner( if labels is None: labels = ndim * [""] - fig, axs = plt.subplots( - ncols=ndim, nrows=ndim, sharex=None, sharey=None, figsize=(8, 8) - ) + fig, axs = plt.subplots(ncols=ndim, nrows=ndim, sharex=None, sharey=None, figsize=(8, 8)) for i in range(ndim): for j in range(ndim): axis = (j, i) @@ -99,9 +97,7 @@ def plot_corner( shading="auto", ) elif i == j: - values, edges = np.histogram( - particles[:, i], bins=bins, range=limits[i] - ) + values, edges = np.histogram(particles[:, i], bins=bins, range=limits[i]) if blur: values = scipy.ndimage.gaussian_filter(values, sigma=blur) ax.stairs(values, edges, lw=1.5, color="black") diff --git a/examples/Envelope/run.sh b/examples/Envelope/run.sh index bde5b25d..1140f126 100755 --- a/examples/Envelope/run.sh +++ b/examples/Envelope/run.sh @@ -1,30 +1,32 @@ #!/bin/bash -set -x +set -e -x -python test_fodo_2d.py --sc 0 -python test_fodo_2d.py --sc 1 -python test_fodo_2d.py --sc 1 --offset-x 0.001 -python test_fodo_2d.py --sc 1 --tilt 45.0 -python test_fodo_2d_speed.py --sc 0 -python test_fodo_2d_speed.py --sc 1 -python test_drift_3d.py --sc 0 -python test_drift_3d.py --sc 1 -python test_drift_3d.py --sc 1 --rms-y 0.002 --rot-z 45.0 -python test_drift_3d.py --sc 1 --rms-z 0.002 --rot-x 45.0 +python fodo.py --sc 0 +python fodo.py --sc 1 +python fodo.py --sc 1 --offset-x 0.001 +python fodo.py --sc 1 --tilt 45.0 +python fodo_match.py +python fodo_optimize.py +python fodo_speed.py --sc 0 +python fodo_speed.py --sc 1 -cd sns_linac -python test_sns_linac.py --sc 0 -python test_sns_linac.py --sc 1 --dist kv -python test_sns_linac.py --sc 1 --dist waterbag -python test_sns_linac.py --sc 1 --dist gauss -cd .. +python uniform_ellipsoid.py +python uniform_ellipsoid_pic.py --sc 0 +python uniform_ellipsoid_pic.py --sc 1 +python uniform_ellipsoid_pic.py --sc 1 --rms-y 0.002 --rot-z 45.0 +python uniform_ellipsoid_pic.py --sc 1 --rms-z 0.002 --rot-x 45.0 -cd sns_ring -python test_sns_ring.py --sc 0 -python test_sns_ring.py --sc 1 -python test_sns_ring.py --sc 1 --tilt 45.0 -python test_sns_ring.py --sc 1 --sol 1 -python test_sns_ring_speed.py --sc 0 -python test_sns_ring_speed.py --sc 1 -cd .. +python sns_linac.py --sc 0 +python sns_linac.py --sc 1 --dist kv +python sns_linac.py --sc 1 --dist waterbag +python sns_linac.py --sc 1 --dist gauss +python sns_linac_speed.py + +python sns_ring.py --sc 0 +python sns_ring.py --sc 1 +python sns_ring.py --sc 1 --tilt 45.0 +python sns_ring.py --sc 1 --sol 1 +python sns_ring_speed.py --sc 0 +python sns_ring_speed.py --sc 1 +python sns_ring_orbit_correction.py diff --git a/examples/Envelope/sns_linac/test_sns_linac.py b/examples/Envelope/sns_linac.py similarity index 93% rename from examples/Envelope/sns_linac/test_sns_linac.py rename to examples/Envelope/sns_linac.py index cd54b006..3de3e97f 100755 --- a/examples/Envelope/sns_linac/test_sns_linac.py +++ b/examples/Envelope/sns_linac.py @@ -1,12 +1,4 @@ -"""SNS linac benchmark. - -Note that there is no analytic benchmark with 3D space charge since there -is no 3D KV equilibrium distribution. For comparison to particle tracking, -we use the `SpaceChargeCalcUnifEllipse` space charge calculator, which -approximates the charge distribution as a uniform-density ellipsoid with -the same x-y-z covariance matrix as the real charge distribution. (It -currently assumes an upright ellipsoid.) -""" +"""SNS linac benchmark.""" import argparse import math @@ -43,7 +35,6 @@ from orbit.utils.consts import mass_electron from orbit.utils.consts import charge_electron -sys.path.append("..") from plot import plot_corner from plot import plot_rms_ellipse from utils import project_cov_matrix @@ -254,9 +245,7 @@ def main(args: argparse.Namespace) -> None: if args.sc_model == "ellipsoid": n_ellipsoids = args.sc_ellipsoid_n sc_calc = SpaceChargeCalcUnifEllipse(n_ellipsoids) - sc_nodes = setUniformEllipsesSCAccNodes( - lattice, args.sc_path_length_min, sc_calc - ) + sc_nodes = setUniformEllipsesSCAccNodes(lattice, args.sc_path_length_min, sc_calc) if args.sc_model == "fft": sc_calc = SpaceChargeCalc3D(64, 64, 64) sc_nodes = setSC3DAccNodes(lattice, args.sc_path_length_min, sc_calc) @@ -281,9 +270,7 @@ def main(args: argparse.Namespace) -> None: plot_kws["bunch"] = dict(color="black", lw=0, marker=".", ms=2) plot_kws["envelope"] = dict(color="red", lw=0, marker=".", ms=1) - fig, axs = plt.subplots( - nrows=3, figsize=(10, 5), sharex=True, constrained_layout=True - ) + fig, axs = plt.subplots(nrows=3, figsize=(10, 5), sharex=True, constrained_layout=True) for mode in ["bunch", "envelope"]: history = histories[mode] for ax, key in zip(axs, ["rms_x", "rms_y", "rms_z"]): @@ -300,9 +287,7 @@ def main(args: argparse.Namespace) -> None: plt.close() # History: rms emittance - fig, axs = plt.subplots( - nrows=3, figsize=(10, 5), sharex=True, constrained_layout=True - ) + fig, axs = plt.subplots(nrows=3, figsize=(10, 5), sharex=True, constrained_layout=True) for mode in ["bunch", "envelope"]: history = histories[mode] for ax, key in zip(axs, ["eps_x_n", "eps_y_n", "eps_z_n"]): diff --git a/examples/Envelope/sns_linac/style.mplstyle b/examples/Envelope/sns_linac/style.mplstyle deleted file mode 100644 index 71f36605..00000000 --- a/examples/Envelope/sns_linac/style.mplstyle +++ /dev/null @@ -1,8 +0,0 @@ -axes.linewidth: 1.25 -axes.titlesize: "medium" -image.cmap: "Greys" -figure.constrained_layout.use: True -savefig.dpi: 300 -savefig.format: "png" -xtick.minor.visible: True -ytick.minor.visible: True diff --git a/examples/Envelope/sns_linac/test_sns_linac_speed.py b/examples/Envelope/sns_linac_speed.py similarity index 53% rename from examples/Envelope/sns_linac/test_sns_linac_speed.py rename to examples/Envelope/sns_linac_speed.py index 3569126c..ba0dc43f 100644 --- a/examples/Envelope/sns_linac/test_sns_linac_speed.py +++ b/examples/Envelope/sns_linac_speed.py @@ -1,10 +1,8 @@ -"""Time envelope and particle tracking through the SNS linac.""" +"""Profile envelope tracking in SNS linac lattice.""" import argparse import cProfile import pstats -import random -import time from orbit.bunch_generators import GaussDist3D from orbit.bunch_generators import KVDist3D @@ -12,13 +10,9 @@ from orbit.bunch_generators import WaterBagDist3D from orbit.core.bunch import Bunch from orbit.core.linac import MatrixRfGap -from orbit.core.spacecharge import SpaceChargeCalc3D -from orbit.core.spacecharge import SpaceChargeCalcUnifEllipse from orbit.envelope import Envelope from orbit.py_linac.lattice import LinacAccLattice from orbit.py_linac.linac_parsers import SNS_LinacLatticeFactory -from orbit.space_charge.sc3d import setSC3DAccNodes -from orbit.space_charge.sc3d import setUniformEllipsesSCAccNodes from orbit.utils.consts import charge_electron from orbit.utils.consts import mass_electron from orbit.utils.consts import mass_proton @@ -45,11 +39,24 @@ def parse_args() -> argparse.Namespace: def make_lattice(args: argparse.Namespace) -> LinacAccLattice: sequences = [ - "MEBT", "DTL1", "DTL2", "DTL3", "DTL4", "DTL5", "DTL6", - "CCL1", "CCL2", "CCL3", "CCL4", "SCLMed", "SCLHigh", "HEBT1", "HEBT2", + "MEBT", + "DTL1", + "DTL2", + "DTL3", + "DTL4", + "DTL5", + "DTL6", + "CCL1", + "CCL2", + "CCL3", + "CCL4", + "SCLMed", + "SCLHigh", + "HEBT1", + "HEBT2", ] if args.seq_stop: - sequences = sequences[:sequences.index(args.seq_stop) + 1] + sequences = sequences[: sequences.index(args.seq_stop) + 1] factory = SNS_LinacLatticeFactory() factory.setMaxDriftLength(args.sc_path_length_min) @@ -70,6 +77,7 @@ def make_bunch(args: argparse.Namespace) -> Bunch: mass = mass_proton + 2 * mass_electron charge = -1.0 intensity = args.current / 402.5e6 / (abs(charge) * charge_electron) + bunch = Bunch() bunch.mass(mass) bunch.charge(charge) @@ -82,73 +90,39 @@ def make_bunch(args: argparse.Namespace) -> Bunch: TwissContainer(+1.768, 0.162, 2.874e-06), TwissContainer(-0.0196, 116.414, 1.651e-08), ] - distribution = { - "kv": KVDist3D, - "waterbag": WaterBagDist3D, - "gauss": GaussDist3D, - }[args.dist](*twiss) + if args.dist == "kv": + distribution = KVDist3D(*twiss) + elif args.dist == "waterbag": + distribution = WaterBagDist3D(*twiss) + elif args.dist == "gauss": + distribution = GaussDist3D(*twiss) + else: + raise ValueError for _ in range(args.nparts): bunch.addParticle(*distribution.getCoordinates()) return bunch -def configure_space_charge(lattice, bunch, args): - if not args.sc: - return - if args.sc_model == "ellipsoid": - calculator = SpaceChargeCalcUnifEllipse(args.sc_ellipsoid_n) - setUniformEllipsesSCAccNodes(lattice, args.sc_path_length_min, calculator) - else: - calculator = SpaceChargeCalc3D(args.sc_grid, args.sc_grid, args.sc_grid) - setSC3DAccNodes(lattice, args.sc_path_length_min, calculator) - - -def time_tracking(track, turns: int) -> float: - track() # warm-up outside the timed interval - start = time.perf_counter() - for _ in range(turns): - track() - return (time.perf_counter() - start) / turns - - def main(args: argparse.Namespace) -> None: - random.seed(23) lattice = make_lattice(args) + bunch = make_bunch(args) + lattice.trackDesignBunch(bunch) + envelope = Envelope(bunch=bunch) - envelope_bunch = make_bunch(args) - lattice.trackDesignBunch(envelope_bunch) - envelope = Envelope(bunch=envelope_bunch) - configure_space_charge(lattice, envelope_bunch, args) - track_envelope = lambda: lattice.trackEnvelope( - envelope, sc=("3d" if args.sc else None), fit=args.fit, static=args.static, fallback=args.fallback - ) - track_envelope() # warm-up outside the timed interval profiler = cProfile.Profile() profiler.enable() - start = time.perf_counter() - for _ in range(args.turns): - track_envelope() - envelope_time = (time.perf_counter() - start) / args.turns + lattice.trackEnvelope( + envelope, + sc=("3d" if args.sc else None), + fit=args.fit, + static=args.static, + fallback=args.fallback, + ) profiler.disable() - particle_lattice = None - bunch_time = None - if args.bunch: - particle_lattice = make_lattice(args) - bunch = make_bunch(args) - particle_lattice.trackDesignBunch(bunch) - configure_space_charge(particle_lattice, bunch, args) - bunch_time = time_tracking(lambda: particle_lattice.trackBunch(bunch), args.turns) - - print(f"lattice nodes: {len(lattice.getNodes())}") - print(f"particles: {args.nparts}") - print(f"turns: {args.turns}") - print(f"fit: {args.fit}; static: {args.static}; space charge: {args.sc_model if args.sc else 'off'}") - print(f"envelope: {envelope_time:.6f} s/turn") - if bunch_time is not None: - print(f"bunch: {bunch_time:.6f} s/turn") - print("\nEnvelope profile (top 10 by cumulative time):") - pstats.Stats(profiler).strip_dirs().sort_stats(pstats.SortKey.CUMULATIVE).print_stats(10) + profiler_stats = pstats.Stats(profiler) + profiler_stats.sort_stats(pstats.SortKey.TIME) + profiler_stats.print_stats(10) if __name__ == "__main__": diff --git a/examples/Envelope/sns_ring/test_sns_ring.py b/examples/Envelope/sns_ring.py similarity index 95% rename from examples/Envelope/sns_ring/test_sns_ring.py rename to examples/Envelope/sns_ring.py index 2708087a..354df960 100644 --- a/examples/Envelope/sns_ring/test_sns_ring.py +++ b/examples/Envelope/sns_ring.py @@ -24,10 +24,9 @@ from orbit.teapot import teapot from orbit.utils.consts import mass_proton -sys.path.append("..") from plot import plot_rms_ellipse from plot import plot_corner -from utils import gen_dist +from utils import sample_distribution from utils import build_rotation_matrix_xy from utils import project_cov_matrix @@ -40,9 +39,7 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--kin-energy", type=float, default=1.300) parser.add_argument("--intensity", type=float, default=2e14) - parser.add_argument( - "--dist", type=str, default="kv", choices=["kv", "waterbag", "gauss"] - ) + parser.add_argument("--dist", type=str, default="kv", choices=["kv", "waterbag", "gauss"]) parser.add_argument("--eps-x", type=float, default=25.0) parser.add_argument("--eps-y", type=float, default=25.0) parser.add_argument("--mismatch-x", type=float, default=0.0) @@ -133,7 +130,7 @@ def main(args: argparse.Namespace) -> None: rng = np.random.default_rng() bunch_coords = np.zeros((args.nparts, 6)) - bunch_coords[:, :4] = gen_dist( + bunch_coords[:, :4] = sample_distribution( size=args.nparts, cov_matrix=cov_matrix[0:4, 0:4], name=args.dist ) bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) @@ -165,20 +162,27 @@ def main(args: argparse.Namespace) -> None: ) analysis = EnvelopeAnalysis(envelope) - history = {key: [] for key in ('rms_x', 'rms_y', 'avg_x', 'avg_y', 'eps_x', 'eps_y')} + history = {key: [] for key in ("rms_x", "rms_y", "avg_x", "avg_y", "eps_x", "eps_y")} for turn in range(args.turns + 1): if turn > 0: lattice.trackEnvelope( - envelope, sc=("2d" if args.sc else None), fit=args.fit, static=args.static, fallback=args.fallback + envelope, + sc=("2d" if args.sc else None), + fit=args.fit, + static=args.static, + fallback=args.fallback, ) rms = 1000.0 * analysis.rms() mean = 1000.0 * analysis.centroid() eps = 1e6 * analysis.emittances() parameters = { - "rms_x": rms[0], "rms_y": rms[1], - "avg_x": mean[0], "avg_y": mean[2], - "eps_x": eps[0], "eps_y": eps[1], + "rms_x": rms[0], + "rms_y": rms[1], + "avg_x": mean[0], + "avg_y": mean[2], + "eps_x": eps[0], + "eps_y": eps[1], } for key, value in parameters.items(): history[key].append(value) diff --git a/examples/Envelope/sns_ring/style.mplstyle b/examples/Envelope/sns_ring/style.mplstyle deleted file mode 100644 index 71f36605..00000000 --- a/examples/Envelope/sns_ring/style.mplstyle +++ /dev/null @@ -1,8 +0,0 @@ -axes.linewidth: 1.25 -axes.titlesize: "medium" -image.cmap: "Greys" -figure.constrained_layout.use: True -savefig.dpi: 300 -savefig.format: "png" -xtick.minor.visible: True -ytick.minor.visible: True diff --git a/examples/Envelope/sns_ring_orbit_correction.py b/examples/Envelope/sns_ring_orbit_correction.py new file mode 100644 index 00000000..4cfe81f8 --- /dev/null +++ b/examples/Envelope/sns_ring_orbit_correction.py @@ -0,0 +1,104 @@ +"""Correct horizontal closed orbit based on centroid tracking.""" + +import argparse +import sys +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +import scipy.optimize + +from orbit.envelope import Envelope +from orbit.lattice import AccNode +from orbit.teapot import KickTEAPOT +from orbit.teapot import TEAPOT_Ring +from orbit.utils.consts import mass_proton + +from utils import make_output_dir +from utils import track_history + + +def main(args: argparse.Namespace) -> None: + output_dir = make_output_dir(__file__) + plt.style.use("style.mplstyle") + + lattice = TEAPOT_Ring() + lattice.readMADX(str(Path(__file__).with_name("inputs") / "sns_ring.lat"), "rnginjsol") + for node in lattice.getNodes(): + if hasattr(node, "setUsageFringeFieldIN"): + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + if node.getLength() > 1.0: + node.setnParts(1 + int(node.getLength())) + + nodes = lattice.getNodes() + if not 1 <= args.correctors <= len(nodes) // 2: + raise ValueError("Corrector count must be between 1 and half the ring node count") + + positions = np.linspace(0, len(nodes), 2 * args.correctors, endpoint=False, dtype=int) + rng = np.random.default_rng(23) + corrector_nodes = [] + for i, index in enumerate(positions): + corrector_node = KickTEAPOT( + name=f"orbit_kick_{i}", kx=(rng.normal(0.0, args.error) if i % 2 else 0.0) + ) + nodes[index].addChildNode(corrector_node, AccNode.ENTRANCE) + if i % 2 == 0: + corrector_nodes.append(corrector_node) + lattice.initialize() + + def closed_orbit() -> tuple[np.ndarray, np.ndarray, float]: + beam = Envelope(kin_energy=1.3, mass=mass_proton) + matrix = lattice.trackEnvelope(beam.copy(), fit=False, return_matrix=True) + beam.centroid[:4] = np.linalg.solve(np.eye(4) - matrix[:4, :4], matrix[:4, 6]) + initial = beam.centroid.copy() + history, _ = track_history(lattice, beam) + s = history["s"] + centroid = history["centroid"] + closure = np.linalg.norm(centroid[-1, :4] - initial[:4]) + return s, centroid[:, 0], closure + + s, before, _ = closed_orbit() + + columns = [] + for corrector_node in corrector_nodes: + corrector_node.setParam("kx", args.delta) + _, displaced, _ = closed_orbit() + columns.append((displaced - before) / args.delta) + corrector_node.setParam("kx", 0.0) + + response = np.column_stack(columns) + result = scipy.optimize.lsq_linear( + response, -before, bounds=(-args.max_kick, args.max_kick), tol=1e-12 + ) + if not result.success: + raise RuntimeError(result.message) + + for corrector_node, strength in zip(corrector_nodes, result.x): + corrector_node.setParam("kx", strength) + + _, after, closure = closed_orbit() + + print(f"Orbit RMS: {1e3 * np.std(before):.4g} -> {1e3 * np.std(after):.4g} mm") + print( + f"Orbit norm/sqrt(BPMs): {1e3 * np.sqrt(np.mean(before**2)):.4g} -> " + f"{1e3 * np.sqrt(np.mean(after**2)):.4g} mm; transverse closure: {closure:.3g}" + ) + print("Corrector kicks [rad]:", result.x) + + fig, ax = plt.subplots(figsize=(6, 3)) + ax.plot(s, 1e3 * before, color="black", ls=":", label="Before") + ax.plot(s, 1e3 * after, color="black", ls="-", label="After") + ax.set(xlabel="s [m]", ylabel="Horizontal closed orbit [mm]") + ax.legend() + fig.savefig(output_dir / "orbit.png") + plt.close(fig) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--correctors", type=int, default=12) + parser.add_argument("--error", type=float, default=1e-4, help="RMS injected dipole error [rad]") + parser.add_argument("--max-kick", type=float, default=1e-3) + parser.add_argument("--delta", type=float, default=1e-6) + main(parser.parse_args()) diff --git a/examples/Envelope/sns_ring/test_sns_ring_speed.py b/examples/Envelope/sns_ring_speed.py similarity index 65% rename from examples/Envelope/sns_ring/test_sns_ring_speed.py rename to examples/Envelope/sns_ring_speed.py index 3260ad9a..42181923 100644 --- a/examples/Envelope/sns_ring/test_sns_ring_speed.py +++ b/examples/Envelope/sns_ring_speed.py @@ -1,4 +1,4 @@ -"""Test envelope tracker speed in SNS ring.""" +"""Profile envelope tracking in SNS ring lattice.""" import argparse import time @@ -10,18 +10,12 @@ from tqdm import trange from orbit.core.bunch import Bunch -from orbit.core.spacecharge import SpaceChargeCalc2p5D from orbit.envelope import Envelope -from orbit.core.spacecharge import SpaceChargeCalc2p5D -from orbit.space_charge.sc2p5d import setSC2p5DAccNodes from orbit.teapot import TEAPOT_Ring from orbit.teapot import TEAPOT_MATRIX_Lattice from orbit.teapot import BendTEAPOT from orbit.utils.consts import mass_proton -sys.path.append("..") -from utils import gen_dist - def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() @@ -37,13 +31,10 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--fit", type=int, default=0) parser.add_argument("--static", type=int, default=1) parser.add_argument("--fallback", type=int, default=0) - - parser.add_argument("--bunch", action="store_true") return parser.parse_args() def main(args: argparse.Namespace) -> None: - lattice = TEAPOT_Ring() lattice.readMADX("inputs/sns_ring.lat", "rnginjsol") lattice.initialize() @@ -86,9 +77,6 @@ def main(args: argparse.Namespace) -> None: cov_matrix_init = np.copy(cov_matrix) - # Track envelope - print("ENVELOPE") - envelope = Envelope( kin_energy=sync_part.kinEnergy(), mass=bunch.mass(), @@ -98,11 +86,8 @@ def main(args: argparse.Namespace) -> None: intensity=args.intensity, ) - start_time = time.time() - profiler = cProfile.Profile() profiler.enable() - for turn in trange(args.turns): lattice.trackEnvelope( envelope, @@ -111,58 +96,12 @@ def main(args: argparse.Namespace) -> None: fallback=args.fallback, sc=("2d" if args.sc else None), ) - - time_per_turn = (time.time() - start_time) / args.turns - profiler.disable() - print("Time per turn:", time_per_turn) - profiler_stats = pstats.Stats(profiler) profiler_stats.sort_stats(pstats.SortKey.TIME) profiler_stats.print_stats(10) - # Track bunch - if args.bunch: - print("BUNCH") - - rng = np.random.default_rng() - - bunch_coords = np.zeros((args.nparts, 6)) - bunch_coords[:, :4] = gen_dist( - size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name="kv" - ) - bunch_coords[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) - - for i in range(bunch_coords.shape[0]): - bunch.addParticle(*bunch_coords[i]) - - if args.sc: - sc_calc = SpaceChargeCalc2p5D(64, 64, 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) - - start_time = time.time() - - profiler = cProfile.Profile() - profiler.enable() - - for turn in trange(args.turns): - lattice.trackBunch(bunch) - - time_per_turn = (time.time() - start_time) / args.turns - - profiler.disable() - - print("Time per turn:", time_per_turn) - - profiler_stats = pstats.Stats(profiler) - profiler_stats.sort_stats(pstats.SortKey.TIME) - profiler_stats.print_stats(10) - if __name__ == "__main__": main(parse_args()) diff --git a/examples/Envelope/uniform_ellipsoid.py b/examples/Envelope/uniform_ellipsoid.py new file mode 100644 index 00000000..38c1fa0d --- /dev/null +++ b/examples/Envelope/uniform_ellipsoid.py @@ -0,0 +1,98 @@ +"""Cold uniform ellipsoid in free space - ODE benchmark.""" + +import argparse +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +import scipy.integrate +import scipy.special + +from orbit.envelope import Envelope +from orbit.teapot import DriftTEAPOT +from orbit.teapot import TEAPOT_Lattice +from orbit.utils.consts import mass_proton + +from utils import make_output_dir +from utils import track_history + + +def main(args: argparse.Namespace) -> None: + output_dir = make_output_dir(__file__) + plt.style.use("style.mplstyle") + + radii = np.array([args.radius, args.radius, args.radius * args.aspect]) + envelope = Envelope( + kin_energy=args.kin_energy, + mass=mass_proton, + intensity=args.intensity, + cov_matrix=np.zeros((6, 6)), + ) + + # For a uniform ellipsoid, each spatial variance is semiaxis**2 / 5. + # Longitudinal covariance is stored in lab coordinates, z_lab = z_rest / gamma. + envelope.cov_matrix[0, 0] = radii[0] ** 2 / 5.0 + envelope.cov_matrix[2, 2] = radii[1] ** 2 / 5.0 + envelope.cov_matrix[4, 4] = (radii[2] / envelope.gamma) ** 2 / 5.0 + coefficient = args.intensity * envelope.classical_radius / (envelope.beta * envelope.gamma) ** 2 + + def derivative(s: float, state: np.ndarray) -> np.ndarray: + a, b, c = state[:3] ** 2 + acceleration = ( + coefficient + * state[:3] + * [ + scipy.special.elliprd(b, c, a), + scipy.special.elliprd(a, c, b), + scipy.special.elliprd(a, b, c), + ] + ) + return np.r_[state[3:], acceleration] + + lattice = TEAPOT_Lattice() + for _ in range(args.nslice): + lattice.addNode(DriftTEAPOT(length=args.length / args.nslice)) + lattice.initialize() + + gamma = envelope.gamma + history, _ = track_history(lattice, envelope, sc="3d") + + tracked = np.zeros((history["covariance"].shape[0], 3)) + tracked[:, 0] = np.sqrt(5.0 * history["covariance"][:, 0, 0]) + tracked[:, 1] = np.sqrt(5.0 * history["covariance"][:, 2, 2]) + tracked[:, 2] = np.sqrt(5.0 * history["covariance"][:, 4, 4]) * gamma + + reference = scipy.integrate.solve_ivp( + derivative, + [0.0, args.length], + np.r_[radii, np.zeros(3)], + dense_output=True, + rtol=1e-10, + atol=1e-12, + ) + if not reference.success: + raise RuntimeError(reference.message) + + exact = reference.sol(history["s"])[:3].T + print(f"Maximum relative radius error: {np.max(abs(tracked / exact - 1)):.3g}") + + fig, axs = plt.subplots(ncols=3, sharex=True, sharey=False, figsize=(10.0, 2.5)) + for i, dim in enumerate(("x", "y", "z")): + axs[i].plot(history["s"], 1e3 * tracked[:, i], color="black", label=f"ENV") + axs[i].plot(history["s"], 1e3 * exact[:, i], ls="--", color="red", label=f"ODE") + axs[i].set_xlabel("s [m]") + axs[i].set_ylabel(f"{dim} [mm]") + axs[i].legend(loc="upper left", fontsize="small") + fig.savefig(output_dir / "expansion") + plt.close(fig) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--radius", type=float, default=0.01) + parser.add_argument("--aspect", type=float, default=2.0) + parser.add_argument("--length", type=float, default=10.0) + parser.add_argument("--kin-energy", type=float, default=0.01) + parser.add_argument("--intensity", type=float, default=1e8) + parser.add_argument("--nslice", type=int, default=400) + main(parser.parse_args()) diff --git a/examples/Envelope/test_drift_3d.py b/examples/Envelope/uniform_ellipsoid_pic.py similarity index 91% rename from examples/Envelope/test_drift_3d.py rename to examples/Envelope/uniform_ellipsoid_pic.py index d739022d..b60de87e 100644 --- a/examples/Envelope/test_drift_3d.py +++ b/examples/Envelope/uniform_ellipsoid_pic.py @@ -1,7 +1,8 @@ -"""Test 3D envelope tracker in drift +"""Cold uniform ellipsoid in free space - PIC benchmark. -The initial beam is a uniform-density ellipsoid in the x-y-z plane, with zero initial velocity. -The ellipsoid can have arbitrary size and orientation. +The initial beam is a uniform-density ellipsoid in the x-y-z plane, +with zero initial velocity. The ellipsoid can have arbitrary aspect +ratio and orientation. """ import argparse @@ -28,7 +29,7 @@ from plot import plot_rms_ellipse from plot import plot_corner -from utils import gen_dist +from utils import sample_distribution from utils import project_cov_matrix plt.style.use("style.mplstyle") @@ -64,9 +65,7 @@ def rotation_matrix_3d(angle_x: float, angle_y: float, angle_z: float) -> np.nda ).as_matrix() -def build_cov_matrix_xyz( - rms_sizes: np.ndarray, rotation_matrix: np.ndarray = None -) -> np.ndarray: +def build_cov_matrix_xyz(rms_sizes: np.ndarray, rotation_matrix: np.ndarray = None) -> np.ndarray: cov_matrix = np.diag(np.square(rms_sizes)) if rotation_matrix is None: return cov_matrix @@ -134,17 +133,21 @@ def main(args: argparse.Namespace) -> None: envelope_sc = "3d" if args.sc else None analysis = EnvelopeAnalysis(envelope) - history = {key: [] for key in ('s', 'xrms', 'yrms', 'zrms')} + history = {key: [] for key in ("s", "xrms", "yrms", "zrms")} for turn in range(args.turns): if turn > 0: lattice.trackEnvelope( - envelope, sc=envelope_sc, fit=args.fit, + envelope, + sc=envelope_sc, + fit=args.fit, ) rms = 1000.0 * analysis.rms() parameters = { "s": turn * lattice.getLength(), - "xrms": rms[0], "yrms": rms[1], "zrms": rms[2] * envelope.gamma, + "xrms": rms[0], + "yrms": rms[1], + "zrms": rms[2] * envelope.gamma, } for key, value in parameters.items(): history[key].append(value) @@ -162,7 +165,7 @@ def main(args: argparse.Namespace) -> None: bunch.getSyncParticle().kinEnergy(args.kin_energy) bunch_coords = np.zeros((args.nparts, 6)) - bunch_coords[:, (0, 2, 4)] = gen_dist( + bunch_coords[:, (0, 2, 4)] = sample_distribution( size=args.nparts, cov_matrix=cov_matrix_xyz, name="waterbag" ) @@ -224,8 +227,14 @@ def main(args: argparse.Namespace) -> None: for i, model in enumerate(["envelope", "bunch"]): color = ["black", "red"][i] lw = [None, 0][i] - ax.plot(histories[model]["s"], histories[model][key], - marker=".", lw=lw, color=color, label=model) + ax.plot( + histories[model]["s"], + histories[model][key], + marker=".", + lw=lw, + color=color, + label=model, + ) ax.set_ylim(0.0, ax.get_ylim()[1] * 1.2) ax.set_xlabel("s [m]") ax.set_ylabel("rms size [mm]") diff --git a/examples/Envelope/utils.py b/examples/Envelope/utils.py index daf2a6c7..b950c195 100644 --- a/examples/Envelope/utils.py +++ b/examples/Envelope/utils.py @@ -1,7 +1,22 @@ +import time +from typing import Any +from pathlib import Path + +import matplotlib.pyplot as plt import numpy as np +import scipy.optimize + +from orbit.envelope import Envelope +from orbit.lattice import AccActionsContainer +from orbit.lattice import AccLattice +from orbit.lattice import AccNode +from orbit.teapot import DriftTEAPOT +from orbit.teapot import QuadTEAPOT +from orbit.teapot import TEAPOT_Lattice +from orbit.utils.consts import mass_proton -def gen_dist_gauss(size: int, dim: np.ndarray) -> np.ndarray: +def sample_distribution_gauss(size: int, dim: np.ndarray) -> np.ndarray: return np.random.multivariate_normal( mean=np.zeros(dim), cov=np.eye(dim), @@ -9,15 +24,15 @@ def gen_dist_gauss(size: int, dim: np.ndarray) -> np.ndarray: ) -def gen_dist_kv(size: int, dim: int) -> np.ndarray: +def sample_distribution_kv(size: int, dim: int) -> np.ndarray: X = np.random.normal(size=(size, dim)) X /= np.linalg.norm(X, axis=1)[:, None] X /= np.std(X, axis=0) return X -def gen_dist_waterbag(size: int, dim: int) -> np.ndarray: - X = gen_dist_kv(size, dim) +def sample_distribution_waterbag(size: int, dim: int) -> np.ndarray: + X = sample_distribution_kv(size, dim) dim = X.shape[1] r = np.random.uniform(size=size) ** (1.0 / dim) X *= r[:, None] @@ -25,14 +40,14 @@ def gen_dist_waterbag(size: int, dim: int) -> np.ndarray: return X -def gen_dist(size: int, cov_matrix: np.ndarray, name: str) -> np.ndarray: +def sample_distribution(size: int, cov_matrix: np.ndarray, name: str) -> np.ndarray: dim = cov_matrix.shape[0] if name == "kv": - X = gen_dist_kv(size, dim) + X = sample_distribution_kv(size, dim) elif name == "waterbag": - X = gen_dist_waterbag(size, dim) + X = sample_distribution_waterbag(size, dim) elif name == "gauss": - X = gen_dist_gauss(size, dim) + X = sample_distribution_gauss(size, dim) else: raise ValueError(f"Invalid distribution name: {name}") @@ -58,3 +73,151 @@ def project_cov_matrix(cov_matrix: np.ndarray, axis: tuple[int, ...]) -> np.ndar for j in range(len(axis)): cov_matrix_proj[i, j] = cov_matrix[axis[i], axis[j]] return cov_matrix_proj + + +def make_output_dir(script: str | Path, timestamp: bool = False) -> Path: + output_dir = Path("outputs") / Path(script).stem + if timestamp: + output_dir = output_dir / time.strftime("%Y%m%d_%H%M%S") + output_dir.mkdir(parents=True, exist_ok=True) + return output_dir + + +def make_fodo( + kq: float = 0.25, nslice: int = 20, cells: int = 1 +) -> tuple[TEAPOT_Lattice, list[QuadTEAPOT]]: + lattice = TEAPOT_Lattice() + quad_nodes = [] + for _ in range(cells): + for length, strength in [ + (0.5, kq), + (1.0, None), + (1.0, -kq), + (1.0, None), + (0.5, kq), + ]: + node = ( + DriftTEAPOT(length=length) + if strength is None + else QuadTEAPOT(length=length, kq=strength) + ) + node.setnParts(nslice) + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + lattice.addNode(node) + if strength is not None: + quad_nodes.append(node) + lattice.initialize() + return lattice, quad_nodes + + +def make_envelope( + parameters: np.ndarray | list[float], + intensity: float = 5e9, + emittance: float = 0.25e-6, + kin_energy: float = 0.0025, +) -> Envelope: + log_beta_x, alpha_x, log_beta_y, alpha_y = parameters + beta_x = np.exp(log_beta_x) + beta_y = np.exp(log_beta_y) + + cov_matrix = np.zeros((6, 6)) + cov_matrix[0, 0] = emittance * beta_x + cov_matrix[2, 2] = emittance * beta_y + cov_matrix[0, 1] = cov_matrix[1, 0] = -emittance * alpha_x + cov_matrix[2, 3] = cov_matrix[3, 2] = -emittance * alpha_y + cov_matrix[1, 1] = emittance * (1.0 + alpha_x**2) / beta_x + cov_matrix[3, 3] = emittance * (1.0 + alpha_y**2) / beta_y + cov_matrix[4, 4] = (5.0) ** 2 / 12.0 + return Envelope( + cov_matrix=cov_matrix, + kin_energy=kin_energy, + mass=mass_proton, + intensity=intensity, + ) + + +def twiss_parameters(envelope: Envelope) -> np.ndarray: + result = [] + for i in (0, 2): + c = envelope.cov_matrix[i : i + 2, i : i + 2] + emittance = np.sqrt(np.linalg.det(c)) + beta = c[0, 0] / emittance + alpha = -c[0, 1] / emittance + result.extend([np.log(beta), alpha]) + return np.array(result) + + +def matched_envelope( + lattice: AccLattice, + intensity: float = 5e9, + initial: np.ndarray | list[float] | None = None, + optimizer_kwargs: dict = None, +) -> tuple[Envelope, float]: + + if initial is None: + envelope = make_envelope([0, 0, 0, 0]) + matrix = lattice.trackEnvelope(envelope, fit=False, return_matrix=True) + initial = [] + for i in (0, 2): + m = matrix[i : i + 2, i : i + 2] + cosine = np.trace(m) / 2 + if abs(cosine) >= 1: + raise ValueError("Bare lattice is unstable") + sine = np.copysign(np.sqrt(1 - cosine**2), m[0, 1]) + initial.extend([np.log(m[0, 1] / sine), (m[0, 0] - m[1, 1]) / (2 * sine)]) + + def residual(parameters: np.ndarray) -> np.ndarray: + envelope = make_envelope(parameters, intensity) + lattice.trackEnvelope(envelope, fit=False, static=True, sc="2d") + return twiss_parameters(envelope) - parameters + + optimizer_kwargs = optimizer_kwargs or {} + optimizer_kwargs.setdefault("xtol", 1e-10) + optimizer_kwargs.setdefault("ftol", 1e-10) + optimizer_kwargs.setdefault("gtol", 1e-10) + optimizer_kwargs.setdefault("verbose", 2) + + result = scipy.optimize.least_squares(residual, initial, **optimizer_kwargs) + error = np.linalg.norm(result.fun) + if not result.success or error > 1e-7: + raise RuntimeError(f"Matching failed: residual={error:.3g}") + return make_envelope(result.x, intensity), error + + +def track_history( + lattice: AccLattice, + envelope: Envelope, + sc: str | None = None, + static: bool = False, +) -> tuple[dict[str, np.ndarray], np.ndarray]: + + history = {} + for key in ["s", "centroid", "covariance"]: + history[key] = [] + + def monitor(params_dict: dict) -> None: + envelope = params_dict["envelope"] + position = params_dict["path_length"] + if history["s"] and history["s"][-1] == position: + return + history["s"].append(position) + history["centroid"].append(envelope.centroid.copy()) + history["covariance"].append(envelope.cov_matrix.copy()) + + action_container = AccActionsContainer() + action_container.addAction(monitor, AccActionsContainer.ENTRANCE) + action_container.addAction(monitor, AccActionsContainer.BODY) + action_container.addAction(monitor, AccActionsContainer.EXIT) + + matrix = lattice.trackEnvelope( + envelope, + sc=sc, + fit=False, + static=static, + action_container=action_container, + return_matrix=True, + ) + for key in history: + history[key] = np.array(history[key]) + return history, matrix diff --git a/py/orbit/envelope/analysis.py b/py/orbit/envelope/analysis.py index 7bd06898..5c3f0431 100644 --- a/py/orbit/envelope/analysis.py +++ b/py/orbit/envelope/analysis.py @@ -21,9 +21,7 @@ def rms(self, axis: int | None = None) -> np.ndarray | float: def emittances(self, normalized: bool = False) -> np.ndarray: cov = self.envelope.cov_matrix - values = np.array( - [np.sqrt(np.linalg.det(cov[i : i + 2, i : i + 2])) for i in (0, 2, 4)] - ) + values = np.array([np.sqrt(np.linalg.det(cov[i : i + 2, i : i + 2])) for i in (0, 2, 4)]) if normalized: beta = self.envelope.beta values *= np.array([beta * self.envelope.gamma] * 2 + [1.0 / beta]) diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index e0b2a14c..d02c5b4e 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -39,7 +39,8 @@ def get_bunch_centroid(bunch: Bunch) -> np.ndarray: class Envelope: - """Represents the first and second moments of a phase-space distribution..""" + """Represents the first and second moments of the beam distribution.""" + def __init__( self, cov_matrix: np.ndarray | None = None, @@ -53,7 +54,7 @@ def __init__( ) -> None: """Constructor. - Args: + Args: cov_matrix: 6 x 6 covariance matrix. centroid: 6 x 1 centroid vector. kin_energy: Synchronous particle kinetic energy [GeV]. @@ -105,7 +106,7 @@ def rigidity(self) -> float: @property def sc_factor(self) -> float: - return 2.0 * self.intensity * self.classical_radius / (self.beta ** 2 * self.gamma ** 3) + return 2.0 * self.intensity * self.classical_radius / (self.beta**2 * self.gamma**3) def rms(self, axis: int | None = None) -> float | np.ndarray: return np.sqrt(np.diag(self.cov_matrix))[axis] @@ -144,8 +145,12 @@ def sc_matrix_2d(self, length: float) -> np.ndarray: phi = -0.5 * math.atan2(2.0 * cov_xy, cov_xx - cov_yy) sin_phi = math.sin(phi) cos_phi = math.cos(phi) - rx = 2.0 * math.sqrt(abs(cov_xx * cos_phi**2 + cov_yy * sin_phi**2 - 2.0 * cov_xy * sin_phi * cos_phi)) - ry = 2.0 * math.sqrt(abs(cov_xx * sin_phi**2 + cov_yy * cos_phi**2 + 2.0 * cov_xy * sin_phi * cos_phi)) + rx = 2.0 * math.sqrt( + abs(cov_xx * cos_phi**2 + cov_yy * sin_phi**2 - 2.0 * cov_xy * sin_phi * cos_phi) + ) + ry = 2.0 * math.sqrt( + abs(cov_xx * sin_phi**2 + cov_yy * cos_phi**2 + 2.0 * cov_xy * sin_phi * cos_phi) + ) bunch_length = self.rms_bunch_length_factor * math.sqrt(cov_matrix[4, 4]) factor = 2.0 * self.sc_factor * length / (bunch_length * (rx + ry)) @@ -178,11 +183,13 @@ def sc_matrix_3d(self, length: float) -> np.ndarray: eigenvalues, eigenvectors = np.linalg.eigh(cov_position) cov_xx, cov_yy, cov_zz = eigenvalues - strengths = np.array([ - scipy.special.elliprd(cov_yy, cov_zz, cov_xx), - scipy.special.elliprd(cov_xx, cov_zz, cov_yy), - scipy.special.elliprd(cov_xx, cov_yy, cov_zz), - ]) + strengths = np.array( + [ + scipy.special.elliprd(cov_yy, cov_zz, cov_xx), + scipy.special.elliprd(cov_xx, cov_zz, cov_yy), + scipy.special.elliprd(cov_xx, cov_yy, cov_zz), + ] + ) strengths *= 0.5 * self.sc_factor * (0.2**1.5) * length # Rotate out of upright frame. diff --git a/py/orbit/envelope/matrix.py b/py/orbit/envelope/matrix.py index 40b7d19b..adf8ad9f 100644 --- a/py/orbit/envelope/matrix.py +++ b/py/orbit/envelope/matrix.py @@ -70,7 +70,7 @@ def get_matrix_drift(envelope: Envelope, length: float) -> np.ndarray: M = np.identity(7) M[0, 1] = length M[2, 3] = length - M[4, 5] = length / (envelope.gamma ** 2) + M[4, 5] = length / (envelope.gamma**2) M[4, 5] *= get_dp_p_coeff(envelope) # convert_matrix_dp_p_to_dE(M, envelope) envelope.time += length / (envelope.beta * speed_of_light) return M @@ -140,7 +140,7 @@ def get_matrix_bend(envelope: Envelope, length: float, theta: float) -> np.ndarr M[2, 3] = length M[4, 0] = -sx M[4, 1] = -rho * (1.0 - cx) - M[4, 5] = -(envelope.beta ** 2) * length + rho * sx + M[4, 5] = -(envelope.beta**2) * length + rho * sx M[:5, 5] *= get_dp_p_coeff(envelope) # convert_matrix_dp_p_to_dE(M, envelope) envelope.time += length / (envelope.beta * speed_of_light) @@ -201,7 +201,9 @@ def get_matrix_cf(envelope: Envelope, length: float, kq: float) -> np.ndarray: return M -def get_matrix_rf_gap(envelope: Envelope, frequency: float, E0TL: float, phase: float) -> np.ndarray: +def get_matrix_rf_gap( + envelope: Envelope, frequency: float, E0TL: float, phase: float +) -> np.ndarray: gamma = envelope.gamma beta = envelope.beta mass = envelope.mass diff --git a/py/orbit/envelope/matrix_fitting.py b/py/orbit/envelope/matrix_fitting.py index b0f811f0..765b2267 100644 --- a/py/orbit/envelope/matrix_fitting.py +++ b/py/orbit/envelope/matrix_fitting.py @@ -7,6 +7,7 @@ from orbit.core.bunch import Bunch from orbit.core.orbit_utils import Matrix from orbit.core.teapot_base import MatrixGenerator + if TYPE_CHECKING: from orbit.lattice import AccLattice from orbit.lattice import AccNode diff --git a/py/orbit/envelope/node_matrices.py b/py/orbit/envelope/node_matrices.py index 27600388..13506c4b 100644 --- a/py/orbit/envelope/node_matrices.py +++ b/py/orbit/envelope/node_matrices.py @@ -177,7 +177,9 @@ def _matrix_fringe_field(node, envelope: Envelope, part_index: int = -1) -> np.n @get_node_matrix.register(ContinuousLinearFocusingTEAPOT) -def _matrix_continuous_focusing_teapot(node, envelope: Envelope, part_index: int = -1) -> np.ndarray | None: +def _matrix_continuous_focusing_teapot( + node, envelope: Envelope, part_index: int = -1 +) -> np.ndarray | None: length = node.getLength(part_index) if length <= 0: return None diff --git a/py/orbit/envelope/tracking.py b/py/orbit/envelope/tracking.py index 9ca12545..3afa6462 100644 --- a/py/orbit/envelope/tracking.py +++ b/py/orbit/envelope/tracking.py @@ -52,7 +52,7 @@ def __init__( self.fit = fit self.fallback = fallback - + self._bunch = None self._matrix_generator = None self._node_maps = None @@ -113,7 +113,9 @@ def push_envelope(params_dict: ParamsDict) -> None: if store: if matrix is not None and np.array_equal(matrix, identity_matrix): matrix = None - node_maps[node, part_index] = NodeMap(matrix, envelope.kin_energy, envelope.time) + node_maps[node, part_index] = NodeMap( + matrix, envelope.kin_energy, envelope.time + ) apply_matrix(matrix) action_container.addAction(push_envelope, AccNode.BODY) @@ -138,7 +140,9 @@ def precompute(self, envelope: Envelope, params_dict: ParamsDict | None = None) store=True, ) - def _get_node_matrix(self, params_dict: ParamsDict, part_index: int, handlers: dict) -> np.ndarray | None: + def _get_node_matrix( + self, params_dict: ParamsDict, part_index: int, handlers: dict + ) -> np.ndarray | None: node = params_dict["node"] envelope = params_dict["envelope"] initial_kinetic_energy = envelope.kin_energy From 7adec3d28d4069eaa0fe8f2cf3aef8331c3e0b93 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Sun, 15 Nov 2026 12:47:16 -0500 Subject: [PATCH 33/42] Raise error if SC_Base_AccNode is encountered in envelope tracking --- py/orbit/envelope/tracking.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/py/orbit/envelope/tracking.py b/py/orbit/envelope/tracking.py index 3afa6462..227b352e 100644 --- a/py/orbit/envelope/tracking.py +++ b/py/orbit/envelope/tracking.py @@ -8,6 +8,7 @@ from orbit.core.bunch import Bunch from orbit.core.teapot_base import MatrixGenerator +from orbit.space_charge import SC_Base_AccNode from .envelope import Envelope from .matrix_fitting import fit_node_matrix @@ -148,6 +149,9 @@ def _get_node_matrix( initial_kinetic_energy = envelope.kin_energy initial_time = envelope.time + if isinstance(node, SC_Base_AccNode): + raise NotImplementedError + use_fit = self.fit if not use_fit: @@ -171,8 +175,10 @@ def _get_node_matrix( sync_particle = self._bunch.getSyncParticle() sync_particle.kinEnergy(envelope.kin_energy) sync_particle.time(envelope.time) + if self._matrix_generator is None: self._matrix_generator = MatrixGenerator() + matrix = fit_node_matrix( node=node, bunch=self._bunch, @@ -180,6 +186,7 @@ def _get_node_matrix( matrix_generator=self._matrix_generator, params_dict=params_dict, ) + envelope.kin_energy = sync_particle.kinEnergy() envelope.time = sync_particle.time() From 4474003294a89a20f7fa8b5d5de32d59ef0a8d3e Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Sun, 15 Nov 2026 13:22:58 -0500 Subject: [PATCH 34/42] Remove test_sync_part.py --- tests/py/orbit/test_sync_part.py | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 tests/py/orbit/test_sync_part.py diff --git a/tests/py/orbit/test_sync_part.py b/tests/py/orbit/test_sync_part.py deleted file mode 100644 index f0b0ee7b..00000000 --- a/tests/py/orbit/test_sync_part.py +++ /dev/null @@ -1,18 +0,0 @@ -from orbit.core.bunch import Bunch -from orbit.core.bunch import SyncParticle - - -def make_bunch(): - bunch = Bunch() - bunch.mass(0.938272) - bunch.charge(1.0) - bunch.getSyncParticle().kinEnergy(1.0) - return bunch - - -def test_get_mass_charge(): - bunch = make_bunch() - sync_part = bunch.getSyncParticle() - - assert sync_part.mass() == bunch.mass() - assert sync_part.charge() == bunch.charge() From 54d574f35dbfc090ae2b67c23bd6cbab0c122265 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Sun, 15 Nov 2026 13:25:47 -0500 Subject: [PATCH 35/42] Undo changes to syncpart.cc --- src/orbit/SyncPart.cc | 4 --- src/orbit/wrap_syncpart.cc | 61 ++++++++++++++------------------------ 2 files changed, 23 insertions(+), 42 deletions(-) diff --git a/src/orbit/SyncPart.cc b/src/orbit/SyncPart.cc index 320f9850..6494ecbf 100644 --- a/src/orbit/SyncPart.cc +++ b/src/orbit/SyncPart.cc @@ -320,10 +320,6 @@ double SyncPart::getMass(){ return bunch->getMass(); } -double SyncPart::getCharge(){ - return bunch->getCharge(); -} - void SyncPart::readSyncPart(const char* fileName){ //for MPI diff --git a/src/orbit/wrap_syncpart.cc b/src/orbit/wrap_syncpart.cc index 419ae556..787c00a7 100644 --- a/src/orbit/wrap_syncpart.cc +++ b/src/orbit/wrap_syncpart.cc @@ -129,20 +129,6 @@ extern "C" { return Py_BuildValue("d",val); } - // charge() - returns charge in elementary charge units - static PyObject* SyncPart_charge(PyObject *self, PyObject *args){ - pyORBIT_Object* pySyncPart = (pyORBIT_Object*) self; - int nVars = PyTuple_Size(args); - if(nVars > 0){ - error("PySyncPart - charge() - you should use bunch.charge(charge_value) instead!"); - } - double val = 0.; - SyncPart* cpp_SyncPart = (SyncPart*) pySyncPart->cpp_obj; - val = cpp_SyncPart->getCharge(); - return Py_BuildValue("d",val); - } - - //Sets or returns the momentum for the SyncPart object // the action is depended on the number of arguments // momentum() - returns momentum @@ -557,38 +543,37 @@ extern "C" { return Py_BuildValue("d",val); } - // Definition of the methods of the python SyncPart wrapper class. - // They will be available from the Python level. + // defenition of the methods of the python SyncPart wrapper class + // they will be vailable from python level static PyMethodDef SyncPartClassMethods[] = { - { "mass", SyncPart_mass, METH_VARARGS,"Returns mass in GeV"}, - { "charge", SyncPart_charge, METH_VARARGS,"Returns charge in elementary charge units"}, - { "momentum", SyncPart_momentum, METH_VARARGS,"Returns or sets momentum in GeV/c."}, - { "beta", SyncPart_beta, METH_VARARGS,"Returns beta=v/c"}, - { "gamma", SyncPart_gamma, METH_VARARGS,"Returns gamma=1/sqrt(1-(v/c)**2)"}, - { "kinEnergy", SyncPart_kinEnergy, METH_VARARGS,"Returns or sets kinetic energy of the synchronous particle in MeV"}, - { "time", SyncPart_time, METH_VARARGS,"Sets or returns time in sec"}, - { "x", SyncPart_x, METH_VARARGS,"Sets or returns the x-coordinate"}, - { "y", SyncPart_y, METH_VARARGS,"Sets or returns the y-coordinate"}, - { "z", SyncPart_z, METH_VARARGS,"Sets or returns the z-coordinate"}, - { "px", SyncPart_px, METH_VARARGS,"Sets or returns the x-momentum"}, - { "py", SyncPart_py, METH_VARARGS,"Sets or returns the y-momentum"}, - { "pz", SyncPart_pz, METH_VARARGS,"Sets or returns the z-momentum"}, - { "pVector", SyncPart_pVector, METH_VARARGS,"Sets or returns the momentum vector as a tuple"}, - { "rVector", SyncPart_rVector, METH_VARARGS,"Sets or returns the position vector as a tuple"}, - { "nxVector", SyncPart_nxVector, METH_VARARGS,"Sets or returns the x-axis vector as a tuple"}, - { "nyVector", SyncPart_nyVector, METH_VARARGS,"Returns the y-axis vector as a tuple"}, - { "energyToMomentum", SyncPart_eToP, METH_VARARGS,"Transforms the kinetic energy to momentum"}, - { "momentumToEnergy", SyncPart_pToE, METH_VARARGS,"Transforms the momentum to kinetic energy"}, + { "mass", SyncPart_mass ,METH_VARARGS,"Returns mass in GeV"}, + { "momentum", SyncPart_momentum ,METH_VARARGS,"Returns or sets momentum in GeV/c."}, + { "beta", SyncPart_beta ,METH_VARARGS,"Returns beta=v/c"}, + { "gamma", SyncPart_gamma ,METH_VARARGS,"Returns gamma=1/sqrt(1-(v/c)**2)"}, + { "kinEnergy", SyncPart_kinEnergy ,METH_VARARGS,"Returns or sets kinetic energy of the synchronous particle in MeV"}, + { "time", SyncPart_time ,METH_VARARGS,"Sets or returns time in sec"}, + { "x", SyncPart_x ,METH_VARARGS,"Sets or returns the x-coordinate"}, + { "y", SyncPart_y ,METH_VARARGS,"Sets or returns the y-coordinate"}, + { "z", SyncPart_z ,METH_VARARGS,"Sets or returns the z-coordinate"}, + { "px", SyncPart_px ,METH_VARARGS,"Sets or returns the x-momentum"}, + { "py", SyncPart_py ,METH_VARARGS,"Sets or returns the y-momentum"}, + { "pz", SyncPart_pz ,METH_VARARGS,"Sets or returns the z-momentum"}, + { "pVector", SyncPart_pVector ,METH_VARARGS,"Sets or returns the momentum vector as a tuple"}, + { "rVector", SyncPart_rVector ,METH_VARARGS,"Sets or returns the position vector as a tuple"}, + { "nxVector", SyncPart_nxVector ,METH_VARARGS,"Sets or returns the x-axis vector as a tuple"}, + { "nyVector", SyncPart_nyVector ,METH_VARARGS,"Returns the y-axis vector as a tuple"}, + { "energyToMomentum", SyncPart_eToP ,METH_VARARGS,"Transforms the kinetic energy to momentum"}, + { "momentumToEnergy", SyncPart_pToE ,METH_VARARGS,"Transforms the momentum to kinetic energy"}, {NULL} }; - // Definition of the members of the python SyncPart wrapper class. - // They will be available from python level. + // defenition of the memebers of the python SyncPart wrapper class + // they will be vailable from python level static PyMemberDef SyncPartClassMembers [] = { {NULL} }; - // New Python SyncPart wrapper type definition. + //new python SyncPart wrapper type definition static PyTypeObject pyORBIT_SyncPart_Type = { PyVarObject_HEAD_INIT(NULL, 0) "SyncParticle", /*tp_name*/ From b532f4ab1778c6ad101335b272615d3ed72b12da Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Sun, 15 Nov 2026 13:27:15 -0500 Subject: [PATCH 36/42] Undo changes to syncpart.hh --- src/orbit/SyncPart.hh | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/orbit/SyncPart.hh b/src/orbit/SyncPart.hh index 2081e4bf..d14aa9ba 100644 --- a/src/orbit/SyncPart.hh +++ b/src/orbit/SyncPart.hh @@ -68,11 +68,6 @@ class SyncPart */ double getMass(); - /** - Charge in elementary charge units - */ - double getCharge(); - /** time in seconds */ From 60c54953394b0759bf97bbb65bd38bddecf63ff2 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Sun, 15 Nov 2026 13:37:53 -0500 Subject: [PATCH 37/42] Pass already created lostbunch and matrix to fitting function --- py/orbit/envelope/matrix_fitting.py | 7 ++++--- py/orbit/envelope/tracking.py | 10 ++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/py/orbit/envelope/matrix_fitting.py b/py/orbit/envelope/matrix_fitting.py index 765b2267..db4882f9 100644 --- a/py/orbit/envelope/matrix_fitting.py +++ b/py/orbit/envelope/matrix_fitting.py @@ -26,6 +26,7 @@ def fit_node_matrix( matrix_generator: MatrixGenerator | None = None, lost_bunch: Bunch | None = None, params_dict: dict | None = None, + matrix: Matrix | None = None, ) -> np.ndarray: if matrix_generator is None: @@ -35,8 +36,9 @@ def fit_node_matrix( lost_bunch = Bunch() bunch.copyEmptyBunchTo(lost_bunch) - matrix = Matrix(7, 7) - matrix.unit() + if matrix is None: + matrix = Matrix(7, 7) + matrix_generator.initBunch(bunch) params_dict = {} if params_dict is None else params_dict.copy() @@ -67,7 +69,6 @@ def fit_lattice_matrix( index_stop = -1 matrix = Matrix(7, 7) - matrix.unit() bunch_out = Bunch() lost_bunch = Bunch() diff --git a/py/orbit/envelope/tracking.py b/py/orbit/envelope/tracking.py index 227b352e..9d3adb91 100644 --- a/py/orbit/envelope/tracking.py +++ b/py/orbit/envelope/tracking.py @@ -7,6 +7,7 @@ import numpy as np from orbit.core.bunch import Bunch +from orbit.core.orbit_utils import Matrix from orbit.core.teapot_base import MatrixGenerator from orbit.space_charge import SC_Base_AccNode @@ -56,6 +57,8 @@ def __init__( self._bunch = None self._matrix_generator = None + self._lost_bunch = None + self._fit_matrix = None self._node_maps = None def track( @@ -178,13 +181,20 @@ def _get_node_matrix( if self._matrix_generator is None: self._matrix_generator = MatrixGenerator() + if self._lost_bunch is None: + self._lost_bunch = Bunch() + self._bunch.copyEmptyBunchTo(self._lost_bunch) + if self._fit_matrix is None: + self._fit_matrix = Matrix(7, 7) matrix = fit_node_matrix( node=node, bunch=self._bunch, part_index=part_index, matrix_generator=self._matrix_generator, + lost_bunch=self._lost_bunch, params_dict=params_dict, + matrix=self._fit_matrix, ) envelope.kin_energy = sync_particle.kinEnergy() From 08a1592fa41ecc2e1cf8f9bf092aa744e5f321a6 Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Sun, 15 Nov 2026 13:49:19 -0500 Subject: [PATCH 38/42] Stored maps should increment envelope time/energy --- py/orbit/envelope/tracking.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/py/orbit/envelope/tracking.py b/py/orbit/envelope/tracking.py index 9d3adb91..f51df4a3 100644 --- a/py/orbit/envelope/tracking.py +++ b/py/orbit/envelope/tracking.py @@ -27,12 +27,12 @@ @dataclass class NodeMap: matrix: np.ndarray | None - kin_energy: float - time: float + delta_kin_energy: float + delta_time: float def update_envelope(self, envelope: Envelope) -> None: - envelope.kin_energy = self.kin_energy - envelope.time = self.time + envelope.kin_energy += self.delta_kin_energy + envelope.time += self.delta_time class EnvelopeTracker: @@ -113,12 +113,16 @@ def push_envelope(params_dict: ParamsDict) -> None: node_map.update_envelope(envelope) matrix = node_map.matrix else: + initial_kin_energy = envelope.kin_energy + initial_time = envelope.time matrix = self._get_node_matrix(params_dict, part_index, handlers) if store: if matrix is not None and np.array_equal(matrix, identity_matrix): matrix = None node_maps[node, part_index] = NodeMap( - matrix, envelope.kin_energy, envelope.time + matrix, + envelope.kin_energy - initial_kin_energy, + envelope.time - initial_time, ) apply_matrix(matrix) From 8156f1d7ba48be72f1a0af1e3413a9e0e160747c Mon Sep 17 00:00:00 2001 From: austin-hoover Date: Sun, 15 Nov 2026 14:06:27 -0500 Subject: [PATCH 39/42] fit and fallback should be false by default --- py/orbit/lattice/AccLattice.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index 400dc6f1..58f27fcc 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -279,8 +279,8 @@ def trackEnvelope( sc: str | None = None, params_dict: dict | None = None, action_container: AccActionsContainer | None = None, - fit: bool = True, - fallback: bool = True, + fit: bool = False, + fallback: bool = False, static: bool = False, return_matrix: bool = False, ) -> np.ndarray | None: From ccb4aeca40c36bc23bd8c2cdd090cbf0e19235b6 Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Tue, 17 Nov 2026 15:51:41 -0500 Subject: [PATCH 40/42] Add from_bunch function to Envelope --- py/orbit/envelope/envelope.py | 37 ++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/py/orbit/envelope/envelope.py b/py/orbit/envelope/envelope.py index d02c5b4e..59ee1a0a 100644 --- a/py/orbit/envelope/envelope.py +++ b/py/orbit/envelope/envelope.py @@ -43,38 +43,25 @@ class Envelope: def __init__( self, - cov_matrix: np.ndarray | None = None, - centroid: np.ndarray | None = None, - kin_energy: float | None = None, - mass: float | None = None, + cov_matrix: np.ndarray, + kin_energy: float, + mass: float, charge: float = 1.0, time: float = 0.0, intensity: float = 0.0, - bunch: Bunch | None = None, + centroid: np.ndarray | None = None, ) -> None: """Constructor. Args: cov_matrix: 6 x 6 covariance matrix. - centroid: 6 x 1 centroid vector. + centroid: 6 x 1 centroid vector. Defaults to zero. kin_energy: Synchronous particle kinetic energy [GeV]. mass: Particle mass [GeV / c^2]. charge: Particle charge [e]. time: Synchronous particle time [s]. intensity: Total number of particles in bunch. - bunch: If provided, the parameters above are calculated - from the bunch parameters and macroparticle coordiantes. """ - if bunch is not None: - cov_matrix = get_bunch_covariance(bunch) - centroid = get_bunch_centroid(bunch) - mass = bunch.mass() - charge = bunch.charge() - sync_part = bunch.getSyncParticle() - kin_energy = sync_part.kinEnergy() - time = sync_part.time() - intensity = bunch.macroSize() * bunch.getSizeGlobal() - self.centroid = np.zeros(6) if centroid is None else centroid self.cov_matrix = np.eye(6) if cov_matrix is None else cov_matrix self.kin_energy = kin_energy @@ -85,6 +72,20 @@ def __init__( self.classical_radius = get_classical_radius(self.charge, self.mass) self.rms_bunch_length_factor = RMS_BUNCH_LENGTH_FACTOR + @classmethod + def from_bunch(cls, bunch: Bunch) -> "Envelope": + """Snapshot the bunch moments and reference state without retaining it.""" + sync_part = bunch.getSyncParticle() + return cls( + cov_matrix=get_bunch_covariance(bunch), + centroid=get_bunch_centroid(bunch), + kin_energy=sync_part.kinEnergy(), + mass=bunch.mass(), + charge=bunch.charge(), + time=sync_part.time(), + intensity=bunch.macroSize() * bunch.getSizeGlobal(), + ) + def copy(self) -> "Envelope": return copy.deepcopy(self) From adab3ce33ae8f06181eb78ce4151640827307236 Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Tue, 17 Nov 2026 15:52:27 -0500 Subject: [PATCH 41/42] Update tests --- tests/py/orbit/test_envelope.py | 43 +++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/tests/py/orbit/test_envelope.py b/tests/py/orbit/test_envelope.py index ad237147..2c72fdd5 100644 --- a/tests/py/orbit/test_envelope.py +++ b/tests/py/orbit/test_envelope.py @@ -31,6 +31,39 @@ from orbit.utils.consts import mass_proton +def test_envelope_from_bunch(): + bunch = Bunch() + bunch.mass(2 * mass_proton) + bunch.charge(-1) + bunch.getSyncParticle().kinEnergy(.1) + bunch.getSyncParticle().time(1.25) + bunch.macroSize(100) + coords = np.random.default_rng(42).normal(size=(20, 6)) * 1e-3 + coords += np.arange(6) * 1e-3 + for row in coords: + bunch.addParticle(*row) + + envelope = Envelope.from_bunch(bunch) + np.testing.assert_allclose(envelope.centroid, coords.mean(axis=0), atol=1e-15) + np.testing.assert_allclose(envelope.cov_matrix, calc_bunch_cov(bunch), atol=1e-15) + assert envelope.mass == bunch.mass() + assert envelope.charge == -1 + assert envelope.kin_energy == pytest.approx(.1) + assert envelope.time == 1.25 + assert envelope.intensity == 100 * bunch.getSizeGlobal() + + bunch.getSyncParticle().kinEnergy(.2) + bunch.getSyncParticle().time(2.5) + bunch.mass(mass_proton) + bunch.charge(1) + bunch.x(0, 10) + assert envelope.kin_energy == pytest.approx(.1) + assert envelope.time == 1.25 + assert envelope.mass == 2 * mass_proton + assert envelope.charge == -1 + np.testing.assert_allclose(envelope.centroid, coords.mean(axis=0), atol=1e-15) + + def get_lorentz_factors(kin_energy: float, mass: float) -> tuple[float, float]: gamma = 1.0 + kin_energy / mass beta = np.sqrt(1.0 - (1.0 / gamma) ** 2) @@ -109,7 +142,7 @@ def track_and_compare_rms( # Covariance matrix calculated from particles will be slightly different. cov_matrix = calc_bunch_cov(bunch) - envelope = Envelope(bunch=bunch).copy() + envelope = Envelope.from_bunch(bunch).copy() data["bunch"]["cov"]["in"] = cov_scale * calc_bunch_cov(bunch) lattice.trackBunch(bunch) data["bunch"]["cov"]["out"] = cov_scale * calc_bunch_cov(bunch) @@ -238,7 +271,7 @@ def test_bend_teapot_edge_matrix(charge: float): bunch.getSyncParticle().kinEnergy(1.3) matrix_fit = fit_lattice_matrix(lattice, bunch) - envelope = Envelope(bunch=bunch) + envelope = Envelope.from_bunch(bunch) matrix_analytic = lattice.trackEnvelope(envelope.copy(), fit=False, return_matrix=True) assert np.allclose(matrix_analytic, matrix_fit, atol=1.0e-10) @@ -258,7 +291,7 @@ def test_fitted_envelope_matrices(): bunch.getSyncParticle().kinEnergy(1.3) matrix_expected = fit_lattice_matrix(lattice, bunch) - envelope = Envelope(bunch=bunch) + envelope = Envelope.from_bunch(bunch) matrix_actual = lattice.trackEnvelope(envelope.copy(), return_matrix=True, fit=True) assert np.allclose(matrix_actual, matrix_expected, atol=1.0e-12) @@ -348,7 +381,7 @@ def test_rf_gap_matrix(charge: float): coords_out_1 = collect_bunch(bunch_out_1)["coords"] - reference = Envelope(bunch=bunch_in) + reference = Envelope.from_bunch(bunch_in) matrix = get_matrix_rf_gap( reference, frequency=frequency, @@ -469,7 +502,7 @@ def test_edge_bends_with_fringe(kind, fringe_in, fringe_out, static, theta, char for coord in coords: bunch.addParticle(*coord) - envelope = Envelope(bunch=bunch) + envelope = Envelope.from_bunch(bunch) expected = fit_lattice_matrix(lattice, bunch) actual = lattice.trackEnvelope( From 3a7ce9278d649d25c894135f1511ba53ef3789b0 Mon Sep 17 00:00:00 2001 From: Austin Hoover Date: Tue, 17 Nov 2026 15:54:53 -0500 Subject: [PATCH 42/42] Update examples that construct envelope from bunch --- examples/Envelope/sns_linac.py | 4 ++-- examples/Envelope/sns_linac_speed.py | 2 +- examples/Envelope/sns_ring_orbit_correction.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/Envelope/sns_linac.py b/examples/Envelope/sns_linac.py index 3de3e97f..7fa88711 100755 --- a/examples/Envelope/sns_linac.py +++ b/examples/Envelope/sns_linac.py @@ -193,7 +193,7 @@ def __call__(self, params_dict: dict) -> None: params_dict["old_pos"] = position params_dict["count"] += 1 - analysis = EnvelopeAnalysis(Envelope(bunch=bunch)) + analysis = EnvelopeAnalysis(Envelope.from_bunch(bunch)) results = {"s": position, **analysis.to_dict()} for key in self.history: self.history[key].append(results[key]) @@ -220,7 +220,7 @@ def main(args: argparse.Namespace) -> None: # Track envelope bunch = make_bunch(args) - envelope = Envelope(bunch=bunch) + envelope = Envelope.from_bunch(bunch) lattice = make_lattice(args) lattice.trackDesignBunch(bunch) diff --git a/examples/Envelope/sns_linac_speed.py b/examples/Envelope/sns_linac_speed.py index ba0dc43f..3eba3d57 100644 --- a/examples/Envelope/sns_linac_speed.py +++ b/examples/Envelope/sns_linac_speed.py @@ -107,7 +107,7 @@ def main(args: argparse.Namespace) -> None: lattice = make_lattice(args) bunch = make_bunch(args) lattice.trackDesignBunch(bunch) - envelope = Envelope(bunch=bunch) + envelope = Envelope.from_bunch(bunch) profiler = cProfile.Profile() profiler.enable() diff --git a/examples/Envelope/sns_ring_orbit_correction.py b/examples/Envelope/sns_ring_orbit_correction.py index 4cfe81f8..8fb67fed 100644 --- a/examples/Envelope/sns_ring_orbit_correction.py +++ b/examples/Envelope/sns_ring_orbit_correction.py @@ -48,7 +48,7 @@ def main(args: argparse.Namespace) -> None: lattice.initialize() def closed_orbit() -> tuple[np.ndarray, np.ndarray, float]: - beam = Envelope(kin_energy=1.3, mass=mass_proton) + beam = Envelope(cov_matrix=np.eye(6), kin_energy=1.3, mass=mass_proton) matrix = lattice.trackEnvelope(beam.copy(), fit=False, return_matrix=True) beam.centroid[:4] = np.linalg.solve(np.eye(4) - matrix[:4, :4], matrix[:4, 6]) initial = beam.centroid.copy()