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/fodo.py b/examples/Envelope/fodo.py new file mode 100644 index 00000000..58d243b7 --- /dev/null +++ b/examples/Envelope/fodo.py @@ -0,0 +1,315 @@ +"""Test 2D envelope tracker in FODO lattice.""" + +import argparse +import copy +import math +import os +import time +from pathlib import Path + +import numpy as np +import matplotlib.pyplot as plt + +from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis +from orbit.core.spacecharge import SpaceChargeCalc2p5D +from orbit.bunch_utils import collect_bunch +from orbit.envelope import Envelope +from orbit.envelope import EnvelopeAnalysis +from orbit.lattice import AccLattice +from orbit.lattice import AccNode +from orbit.core.spacecharge import SpaceChargeCalc2p5D +from orbit.space_charge.sc2p5d import setSC2p5DAccNodes +from orbit.teapot import DriftTEAPOT +from orbit.teapot import QuadTEAPOT +from orbit.teapot import TEAPOT_Lattice +from orbit.teapot import TEAPOT_MATRIX_Lattice +from orbit.utils.consts import mass_proton + +from plot import plot_rms_ellipse +from plot import plot_corner +from utils import sample_distribution +from utils import build_rotation_matrix_xy +from utils import project_cov_matrix + +plt.style.use("style.mplstyle") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--bunch-length", type=float, default=5.0) + parser.add_argument("--kin-energy", type=float, default=0.0025) + parser.add_argument("--intensity", type=float, default=5e9) + + parser.add_argument("--dist", type=str, default="kv", choices=["kv", "waterbag", "gauss"]) + parser.add_argument("--mismatch-x", type=float, default=0.0) + parser.add_argument("--mismatch-y", type=float, default=0.0) + parser.add_argument("--offset-x", type=float, default=0.0) + parser.add_argument("--offset-y", type=float, default=0.0) + parser.add_argument("--tilt", type=float, default=0) + + parser.add_argument("--nslice", type=int, default=10) + parser.add_argument("--kq", type=float, default=0.25) + + parser.add_argument("--nparts", type=int, default=100_000) + parser.add_argument("--turns", type=int, default=25) + parser.add_argument("--sc", type=int, default=0) + parser.add_argument("--fit", type=int, default=1) + return parser.parse_args() + + +def main(args: argparse.Namespace) -> None: + output_dir = os.path.join("outputs", Path(__file__).stem, time.strftime("%Y%m%d_%H%M%S")) + os.makedirs(output_dir, exist_ok=True) + + # Create lattice + # ------------------------------------------------------------------------------ + + nodes = [ + QuadTEAPOT(length=0.5, kq=+args.kq), + DriftTEAPOT(length=1.0), + QuadTEAPOT(length=1.0, kq=-args.kq), + DriftTEAPOT(length=1.0), + QuadTEAPOT(length=0.5, kq=+args.kq), + ] + + lattice = TEAPOT_Lattice() + for node in nodes: + node.setnParts(args.nslice) + node.setUsageFringeFieldIN(False) + node.setUsageFringeFieldOUT(False) + lattice.addNode(node) + + lattice.initialize() + + # Create envelope + # ------------------------------------------------------------------------------ + + # Create bunch + bunch = Bunch() + bunch.mass(mass_proton) + sync_part = bunch.getSyncParticle() + sync_part.kinEnergy(args.kin_energy) + + # Find periodic lattice parameters + matrix_lattice = TEAPOT_MATRIX_Lattice(lattice, bunch) + matrix_lattice_params = matrix_lattice.getRingParametersDict() + alpha_x = matrix_lattice_params["alpha x"] + alpha_y = matrix_lattice_params["alpha y"] + beta_x = matrix_lattice_params["beta x [m]"] + beta_y = matrix_lattice_params["beta y [m]"] + eps_x = 0.25e-06 + eps_y = eps_x + + # Generate covariance matrix + cov_matrix = np.zeros((6, 6)) + cov_matrix[0, 0] = eps_x * beta_x + cov_matrix[2, 2] = eps_y * beta_y + cov_matrix[0, 1] = cov_matrix[1, 0] = -eps_x * alpha_x + cov_matrix[2, 3] = cov_matrix[3, 2] = -eps_y * alpha_y + cov_matrix[1, 1] = eps_x * (1.0 + alpha_x**2) / beta_x + cov_matrix[3, 3] = eps_y * (1.0 + alpha_y**2) / beta_y + cov_matrix[4, 4] = args.bunch_length**2 / 12.0 + cov_matrix[5, 5] = 0.0 + + # Tilt + if args.tilt: + rot_matrix = np.identity(6) + rot_matrix[:4, :4] = build_rotation_matrix_xy(angle=np.radians(args.tilt)) + cov_matrix = np.linalg.multi_dot([rot_matrix, cov_matrix, rot_matrix.T]) + + # Mismatch + cov_matrix[0, 0] *= (1.0 + args.mismatch_x) ** 2 + cov_matrix[2, 2] *= (1.0 + args.mismatch_y) ** 2 + cov_matrix_init = np.copy(cov_matrix) + + # Offset + centroid_init = np.zeros(6) + centroid_init[0] += args.offset_x + centroid_init[2] += args.offset_y + + # Create envelope + envelope = Envelope( + kin_energy=sync_part.kinEnergy(), + mass=bunch.mass(), + charge=bunch.charge(), + time=sync_part.time(), + cov_matrix=cov_matrix_init, + centroid=centroid_init, + intensity=args.intensity, + ) + + # Track envelope + # ------------------------------------------------------------------------------ + + print("TRACK ENVELOPE") + + envelope_sc = "2d" if args.sc else None + + analysis = EnvelopeAnalysis(envelope) + history = {key: [] for key in ("xrms", "yrms", "xavg", "yavg")} + for turn in range(args.turns): + if turn > 0: + lattice.trackEnvelope( + envelope, + sc=envelope_sc, + fit=args.fit, + static=True, + ) + + rms = 1000.0 * analysis.rms() + mean = 1000.0 * analysis.centroid() + parameters = {"xrms": rms[0], "yrms": rms[1], "xavg": mean[0], "yavg": mean[2]} + for key, value in parameters.items(): + history[key].append(value) + print(f"turn={turn}", parameters) + + histories = {"envelope": history} + + # Track bunch + # ------------------------------------------------------------------------------ + + print("TRACK BUNCH") + + rng = np.random.default_rng() + + particles = np.zeros((args.nparts, 6)) + particles[:, :4] = sample_distribution( + size=args.nparts, cov_matrix=cov_matrix_init[0:4, 0:4], name=args.dist + ) + particles[:, 4] = args.bunch_length * rng.uniform(-0.5, 0.5, size=args.nparts) + particles += centroid_init[None, :6] + + for i in range(particles.shape[0]): + bunch.addParticle(*particles[i]) + + if args.sc: + sc_calc = SpaceChargeCalc2p5D(128, 128, 1) + sc_path_length_min = 1.00e-06 + sc_nodes = setSC2p5DAccNodes(lattice, sc_path_length_min, sc_calc) + + bunch_size = bunch.getSizeGlobal() + bunch.macroSize(args.intensity / bunch_size) + + history = {"xrms": [], "yrms": [], "xavg": [], "yavg": []} + for turn in range(args.turns): + if turn > 0: + lattice.trackBunch(bunch) + + twiss_calc = BunchTwissAnalysis() + twiss_calc.computeBunchMoments(bunch, 2, 0, 0) + + cov_matrix = np.zeros((6, 6)) + for i in range(6): + for j in range(i + 1): + cov_matrix[i, j] = twiss_calc.getCorrelation(j, i) + cov_matrix[j, i] = cov_matrix[i, j] + + xrms = 1000.0 * math.sqrt(cov_matrix[0, 0]) + yrms = 1000.0 * math.sqrt(cov_matrix[2, 2]) + xavg = 1000.0 * twiss_calc.getAverage(0) + yavg = 1000.0 * twiss_calc.getAverage(2) + + print(f"turn={turn} xrms={xrms:0.3f} yrms={yrms:0.3f} xavg={xavg:0.3f} yavg={yavg:0.3f}") + + history["xrms"].append(xrms) + history["yrms"].append(yrms) + history["xavg"].append(xavg) + history["yavg"].append(yavg) + + histories["bunch"] = copy.deepcopy(history) + + # Analysis + # ------------------------------------------------------------------------------ + + for history in histories.values(): + for key in history: + history[key] = np.array(history[key]) + + # Print errors + for key in histories["envelope"]: + deltas = histories["bunch"][key] - histories["envelope"][key] + print("key:", key) + print("max_abs_delta:", np.max(np.abs(deltas))) + print("avg_abs_delta:", np.mean(np.abs(deltas))) + + # Plot rms bunch sizes + for key in ["xrms", "yrms"]: + fig, ax = plt.subplots(figsize=(5, 3)) + for i, model in enumerate(["envelope", "bunch"]): + color = ["black", "red"][i] + lw = [None, 0][i] + ax.plot(histories[model][key], marker=".", lw=lw, color=color, label=model) + ax.set_ylim(0.0, ax.get_ylim()[1] * 2.0) + ax.set_xlabel("Turn") + ax.set_ylabel("RMS [mm]") + ax.legend(loc="upper right") + plt.savefig(os.path.join(output_dir, f"fig_{key}")) + plt.close() + + # Plot centroids + for key in ["xavg", "yavg"]: + fig, ax = plt.subplots(figsize=(5, 3)) + for i, model in enumerate(["envelope", "bunch"]): + color = ["black", "red"][i] + lw = [None, 0][i] + ax.plot(histories[model][key], marker=".", lw=lw, color=color, label=model) + ax.set_ylim(-5.0, 5.0) + ax.set_xlabel("Turn") + ax.set_ylabel("AVG [mm]") + ax.legend(loc="upper right") + plt.savefig(os.path.join(output_dir, f"fig_{key}")) + plt.close() + + # Collect bunch/envelope data on final turn. + particles = collect_bunch(bunch)["coords"] + particles[:, :4] *= 1000.0 + + env_cov_matrix = EnvelopeAnalysis(envelope).covariance() + env_cov_matrix[:4, :4] *= 1000.0**2 + + env_centroid = envelope.centroid + env_centroid[:4] *= 1000.0 + + xmax = 4.0 * np.std(particles, axis=0) + limits = list(zip(-xmax, xmax)) + labels = ["x [mm]", "xp [mrad]", "y [mm]", "yp [mrad]", "z [m]", "dE [GeV]"] + + # Plot x-x' + fig, ax = plt.subplots(figsize=(4, 4)) + ax.hist2d(particles[:, 0], particles[:, 1], bins=100, range=[limits[0], limits[1]]) + plot_rms_ellipse( + env_cov_matrix[0:2, 0:2], + center=(env_centroid[0], env_centroid[1]), + level=2.0, + color="red", + ax=ax, + ) + ax.set_xlabel(labels[0]) + ax.set_ylabel(labels[1]) + plt.savefig(os.path.join(output_dir, "fig_dist_x_xp")) + plt.close() + + # Plot corner + fig, axs = plot_corner( + particles, + limits=limits, + bins=100, + labels=labels, + ) + for i in range(6): + for j in range(i): + env_cov_matrix_proj = project_cov_matrix(env_cov_matrix, axis=(j, i)) + plot_rms_ellipse( + env_cov_matrix_proj, + center=(env_centroid[j], env_centroid[i]), + level=2.0, + color="red", + ax=axs[i, j], + ) + plt.savefig(os.path.join(output_dir, "fig_dist_corner")) + plt.close() + + +if __name__ == "__main__": + main(parse_args()) 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/fodo_speed.py b/examples/Envelope/fodo_speed.py new file mode 100644 index 00000000..0467a03d --- /dev/null +++ b/examples/Envelope/fodo_speed.py @@ -0,0 +1,91 @@ +"""Profile envelope tracking in FODO lattice.""" + +import argparse +import time +import cProfile +import pstats + +import numpy as np +from tqdm import trange + +from orbit.core.bunch import Bunch +from orbit.envelope import Envelope +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 + + +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("--turns", type=int, default=500) +parser.add_argument("--sc", type=int, default=0) +parser.add_argument("--fit", type=int, default=1) +parser.add_argument("--static", type=int, default=1) +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 + +envelope = Envelope( + cov_matrix=cov_matrix, + kin_energy=sync_part.kinEnergy(), + mass=bunch.mass(), + charge=bunch.charge(), + intensity=args.intensity, +) +sc = "2d" if args.sc else None + +profiler = cProfile.Profile() +profiler.enable() +for turn in trange(args.turns): + lattice.trackEnvelope(envelope, sc=sc, fit=args.fit, static=args.static) +profiler.disable() + +stats = pstats.Stats(profiler) +stats.sort_stats(pstats.SortKey.TIME) +stats.print_stats(10) diff --git a/examples/Envelope/inputs/sns_linac.xml b/examples/Envelope/inputs/sns_linac.xml new file mode 100644 index 00000000..62cdbf41 --- /dev/null +++ b/examples/Envelope/inputs/sns_linac.xml @@ -0,0 +1,13475 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Envelope/inputs/sns_ring.lat b/examples/Envelope/inputs/sns_ring.lat new file mode 100644 index 00000000..cbfb8df1 --- /dev/null +++ b/examples/Envelope/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/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/run.sh b/examples/Envelope/run.sh new file mode 100755 index 00000000..1140f126 --- /dev/null +++ b/examples/Envelope/run.sh @@ -0,0 +1,32 @@ +#!/bin/bash + +set -e -x + +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 + +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 + +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.py b/examples/Envelope/sns_linac.py new file mode 100755 index 00000000..7fa88711 --- /dev/null +++ b/examples/Envelope/sns_linac.py @@ -0,0 +1,369 @@ +"""SNS linac benchmark.""" + +import argparse +import math +import os +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.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 EnvelopeAnalysis +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 + +from plot import plot_corner +from plot import plot_rms_ellipse +from utils import project_cov_matrix + +plt.style.use("style.mplstyle") + + +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", 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, help="Use best-fit transfer matrices") + return parser.parse_args() + + +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] + + 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()) + + return lattice + + +def make_bunch(args: argparse.Namespace) -> 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()) + return bunch + + +class EnvelopeMonitor: + 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) + + 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) + + +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.from_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 + bunch = make_bunch(args) + envelope = Envelope.from_bunch(bunch) + + lattice = make_lattice(args) + lattice.trackDesignBunch(bunch) + + monitor = EnvelopeMonitor() + action_container = AccActionsContainer() + action_container.addAction(monitor, AccActionsContainer.ENTRANCE) + action_container.addAction(monitor, AccActionsContainer.EXIT) + lattice.trackEnvelope( + envelope, + action_container=action_container, + sc=("3d" if args.sc else None), + fit=args.fit, + ) + 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 = args.sc_ellipsoid_n + sc_calc = SpaceChargeCalcUnifEllipse(n_ellipsoids) + 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) + + 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 + # -------------------------------------------------------------------------------- + + 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) + + 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_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() + + # 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 = EnvelopeAnalysis(envelope).covariance() + 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_linac_speed.py b/examples/Envelope/sns_linac_speed.py new file mode 100644 index 00000000..3eba3d57 --- /dev/null +++ b/examples/Envelope/sns_linac_speed.py @@ -0,0 +1,129 @@ +"""Profile envelope tracking in SNS linac lattice.""" + +import argparse +import cProfile +import pstats + +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.envelope import Envelope +from orbit.py_linac.lattice import LinacAccLattice +from orbit.py_linac.linac_parsers import SNS_LinacLatticeFactory +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), + ] + 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 main(args: argparse.Namespace) -> None: + lattice = make_lattice(args) + bunch = make_bunch(args) + lattice.trackDesignBunch(bunch) + envelope = Envelope.from_bunch(bunch) + + profiler = cProfile.Profile() + profiler.enable() + lattice.trackEnvelope( + envelope, + sc=("3d" if args.sc else None), + fit=args.fit, + static=args.static, + fallback=args.fallback, + ) + profiler.disable() + + 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/sns_ring.py b/examples/Envelope/sns_ring.py new file mode 100644 index 00000000..354df960 --- /dev/null +++ b/examples/Envelope/sns_ring.py @@ -0,0 +1,369 @@ +"""Test envelope tracker in SNS ring.""" + +import argparse +import copy +import math +import os +import pathlib +import sys +import time + +import numpy as np +import matplotlib.pyplot as plt + +from orbit.core.bunch import Bunch +from orbit.core.bunch import BunchTwissAnalysis +from orbit.core.spacecharge import SpaceChargeCalc2p5D +from orbit.bunch_utils import collect_bunch +from orbit.envelope import Envelope +from orbit.envelope import EnvelopeAnalysis +from orbit.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 + +from plot import plot_rms_ellipse +from plot import plot_corner +from utils import sample_distribution +from utils import build_rotation_matrix_xy +from utils import project_cov_matrix + +plt.style.use("style.mplstyle") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--bunch-length", type=float, default=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("--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() + + +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) + + # 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(args.fringe) + node.setUsageFringeFieldOUT(args.fringe) + + 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=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: + 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] = 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) + 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( + 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, + ) + + 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=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], + } + for key, value in parameters.items(): + history[key].append(value) + print(f"turn={turn}", parameters) + + histories = {"envelope": 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 + for key in ["eps_x", "eps_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 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"]: + 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 = EnvelopeAnalysis(envelope).covariance() + env_cov_matrix[:4, :4] *= 1000.0**2 + + env_centroid = envelope.centroid + env_centroid[:4] *= 1000.0 + + xmax = 4.0 * np.std(particles, axis=0) + limits = list(zip(-xmax, xmax)) + labels = ["x [mm]", "xp [mrad]", "y [mm]", "yp [mrad]", "z [m]", "dE [GeV]"] + + # Plot x-x' + fig, ax = plt.subplots(figsize=(4, 4)) + ax.hist2d(particles[:, 0], particles[:, 1], bins=100, range=[limits[0], limits[1]]) + plot_rms_ellipse( + env_cov_matrix[0:2, 0:2], + center=(env_centroid[0], env_centroid[1]), + level=2.0, + color="red", + ax=ax, + ) + ax.set_xlabel(labels[0]) + ax.set_ylabel(labels[1]) + plt.savefig(os.path.join(output_dir, "fig_dist_x_xp")) + plt.close() + + # Plot corner + fig, axs = plot_corner( + particles, + limits=limits, + bins=100, + labels=labels, + ) + for i in range(6): + for j in range(i): + env_cov_matrix_proj = project_cov_matrix(env_cov_matrix, axis=(j, i)) + plot_rms_ellipse( + env_cov_matrix_proj, + center=(env_centroid[j], env_centroid[i]), + level=2.0, + color="red", + ax=axs[i, j], + ) + plt.savefig(os.path.join(output_dir, "fig_dist_corner")) + plt.close() + + +if __name__ == "__main__": + main(parse_args()) diff --git a/examples/Envelope/sns_ring_orbit_correction.py b/examples/Envelope/sns_ring_orbit_correction.py new file mode 100644 index 00000000..8fb67fed --- /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(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() + 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_speed.py b/examples/Envelope/sns_ring_speed.py new file mode 100644 index 00000000..42181923 --- /dev/null +++ b/examples/Envelope/sns_ring_speed.py @@ -0,0 +1,107 @@ +"""Profile envelope tracking in SNS ring lattice.""" + +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.envelope import Envelope +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 + + +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=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=0) + parser.add_argument("--static", type=int, default=1) + parser.add_argument("--fallback", type=int, default=0) + 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(): + 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) + + envelope = Envelope( + kin_energy=sync_part.kinEnergy(), + mass=bunch.mass(), + charge=bunch.charge(), + time=sync_part.time(), + cov_matrix=cov_matrix_init, + intensity=args.intensity, + ) + + profiler = cProfile.Profile() + profiler.enable() + for turn in trange(args.turns): + lattice.trackEnvelope( + envelope, + static=args.static, + fit=args.fit, + fallback=args.fallback, + sc=("2d" if args.sc else None), + ) + profiler.disable() + + 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/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/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/uniform_ellipsoid_pic.py b/examples/Envelope/uniform_ellipsoid_pic.py new file mode 100644 index 00000000..b60de87e --- /dev/null +++ b/examples/Envelope/uniform_ellipsoid_pic.py @@ -0,0 +1,296 @@ +"""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 aspect +ratio and orientation. +""" + +import argparse +import copy +import math +import os +import pathlib +import time + +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 EnvelopeAnalysis +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 sample_distribution +from utils import project_cov_matrix + +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) + parser.add_argument("--fit", 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: + 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: + + 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) + + # 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 + # ------------------------------------------------------------------------------ + + gamma = 1.0 + args.kin_energy / mass_proton + + 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 / 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( + kin_energy=args.kin_energy, + mass=mass_proton, + cov_matrix=cov_matrix_init, + centroid=centroid_init, + intensity=args.intensity, + ) + + # Track envelope + # ------------------------------------------------------------------------------ + + print("TRACK ENVELOPE") + + envelope_sc = "3d" if args.sc else None + + 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, + ) + + 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 = {"envelope": history} + + # Track bunch + # ------------------------------------------------------------------------------ + + 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)] = sample_distribution( + 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 = {"s": [], "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["s"].append(turn * lattice.getLength()) + 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]["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]") + 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 = EnvelopeAnalysis(envelope).covariance() + 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/utils.py b/examples/Envelope/utils.py new file mode 100644 index 00000000..b950c195 --- /dev/null +++ b/examples/Envelope/utils.py @@ -0,0 +1,223 @@ +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 sample_distribution_gauss(size: int, dim: np.ndarray) -> np.ndarray: + return np.random.multivariate_normal( + mean=np.zeros(dim), + cov=np.eye(dim), + size=size, + ) + + +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 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] + X /= np.std(X, axis=0) + return X + + +def sample_distribution(size: int, cov_matrix: np.ndarray, name: str) -> np.ndarray: + dim = cov_matrix.shape[0] + if name == "kv": + X = sample_distribution_kv(size, dim) + elif name == "waterbag": + X = sample_distribution_waterbag(size, dim) + elif name == "gauss": + X = sample_distribution_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 + + +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/__init__.py b/py/orbit/envelope/__init__.py new file mode 100644 index 00000000..38001c9e --- /dev/null +++ b/py/orbit/envelope/__init__.py @@ -0,0 +1,3 @@ +from .envelope import Envelope +from .analysis import EnvelopeAnalysis +from .tracking import EnvelopeTracker diff --git a/py/orbit/envelope/analysis.py b/py/orbit/envelope/analysis.py new file mode 100644 index 00000000..5c3f0431 --- /dev/null +++ b/py/orbit/envelope/analysis.py @@ -0,0 +1,61 @@ +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 new file mode 100644 index 00000000..59ee1a0a --- /dev/null +++ b/py/orbit/envelope/envelope.py @@ -0,0 +1,215 @@ +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 .matrix import get_zp_coeff +from .utils import get_classical_radius +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_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): + cov_matrix[i, j] = cov_matrix[j, i] = twiss_calc.getCorrelation(i, j) + return cov_matrix + + +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 + + +class Envelope: + """Represents the first and second moments of the beam distribution.""" + + def __init__( + self, + cov_matrix: np.ndarray, + kin_energy: float, + mass: float, + charge: float = 1.0, + time: float = 0.0, + intensity: float = 0.0, + centroid: np.ndarray | None = None, + ) -> None: + """Constructor. + + Args: + cov_matrix: 6 x 6 covariance matrix. + 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. + """ + 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 + + @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) + + @property + def gamma(self) -> float: + return 1.0 + self.kin_energy / self.mass + + @property + def beta(self) -> float: + return self.momentum / (self.kin_energy + self.mass) + + @property + def momentum(self) -> float: + return math.sqrt(self.kin_energy * (self.kin_energy + 2.0 * self.mass)) + + @property + 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: + return np.sqrt(np.diag(self.cov_matrix))[axis] + + 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 = m @ self.centroid + u + + def sample(self, size: int, dist: str = "kv") -> np.ndarray: + particles = sample_distribution(size=size, cov_matrix=self.cov_matrix, name=dist) + 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.getSyncParticle().time(self.time) + bunch.macroSize(self.intensity / size) + 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: + cov_matrix = self.cov_matrix + cov_xx = cov_matrix[0, 0] + cov_yy = cov_matrix[2, 2] + cov_xy = cov_matrix[0, 2] + + # 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: + gamma = self.gamma + + # 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": + return self.sc_matrix_2d(length) + elif model == "3d": + return self.sc_matrix_3d(length) + else: + raise ValueError(f"Unknown space charge model {model}") diff --git a/py/orbit/envelope/matrix.py b/py/orbit/envelope/matrix.py new file mode 100644 index 00000000..adf8ad9f --- /dev/null +++ b/py/orbit/envelope/matrix.py @@ -0,0 +1,245 @@ +from __future__ import annotations + +import math +from typing import TYPE_CHECKING + +import numpy as np + +from orbit.utils.consts import speed_of_light + +if TYPE_CHECKING: + from .envelope import Envelope + + +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 + return 1.0 / (envelope.beta**2 * envelope.gamma * envelope.mass) + + +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' + return 1.0 / (envelope.beta**2 * envelope.gamma**3 * envelope.mass) + + +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(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, 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 + return matrix + + +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: + M = np.identity(7) + M[0, 1] = length + M[2, 3] = length + 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(envelope: Envelope, length: float, kq: float) -> np.ndarray: + if abs(kq) == 0: + return get_matrix_drift(envelope, length) + + 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 / (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_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) + + 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] = -(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) + return M + + +def get_matrix_solenoid(envelope: Envelope, length: float, B: float) -> np.ndarray: + if B == 0: + return get_matrix_drift(envelope, length) + + 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 / (envelope.gamma**2) + + M = np.linalg.inv(V) @ M @ V + 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_cf(envelope: Envelope, length: float, kq: float) -> np.ndarray: + if kq == 0: + return get_matrix_drift(envelope, length) + + 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 / (envelope.gamma**2) + M[4, 5] *= get_dp_p_coeff(envelope) + + envelope.time += length / (envelope.beta * speed_of_light) + return M + + +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 = 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. + 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 + envelope.kin_energy = kin_energy_out + + # The base RF gap is simple - no phase correction. + gamma_out = envelope.gamma + beta_out = envelope.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 diff --git a/py/orbit/envelope/matrix_fitting.py b/py/orbit/envelope/matrix_fitting.py new file mode 100644 index 00000000..db4882f9 --- /dev/null +++ b/py/orbit/envelope/matrix_fitting.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np + +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 + + +def orbit_matrix_to_numpy(matrix: Matrix) -> np.ndarray: + matrix_out = np.empty(matrix.size(), dtype=np.float64) + matrix.copyToBuffer(matrix_out) + return matrix_out + + +def fit_node_matrix( + node: AccNode, + bunch: Bunch, + part_index: int = -1, + 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: + matrix_generator = MatrixGenerator() + + if lost_bunch is None: + lost_bunch = Bunch() + bunch.copyEmptyBunchTo(lost_bunch) + + if matrix is None: + matrix = Matrix(7, 7) + + matrix_generator.initBunch(bunch) + + params_dict = {} if params_dict is None else params_dict.copy() + params_dict["bunch"] = bunch + params_dict["lostbunch"] = lost_bunch + params_dict["node"] = node + + active_part_index = node.getActivePartIndex() + if part_index >= 0: + node.setActivePartIndex(part_index) + try: + node.track(params_dict) + finally: + node.setActivePartIndex(active_part_index) + + matrix_generator.calculateMatrix(bunch, matrix) + return orbit_matrix_to_numpy(matrix) + + +def fit_lattice_matrix( + lattice: AccLattice, + bunch: Bunch, + index_start: int = 0, + index_stop: int | None = None, +) -> np.ndarray: + + if index_stop is None: + index_stop = -1 + + matrix = Matrix(7, 7) + + 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 new file mode 100644 index 00000000..869cb67b --- /dev/null +++ b/py/orbit/envelope/meson.build @@ -0,0 +1,16 @@ +py_sources = files([ + '__init__.py', + 'analysis.py', + 'envelope.py', + 'matrix.py', + 'matrix_fitting.py', + 'node_matrices.py', + 'tracking.py', + 'utils.py' +]) + +python.install_sources( + py_sources, + subdir: 'orbit/envelope', + # pure: true, +) diff --git a/py/orbit/envelope/node_matrices.py b/py/orbit/envelope/node_matrices.py new file mode 100644 index 00000000..13506c4b --- /dev/null +++ b/py/orbit/envelope/node_matrices.py @@ -0,0 +1,281 @@ +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 new file mode 100644 index 00000000..f51df4a3 --- /dev/null +++ b/py/orbit/envelope/tracking.py @@ -0,0 +1,207 @@ +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.orbit_utils import Matrix +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 +from .node_matrices import get_node_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 + delta_kin_energy: float + delta_time: float + + def update_envelope(self, envelope: Envelope) -> None: + envelope.kin_energy += self.delta_kin_energy + envelope.time += self.delta_time + + +class EnvelopeTracker: + def __init__( + self, + lattice: AccLattice, + index_start: int = 0, + index_stop: int | None = None, + fit: bool = True, + fallback: bool = False, + ) -> None: + self.lattice = lattice + 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()) + else: + self.index_stop = min(self.index_stop + 1, len(self.lattice.getNodes())) + + self.fit = fit + self.fallback = fallback + + self._bunch = None + self._matrix_generator = None + self._lost_bunch = None + self._fit_matrix = None + self._node_maps = 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: bool = False, + ) -> np.ndarray | None: + + from orbit.lattice import AccActionsContainer + 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["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 = 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.apply_matrix(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 and not store: + node_map = node_maps[node, part_index] + 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 - initial_kin_energy, + envelope.time - initial_time, + ) + apply_matrix(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: + 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=True, + ) + + 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 + initial_time = envelope.time + + if isinstance(node, SC_Base_AccNode): + raise NotImplementedError + + 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 = handler(node, envelope, part_index=part_index) + except NotImplementedError: + envelope.kin_energy = initial_kinetic_energy + envelope.time = initial_time + if not self.fallback: + raise + 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() + 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() + envelope.time = sync_particle.time() + + return matrix diff --git a/py/orbit/envelope/utils.py b/py/orbit/envelope/utils.py new file mode 100644 index 00000000..9876fbcc --- /dev/null +++ b/py/orbit/envelope/utils.py @@ -0,0 +1,57 @@ +import math +import numpy as np +from scipy.constants import epsilon_0 + +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 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, + size=size, + ) + + +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 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] + X /= np.std(X, axis=0) + return X + + +def sample_distribution(size: int, cov_matrix: np.ndarray, name: str) -> np.ndarray: + if name == "kv": + X = sample_distribution_kv(size, cov_matrix) + elif name == "waterbag": + X = sample_distribution_waterbag(size, cov_matrix) + elif name == "gauss": + X = sample_distribution_gauss(size, cov_matrix) + else: + raise ValueError(f"Invalid distribution name: {name}") + + L = np.linalg.cholesky(cov_matrix) + return X @ L.T + + +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)): + cov_matrix_proj[i, j] = cov_matrix[axis[i], axis[j]] + return cov_matrix_proj diff --git a/py/orbit/lattice/AccLattice.py b/py/orbit/lattice/AccLattice.py index 84a466f8..58f27fcc 100644 --- a/py/orbit/lattice/AccLattice.py +++ b/py/orbit/lattice/AccLattice.py @@ -1,12 +1,20 @@ -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 orbit.utils import orbitFinalize +from orbit.utils import NamedObject +from orbit.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 + from orbit.envelope.tracking import EnvelopeTracker class AccLattice(NamedObject, TypedObject): @@ -31,6 +39,7 @@ def __init__(self, name="no name"): self.__isInitialized = False self.__children = [] self.__childPositions = {} + self._envelope_tracker: EnvelopeTracker | None = None def initialize(self): """ @@ -261,3 +270,70 @@ def trackActions(self, actionsContainer, paramsDict={}, index_start=-1, index_st paramsDict["node"] = node paramsDict["parentNode"] = self node.trackActions(actionsContainer, paramsDict) + + def trackEnvelope( + self, + envelope: Envelope, + index_start: int = 0, + index_stop: int | None = None, + sc: str | None = None, + params_dict: dict | None = None, + action_container: AccActionsContainer | None = None, + fit: bool = False, + fallback: bool = False, + static: bool = False, + return_matrix: bool = False, + ) -> np.ndarray | None: + """Tracks envelope through the lattice. + + Args: + 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. + """ + from orbit.envelope.tracking import EnvelopeTracker + + tracker = EnvelopeTracker( + self, + index_start=index_start, + index_stop=index_stop, + fit=fit, + fallback=fallback, + ) + + if static: + 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: + self._envelope_tracker = None + + return tracker.track( + envelope, + sc=sc, + params_dict=params_dict, + action_container=action_container, + return_matrix=return_matrix, + ) diff --git a/py/orbit/lattice/AccNode.py b/py/orbit/lattice/AccNode.py index fdc145dc..bc4a2e40 100644 --- a/py/orbit/lattice/AccNode.py +++ b/py/orbit/lattice/AccNode.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import sys import os import math @@ -7,7 +9,7 @@ from ..utils import TypedObject from ..utils import ParamsDictObject -from ..lattice import AccActionsContainer +from .AccActionsContainer import AccActionsContainer class AccNode(NamedObject, TypedObject, ParamsDictObject): 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/LinacAccNodes.py b/py/orbit/py_linac/lattice/LinacAccNodes.py index d6872dca..2765adf1 100755 --- a/py/orbit/py_linac/lattice/LinacAccNodes.py +++ b/py/orbit/py_linac/lattice/LinacAccNodes.py @@ -18,6 +18,7 @@ # import teapot base functions from wrapper around C++ functions from orbit.teapot_base import TPB + # Import the linac specific tracking from linac_tracking. This module has # the following functions duplicated the original TEAPOT functions # drift - linac drift tracking @@ -141,7 +142,6 @@ def __init__(self, name="none"): BaseLinacNode.__init__(self, name) self.setType("markerLinacNode") - class LinacNode(BaseLinacNode): """ The abstract class of the linac accelerator elements hierarchy that can be tilted. @@ -308,7 +308,6 @@ def track(self, paramsDict): bunch = paramsDict["bunch"] self.tracking_module.drift(bunch, length) - class Quad(LinacMagnetNode): """ Quad Combined Function TEAPOT element. @@ -517,7 +516,6 @@ def getTotalField(self, z): G = self.getParam("dB/dr") return G - class Bend(LinacMagnetNode): """ Bend Combined Functions TEAPOT element. @@ -534,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) @@ -709,7 +709,6 @@ def track(self, paramsDict): TPB.bend1(bunch, length, theta / 2.0) return - class DCorrectorH(LinacMagnetNode): """ The Horizontal Dipole Corrector. @@ -754,7 +753,6 @@ def track(self, paramsDict): kick = -field * charge * length * 0.299792 / momentum self.tracking_module.kick(bunch, kick, 0.0, 0.0) - class DCorrectorV(LinacMagnetNode): """ The Vertical Dipole Corrector. @@ -799,7 +797,6 @@ def track(self, paramsDict): kick = field * charge * length * 0.299792 / momentum self.tracking_module.kick(bunch, 0, kick, 0.0) - class ThickKick(LinacMagnetNode): """ Thick kiker linac node. @@ -1014,7 +1011,6 @@ def track(self, paramsDict): bunch = paramsDict["bunch"] TPB.rotatexy(bunch, self.__angle) - class FringeField(BaseLinacNode): """ The class is a base class for the fringe field classes for others elements. diff --git a/py/orbit/py_linac/lattice/LinacRfGapNodes.py b/py/orbit/py_linac/lattice/LinacRfGapNodes.py index 30b1fbe8..dd28a848 100644 --- a/py/orbit/py_linac/lattice/LinacRfGapNodes.py +++ b/py/orbit/py_linac/lattice/LinacRfGapNodes.py @@ -26,6 +26,7 @@ # The abstract RF gap import from orbit.py_linac.lattice.LinacAccNodes import AbstractRF_Gap + # import teapot base functions from wrapper around C++ functions # Import the linac specific tracking from linac_tracking. This module has 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/py/orbit/teapot/teapot.py b/py/orbit/teapot/teapot.py index 63a09b27..ce2903d2 100644 --- a/py/orbit/teapot/teapot.py +++ b/py/orbit/teapot/teapot.py @@ -23,16 +23,16 @@ 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.core.aperture import Aperture from orbit.core.bunch import Bunch @@ -440,7 +440,6 @@ def track(self, paramsDict: dict) -> None: turn = bunch.bunchAttrInt("TurnNumber") bunch.bunchAttrInt("TurnNumber", turn + 1) - class NodeTEAPOT(BaseTEAPOT): def __init__(self, name: str = "no name") -> None: """ @@ -582,7 +581,6 @@ def track(self, paramsDict: dict) -> None: bunch = paramsDict["bunch"] TPB.drift(bunch, length) - class ApertureTEAPOT(NodeTEAPOT): """ Aperture TEAPOT element. @@ -622,7 +620,6 @@ def track(self, paramsDict: dict) -> None: lostbunch = paramsDict["lostbunch"] self.aperture.checkBunch(bunch, lostbunch) - class MonitorTEAPOT(NodeTEAPOT): """ Monitor TEAPOT element. @@ -649,7 +646,6 @@ def track(self, paramsDict: dict) -> None: self.addParam("yAvg", self.twiss.getAverage(2)) self.addParam("ypAvg", self.twiss.getAverage(3)) - class BunchWrapTEAPOT(NodeTEAPOT): """ Drift TEAPOT element. @@ -673,7 +669,6 @@ def track(self, paramsDict: dict) -> None: length = self.getParam("ring_length") TPB.wrapbunch(bunch, length) - class SolenoidTEAPOT(NodeTEAPOT): """ Solenoid TEAPOT element. @@ -721,7 +716,6 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform - class MultipoleTEAPOT(NodeTEAPOT): """ Multipole Combined Function TEAPOT element. @@ -871,7 +865,6 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform - class QuadTEAPOT(NodeTEAPOT): """ Quad Combined Function TEAPOT element. @@ -1034,7 +1027,6 @@ def setWaveform(self, waveform: Any) -> None: """ self.waveform = waveform - class BendTEAPOT(NodeTEAPOT): """ Bend Combined Functions TEAPOT element. @@ -1063,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) @@ -1248,7 +1242,6 @@ def track(self, paramsDict: dict) -> None: TPB.bend1(bunch, length, theta / 2.0) return - class RingRFTEAPOT(NodeTEAPOT): """ Ring RF TEAPOT element. @@ -1414,7 +1407,6 @@ def setWaveform(self, waveform): """ self.waveform = waveform - class TiltTEAPOT(BaseTEAPOT): """ The class to do tilt at the entrance of an TEAPOT element. @@ -1449,7 +1441,6 @@ def track(self, paramsDict: dict) -> None: bunch = paramsDict["bunch"] TPB.rotatexy(bunch, self.__angle) - class FringeFieldTEAPOT(BaseTEAPOT): """ The class is a base class for the fringe field classes for others TEAPOT elements. 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 new file mode 100644 index 00000000..2c72fdd5 --- /dev/null +++ b/tests/py/orbit/test_envelope.py @@ -0,0 +1,536 @@ +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 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 +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 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) + 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.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) + + # 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_lattice_matrix(lattice, 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) + + +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_lattice_matrix(lattice, 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) + + +@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): + from orbit.envelope.matrix import get_matrix_rf_gap + + 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"] + + reference = Envelope.from_bunch(bunch_in) + matrix = get_matrix_rf_gap( + reference, + 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) + 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(): + # 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( + 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)]) + 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(kin_energy=sync_part.kinEnergy(), mass=bunch.mass(), 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( + 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.apply_matrix(matrix) + assert np.all(np.isclose(envelope_out_a.cov_matrix, envelope_out_b.cov_matrix)) + + +@pytest.mark.parametrize("kind", ["teapot", "linac"]) +@pytest.mark.parametrize("fringe_in,fringe_out", [(False, False), (True, False), (False, True), (True, True)]) +@pytest.mark.parametrize("static", [False, True]) +@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=theta, ea1=ea1, ea2=ea2, nparts=5) + else: + node = Bend() + node.setLength(1) + node.setnParts(5) + for name, value in [("theta", theta), ("ea1", ea1), ("ea2", ea2)]: + node.setParam(name, value) + + lattice = make_lattice([node]) + node.setUsageFringeFieldIN(fringe_in) + node.setUsageFringeFieldOUT(fringe_out) + + bunch = Bunch() + 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.from_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)