Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
358c999
Add tests for `Sextupole` implementation
jank324 Apr 22, 2025
dc37cff
Add sextupole sekelton
jank324 Apr 22, 2025
75a0f98
Rearrange contents of `track_methods.py`
jank324 Apr 22, 2025
7cbe9e0
Implement method to generate second order transfer map
jank324 Apr 22, 2025
747ceb1
Fix sextupole into working state
jank324 Apr 22, 2025
f8be117
Fix test failures resulting from minor oversights
jank324 Apr 22, 2025
9d51d00
First draft of `ParameterBeam` implementation for `Sextupole`
jank324 Apr 22, 2025
00da660
Add a test for `ParameterBeam` tracking through a `Sextupole`
jank324 Apr 22, 2025
96ee1a0
Add changelog entry
jank324 Apr 22, 2025
2951aa0
Implement `ParameterBeam` in `Sextupole` with first order effects only
jank324 Apr 23, 2025
214fc7c
Rename method for computing T to reflect that T is a tensor
jank324 Apr 25, 2025
142fca7
Add vectorization and dtype tests for sextupole
Hespe Apr 25, 2025
2061e24
Add clone test for sextupole
Hespe Apr 25, 2025
7a1c5fd
Slightly cleaer docstring for `rotation_matrix` method
jank324 Apr 25, 2025
3311f1d
Merge branch 'sextupole' of github.com:desy-ml/cheetah into sextupole
jank324 Apr 25, 2025
23a6125
Address (mostly) the comments from Copilot review
jank324 Apr 25, 2025
9ebf1b7
Add unit to docstring
jank324 Apr 25, 2025
d27f710
Fix precedence that I ignored when originally combining the two steps…
jank324 Apr 25, 2025
c99215d
Merge branch 'master' into sextupole
jank324 Apr 25, 2025
49980f5
Use realistic sextupole values in test similar to those in EuXFEL lat…
jank324 Apr 25, 2025
578e8d2
Merge branch 'sextupole' of github.com:desy-ml/cheetah into sextupole
jank324 Apr 25, 2025
4650997
Address the fact the `ParameterBeam` and `ParticleBeam` comparison on…
jank324 Apr 25, 2025
b9e9d48
Add docs entry for `Sextupole`
jank324 Apr 25, 2025
2fede43
Add vectorised sextupole test
jank324 Apr 25, 2025
3645c62
Fix bug discovered in sextupole vectorisation
jank324 Apr 25, 2025
0b6c720
Test with vectorisation in first order as well
jank324 Apr 25, 2025
e1ed559
Add dependency to speed up einsum operations in `torch`
jank324 Apr 25, 2025
f285e3c
Presumed minor speed up in first order titlt by replacing `einsum`
jank324 Apr 25, 2025
3d3eea7
Fix `Sextupole.defining_features`
jank324 Apr 25, 2025
5971ad0
Clean up matrix multiplications across Cheetah replacing `matmul` wit…
jank324 Apr 25, 2025
504e18c
Merge branch 'master' into sextupole
jank324 Apr 25, 2025
894dbd5
Add sentence to docstring that MAD convention is used
jank324 Apr 28, 2025
64ac13c
Replace `einsum` by matrix multiplications
jank324 Apr 28, 2025
e741aca
Add further suggestions by @Hespe
jank324 Apr 28, 2025
b05f4d0
Merge branch 'sextupole' of github.com:desy-ml/cheetah into sextupole
jank324 Apr 28, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

- Implement `split` method for the `Solenoid` element (see #380) (@cr-xu)
- Implement a more robust RPN parser, fixing a bug where short strings in an Elegant variable definition would cause parsing to fail. (see #387) (@amylizzle, @Hespe, @jank324)
- Add a `Sextupole` element (see #406) (@jank324, @Hespe)

### 🐛 Bug fixes

Expand Down
1 change: 1 addition & 0 deletions cheetah/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
RBend,
Screen,
Segment,
Sextupole,
Solenoid,
SpaceChargeKick,
TransverseDeflectingCavity,
Expand Down
1 change: 1 addition & 0 deletions cheetah/accelerator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .rbend import RBend # noqa: F401
from .screen import Screen # noqa: F401
from .segment import Segment # noqa: F401
from .sextupole import Sextupole # noqa: F401
from .solenoid import Solenoid # noqa: F401
from .space_charge_kick import SpaceChargeKick # noqa: F401
from .transverse_deflecting_cavity import TransverseDeflectingCavity # noqa: F401
Expand Down
8 changes: 3 additions & 5 deletions cheetah/accelerator/cavity.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,10 @@ def _track_beam(self, incoming: Beam) -> Beam:

tm = self.transfer_map(incoming.energy, incoming.species)
if isinstance(incoming, ParameterBeam):
outgoing_mu = torch.matmul(tm, incoming.mu.unsqueeze(-1)).squeeze(-1)
outgoing_cov = torch.matmul(
tm, torch.matmul(incoming.cov, tm.transpose(-2, -1))
)
outgoing_mu = (tm @ incoming.mu.unsqueeze(-1)).squeeze(-1)
outgoing_cov = tm @ incoming.cov @ tm.transpose(-2, -1)
else: # ParticleBeam
outgoing_particles = torch.matmul(incoming.particles, tm.transpose(-2, -1))
outgoing_particles = incoming.particles @ tm.transpose(-2, -1)
delta_energy = (
self.voltage * torch.cos(phi) * incoming.species.num_elementary_charges * -1
)
Expand Down
5 changes: 1 addition & 4 deletions cheetah/accelerator/custom_transfer_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,7 @@ def from_merging_elements(
(*incoming_beam.energy.shape, 1, 1)
)
for element in elements:
tm = torch.matmul(
element.transfer_map(incoming_beam.energy, incoming_beam.species),
tm,
)
tm = element.transfer_map(incoming_beam.energy, incoming_beam.species) @ tm
incoming_beam = element.track(incoming_beam)

combined_length = sum(element.length for element in elements)
Expand Down
8 changes: 4 additions & 4 deletions cheetah/accelerator/dipole.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,11 +407,11 @@ def transfer_map(self, energy: torch.Tensor, species: Species) -> torch.Tensor:
R[..., 2, 3] = self.length

# Apply fringe fields
R = torch.matmul(R_exit, torch.matmul(R, R_enter))
R = R_exit @ R @ R_enter

# Apply rotation for tilted magnets
R = torch.matmul(
rotation_matrix(-self.tilt), torch.matmul(R, rotation_matrix(self.tilt))
)
R = rotation_matrix(-self.tilt) @ R @ rotation_matrix(self.tilt)

return R

def _transfer_map_enter(self) -> torch.Tensor:
Expand Down
8 changes: 7 additions & 1 deletion cheetah/accelerator/drift.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

from cheetah.accelerator.element import Element
from cheetah.particles import Beam, ParticleBeam, Species
from cheetah.utils import UniqueNameGenerator, bmadx, compute_relativistic_factors
from cheetah.utils import (
UniqueNameGenerator,
bmadx,
compute_relativistic_factors,
verify_device_and_dtype,
)

generate_unique_name = UniqueNameGenerator(prefix="unnamed_element")

Expand All @@ -30,6 +35,7 @@ def __init__(
device: torch.device | None = None,
dtype: torch.dtype | None = None,
) -> None:
device, dtype = verify_device_and_dtype([length], device, dtype)
factory_kwargs = {"device": device, "dtype": dtype}
super().__init__(name=name, **factory_kwargs)

Expand Down
6 changes: 3 additions & 3 deletions cheetah/accelerator/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ def track(self, incoming: Beam) -> Beam:
"""
if isinstance(incoming, ParameterBeam):
tm = self.transfer_map(incoming.energy, incoming.species)
mu = torch.matmul(tm, incoming.mu.unsqueeze(-1)).squeeze(-1)
cov = torch.matmul(tm, torch.matmul(incoming.cov, tm.transpose(-2, -1)))
mu = (tm @ incoming.mu.unsqueeze(-1)).squeeze(-1)
cov = tm @ incoming.cov @ tm.transpose(-2, -1)
return ParameterBeam(
mu,
cov,
Expand All @@ -79,7 +79,7 @@ def track(self, incoming: Beam) -> Beam:
)
elif isinstance(incoming, ParticleBeam):
tm = self.transfer_map(incoming.energy, incoming.species)
new_particles = torch.matmul(incoming.particles, tm.transpose(-2, -1))
new_particles = incoming.particles @ tm.transpose(-2, -1)
return ParticleBeam(
new_particles,
incoming.energy,
Expand Down
2 changes: 1 addition & 1 deletion cheetah/accelerator/quadrupole.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class Quadrupole(Element):
:param length: Length in meters.
:param k1: Strength of the quadrupole in 1/m^-2.
:param misalignment: Misalignment vector of the quadrupole in x- and y-directions.
:param tilt: Tilt angle of the quadrupole in x-y plane [rad]. pi/4 for
:param tilt: Tilt angle of the quadrupole in x-y plane in radians. pi/4 for
skew-quadrupole.
:param num_steps: Number of drift-kick-drift steps to use for tracking through the
element when tracking method is set to `"bmadx"`.
Expand Down
2 changes: 1 addition & 1 deletion cheetah/accelerator/segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ def transfer_map(self, energy: torch.Tensor, species: Species) -> torch.Tensor:
if self.is_skippable:
tm = torch.eye(7, device=energy.device, dtype=energy.dtype)
for element in self.elements:
tm = torch.matmul(element.transfer_map(energy, species), tm)
tm = element.transfer_map(energy, species) @ tm
return tm
else:
return None
Expand Down
142 changes: 142 additions & 0 deletions cheetah/accelerator/sextupole.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import matplotlib.pyplot as plt
import torch

from cheetah.accelerator.element import Element
from cheetah.particles import Beam, ParameterBeam, ParticleBeam, Species
from cheetah.track_methods import base_rmatrix, base_ttensor, misalignment_matrix
from cheetah.utils import verify_device_and_dtype


class Sextupole(Element):
"""
A sextupole element in a particle accelerator.

:param length: Length in meters.
:param k2: Sextupole strength in 1/m^3.
:param misalignment: Transverse misalignment in x and y directions in meters.
:param tilt: Tilt angle of the quadrupole in x-y plane in radians.
:param name: Unique identifier of the element.
"""

def __init__(
self,
length: torch.Tensor,
k2: torch.Tensor | None = None,
misalignment: torch.Tensor | None = None,
tilt: torch.Tensor | None = None,
name: str | None = None,
device: torch.device | None = None,
dtype: torch.dtype | None = None,
) -> None:
device, dtype = verify_device_and_dtype(
[length, k2, misalignment, tilt], device, dtype
)
factory_kwargs = {"device": device, "dtype": dtype}
super().__init__(name=name, **factory_kwargs)

self.length = torch.as_tensor(length, **factory_kwargs)

self.register_buffer_or_parameter(
"k2", torch.as_tensor(k2 if k2 is not None else 0.0, **factory_kwargs)
)
self.register_buffer_or_parameter(
"misalignment",
torch.as_tensor(
misalignment if misalignment is not None else (0.0, 0.0),
**factory_kwargs,
),
)
self.register_buffer_or_parameter(
"tilt", torch.as_tensor(tilt if tilt is not None else 0.0, **factory_kwargs)
)

def transfer_map(self, energy: torch.Tensor, species: Species) -> torch.Tensor:
R = base_rmatrix(
length=self.length,
k1=torch.zeros_like(self.length),
hx=torch.zeros_like(self.length),
species=species,
tilt=self.tilt,
energy=energy,
)

if torch.all(self.misalignment == 0):
return R
else:
R_entry, R_exit = misalignment_matrix(self.misalignment)
R = R_exit @ R @ R_entry
return R

def track(self, incoming: Beam) -> Beam:
"""
Track the beam through the sextupole element.

:param incoming: Beam entering the element.
:return: Beam exiting the element.
"""
first_order_tm = self.transfer_map(incoming.energy, incoming.species)
second_order_tm = base_ttensor(
length=self.length,
k1=torch.zeros_like(self.length),
k2=self.k2,
hx=torch.zeros_like(self.length),
species=incoming.species,
tilt=self.tilt,
energy=incoming.energy,
)

if isinstance(incoming, ParameterBeam):
# For ParameterBeam, only first-order effects are applied
return super().track(incoming)
elif isinstance(incoming, ParticleBeam):
# Apply the transfer map to the incoming particles
first_order_particles = incoming.particles @ first_order_tm.transpose(
-2, -1
)
second_order_particles = torch.einsum(
"...ijk,...j,...k->...i",
second_order_tm.unsqueeze(-4), # Add broadcast dimension for particles
incoming.particles,
incoming.particles,
)
outgoing_particles = second_order_particles + first_order_particles

return ParticleBeam(
particles=outgoing_particles,
energy=incoming.energy,
particle_charges=incoming.particle_charges,
survival_probabilities=incoming.survival_probabilities,
species=incoming.species,
)
else:
raise TypeError(
f"Unsupported beam type: {type(incoming)}. Expected ParameterBeam or "
"ParticleBeam."
)

@property
def is_skippable(self) -> bool:
return False

@property
def is_active(self) -> bool:
return torch.any(self.k2 != 0.0).item()

def split(self, resolution: torch.Tensor) -> list[Element]:
raise NotImplementedError

def plot(self, ax: plt.Axes, s: float, vector_idx: tuple | None = None) -> None:
raise NotImplementedError

@property
def defining_features(self) -> list[str]:
return super().defining_features + ["length", "k2", "misalignment", "tilt"]

def __repr__(self) -> str:
return (
f"{self.__class__.__name__}(length={repr(self.length)}, "
f"k2={repr(self.k2)}, "
f"misalignment={repr(self.misalignment)}, "
f"tilt={repr(self.tilt)}, "
f"name={repr(self.name)})"
Comment thread
jank324 marked this conversation as resolved.
)
Loading