Manipulate a Lattice
sim.lattice is a list-like sequence of elements.
It holds strong references to the element objects added to it.
You can continue to change an element through a Python variable referring to it, and
the lattice keeps the object alive even if you delete or reassign that variable.
The same element may sit at several lattice positions, making tuning and ramping
operations for whole channels or ring arcs easy.
This page collects the operations that come up most often:
editing a lattice in place, building one lattice per run, and keeping a lattice for longer
than the simulation that used it.
For the full signature of every method, see
impactx.elements.KnownElementsList.
Everything is a Reference
Adding an element gives the lattice a strong reference to that object. Changing the object afterwards changes what is tracked:
q = elements.Quad(ds=0.3, k=2.0)
sim.lattice.append(q)
q.k = 4.0 # q and sim.lattice[0] refer to the same element
sim.track_particles() # tracks through Quad(ds=0.3, k=4.0)
Adding the same variable twice therefore places one element at two positions, and retuning it changes both:
sim.lattice.extend([q, q]) # one element, two positions
For elements that are tuned separately, construct one per position or add a copy:
sim.lattice.append(elements.Quad(ds=0.3, k=2.0))
sim.lattice.append(elements.Quad(ds=0.3, k=2.0)) # two distinct elements
template = elements.Quad(ds=0.3, k=2.0)
sim.lattice.extend([template.copy(), template.copy()]) # also two distinct elements
Repeating a Cell
extend() holds every element of the list it is given, so multiplying a list
repeats its elements rather than duplicating them:
cell = [elements.Drift(ds=0.25), elements.Quad(ds=1.0, k=1.0)]
sim.lattice.extend(cell * 3) # 6 positions, 2 elements used repeatedly
sim.lattice[0].ds = 0.5 # changes all three cells
That is usually what a periodic channel wants: retuning the cell retunes the channel. To tune the cells separately, copy the elements once per repetition:
for _ in range(3):
sim.lattice.extend([element.copy() for element in cell])
Note
Copying the list does not copy the elements in it.
cell.copy(), cell[:] and list(cell) each give a new list holding the same
element objects, so this still places the very elements cell holds:
sim.lattice.extend(cell.copy()) # a new list, the same elements
copy.copy() also copies the list, but references the same elements. Copy the elements, as above, to get independent ones.
Editing a Lattice in Place
Use indexing, insertion, deletion and slice assignment to edit the lattice being tracked:
sim.lattice[1].k = 2.5 # retune one element
sim.lattice.insert(0, elements.Marker(name="start")) # add at a position
del sim.lattice[-1] # remove the last
sim.lattice[2:4] = [elements.Drift(ds=0.75)] # replace a range
sim.lattice[3] = elements.Quad(ds=1.0, k=-1.0) # swap one element out
Indexing, slicing, iteration, len(), in,
insert(), remove(), index(),
count(), del and
reversed() are all available.
Membership, index(), count() and remove() match on
the element itself, so an element that merely has the same parameters as another is not
mistaken for it.
Iteration and reversed() take a snapshot of the element references when the iterator
is created. Later additions, removals and replacements do not change that iterator’s
sequence; changes to the referenced elements’ parameters remain visible.
To work on a group of elements at once, select them with
select(), which gives a
impactx.elements.FilteredElementsList:
sim.lattice.select(kind="Quad").replace_each(elements.Drift(ds=1.0))
sim.lattice.select(name="corrector.*").delete()
A name is matched exactly, or as a regular expression when it looks like one, so
"corrector.*" selects every corrector and "corrector1" selects that one.
A selection is a set of positions, so it describes the lattice as it was when it was taken.
Adding, removing or moving elements afterwards makes it stale, and using it then raises;
take a new one with select().
Changing an element’s own parameters moves nothing and leaves a selection usable.
One Lattice per Run
A parameter scan wants each run to differ in one knob and share everything else. The simplest way is a function that builds a fresh cell per run:
def fodo_cell(k):
return [
elements.Drift(ds=0.25, name="d1"),
elements.Quad(ds=1.0, k=k, name="q1"),
elements.Drift(ds=0.5, name="d2"),
elements.Quad(ds=1.0, k=-k, name="q2"),
elements.Drift(ds=0.25, name="d3"),
]
for k in [0.8, 0.9, 1.0, 1.1]:
sim = ImpactX()
# ... set up the beam ...
sim.lattice.extend(fodo_cell(k))
sim.track_particles()
sim.finalize()
Every run gets its own elements, so nothing a run does can reach the runs around it.
When the elements already exist – loaded from a lattice file, or built once at the top of the script – derive each run from those instead. Copy the elements the scan changes and share the rest:
d1 = elements.Drift(ds=0.25, name="d1")
q1 = elements.Quad(ds=1.0, k=1.0, name="q1")
d2 = elements.Drift(ds=0.5, name="d2")
q2 = elements.Quad(ds=1.0, k=-1.0, name="q2")
d3 = elements.Drift(ds=0.25, name="d3")
for k in [0.8, 0.9, 1.0, 1.1]:
sim = ImpactX()
# ... set up the beam ...
sim.lattice.extend([d1, q1.copy(k=k), d2, q2.copy(k=-k), d3])
sim.track_particles()
sim.finalize()
The quadrupoles are copied because each run gives them a different strength; the drifts are
not, because no run changes them.
q1 and q2 keep their original values throughout, so the scan reads off the loop
variable rather than whatever the previous run left behind.
Keyword arguments to copy() say how the copy differs
from the element it was made from, so that one element supplies the values for many:
scan = [q1.copy(k=k) for k in [0.8, 0.9, 1.0, 1.1]]
rf1 = elements.RFCavity(name="rf1", ds=1.3, escale=20.0, freq=1.3e9, phase=0.0,
cos_coefficients=[2.0], sin_coefficients=[0.0])
cavities = [rf1] + [rf1.copy(name=f"rf{i}") for i in range(2, 5)]
Parameters that only mean something as a pair are given together, as the constructor takes them:
square = elements.PolygonAperture(vertices_x=[-1.0, 1.0, 1.0, -1.0, -1.0],
vertices_y=[-1.0, -1.0, 1.0, 1.0, -1.0])
wider = square.copy(vertices_x=[-2.0, 2.0, 2.0, -2.0, -2.0],
vertices_y=[-2.0, -2.0, 2.0, 2.0, -2.0])
Setting a parameter the element does not have raises an error, e.g., for typos.
Note
element.copy() gives a new element with the same configuration.
A copy of a beam monitor does not inherit an already-open output file, and an element
written as a Python subclass must define copy() for this to work.
A beam monitor’s copy shares settings keyed by its name; overriding alpha, beta,
tn, cn or nonlinear_lens_invariants in copy() raises ValueError.
Construct a monitor with a different name for independent settings.
Keeping a Lattice Longer Than a Simulation
A lattice accessed through sim.lattice belongs to that
simulation, using it after the simulation is gone raises an error.
To reuse a lattice across simulations, keep the elements in a plain Python list and extend
each simulation’s lattice from it before tracking:
cell = [ # a plain Python list, owned by your script
elements.Drift(ds=0.25, name="d1"),
elements.Quad(ds=1.0, k=1.0, name="q1"),
elements.Drift(ds=0.25, name="d2"),
]
for run in range(runs):
sim = ImpactX()
# ... set up the beam ...
sim.lattice.extend(cell) # the same elements each run
sim.track_particles()
sim.finalize()
The list outlives every simulation, and each run tracks the same element objects.
Retuning a lattice list between runs therefore applies to the runs that follow.
Use element.copy() where the runs
must be independent, as in the scan above.
Note
Returning sim.lattice from a function does not work,
because the simulation ends
with the function:
def build():
sim = ImpactX()
sim.lattice.extend(cell)
return sim.lattice # the simulation ends here
lattice = build()
len(lattice) # raises
Return the simulation as well, or keep the elements in your own list as above.