Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend FloorPlot #50

Merged
merged 3 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
163 changes: 145 additions & 18 deletions examples/line.ipynb

Large diffs are not rendered by default.

455 changes: 455 additions & 0 deletions examples/line_check_different_configurations.ipynb

Large diffs are not rendered by default.

11 changes: 9 additions & 2 deletions tests/test_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,20 @@ def test_repeated_elements_survey():
# https://github.com/xsuite/xplt/issues/31
line = xt.Line(elements={"obm": xt.Bend(length=0.5)}, element_names=["obm", "obm"])
# line.replace_all_repeated_elements()
print(line.survey())
survey = line.survey()
print(survey)

plot = xplt.FloorPlot(line=line)
plot = xplt.FloorPlot(survey)

boxes = plot.artists_boxes
assert_equal(len(boxes), 2)
assert_equal(boxes[0].get_center(), [0.25, 0])
assert_equal(boxes[0].get_height(), 0.5)
assert_equal(boxes[1].get_center(), [0.75, 0])
assert_equal(boxes[1].get_height(), 0.5)


def test_sign_sticky():

x = [0, 1, 5, 0, 5, -3, 0, 1, 0, -2, 0]
assert_equal(xplt.line.sign_sticky(x, initial=1), [1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1])
166 changes: 92 additions & 74 deletions xplt/line.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@

def element_strength(element, n):
"""Get knl strength of element"""
if hasattr(element, f"k{n}") and hasattr(element, "length"):
return getattr(element, f"k{n}") * element.length
elif hasattr(element, "knl") and n <= element.order:
return element.knl[n]
return 0
knl = 0
if knl == 0 and hasattr(element, f"k{n}") and hasattr(element, "length"):
knl = getattr(element, f"k{n}") * element.length
if knl == 0 and hasattr(element, "knl") and n <= element.order:
knl = element.knl[n]
return knl


def nominal_order(element):
Expand All @@ -49,16 +50,18 @@ def nominal_order(element):


def effective_order(element):
"""Get effective order of element (ignoring zero strength)"""
order = {-1}
"""Get effective order of element (lowest non-zero knl or ksl strength)"""
order = set()
if hasattr(element, "length") and element.length > 0:
for n in range(10, -1, -1):
for n in range(10):
if get(element, f"k{n}", 0) or get(element, f"k{n}s", 0):
order.add(n)
for knl in ("knl", "ksl"):
if hasattr(element, knl):
order.add(int(np.max(np.nonzero(getattr(element, knl)), initial=-1)))
return max(order)
order.update(np.flatnonzero(getattr(element, knl)).tolist())
if order:
return min(order)
return -1


def order(knl):
Expand All @@ -72,6 +75,17 @@ def tanc(x):
return np.sinc(x / np.pi) / np.cos(x)


def sign_sticky(arr, *, initial=1):
"""Determine sign or values, but keep previous sign for zero values"""
s = np.sign(arr)
if s[0] == 0:
s[0] = initial
index = np.arange(len(s))
index[s == 0] = -1
index_last_nonzero = np.maximum.accumulate(index)
return s[index_last_nonzero]


PUBLIC_SECTION_BEGIN()


Expand Down Expand Up @@ -233,8 +247,7 @@ def __init__(

Args:
survey (Any | None): Survey data from MAD-X or Xsuite.
line (xtrack.Line | None): Line data with additional information about elements.
Use this to have colored boxes of correct size etc.
line (None | xtrack.Line): Optional Xsuite line object for backwards compatible coloring of Multipoles (deprecated).
projection (str): The projection to use: A pair of coordinates ('XZ', 'ZY' etc.)
boxes (None | bool | str | iterable | dict): Config option for showing colored boxes for elements. See below.
Detailed options can be "length" and all options suitable for a patch, such as "color", "alpha", etc.
Expand Down Expand Up @@ -303,8 +316,7 @@ def __init__(
self.artists_boxes = []
self.artists_labels = []

# set data
if survey is not None or line is not None:
if survey is not None:
self.update(survey, line)

def update(self, survey=None, line=None, *, autoscale=None):
Expand All @@ -314,7 +326,7 @@ def update(self, survey=None, line=None, *, autoscale=None):
Args:
survey (Any | None): Survey data. Defaults to `line.survey()`.
For convenience, passing line as first argument is also supported.
line (None | xtrack.Line): Line object. Defaults to `survey.line` if possible.
line (None | xtrack.Line): Optional Xsuite line object for backwards compatible coloring of Multipoles (deprecated).
autoscale (str | None | bool): Whether and on which axes to perform autoscaling.
One of `"x"`, `"y"`, `"xy"`, `False` or `None`. If `None`, decide based on :meth:`matplotlib.axes.Axes.get_autoscalex_on` and :meth:`matplotlib.axes.Axes.get_autoscaley_on`.

Expand All @@ -323,14 +335,6 @@ def update(self, survey=None, line=None, *, autoscale=None):

"""

# Handle various input types in a smart way
if line is None and type(survey).__name__ == "Line":
survey, line = None, survey
if survey is None and line is not None:
survey = line.survey()
if line is None and survey is not None:
line = getattr(survey, "line", None)

changed = []

if self.projection == "3D":
Expand All @@ -344,33 +348,48 @@ def update(self, survey=None, line=None, *, autoscale=None):
# can't handle this, because angles are not preserved
raise ValueError(f"Display units for {A} and {B} must be equal!")

X = get(survey, A) * scale
Y = get(survey, B) * scale
# ang: transform angles from data (A-B) to axis (X-Y) coordinate system
if self.projection == "ZX":
R = get(survey, "theta")
X = get(survey, A) * scale # coordinate to be plotted on x-axis
Y = get(survey, B) * scale # coordinate to be plotted on y-axis

def ang(a):
return a

elif self.projection == "XZ":
R = get(survey, "theta")

def ang(a):
return np.pi / 2 - a
# rotation of element (angle between plot x-axis and tangential beam direction)
if self.projection in ("ZX", "XZ"):
RT = get(survey, "theta")
elif self.projection in ("ZY",):
RT = get(survey, "phi")
else:
raise ValueError(f"Unknown projection {self.projection}")

elif self.projection == "ZY":
R = get(survey, "theta")
# ang: function to transform angles from data (A-B) to axis (X-Y) coordinate system
if self.projection in ("ZX", "ZY"):

def ang(a):
return a

else:
...
raise NotImplementedError()

def ang(a):
return np.pi / 2 - a

NAME = get(survey, "name")
BEND = get(survey, "angle")
ARC = -np.round(np.diff(RT, append=RT[-1]), 9) # bending angle to next element
HELICITY = sign_sticky(ARC) # if the beamline is left or right bending
RR = ang(
RT - ARC / 2 + HELICITY * np.pi / 2
) # angle between plot x-axis and radial vector of bending

LENGTH = get(survey, "length", np.zeros_like(NAME))
IS_THICK = get(survey, "isthick", np.zeros_like(NAME))
ORDER = get(survey, "order", -np.ones_like(NAME))
if (TYPE := get(survey, "element_type", None)) is not None:
# map element type to order when order is not in survey
for type, o in {
"Bend": 0,
"Quadrupole": 1,
"Sextupole": 2,
"Octupole": 3,
"Multipole": 999,
}.items():
ORDER[(ORDER < 0) & (TYPE == type)] = o

# beam line
############
Expand All @@ -391,40 +410,38 @@ def ang(a):
# remove old artists
self.artists_labels.pop().remove()

helicity = 1
legend_entries = []
for i, (x, y, rt, name, arc) in enumerate(zip(X, Y, R, NAME, BEND)):
helicity = np.sign(arc) or helicity
# rt = angle of tangential direction in data coords
# rr = angle of radial direction (outward) in axis coords
rr = ang(rt - arc / 2 + helicity * np.pi / 2)

drift_length = get(get(survey, "drift_length", []), i, -1)
order = get(get(survey, "order", []), i, -1)
length = get(get(survey, "length", []), i, 0)
is_thick = False
for i, (x, y, rt, name, arc) in enumerate(zip(X, Y, RT, NAME, ARC)):
helicity, rr, length, is_thick, order = (
HELICITY[i],
RR[i],
LENGTH[i],
IS_THICK[i],
ORDER[i],
)

if name == "_end_point":
continue

element = None
if line is not None:
# Fallback to extract missing properties from line
try:
element = line.get(
name
) # required also for custom text formatting if user wants to
if not is_thick:
is_thick = element.isthick
if order < 0 or order > 100:
order = effective_order(element)
if not length:
length = get(element, "length", 0)
except (TypeError, KeyError):
pass

try:
element = line[name]
is_thick = element.isthick
if type(element).__name__ == "Replica":
name = element.resolve(line, get_name=True)
if order < 0:
order = nominal_order(element)
if not length:
length = get(element, "length", None)
except (TypeError, KeyError):
pass

# ignored elements
if drift_length > 0 and not is_thick or type(element).__name__ == "Drift":
continue # always skip drift spaces
if self.ignore is not None:
if np.any([re.match(pattern, name) is not None for pattern in self.ignore]):
continue # skip ignored
if name == "_end_point":
continue

# box
######
Expand All @@ -438,14 +455,13 @@ def ang(a):
1: "Quadrupole magnet",
2: "Sextupole magnet",
3: "Octupole magnet",
999: "Multipole magnet",
}.get(order),
)

boxes = self.boxes
if boxes is None:
boxes = line is None or order >= 0
box_style = self._get_config(boxes, name, **default_box_style)
if box_style is None and self.default_boxes and (line is None or order >= 0):
if box_style is None and self.default_boxes and order >= 0:
box_style = default_box_style

if box_style is not None:
Expand Down Expand Up @@ -506,12 +522,14 @@ def ang(a):

labels = self.labels
if labels is None:
labels = line is not None and order >= 0
labels = order >= 0
label_style = self._get_config(labels, name, text=name)

if label_style is not None:
width = label_style.pop("width", self.element_width * scale)
label_style["text"] = label_style["text"].format(name=name, element=element)
label_style["text"] = label_style["text"].format(
name=name, length=length, arc=arc, order=order, element=element
)

label = self.ax.annotate(
**defaults_for(
Expand Down