Skip to content

chemdiagrams.managers

Manager classes for EnergyDiagram

BarManager

Manages the creation and storage of energy difference bars.

Handles drawing of annotated double-headed arrows that span between two energy levels, including optional horizontal whisker lines and text labels. Rendered artists are stored in mpl_objects for later access via EnergyDiagram.bars.

Source code in src/chemdiagrams/managers/bar_manager.py
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
class BarManager:
    """
    Manages the creation and storage of energy difference bars.

    Handles drawing of annotated double-headed arrows that span between
    two energy levels, including optional horizontal whisker lines and
    text labels. Rendered artists are stored in ``mpl_objects`` for
    later access via ``EnergyDiagram.bars``.
    """

    def __init__(
        self,
        figure_manager: FigureManager,
    ) -> None:
        self.figure_manager = figure_manager
        self.mpl_objects: list = []

    def draw_difference_bar(
        self,
        x: float,
        y_start_end: tuple[float, float] | list[float],
        description: str,
        margins: dict,
        figsize: tuple[float, float],
        diff: float | None = None,
        left_side: bool = False,
        add_difference: bool = True,
        n_decimals: int = 0,
        fontsize: int | None = None,
        color: str = "black",
        arrowstyle: str = "|-|",
        x_whiskers: Sequence[float | None] = (None, None),
        whiskercolor: str | None = None,
    ) -> None:
        # Sanity checks
        Validators.validate_number(x, "x")
        Validators.validate_numeric_sequence(y_start_end, "y_start_end", required_length=2)
        Validators.validate_number(fontsize, "fontsize", allow_none=True, min_value=0)
        Validators.validate_number(diff, "diff", allow_none=True)
        Validators.validate_number(n_decimals, "n_decimals", min_value=0, only_integer=True)
        if not isinstance(x_whiskers, Sequence):
            raise TypeError("x_whiskers must be a list or tuple of length 2.")
        if len(x_whiskers) != 2:
            raise ValueError("x_whiskers must be a list or tuple of length 2.")
        if not all(isinstance(val, (float, int, type(None))) for val in x_whiskers):
            raise ValueError("Elements of x_whiskers must be a float or None.")

        y_start, y_end = y_start_end
        if fontsize is None:
            fontsize = self.figure_manager.fontsize

        # Automatic scaling of diff
        if diff is None:
            diff = constants.DISTANCE_TEXT_DIFFBAR
            diff *= margins["x"][1] - margins["x"][0]
            diff /= figsize[0]

        # Adjust diff and ha to side
        if left_side:
            diff *= -1
            horizontal_alignment = "right"
        else:
            horizontal_alignment = "left"

        # Draw vertical bar
        bar = self.figure_manager.ax.annotate(
            "",
            xy=(x, y_end),
            xytext=(x, y_start),
            arrowprops=dict(
                arrowstyle=arrowstyle,
                color=color,
                lw=0.7,
                shrinkA=0,  # no whitespace above and below the Bar
                shrinkB=0,  # no whitespace above and below the Bar
                mutation_scale=3,  # scaling of the horizontal caps
            ),
        )

        # Draw text next to bar
        if add_difference:
            difference_str = str(f"{(y_end - y_start):.{n_decimals}f}")
        else:
            difference_str = ""
        text = self.figure_manager.ax.text(
            x + diff,
            (y_start + y_end) / 2,
            description + difference_str,
            ha=horizontal_alignment,
            va="center",
            fontsize=fontsize,
            color=color,
        )

        # Draw the whiskers
        if whiskercolor is None:
            whiskercolor = color
        whisker_1 = None
        whisker_2 = None
        for i, x_whisker in enumerate(x_whiskers):
            if x_whisker is not None:
                whisker = self.figure_manager.ax.plot(
                    (x_whisker, x),
                    (y_start_end[i], y_start_end[i]),
                    zorder=constants.ZORDER_WHISKER,
                    ls=":",
                    lw=constants.LW_WHISKER,
                    color=whiskercolor,
                )[0]
                if i == 0:
                    whisker_1 = whisker
                elif i == 1:
                    whisker_2 = whisker

        # Save whiskers
        self.mpl_objects.append(DifferenceBar(bar, text, whisker_1, whisker_2))

BrokenLine dataclass

Container for the four artists that make up a broken connector line.

A broken line is drawn as two half-segments with small orthogonal tick marks at the break point, indicating a discontinuity in the reaction coordinate.

Attributes:

Name Type Description
line_part_1 Line2D or list of Line2D

The first half of the connector, from the start to the break.

line_part_2 Line2D or list of Line2D

The second half of the connector, from the break to the end.

stopper_1 Annotation

Orthogonal tick mark at the end of line_part_1.

stopper_2 Annotation

Orthogonal tick mark at the start of line_part_2.

Source code in src/chemdiagrams/managers/path_manager.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
@dataclass
class BrokenLine:
    """
    Container for the four artists that make up a broken connector line.

    A broken line is drawn as two half-segments with small orthogonal
    tick marks at the break point, indicating a discontinuity in the
    reaction coordinate.

    Attributes
    ----------
    line_part_1 : Line2D or list of Line2D
        The first half of the connector, from the start to the break.
    line_part_2 : Line2D or list of Line2D
        The second half of the connector, from the break to the end.
    stopper_1 : Annotation
        Orthogonal tick mark at the end of ``line_part_1``.
    stopper_2 : Annotation
        Orthogonal tick mark at the start of ``line_part_2``.
    """

    line_part_1: Line2D | list[Line2D]
    line_part_2: Line2D | list[Line2D]
    stopper_1: Annotation
    stopper_2: Annotation

    def remove(self):
        self.line_part_1.remove()
        self.line_part_2.remove()
        self.stopper_1.remove()
        self.stopper_2.remove()

DifferenceBar dataclass

Container for the Matplotlib artists that make up a single difference bar.

Attributes:

Name Type Description
bar Annotation

The double-headed arrow spanning the two energy levels.

text Text

The label displayed beside the arrow.

whisker_1 Line2D or None

Horizontal whisker line at the bottom energy level, or None if not drawn.

whisker_2 Line2D or None

Horizontal whisker line at the top energy level, or None if not drawn.

Source code in src/chemdiagrams/managers/bar_manager.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@dataclass
class DifferenceBar:
    """
    Container for the Matplotlib artists that make up a single difference bar.

    Attributes
    ----------
    bar : Annotation
        The double-headed arrow spanning the two energy levels.
    text : Text
        The label displayed beside the arrow.
    whisker_1 : Line2D or None
        Horizontal whisker line at the bottom energy level, or None if not drawn.
    whisker_2 : Line2D or None
        Horizontal whisker line at the top energy level, or None if not drawn.
    """

    bar: Annotation
    text: Text
    whisker_1: Line2D | None
    whisker_2: Line2D | None

DifferenceManager

Container for methods related to calculating difference values for object collision avoidance and label placement. This manager does not store any state or rendered artists, but is kept separate for organizational purposes and to avoid circular imports.

Source code in src/chemdiagrams/managers/difference_manager.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
class DifferenceManager:
    """
    Container for methods related to calculating difference values
    for object collision avoidance and label placement. This manager does not store
    any state or rendered artists, but is kept separate for organizational
    purposes and to avoid circular imports.
    """

    @staticmethod
    def _get_diff_img_plateau(
        margins: dict[str, tuple],
        figsize: tuple[float, float],
    ) -> float:
        """Compute vertical spacing value for image plateau distance in data coordinates."""
        diff_to_plateau = (
            (margins["y"][1] - margins["y"][0]) / figsize[1] * constants.DISTANCE_IMAGE_LINE
        )
        return diff_to_plateau

    @staticmethod
    def _get_diff_img_number(
        margins: dict[str, tuple], figsize: tuple[float, float], fontsize
    ) -> float:
        """Compute vertical spacing value for image number distance in data coordinates."""
        diff_to_number = (
            (fontsize / constants.STD_FONTSIZE)
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
            * constants.DISTANCE_NUMBER_LINE
        )
        return diff_to_number

    @staticmethod
    def _get_diff_img_label(
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        fontsize: int,
        labeltext: str,
    ) -> float:
        """Compute vertical spacing value for image label distance in data coordinates."""
        n_linebreaks = len(findall("\n", labeltext))
        diff_to_label = (
            (fontsize / constants.STD_FONTSIZE)
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
            * (
                constants.DISTANCE_IMAGE_LABEL
                + n_linebreaks * constants.DISTANCE_LABEL_NEWLINE
            )
        )
        return diff_to_label

    @staticmethod
    def _get_diff_plateau_label(
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        fontsize: int,
        labeltext: str,
    ) -> float:
        """Compute vertical spacing value for plateau label distance in data coordinates."""
        n_linebreaks = len(findall("\n", labeltext))
        diff_to_label = (
            (fontsize / constants.STD_FONTSIZE)
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
            * (constants.DISTANCE_LABEL_LINE + n_linebreaks * constants.DISTANCE_LABEL_NEWLINE)
        )
        return diff_to_label

    @staticmethod
    def _get_number_diffs(
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        fontsize: int,
    ) -> tuple[float, float]:
        """
        Compute vertical spacing values for label placement in data coordinates.

        Both values scale proportionally with font size, y-axis range, and
        figure height so that spacing remains visually consistent regardless
        of the diagram's scale.

        Returns
        -------
        diff_bias : float
            The vertical gap between an energy bar and the first label.
        diff_per_step : float
            The vertical distance between consecutive stacked labels.
        """
        diff_bias = (
            (fontsize / constants.STD_FONTSIZE)
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
            * constants.DISTANCE_NUMBER_LINE
        )
        diff_per_step = (
            (fontsize / constants.STD_FONTSIZE)
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
            * constants.DISTANCE_NUMBER_NUMBER
        )
        return diff_bias, diff_per_step

    @staticmethod
    def _get_axis_break_stopper_differences(
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        angle: float,
    ) -> tuple[float, float]:
        """
        Compute data coordinate differences for axis break stoppers in x and y directions.
        """
        delta_x = (
            np.cos(angle * np.pi / 180)
            * 0.001
            * (margins["x"][1] - margins["x"][0])
            / figsize[0]
        )
        delta_y = (
            np.sin(angle * np.pi / 180)
            * 0.001
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
        )
        return delta_x, delta_y

    @staticmethod
    def _get_axis_break_whitespace_cover_width(
        margins: dict[str, tuple],
        figsize: tuple[float, float],
    ) -> float:
        """Compute data coordinate width for axis break whitespace cover."""
        cover_width = (
            constants.MERGED_PLATEAU_COVER_WIDTH
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
        )
        return cover_width

FigureManager

Creates and owns the Matplotlib figure and axes used by the diagram.

Acts as the central reference point for all other managers, which access the figure and axes through this object rather than holding their own references.

Source code in src/chemdiagrams/managers/figure_manager.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class FigureManager:
    """
    Creates and owns the Matplotlib figure and axes used by the diagram.

    Acts as the central reference point for all other managers, which
    access the figure and axes through this object rather than holding
    their own references.
    """

    def __init__(
        self,
        fontsize: int = constants.STD_FONTSIZE,
        dpi: int = 150,
    ) -> None:
        """
        Initialize the Matplotlib figure and configure default tick styling.

        Parameters
        ----------
        fontsize : int, optional
            Base font size applied to axis tick labels throughout the diagram.
            Default is ``constants.STD_FONTSIZE``.
        dpi : int, optional
            Resolution of the figure in dots per inch. Default is 150.
        """

        # Sanity checks
        Validators.validate_number(fontsize, "fontsize", min_value=0)
        Validators.validate_number(dpi, "dpi", min_value=0)

        # Initialize the diagram, get the axis and set axis limits
        self.fig = plt.figure(dpi=dpi)
        self.ax = self.fig.gca()
        self.ax.tick_params(
            which="both", direction="inout", top=False, right=False, bottom=False
        )
        self.ax.tick_params(which="both", labelsize=fontsize)
        self.ax.set_xticks([])
        self.fontsize = fontsize

__init__(fontsize=constants.STD_FONTSIZE, dpi=150)

Initialize the Matplotlib figure and configure default tick styling.

Parameters:

Name Type Description Default
fontsize int

Base font size applied to axis tick labels throughout the diagram. Default is constants.STD_FONTSIZE.

STD_FONTSIZE
dpi int

Resolution of the figure in dots per inch. Default is 150.

150
Source code in src/chemdiagrams/managers/figure_manager.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def __init__(
    self,
    fontsize: int = constants.STD_FONTSIZE,
    dpi: int = 150,
) -> None:
    """
    Initialize the Matplotlib figure and configure default tick styling.

    Parameters
    ----------
    fontsize : int, optional
        Base font size applied to axis tick labels throughout the diagram.
        Default is ``constants.STD_FONTSIZE``.
    dpi : int, optional
        Resolution of the figure in dots per inch. Default is 150.
    """

    # Sanity checks
    Validators.validate_number(fontsize, "fontsize", min_value=0)
    Validators.validate_number(dpi, "dpi", min_value=0)

    # Initialize the diagram, get the axis and set axis limits
    self.fig = plt.figure(dpi=dpi)
    self.ax = self.fig.gca()
    self.ax.tick_params(
        which="both", direction="inout", top=False, right=False, bottom=False
    )
    self.ax.tick_params(which="both", labelsize=fontsize)
    self.ax.set_xticks([])
    self.fontsize = fontsize

ImageManager

Manages the placement and storage of image overlays within the energy diagram.

Supports two modes: standalone images placed at an explicit data-coordinate position, and image series where one image is placed per x-position with automatic collision avoidance against energy bars, number annotations, and x-axis labels. Series images are redrawn whenever number annotations change. All rendered artists are stored in mpl_objects for later access.

Source code in src/chemdiagrams/managers/image_manager.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
class ImageManager:
    """
    Manages the placement and storage of image overlays within the energy diagram.

    Supports two modes: standalone images placed at an explicit data-coordinate
    position, and image series where one image is placed per x-position with
    automatic collision avoidance against energy bars, number annotations, and
    x-axis labels. Series images are redrawn whenever number annotations change.
    All rendered artists are stored in ``mpl_objects`` for later access.
    """

    def __init__(
        self,
        figure_manager: FigureManager,
    ) -> None:
        self.figure_manager = figure_manager
        self.image_series_data: dict = {}
        self.has_image_series = False
        self.solo_image_data: dict = {}
        self.mpl_objects: dict = {}

    def add_image_in_plot(
        self,
        img_path: str,
        position: tuple[float, float] | list[float],
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        img_name: str | None = None,
        width: float | None = None,
        height: float | None = None,
        framed: bool = False,
        frame_color: str = "black",
        horizontal_alignment: str = "center",
        vertical_alignment: str = "center",
    ) -> None:
        # Sanity checks
        Validators.validate_numeric_sequence(position, "position", required_length=2)
        if img_name is not None:
            if not isinstance(img_name, str):
                raise TypeError("img_series_name must be a string or None.")
        Validators.validate_number(width, "width", allow_none=True, min_value=0)
        Validators.validate_number(height, "height", allow_none=True, min_value=0)
        if not isinstance(framed, bool):
            raise TypeError("framed must be a bool.")

        # Construct the image
        img_object = self._construct_image(
            img_path=img_path,
            position=position,
            margins=margins,
            figsize=figsize,
            vertical_alignment=vertical_alignment,
            horizontal_alignment=horizontal_alignment,
            width=width,
            height=height,
            framed=framed,
            frame_color=frame_color,
        )

        # Save mpl objects
        if img_name is None:
            img_name = f"__Image_{len(self.mpl_objects)}"
        self.mpl_objects[img_name] = img_object

        # Save underlying data
        self.solo_image_data[img_name] = {
            "img_name": img_name,
            "img_path": img_path,
            "position": position,
            "width": width,
            "height": height,
            "framed": framed,
            "frame_color": frame_color,
            "horizontal_alignment": horizontal_alignment,
            "vertical_alignment": vertical_alignment,
        }

    def add_image_series_in_plot(
        self,
        img_paths: Sequence[str],
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        path_data: dict,
        number_mpl_objects: dict,
        xlabel_mpl_objects: dict,
        path_mpl_objects: dict,
        img_x_places: Sequence[float] | None = None,
        y_placement: Sequence[str] | str = "auto",
        y_offsets: Sequence[float] | float = 0,
        img_series_name: str | None = None,
        width: Sequence[float | None] | float | None = None,
        height: Sequence[float | None] | float | None = None,
        framed: Sequence[bool] | bool = False,
        frame_colors: Sequence[str] | str = "black",
    ) -> None:
        # Sanity checks
        Validators.validate_string_sequence(img_paths, "img_paths")
        Validators.validate_numeric_sequence(img_x_places, "img_places", allow_none=True)

        # Sanity checks y_placement
        ALLOWED_Y_PLACEMENT = ["top", "bottom", "auto"]
        if isinstance(y_placement, (list, tuple)):
            Validators.validate_string_sequence(y_placement, "y_placement")
            if len(img_paths) != len(y_placement):
                raise ValueError(
                    "There must be the same number of images and elements in y_placement."
                )

            for value in y_placement:
                if value not in ALLOWED_Y_PLACEMENT:
                    raise ValueError(
                        f"All values of y_placement must be oneof {ALLOWED_Y_PLACEMENT}."
                    )
        else:
            if y_placement not in ALLOWED_Y_PLACEMENT:
                raise ValueError(f"y_placement must be one of {ALLOWED_Y_PLACEMENT}.")
            y_placement = [str(y_placement)] * len(img_paths)

        # Sanity checks y_offsets
        if isinstance(y_offsets, Sequence):
            Validators.validate_numeric_sequence(y_offsets, "y_offsets")
            if len(img_paths) != len(y_offsets):
                raise ValueError(
                    "There must be the same number of images and elements in y_offsets."
                )
        else:
            if not isinstance(y_offsets, (int, float)):
                raise ValueError("y_offsets must be a float.")
            y_offsets = [y_offsets] * len(img_paths)

        # Sanity checks img_series_name
        if img_series_name is not None:
            if not isinstance(img_series_name, str):
                raise TypeError("img_series_name must be a string or None.")

        # Sanity checks img_x_places
        if img_x_places is not None:
            if len(img_paths) != len(img_x_places):
                raise ValueError("There must be the same number of images and img_x_places.")
        else:
            img_x_places = list(range(len(img_paths)))

        # Sanity checks height
        if isinstance(height, Sequence):
            Validators.validate_numeric_sequence(
                height,
                "height",
                allow_none_elements=True,
            )
            if len(img_paths) != len(height):
                raise ValueError("height must have the same length as img_paths.")
        elif isinstance(height, (int, float)):
            height = [height] * len(img_paths)
        elif height is None:
            height = [None] * len(img_paths)
        else:
            raise TypeError("height must be a Sequence, numeric value or None.")

        # Sanity checks width
        if isinstance(width, Sequence):
            Validators.validate_numeric_sequence(
                width,
                "width",
                allow_none_elements=True,
            )
            if len(img_paths) != len(width):
                raise ValueError("width must have the same length as img_paths.")
        elif isinstance(width, (int, float)):
            width = [width] * len(img_paths)
        elif width is None:
            # Only set width to default if no height value for same image
            width = [constants.IMAGE_WIDTH if value is None else None for value in height]
        else:
            raise TypeError("width must be a Sequence, numeric value or None.")

        # Sanity checks framed
        if isinstance(framed, (list, tuple)):
            if any([not isinstance(entry, bool) for entry in framed]):
                raise TypeError("Elements in framed must be a bool.")
            if len(framed) != len(height):
                raise ValueError("framed must have the same length as img_paths.")
        elif isinstance(framed, bool):
            framed = [framed] * len(img_paths)
        else:
            raise TypeError("framed must be a Sequence of bools, or a bool.")

        # Sanity checks frame colors
        if isinstance(frame_colors, (list, tuple)):
            if len(img_paths) != len(frame_colors):
                raise ValueError("frame_colors must have the same length as img_paths.")
        elif isinstance(frame_colors, str):
            frame_colors = [frame_colors] * len(img_paths)
        else:
            raise TypeError("frame_colors must be a Sequence, or a string")

        self.has_image_series = True
        # Print the image for each x
        series_mpl_objects = {}
        for index in range(len(img_paths)):
            x = img_x_places[index]

            # Avoid collision with plateaus
            diff_to_plateau = DifferenceManager._get_diff_img_plateau(margins, figsize)
            all_values_at_x = NumberManager._get_all_values_at_x(path_data, x)
            if all_values_at_x:
                y_min_top = max(all_values_at_x) + diff_to_plateau
                y_max_bottom = min(all_values_at_x) - diff_to_plateau
            else:
                print(f"Warning: No plateaus at x = {x}. Placing image at y = 0.")
                y_min_top = 0
                y_max_bottom = 0

            # Avoid collision with numbers
            for _, numbers in number_mpl_objects.items():
                try:
                    number_fontsize = numbers[f"{x:.1f}"].get_fontsize()
                    number_y = numbers[f"{x:.1f}"].get_position()[1]
                    diff_to_number = DifferenceManager._get_diff_img_number(
                        margins, figsize, number_fontsize
                    )
                    if number_y + diff_to_number > y_min_top:
                        y_min_top = number_y + diff_to_number
                    if number_y - diff_to_number < y_max_bottom:
                        y_max_bottom = number_y - diff_to_number
                except KeyError:
                    pass

            # Avoid collision with x-labels
            try:
                label_fontsize = xlabel_mpl_objects[f"{x:.1f}"].get_fontsize()
                label_y = xlabel_mpl_objects[f"{x:.1f}"].get_position()[1]
                labeltext = xlabel_mpl_objects[f"{x:.1f}"].get_text()
                diff_to_label = DifferenceManager._get_diff_img_label(
                    margins, figsize, label_fontsize, labeltext
                )
                if label_y + diff_to_label > y_min_top:
                    y_min_top = label_y + diff_to_label
                if label_y - diff_to_label < y_max_bottom:
                    y_max_bottom = label_y - diff_to_label
            except KeyError:
                pass

            # Avoid collision with path labels
            for _, paths_obj in path_mpl_objects.items():
                try:
                    label_fontsize = paths_obj.labels[f"{x:.1f}"].get_fontsize()
                    label_y = paths_obj.labels[f"{x:.1f}"].get_position()[1]
                    labeltext = paths_obj.labels[f"{x:.1f}"].get_text()
                    diff_to_label = DifferenceManager._get_diff_img_label(
                        margins, figsize, label_fontsize, labeltext
                    )
                    if label_y + diff_to_label > y_min_top:
                        y_min_top = label_y + diff_to_label
                    if label_y - diff_to_label < y_max_bottom:
                        y_max_bottom = label_y - diff_to_label
                except KeyError:
                    pass

            # Determine current vertival alignment and position
            if y_placement[index] == "auto":
                space_on_top = margins["y"][1] - y_min_top
                space_on_bottom = y_max_bottom - margins["y"][0]
                if space_on_top > space_on_bottom:
                    vertical_alignment_current = "bottom"
                    position_current = (x, y_min_top + y_offsets[index])
                else:
                    vertical_alignment_current = "top"
                    position_current = (x, y_max_bottom - y_offsets[index])
            elif y_placement[index] == "top":
                vertical_alignment_current = "bottom"
                position_current = (x, y_min_top + y_offsets[index])
            elif y_placement[index] == "bottom":
                vertical_alignment_current = "top"
                position_current = (x, y_max_bottom - y_offsets[index])

            # Construct the image
            img_object = self._construct_image(
                img_path=img_paths[index],
                position=position_current,
                margins=margins,
                figsize=figsize,
                vertical_alignment=vertical_alignment_current,
                width=width[index],
                height=height[index],
                framed=framed[index],
                frame_color=frame_colors[index],
            )

            series_mpl_objects[f"{x:.1f}"] = img_object

        # Save mpl objects
        if img_series_name is None:
            img_series_name = f"__Series_{len(self.mpl_objects)}"
        self.mpl_objects[img_series_name] = series_mpl_objects

        # Save underlying data if redrawing is neccesary
        self.image_series_data[img_series_name] = {
            "img_series_name": img_series_name,
            "img_paths": img_paths,
            "img_x_places": img_x_places,
            "y_placement": y_placement,
            "y_offsets": y_offsets,
            "width": width,
            "height": height,
            "framed": framed,
            "frame_colors": frame_colors,
        }

    def recalculate_image_series(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        path_data: dict,
        number_mpl_objects: dict,
        xlabel_mpl_objects: dict,
        path_mpl_objects: dict,
    ) -> None:
        # Series images are removed and redrawn; standalone images are permanent
        self._remove_image_series()
        for _, image_series in self.image_series_data.items():
            self.add_image_series_in_plot(
                margins=margins,
                figsize=figsize,
                path_data=path_data,
                number_mpl_objects=number_mpl_objects,
                xlabel_mpl_objects=xlabel_mpl_objects,
                path_mpl_objects=path_mpl_objects,
                **image_series,
            )

    ############################################################
    # Internal helper methods
    ############################################################

    def _remove_image_series(self) -> None:
        for _, series in self.mpl_objects.items():
            if isinstance(series, dict):
                for __, image in series.items():
                    image.remove()

    def _construct_image(
        self,
        img_path: str,
        position: tuple[float, float] | list[float],
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        vertical_alignment: str = "bottom",
        horizontal_alignment: str = "center",
        width: float | None = None,
        height: float | None = None,
        framed: bool = False,
        frame_color: str = "black",
    ) -> ImageObject:
        def draw_frame_part(x_coords, y_coords):
            return self.figure_manager.ax.plot(
                x_coords,
                y_coords,
                zorder=constants.ZORDER_IMAGE_FRAME,
                ls="-",
                lw=constants.LW_IMAGE_FRAME,
                color=frame_color,
            )[0]

        # Sanity checks
        Validators.validate_numeric_sequence(position, "position", required_length=2)
        Validators.validate_number(width, "width", allow_none=True, min_value=0)
        Validators.validate_number(height, "height", allow_none=True, min_value=0)

        ALLOWED_VA_VALUES = ["top", "bottom", "center"]
        if vertical_alignment not in ALLOWED_VA_VALUES:
            raise ValueError(f"vertical_alignment must be in {ALLOWED_VA_VALUES}.")
        ALLOWED_HA_VALUES = ["left", "center", "right"]
        if horizontal_alignment not in ALLOWED_HA_VALUES:
            raise ValueError(f"horizontal alignment must be in {ALLOWED_HA_VALUES}")

        # Read and scale image
        img_file = mpimg.imread(img_path)
        positimg_height_px = img_file.shape[0]
        img_width_px = img_file.shape[1]
        if width is None and height is None:
            width = constants.IMAGE_WIDTH
            height = (
                width
                * positimg_height_px
                / img_width_px
                * (margins["y"][1] - margins["y"][0])
                / (margins["x"][1] - margins["x"][0])
                * figsize[0]
                / figsize[1]
            )
        elif width is None:
            width = (
                height
                * img_width_px
                / positimg_height_px
                / (margins["y"][1] - margins["y"][0])
                * (margins["x"][1] - margins["x"][0])
                / figsize[0]
                * figsize[1]
            )
        elif height is None:
            height = (
                width
                * positimg_height_px
                / img_width_px
                * (margins["y"][1] - margins["y"][0])
                / (margins["x"][1] - margins["x"][0])
                * figsize[0]
                / figsize[1]
            )

        assert width is not None
        assert height is not None

        if horizontal_alignment == "center":
            img_x_extent = (
                position[0] - width / 2,
                position[0] + width / 2,
            )
        elif horizontal_alignment == "left":
            img_x_extent = (
                position[0],
                position[0] + width,
            )
        elif horizontal_alignment == "right":
            img_x_extent = (
                position[0] - width,
                position[0],
            )

        if vertical_alignment == "bottom":
            img_y_extent = (
                position[1],
                position[1] + height,
            )
        elif vertical_alignment == "top":
            img_y_extent = (
                position[1] - height,
                position[1],
            )
        elif vertical_alignment == "center":
            img_y_extent = (
                position[1] - height / 2,
                position[1] + height / 2,
            )

        img_extent = img_x_extent + img_y_extent

        # Draw image
        img_artist = self.figure_manager.ax.imshow(
            img_file,
            extent=img_extent,
            interpolation="bilinear",  # nearest/bilinear/bicubic (nearest ugly)
            aspect="auto",
        )

        # Draw borders
        border_objects = {}
        if framed:
            border_objects["top"] = draw_frame_part(
                (img_extent[0], img_extent[1]), (img_extent[3], img_extent[3])
            )
            border_objects["bottom"] = draw_frame_part(
                (img_extent[0], img_extent[1]), (img_extent[2], img_extent[2])
            )
            border_objects["left"] = draw_frame_part(
                (img_extent[0], img_extent[0]), (img_extent[2], img_extent[3])
            )
            border_objects["right"] = draw_frame_part(
                (img_extent[1], img_extent[1]), (img_extent[2], img_extent[3])
            )
        return ImageObject(img_artist, border_objects)

LayoutManager

Manages axis limits and figure dimensions based on the plotted path data.

Computes appropriate x/y axis limits from the data range plus configured margins, and scales the figure size automatically unless an explicit size was provided.

Source code in src/chemdiagrams/managers/layout_manager.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
class LayoutManager:
    """
    Manages axis limits and figure dimensions based on the plotted path data.

    Computes appropriate x/y axis limits from the data range plus configured
    margins, and scales the figure size automatically unless an explicit size
    was provided.
    """

    def __init__(
        self,
        figure_manager: FigureManager,
        extra_x_margin: tuple[float, float] | list[float],
        extra_y_margin: tuple[float, float] | list[float],
        width_limit: float | None = None,
        figsize: tuple[float, float] | list[float] | None = None,
    ) -> None:
        Validators.validate_numeric_sequence(
            figsize, "figsize", allow_none=True, min_value=0, required_length=2
        )
        Validators.validate_numeric_sequence(
            extra_x_margin, "extra_x_margin", required_length=2
        )
        Validators.validate_numeric_sequence(
            extra_y_margin, "extra_y_margin", required_length=2
        )
        Validators.validate_number(width_limit, "width_limit", min_value=0, allow_none=True)

        self.figure_manager = figure_manager
        self.figsize = figsize
        self.extra_x_margin = extra_x_margin
        self.extra_y_margin = extra_y_margin
        self.width_limit = width_limit

    def adjust_xy_limits(self, path_data: dict) -> dict[str, tuple]:
        """
        Recompute and apply x/y axis limits from the current path data.

        Called before rendering any element that depends on the data range,
        such as difference bars and labels. Returns a margins dict that other
        managers use to scale positions relative to the plot extents.

        Parameters
        ----------
        path_data : dict
            The path registry from ``PathManager.path_data``.

        Returns
        -------
        dict
            A dict with keys ``"x"`` and ``"y"``, each a tuple of
            ``(lower_limit, upper_limit)`` in data coordinates, after
            applying default and user-specified margins.
        """
        # Get all x and y values out of the path data dictionary
        x_all = [
            element
            for path in path_data.values()
            if path and len(path) > 0
            for element in path["x"]
        ]
        y_all = [
            element
            for path in path_data.values()
            if path and len(path) > 0
            for element in path["y"]
        ]
        # Add values if no path was added yet to avoid errors
        if len(x_all) == 0:
            x_all = [0]
        if len(y_all) == 0:
            y_all = [0, 10]

        # Adjust the axis limits
        margins = {
            "x": (
                min(x_all) + constants.DEFAULT_X_MARGINS[0] + self.extra_x_margin[0],
                max(x_all) + constants.DEFAULT_X_MARGINS[1] + self.extra_x_margin[1],
            ),
            "y": (
                min(y_all)
                + (max(y_all) - min(y_all))
                * (constants.DEFAULT_Y_MARGINS[0] + self.extra_y_margin[0]),
                max(y_all)
                + (max(y_all) - min(y_all))
                * (constants.DEFAULT_Y_MARGINS[1] + self.extra_y_margin[1]),
            ),
        }
        self.figure_manager.ax.set_xlim(margins["x"])
        self.figure_manager.ax.set_ylim(margins["y"])

        return margins

    def scale_figure(self, path_data: dict) -> tuple[float, float]:
        """
        Resize the figure to fit the current data range.

        If a fixed ``figsize`` was provided at construction, that size is
        applied directly. Otherwise, width is derived from the x data range
        and capped at ``width_limit`` (unless ``width_limit`` is
        None), and height is set to ``constants.HEIGHT`` or the width,
        whichever is smaller, to avoid disproportionate figures.

        Parameters
        ----------
        path_data : dict
            The path registry from ``PathManager.path_data``.

        Returns
        -------
        tuple of float
            The resulting figure size as ``(width, height)`` in inches.
        """
        # Scale only, if no figure size is predetermined
        if self.figsize is None:
            # Function for scaling the figure automatically
            margins = self.adjust_xy_limits(path_data)

            # Determine and set width
            x_size = constants.X_SCALE * (margins["x"][1] - margins["x"][0])
            if self.width_limit is not None and x_size > self.width_limit:
                x_size = self.width_limit
            if x_size <= 0:  # Avoid a figure without size
                x_size = 1
            self.figure_manager.fig.set_figwidth(x_size)

            # Determine and set height
            y_size = constants.FIG_HEIGHT
            if y_size > x_size:
                y_size = x_size  # Avoid ugly diagrams
            self.figure_manager.fig.set_figheight(y_size)
            return (x_size, y_size)

        else:
            self.adjust_xy_limits(path_data)
            self.figure_manager.fig.set_figwidth(self.figsize[0])
            self.figure_manager.fig.set_figheight(self.figsize[1])
            return (self.figsize[0], self.figsize[1])

adjust_xy_limits(path_data)

Recompute and apply x/y axis limits from the current path data.

Called before rendering any element that depends on the data range, such as difference bars and labels. Returns a margins dict that other managers use to scale positions relative to the plot extents.

Parameters:

Name Type Description Default
path_data dict

The path registry from PathManager.path_data.

required

Returns:

Type Description
dict

A dict with keys "x" and "y", each a tuple of (lower_limit, upper_limit) in data coordinates, after applying default and user-specified margins.

Source code in src/chemdiagrams/managers/layout_manager.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def adjust_xy_limits(self, path_data: dict) -> dict[str, tuple]:
    """
    Recompute and apply x/y axis limits from the current path data.

    Called before rendering any element that depends on the data range,
    such as difference bars and labels. Returns a margins dict that other
    managers use to scale positions relative to the plot extents.

    Parameters
    ----------
    path_data : dict
        The path registry from ``PathManager.path_data``.

    Returns
    -------
    dict
        A dict with keys ``"x"`` and ``"y"``, each a tuple of
        ``(lower_limit, upper_limit)`` in data coordinates, after
        applying default and user-specified margins.
    """
    # Get all x and y values out of the path data dictionary
    x_all = [
        element
        for path in path_data.values()
        if path and len(path) > 0
        for element in path["x"]
    ]
    y_all = [
        element
        for path in path_data.values()
        if path and len(path) > 0
        for element in path["y"]
    ]
    # Add values if no path was added yet to avoid errors
    if len(x_all) == 0:
        x_all = [0]
    if len(y_all) == 0:
        y_all = [0, 10]

    # Adjust the axis limits
    margins = {
        "x": (
            min(x_all) + constants.DEFAULT_X_MARGINS[0] + self.extra_x_margin[0],
            max(x_all) + constants.DEFAULT_X_MARGINS[1] + self.extra_x_margin[1],
        ),
        "y": (
            min(y_all)
            + (max(y_all) - min(y_all))
            * (constants.DEFAULT_Y_MARGINS[0] + self.extra_y_margin[0]),
            max(y_all)
            + (max(y_all) - min(y_all))
            * (constants.DEFAULT_Y_MARGINS[1] + self.extra_y_margin[1]),
        ),
    }
    self.figure_manager.ax.set_xlim(margins["x"])
    self.figure_manager.ax.set_ylim(margins["y"])

    return margins

scale_figure(path_data)

Resize the figure to fit the current data range.

If a fixed figsize was provided at construction, that size is applied directly. Otherwise, width is derived from the x data range and capped at width_limit (unless width_limit is None), and height is set to constants.HEIGHT or the width, whichever is smaller, to avoid disproportionate figures.

Parameters:

Name Type Description Default
path_data dict

The path registry from PathManager.path_data.

required

Returns:

Type Description
tuple of float

The resulting figure size as (width, height) in inches.

Source code in src/chemdiagrams/managers/layout_manager.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def scale_figure(self, path_data: dict) -> tuple[float, float]:
    """
    Resize the figure to fit the current data range.

    If a fixed ``figsize`` was provided at construction, that size is
    applied directly. Otherwise, width is derived from the x data range
    and capped at ``width_limit`` (unless ``width_limit`` is
    None), and height is set to ``constants.HEIGHT`` or the width,
    whichever is smaller, to avoid disproportionate figures.

    Parameters
    ----------
    path_data : dict
        The path registry from ``PathManager.path_data``.

    Returns
    -------
    tuple of float
        The resulting figure size as ``(width, height)`` in inches.
    """
    # Scale only, if no figure size is predetermined
    if self.figsize is None:
        # Function for scaling the figure automatically
        margins = self.adjust_xy_limits(path_data)

        # Determine and set width
        x_size = constants.X_SCALE * (margins["x"][1] - margins["x"][0])
        if self.width_limit is not None and x_size > self.width_limit:
            x_size = self.width_limit
        if x_size <= 0:  # Avoid a figure without size
            x_size = 1
        self.figure_manager.fig.set_figwidth(x_size)

        # Determine and set height
        y_size = constants.FIG_HEIGHT
        if y_size > x_size:
            y_size = x_size  # Avoid ugly diagrams
        self.figure_manager.fig.set_figheight(y_size)
        return (x_size, y_size)

    else:
        self.adjust_xy_limits(path_data)
        self.figure_manager.fig.set_figwidth(self.figsize[0])
        self.figure_manager.fig.set_figheight(self.figsize[1])
        return (self.figsize[0], self.figsize[1])

MergedPlateau dataclass

Source code in src/chemdiagrams/managers/path_manager.py
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
@dataclass
class MergedPlateau:
    plateau_left: LineCollection
    plateau_right: LineCollection
    stopper_left: Annotation
    stopper_right: Annotation
    whitespace: Rectangle
    """
    Container for the Matplotlib artists that make up a merged plateau pair.

    Holds the two shortened half-plateau lines, the diagonal stopper tick
    marks drawn in the gap between them, and the white rectangle that
    covers the original overlapping plateau segments.

    Attributes
    ----------
    plateau_left : LineCollection
        The left half-plateau artist, ending at the left edge of the gap.
    plateau_right : LineCollection
        The right half-plateau artist, starting at the right edge of the gap.
    stopper_left : Annotation
        Diagonal tick mark at the right end of ``plateau_left``.
    stopper_right : Annotation
        Diagonal tick mark at the left end of ``plateau_right``.
    whitespace : Rectangle
        White rectangle covering the gap between the two half-plateaus,
        used to hide any underlying plateau or connector artifacts.
    """

    def remove(self):
        self.plateau_left.remove()
        self.plateau_right.remove()
        self.stopper_left.remove()
        self.stopper_right.remove()
        self.whitespace.remove()

    def recalculate_gap(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        angle: float,
    ) -> None:
        """Recompute stopper positions and whitespace height after a layout change.

        Called whenever the figure size or axis margins are updated (e.g. after
        a new path is added) to keep the stopper tick marks and covering rectangle
        correctly sized in display coordinates.

        Parameters
        ----------
        margins : dict of str to tuple
            Current axis margin data as returned by ``LayoutManager.adjust_xy_limits``.
        figsize : tuple of float
            Current figure size in inches as ``(width, height)``.
        angle : float
            Angle of the stopper tick marks in degrees from the vertical,
            as originally passed to ``merge_plateaus``.
        """
        delta_x, delta_y = DifferenceManager._get_axis_break_stopper_differences(
            margins,
            figsize,
            angle,
        )
        x_left, y_left = self.stopper_left.xy
        x_right, y_right = self.stopper_right.xy
        self.stopper_left.set_position((x_left + delta_x, y_left + delta_y))
        self.stopper_right.set_position((x_right - delta_x, y_right - delta_y))
        cover_width = DifferenceManager._get_axis_break_whitespace_cover_width(
            margins, figsize
        )
        self.whitespace.set_height(cover_width)
        y_whitespace = self.whitespace.get_y()
        self.whitespace.set_y(y_whitespace - cover_width / 2)

whitespace instance-attribute

Container for the Matplotlib artists that make up a merged plateau pair.

Holds the two shortened half-plateau lines, the diagonal stopper tick marks drawn in the gap between them, and the white rectangle that covers the original overlapping plateau segments.

Attributes:

Name Type Description
plateau_left LineCollection

The left half-plateau artist, ending at the left edge of the gap.

plateau_right LineCollection

The right half-plateau artist, starting at the right edge of the gap.

stopper_left Annotation

Diagonal tick mark at the right end of plateau_left.

stopper_right Annotation

Diagonal tick mark at the left end of plateau_right.

whitespace Rectangle

White rectangle covering the gap between the two half-plateaus, used to hide any underlying plateau or connector artifacts.

recalculate_gap(margins, figsize, angle)

Recompute stopper positions and whitespace height after a layout change.

Called whenever the figure size or axis margins are updated (e.g. after a new path is added) to keep the stopper tick marks and covering rectangle correctly sized in display coordinates.

Parameters:

Name Type Description Default
margins dict of str to tuple

Current axis margin data as returned by LayoutManager.adjust_xy_limits.

required
figsize tuple of float

Current figure size in inches as (width, height).

required
angle float

Angle of the stopper tick marks in degrees from the vertical, as originally passed to merge_plateaus.

required
Source code in src/chemdiagrams/managers/path_manager.py
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
def recalculate_gap(
    self,
    margins: dict[str, tuple],
    figsize: tuple[float, float],
    angle: float,
) -> None:
    """Recompute stopper positions and whitespace height after a layout change.

    Called whenever the figure size or axis margins are updated (e.g. after
    a new path is added) to keep the stopper tick marks and covering rectangle
    correctly sized in display coordinates.

    Parameters
    ----------
    margins : dict of str to tuple
        Current axis margin data as returned by ``LayoutManager.adjust_xy_limits``.
    figsize : tuple of float
        Current figure size in inches as ``(width, height)``.
    angle : float
        Angle of the stopper tick marks in degrees from the vertical,
        as originally passed to ``merge_plateaus``.
    """
    delta_x, delta_y = DifferenceManager._get_axis_break_stopper_differences(
        margins,
        figsize,
        angle,
    )
    x_left, y_left = self.stopper_left.xy
    x_right, y_right = self.stopper_right.xy
    self.stopper_left.set_position((x_left + delta_x, y_left + delta_y))
    self.stopper_right.set_position((x_right - delta_x, y_right - delta_y))
    cover_width = DifferenceManager._get_axis_break_whitespace_cover_width(
        margins, figsize
    )
    self.whitespace.set_height(cover_width)
    y_whitespace = self.whitespace.get_y()
    self.whitespace.set_y(y_whitespace - cover_width / 2)

NumberManager

Manages energy value annotations on the diagram.

Provides four strategies for placing numeric labels above energy levels: naive (directly above each bar), stacked (vertically arranged), auto (distribution without collision), and average (one label per x-position showing the mean across paths). Rendered Text artists are stored in mpl_objects keyed by path name and x-coordinate.

Source code in src/chemdiagrams/managers/number_manager.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
class NumberManager:
    """
    Manages energy value annotations on the diagram.

    Provides four strategies for placing numeric labels above energy
    levels: naive (directly above each bar), stacked (vertically
    arranged), auto (distribution without collision), and average
    (one label per x-position showing the mean across paths).
    Rendered Text artists are stored in ``mpl_objects`` keyed by
    path name and x-coordinate.
    """

    def __init__(
        self,
        figure_manager: FigureManager,
    ) -> None:
        self.figure_manager = figure_manager
        self.mpl_objects: dict[str, dict] = {}
        self.numberings_added: list[dict] = []

    ############################################################
    # Main numbering methods
    ############################################################

    def add_numbers_naive(
        self,
        path_data: dict,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        x_min_max: tuple[float, float] | list[float] | float | None = None,
        fontsize: int | None = None,
        n_decimals: int = 0,
    ) -> None:
        # Regularize x_min_max, fontsize and get all the numbers to plot
        x_min_max = NumberManager._regularize_x_min_max(x_min_max)
        values_to_print = NumberManager._get_all_visible_numbers(path_data, x_min_max)
        Validators.validate_number(fontsize, "fontsize", min_value=0, allow_none=True)
        Validators.validate_number(n_decimals, "n_decimals", min_value=0, only_integer=True)
        if fontsize is None:
            fontsize = self.figure_manager.fontsize

        # Plot the numbers
        for value_series in values_to_print:
            for i in range(len(value_series["x"])):
                number_to_print = [
                    {
                        "y": value_series["y"][i],
                        "color": value_series["color"],
                        "name": value_series["name"],
                    }
                ]
                self._print_stacked(
                    value_series["x"][i],
                    number_to_print,
                    value_series["y"][i],
                    margins,
                    figsize,
                    fontsize,
                    n_decimals,
                )
        self.numberings_added.append(
            {
                "type": self.add_numbers_naive,
                "x_min_max": x_min_max,
                "fontsize": fontsize,
            }
        )

    def add_numbers_stacked(
        self,
        path_data: dict,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        path_mpl_objects: dict,
        x_min_max: tuple[float, float] | list[float] | float | None = None,
        fontsize: int | None = None,
        sort_by_energy: bool = True,
        no_overlap_with_nonnumbered: bool = True,
        n_decimals: int = 0,
    ) -> None:
        # Regularize x_min_max, fontsize and get all the numbers to plot
        x_min_max = NumberManager._regularize_x_min_max(x_min_max)
        values_to_print = NumberManager._get_all_visible_numbers(path_data, x_min_max)
        Validators.validate_number(fontsize, "fontsize", min_value=0, allow_none=True)
        Validators.validate_number(n_decimals, "n_decimals", min_value=0, only_integer=True)
        if fontsize is None:
            fontsize = self.figure_manager.fontsize

        # Get a list of all x values where to print
        x_places: list | np.ndarray = []
        for value_series in values_to_print:
            x_places = np.concatenate((x_places, np.array(value_series["x"])))
        x_places = np.unique(x_places)

        # For every step, get all energies, assign the colors and sort by energy
        # If sortenergy is True then print the numbers
        for x_current in x_places:
            numbers_to_stack = NumberManager._get_numbers_to_stack_at_x(
                values_to_print, x_current, sort_by_energy=sort_by_energy
            )

            # Find y where to print
            y_print_start = max(num["y"] for num in numbers_to_stack)
            if no_overlap_with_nonnumbered:
                all_numbers_at_x = NumberManager._get_all_values_at_x(path_data, x_current)
                higher_numbers_at_x = [val for val in all_numbers_at_x if val > y_print_start]
                while True:
                    no_overlap = NumberManager._check_no_overlap(
                        y_print_start,
                        numbers_to_stack,
                        higher_numbers_at_x,
                        margins,
                        figsize,
                        fontsize,
                        path_mpl_objects,
                        x_current,
                    )
                    if no_overlap:
                        break
                    if not higher_numbers_at_x:
                        print(f"Warning: Could not accurately place numbers at x={x_current}")
                        break
                    else:
                        y_print_start = higher_numbers_at_x[0]
                        higher_numbers_at_x = higher_numbers_at_x[1:]

            # Print the numbers
            self._print_stacked(
                x_current,
                numbers_to_stack,
                y_print_start,
                margins,
                figsize,
                fontsize,
                n_decimals,
            )
        self.numberings_added.append(
            {
                "type": self.add_numbers_stacked,
                "x_min_max": x_min_max,
                "fontsize": fontsize,
                "sort_by_energy": sort_by_energy,
                "no_overlap_with_nonnumbered": no_overlap_with_nonnumbered,
            }
        )

    def add_numbers_auto(
        self,
        path_data: dict,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        path_mpl_objects: dict,
        x_min_max: tuple[float, float] | list[float] | float | None = None,
        fontsize: int | None = None,
        n_decimals: int = 0,
    ) -> None:
        # Regularize x_min_max, fontsize and get all the numbers to plot
        Validators.validate_number(fontsize, "fontsize", min_value=0, allow_none=True)
        Validators.validate_number(n_decimals, "n_decimals", min_value=0, only_integer=True)
        if fontsize is None:
            fontsize = self.figure_manager.fontsize
        x_min_max = NumberManager._regularize_x_min_max(x_min_max)
        values_to_print = NumberManager._get_all_visible_numbers(path_data, x_min_max)
        _, diff_per_step = DifferenceManager._get_number_diffs(margins, figsize, fontsize)

        # Get a list of all x values where to print
        x_places: list | np.ndarray = []
        for value_series in values_to_print:
            x_places = np.concatenate((x_places, np.array(value_series["x"])))
        x_places = np.unique(x_places)

        # For every step, get all energies, assign the colors and sort by energy
        for x_current in x_places:
            numbers_to_stack = NumberManager._get_numbers_to_stack_at_x(
                values_to_print, x_current
            )
            # Start with lowest to print
            n_numbers_printed = 0
            y_last_printed = -np.inf
            all_numbers_at_x = NumberManager._get_all_values_at_x(path_data, x_current)
            while n_numbers_printed < len(numbers_to_stack):
                # Append to temporary list one number after each other
                numbers_to_stack_current = []
                numbers_to_stack_current.append(numbers_to_stack[n_numbers_printed])
                # Calulate where to try to print
                y_print_start = max(
                    numbers_to_stack[n_numbers_printed]["y"],
                    y_last_printed + diff_per_step,
                )
                # Append more numbers, if they have the same value
                start_index = len(numbers_to_stack_current) + n_numbers_printed
                numbers_to_check = numbers_to_stack[start_index:]
                for number in numbers_to_check:
                    if y_print_start >= number["y"]:
                        numbers_to_stack_current.append(number)
                # Determine every value greater than where to print
                higher_numbers_at_x = [val for val in all_numbers_at_x if val > y_print_start]
                # Increse print height, until no overlap
                while True:
                    no_overlap = NumberManager._check_no_overlap(
                        y_print_start,
                        numbers_to_stack_current,
                        higher_numbers_at_x,
                        margins,
                        figsize,
                        fontsize,
                        path_mpl_objects,
                        x_current,
                    )
                    if no_overlap or not higher_numbers_at_x:
                        if not no_overlap:
                            print(
                                f"Warning: Could not accurately place numbers at x={x_current}"
                            )
                        self._print_stacked(
                            x_current,
                            numbers_to_stack_current,
                            y_print_start,
                            margins,
                            figsize,
                            fontsize,
                            n_decimals,
                        )
                        y_last_printed = (
                            y_print_start + (len(numbers_to_stack_current) - 1) * diff_per_step
                        )
                        n_numbers_printed += len(numbers_to_stack_current)
                        break
                    else:
                        # Get next possible print height
                        y_print_start = higher_numbers_at_x[0]
                        # Append all numbers if they are on the print height
                        start_index = len(numbers_to_stack_current) + n_numbers_printed
                        numbers_to_check = numbers_to_stack[start_index:]
                        for number in numbers_to_check:
                            if y_print_start >= number["y"]:
                                numbers_to_stack_current.append(number)
                        # Determine new values above
                        higher_numbers_at_x = [
                            val for val in all_numbers_at_x if val > y_print_start
                        ]
        self.numberings_added.append(
            {
                "type": self.add_numbers_auto,
                "x_min_max": x_min_max,
                "fontsize": fontsize,
            }
        )

    def add_numbers_average(
        self,
        path_data: dict,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        x_min_max: tuple[float, float] | list[float] | float | None = None,
        fontsize: int | None = None,
        color: str = "black",
        n_decimals: int = 0,
    ) -> None:
        # Regularize x_min_max, fontsize and get all the numbers to plot
        x_min_max = NumberManager._regularize_x_min_max(x_min_max)
        values_to_print = NumberManager._get_all_visible_numbers(path_data, x_min_max)
        Validators.validate_number(fontsize, "fontsize", min_value=0, allow_none=True)
        Validators.validate_number(n_decimals, "n_decimals", min_value=0, only_integer=True)
        if fontsize is None:
            fontsize = self.figure_manager.fontsize

        # Get a list of all x values where to print
        x_places: list | np.ndarray = []
        for value_series in values_to_print:
            x_places = np.concatenate((x_places, np.array(value_series["x"])))
        x_places = np.unique(x_places)

        # For every step, get all y values, average and print
        for x_current in x_places:
            numbers_to_stack = NumberManager._get_numbers_to_stack_at_x(
                values_to_print, x_current
            )
            numbers_to_stack_y = np.array([number["y"] for number in numbers_to_stack])
            y_avg = numbers_to_stack_y.mean()
            number_to_print = [
                {
                    "y": y_avg,
                    "color": color,
                    "name": "Average",
                }
            ]
            self._print_stacked(
                x_current,
                number_to_print,
                numbers_to_stack_y.max(),
                margins,
                figsize,
                fontsize,
                n_decimals,
            )
        self.numberings_added.append(
            {
                "type": self.add_numbers_average,
                "x_min_max": x_min_max,
                "fontsize": fontsize,
                "color": color,
            }
        )

    def _recalculate_numbers(
        self,
        path_data: dict,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        path_mpl_objects: dict,
    ) -> None:
        # Remove all numbers from the plot
        for path_numbers in self.mpl_objects.values():
            for number in path_numbers.values():
                number.remove()
        self.mpl_objects = {}
        # Recalculate all numbers that have been added
        old_numberings = self.numberings_added.copy()
        self.numberings_added = []
        for numbering in old_numberings:
            settings = numbering.copy()
            del settings["type"]
            need_path_mpl_objects = numbering["type"] in [
                self.add_numbers_stacked,
                self.add_numbers_auto,
            ]
            if need_path_mpl_objects:
                settings["path_mpl_objects"] = path_mpl_objects
            numbering["type"](
                path_data=path_data,
                margins=margins,
                figsize=figsize,
                **settings,
            )

    def modify_number_values(
        self,
        path_data: dict,
        x: float,
        base_value: float = 0.0,
        x_add: float | list[float] | None = None,
        x_subtract: float | list[float] | None = None,
        include_paths: list[str] | None = None,
        exclude_paths: list[str] | None = None,
        brackets: tuple[str, str] | list[str] | None = ("(", ")"),
        n_decimals: int = 0,
    ) -> None:
        # Sanity checks
        Validators.validate_number(x, "x")
        Validators.validate_number(base_value, "base_value")
        if x_add is not None:
            if isinstance(x_add, (int, float)):
                x_add = [x_add]
        Validators.validate_numeric_sequence(x_add, "x_add", allow_none=True)
        if x_subtract is not None:
            if isinstance(x_subtract, (int, float)):
                x_subtract = [x_subtract]
        Validators.validate_numeric_sequence(x_subtract, "x_subtract", allow_none=True)
        Validators.validate_string_sequence(include_paths, "include_paths", allow_none=True)
        Validators.validate_string_sequence(exclude_paths, "exclude_paths", allow_none=True)
        if brackets is None:
            brackets = ("", "")
        Validators.validate_string_sequence(brackets, "brackets", required_length=2)
        Validators.validate_number(n_decimals, "n_decimals", min_value=0, only_integer=True)
        if include_paths is not None and exclude_paths is not None:
            raise ValueError("Cannot specify both include_paths and exclude_paths.")

        # Get all paths that should be modified
        if include_paths is not None:
            path_names_to_modify = set(include_paths)
        elif exclude_paths is not None:
            path_names_to_modify = set(path_data.keys()) - set(exclude_paths)
        else:
            path_names_to_modify = set(path_data.keys())

        # For each path modify the number at x and update the label
        for path_name in path_names_to_modify:
            try:
                path = path_data[path_name]
            except KeyError:
                raise ValueError(f"Path '{path_name}' not found in path_data.")
            try:
                label = self.mpl_objects[path_name][f"{x:.1f}"]
                is_label_found = True
            except KeyError:
                print(
                    f"Warning (modify_number_values): No label found for path"
                    f" '{path_name}' at x={x}. Skipping modification."
                )
                is_label_found = False

            if is_label_found:
                number_new = base_value

                # Add all the values at x position specified in x_subtract and x_add
                if x_add is not None:
                    for x_val in x_add:
                        try:
                            index = path["x"].index(x_val)
                            number_new += path_data[path_name]["y"][index]
                        except ValueError:
                            print(
                                f"Warning (modify_number_values): Value at x={x_val} not"
                                f" found for path. '{path_name}'. Skipping addition."
                            )

                if x_subtract is not None:
                    for x_val in x_subtract:
                        try:
                            index = path["x"].index(x_val)
                            number_new -= path_data[path_name]["y"][index]
                        except ValueError:
                            print(
                                f"Warning (modify_number_values): Value at x={x_val} not"
                                f" found for path. '{path_name}'. Skipping subtraction."
                            )

                # Update the label text
                new_text = f"{brackets[0]}{number_new:.{n_decimals}f}{brackets[1]}"
                label.set_text(new_text)

    ############################################################
    # Helper methods for number placement and overlap checking
    ############################################################

    @staticmethod
    def _regularize_x_min_max(
        x_min_max: tuple[float, float] | list[float] | float | None,
    ) -> tuple[float, float]:
        # Convert x_min_max to an inclusive interval
        if x_min_max is not None:
            if isinstance(x_min_max, (Sequence)):
                Validators.validate_numeric_sequence(x_min_max, "x_min_max", required_length=2)
                x_min_max_new = (x_min_max[0], x_min_max[1])
            elif isinstance(x_min_max, (int, float)):
                x_min_max_new = (x_min_max, x_min_max)
            else:
                raise TypeError(
                    "x_min_max must be a tuple or list with length 2 or a numeric value."
                )
        else:
            x_min_max_new = (-np.inf, np.inf)
        return x_min_max_new

    @staticmethod
    def _get_all_visible_numbers(
        path_data: dict, x_min_max: tuple[float, float]
    ) -> list[dict]:
        # Create new list of values which should be printed
        values_to_print = []
        for path_name, path in path_data.items():
            # Only select data [[x...],[y...],color] in interval if show_numbers=True
            if path["show_numbers"]:
                values_to_print.append(
                    {
                        "x": [
                            path["x"][i]
                            for i in range(len(path["x"]))
                            if x_min_max[0] <= path["x"][i] <= x_min_max[1]
                        ],
                        "y": [
                            path["y"][i]
                            for i in range(len(path["x"]))
                            if x_min_max[0] <= path["x"][i] <= x_min_max[1]
                        ],
                        "color": path["color"],
                        "name": path_name,
                    }
                )
        return values_to_print

    @staticmethod
    def _get_all_values_at_x(path_data: dict, x: float) -> list[float]:
        # Select y values at ax
        numbers_at_x = []
        for path in path_data.values():
            numbers_at_x += [path["y"][i] for i in range(len(path["x"])) if path["x"][i] == x]
        return sorted(numbers_at_x)

    @staticmethod
    def _get_numbers_to_stack_at_x(
        values_to_print: Sequence[dict], x_current: float, sort_by_energy: bool = True
    ) -> list[dict]:
        # Get all values to print at a given location x
        numbers_to_stack = []
        for value_series in values_to_print:
            if x_current in value_series["x"]:
                numbers_to_stack.append(
                    {
                        "y": value_series["y"][value_series["x"].index(x_current)],
                        "color": value_series["color"],
                        "name": value_series["name"],
                    }
                )
            if sort_by_energy:
                numbers_to_stack = sorted(numbers_to_stack, key=lambda x: x["y"])
        return numbers_to_stack

    def _print_stacked(
        self,
        x: float,
        numbers_to_stack: Sequence[dict],
        y_print_start: float,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        fontsize: int,
        n_decimals: int = 0,
    ) -> None:
        """
        Render a vertical stack of energy labels at a given x-position.

        Labels are placed starting at ``y_print_start`` plus ``diff_bias``,
        with each subsequent label offset upward by ``diff_per_step``. The
        resulting Text artists are saved into ``mpl_objects`` under their
        path name and x-coordinate key.
        """
        diff_bias, diff_per_step = DifferenceManager._get_number_diffs(
            margins, figsize, fontsize
        )
        n_printed = 0
        for number in numbers_to_stack:
            number_obj = self.figure_manager.ax.text(
                x,
                (y_print_start + diff_bias + n_printed * diff_per_step),
                f"{number['y']:.{n_decimals}f}",
                ha="center",
                va="center",
                fontsize=fontsize,
                color=number["color"],
                zorder=constants.ZORDER_NUMBERS,
            )
            n_printed += 1
            if number["name"] not in self.mpl_objects:
                self.mpl_objects[number["name"]] = {}
            self.mpl_objects[number["name"]][f"{x:.1f}"] = number_obj

    @staticmethod
    def _check_no_overlap(
        y_print_start: float,
        numbers_to_stack: Sequence[dict],
        higher_numbers_at_x: Sequence[float],
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        fontsize: int,
        path_mpl_objects: dict,
        x: float,
    ) -> bool:
        """
        Return True if a proposed label stack would not collide with
        any higher plateaus or path labels.
        """
        no_number_overlap = NumberManager._check_no_plateau_overlap(
            y_print_start=y_print_start,
            numbers_to_stack=numbers_to_stack,
            higher_numbers_at_x=higher_numbers_at_x,
            margins=margins,
            figsize=figsize,
            fontsize=fontsize,
        )
        no_overlap_with_path_labels = NumberManager._check_no_overlap_with_path_labels(
            y_print_start=y_print_start,
            numbers_to_stack=numbers_to_stack,
            margins=margins,
            figsize=figsize,
            fontsize=fontsize,
            path_mpl_objects=path_mpl_objects,
            x=x,
        )
        return no_number_overlap and no_overlap_with_path_labels

    @staticmethod
    def _check_no_overlap_with_path_labels(
        y_print_start: float,
        numbers_to_stack: Sequence[dict],
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        fontsize: int,
        path_mpl_objects: dict,
        x: float,
    ) -> bool:
        """
        Return True if a proposed label stack would not collide with any path labels.

        Checks the vertical position of all path labels at the given x-coordinate
        and compares it to the proposed stack position. Returns True if there is no
        overlap, False otherwise.
        """
        diff_bias, diff_per_step = DifferenceManager._get_number_diffs(
            margins, figsize, fontsize
        )
        stacked_offset = (len(numbers_to_stack) - 1) * diff_per_step
        base_offset = 2 * diff_bias
        y_stacked_max = y_print_start + base_offset + stacked_offset
        no_overlap_with_path_labels = True
        for path_obj in path_mpl_objects.values():
            try:
                label_obj = path_obj.labels[f"{x:.1f}"]
                label_fontsize = label_obj.get_fontsize()
                label_y = label_obj.get_position()[1]
                labeltext = label_obj.get_text()
                diff_to_label = DifferenceManager._get_diff_img_label(
                    margins, figsize, label_fontsize, labeltext
                )
                has_collision = (
                    label_y - diff_to_label < y_stacked_max
                    and label_y + diff_to_label > y_print_start
                )
                if has_collision:
                    no_overlap_with_path_labels = False
            except KeyError:
                pass
        return no_overlap_with_path_labels

    @staticmethod
    def _check_no_plateau_overlap(
        y_print_start: float,
        numbers_to_stack: Sequence[dict],
        higher_numbers_at_x: Sequence[float],
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        fontsize: int,
    ) -> bool:
        """
        Return True if a proposed label stack would not collide with any higher plateaus.

        Computes the top edge of the stacked labels (including bias and
        per-step offsets) and checks that it falls below the nearest energy
        bar above ``y_print_start``. Returns True unconditionally if there
        are no higher bars.
        """
        diff_bias, diff_per_step = DifferenceManager._get_number_diffs(
            margins, figsize, fontsize
        )
        stacked_offset = (len(numbers_to_stack) - 1) * diff_per_step
        base_offset = 2 * diff_bias
        y_stacked_max = y_print_start + base_offset + stacked_offset
        # Check if a bar collides
        min_higher = min(higher_numbers_at_x) if higher_numbers_at_x else float("inf")
        # Check if there are numbers at all
        no_higher_numbers = len(higher_numbers_at_x) == 0
        return y_stacked_max < min_higher or no_higher_numbers

PathManager

Manages the creation and storage of reaction path artists.

Draws horizontal energy levels (plateaus) and the connectors between them, storing all rendered artists in mpl_objects and the underlying data in path_data for use by other managers.

Source code in src/chemdiagrams/managers/path_manager.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
class PathManager:
    """
    Manages the creation and storage of reaction path artists.

    Draws horizontal energy levels (plateaus) and the connectors
    between them, storing all rendered artists in ``mpl_objects`` and
    the underlying data in ``path_data`` for use by other managers.
    """

    def __init__(
        self,
        figure_manager: FigureManager,
    ) -> None:
        self.figure_manager = figure_manager
        self.path_data: dict[str, dict] = {}
        self.path_label_data: list[dict] = []
        self.mpl_objects: dict[str, PathObject] = {}
        self.merged_plateau_objects: list[dict] = []

    def draw_path(
        self,
        x_data: Sequence[float],
        y_data: Sequence[float],
        color: str,
        linetypes: Sequence[int] | int | None = None,
        path_name: str | None = None,
        show_numbers: bool = True,
        width_plateau: float | None = None,
        lw_plateau: float | str = "plateau",
        lw_connector: float | str = "connector",
        gap_scale: float | int | Sequence[float | int] = 1,
    ) -> None:
        # Sanity checks and linetype normalization
        Validators.validate_numeric_sequence(x_data, "x_data")
        Validators.validate_numeric_sequence(y_data, "y_data")
        if not isinstance(path_name, (str, type(None))):
            raise TypeError("path_name must be a string or None")
        if path_name in list(self.path_data.keys()):
            raise ValueError("path_name must not already exist")
        if len(x_data) != len(y_data):
            raise ValueError("x_data and y_data must have the same length")
        if width_plateau is not None:
            Validators.validate_number(width_plateau, "width_plateau", min_value=0)
        else:
            width_plateau = constants.WIDTH_PLATEAU

        ALLOWED_LINETYPES = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
        if linetypes is None:
            linetypes = [1] * (len(y_data) - 1)
        elif isinstance(linetypes, int):
            if linetypes not in ALLOWED_LINETYPES:
                raise ValueError(f"linetype must be in {ALLOWED_LINETYPES}.")
            linetypes = [linetypes] * (len(y_data) - 1)
        elif isinstance(linetypes, Sequence):
            if not all(val in ALLOWED_LINETYPES for val in linetypes):
                raise ValueError(f"linetype elements must be in {ALLOWED_LINETYPES}.")
            if len(linetypes) != len(x_data) - 1 or len(linetypes) != len(y_data) - 1:
                raise ValueError(
                    f"Length of linetypes + 1 (now {len(linetypes)} + 1) "
                    f"must equal the number of data points (right now {len(x_data)})."
                )
        else:
            raise TypeError("linetypes must be an tuple, list or integer.")

        if isinstance(lw_plateau, str):
            if lw_plateau == "plateau":
                lw_plateau = constants.LW_PLATEAU
            elif lw_plateau == "connector":
                lw_plateau = constants.LW_CONNECTOR
            else:
                raise ValueError(
                    "Invalid string value for lw_plateau. "
                    "Use 'plateau', 'connector', or a number."
                )
        else:
            Validators.validate_number(lw_plateau, "lw_plateau", min_value=0)
        assert isinstance(lw_plateau, (float, int))

        if isinstance(lw_connector, str):
            if lw_connector == "plateau":
                lw_connector = constants.LW_PLATEAU
            elif lw_connector == "connector":
                lw_connector = constants.LW_CONNECTOR
            else:
                raise ValueError(
                    "Invalid string value for lw_connector. "
                    "Use 'plateau', 'connector', or a number."
                )
        else:
            Validators.validate_number(lw_connector, "lw_connector", min_value=0)
        assert isinstance(lw_connector, (float, int))

        if isinstance(gap_scale, Sequence):
            if isinstance(gap_scale, str):
                raise TypeError("gap_scale cannot be a string.")
            if len(gap_scale) != len(x_data) - 1:
                raise ValueError(
                    f"Length of gap_scale + 1 (now {len(gap_scale)} + 1) "
                    f"must equal the number of data points (right now {len(x_data)})."
                )
            Validators.validate_numeric_sequence(
                gap_scale, "gap_scale", required_length=len(x_data) - 1, min_value=0
            )
        else:
            Validators.validate_number(gap_scale, "gap_scale", min_value=0)
            gap_scale = [gap_scale] * (len(x_data) - 1)
        for val in gap_scale:
            if val * constants.BROKEN_LINE_GAP >= 1:
                raise ValueError(
                    f"gap_scale values must be small enough that the "
                    f"gap in broken line styles is less than 100% of the line length. "
                    f"Currently, gap_scale * BROKEN_LINE_GAP "
                    f"= {val * constants.BROKEN_LINE_GAP}."
                )

        # Save data for numbering or legend
        has_name = True
        if path_name is None:
            has_name = False
            path_name = f"__NONAME{len(self.path_data)}"
        self.path_data[path_name] = {
            "x": x_data,
            "y": y_data,
            "color": color,
            "has_name": has_name,
            "show_numbers": show_numbers,
        }

        # Initialize nested dicts
        connections: dict = {}
        plateaus: dict = {}
        labels: dict = {}

        # Create lists in order to draw the lines
        x_corners = []
        y_corners = []

        # Draw the lines
        for i, v in enumerate(y_data):
            x_corners.append(x_data[i] - 0.5 * width_plateau)
            x_corners.append(x_data[i] + 0.5 * width_plateau)
            y_corners.append(y_data[i])
            y_corners.append(y_data[i])
            if width_plateau > 0:
                plateau = self.figure_manager.ax.hlines(
                    v,
                    x_corners[-2],
                    x_corners[-1],
                    zorder=constants.ZORDER_PLATEAU,
                    lw=lw_plateau,
                    color=color,
                    capstyle="round",
                )
            else:
                plateau = None
            plateaus[f"{x_data[i]:.1f}"] = plateau
            if i > 0:
                connector = self._draw_connector(
                    x_corners[-3:-1],
                    y_corners[-3:-1],
                    linetypes[i - 1],
                    color,
                    lw_connector,
                    gap_scale[i - 1],
                )
                connections[f"{sum(x_corners[-3:-1]) / 2:.1f}"] = connector
        # Save Path
        self.mpl_objects[path_name] = PathObject(connections, plateaus, labels)

    def add_path_labels(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        path_name: str,
        labels: Sequence[str],
        fontsize: int | None = None,
        weight: str = "normal",
        color: str | None = None,
    ) -> None:
        # Sanity checks
        if path_name not in self.path_data.keys():
            raise ValueError(f'Path "{path_name}" does not exist.')
        Validators.validate_string_sequence(
            labels,
            "labels",
            can_contain_none=True,
            required_length=len(self.path_data[path_name]["x"]),
        )
        if fontsize is not None:
            Validators.validate_number(fontsize, "fontsize", min_value=0, allow_none=True)
        else:
            fontsize = self.figure_manager.fontsize
        if color is None:
            color = self.path_data[path_name]["color"]

        labelfont = font_manager.FontProperties(weight=weight, size=fontsize)

        for i, labeltext in enumerate(labels):
            if labeltext is not None:
                x = self.path_data[path_name]["x"][i]
                y = self.path_data[path_name]["y"][i]
                label_artist = StyleManager._add_label_in_plot(
                    figure_manager=self.figure_manager,
                    margins=margins,
                    figsize=figsize,
                    labeltext=labeltext,
                    fontsize=fontsize,
                    labelfont=labelfont,
                    x=x,
                    y=y,
                    color=color,
                )
                self.mpl_objects[path_name].labels[f"{x:.1f}"] = label_artist

        self.path_label_data.append(
            {
                "path_name": path_name,
                "labels": labels,
                "fontsize": fontsize,
                "weight": weight,
                "color": color,
            }
        )

    def _recalculate_path_labels(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
    ) -> None:
        old_path_label_data = self.path_label_data.copy()
        self.path_label_data = []
        for label_data in old_path_label_data:
            # Remove old labels
            self.mpl_objects[label_data["path_name"]].remove_labels()

            # Add new labels with updated positions
            self.add_path_labels(
                margins=margins,
                figsize=figsize,
                **label_data,
            )

    def merge_plateaus(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        x: int,
        path_name_left: str,
        path_name_right: str,
        gap_scale: float = 1,
        stopper_scale: float = 1,
        angle: float = 30,
    ) -> None:
        # Sanity checks
        Validators.validate_number(x, "x")
        Validators.validate_number(gap_scale, "gap_scale", min_value=0)
        Validators.validate_number(stopper_scale, "stopper_scale", min_value=0)
        Validators.validate_number(angle, "angle")
        try:
            full_plateau_left = self.mpl_objects[path_name_left].plateaus[f"{x:.1f}"]
        except KeyError:
            raise ValueError(
                f'Path "{path_name_left}" must exist and have a value at x = {x}.'
            )
        try:
            full_plateau_right = self.mpl_objects[path_name_right].plateaus[f"{x:.1f}"]
        except KeyError:
            raise ValueError(
                f'Path "{path_name_right}" must exist and have a value at x = {x}.'
            )
        if full_plateau_left is None:
            raise ValueError(f"Plateau for {path_name_left} at x = {x} is non-existent.")
        if full_plateau_right is None:
            raise ValueError(f"Plateau for {path_name_right} at x = {x} is non-existent.")
        y_left = full_plateau_left.get_segments()[0][0][1]
        y_right = full_plateau_right.get_segments()[0][0][1]
        if y_left != y_right:
            raise ValueError(
                f"{path_name_left} and {path_name_right} must have the same y at x = {x}."
            )
        y = y_left

        # Get color information
        color_left = full_plateau_left.get_color()
        color_right = full_plateau_right.get_color()
        full_plateau_left.remove()
        full_plateau_right.remove()

        # Print plateaus
        gap = constants.MERGED_PLATEAU_GAP * gap_scale
        plateau_left = self.figure_manager.ax.hlines(
            y,
            x - constants.WIDTH_PLATEAU / 2,
            x - gap / 2,
            zorder=constants.ZORDER_PLATEAU,
            lw=constants.LW_PLATEAU,
            color=color_left,
            capstyle="round",
        )
        plateau_right = self.figure_manager.ax.hlines(
            y,
            x + constants.WIDTH_PLATEAU / 2,
            x + gap / 2,
            zorder=constants.ZORDER_PLATEAU,
            lw=constants.LW_PLATEAU,
            color=color_right,
            capstyle="round",
        )

        # Draw white rectangle to
        cover_width = DifferenceManager._get_axis_break_whitespace_cover_width(
            margins, figsize
        )

        # Add white covering reactange
        # x in data coords, y in axis fractions
        whitespace = mpatches.Rectangle(
            (x - gap / 2, y - cover_width / 2),
            gap,
            cover_width,
            facecolor="white",
            edgecolor="white",
            zorder=constants.ZORDER_MERGED_PLATEAU_COVER,
        )

        # Calculate stopper direction in data coordinates
        delta_x, delta_y = DifferenceManager._get_axis_break_stopper_differences(
            margins,
            figsize,
            angle,
        )

        stopper_left = self.figure_manager.ax.annotate(
            "",
            xy=(x - gap / 2, y),
            xytext=(x - gap / 2 + delta_x, y + delta_y),
            arrowprops=dict(
                arrowstyle="|-|",
                color=color_left,
                lw=constants.LW_MERGED_PLATEAU_STOPPER,
                shrinkA=15,
                shrinkB=15,
                mutation_scale=constants.SIZE_MERGED_PLATEAU_STOPPER * stopper_scale,
                zorder=constants.ZORDER_MERGED_PLATEAU_STOPPER,
            ),
        )
        stopper_right = self.figure_manager.ax.annotate(
            "",
            xy=(x + gap / 2, y),
            xytext=(x + gap / 2 - delta_x, y - delta_y),
            arrowprops=dict(
                arrowstyle="|-|",
                color=color_right,
                lw=constants.LW_MERGED_PLATEAU_STOPPER,
                shrinkA=15,
                shrinkB=15,
                mutation_scale=constants.SIZE_MERGED_PLATEAU_STOPPER * stopper_scale,
                zorder=constants.ZORDER_MERGED_PLATEAU_STOPPER,
            ),
        )

        # Save mpl objects get a pointer for angle correction
        merged_plateau = MergedPlateau(
            plateau_left,
            plateau_right,
            stopper_left,
            stopper_right,
            whitespace,
        )
        self.mpl_objects[path_name_left].plateaus[f"{x:.1f}"] = merged_plateau
        self.mpl_objects[path_name_right].plateaus[f"{x:.1f}"] = merged_plateau

        self.merged_plateau_objects.append(
            {
                "object": merged_plateau,
                "angle": angle,
            }
        )

    def _recalculate_merged_plateaus(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
    ) -> None:
        for merged_plateau_dict in self.merged_plateau_objects:
            merged_plateau_object = merged_plateau_dict["object"]
            angle = merged_plateau_dict["angle"]
            merged_plateau_object.recalculate_gap(margins, figsize, angle)

    def _draw_connector(
        self,
        x_coords: Sequence[float],
        y_coords: Sequence[float],
        linetype: int,
        color: str,
        lw_connector: float | int,
        gap_scale: float | int,
    ) -> Line2D | list[Line2D] | BrokenLine | None:
        connector: Line2D | list[Line2D] | BrokenLine | None = None
        if linetype == 0:
            connector = None
        elif linetype == 1:
            connector = self._draw_line(
                x_coords, y_coords, color, lw=lw_connector, dotted=True
            )
        elif linetype == -1:
            connector = self._draw_broken_line(
                x_coords, y_coords, color, lw=lw_connector, gap_scale=gap_scale, dotted=True
            )
        elif linetype == 2:
            connector = self._draw_line(
                x_coords, y_coords, color, lw=lw_connector, dotted=False
            )
        elif linetype == -2:
            connector = self._draw_broken_line(
                x_coords, y_coords, color, lw=lw_connector, gap_scale=gap_scale, dotted=False
            )
        elif linetype == 3:
            connector = self._draw_spline(
                x_coords, y_coords, color, lw=lw_connector, dotted=True
            )
        elif linetype == -3:
            connector = self._draw_broken_spline(
                x_coords, y_coords, color, lw=lw_connector, gap_scale=gap_scale, dotted=True
            )
        elif linetype == 4:
            connector = self._draw_spline(
                x_coords, y_coords, color, lw=lw_connector, dotted=False
            )
        elif linetype == -4:
            connector = self._draw_broken_spline(
                x_coords, y_coords, color, lw=lw_connector, gap_scale=gap_scale, dotted=False
            )
        else:
            raise ValueError(f"Invalid linetype argument: {linetype}")
        return connector

    def _draw_line(
        self,
        x_coords: Sequence[float],
        y_coords: Sequence[float],
        color: str,
        lw: float | int,
        dotted: bool = False,
    ) -> Line2D:
        if dotted:
            ls = ":"
        else:
            ls = "-"
        return self.figure_manager.ax.plot(
            x_coords,
            y_coords,
            zorder=constants.ZORDER_CONNECTOR,
            ls=ls,
            lw=lw,
            color=color,
        )[0]

    def _draw_broken_line(
        self,
        x_coords: Sequence[float],
        y_coords: Sequence[float],
        color: str,
        lw: float | int,
        gap_scale: float | int,
        dotted: bool = True,
    ) -> BrokenLine:
        # Portion of the line that has a gap
        linegap = constants.BROKEN_LINE_GAP * gap_scale
        # Ensure tuples are converted to list
        x_coords = list(x_coords)
        y_coords = list(y_coords)

        # Draw first part of line
        x1 = x_coords.copy()
        y1 = y_coords.copy()
        x1[1] = x1[0] + (x1[1] - x1[0]) * (0.5 - linegap / 2)
        y1[1] = y1[0] + (y1[1] - y1[0]) * (0.5 - linegap / 2)
        if dotted:
            line_1 = self._draw_line(x1, y1, color=color, lw=lw, dotted=True)
        else:
            line_1 = self._draw_line(x1, y1, color=color, lw=lw, dotted=False)

        # Draw second part of line
        x2 = x_coords.copy()
        y2 = y_coords.copy()
        x2[0] = x2[0] + (x2[1] - x2[0]) * (0.5 + linegap / 2)
        y2[0] = y2[0] + (y2[1] - y2[0]) * (0.5 + linegap / 2)
        if dotted:
            line_2 = self._draw_line(x2, y2, color=color, lw=lw, dotted=True)
        else:
            line_2 = self._draw_line(x2, y2, color=color, lw=lw, dotted=False)

        # Draw small orthogonal lines
        stopper_1 = self.figure_manager.ax.annotate(
            "",
            xy=(x1[1], y1[1]),
            xytext=(x1[1] + 0.001 * (x2[0] - x1[1]), y1[1] + 0.001 * (y2[0] - y1[1])),
            arrowprops=dict(
                arrowstyle="|-|",
                color=color,
                lw=constants.LW_BROKEN_LINE_STOPPER,
                shrinkA=15,
                shrinkB=15,
                mutation_scale=constants.SIZE_BROKEN_LINE_STOPPER,
                zorder=constants.ZORDER_BROKEN_LINE_STOPPER,
            ),
        )
        stopper_2 = self.figure_manager.ax.annotate(
            "",
            xy=(x2[0], y2[0]),
            xytext=(x2[0] - 0.001 * (x2[0] - x1[1]), y2[0] - 0.001 * (y2[0] - y1[1])),
            arrowprops=dict(
                arrowstyle="|-|",
                color=color,
                lw=constants.LW_BROKEN_LINE_STOPPER,
                shrinkA=15,
                shrinkB=15,
                mutation_scale=constants.SIZE_BROKEN_LINE_STOPPER,
                zorder=constants.ZORDER_BROKEN_LINE_STOPPER,
            ),
        )
        return BrokenLine(line_1, line_2, stopper_1, stopper_2)

    def _draw_spline(
        self,
        x_coords: Sequence[float],
        y_coords: Sequence[float],
        color: str,
        lw: float | int,
        dotted: bool = False,
    ) -> list[Line2D]:
        if dotted:
            ls = ":"
        else:
            ls = "-"
        # Create a cubic spline interpolation of the points
        cs = CubicSpline(x_coords, y_coords, bc_type="clamped")
        x_spline = np.linspace(x_coords[0], x_coords[-1], 100)
        y_spline = cs(x_spline)

        # Draw the spline as a solid line
        return self.figure_manager.ax.plot(
            x_spline,
            y_spline,
            zorder=constants.ZORDER_CONNECTOR,
            ls=ls,
            lw=lw,
            color=color,
        )

    def _draw_broken_spline(
        self,
        x_coords: Sequence[float],
        y_coords: Sequence[float],
        color: str,
        lw: float | int,
        gap_scale: float | int,
        dotted: bool = True,
    ) -> list[Line2D] | BrokenLine:
        # Portion of the line that has a gap
        linegap = constants.BROKEN_LINE_GAP * gap_scale
        cs = CubicSpline(x_coords, y_coords, bc_type="clamped")
        x_spline = np.linspace(x_coords[0], x_coords[-1], 100)
        y_spline = cs(x_spline)

        # Draw first part of spline
        interval_start_gap = int(len(x_spline) * (0.5 - linegap / 2))
        x1 = x_spline[:interval_start_gap]
        y1 = y_spline[:interval_start_gap]
        if dotted:
            line_1 = self._draw_spline_part(x1, y1, color=color, lw=lw, dotted=True)
        else:
            line_1 = self._draw_spline_part(x1, y1, color=color, lw=lw, dotted=False)

        # Draw second part of spline
        interval_end_gap = int(len(x_spline) * (0.5 + linegap / 2))
        x2 = x_spline[interval_end_gap:]
        y2 = y_spline[interval_end_gap:]
        if dotted:
            line_2 = self._draw_spline_part(x2, y2, color=color, lw=lw, dotted=True)
        else:
            line_2 = self._draw_spline_part(x2, y2, color=color, lw=lw, dotted=False)

        # Draw small orthogonal lines at the break point
        stopper_1 = self.figure_manager.ax.annotate(
            "",
            xy=(x_spline[interval_start_gap], y_spline[interval_start_gap]),
            xytext=(
                x_spline[interval_start_gap]
                + 0.01 * (x_spline[interval_start_gap + 1] - x_spline[interval_start_gap]),
                y_spline[interval_start_gap]
                + 0.01 * (y_spline[interval_start_gap + 1] - y_spline[interval_start_gap]),
            ),
            arrowprops=dict(
                arrowstyle="|-|",
                color=color,
                lw=constants.LW_BROKEN_LINE_STOPPER,
                shrinkA=15,
                shrinkB=15,
                mutation_scale=constants.SIZE_BROKEN_LINE_STOPPER,
                zorder=constants.ZORDER_BROKEN_LINE_STOPPER,
            ),
        )
        stopper_2 = self.figure_manager.ax.annotate(
            "",
            xy=(x_spline[interval_end_gap], y_spline[interval_end_gap]),
            xytext=(
                x_spline[interval_end_gap]
                - 0.01 * (x_spline[interval_end_gap] - x_spline[interval_end_gap - 1]),
                y_spline[interval_end_gap]
                - 0.01 * (y_spline[interval_end_gap] - y_spline[interval_end_gap - 1]),
            ),
            arrowprops=dict(
                arrowstyle="|-|",
                color=color,
                lw=constants.LW_BROKEN_LINE_STOPPER,
                shrinkA=15,
                shrinkB=15,
                mutation_scale=constants.SIZE_BROKEN_LINE_STOPPER,
                zorder=constants.ZORDER_BROKEN_LINE_STOPPER,
            ),
        )
        return BrokenLine(line_1, line_2, stopper_1, stopper_2)

    def _draw_spline_part(
        self,
        x_coords: Sequence[float] | np.ndarray,
        y_coords: Sequence[float] | np.ndarray,
        color: str,
        lw: float | int,
        dotted: bool = False,
    ) -> Line2D:
        if dotted:
            ls = ":"
        else:
            ls = "-"
        return self.figure_manager.ax.plot(
            x_coords,
            y_coords,
            zorder=constants.ZORDER_CONNECTOR,
            ls=ls,
            lw=lw,
            color=color,
        )[0]

    @staticmethod
    def _get_stopper_differences(
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        angle: float,
    ) -> tuple[float, float]:
        delta_x = (
            np.cos(angle * np.pi / 180)
            * 0.001
            * (margins["x"][1] - margins["x"][0])
            / figsize[0]
        )
        delta_y = (
            np.sin(angle * np.pi / 180)
            * 0.001
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
        )
        return delta_x, delta_y

    @staticmethod
    def _get_whitespace_cover_width(
        margins: dict[str, tuple],
        figsize: tuple[float, float],
    ) -> float:
        cover_width = (
            constants.MERGED_PLATEAU_COVER_WIDTH
            * (margins["y"][1] - margins["y"][0])
            / figsize[1]
        )
        return cover_width

PathObject dataclass

Container for the Matplotlib artists that make up a single reaction path.

Attributes:

Name Type Description
connections dict of str to Line2D, BrokenLine, or None

Connector artists between energy levels, keyed by the midpoint x-coordinate of each segment as a formatted string (e.g. "1.5").

plateaus dict of str to LineCollection

Horizontal energy bar artists, keyed by their x-coordinate as a formatted string (e.g. "1.0").

Source code in src/chemdiagrams/managers/path_manager.py
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
@dataclass
class PathObject:
    """
    Container for the Matplotlib artists that make up a single reaction path.

    Attributes
    ----------
    connections : dict of str to Line2D, BrokenLine, or None
        Connector artists between energy levels, keyed by the midpoint
        x-coordinate of each segment as a formatted string (e.g. ``"1.5"``).
    plateaus : dict of str to LineCollection
        Horizontal energy bar artists, keyed by their x-coordinate
        as a formatted string (e.g. ``"1.0"``).
    """

    connections: dict
    plateaus: dict
    labels: dict

    def remove(self):
        for _, connection in self.connections.items():
            connection.remove()
        for _, plateau in self.plateaus.items():
            try:
                plateau.remove()
            except AttributeError:
                pass
        for _, label in self.labels.items():
            label.remove()

    def remove_labels(self):
        for _, label in self.labels.items():
            label.remove()
        self.labels = {}

StyleManager

Manages the visual style and x-axis labels of the diagram.

Handles spine visibility, axis arrows, and background elements for the five supported styles: "boxed", "halfboxed", "open", "twosided" and "borderless". Also manages x-axis label placement, either below the axis or inside the plot area.

Source code in src/chemdiagrams/managers/style_manager.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
class StyleManager:
    """
    Manages the visual style and x-axis labels of the diagram.

    Handles spine visibility, axis arrows, and background elements
    for the five supported styles: ``"boxed"``, ``"halfboxed"``,
    ``"open"``, ``"twosided"`` and ``"borderless"``. Also manages x-axis label
    placement, either below the axis or inside the plot area.
    """

    def __init__(
        self,
        figure_manager: FigureManager,
        style: str,
    ) -> None:
        self.figure_manager = figure_manager
        self.style = style
        self.mpl_objects = StyleObjects({}, {}, {}, {}, {})
        self.axes_break_data: dict[str, list] = {"x": [], "y": []}
        self.has_axes_breaks = False
        self.set_diagram_style(self.style)

    def set_diagram_style(self, style: str) -> None:
        def draw_arrow(xy, xytext):
            arrow = self.figure_manager.ax.annotate(
                "",
                xy=xy,
                xytext=xytext,
                xycoords="axes fraction",
                arrowprops=dict(
                    arrowstyle="-|>",
                    color="black",
                    lw=0,
                    shrinkA=0,
                    shrinkB=0,
                    mutation_scale=constants.SIZE_AXIS_ARROWS,
                    zorder=constants.ZORDER_AXIS_ARROWS,
                ),
            )
            return arrow

        ALLOWED_STYLES = ["boxed", "halfboxed", "open", "twosided", "borderless"]

        if style not in ALLOWED_STYLES:
            raise ValueError(f"style must be one of {ALLOWED_STYLES}.")

        self.style = style

        # Remove grid lines and set x axes to default cover_width
        self.figure_manager.ax.xaxis.grid(False)
        self.figure_manager.ax.yaxis.grid(False)
        self.figure_manager.ax.spines["bottom"].set_position(("axes", 0))
        self.figure_manager.ax.set_zorder(0.5)

        # Remove unwanted objects
        self.mpl_objects.remove_axes()
        axes_dict = {}
        arrows_dict = {}

        # Reset y labels and ticks automatically
        self.figure_manager.ax.yaxis.set_major_locator(ticker.AutoLocator())
        self.figure_manager.ax.yaxis.set_major_formatter(ticker.ScalarFormatter())

        # Adjust axes
        if style == "boxed":
            self.figure_manager.ax.spines["top"].set_visible(True)
            self.figure_manager.ax.spines["right"].set_visible(True)
            self.figure_manager.ax.spines["left"].set_visible(True)
            self.figure_manager.ax.spines["bottom"].set_visible(True)

        elif style == "halfboxed":
            self.figure_manager.ax.spines["top"].set_visible(False)
            self.figure_manager.ax.spines["right"].set_visible(False)
            self.figure_manager.ax.spines["left"].set_visible(True)
            self.figure_manager.ax.spines["bottom"].set_visible(True)
            arrows_dict["x_arrow"] = draw_arrow((1.01, 0), (0.97, 0))
            arrows_dict["y_arrow"] = draw_arrow((0, 1.01), (0, 0.97))

        elif style == "open":
            self.figure_manager.ax.spines["top"].set_visible(False)
            self.figure_manager.ax.spines["right"].set_visible(False)
            self.figure_manager.ax.spines["left"].set_visible(True)
            self.figure_manager.ax.spines["bottom"].set_visible(False)
            axes_dict["x_axis"] = self.figure_manager.ax.axhline(
                0,
                color="black",
                zorder=constants.ZORDER_X_AXIS,
                lw=constants.LW_X_AXIS,
            )
            arrows_dict["y_arrow"] = draw_arrow((0, 1.01), (0, 0.97))

        elif style == "twosided":
            self.figure_manager.ax.spines["top"].set_visible(False)
            self.figure_manager.ax.spines["right"].set_visible(False)
            self.figure_manager.ax.spines["left"].set_visible(True)
            self.figure_manager.ax.spines["bottom"].set_visible(True)
            self.figure_manager.ax.spines["bottom"].set_position(
                ("axes", constants.X_AXIS_OFFSET_OPENSTYLE)
            )
            arrows_dict["x_arrow_right"] = draw_arrow((1.01, -0.03), (0.96, -0.03))
            arrows_dict["x_arrow_left"] = draw_arrow((-0.01, -0.03), (0.04, -0.03))
            arrows_dict["y_arrow"] = draw_arrow((0, 1.01), (0, 0.97))

        elif style == "borderless":
            self.figure_manager.ax.spines["top"].set_visible(False)
            self.figure_manager.ax.spines["right"].set_visible(False)
            self.figure_manager.ax.spines["left"].set_visible(False)
            self.figure_manager.ax.spines["bottom"].set_visible(False)
            self.figure_manager.ax.set_yticklabels([])
            self.figure_manager.ax.set_yticks([])

        self.mpl_objects.arrows = arrows_dict
        self.mpl_objects.axes = axes_dict

    def set_xlabels(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        path_data: dict,
        labels: Sequence,
        labelplaces: Sequence[float] | None = None,
        fontsize: int | None = None,
        weight: str = "bold",
        in_plot: bool = False,
    ) -> None:
        # Sanity checks
        Validators.validate_numeric_sequence(labelplaces, "labelplaces", allow_none=True)
        Validators.validate_number(fontsize, "fontsize", allow_none=True, min_value=0)
        if labelplaces is not None:
            if len(labels) != len(labelplaces):
                raise ValueError("There must be the same number of labels and labelplaces.")

        # Create labelplace list if none given
        if labelplaces is None:
            labelplaces = list(range(len(labels)))
        self.labelproperties = {
            "labels": labels,
            "labelplaces": labelplaces,
            "fontsize": fontsize,
            "weight": weight,
            "in_plot": in_plot,
        }

        # Clear or hide labels if present
        self.figure_manager.ax.set_xticks([])
        self.mpl_objects.remove_xlabels()
        label_dict = {}

        # Set font of x labels
        if fontsize is None:
            fontsize = self.figure_manager.fontsize
        labelfont = font_manager.FontProperties(weight=weight, size=fontsize)

        # Set labels in the plot or at axis
        if in_plot:
            for x, labeltext in zip(labelplaces, labels):
                all_values_at_x = NumberManager._get_all_values_at_x(path_data, x)
                if all_values_at_x:
                    y = min(all_values_at_x)
                    label = self._add_label_in_plot(
                        self.figure_manager,
                        margins,
                        figsize,
                        labeltext,
                        fontsize,
                        labelfont,
                        x,
                        y,
                    )
                    label_dict[f"{x:.1f}"] = label
                else:
                    print(
                        f"Warning: There was no datapoint found at x = {x}, "
                        f"therefore no label is shown."
                    )
            self.mpl_objects.x_labels = label_dict
        else:
            self.figure_manager.ax.set_xticks(labelplaces)
            self.figure_manager.ax.set_xticklabels(labels)
            for label in self.figure_manager.ax.get_xticklabels():
                label.set_fontproperties(labelfont)

    def add_xaxis_break(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        x: float,
        gap_scale: float = 1,
        stopper_scale: float = 1,
        angle: float = 30,
    ) -> None:
        Validators.validate_number(x, "x")
        Validators.validate_number(gap_scale, "gap_scale", min_value=0)
        Validators.validate_number(stopper_scale, "stopper_scale", min_value=0)
        Validators.validate_number(angle, "angle")

        def draw_xaxis_break(x_pos, y_pos):
            # gap in x data coords
            gap = (
                constants.AXIS_BREAK_GAP
                * (margins["x"][1] - margins["x"][0])
                / figsize[0]
                * gap_scale
            )

            # cover_width in y axis fraction
            cover_width = constants.AXIS_BREAK_COVER_WIDTH / figsize[1]

            # Add white covering reactange
            # x in data coords, y in axis fractions
            rect = mpatches.Rectangle(
                (x_pos - gap / 2, y_pos - cover_width / 2),
                gap,
                cover_width,
                transform=self.figure_manager.ax.get_xaxis_transform(),
                facecolor="white",
                edgecolor="white",
                zorder=constants.ZORDER_AXIS_BREAK_COVER,
                clip_on=False,
            )
            self.figure_manager.ax.add_artist(rect)

            # Convert stopper angle
            # delta_x in data coords, delta_y in axis coords
            delta_x = np.cos(angle * np.pi / 180) * 0.001
            delta_y = (
                np.sin(angle * np.pi / 180)
                * 0.001
                / (margins["x"][1] - margins["x"][0])
                * figsize[1]
                / figsize[0]
            )

            # Draw stoppers
            stopper_1 = self.figure_manager.ax.annotate(
                "",
                xy=(x_pos - gap / 2, y_pos),
                xytext=(x_pos - gap / 2 + delta_x, y_pos + delta_y),
                xycoords=self.figure_manager.ax.get_xaxis_transform(),
                arrowprops=dict(
                    arrowstyle="|-|",
                    color="black",
                    lw=constants.LW_AXIS_BREAK_STOPPER,
                    shrinkA=15,
                    shrinkB=15,
                    mutation_scale=constants.SIZE_AXIS_BREAK_STOPPER * stopper_scale,
                    zorder=constants.ZORDER_AXIS_BREAK_STOPPER,
                ),
            )
            stopper_1.set_zorder(constants.ZORDER_AXIS_BREAK_STOPPER)

            stopper_2 = self.figure_manager.ax.annotate(
                "",
                xy=(x_pos + gap / 2, y_pos),
                xytext=(x_pos + gap / 2 + delta_x, y_pos + delta_y),
                xycoords=self.figure_manager.ax.get_xaxis_transform(),
                arrowprops=dict(
                    arrowstyle="|-|",
                    color="black",
                    lw=constants.LW_AXIS_BREAK_STOPPER,
                    shrinkA=15,
                    shrinkB=15,
                    mutation_scale=constants.SIZE_AXIS_BREAK_STOPPER * stopper_scale,
                    zorder=constants.ZORDER_AXIS_BREAK_STOPPER,
                ),
            )
            stopper_2.set_zorder(constants.ZORDER_AXIS_BREAK_STOPPER)

            return AxisBreak(rect, stopper_1, stopper_2)

        self.has_axes_breaks = True
        if self.style == "open":
            raise NotImplementedError(
                "x-axis breaks are not compatible with open diagram style"
            )
        elif self.style == "halfboxed":
            break_object = draw_xaxis_break(x, 0)
        elif self.style == "boxed":
            break_object_bottom = draw_xaxis_break(x, 0)
            break_object_top = draw_xaxis_break(x, 1)
            break_object = {
                "top": break_object_top,
                "bottom": break_object_bottom,
            }
        elif self.style == "twosided":
            break_object = draw_xaxis_break(x, constants.X_AXIS_OFFSET_OPENSTYLE)
        elif self.style == "borderless":
            raise NotImplementedError(
                "x-axis breaks are not compatible with borderless diagram style"
            )

        self.mpl_objects.xaxis_breaks[f"{x:.1f}"] = break_object

        # Save for redrawing
        self.axes_break_data["x"].append(
            {
                "x": x,
                "gap_scale": gap_scale,
                "stopper_scale": stopper_scale,
                "angle": angle,
            }
        )

    def add_yaxis_break(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        y: float,
        gap_scale: float = 1,
        stopper_scale: float = 1,
        angle: float = 30,
    ) -> None:
        Validators.validate_number(y, "y")
        Validators.validate_number(gap_scale, "gap_scale", min_value=0)
        Validators.validate_number(stopper_scale, "stopper_scale", min_value=0)
        Validators.validate_number(angle, "angle")

        def draw_xaxis_break(x_pos, y_pos):
            # Gap in y data coords
            gap = (
                constants.AXIS_BREAK_GAP
                * (margins["y"][1] - margins["y"][0])
                / figsize[1]
                * gap_scale
            )

            # Cover_width in x axis fraction
            cover_width = constants.AXIS_BREAK_COVER_WIDTH / figsize[0]

            # Add white covering reactange
            # y in data coords, x in axis fractions
            rect = mpatches.Rectangle(
                (x_pos - cover_width / 2, y_pos - gap / 2),
                cover_width,
                gap,
                transform=self.figure_manager.ax.get_yaxis_transform(),
                facecolor="white",
                edgecolor="white",
                zorder=constants.ZORDER_AXIS_BREAK_COVER,
                clip_on=False,
            )
            self.figure_manager.ax.add_artist(rect)

            # Convert stopper angle
            delta_x = (
                np.sin(angle * np.pi / 180)
                * 0.001
                / (margins["y"][1] - margins["y"][0])
                * figsize[1]
                / figsize[0]
            )
            delta_y = np.cos(angle * np.pi / 180) * 0.001

            # Draw stoppers
            stopper_1 = self.figure_manager.ax.annotate(
                "",
                xy=(x_pos, y_pos - gap / 2),
                xytext=(x_pos + delta_x, y_pos - gap / 2 + delta_y),
                xycoords=self.figure_manager.ax.get_yaxis_transform(),
                arrowprops=dict(
                    arrowstyle="|-|",
                    color="black",
                    lw=constants.LW_AXIS_BREAK_STOPPER,
                    shrinkA=15,
                    shrinkB=15,
                    mutation_scale=constants.SIZE_AXIS_BREAK_STOPPER * stopper_scale,
                    zorder=constants.ZORDER_AXIS_BREAK_STOPPER,
                ),
            )
            stopper_1.set_zorder(constants.ZORDER_AXIS_BREAK_STOPPER)

            stopper_2 = self.figure_manager.ax.annotate(
                "",
                xy=(x_pos, y_pos + gap / 2),
                xytext=(x_pos + delta_x, y_pos + gap / 2 + delta_y),
                xycoords=self.figure_manager.ax.get_yaxis_transform(),
                arrowprops=dict(
                    arrowstyle="|-|",
                    color="black",
                    lw=constants.LW_AXIS_BREAK_STOPPER,
                    shrinkA=15,
                    shrinkB=15,
                    mutation_scale=constants.SIZE_AXIS_BREAK_STOPPER * stopper_scale,
                    zorder=constants.ZORDER_AXIS_BREAK_STOPPER,
                ),
            )
            stopper_2.set_zorder(constants.ZORDER_AXIS_BREAK_STOPPER)

            return AxisBreak(rect, stopper_1, stopper_2)

        self.has_axes_breaks = True
        if self.style == "boxed":
            break_object_left = draw_xaxis_break(0, y)
            break_object_right = draw_xaxis_break(1, y)
            break_object = {
                "left": break_object_left,
                "right": break_object_right,
            }
        elif self.style == "borderless":
            raise NotImplementedError(
                "y-axis breaks are not compatible with borderless diagram style"
            )
        else:
            break_object = draw_xaxis_break(0, y)

        self.mpl_objects.yaxis_breaks[f"{y:.1f}"] = break_object

        # Save for redrawing
        self.axes_break_data["y"].append(
            {
                "y": y,
                "gap_scale": gap_scale,
                "stopper_scale": stopper_scale,
                "angle": angle,
            }
        )

    def recalculate_axis_breaks(
        self,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
    ) -> None:
        self.mpl_objects.remove_axes_breaks()
        xaxis_breaks = self.axes_break_data["x"][:]
        yaxis_breaks = self.axes_break_data["y"][:]
        self.axes_break_data["x"] = []
        self.axes_break_data["y"] = []
        for x_break in xaxis_breaks:
            self.add_xaxis_break(
                margins=margins,
                figsize=figsize,
                **x_break,
            )
        for y_break in yaxis_breaks:
            self.add_yaxis_break(
                margins=margins,
                figsize=figsize,
                **y_break,
            )

    @staticmethod
    def _add_label_in_plot(
        figure_manager: FigureManager,
        margins: dict[str, tuple],
        figsize: tuple[float, float],
        labeltext: str,
        fontsize: int,
        labelfont: font_manager.FontProperties,
        x: float,
        y: float,
        color: str = "black",
    ) -> Text:
        y_diff = -DifferenceManager._get_diff_plateau_label(
            margins, figsize, fontsize, labeltext
        )
        label = figure_manager.ax.text(
            x,
            y + y_diff,
            labeltext,
            font=labelfont,
            ha="center",
            va="center",
            color=color,
            zorder=constants.ZORDER_X_LABEL,
        )
        return label

StyleObjects dataclass

Container for the Matplotlib artists controlled by the style manager.

Attributes:

Name Type Description
arrows dict of str to Annotation

Axis arrow artists, keyed by name (e.g. "x_arrow", "y_arrow").

axes dict of str to Line2D

Supplementary axis line artists, such as the horizontal zero line in the "open" style, keyed by name (e.g. "x_axis").

x_labels dict of str to Text

In-plot x label artists, keyed by x-coordinate as a formatted string. Only populated when in_plot=True is used in set_xlabels; otherwise labels are handled by Matplotlib's own tick system and not stored here.

xaxis_breaks dict of str to AxisBreak

X-axis break artists, keyed by position as a formatted string (e.g. "2.0").

yaxis_breaks dict of str to AxisBreak

Y-axis break artists, keyed by position as a formatted string (e.g. "5.0").

Source code in src/chemdiagrams/managers/style_manager.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
@dataclass
class StyleObjects:
    """
    Container for the Matplotlib artists controlled by the style manager.

    Attributes
    ----------
    arrows : dict of str to Annotation
        Axis arrow artists, keyed by name (e.g. ``"x_arrow"``, ``"y_arrow"``).
    axes : dict of str to Line2D
        Supplementary axis line artists, such as the horizontal zero line
        in the ``"open"`` style, keyed by name (e.g. ``"x_axis"``).
    x_labels : dict of str to Text
        In-plot x label artists, keyed by x-coordinate as a formatted
        string. Only populated when ``in_plot=True`` is used in
        ``set_xlabels``; otherwise labels are handled by Matplotlib's
        own tick system and not stored here.
    xaxis_breaks : dict of str to AxisBreak
        X-axis break artists, keyed by position as a formatted string
        (e.g. ``"2.0"``).
    yaxis_breaks : dict of str to AxisBreak
        Y-axis break artists, keyed by position as a formatted string
        (e.g. ``"5.0"``).
    """

    arrows: dict[str, Annotation]
    axes: dict[str, Line2D]
    x_labels: dict[str, Text]
    xaxis_breaks: dict[str, AxisBreak | dict[str, AxisBreak]]
    yaxis_breaks: dict[str, AxisBreak | dict[str, AxisBreak]]

    def remove_axes(self):
        for _, arrow in self.arrows.items():
            arrow.remove()
        for _, axis in self.axes.items():
            axis.remove()
        for _, axis_break in self.xaxis_breaks.items():
            axis_break.remove()
        for _, axis_break in self.yaxis_breaks.items():
            axis_break.remove()
        self.arrows = {}
        self.axes = {}
        self.xaxis_breaks = {}
        self.yaxis_breaks = {}

    def remove_axes_breaks(self):
        for _, axis_break in self.xaxis_breaks.items():
            axis_break.remove()
        for _, axis_break in self.yaxis_breaks.items():
            axis_break.remove()
        self.xaxis_breaks = {}
        self.yaxis_breaks = {}

    def remove_xlabels(self):
        for _, label in self.x_labels.items():
            label.remove()
        self.x_labels = {}