slipstream-accel 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- slipstream/__init__.py +77 -0
- slipstream/_compile_env.py +38 -0
- slipstream/analysis/__init__.py +1 -0
- slipstream/analysis/beamline_radiation.py +122 -0
- slipstream/analysis/emittance.py +27 -0
- slipstream/analysis/loco.py +76 -0
- slipstream/analysis/nonlinear.py +346 -0
- slipstream/analysis/nonlinear_opt.py +388 -0
- slipstream/analysis/ring6d.py +148 -0
- slipstream/analysis/ring_outputs.py +196 -0
- slipstream/analysis/slices.py +221 -0
- slipstream/beamline.py +219 -0
- slipstream/beamline_cli.py +52 -0
- slipstream/beamline_config.py +228 -0
- slipstream/constants.py +10 -0
- slipstream/data/__init__.py +5 -0
- slipstream/data/particles.py +39 -0
- slipstream/data/results.py +255 -0
- slipstream/ibs.py +224 -0
- slipstream/lattice/__init__.py +5 -0
- slipstream/lattice/apertures.py +199 -0
- slipstream/lattice/lattice.py +81 -0
- slipstream/lattice/optics.py +40 -0
- slipstream/lattice/ramp.py +104 -0
- slipstream/lattice/twiss_table.py +61 -0
- slipstream/reconstruction.py +189 -0
- slipstream/sdds_io.py +25 -0
- slipstream/serialization.py +20 -0
- slipstream/tracking/__init__.py +2 -0
- slipstream/tracking/distributions.py +145 -0
- slipstream/tracking/native/__init__.py +21 -0
- slipstream/tracking/native/astra_io.py +190 -0
- slipstream/tracking/native/collective.py +1149 -0
- slipstream/tracking/native/double_single.py +325 -0
- slipstream/tracking/native/elements.py +592 -0
- slipstream/tracking/native/errors.py +131 -0
- slipstream/tracking/native/fields.py +310 -0
- slipstream/tracking/native/generator.py +581 -0
- slipstream/tracking/native/gun.py +161 -0
- slipstream/tracking/native/injector.py +2516 -0
- slipstream/tracking/native/injector_ibs.py +251 -0
- slipstream/tracking/native/injector_ibs_warp.py +152 -0
- slipstream/tracking/native/injector_wake.py +99 -0
- slipstream/tracking/native/lattice_import.py +352 -0
- slipstream/tracking/native/laura_fields.py +101 -0
- slipstream/tracking/native/laura_import.py +88 -0
- slipstream/tracking/native/laura_injector.py +171 -0
- slipstream/tracking/native/linac.py +682 -0
- slipstream/tracking/native/linac_setup.py +51 -0
- slipstream/tracking/native/linac_twiss.py +206 -0
- slipstream/tracking/native/magnets.py +270 -0
- slipstream/tracking/native/optics.py +111 -0
- slipstream/tracking/native/photocathode.py +164 -0
- slipstream/tracking/native/radiation.py +51 -0
- slipstream/tracking/native/ring.py +376 -0
- slipstream/tracking/native/ring_physics.py +116 -0
- slipstream/tracking/native/ring_warp.py +395 -0
- slipstream/tracking/native/space_charge.py +465 -0
- slipstream/tracking/native/tracker.py +623 -0
- slipstream/tracking/native/warp_kernels.py +1173 -0
- slipstream/wakefields/__init__.py +16 -0
- slipstream/wakefields/chambers.py +74 -0
- slipstream/wakefields/impedance.py +52 -0
- slipstream/wakefields/longrange.py +108 -0
- slipstream/wakefields/multilayer/__init__.py +2 -0
- slipstream/wakefields/multilayer/bessel.py +163 -0
- slipstream/wakefields/multilayer/flat.py +232 -0
- slipstream/wakefields/multilayer/round.py +264 -0
- slipstream/wakefields/multilayer/yokoya.py +141 -0
- slipstream/wakefields/shortrange.py +250 -0
- slipstream/wakefields/transverse.py +138 -0
- slipstream_accel-1.1.0.dist-info/METADATA +147 -0
- slipstream_accel-1.1.0.dist-info/RECORD +77 -0
- slipstream_accel-1.1.0.dist-info/WHEEL +5 -0
- slipstream_accel-1.1.0.dist-info/entry_points.txt +2 -0
- slipstream_accel-1.1.0.dist-info/licenses/LICENSE +201 -0
- slipstream_accel-1.1.0.dist-info/top_level.txt +1 -0
slipstream/__init__.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Public exports collect native transport, machine models, wakes and beam diagnostics. See
|
|
2
|
+
docs/modules/__init__.md."""
|
|
3
|
+
|
|
4
|
+
from .beamline import BeamlineStudy
|
|
5
|
+
from .analysis.nonlinear import CoupledOptics, coupled_optics, coupled_signals
|
|
6
|
+
from .analysis.ring_outputs import (
|
|
7
|
+
plot_dynamic_aperture, plot_ring_layout, plot_ring_twiss,
|
|
8
|
+
ring_lattice_table, ring_optics_table, ring_parameters,
|
|
9
|
+
)
|
|
10
|
+
from .analysis.ring6d import (
|
|
11
|
+
MomentumScan, Ring6DResult, betatron_tunes6d, dynamic_aperture6d,
|
|
12
|
+
frequency_map6d, momentum_aperture6d, track_ring6d,
|
|
13
|
+
)
|
|
14
|
+
from .constants import C_LIGHT, ELECTRON_MASS_EV
|
|
15
|
+
from .data.results import BeamlineResult, TrackingResult
|
|
16
|
+
from .lattice.lattice import Lattice
|
|
17
|
+
from .lattice.optics import TransverseOptics
|
|
18
|
+
from .lattice.ramp import RampProfile
|
|
19
|
+
from .reconstruction import GraphedStep, ScanModel, Screen
|
|
20
|
+
from .tracking.native import (
|
|
21
|
+
ElementSpec, Injector, InjectorIBSSettings, LinacTracker, NativeTracker, NativeTrackResult, Photocathode, parse_elegant_lattice,
|
|
22
|
+
)
|
|
23
|
+
from .tracking.native.ring import RingLossMap, RingMap, RingTrackResult
|
|
24
|
+
from .wakefields.chambers import FlatChamber, FreqScan, RoundChamber
|
|
25
|
+
from .wakefields.impedance import Impedance
|
|
26
|
+
from .wakefields.longrange import LongRangeWake, Resonator, equivalent_voltage_phasor, phasor_at_particles
|
|
27
|
+
from .wakefields.shortrange import ShortRangeWake
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"plot_dynamic_aperture",
|
|
31
|
+
"plot_ring_layout",
|
|
32
|
+
"plot_ring_twiss",
|
|
33
|
+
"ring_lattice_table",
|
|
34
|
+
"ring_optics_table",
|
|
35
|
+
"ring_parameters",
|
|
36
|
+
"CoupledOptics",
|
|
37
|
+
"coupled_optics",
|
|
38
|
+
"coupled_signals",
|
|
39
|
+
"RingLossMap",
|
|
40
|
+
"RingTrackResult",
|
|
41
|
+
"MomentumScan",
|
|
42
|
+
"Ring6DResult",
|
|
43
|
+
"betatron_tunes6d",
|
|
44
|
+
"dynamic_aperture6d",
|
|
45
|
+
"frequency_map6d",
|
|
46
|
+
"momentum_aperture6d",
|
|
47
|
+
"track_ring6d",
|
|
48
|
+
"BeamlineResult",
|
|
49
|
+
"BeamlineStudy",
|
|
50
|
+
"C_LIGHT",
|
|
51
|
+
"ELECTRON_MASS_EV",
|
|
52
|
+
"ElementSpec",
|
|
53
|
+
"FlatChamber",
|
|
54
|
+
"FreqScan",
|
|
55
|
+
"GraphedStep",
|
|
56
|
+
"Impedance",
|
|
57
|
+
"Injector",
|
|
58
|
+
"InjectorIBSSettings",
|
|
59
|
+
"Lattice",
|
|
60
|
+
"LinacTracker",
|
|
61
|
+
"LongRangeWake",
|
|
62
|
+
"NativeTrackResult",
|
|
63
|
+
"NativeTracker",
|
|
64
|
+
"Photocathode",
|
|
65
|
+
"RampProfile",
|
|
66
|
+
"RingMap",
|
|
67
|
+
"Resonator",
|
|
68
|
+
"RoundChamber",
|
|
69
|
+
"ScanModel",
|
|
70
|
+
"Screen",
|
|
71
|
+
"ShortRangeWake",
|
|
72
|
+
"TrackingResult",
|
|
73
|
+
"TransverseOptics",
|
|
74
|
+
"equivalent_voltage_phasor",
|
|
75
|
+
"parse_elegant_lattice",
|
|
76
|
+
"phasor_at_particles",
|
|
77
|
+
]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Cache configuration changes compilation storage, without changing transport or physical models. See
|
|
2
|
+
docs/modules/_compile_env.md."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _default_cache_root() -> Path:
|
|
11
|
+
"""One stable root per OS -- survives what the volatile default does not."""
|
|
12
|
+
if sys.platform == "win32":
|
|
13
|
+
base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
|
|
14
|
+
return Path(base) / "slipstream-inductor-cache"
|
|
15
|
+
return Path.home() / ".cache" / "slipstream-inductor"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def cache_dirs(root: Path | None = None) -> tuple[Path, Path]:
|
|
19
|
+
"""``(inductor_dir, triton_dir)`` under ``root`` (default: ``_default_cache_root()``) -- the two
|
|
20
|
+
directories ``set_compile_cache_env`` points ``TORCHINDUCTOR_CACHE_DIR``/ ``TRITON_CACHE_DIR``
|
|
21
|
+
at."""
|
|
22
|
+
root = root or _default_cache_root()
|
|
23
|
+
return root / "inductor", root / "triton"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def set_compile_cache_env(root: Path | None = None) -> None:
|
|
27
|
+
"""Compute set compile cache env; see the module documentation for details."""
|
|
28
|
+
inductor_dir, triton_dir = cache_dirs(root)
|
|
29
|
+
inductor_dir = Path(os.environ.get("TORCHINDUCTOR_CACHE_DIR", str(inductor_dir)))
|
|
30
|
+
triton_dir = Path(os.environ.get("TRITON_CACHE_DIR", str(triton_dir)))
|
|
31
|
+
inductor_dir.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
triton_dir.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", str(inductor_dir))
|
|
34
|
+
os.environ.setdefault("TRITON_CACHE_DIR", str(triton_dir))
|
|
35
|
+
os.environ.setdefault("TORCHINDUCTOR_FX_GRAPH_CACHE", "1")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
set_compile_cache_env()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Analysis computes statistics from transported particle data. See docs/modules/analysis/__init__.md."""
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Differentiable linear beamline covariance transport with dipole ISR.
|
|
2
|
+
|
|
3
|
+
Coordinates are slopes (x, x', y, y', delta), not canonical particle states.
|
|
4
|
+
Reference energy is constant; classical damping and nonlinear transport are
|
|
5
|
+
not included. See docs/modules/analysis/beamline_radiation.md.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
import math
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
|
|
14
|
+
from ..constants import ELECTRON_MASS_EV
|
|
15
|
+
from ..tracking.native.radiation import bend_radiation_rates
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class LinearRadiationResult:
|
|
20
|
+
input_covariance: torch.Tensor
|
|
21
|
+
covariance: torch.Tensor
|
|
22
|
+
covariance_without_isr: torch.Tensor
|
|
23
|
+
diffusion_covariance: torch.Tensor
|
|
24
|
+
transport: torch.Tensor
|
|
25
|
+
s_m: torch.Tensor
|
|
26
|
+
transport_profile: torch.Tensor
|
|
27
|
+
diffusion_profile: torch.Tensor
|
|
28
|
+
offset_m: torch.Tensor
|
|
29
|
+
longitudinal_m: torch.Tensor
|
|
30
|
+
exit_angle_rad: torch.Tensor
|
|
31
|
+
i2_m_inv: torch.Tensor
|
|
32
|
+
i3_m_inv2: torch.Tensor
|
|
33
|
+
loss_parameter: torch.Tensor
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def linear_radiation_transport(
|
|
37
|
+
length_m: torch.Tensor, angle_rad: torch.Tensor, k1_m2: torch.Tensor,
|
|
38
|
+
covariance: torch.Tensor, *, energy_eV: float,
|
|
39
|
+
e1_rad: torch.Tensor | None = None, e2_rad: torch.Tensor | None = None,
|
|
40
|
+
samples_per_element: int = 2,
|
|
41
|
+
) -> LinearRadiationResult:
|
|
42
|
+
"""Propagate expected ISR second moments through aligned hard-edge elements.
|
|
43
|
+
|
|
44
|
+
Lengths, angles, quadrupole strengths and faces retain their AD graphs.
|
|
45
|
+
All tensors must be CPU float64. Elements have positive length; bends
|
|
46
|
+
must be pure dipoles. Faces use first-order zero-gap edge focusing.
|
|
47
|
+
Sampling changes the optics profile, not the exact linear noise integral.
|
|
48
|
+
"""
|
|
49
|
+
e1 = torch.zeros_like(angle_rad) if e1_rad is None else e1_rad
|
|
50
|
+
e2 = torch.zeros_like(angle_rad) if e2_rad is None else e2_rad
|
|
51
|
+
inputs = (length_m, angle_rad, k1_m2, covariance, e1, e2)
|
|
52
|
+
if any(t.device.type != "cpu" or t.dtype != torch.float64 for t in inputs):
|
|
53
|
+
raise ValueError("Linear radiation transport requires CPU float64 tensors")
|
|
54
|
+
if (length_m.ndim != 1 or not len(length_m) or covariance.shape != (5, 5)
|
|
55
|
+
or any(t.shape != length_m.shape for t in (angle_rad, k1_m2, e1, e2))):
|
|
56
|
+
raise ValueError("Expected nonempty equal-length element vectors and a (5,5) covariance")
|
|
57
|
+
if samples_per_element < 1 or not isinstance(samples_per_element, int):
|
|
58
|
+
raise ValueError("samples_per_element must be a positive integer")
|
|
59
|
+
if not math.isfinite(energy_eV) or energy_eV/ELECTRON_MASS_EV < 1000:
|
|
60
|
+
raise ValueError("Ultrarelativistic electron total energy is required")
|
|
61
|
+
if any(not bool(torch.isfinite(t).all()) for t in inputs) or bool((length_m <= 0).any()):
|
|
62
|
+
raise ValueError("Finite inputs and positive lengths are required")
|
|
63
|
+
if bool(((angle_rad != 0) & (k1_m2 != 0)).any()):
|
|
64
|
+
raise NotImplementedError("Radiating bends must be pure dipoles")
|
|
65
|
+
if not torch.allclose(covariance, covariance.T, atol=1e-24, rtol=1e-12):
|
|
66
|
+
raise ValueError("Input covariance must be symmetric")
|
|
67
|
+
h = angle_rad/length_m
|
|
68
|
+
loss_rate, variance_rate = bend_radiation_rates(energy_eV, h)
|
|
69
|
+
z, one = torch.zeros_like(h), torch.ones_like(h)
|
|
70
|
+
a = torch.stack((z, one, z, -(k1_m2+h*h), z, h, z, z, z), -1).reshape(-1, 3, 3)
|
|
71
|
+
q = torch.diag_embed(torch.stack((z, z, variance_rate), -1))
|
|
72
|
+
block = torch.cat((torch.cat((a, q), -1), torch.cat((torch.zeros_like(a), -a.transpose(-1, -2)), -1)), -2)
|
|
73
|
+
ds = length_m/samples_per_element
|
|
74
|
+
exponential = torch.matrix_exp(block*ds[:, None, None])
|
|
75
|
+
tx = exponential[:, :3, :3]
|
|
76
|
+
qx = exponential[:, :3, 3:] @ tx.transpose(-1, -2)
|
|
77
|
+
qx = (qx+qx.transpose(-1, -2))/2
|
|
78
|
+
ay = torch.stack((z, one, k1_m2, z), -1).reshape(-1, 2, 2)
|
|
79
|
+
ty = torch.matrix_exp(ay*ds[:, None, None])
|
|
80
|
+
n = len(length_m)
|
|
81
|
+
body = torch.zeros((n, 5, 5), dtype=length_m.dtype, device=length_m.device)
|
|
82
|
+
noise = torch.zeros_like(body)
|
|
83
|
+
ix, iy = torch.tensor([0, 1, 4]), torch.tensor([2, 3])
|
|
84
|
+
body[:, ix[:, None], ix[None, :]] = tx
|
|
85
|
+
body[:, iy[:, None], iy[None, :]] = ty
|
|
86
|
+
noise[:, ix[:, None], ix[None, :]] = qx
|
|
87
|
+
def faces(angles):
|
|
88
|
+
result = torch.eye(5, dtype=length_m.dtype).repeat(n, 1, 1)
|
|
89
|
+
focus = h*torch.tan(angles)
|
|
90
|
+
result[:, 1, 0], result[:, 3, 2] = focus, -focus
|
|
91
|
+
return result
|
|
92
|
+
entrance, exit_ = faces(e1), faces(e2)
|
|
93
|
+
body = body[:, None].expand(-1, samples_per_element, -1, -1)
|
|
94
|
+
noise = noise[:, None].expand_as(body)
|
|
95
|
+
identity = torch.eye(5, dtype=length_m.dtype).repeat(n, samples_per_element, 1, 1)
|
|
96
|
+
entry_steps, exit_steps = identity.clone(), identity.clone()
|
|
97
|
+
entry_steps[:, 0], exit_steps[:, -1] = entrance, exit_
|
|
98
|
+
maps = (exit_steps @ body @ entry_steps).reshape(-1, 5, 5)
|
|
99
|
+
noises = (exit_steps @ noise @ exit_steps.transpose(-1, -2)).reshape(-1, 5, 5)
|
|
100
|
+
# Associative prefix composition keeps the complete AD Jacobian batched.
|
|
101
|
+
stride = 1
|
|
102
|
+
while stride < len(maps):
|
|
103
|
+
later = maps[stride:]
|
|
104
|
+
noises = torch.cat((noises[:stride], noises[stride:]+later@noises[:-stride]@later.transpose(-1, -2)))
|
|
105
|
+
maps = torch.cat((maps[:stride], later@maps[:-stride]))
|
|
106
|
+
stride *= 2
|
|
107
|
+
transfer, diffusion = maps[-1], noises[-1]
|
|
108
|
+
off = transfer @ covariance @ transfer.T
|
|
109
|
+
diffusion = (diffusion+diffusion.T)/2
|
|
110
|
+
heading = torch.cumsum(angle_rad, 0)-angle_rad/2
|
|
111
|
+
chord = length_m*torch.sinc(angle_rad/(2*math.pi))
|
|
112
|
+
return LinearRadiationResult(
|
|
113
|
+
input_covariance=covariance, covariance=off+diffusion, covariance_without_isr=off,
|
|
114
|
+
diffusion_covariance=diffusion, transport=transfer,
|
|
115
|
+
s_m=torch.cat((length_m.new_zeros(1), torch.cumsum(ds.repeat_interleave(samples_per_element), 0))),
|
|
116
|
+
transport_profile=torch.cat((torch.eye(5, dtype=length_m.dtype)[None], maps)),
|
|
117
|
+
diffusion_profile=torch.cat((torch.zeros_like(transfer)[None], noises)),
|
|
118
|
+
offset_m=(chord*torch.sin(heading)).sum(),
|
|
119
|
+
longitudinal_m=(chord*torch.cos(heading)).sum(), exit_angle_rad=angle_rad.sum(),
|
|
120
|
+
i2_m_inv=(h*h*length_m).sum(), i3_m_inv2=(h.abs()**3*length_m).sum(),
|
|
121
|
+
loss_parameter=(loss_rate*length_m).sum(),
|
|
122
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""RMS helpers combine unbiased position/momentum variances with the mean cross product. See
|
|
2
|
+
docs/modules/analysis/emittance.md."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def rms_emittance(u: torch.Tensor, up: torch.Tensor) -> torch.Tensor:
|
|
9
|
+
"""Whole-ensemble RMS geometric emittance: ``sqrt(<u^2><up^2> -
|
|
10
|
+
<u*up>^2)``, via the unbiased (N-1) variance -- same convention as
|
|
11
|
+
``tracking.native.ring_physics.rms_emittance_tensor``."""
|
|
12
|
+
return torch.sqrt(torch.clamp(u.var() * up.var() - (u * up).mean() ** 2, min=0.0))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def geometric_emittance_xy(
|
|
16
|
+
xp: torch.Tensor, yp: torch.Tensor, x: torch.Tensor, y: torch.Tensor,
|
|
17
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
18
|
+
"""``(eps_x, eps_y)`` -- moved from ``injector._geometric_emittance_m``
|
|
19
|
+
unchanged (note the historical argument order: slopes first)."""
|
|
20
|
+
return rms_emittance(x, xp), rms_emittance(y, yp)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def longitudinal_emittance_keV_mm(z_or_tau_m: torch.Tensor, ekin_eV: torch.Tensor) -> torch.Tensor:
|
|
24
|
+
"""Compute longitudinal emittance keV mm; see the module documentation for details."""
|
|
25
|
+
dz_mm = (z_or_tau_m - z_or_tau_m.mean()) * 1e3
|
|
26
|
+
de_keV = (ekin_eV - ekin_eV.mean()) / 1e3
|
|
27
|
+
return torch.sqrt(torch.clamp(dz_mm.var() * de_keV.var() - (dz_mm * de_keV).mean() ** 2, min=0.0))
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Differentiates closed-orbit BPM readings with respect to corrector kick angles. See
|
|
2
|
+
docs/modules/analysis/loco.md."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from ..tracking.native.ring import RingMap
|
|
8
|
+
from .nonlinear import closed_orbit
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def orbit_response_matrix(
|
|
12
|
+
ring: RingMap, corrector_names: list[str], bpm_names: list[str],
|
|
13
|
+
delta: float = 0.0, create_graph: bool = False,
|
|
14
|
+
) -> torch.Tensor:
|
|
15
|
+
"""Compute orbit response matrix; see the module documentation for details."""
|
|
16
|
+
plane_of = {s.name.upper(): ("x" if s.kind == "hkick" else "y") for s in ring.specs if s.kind in ("hkick", "vkick")}
|
|
17
|
+
unknown_corr = [n for n in corrector_names if n.upper() not in plane_of]
|
|
18
|
+
if unknown_corr:
|
|
19
|
+
raise KeyError(f"not a corrector (hkick/vkick) element in this lattice: {unknown_corr}")
|
|
20
|
+
planes = [plane_of[n.upper()] for n in corrector_names]
|
|
21
|
+
|
|
22
|
+
index_of = {s.name.upper(): i for i, s in enumerate(ring.specs)}
|
|
23
|
+
unknown_bpm = [n for n in bpm_names if n.upper() not in index_of]
|
|
24
|
+
if unknown_bpm:
|
|
25
|
+
raise KeyError(f"no such element(s) in lattice: {unknown_bpm}")
|
|
26
|
+
tap_indices = [index_of[n.upper()] for n in bpm_names]
|
|
27
|
+
|
|
28
|
+
n = len(corrector_names)
|
|
29
|
+
|
|
30
|
+
zero = torch.zeros((), dtype=ring.dtype, device=ring.device)
|
|
31
|
+
zero_ring = ring.with_strengths(
|
|
32
|
+
kick_x={name: zero for name, plane in zip(corrector_names, planes) if plane == "x"},
|
|
33
|
+
kick_y={name: zero for name, plane in zip(corrector_names, planes) if plane == "y"},
|
|
34
|
+
)
|
|
35
|
+
co = closed_orbit(zero_ring, delta=delta, create_graph=create_graph)
|
|
36
|
+
|
|
37
|
+
def map_ring(state_and_kicks: torch.Tensor) -> tuple[RingMap, torch.Tensor]:
|
|
38
|
+
state = state_and_kicks[:6]
|
|
39
|
+
theta = state_and_kicks[6:]
|
|
40
|
+
kick_x = {name: theta[i] for i, (name, plane) in enumerate(zip(corrector_names, planes)) if plane == "x"}
|
|
41
|
+
kick_y = {name: theta[i] for i, (name, plane) in enumerate(zip(corrector_names, planes)) if plane == "y"}
|
|
42
|
+
return ring.with_strengths(kick_x=kick_x, kick_y=kick_y), state
|
|
43
|
+
|
|
44
|
+
def observe(state_and_kicks: torch.Tensor) -> torch.Tensor:
|
|
45
|
+
r, state = map_ring(state_and_kicks)
|
|
46
|
+
final, tapped = r.turn_with_taps(state, tap_indices)
|
|
47
|
+
return torch.cat((final[:4], tapped[..., (0, 2)].reshape(-1)))
|
|
48
|
+
|
|
49
|
+
base = torch.cat((co, torch.zeros(n, dtype=ring.dtype, device=ring.device)))
|
|
50
|
+
if not create_graph:
|
|
51
|
+
# Forward-mode keeps the full tapped tape out of a reverse-mode graph.
|
|
52
|
+
D = torch.func.jacfwd(observe)(base)
|
|
53
|
+
M, B = D[:4, :4], D[:4, 6:]
|
|
54
|
+
dco = torch.linalg.solve(torch.eye(4, dtype=ring.dtype, device=ring.device) - M, B)
|
|
55
|
+
P, Q = D[4:, :4], D[4:, 6:]
|
|
56
|
+
return (Q + P @ dco).reshape(len(bpm_names), 2, n)
|
|
57
|
+
|
|
58
|
+
D = torch.autograd.functional.jacobian(observe, base, create_graph=True, vectorize=True)
|
|
59
|
+
M, B = D[:4, :4], D[:4, 6:]
|
|
60
|
+
P, Q = D[4:, :4], D[4:, 6:]
|
|
61
|
+
dco = torch.linalg.solve(torch.eye(4, dtype=ring.dtype, device=ring.device) - M, B)
|
|
62
|
+
return (Q + P @ dco).reshape(len(bpm_names), 2, n)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def apply_calibration(
|
|
66
|
+
J: torch.Tensor, bpm_gain_x: torch.Tensor, bpm_gain_y: torch.Tensor,
|
|
67
|
+
bpm_roll: torch.Tensor, corrector_gain: torch.Tensor,
|
|
68
|
+
) -> torch.Tensor:
|
|
69
|
+
"""Compute apply calibration; see the module documentation for details."""
|
|
70
|
+
cos_r, sin_r = torch.cos(bpm_roll), torch.sin(bpm_roll)
|
|
71
|
+
m00, m01 = bpm_gain_x * cos_r, -bpm_gain_x * sin_r
|
|
72
|
+
m10, m11 = bpm_gain_y * sin_r, bpm_gain_y * cos_r
|
|
73
|
+
x, y = J[:, 0, :], J[:, 1, :]
|
|
74
|
+
x_cal = (m00.unsqueeze(-1) * x + m01.unsqueeze(-1) * y) * corrector_gain
|
|
75
|
+
y_cal = (m10.unsqueeze(-1) * x + m11.unsqueeze(-1) * y) * corrector_gain
|
|
76
|
+
return torch.stack([x_cal, y_cal], dim=1)
|