Skip to content

display

Display subsystem for tables and plots.

This package contains user-facing facades and backend implementations to render tabular data and plots in different environments.

  • Tables: see :mod:easydiffraction.display.tables and the engines in :mod:easydiffraction.display.tablers. - Plots: see :mod:easydiffraction.display.plotting and the engines in :mod:easydiffraction.display.plotters.

base

Common base classes for display components and their factories.

RendererBase

Bases: SingletonBase, ABC

Base class for display components with pluggable engines.

Subclasses provide a factory and a default engine. This class manages the active backend instance and exposes helpers to inspect supported engines in a table-friendly format.

Source code in src/easydiffraction/display/base.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
class RendererBase(SingletonBase, ABC):
    """
    Base class for display components with pluggable engines.

    Subclasses provide a factory and a default engine. This class
    manages the active backend instance and exposes helpers to inspect
    supported engines in a table-friendly format.
    """

    def __init__(self) -> None:
        self._engine = self._default_engine()
        self._backend = self._factory().create(self._engine)

    @classmethod
    @abstractmethod
    def _factory(cls) -> type[RendererFactoryBase]:
        """Return the factory class for this renderer type."""
        raise NotImplementedError

    @classmethod
    @abstractmethod
    def _default_engine(cls) -> str:
        """Return the default engine name for this renderer."""
        raise NotImplementedError

    @property
    def engine(self) -> str:
        """
        Return the name of the currently active rendering engine.

        Returns
        -------
        str
            Identifier of the active engine.
        """
        return self._engine

    @engine.setter
    def engine(self, new_engine: str) -> None:
        """
        Switch to a different rendering engine.

        Parameters
        ----------
        new_engine : str
            Identifier of the engine to activate.  Must be a key
            returned by ``_factory()._registry()``.
        """
        if new_engine == self._engine:
            log.info(f"Engine is already set to '{new_engine}'. No change made.")
            return
        try:
            self._backend = self._factory().create(new_engine)
        except ValueError as exc:
            # Log a friendly message and leave engine unchanged
            log.warning(str(exc))
            return
        else:
            self._engine = new_engine
            console.paragraph('Current engine changed to')
            console.print(f"'{self._engine}'")

    @abstractmethod
    def show_config(self) -> None:
        """Display the current renderer configuration."""
        raise NotImplementedError

    def show_supported_engines(self) -> None:
        """List supported engines with descriptions in a table."""
        headers = [
            ('Engine', 'left'),
            ('Description', 'left'),
        ]
        rows = self._factory().descriptions()
        df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(headers))
        console.paragraph('Supported engines')
        # Delegate table rendering to the TableRenderer singleton
        from easydiffraction.display.tables import TableRenderer  # noqa: PLC0415

        TableRenderer.get().render(df)

    def show_current_engine(self) -> None:
        """Display the currently selected engine."""
        console.paragraph('Current engine')
        console.print(f"'{self._engine}'")

engine property writable

Return the name of the currently active rendering engine.

Returns:

Type Description
str

Identifier of the active engine.

show_config() abstractmethod

Display the current renderer configuration.

Source code in src/easydiffraction/display/base.py
79
80
81
82
@abstractmethod
def show_config(self) -> None:
    """Display the current renderer configuration."""
    raise NotImplementedError

show_current_engine()

Display the currently selected engine.

Source code in src/easydiffraction/display/base.py
 98
 99
100
101
def show_current_engine(self) -> None:
    """Display the currently selected engine."""
    console.paragraph('Current engine')
    console.print(f"'{self._engine}'")

show_supported_engines()

List supported engines with descriptions in a table.

Source code in src/easydiffraction/display/base.py
84
85
86
87
88
89
90
91
92
93
94
95
96
def show_supported_engines(self) -> None:
    """List supported engines with descriptions in a table."""
    headers = [
        ('Engine', 'left'),
        ('Description', 'left'),
    ]
    rows = self._factory().descriptions()
    df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(headers))
    console.paragraph('Supported engines')
    # Delegate table rendering to the TableRenderer singleton
    from easydiffraction.display.tables import TableRenderer  # noqa: PLC0415

    TableRenderer.get().render(df)

RendererFactoryBase

Bases: ABC

Base factory that manages discovery and creation of backends.

Source code in src/easydiffraction/display/base.py
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
class RendererFactoryBase(ABC):
    """Base factory that manages discovery and creation of backends."""

    @classmethod
    def create(cls, engine_name: str) -> object:
        """
        Create a backend instance for the given engine.

        Parameters
        ----------
        engine_name : str
            Identifier of the engine to instantiate as listed in
            ``_registry()``.

        Returns
        -------
        object
            A new backend instance corresponding to ``engine_name``.

        Raises
        ------
        ValueError
            If the engine name is not supported.
        """
        registry = cls._registry()
        if engine_name not in registry:
            supported = list(registry.keys())
            msg = f"Unsupported engine '{engine_name}'. Supported engines: {supported}"
            raise ValueError(msg)
        engine_class = registry[engine_name]['class']
        return engine_class()

    @classmethod
    def supported_engines(cls) -> list[str]:
        """Return a list of supported engine identifiers."""
        return list(cls._registry().keys())

    @classmethod
    def descriptions(cls) -> list[tuple[str, str]]:
        """Return (name, description) pairs for each engine."""
        items = cls._registry().items()
        return [(name, config.get('description')) for name, config in items]

    @classmethod
    @abstractmethod
    def _registry(cls) -> dict:
        """
        Return engine registry. Implementations must provide this.

        The returned mapping should have keys as engine names and values
        as a config dict with 'description' and 'class'. Lazy imports
        are allowed to avoid circular dependencies.
        """
        raise NotImplementedError

create(engine_name) classmethod

Create a backend instance for the given engine.

Parameters:

Name Type Description Default
engine_name str

Identifier of the engine to instantiate as listed in _registry().

required

Returns:

Type Description
object

A new backend instance corresponding to engine_name.

Raises:

Type Description
ValueError

If the engine name is not supported.

Source code in src/easydiffraction/display/base.py
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
@classmethod
def create(cls, engine_name: str) -> object:
    """
    Create a backend instance for the given engine.

    Parameters
    ----------
    engine_name : str
        Identifier of the engine to instantiate as listed in
        ``_registry()``.

    Returns
    -------
    object
        A new backend instance corresponding to ``engine_name``.

    Raises
    ------
    ValueError
        If the engine name is not supported.
    """
    registry = cls._registry()
    if engine_name not in registry:
        supported = list(registry.keys())
        msg = f"Unsupported engine '{engine_name}'. Supported engines: {supported}"
        raise ValueError(msg)
    engine_class = registry[engine_name]['class']
    return engine_class()

descriptions() classmethod

Return (name, description) pairs for each engine.

Source code in src/easydiffraction/display/base.py
141
142
143
144
145
@classmethod
def descriptions(cls) -> list[tuple[str, str]]:
    """Return (name, description) pairs for each engine."""
    items = cls._registry().items()
    return [(name, config.get('description')) for name, config in items]

supported_engines() classmethod

Return a list of supported engine identifiers.

Source code in src/easydiffraction/display/base.py
136
137
138
139
@classmethod
def supported_engines(cls) -> list[str]:
    """Return a list of supported engine identifiers."""
    return list(cls._registry().keys())

plotters

Plotting backends.

This subpackage implements plotting engines used by the high-level plotting facade:

  • :mod:.ascii for terminal-friendly ASCII plots. - :mod:.plotly for interactive plots in notebooks or browsers.

ascii

ASCII plotting backend.

Renders compact line charts in the terminal using asciichartpy. This backend is well suited for quick feedback in CLI environments and keeps a consistent API with other plotters.

AsciiPlotter

Bases: PlotterBase

Terminal-based plotter using ASCII art.

Source code in src/easydiffraction/display/plotters/ascii.py
 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
class AsciiPlotter(PlotterBase):
    """Terminal-based plotter using ASCII art."""

    @staticmethod
    def _get_legend_item(label: str) -> str:
        """
        Return a colored legend entry for a given series label.

        The legend uses a colored line matching the series color and the
        human-readable name from :data:`SERIES_CONFIG`.

        Parameters
        ----------
        label : str
            Series identifier (e.g., ``'meas'``).

        Returns
        -------
        str
            A formatted legend string with color escapes.
        """
        color_start = DEFAULT_COLORS[label]
        color_end = asciichartpy.reset
        line = '────'
        name = SERIES_CONFIG[label]['name']
        return f'{color_start}{line}{color_end} {name}'

    def plot_powder(
        self,
        x: object,
        y_series: object,
        labels: object,
        axes_labels: object,
        title: str,
        height: int | None = None,
    ) -> None:
        """
        Render a line plot for powder diffraction data.

        Suitable for powder diffraction data where intensity is plotted
        against an x-axis variable (2θ, TOF, d-spacing). Uses ASCII
        characters for terminal display.

        Parameters
        ----------
        x : object
            1D array-like of x values (only used for range display).
        y_series : object
            Sequence of y arrays to plot.
        labels : object
            Series identifiers corresponding to y_series.
        axes_labels : object
            Ignored; kept for API compatibility.
        title : str
            Figure title printed above the chart.
        height : int | None, default=None
            Number of text rows to allocate for the chart.
        """
        # Intentionally unused; kept for a consistent display API
        del axes_labels
        legend = '\n'.join([self._get_legend_item(label) for label in labels])

        if height is None:
            height = DEFAULT_HEIGHT
        colors = [DEFAULT_COLORS[label] for label in labels]
        config = {'height': height, 'colors': colors}
        y_series = [y.tolist() for y in y_series]

        chart = asciichartpy.plot(y_series, config)

        console.paragraph(f'{title}')  # TODO: f''?
        console.print(
            f'Displaying data for selected x-range from {x[0]} to {x[-1]} ({len(x)} points)'
        )
        console.print(f'Legend:\n{legend}')

        padded = '\n'.join(' ' + line for line in chart.splitlines())

        print(padded)

    @staticmethod
    def plot_single_crystal(
        x_calc: object,
        y_meas: object,
        y_meas_su: object,
        axes_labels: object,
        title: str,
        height: int | None = None,
    ) -> None:
        """
        Render a scatter plot for single crystal diffraction data.

        Creates an ASCII scatter plot showing measured vs calculated
        values with a diagonal reference line.

        Parameters
        ----------
        x_calc : object
            1D array-like of calculated values (x-axis).
        y_meas : object
            1D array-like of measured values (y-axis).
        y_meas_su : object
            1D array-like of measurement uncertainties (ignored in ASCII
            mode).
        axes_labels : object
            Pair of strings for the x and y titles.
        title : str
            Figure title.
        height : int | None, default=None
            Number of text rows for the chart (default: 15).
        """
        # Intentionally unused; ASCII scatter doesn't show error bars
        del y_meas_su

        if height is None:
            height = DEFAULT_HEIGHT
        width = 60  # TODO: Make width configurable

        # Determine axis limits
        vmin = float(min(np.min(y_meas), np.min(x_calc)))
        vmax = float(max(np.max(y_meas), np.max(x_calc)))
        pad = 0.05 * (vmax - vmin) if vmax > vmin else 1.0
        vmin -= pad
        vmax += pad

        # Create empty grid
        grid = [[' ' for _ in range(width)] for _ in range(height)]

        # Draw diagonal line (calc == meas)
        for i in range(min(width, height)):
            row = height - 1 - int(i * height / width)
            col = i
            if 0 <= row < height and 0 <= col < width:
                grid[row][col] = '·'

        # Plot data points
        for xv, yv in zip(x_calc, y_meas, strict=False):
            col = int((xv - vmin) / (vmax - vmin) * (width - 1))
            row = height - 1 - int((yv - vmin) / (vmax - vmin) * (height - 1))
            if 0 <= row < height and 0 <= col < width:
                grid[row][col] = '●'

        # Build chart string with axes
        chart_lines = []
        for row in grid:
            label = '│'
            chart_lines.append(label + ''.join(row))

        # X-axis
        x_axis = '└' + '─' * width

        # Print output
        console.paragraph(f'{title}')
        console.print(f'{axes_labels[1]}')
        for line in chart_lines:
            print(f'  {line}')
        print(f'  {x_axis}')
        console.print(f'{" " * (width - 3)}{axes_labels[0]}')

    @staticmethod
    def plot_scatter(
        x: object,
        y: object,
        sy: object,
        axes_labels: object,
        title: str,
        height: int | None = None,
    ) -> None:
        """Render a scatter plot with error bars in ASCII."""
        _ = x, sy  # ASCII backend does not use x ticks or error bars

        if height is None:
            height = DEFAULT_HEIGHT

        config = {'height': height, 'colors': [asciichartpy.blue]}
        chart = asciichartpy.plot([list(y)], config)

        console.paragraph(f'{title}')
        console.print(f'{axes_labels[1]} vs {axes_labels[0]}')
        padded = '\n'.join(' ' + line for line in chart.splitlines())
        print(padded)
plot_powder(x, y_series, labels, axes_labels, title, height=None)

Render a line plot for powder diffraction data.

Suitable for powder diffraction data where intensity is plotted against an x-axis variable (2θ, TOF, d-spacing). Uses ASCII characters for terminal display.

Parameters:

Name Type Description Default
x object

1D array-like of x values (only used for range display).

required
y_series object

Sequence of y arrays to plot.

required
labels object

Series identifiers corresponding to y_series.

required
axes_labels object

Ignored; kept for API compatibility.

required
title str

Figure title printed above the chart.

required
height int | None

Number of text rows to allocate for the chart.

None
Source code in src/easydiffraction/display/plotters/ascii.py
 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
def plot_powder(
    self,
    x: object,
    y_series: object,
    labels: object,
    axes_labels: object,
    title: str,
    height: int | None = None,
) -> None:
    """
    Render a line plot for powder diffraction data.

    Suitable for powder diffraction data where intensity is plotted
    against an x-axis variable (2θ, TOF, d-spacing). Uses ASCII
    characters for terminal display.

    Parameters
    ----------
    x : object
        1D array-like of x values (only used for range display).
    y_series : object
        Sequence of y arrays to plot.
    labels : object
        Series identifiers corresponding to y_series.
    axes_labels : object
        Ignored; kept for API compatibility.
    title : str
        Figure title printed above the chart.
    height : int | None, default=None
        Number of text rows to allocate for the chart.
    """
    # Intentionally unused; kept for a consistent display API
    del axes_labels
    legend = '\n'.join([self._get_legend_item(label) for label in labels])

    if height is None:
        height = DEFAULT_HEIGHT
    colors = [DEFAULT_COLORS[label] for label in labels]
    config = {'height': height, 'colors': colors}
    y_series = [y.tolist() for y in y_series]

    chart = asciichartpy.plot(y_series, config)

    console.paragraph(f'{title}')  # TODO: f''?
    console.print(
        f'Displaying data for selected x-range from {x[0]} to {x[-1]} ({len(x)} points)'
    )
    console.print(f'Legend:\n{legend}')

    padded = '\n'.join(' ' + line for line in chart.splitlines())

    print(padded)
plot_scatter(x, y, sy, axes_labels, title, height=None) staticmethod

Render a scatter plot with error bars in ASCII.

Source code in src/easydiffraction/display/plotters/ascii.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
@staticmethod
def plot_scatter(
    x: object,
    y: object,
    sy: object,
    axes_labels: object,
    title: str,
    height: int | None = None,
) -> None:
    """Render a scatter plot with error bars in ASCII."""
    _ = x, sy  # ASCII backend does not use x ticks or error bars

    if height is None:
        height = DEFAULT_HEIGHT

    config = {'height': height, 'colors': [asciichartpy.blue]}
    chart = asciichartpy.plot([list(y)], config)

    console.paragraph(f'{title}')
    console.print(f'{axes_labels[1]} vs {axes_labels[0]}')
    padded = '\n'.join(' ' + line for line in chart.splitlines())
    print(padded)
plot_single_crystal(x_calc, y_meas, y_meas_su, axes_labels, title, height=None) staticmethod

Render a scatter plot for single crystal diffraction data.

Creates an ASCII scatter plot showing measured vs calculated values with a diagonal reference line.

Parameters:

Name Type Description Default
x_calc object

1D array-like of calculated values (x-axis).

required
y_meas object

1D array-like of measured values (y-axis).

required
y_meas_su object

1D array-like of measurement uncertainties (ignored in ASCII mode).

required
axes_labels object

Pair of strings for the x and y titles.

required
title str

Figure title.

required
height int | None

Number of text rows for the chart (default: 15).

None
Source code in src/easydiffraction/display/plotters/ascii.py
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
@staticmethod
def plot_single_crystal(
    x_calc: object,
    y_meas: object,
    y_meas_su: object,
    axes_labels: object,
    title: str,
    height: int | None = None,
) -> None:
    """
    Render a scatter plot for single crystal diffraction data.

    Creates an ASCII scatter plot showing measured vs calculated
    values with a diagonal reference line.

    Parameters
    ----------
    x_calc : object
        1D array-like of calculated values (x-axis).
    y_meas : object
        1D array-like of measured values (y-axis).
    y_meas_su : object
        1D array-like of measurement uncertainties (ignored in ASCII
        mode).
    axes_labels : object
        Pair of strings for the x and y titles.
    title : str
        Figure title.
    height : int | None, default=None
        Number of text rows for the chart (default: 15).
    """
    # Intentionally unused; ASCII scatter doesn't show error bars
    del y_meas_su

    if height is None:
        height = DEFAULT_HEIGHT
    width = 60  # TODO: Make width configurable

    # Determine axis limits
    vmin = float(min(np.min(y_meas), np.min(x_calc)))
    vmax = float(max(np.max(y_meas), np.max(x_calc)))
    pad = 0.05 * (vmax - vmin) if vmax > vmin else 1.0
    vmin -= pad
    vmax += pad

    # Create empty grid
    grid = [[' ' for _ in range(width)] for _ in range(height)]

    # Draw diagonal line (calc == meas)
    for i in range(min(width, height)):
        row = height - 1 - int(i * height / width)
        col = i
        if 0 <= row < height and 0 <= col < width:
            grid[row][col] = '·'

    # Plot data points
    for xv, yv in zip(x_calc, y_meas, strict=False):
        col = int((xv - vmin) / (vmax - vmin) * (width - 1))
        row = height - 1 - int((yv - vmin) / (vmax - vmin) * (height - 1))
        if 0 <= row < height and 0 <= col < width:
            grid[row][col] = '●'

    # Build chart string with axes
    chart_lines = []
    for row in grid:
        label = '│'
        chart_lines.append(label + ''.join(row))

    # X-axis
    x_axis = '└' + '─' * width

    # Print output
    console.paragraph(f'{title}')
    console.print(f'{axes_labels[1]}')
    for line in chart_lines:
        print(f'  {line}')
    print(f'  {x_axis}')
    console.print(f'{" " * (width - 3)}{axes_labels[0]}')

base

Abstract base and shared constants for plotting backends.

PlotterBase

Bases: ABC

Abstract base for plotting backends.

Implementations accept x values, multiple y-series, optional labels and render a plot to the chosen medium.

Two main plot types are supported: - plot_powder: Line plots for powder diffraction patterns (intensity vs. 2θ/TOF/d-spacing). - plot_single_crystal: Scatter plots comparing measured vs. calculated values (e.g., F²meas vs F²calc for single crystal).

Source code in src/easydiffraction/display/plotters/base.py
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
class PlotterBase(ABC):
    """
    Abstract base for plotting backends.

    Implementations accept x values, multiple y-series, optional labels
    and render a plot to the chosen medium.

    Two main plot types are supported: - ``plot_powder``: Line plots for
    powder diffraction patterns   (intensity vs. 2θ/TOF/d-spacing). -
    ``plot_single_crystal``: Scatter plots comparing measured vs.
    calculated values (e.g., F²meas vs F²calc for single crystal).
    """

    _supports_graphical_heatmap: bool = False

    @abstractmethod
    def plot_powder(
        self,
        x: object,
        y_series: object,
        labels: object,
        axes_labels: object,
        title: str,
        height: int | None,
    ) -> None:
        """
        Render a line plot for powder diffraction data.

        Suitable for powder diffraction data where intensity is plotted
        against an x-axis variable (2θ, TOF, d-spacing).

        Parameters
        ----------
        x : object
            1D array of x-axis values.
        y_series : object
            Sequence of y arrays to plot.
        labels : object
            Identifiers corresponding to y_series.
        axes_labels : object
            Pair of strings for the x and y titles.
        title : str
            Figure title.
        height : int | None
            Backend-specific height (text rows or pixels).
        """

    @abstractmethod
    def plot_single_crystal(
        self,
        x_calc: object,
        y_meas: object,
        y_meas_su: object,
        axes_labels: object,
        title: str,
        height: int | None,
    ) -> None:
        """
        Render a scatter plot for single crystal diffraction data.

        Suitable for single crystal diffraction data where measured
        values are plotted against calculated values with error bars.

        Parameters
        ----------
        x_calc : object
            1D array of calculated values (x-axis).
        y_meas : object
            1D array of measured values (y-axis).
        y_meas_su : object
            1D array of measurement uncertainties.
        axes_labels : object
            Pair of strings for the x and y titles.
        title : str
            Figure title.
        height : int | None
            Backend-specific height (text rows or pixels).
        """

    @abstractmethod
    def plot_scatter(
        self,
        x: object,
        y: object,
        sy: object,
        axes_labels: object,
        title: str,
        height: int | None,
    ) -> None:
        """
        Render a scatter plot with error bars.

        Parameters
        ----------
        x : object
            1-D array of x-axis values.
        y : object
            1-D array of y-axis values.
        sy : object
            1-D array of y uncertainties.
        axes_labels : object
            Pair of strings for x and y axis titles.
        title : str
            Figure title.
        height : int | None
            Backend-specific height (text rows or pixels).
        """

    def plot_correlation_heatmap(
        self,
        corr_df: object,
        title: str,
        threshold: float | None,
        precision: int,
    ) -> None:
        """
        Render a graphical heatmap for a correlation matrix.

        The default implementation does nothing. Graphical backends
        (e.g. Plotly) override this method and set
        ``_supports_graphical_heatmap = True`` so the facade knows a
        heatmap was rendered.

        Parameters
        ----------
        corr_df : object
            Square correlation DataFrame.
        title : str
            Figure title.
        threshold : float | None
            Absolute-correlation cutoff used for value labels.
        precision : int
            Number of decimals to show in labels and hover text.
        """
        # Intentionally unused; accepted for API compatibility with
        # graphical backends that override this method.
        _ = self._supports_graphical_heatmap
        del corr_df, title, threshold, precision
plot_correlation_heatmap(corr_df, title, threshold, precision)

Render a graphical heatmap for a correlation matrix.

The default implementation does nothing. Graphical backends (e.g. Plotly) override this method and set _supports_graphical_heatmap = True so the facade knows a heatmap was rendered.

Parameters:

Name Type Description Default
corr_df object

Square correlation DataFrame.

required
title str

Figure title.

required
threshold float | None

Absolute-correlation cutoff used for value labels.

required
precision int

Number of decimals to show in labels and hover text.

required
Source code in src/easydiffraction/display/plotters/base.py
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
def plot_correlation_heatmap(
    self,
    corr_df: object,
    title: str,
    threshold: float | None,
    precision: int,
) -> None:
    """
    Render a graphical heatmap for a correlation matrix.

    The default implementation does nothing. Graphical backends
    (e.g. Plotly) override this method and set
    ``_supports_graphical_heatmap = True`` so the facade knows a
    heatmap was rendered.

    Parameters
    ----------
    corr_df : object
        Square correlation DataFrame.
    title : str
        Figure title.
    threshold : float | None
        Absolute-correlation cutoff used for value labels.
    precision : int
        Number of decimals to show in labels and hover text.
    """
    # Intentionally unused; accepted for API compatibility with
    # graphical backends that override this method.
    _ = self._supports_graphical_heatmap
    del corr_df, title, threshold, precision
plot_powder(x, y_series, labels, axes_labels, title, height) abstractmethod

Render a line plot for powder diffraction data.

Suitable for powder diffraction data where intensity is plotted against an x-axis variable (2θ, TOF, d-spacing).

Parameters:

Name Type Description Default
x object

1D array of x-axis values.

required
y_series object

Sequence of y arrays to plot.

required
labels object

Identifiers corresponding to y_series.

required
axes_labels object

Pair of strings for the x and y titles.

required
title str

Figure title.

required
height int | None

Backend-specific height (text rows or pixels).

required
Source code in src/easydiffraction/display/plotters/base.py
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
@abstractmethod
def plot_powder(
    self,
    x: object,
    y_series: object,
    labels: object,
    axes_labels: object,
    title: str,
    height: int | None,
) -> None:
    """
    Render a line plot for powder diffraction data.

    Suitable for powder diffraction data where intensity is plotted
    against an x-axis variable (2θ, TOF, d-spacing).

    Parameters
    ----------
    x : object
        1D array of x-axis values.
    y_series : object
        Sequence of y arrays to plot.
    labels : object
        Identifiers corresponding to y_series.
    axes_labels : object
        Pair of strings for the x and y titles.
    title : str
        Figure title.
    height : int | None
        Backend-specific height (text rows or pixels).
    """
plot_scatter(x, y, sy, axes_labels, title, height) abstractmethod

Render a scatter plot with error bars.

Parameters:

Name Type Description Default
x object

1-D array of x-axis values.

required
y object

1-D array of y-axis values.

required
sy object

1-D array of y uncertainties.

required
axes_labels object

Pair of strings for x and y axis titles.

required
title str

Figure title.

required
height int | None

Backend-specific height (text rows or pixels).

required
Source code in src/easydiffraction/display/plotters/base.py
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
@abstractmethod
def plot_scatter(
    self,
    x: object,
    y: object,
    sy: object,
    axes_labels: object,
    title: str,
    height: int | None,
) -> None:
    """
    Render a scatter plot with error bars.

    Parameters
    ----------
    x : object
        1-D array of x-axis values.
    y : object
        1-D array of y-axis values.
    sy : object
        1-D array of y uncertainties.
    axes_labels : object
        Pair of strings for x and y axis titles.
    title : str
        Figure title.
    height : int | None
        Backend-specific height (text rows or pixels).
    """
plot_single_crystal(x_calc, y_meas, y_meas_su, axes_labels, title, height) abstractmethod

Render a scatter plot for single crystal diffraction data.

Suitable for single crystal diffraction data where measured values are plotted against calculated values with error bars.

Parameters:

Name Type Description Default
x_calc object

1D array of calculated values (x-axis).

required
y_meas object

1D array of measured values (y-axis).

required
y_meas_su object

1D array of measurement uncertainties.

required
axes_labels object

Pair of strings for the x and y titles.

required
title str

Figure title.

required
height int | None

Backend-specific height (text rows or pixels).

required
Source code in src/easydiffraction/display/plotters/base.py
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
@abstractmethod
def plot_single_crystal(
    self,
    x_calc: object,
    y_meas: object,
    y_meas_su: object,
    axes_labels: object,
    title: str,
    height: int | None,
) -> None:
    """
    Render a scatter plot for single crystal diffraction data.

    Suitable for single crystal diffraction data where measured
    values are plotted against calculated values with error bars.

    Parameters
    ----------
    x_calc : object
        1D array of calculated values (x-axis).
    y_meas : object
        1D array of measured values (y-axis).
    y_meas_su : object
        1D array of measurement uncertainties.
    axes_labels : object
        Pair of strings for the x and y titles.
    title : str
        Figure title.
    height : int | None
        Backend-specific height (text rows or pixels).
    """

XAxisType

Bases: StrEnum

X-axis types for diffraction plots.

Values match attribute names in data models for direct use with getattr(pattern, x_axis).

Source code in src/easydiffraction/display/plotters/base.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class XAxisType(StrEnum):
    """
    X-axis types for diffraction plots.

    Values match attribute names in data models for direct use with
    ``getattr(pattern, x_axis)``.
    """

    TWO_THETA = 'two_theta'
    TIME_OF_FLIGHT = 'time_of_flight'
    R = 'x'

    INTENSITY_CALC = 'intensity_calc'

    D_SPACING = 'd_spacing'
    SIN_THETA_OVER_LAMBDA = 'sin_theta_over_lambda'

plotly

Plotly plotting backend.

Provides an interactive plotting implementation using Plotly. In notebooks, figures are displayed inline; in other environments a browser renderer may be used depending on configuration.

PlotlyPlotter

Bases: PlotterBase

Interactive plotter using Plotly for notebooks and browsers.

Source code in src/easydiffraction/display/plotters/plotly.py
 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
class PlotlyPlotter(PlotterBase):
    """Interactive plotter using Plotly for notebooks and browsers."""

    _supports_graphical_heatmap: bool = True

    def __init__(self) -> None:
        if hasattr(pio, 'templates'):
            pio.templates.default = self._default_template_name()
        if in_pycharm():
            pio.renderers.default = 'browser'

    @staticmethod
    def _is_dark_mode() -> bool:
        """
        Return whether the active plotting context should use dark mode.

        In Jupyter, prefer notebook dark-mode detection. Outside
        Jupyter, fall back to the system theme via ``darkdetect``.

        Returns
        -------
        bool
            ``True`` for dark mode, otherwise ``False``.
        """
        return is_dark() if in_jupyter() else darkdetect.isDark()

    @classmethod
    def _default_template_name(cls) -> str:
        """
        Return the Plotly template matching the active theme.

        In Jupyter, prefer notebook dark-mode detection. Outside
        Jupyter, fall back to the system theme via ``darkdetect``.

        Returns
        -------
        str
            Either ``'plotly_dark'`` or ``'plotly_white'``.
        """
        return 'plotly_dark' if cls._is_dark_mode() else 'plotly_white'

    @classmethod
    def _correlation_colorscale(cls) -> list[tuple[float, str]]:
        """
        Return a diverging colorscale for correlation heatmaps.

        Dark mode uses black at zero correlation for lower visual
        prominence. Light mode uses white at zero correlation.

        Returns
        -------
        list[tuple[float, str]]
            Plotly-compatible colorscale definition.
        """
        if cls._is_dark_mode():
            return [
                (0.0, '#d73027'),
                (0.5, '#000000'),
                (1.0, '#4575b4'),
            ]
        return [
            (0.0, '#d73027'),
            (0.5, '#f7f7f7'),
            (1.0, '#4575b4'),
        ]

    @classmethod
    def _correlation_grid_color(cls) -> str:
        """
        Return the boundary-line color for correlation heatmaps.

        Returns
        -------
        str
            RGBA color string tuned for the active theme.
        """
        if cls._is_dark_mode():
            return 'rgba(110, 145, 190, 0.35)'
        return 'rgba(120, 140, 160, 0.28)'

    def plot_correlation_heatmap(
        self,
        corr_df: object,
        title: str,
        threshold: float | None,
        precision: int,
    ) -> None:
        """
        Render a Plotly heatmap for a correlation matrix.

        Parameters
        ----------
        corr_df : object
            Square correlation DataFrame.
        title : str
            Figure title.
        threshold : float | None
            Absolute-correlation cutoff used for value labels.
        precision : int
            Number of decimals to show in labels and hover text.
        """
        num_rows, num_cols = corr_df.shape
        x_edges = np.arange(num_cols + 1, dtype=float)
        y_edges = np.arange(num_rows + 1, dtype=float)
        x_centers = np.arange(num_cols, dtype=float) + 0.5
        y_centers = np.arange(num_rows, dtype=float) + 0.5
        grid_color = self._correlation_grid_color()

        heatmap = go.Heatmap(
            z=corr_df.to_numpy(),
            x=x_edges,
            y=y_edges,
            zmin=-1.0,
            zmax=1.0,
            zmid=0.0,
            colorscale=self._correlation_colorscale(),
            colorbar={
                'title': {'text': ''},
                'lenmode': 'fraction',
                'len': 1.0,
                'y': 0.5,
                'yanchor': 'middle',
            },
            hoverongaps=False,
            hovertemplate=f'x: %{{x}}<br>y: %{{y}}<br>corr: %{{z:.{precision}f}}<extra></extra>',
        )
        label_trace = self._get_correlation_label_trace(
            corr_df,
            x_centers=x_centers,
            y_centers=y_centers,
            threshold=threshold,
            precision=precision,
        )

        shapes = [
            {
                'type': 'line',
                'x0': float(x_pos),
                'x1': float(x_pos),
                'y0': 0.0,
                'y1': float(num_rows),
                'xref': 'x',
                'yref': 'y',
                'layer': 'above',
                'line': {'color': grid_color, 'width': 1},
            }
            for x_pos in x_edges[1:-1]
        ]
        shapes.extend(
            {
                'type': 'line',
                'x0': 0.0,
                'x1': float(num_cols),
                'y0': float(y_pos),
                'y1': float(y_pos),
                'xref': 'x',
                'yref': 'y',
                'layer': 'above',
                'line': {'color': grid_color, 'width': 1},
            }
            for y_pos in y_edges[1:-1]
        )
        shapes.append({
            'type': 'rect',
            'x0': 0.0,
            'x1': 1.0,
            'y0': 0.0,
            'y1': 1.0,
            'xref': 'paper',
            'yref': 'paper',
            'layer': 'above',
            'line': {'color': grid_color, 'width': 1},
            'fillcolor': 'rgba(0, 0, 0, 0)',
        })

        layout = self._get_layout(
            title,
            ['Parameter', 'Parameter'],
            shapes=shapes,
        )
        traces = [heatmap]
        if label_trace is not None:
            traces.append(label_trace)
        fig = self._get_figure(traces, layout)
        fig.update_xaxes(
            side='bottom',
            tickangle=-10,
            automargin=True,
            tickmode='array',
            tickvals=x_centers.tolist(),
            ticktext=corr_df.columns.tolist(),
            range=[0.0, float(num_cols)],
            showgrid=False,
            showline=False,
            mirror=False,
            ticks='',
            layer='above traces',
        )
        fig.update_yaxes(
            autorange='reversed',
            automargin=True,
            tickmode='array',
            tickvals=y_centers.tolist(),
            ticktext=corr_df.index.tolist(),
            ticklabelstandoff=8,
            range=[float(num_rows), 0.0],
            showgrid=False,
            showline=False,
            mirror=False,
            ticks='',
            layer='above traces',
        )
        self._show_figure(fig)

    @classmethod
    def _correlation_label_color(cls) -> str:
        """
        Return the text color used for in-cell correlation labels.

        Returns
        -------
        str
            Hex color string.
        """
        return '#f5f5f5'

    @classmethod
    def _get_correlation_label_trace(
        cls,
        corr_df: object,
        x_centers: np.ndarray,
        y_centers: np.ndarray,
        threshold: float | None,
        precision: int,
    ) -> object | None:
        """
        Build a text trace for visible correlation values.

        Parameters
        ----------
        corr_df : object
            Correlation DataFrame to annotate.
        x_centers : np.ndarray
            Cell center x coordinates.
        y_centers : np.ndarray
            Cell center y coordinates.
        threshold : float | None
            Minimum absolute correlation required for a label.
        precision : int
            Number of decimals for rendered labels.

        Returns
        -------
        object | None
            Plotly text trace, or ``None`` when no labels should be
            shown.
        """
        values = corr_df.to_numpy()
        label_x = []
        label_y = []
        label_text = []

        for row_idx, row in enumerate(values):
            for col_idx, value in enumerate(row):
                if np.isnan(value):
                    continue
                if threshold is not None and threshold > 0 and abs(float(value)) < threshold:
                    continue
                label_x.append(float(x_centers[col_idx]))
                label_y.append(float(y_centers[row_idx]))
                label_text.append(f'{float(value):.{precision}f}')

        if not label_text:
            return None

        return go.Scatter(
            x=label_x,
            y=label_y,
            mode='text',
            text=label_text,
            textposition='middle center',
            textfont={'color': cls._correlation_label_color()},
            hoverinfo='skip',
            showlegend=False,
        )

    @staticmethod
    def _get_powder_trace(
        x: object,
        y: object,
        label: str,
    ) -> object:
        """
        Create a Plotly trace for powder diffraction data.

        Parameters
        ----------
        x : object
            1D array-like of x-axis values.
        y : object
            1D array- like of y-axis values.
        label : str
            Series identifier (``'meas'``, ``'calc'``, or ``'resid'``).

        Returns
        -------
        object
            A configured :class:`plotly.graph_objects.Scatter` trace.
        """
        mode = SERIES_CONFIG[label]['mode']
        name = SERIES_CONFIG[label]['name']
        color = DEFAULT_COLORS[label]
        line = {'color': color}

        return go.Scatter(
            x=x,
            y=y,
            line=line,
            mode=mode,
            name=name,
        )

    @staticmethod
    def _get_single_crystal_trace(
        x_calc: object,
        y_meas: object,
        y_meas_su: object,
    ) -> object:
        """
        Create a Plotly trace for single crystal diffraction data.

        Parameters
        ----------
        x_calc : object
            1D array-like of calculated values (x-axis).
        y_meas : object
            1D array-like of measured values (y-axis).
        y_meas_su : object
            1D array-like of measurement uncertainties.

        Returns
        -------
        object
            A configured :class:`plotly.graph_objects.Scatter` trace
            with markers and error bars.
        """
        return go.Scatter(
            x=x_calc,
            y=y_meas,
            mode='markers',
            marker={
                'symbol': 'circle',
                'size': 10,
                'line': {'width': 0.5},
                'color': DEFAULT_COLORS['meas'],
            },
            error_y={
                'type': 'data',
                'array': y_meas_su,
                'visible': True,
            },
            hovertemplate='calc: %{x}<br>meas: %{y}<br><extra></extra>',
        )

    @staticmethod
    def _get_diagonal_shape() -> dict:
        """
        Create a diagonal reference line shape.

        Returns a y=x diagonal line spanning the plot area using paper
        coordinates (0,0) to (1,1).

        Returns
        -------
        dict
            A dict configuring a diagonal line shape.
        """
        return {
            'type': 'line',
            'x0': 0,
            'y0': 0,
            'x1': 1,
            'y1': 1,
            'xref': 'paper',
            'yref': 'paper',
            'layer': 'below',
            'line': {'width': 0.5},
        }

    @staticmethod
    def _get_config() -> dict:
        """
        Return the Plotly figure configuration.

        Returns
        -------
        dict
            A dict with display and mode bar settings.
        """
        return {
            'displaylogo': False,
            'modeBarButtonsToRemove': [
                'select2d',
                'lasso2d',
                'zoomIn2d',
                'zoomOut2d',
                'autoScale2d',
            ],
        }

    @staticmethod
    def _get_figure(
        data: object,
        layout: object,
    ) -> object:
        """
        Create and configure a Plotly figure.

        Parameters
        ----------
        data : object
            List of traces to include in the figure.
        layout : object
            Layout configuration dict.

        Returns
        -------
        object
            A configured :class:`plotly.graph_objects.Figure`.
        """
        fig = go.Figure(data=data, layout=layout)
        # Format axis ticks:
        # decimals for small numbers, grouped thousands for large
        fig.update_xaxes(tickformat=',.6~g', separatethousands=True)
        fig.update_yaxes(tickformat=',.6~g', separatethousands=True)
        return fig

    def _show_figure(
        self,
        fig: object,
    ) -> None:
        """
        Display a Plotly figure.

        Renders the figure using the appropriate method for the current
        environment (browser for PyCharm, inline HTML for Jupyter).

        Parameters
        ----------
        fig : object
            A :class:`plotly.graph_objects.Figure` to display.
        """
        config = self._get_config()

        if in_pycharm() or display is None or HTML is None:
            fig.show(config=config)
        else:
            html_fig = pio.to_html(
                fig,
                include_plotlyjs='cdn',
                full_html=False,
                config=config,
            )
            display(HTML(html_fig))

    @staticmethod
    def _get_layout(
        title: str,
        axes_labels: object,
        shapes: list | None = None,
    ) -> object:
        """
        Create a Plotly layout configuration.

        Parameters
        ----------
        title : str
            Figure title.
        axes_labels : object
            Pair of strings for the x and y titles.
        shapes : list | None, default=None
            Optional list of shape dicts to overlay on the plot.

        Returns
        -------
        object
            A configured :class:`plotly.graph_objects.Layout`.
        """
        return go.Layout(
            margin={
                'autoexpand': True,
                'r': 30,
                't': 40,
                'b': 45,
            },
            title={
                'text': title,
            },
            legend={
                'xanchor': 'right',
                'x': 1.0,
                'yanchor': 'top',
                'y': 1.0,
            },
            xaxis={
                'title_text': axes_labels[0],
                'showline': True,
                'mirror': True,
                'zeroline': False,
            },
            yaxis={
                'title_text': axes_labels[1],
                'showline': True,
                'mirror': True,
                'zeroline': False,
            },
            shapes=shapes,
        )

    def plot_powder(
        self,
        x: object,
        y_series: object,
        labels: object,
        axes_labels: object,
        title: str,
        height: int | None = None,
    ) -> None:
        """
        Render a line plot for powder diffraction data.

        Suitable for powder diffraction data where intensity is plotted
        against an x-axis variable (2θ, TOF, d-spacing).

        Parameters
        ----------
        x : object
            1D array-like of x-axis values.
        y_series : object
            Sequence of y arrays to plot.
        labels : object
            Series identifiers corresponding to y_series.
        axes_labels : object
            Pair of strings for the x and y titles.
        title : str
            Figure title.
        height : int | None, default=None
            Ignored; Plotly auto-sizes based on renderer.
        """
        # Intentionally unused; accepted for API compatibility
        del height

        data = []
        for idx, y in enumerate(y_series):
            label = labels[idx]
            trace = self._get_powder_trace(x, y, label)
            data.append(trace)

        layout = self._get_layout(
            title,
            axes_labels,
        )

        fig = self._get_figure(data, layout)
        self._show_figure(fig)

    def plot_single_crystal(
        self,
        x_calc: object,
        y_meas: object,
        y_meas_su: object,
        axes_labels: object,
        title: str,
        height: int | None = None,
    ) -> None:
        """
        Render a scatter plot for single crystal diffraction data.

        Suitable for single crystal diffraction data where measured
        values are plotted against calculated values with error bars and
        a diagonal reference line.

        Parameters
        ----------
        x_calc : object
            1D array-like of calculated values (x-axis).
        y_meas : object
            1D array-like of measured values (y-axis).
        y_meas_su : object
            1D array-like of measurement uncertainties.
        axes_labels : object
            Pair of strings for the x and y titles.
        title : str
            Figure title.
        height : int | None, default=None
            Ignored; Plotly auto-sizes based on renderer.
        """
        # Intentionally unused; accepted for API compatibility
        del height

        data = [
            self._get_single_crystal_trace(
                x_calc,
                y_meas,
                y_meas_su,
            )
        ]

        layout = self._get_layout(
            title,
            axes_labels,
            shapes=[self._get_diagonal_shape()],
        )

        fig = self._get_figure(data, layout)
        self._show_figure(fig)

    def plot_scatter(
        self,
        x: object,
        y: object,
        sy: object,
        axes_labels: object,
        title: str,
        height: int | None = None,
    ) -> None:
        """Render a scatter plot with error bars via Plotly."""
        _ = height  # not used by Plotly backend

        trace = go.Scatter(
            x=x,
            y=y,
            mode='markers+lines',
            marker={
                'symbol': 'circle',
                'size': 10,
                'line': {'width': 0.5},
                'color': DEFAULT_COLORS['meas'],
            },
            line={
                'width': 1,
                'color': DEFAULT_COLORS['meas'],
            },
            error_y={
                'type': 'data',
                'array': sy,
                'visible': True,
            },
            hovertemplate='x: %{x}<br>y: %{y}<br><extra></extra>',
        )

        layout = self._get_layout(
            title,
            axes_labels,
        )

        fig = self._get_figure(trace, layout)
        self._show_figure(fig)
plot_correlation_heatmap(corr_df, title, threshold, precision)

Render a Plotly heatmap for a correlation matrix.

Parameters:

Name Type Description Default
corr_df object

Square correlation DataFrame.

required
title str

Figure title.

required
threshold float | None

Absolute-correlation cutoff used for value labels.

required
precision int

Number of decimals to show in labels and hover text.

required
Source code in src/easydiffraction/display/plotters/plotly.py
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
def plot_correlation_heatmap(
    self,
    corr_df: object,
    title: str,
    threshold: float | None,
    precision: int,
) -> None:
    """
    Render a Plotly heatmap for a correlation matrix.

    Parameters
    ----------
    corr_df : object
        Square correlation DataFrame.
    title : str
        Figure title.
    threshold : float | None
        Absolute-correlation cutoff used for value labels.
    precision : int
        Number of decimals to show in labels and hover text.
    """
    num_rows, num_cols = corr_df.shape
    x_edges = np.arange(num_cols + 1, dtype=float)
    y_edges = np.arange(num_rows + 1, dtype=float)
    x_centers = np.arange(num_cols, dtype=float) + 0.5
    y_centers = np.arange(num_rows, dtype=float) + 0.5
    grid_color = self._correlation_grid_color()

    heatmap = go.Heatmap(
        z=corr_df.to_numpy(),
        x=x_edges,
        y=y_edges,
        zmin=-1.0,
        zmax=1.0,
        zmid=0.0,
        colorscale=self._correlation_colorscale(),
        colorbar={
            'title': {'text': ''},
            'lenmode': 'fraction',
            'len': 1.0,
            'y': 0.5,
            'yanchor': 'middle',
        },
        hoverongaps=False,
        hovertemplate=f'x: %{{x}}<br>y: %{{y}}<br>corr: %{{z:.{precision}f}}<extra></extra>',
    )
    label_trace = self._get_correlation_label_trace(
        corr_df,
        x_centers=x_centers,
        y_centers=y_centers,
        threshold=threshold,
        precision=precision,
    )

    shapes = [
        {
            'type': 'line',
            'x0': float(x_pos),
            'x1': float(x_pos),
            'y0': 0.0,
            'y1': float(num_rows),
            'xref': 'x',
            'yref': 'y',
            'layer': 'above',
            'line': {'color': grid_color, 'width': 1},
        }
        for x_pos in x_edges[1:-1]
    ]
    shapes.extend(
        {
            'type': 'line',
            'x0': 0.0,
            'x1': float(num_cols),
            'y0': float(y_pos),
            'y1': float(y_pos),
            'xref': 'x',
            'yref': 'y',
            'layer': 'above',
            'line': {'color': grid_color, 'width': 1},
        }
        for y_pos in y_edges[1:-1]
    )
    shapes.append({
        'type': 'rect',
        'x0': 0.0,
        'x1': 1.0,
        'y0': 0.0,
        'y1': 1.0,
        'xref': 'paper',
        'yref': 'paper',
        'layer': 'above',
        'line': {'color': grid_color, 'width': 1},
        'fillcolor': 'rgba(0, 0, 0, 0)',
    })

    layout = self._get_layout(
        title,
        ['Parameter', 'Parameter'],
        shapes=shapes,
    )
    traces = [heatmap]
    if label_trace is not None:
        traces.append(label_trace)
    fig = self._get_figure(traces, layout)
    fig.update_xaxes(
        side='bottom',
        tickangle=-10,
        automargin=True,
        tickmode='array',
        tickvals=x_centers.tolist(),
        ticktext=corr_df.columns.tolist(),
        range=[0.0, float(num_cols)],
        showgrid=False,
        showline=False,
        mirror=False,
        ticks='',
        layer='above traces',
    )
    fig.update_yaxes(
        autorange='reversed',
        automargin=True,
        tickmode='array',
        tickvals=y_centers.tolist(),
        ticktext=corr_df.index.tolist(),
        ticklabelstandoff=8,
        range=[float(num_rows), 0.0],
        showgrid=False,
        showline=False,
        mirror=False,
        ticks='',
        layer='above traces',
    )
    self._show_figure(fig)
plot_powder(x, y_series, labels, axes_labels, title, height=None)

Render a line plot for powder diffraction data.

Suitable for powder diffraction data where intensity is plotted against an x-axis variable (2θ, TOF, d-spacing).

Parameters:

Name Type Description Default
x object

1D array-like of x-axis values.

required
y_series object

Sequence of y arrays to plot.

required
labels object

Series identifiers corresponding to y_series.

required
axes_labels object

Pair of strings for the x and y titles.

required
title str

Figure title.

required
height int | None

Ignored; Plotly auto-sizes based on renderer.

None
Source code in src/easydiffraction/display/plotters/plotly.py
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
def plot_powder(
    self,
    x: object,
    y_series: object,
    labels: object,
    axes_labels: object,
    title: str,
    height: int | None = None,
) -> None:
    """
    Render a line plot for powder diffraction data.

    Suitable for powder diffraction data where intensity is plotted
    against an x-axis variable (2θ, TOF, d-spacing).

    Parameters
    ----------
    x : object
        1D array-like of x-axis values.
    y_series : object
        Sequence of y arrays to plot.
    labels : object
        Series identifiers corresponding to y_series.
    axes_labels : object
        Pair of strings for the x and y titles.
    title : str
        Figure title.
    height : int | None, default=None
        Ignored; Plotly auto-sizes based on renderer.
    """
    # Intentionally unused; accepted for API compatibility
    del height

    data = []
    for idx, y in enumerate(y_series):
        label = labels[idx]
        trace = self._get_powder_trace(x, y, label)
        data.append(trace)

    layout = self._get_layout(
        title,
        axes_labels,
    )

    fig = self._get_figure(data, layout)
    self._show_figure(fig)
plot_scatter(x, y, sy, axes_labels, title, height=None)

Render a scatter plot with error bars via Plotly.

Source code in src/easydiffraction/display/plotters/plotly.py
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
def plot_scatter(
    self,
    x: object,
    y: object,
    sy: object,
    axes_labels: object,
    title: str,
    height: int | None = None,
) -> None:
    """Render a scatter plot with error bars via Plotly."""
    _ = height  # not used by Plotly backend

    trace = go.Scatter(
        x=x,
        y=y,
        mode='markers+lines',
        marker={
            'symbol': 'circle',
            'size': 10,
            'line': {'width': 0.5},
            'color': DEFAULT_COLORS['meas'],
        },
        line={
            'width': 1,
            'color': DEFAULT_COLORS['meas'],
        },
        error_y={
            'type': 'data',
            'array': sy,
            'visible': True,
        },
        hovertemplate='x: %{x}<br>y: %{y}<br><extra></extra>',
    )

    layout = self._get_layout(
        title,
        axes_labels,
    )

    fig = self._get_figure(trace, layout)
    self._show_figure(fig)
plot_single_crystal(x_calc, y_meas, y_meas_su, axes_labels, title, height=None)

Render a scatter plot for single crystal diffraction data.

Suitable for single crystal diffraction data where measured values are plotted against calculated values with error bars and a diagonal reference line.

Parameters:

Name Type Description Default
x_calc object

1D array-like of calculated values (x-axis).

required
y_meas object

1D array-like of measured values (y-axis).

required
y_meas_su object

1D array-like of measurement uncertainties.

required
axes_labels object

Pair of strings for the x and y titles.

required
title str

Figure title.

required
height int | None

Ignored; Plotly auto-sizes based on renderer.

None
Source code in src/easydiffraction/display/plotters/plotly.py
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
def plot_single_crystal(
    self,
    x_calc: object,
    y_meas: object,
    y_meas_su: object,
    axes_labels: object,
    title: str,
    height: int | None = None,
) -> None:
    """
    Render a scatter plot for single crystal diffraction data.

    Suitable for single crystal diffraction data where measured
    values are plotted against calculated values with error bars and
    a diagonal reference line.

    Parameters
    ----------
    x_calc : object
        1D array-like of calculated values (x-axis).
    y_meas : object
        1D array-like of measured values (y-axis).
    y_meas_su : object
        1D array-like of measurement uncertainties.
    axes_labels : object
        Pair of strings for the x and y titles.
    title : str
        Figure title.
    height : int | None, default=None
        Ignored; Plotly auto-sizes based on renderer.
    """
    # Intentionally unused; accepted for API compatibility
    del height

    data = [
        self._get_single_crystal_trace(
            x_calc,
            y_meas,
            y_meas_su,
        )
    ]

    layout = self._get_layout(
        title,
        axes_labels,
        shapes=[self._get_diagonal_shape()],
    )

    fig = self._get_figure(data, layout)
    self._show_figure(fig)

plotting

Plotting facade for measured and calculated patterns.

Uses the common :class:RendererBase so plotters and tablers share a consistent configuration surface and engine handling.

Plotter

Bases: RendererBase

User-facing plotting facade backed by concrete plotters.

Source code in src/easydiffraction/display/plotting.py
  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
 702
 703
 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
 738
 739
 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
 771
 772
 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
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
class Plotter(RendererBase):
    """User-facing plotting facade backed by concrete plotters."""

    # ------------------------------------------------------------------
    #  Private special methods
    # ------------------------------------------------------------------

    def __init__(self) -> None:
        super().__init__()
        # X-axis limits
        self._x_min = DEFAULT_MIN
        self._x_max = DEFAULT_MAX
        # Chart height
        self.height = DEFAULT_HEIGHT
        # Back-reference to the owning Project (set via _set_project)
        self._project = None

    # ------------------------------------------------------------------
    #  Private class methods
    # ------------------------------------------------------------------

    def _set_project(self, project: object) -> None:
        """Wire the owning project for high-level plot methods."""
        self._project = project

    def _update_project_categories(self, expt_name: str) -> None:
        """Update all project categories before plotting."""
        for structure in self._project.structures:
            structure._update_categories()
        self._project.analysis._update_categories()
        experiment = self._project.experiments[expt_name]
        experiment._update_categories()

    @classmethod
    def _factory(cls) -> type[RendererFactoryBase]:  # type: ignore[override]
        return PlotterFactory

    @classmethod
    def _default_engine(cls) -> str:
        return PlotterEngineEnum.default().value

    # ------------------------------------------------------------------
    #  Private helper methods
    # ------------------------------------------------------------------

    def _auto_x_range_for_ascii(
        self,
        pattern: object,
        x_array: object,
        x_min: object,
        x_max: object,
    ) -> tuple:
        """
        For the ASCII engine, narrow the range around the tallest peak.

        Parameters
        ----------
        pattern : object
            Data pattern object (needs ``intensity_meas``).
        x_array : object
            Full x-axis array.
        x_min : object
            Current minimum (may be ``None``).
        x_max : object
            Current maximum (may be ``None``).

        Returns
        -------
        tuple
            Tuple of ``(x_min, x_max)``, possibly narrowed.
        """
        if self._engine == 'asciichartpy' and (x_min is None or x_max is None):
            max_intensity_pos = np.argmax(pattern.intensity_meas)
            half_range = 50
            start = max(0, max_intensity_pos - half_range)
            end = min(len(x_array) - 1, max_intensity_pos + half_range)
            x_min = x_array[start]
            x_max = x_array[end]
        return x_min, x_max

    def _filtered_y_array(
        self,
        y_array: object,
        x_array: object,
        x_min: object,
        x_max: object,
    ) -> object:
        """
        Filter an array by the inclusive x-range limits.

        Parameters
        ----------
        y_array : object
            1D array-like of y values.
        x_array : object
            1D array-like of x values (same length as ``y_array``).
        x_min : object
            Minimum x limit (or ``None`` to use default).
        x_max : object
            Maximum x limit (or ``None`` to use default).

        Returns
        -------
        object
            Filtered ``y_array`` values where ``x_array`` lies within
            ``[x_min, x_max]``.
        """
        if x_min is None:
            x_min = self.x_min
        if x_max is None:
            x_max = self.x_max

        mask = (x_array >= x_min) & (x_array <= x_max)
        return y_array[mask]

    @staticmethod
    def _get_axes_labels(
        sample_form: object,
        scattering_type: object,
        x_axis: object,
    ) -> list:
        """Look up axis labels for the experiment / x-axis."""
        return DEFAULT_AXES_LABELS[sample_form, scattering_type, x_axis]

    def _prepare_powder_context(
        self,
        pattern: object,
        expt_name: str,
        expt_type: object,
        x_min: object,
        x_max: object,
        x: object,
    ) -> dict | None:
        """
        Resolve axes, auto-range, and filter x-array.

        Parameters
        ----------
        pattern : object
            Data pattern object with intensity arrays.
        expt_name : str
            Experiment name for error messages.
        expt_type : object
            Experiment type with sample_form, scattering, and beam
            enums.
        x_min : object
            Optional minimum x-axis limit.
        x_max : object
            Optional maximum x-axis limit.
        x : object
            Explicit x-axis type or ``None``.

        Returns
        -------
        dict | None
            A dict with keys ``x_filtered``, ``x_array``, ``x_min``,
            ``x_max``, and ``axes_labels``; or ``None`` when the x-array
            is missing.
        """
        x_axis, x_name, sample_form, scattering_type, _ = self._resolve_x_axis(expt_type, x)

        # Get x-array from pattern
        x_raw = getattr(pattern, x_axis, None)
        if x_raw is None:
            log.error(f'No {x_name} data available for experiment {expt_name}')
            return None

        x_array = np.asarray(x_raw)

        # Auto-range for ASCII engine
        x_min, x_max = self._auto_x_range_for_ascii(pattern, x_array, x_min, x_max)

        # Filter x
        x_filtered = self._filtered_y_array(x_array, x_array, x_min, x_max)

        axes_labels = self._get_axes_labels(sample_form, scattering_type, x_axis)

        return {
            'x_filtered': x_filtered,
            'x_array': x_array,
            'x_min': x_min,
            'x_max': x_max,
            'axes_labels': axes_labels,
        }

    @staticmethod
    def _resolve_x_axis(expt_type: object, x: object) -> tuple:
        """
        Determine the x-axis type from experiment metadata.

        Parameters
        ----------
        expt_type : object
            Experiment type with sample_form, scattering_type, and
            beam_mode enums.
        x : object
            Explicit x-axis type or ``None`` to auto-detect.

        Returns
        -------
        tuple
            Tuple of ``(x_axis, x_name, sample_form, scattering_type,
            beam_mode)``.
        """
        sample_form = expt_type.sample_form.value
        scattering_type = expt_type.scattering_type.value
        beam_mode = expt_type.beam_mode.value
        x_axis = DEFAULT_X_AXIS[sample_form, scattering_type, beam_mode] if x is None else x
        x_name = getattr(x_axis, 'value', x_axis)
        return x_axis, x_name, sample_form, scattering_type, beam_mode

    # ------------------------------------------------------------------
    #  Public properties
    # ------------------------------------------------------------------

    @property
    def x_min(self) -> float:
        """Minimum x-axis limit."""
        return self._x_min

    @x_min.setter
    def x_min(self, value: object) -> None:
        """
        Set the minimum x-axis limit.

        Parameters
        ----------
        value : object
            Minimum limit or ``None`` to reset to default.
        """
        if value is not None:
            self._x_min = value
        else:
            self._x_min = DEFAULT_MIN

    @property
    def x_max(self) -> float:
        """Maximum x-axis limit."""
        return self._x_max

    @x_max.setter
    def x_max(self, value: object) -> None:
        """
        Set the maximum x-axis limit.

        Parameters
        ----------
        value : object
            Maximum limit or ``None`` to reset to default.
        """
        if value is not None:
            self._x_max = value
        else:
            self._x_max = DEFAULT_MAX

    @property
    def height(self) -> int:
        """Plot height (rows for ASCII, pixels for Plotly)."""
        return self._height

    @height.setter
    def height(self, value: object) -> None:
        """
        Set plot height.

        Parameters
        ----------
        value : object
            Height value or ``None`` to reset to default.
        """
        if value is not None:
            self._height = value
        else:
            self._height = DEFAULT_HEIGHT

    # ------------------------------------------------------------------
    #  Public methods
    # ------------------------------------------------------------------

    def show_config(self) -> None:
        """Display the current plotting configuration."""
        headers = [
            ('Parameter', 'left'),
            ('Value', 'left'),
        ]
        rows = [
            ['Plotting engine', self.engine],
            ['x-axis limits', f'[{self.x_min}, {self.x_max}]'],
            ['Chart height', self.height],
        ]
        df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(headers))
        console.paragraph('Current plotter configuration')
        TableRenderer.get().render(df)

    def plot_meas(
        self,
        expt_name: str,
        x_min: float | None = None,
        x_max: float | None = None,
        x: object | None = None,
    ) -> None:
        """
        Plot measured diffraction data for an experiment.

        Parameters
        ----------
        expt_name : str
            Name of the experiment to plot.
        x_min : float | None, default=None
            Lower bound for the x-axis range.
        x_max : float | None, default=None
            Upper bound for the x-axis range.
        x : object | None, default=None
            Optional explicit x-axis data to override stored values.
        """
        self._update_project_categories(expt_name)
        experiment = self._project.experiments[expt_name]
        self._plot_meas_data(
            experiment.data,
            expt_name,
            experiment.type,
            x_min=x_min,
            x_max=x_max,
            x=x,
        )

    def plot_calc(
        self,
        expt_name: str,
        x_min: float | None = None,
        x_max: float | None = None,
        x: object | None = None,
    ) -> None:
        """
        Plot calculated diffraction pattern for an experiment.

        Parameters
        ----------
        expt_name : str
            Name of the experiment to plot.
        x_min : float | None, default=None
            Lower bound for the x-axis range.
        x_max : float | None, default=None
            Upper bound for the x-axis range.
        x : object | None, default=None
            Optional explicit x-axis data to override stored values.
        """
        self._update_project_categories(expt_name)
        experiment = self._project.experiments[expt_name]
        self._plot_calc_data(
            experiment.data,
            expt_name,
            experiment.type,
            x_min=x_min,
            x_max=x_max,
            x=x,
        )

    def plot_meas_vs_calc(
        self,
        expt_name: str,
        x_min: float | None = None,
        x_max: float | None = None,
        *,
        show_residual: bool = False,
        x: object | None = None,
    ) -> None:
        """
        Plot measured vs calculated data for an experiment.

        Parameters
        ----------
        expt_name : str
            Name of the experiment to plot.
        x_min : float | None, default=None
            Lower bound for the x-axis range.
        x_max : float | None, default=None
            Upper bound for the x-axis range.
        show_residual : bool, default=False
            When ``True``, include the residual (difference) curve.
        x : object | None, default=None
            Optional explicit x-axis data to override stored values.
        """
        self._update_project_categories(expt_name)
        experiment = self._project.experiments[expt_name]
        self._plot_meas_vs_calc_data(
            experiment,
            expt_name,
            x_min=x_min,
            x_max=x_max,
            show_residual=show_residual,
            x=x,
        )

    def plot_param_series(
        self,
        param: object,
        versus: object | None = None,
    ) -> None:
        """
        Plot a parameter's value across sequential fit results.

        When a ``results.csv`` file exists in the project's
        ``analysis/`` directory, data is read from CSV.  Otherwise,
        falls back to in-memory parameter snapshots (produced by
        ``fit()`` in single mode).

        Parameters
        ----------
        param : object
            Parameter descriptor whose ``unique_name`` identifies the
            values to plot.
        versus : object | None, default=None
            A diffrn descriptor (e.g.
            ``expt.diffrn.ambient_temperature``) whose value is used as
            the x-axis for each experiment.  When ``None``, the
            experiment sequence number is used instead.
        """
        unique_name = param.unique_name

        # Try CSV first (produced by fit_sequential or future fit)
        csv_path = None
        if self._project.info.path is not None:
            candidate = pathlib.Path(self._project.info.path) / 'analysis' / 'results.csv'
            if candidate.is_file():
                csv_path = str(candidate)

        if csv_path is not None:
            self._plot_param_series_from_csv(
                csv_path=csv_path,
                unique_name=unique_name,
                param_descriptor=param,
                versus_descriptor=versus,
            )
        else:
            # Fallback: in-memory snapshots from fit() single mode
            versus_name = versus.name if versus is not None else None
            self.plot_param_series_from_snapshots(
                unique_name,
                versus_name,
                self._project.experiments,
                self._project.analysis._parameter_snapshots,
            )

    def plot_param_correlations(
        self,
        threshold: float | None = DEFAULT_CORRELATION_THRESHOLD,
        precision: int = 2,
    ) -> None:
        """
        Plot the parameter correlation matrix from the latest fit.

        The matrix is taken from ``project.analysis.fit_results``. When
        the active engine is Plotly, an interactive heatmap is shown.
        Otherwise, a rounded correlation table is rendered.

        Only the lower triangle is shown (without the diagonal), since
        the matrix is symmetric and diagonal values are always ``1``.

        Parameters
        ----------
        threshold : float | None, default=DEFAULT_CORRELATION_THRESHOLD
            Minimum absolute off-diagonal correlation required for a
            parameter to be shown. Parameters are kept only if they
            participate in at least one pair with ``abs(correlation) >=
            threshold``. Set to ``None`` or ``0`` to show the full
            matrix.
        precision : int, default=2
            Number of decimal places to show in the table fallback.
        """
        corr_df = self._get_param_correlation_dataframe()
        if corr_df is None:
            return

        corr_df = self._filter_correlation_dataframe(corr_df, threshold=threshold)
        if corr_df is None:
            return

        corr_df = self._mask_correlation_lower_triangle(corr_df)
        title = 'Refined parameter correlation matrix'
        if threshold is not None and threshold > 0:
            title += f' with |correlation| >= {threshold:.2f}'

        is_graphical = self._backend._supports_graphical_heatmap
        display_corr_df, row_numbers, col_numbers = self._trim_correlation_display_dataframe(
            corr_df,
            preserve_all_rows=not is_graphical,
        )

        if is_graphical:
            self._plot_correlation_heatmap(
                display_corr_df,
                title,
                threshold=threshold,
                precision=precision,
            )
            return

        console.paragraph(title)
        TableRenderer.get().render(
            self._format_correlation_table_dataframe(
                display_corr_df,
                row_numbers=row_numbers,
                col_numbers=col_numbers,
                threshold=threshold,
                precision=precision,
            )
        )

    @staticmethod
    def _filter_correlation_dataframe(
        corr_df: pd.DataFrame,
        threshold: float | None,
    ) -> pd.DataFrame | None:
        """
        Filter a correlation matrix to only strongly correlated params.

        Parameters
        ----------
        corr_df : pd.DataFrame
            Square correlation matrix.
        threshold : float | None
            Absolute-correlation cutoff. ``None`` or ``0`` keeps all
            parameters.

        Returns
        -------
        pd.DataFrame | None
            Filtered square matrix, or ``None`` if no off-diagonal
            correlations meet the cutoff.

        Raises
        ------
        ValueError
            If *threshold* is outside ``[0, 1]``.
        """
        if threshold is None or threshold <= 0:
            return corr_df
        if threshold > 1:
            msg = 'Correlation threshold must be between 0 and 1.'
            raise ValueError(msg)

        abs_corr = np.abs(corr_df.to_numpy(copy=True))
        np.fill_diagonal(abs_corr, 0.0)
        keep_mask = (abs_corr >= threshold).any(axis=0)

        if not keep_mask.any():
            log.warning(f'No parameter pairs with |correlation| >= {threshold:.2f} were found.')
            return None

        labels = corr_df.index[keep_mask]
        return corr_df.loc[labels, labels]

    @staticmethod
    def _mask_correlation_lower_triangle(
        corr_df: pd.DataFrame,
    ) -> pd.DataFrame:
        """
        Mask the upper triangle and diagonal of a correlation matrix.

        Only the lower triangle is kept, since the matrix is symmetric
        and diagonal values are always ``1``.

        Parameters
        ----------
        corr_df : pd.DataFrame
            Square correlation matrix.

        Returns
        -------
        pd.DataFrame
            Correlation matrix with upper triangle and diagonal masked.
        """
        masked_values = corr_df.to_numpy(copy=True)
        mask = np.triu(np.ones_like(masked_values, dtype=bool), k=0)
        masked_values[mask] = np.nan
        return pd.DataFrame(masked_values, index=corr_df.index, columns=corr_df.columns)

    @staticmethod
    def _trim_correlation_display_dataframe(
        corr_df: pd.DataFrame,
        *,
        preserve_all_rows: bool,
    ) -> tuple[pd.DataFrame, list[int], list[int]]:
        """
        Trim empty outer rows/columns from the lower-triangle view.

        For the lower triangle without diagonal, the last column and
        first row are always empty and can be trimmed.

        Parameters
        ----------
        corr_df : pd.DataFrame
            Masked correlation matrix.
        preserve_all_rows : bool
            Whether to keep the full row list so row labels continue to
            identify all numeric column headers in tabular output.

        Returns
        -------
        tuple[pd.DataFrame, list[int], list[int]]
            Display matrix plus 1-based parameter numbers for the kept
            rows and columns.
        """
        num_rows, num_cols = corr_df.shape
        row_numbers = list(range(1, num_rows + 1))
        col_numbers = list(range(1, num_cols + 1))

        if min(num_rows, num_cols) <= 1:
            return corr_df, row_numbers, col_numbers

        if preserve_all_rows:
            return corr_df.iloc[:, :-1], row_numbers, col_numbers[:-1]
        return corr_df.iloc[1:, :-1], row_numbers[1:], col_numbers[:-1]

    def _get_param_correlation_dataframe(self) -> pd.DataFrame | None:
        """
        Return the correlation matrix for the latest fit.

        Returns
        -------
        pd.DataFrame | None
            Square correlation matrix labeled by parameter unique names,
            or ``None`` if unavailable.
        """
        result = self._get_fit_result_for_correlation()
        if result is None:
            return None
        raw_result, var_names, fit_results = result

        covar = getattr(raw_result, 'covar', None)
        if covar is not None:
            return self._correlation_from_covariance(covar, var_names, fit_results.parameters)

        corr_df = self._get_param_correlation_dataframe_from_engine_params(
            raw_result=raw_result,
            parameters=fit_results.parameters,
        )
        if corr_df is not None:
            return corr_df

        log.warning(
            'Correlation matrix is unavailable for this fit. '
            'Use the lmfit minimizer and ensure covariance estimation succeeds.'
        )
        return None

    def _get_fit_result_for_correlation(
        self,
    ) -> tuple[object, list[str], object] | None:
        """
        Validate and return the raw fit result for correlation.

        Returns
        -------
        tuple[object, list[str], object] | None
            A tuple of ``(raw_result, var_names, fit_results)`` when all
            required data is present, or ``None`` otherwise.
        """
        if self._project is None:
            log.warning('Plotter is not attached to a project.')
            return None

        fit_results = getattr(self._project.analysis, 'fit_results', None)
        if fit_results is None:
            log.warning('No fit results available. Run fit() first.')
            return None

        raw_result = getattr(fit_results, 'engine_result', None)
        if raw_result is None:
            log.warning('No raw fit result available. Correlation matrix cannot be plotted.')
            return None

        var_names = getattr(raw_result, 'var_names', None)
        if not var_names:
            log.warning('Fit result does not expose variable names for a correlation matrix.')
            return None

        return raw_result, var_names, fit_results

    @staticmethod
    def _correlation_from_covariance(
        covar: object,
        var_names: list[str],
        parameters: list[object],
    ) -> pd.DataFrame | None:
        """
        Convert a covariance matrix to a correlation DataFrame.

        Parameters
        ----------
        covar : object
            Raw covariance matrix from the fit result.
        var_names : list[str]
            Minimizer variable names.
        parameters : list[object]
            Fitted parameter descriptors.

        Returns
        -------
        pd.DataFrame | None
            Correlation matrix, or ``None`` if the covariance is
            invalid.
        """
        covar_array = np.asarray(covar, dtype=float)
        if covar_array.ndim != EXPECTED_COVAR_NDIM or covar_array.shape[0] != covar_array.shape[1]:
            log.warning('Fit result returned an invalid covariance matrix.')
            return None
        if covar_array.shape[0] != len(var_names):
            log.warning('Covariance matrix size does not match the fitted parameter list.')
            return None

        sigma = np.sqrt(np.diag(covar_array))
        with np.errstate(divide='ignore', invalid='ignore'):
            corr = covar_array / np.outer(sigma, sigma)
        corr = np.nan_to_num(corr, nan=0.0, posinf=0.0, neginf=0.0)
        np.fill_diagonal(corr, 1.0)

        labels = Plotter._get_correlation_labels(parameters, var_names)
        return pd.DataFrame(corr, index=labels, columns=labels)

    @staticmethod
    def _get_correlation_labels(
        parameters: list[object],
        var_names: list[str],
    ) -> list[str]:
        """
        Map minimizer variable names to readable parameter labels.

        Parameters
        ----------
        parameters : list[object]
            Fitted parameter descriptors.
        var_names : list[str]
            Minimizer variable names from the engine result.

        Returns
        -------
        list[str]
            Labels for the correlation matrix axes.
        """
        labels_by_uid = {
            getattr(param, '_minimizer_uid', ''): getattr(
                param, 'unique_name', getattr(param, 'name', '')
            )
            for param in parameters
        }
        return [labels_by_uid.get(name, name) for name in var_names]

    def _get_param_correlation_dataframe_from_engine_params(
        self,
        raw_result: object,
        parameters: list[object],
    ) -> pd.DataFrame | None:
        """
        Reconstruct a correlation matrix from engine parameter metadata.

        This is a fallback for backends that populate per-parameter
        correlation coefficients but do not expose a covariance matrix.

        Parameters
        ----------
        raw_result : object
            Backend-specific fit result.
        parameters : list[object]
            Fitted parameter descriptors.

        Returns
        -------
        pd.DataFrame | None
            Correlation matrix labeled by readable parameter names, or
            ``None`` if no correlation coefficients are available.
        """
        engine_params = getattr(raw_result, 'params', None)
        var_names = getattr(raw_result, 'var_names', None)
        if engine_params is None or not var_names:
            return None

        corr = np.eye(len(var_names), dtype=float)
        indices = {name: idx for idx, name in enumerate(var_names)}
        found_corr = False

        for name, idx in indices.items():
            engine_param = engine_params.get(name)
            param_corr = getattr(engine_param, 'correl', None)
            if not param_corr:
                continue

            for other_name, value in param_corr.items():
                other_idx = indices.get(other_name)
                if other_idx is None:
                    continue
                corr_value = float(value)
                corr[idx, other_idx] = corr_value
                corr[other_idx, idx] = corr_value
                found_corr = True

        if not found_corr:
            return None

        labels = self._get_correlation_labels(parameters, var_names)
        return pd.DataFrame(corr, index=labels, columns=labels)

    def _plot_correlation_heatmap(
        self,
        corr_df: pd.DataFrame,
        title: str,
        threshold: float | None,
        precision: int,
    ) -> None:
        """
        Delegate correlation heatmap rendering to the backend.

        Parameters
        ----------
        corr_df : pd.DataFrame
            Square correlation matrix.
        title : str
            Figure title.
        threshold : float | None
            Absolute-correlation cutoff used for value labels.
        precision : int
            Number of decimals to show in plot labels and hover text.
        """
        self._backend.plot_correlation_heatmap(
            corr_df,
            title,
            threshold=threshold,
            precision=precision,
        )

    @staticmethod
    def _format_correlation_table_dataframe(
        corr_df: pd.DataFrame,
        row_numbers: list[int],
        col_numbers: list[int],
        threshold: float | None,
        precision: int,
    ) -> pd.DataFrame:
        """
        Format a correlation matrix for TableRenderer.

        Parameters
        ----------
        corr_df : pd.DataFrame
            Correlation matrix labeled by parameter name.
        row_numbers : list[int]
            1-based parameter numbers for displayed rows.
        col_numbers : list[int]
            1-based parameter numbers for displayed columns.
        threshold : float | None
            Absolute-correlation cutoff used to blank low-magnitude
            cells in the rendered table. ``None`` or ``0`` keeps all
            non-masked values.
        precision : int
            Number of decimals to show in the rendered values.

        Returns
        -------
        pd.DataFrame
            DataFrame with MultiIndex columns and default numeric index,
            suitable for :class:`TableRenderer`. Correlation columns use
            1-based numeric headers so they line up with the numbered
            parameter rows in terminal output.
        """
        rounded = corr_df.round(precision)
        cell_width = max(
            len(str(max(col_numbers, default=0))),
            len(f'{-1.0:.{precision}f}'),
        )
        headers = [('parameter', 'left')]
        headers.extend((str(index).rjust(cell_width), 'right') for index in col_numbers)

        rows = []
        for label, values in rounded.iterrows():
            row_values = []
            for value in values.tolist():
                should_blank = pd.isna(value) or (
                    threshold is not None and threshold > 0 and abs(float(value)) < threshold
                )
                if should_blank:
                    row_values.append('')
                else:
                    fval = float(value)
                    text = f'{fval:>{cell_width}.{precision}f}'
                    if fval < 0:
                        text = f'[red]{text}[/red]'
                    elif fval > 0:
                        text = f'[blue]{text}[/blue]'
                    row_values.append(text)
            rows.append([label, *row_values])

        df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(headers))
        df.index = pd.Index([row_number - 1 for row_number in row_numbers])
        return df

    def _plot_meas_data(
        self,
        pattern: object,
        expt_name: str,
        expt_type: object,
        x_min: object = None,
        x_max: object = None,
        x: object = None,
    ) -> None:
        """
        Plot measured pattern using the current engine.

        Parameters
        ----------
        pattern : object
            Object with x-axis arrays (``two_theta``,
            ``time_of_flight``, ``d_spacing``) and ``meas`` array.
        expt_name : str
            Experiment name for the title.
        expt_type : object
            Experiment type with scattering/beam enums.
        x_min : object, default=None
            Optional minimum x-axis limit.
        x_max : object, default=None
            Optional maximum x-axis limit.
        x : object, default=None
            X-axis type. If ``None``, auto-detected from beam mode.
        """
        ctx = self._prepare_powder_context(
            pattern,
            expt_name,
            expt_type,
            x_min,
            x_max,
            x,
        )
        if ctx is None:
            return

        if pattern.intensity_meas is None:
            log.error(f'No measured data available for experiment {expt_name}')
            return
        y_meas = self._filtered_y_array(
            pattern.intensity_meas, ctx['x_array'], ctx['x_min'], ctx['x_max']
        )

        self._backend.plot_powder(
            x=ctx['x_filtered'],
            y_series=[y_meas],
            labels=['meas'],
            axes_labels=ctx['axes_labels'],
            title=f"Measured data for experiment 🔬 '{expt_name}'",
            height=self.height,
        )

    def _plot_calc_data(
        self,
        pattern: object,
        expt_name: str,
        expt_type: object,
        x_min: object = None,
        x_max: object = None,
        x: object = None,
    ) -> None:
        """
        Plot calculated pattern using the current engine.

        Parameters
        ----------
        pattern : object
            Object with x-axis arrays (``two_theta``,
            ``time_of_flight``, ``d_spacing``) and ``calc`` array.
        expt_name : str
            Experiment name for the title.
        expt_type : object
            Experiment type with scattering/beam enums.
        x_min : object, default=None
            Optional minimum x-axis limit.
        x_max : object, default=None
            Optional maximum x-axis limit.
        x : object, default=None
            X-axis type. If ``None``, auto-detected from beam mode.
        """
        ctx = self._prepare_powder_context(
            pattern,
            expt_name,
            expt_type,
            x_min,
            x_max,
            x,
        )
        if ctx is None:
            return

        if pattern.intensity_calc is None:
            log.error(f'No calculated data available for experiment {expt_name}')
            return
        y_calc = self._filtered_y_array(
            pattern.intensity_calc, ctx['x_array'], ctx['x_min'], ctx['x_max']
        )

        self._backend.plot_powder(
            x=ctx['x_filtered'],
            y_series=[y_calc],
            labels=['calc'],
            axes_labels=ctx['axes_labels'],
            title=f"Calculated data for experiment 🔬 '{expt_name}'",
            height=self.height,
        )

    def _plot_meas_vs_calc_data(
        self,
        experiment: object,
        expt_name: str,
        x_min: object = None,
        x_max: object = None,
        *,
        show_residual: bool = False,
        x: object = None,
    ) -> None:
        """
        Plot measured and calculated series and optional residual.

        Supports both powder and single crystal data with a unified API.

        For powder diffraction: - x='two_theta', 'time_of_flight', or
        'd_spacing' - Auto-detected from beam mode if not specified

        For single crystal diffraction: - x='intensity_calc' (default):
        scatter plot - x='d_spacing' or 'sin_theta_over_lambda': line
        plot

        Parameters
        ----------
        experiment : object
            Experiment instance with ``.data`` and ``.type`` attributes.
        expt_name : str
            Experiment name for the title.
        x_min : object, default=None
            Optional minimum x-axis limit.
        x_max : object, default=None
            Optional maximum x-axis limit.
        show_residual : bool, default=False
            If ``True``, add residual series (powder only).
        x : object, default=None
            X-axis type. If ``None``, auto-detected from sample form and
            beam mode.
        """
        pattern = experiment.data
        expt_type = experiment.type

        x_axis, _, sample_form, scattering_type, _ = self._resolve_x_axis(expt_type, x)

        # Validate required data (before x-array check, matching
        # original behavior for plot_meas_vs_calc)
        if pattern.intensity_meas is None:
            log.error(f'No measured data available for experiment {expt_name}')
            return
        if pattern.intensity_calc is None:
            log.error(f'No calculated data available for experiment {expt_name}')
            return

        title = f"Measured vs Calculated data for experiment 🔬 '{expt_name}'"

        # Single crystal scatter plot (I²calc vs I²meas)
        if x_axis in {XAxisType.INTENSITY_CALC, 'intensity_calc'}:
            axes_labels = self._get_axes_labels(sample_form, scattering_type, x_axis)

            if pattern.intensity_meas_su is None:
                log.warning(f'No measurement uncertainties for experiment {expt_name}')
                meas_su = np.zeros_like(pattern.intensity_meas)
            else:
                meas_su = pattern.intensity_meas_su

            self._backend.plot_single_crystal(
                x_calc=pattern.intensity_calc,
                y_meas=pattern.intensity_meas,
                y_meas_su=meas_su,
                axes_labels=axes_labels,
                title=f"Measured vs Calculated data for experiment 🔬 '{expt_name}'",
                height=self.height,
            )
            return

        # Line plot (PD or SC with d_spacing/sin_theta_over_lambda)
        ctx = self._prepare_powder_context(
            pattern,
            expt_name,
            expt_type,
            x_min,
            x_max,
            x,
        )
        if ctx is None:
            return

        y_series = []
        y_labels = []
        y_meas = self._filtered_y_array(
            pattern.intensity_meas, ctx['x_array'], ctx['x_min'], ctx['x_max']
        )
        y_series.append(y_meas)
        y_labels.append('meas')
        y_calc = self._filtered_y_array(
            pattern.intensity_calc, ctx['x_array'], ctx['x_min'], ctx['x_max']
        )
        y_series.append(y_calc)
        y_labels.append('calc')
        if show_residual:
            y_series.append(y_meas - y_calc)
            y_labels.append('resid')

        self._backend.plot_powder(
            x=ctx['x_filtered'],
            y_series=y_series,
            labels=y_labels,
            axes_labels=ctx['axes_labels'],
            title=title,
            height=self.height,
        )

    def _plot_param_series_from_csv(
        self,
        csv_path: str,
        unique_name: str,
        param_descriptor: object,
        versus_descriptor: object | None = None,
    ) -> None:
        """
        Plot a parameter's value across sequential fit results.

        Reads data from the CSV file at *csv_path*.  The y-axis values
        come from the column named *unique_name*, uncertainties from
        ``{unique_name}.uncertainty``.  When *versus_descriptor* is
        provided, the x-axis uses the corresponding ``diffrn.{name}``
        column; otherwise the row index is used.

        Axis labels are derived from the live descriptor objects
        (*param_descriptor* and *versus_descriptor*), which carry
        ``.description`` and ``.units`` attributes.

        Parameters
        ----------
        csv_path : str
            Path to the ``results.csv`` file.
        unique_name : str
            Unique name of the parameter to plot (CSV column key).
        param_descriptor : object
            The live parameter descriptor (for axis label / units).
        versus_descriptor : object | None, default=None
            A diffrn descriptor whose ``.name`` maps to a
            ``diffrn.{name}`` CSV column.  ``None`` → use row index.
        """
        df = pd.read_csv(csv_path)

        if unique_name not in df.columns:
            log.warning(
                f"Parameter '{unique_name}' not found in CSV columns. "
                f'Available: {list(df.columns)}'
            )
            return

        y = df[unique_name].astype(float).tolist()
        uncert_col = f'{unique_name}.uncertainty'
        sy = df[uncert_col].astype(float).tolist() if uncert_col in df.columns else [0.0] * len(y)

        # X-axis: diffrn column or row index
        versus_name = versus_descriptor.name if versus_descriptor is not None else None
        diffrn_col = f'diffrn.{versus_name}' if versus_name else None

        if diffrn_col and diffrn_col in df.columns:
            x = pd.to_numeric(df[diffrn_col], errors='coerce').tolist()
            x_label = getattr(versus_descriptor, 'description', None) or versus_name
            if hasattr(versus_descriptor, 'units') and versus_descriptor.units:
                x_label = f'{x_label} ({versus_descriptor.units})'
        else:
            x = list(range(1, len(y) + 1))
            x_label = 'Experiment No.'

        # Y-axis label from descriptor
        param_units = getattr(param_descriptor, 'units', '')
        y_label = f'Parameter value ({param_units})' if param_units else 'Parameter value'

        title = f"Parameter '{unique_name}' across fit results"

        self._backend.plot_scatter(
            x=x,
            y=y,
            sy=sy,
            axes_labels=[x_label, y_label],
            title=title,
            height=self.height,
        )

    def plot_param_series_from_snapshots(
        self,
        unique_name: str,
        versus_name: str | None,
        experiments: object,
        parameter_snapshots: dict[str, dict[str, dict]],
    ) -> None:
        """
        Plot a parameter's value from in-memory snapshots.

        This is a backward-compatibility method used when no CSV file is
        available (e.g. after ``fit()`` in single mode, before PR 13
        adds CSV output to the existing fit loop).

        Parameters
        ----------
        unique_name : str
            Unique name of the parameter to plot.
        versus_name : str | None
            Name of the diffrn descriptor for the x-axis.
        experiments : object
            Experiments collection for accessing diffrn conditions.
        parameter_snapshots : dict[str, dict[str, dict]]
            Per-experiment parameter value snapshots.
        """
        x = []
        y = []
        sy = []
        axes_labels = []
        title = ''

        for idx, expt_name in enumerate(parameter_snapshots, start=1):
            experiment = experiments[expt_name]
            diffrn = experiment.diffrn

            x_axis_param = self._resolve_diffrn_descriptor(diffrn, versus_name)

            if x_axis_param is not None and x_axis_param.value is not None:
                value = x_axis_param.value
            else:
                value = idx
            x.append(value)

            param_data = parameter_snapshots[expt_name][unique_name]
            y.append(param_data['value'])
            sy.append(param_data['uncertainty'])

            if x_axis_param is not None:
                axes_labels = [
                    x_axis_param.description or x_axis_param.name,
                    f'Parameter value ({param_data["units"]})',
                ]
            else:
                axes_labels = [
                    'Experiment No.',
                    f'Parameter value ({param_data["units"]})',
                ]

            title = f"Parameter '{unique_name}' across fit results"

        self._backend.plot_scatter(
            x=x,
            y=y,
            sy=sy,
            axes_labels=axes_labels,
            title=title,
            height=self.height,
        )

    @staticmethod
    def _resolve_diffrn_descriptor(
        diffrn: object,
        name: str | None,
    ) -> object | None:
        """
        Return the diffrn descriptor matching *name*, or ``None``.

        Parameters
        ----------
        diffrn : object
            The diffrn category of an experiment.
        name : str | None
            Descriptor name (e.g. ``'ambient_temperature'``).

        Returns
        -------
        object | None
            The matching ``NumericDescriptor``, or ``None`` when *name*
            is ``None`` or unrecognised.
        """
        if name is None:
            return None
        if name == 'ambient_temperature':
            return diffrn.ambient_temperature
        if name == 'ambient_pressure':
            return diffrn.ambient_pressure
        if name == 'ambient_magnetic_field':
            return diffrn.ambient_magnetic_field
        if name == 'ambient_electric_field':
            return diffrn.ambient_electric_field
        return None

height property writable

Plot height (rows for ASCII, pixels for Plotly).

plot_calc(expt_name, x_min=None, x_max=None, x=None)

Plot calculated diffraction pattern for an experiment.

Parameters:

Name Type Description Default
expt_name str

Name of the experiment to plot.

required
x_min float | None

Lower bound for the x-axis range.

None
x_max float | None

Upper bound for the x-axis range.

None
x object | None

Optional explicit x-axis data to override stored values.

None
Source code in src/easydiffraction/display/plotting.py
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
def plot_calc(
    self,
    expt_name: str,
    x_min: float | None = None,
    x_max: float | None = None,
    x: object | None = None,
) -> None:
    """
    Plot calculated diffraction pattern for an experiment.

    Parameters
    ----------
    expt_name : str
        Name of the experiment to plot.
    x_min : float | None, default=None
        Lower bound for the x-axis range.
    x_max : float | None, default=None
        Upper bound for the x-axis range.
    x : object | None, default=None
        Optional explicit x-axis data to override stored values.
    """
    self._update_project_categories(expt_name)
    experiment = self._project.experiments[expt_name]
    self._plot_calc_data(
        experiment.data,
        expt_name,
        experiment.type,
        x_min=x_min,
        x_max=x_max,
        x=x,
    )

plot_meas(expt_name, x_min=None, x_max=None, x=None)

Plot measured diffraction data for an experiment.

Parameters:

Name Type Description Default
expt_name str

Name of the experiment to plot.

required
x_min float | None

Lower bound for the x-axis range.

None
x_max float | None

Upper bound for the x-axis range.

None
x object | None

Optional explicit x-axis data to override stored values.

None
Source code in src/easydiffraction/display/plotting.py
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
def plot_meas(
    self,
    expt_name: str,
    x_min: float | None = None,
    x_max: float | None = None,
    x: object | None = None,
) -> None:
    """
    Plot measured diffraction data for an experiment.

    Parameters
    ----------
    expt_name : str
        Name of the experiment to plot.
    x_min : float | None, default=None
        Lower bound for the x-axis range.
    x_max : float | None, default=None
        Upper bound for the x-axis range.
    x : object | None, default=None
        Optional explicit x-axis data to override stored values.
    """
    self._update_project_categories(expt_name)
    experiment = self._project.experiments[expt_name]
    self._plot_meas_data(
        experiment.data,
        expt_name,
        experiment.type,
        x_min=x_min,
        x_max=x_max,
        x=x,
    )

plot_meas_vs_calc(expt_name, x_min=None, x_max=None, *, show_residual=False, x=None)

Plot measured vs calculated data for an experiment.

Parameters:

Name Type Description Default
expt_name str

Name of the experiment to plot.

required
x_min float | None

Lower bound for the x-axis range.

None
x_max float | None

Upper bound for the x-axis range.

None
show_residual bool

When True, include the residual (difference) curve.

False
x object | None

Optional explicit x-axis data to override stored values.

None
Source code in src/easydiffraction/display/plotting.py
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
def plot_meas_vs_calc(
    self,
    expt_name: str,
    x_min: float | None = None,
    x_max: float | None = None,
    *,
    show_residual: bool = False,
    x: object | None = None,
) -> None:
    """
    Plot measured vs calculated data for an experiment.

    Parameters
    ----------
    expt_name : str
        Name of the experiment to plot.
    x_min : float | None, default=None
        Lower bound for the x-axis range.
    x_max : float | None, default=None
        Upper bound for the x-axis range.
    show_residual : bool, default=False
        When ``True``, include the residual (difference) curve.
    x : object | None, default=None
        Optional explicit x-axis data to override stored values.
    """
    self._update_project_categories(expt_name)
    experiment = self._project.experiments[expt_name]
    self._plot_meas_vs_calc_data(
        experiment,
        expt_name,
        x_min=x_min,
        x_max=x_max,
        show_residual=show_residual,
        x=x,
    )

plot_param_correlations(threshold=DEFAULT_CORRELATION_THRESHOLD, precision=2)

Plot the parameter correlation matrix from the latest fit.

The matrix is taken from project.analysis.fit_results. When the active engine is Plotly, an interactive heatmap is shown. Otherwise, a rounded correlation table is rendered.

Only the lower triangle is shown (without the diagonal), since the matrix is symmetric and diagonal values are always 1.

Parameters:

Name Type Description Default
threshold float | None

Minimum absolute off-diagonal correlation required for a parameter to be shown. Parameters are kept only if they participate in at least one pair with abs(correlation) >= threshold. Set to None or 0 to show the full matrix.

DEFAULT_CORRELATION_THRESHOLD
precision int

Number of decimal places to show in the table fallback.

2
Source code in src/easydiffraction/display/plotting.py
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
def plot_param_correlations(
    self,
    threshold: float | None = DEFAULT_CORRELATION_THRESHOLD,
    precision: int = 2,
) -> None:
    """
    Plot the parameter correlation matrix from the latest fit.

    The matrix is taken from ``project.analysis.fit_results``. When
    the active engine is Plotly, an interactive heatmap is shown.
    Otherwise, a rounded correlation table is rendered.

    Only the lower triangle is shown (without the diagonal), since
    the matrix is symmetric and diagonal values are always ``1``.

    Parameters
    ----------
    threshold : float | None, default=DEFAULT_CORRELATION_THRESHOLD
        Minimum absolute off-diagonal correlation required for a
        parameter to be shown. Parameters are kept only if they
        participate in at least one pair with ``abs(correlation) >=
        threshold``. Set to ``None`` or ``0`` to show the full
        matrix.
    precision : int, default=2
        Number of decimal places to show in the table fallback.
    """
    corr_df = self._get_param_correlation_dataframe()
    if corr_df is None:
        return

    corr_df = self._filter_correlation_dataframe(corr_df, threshold=threshold)
    if corr_df is None:
        return

    corr_df = self._mask_correlation_lower_triangle(corr_df)
    title = 'Refined parameter correlation matrix'
    if threshold is not None and threshold > 0:
        title += f' with |correlation| >= {threshold:.2f}'

    is_graphical = self._backend._supports_graphical_heatmap
    display_corr_df, row_numbers, col_numbers = self._trim_correlation_display_dataframe(
        corr_df,
        preserve_all_rows=not is_graphical,
    )

    if is_graphical:
        self._plot_correlation_heatmap(
            display_corr_df,
            title,
            threshold=threshold,
            precision=precision,
        )
        return

    console.paragraph(title)
    TableRenderer.get().render(
        self._format_correlation_table_dataframe(
            display_corr_df,
            row_numbers=row_numbers,
            col_numbers=col_numbers,
            threshold=threshold,
            precision=precision,
        )
    )

plot_param_series(param, versus=None)

Plot a parameter's value across sequential fit results.

When a results.csv file exists in the project's analysis/ directory, data is read from CSV. Otherwise, falls back to in-memory parameter snapshots (produced by fit() in single mode).

Parameters:

Name Type Description Default
param object

Parameter descriptor whose unique_name identifies the values to plot.

required
versus object | None

A diffrn descriptor (e.g. expt.diffrn.ambient_temperature) whose value is used as the x-axis for each experiment. When None, the experiment sequence number is used instead.

None
Source code in src/easydiffraction/display/plotting.py
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
def plot_param_series(
    self,
    param: object,
    versus: object | None = None,
) -> None:
    """
    Plot a parameter's value across sequential fit results.

    When a ``results.csv`` file exists in the project's
    ``analysis/`` directory, data is read from CSV.  Otherwise,
    falls back to in-memory parameter snapshots (produced by
    ``fit()`` in single mode).

    Parameters
    ----------
    param : object
        Parameter descriptor whose ``unique_name`` identifies the
        values to plot.
    versus : object | None, default=None
        A diffrn descriptor (e.g.
        ``expt.diffrn.ambient_temperature``) whose value is used as
        the x-axis for each experiment.  When ``None``, the
        experiment sequence number is used instead.
    """
    unique_name = param.unique_name

    # Try CSV first (produced by fit_sequential or future fit)
    csv_path = None
    if self._project.info.path is not None:
        candidate = pathlib.Path(self._project.info.path) / 'analysis' / 'results.csv'
        if candidate.is_file():
            csv_path = str(candidate)

    if csv_path is not None:
        self._plot_param_series_from_csv(
            csv_path=csv_path,
            unique_name=unique_name,
            param_descriptor=param,
            versus_descriptor=versus,
        )
    else:
        # Fallback: in-memory snapshots from fit() single mode
        versus_name = versus.name if versus is not None else None
        self.plot_param_series_from_snapshots(
            unique_name,
            versus_name,
            self._project.experiments,
            self._project.analysis._parameter_snapshots,
        )

plot_param_series_from_snapshots(unique_name, versus_name, experiments, parameter_snapshots)

Plot a parameter's value from in-memory snapshots.

This is a backward-compatibility method used when no CSV file is available (e.g. after fit() in single mode, before PR 13 adds CSV output to the existing fit loop).

Parameters:

Name Type Description Default
unique_name str

Unique name of the parameter to plot.

required
versus_name str | None

Name of the diffrn descriptor for the x-axis.

required
experiments object

Experiments collection for accessing diffrn conditions.

required
parameter_snapshots dict[str, dict[str, dict]]

Per-experiment parameter value snapshots.

required
Source code in src/easydiffraction/display/plotting.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
def plot_param_series_from_snapshots(
    self,
    unique_name: str,
    versus_name: str | None,
    experiments: object,
    parameter_snapshots: dict[str, dict[str, dict]],
) -> None:
    """
    Plot a parameter's value from in-memory snapshots.

    This is a backward-compatibility method used when no CSV file is
    available (e.g. after ``fit()`` in single mode, before PR 13
    adds CSV output to the existing fit loop).

    Parameters
    ----------
    unique_name : str
        Unique name of the parameter to plot.
    versus_name : str | None
        Name of the diffrn descriptor for the x-axis.
    experiments : object
        Experiments collection for accessing diffrn conditions.
    parameter_snapshots : dict[str, dict[str, dict]]
        Per-experiment parameter value snapshots.
    """
    x = []
    y = []
    sy = []
    axes_labels = []
    title = ''

    for idx, expt_name in enumerate(parameter_snapshots, start=1):
        experiment = experiments[expt_name]
        diffrn = experiment.diffrn

        x_axis_param = self._resolve_diffrn_descriptor(diffrn, versus_name)

        if x_axis_param is not None and x_axis_param.value is not None:
            value = x_axis_param.value
        else:
            value = idx
        x.append(value)

        param_data = parameter_snapshots[expt_name][unique_name]
        y.append(param_data['value'])
        sy.append(param_data['uncertainty'])

        if x_axis_param is not None:
            axes_labels = [
                x_axis_param.description or x_axis_param.name,
                f'Parameter value ({param_data["units"]})',
            ]
        else:
            axes_labels = [
                'Experiment No.',
                f'Parameter value ({param_data["units"]})',
            ]

        title = f"Parameter '{unique_name}' across fit results"

    self._backend.plot_scatter(
        x=x,
        y=y,
        sy=sy,
        axes_labels=axes_labels,
        title=title,
        height=self.height,
    )

show_config()

Display the current plotting configuration.

Source code in src/easydiffraction/display/plotting.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def show_config(self) -> None:
    """Display the current plotting configuration."""
    headers = [
        ('Parameter', 'left'),
        ('Value', 'left'),
    ]
    rows = [
        ['Plotting engine', self.engine],
        ['x-axis limits', f'[{self.x_min}, {self.x_max}]'],
        ['Chart height', self.height],
    ]
    df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(headers))
    console.paragraph('Current plotter configuration')
    TableRenderer.get().render(df)

x_max property writable

Maximum x-axis limit.

x_min property writable

Minimum x-axis limit.

PlotterEngineEnum

Bases: StrEnum

Available plotting engine backends.

Source code in src/easydiffraction/display/plotting.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class PlotterEngineEnum(StrEnum):
    """Available plotting engine backends."""

    ASCII = 'asciichartpy'
    PLOTLY = 'plotly'

    @classmethod
    def default(cls) -> PlotterEngineEnum:
        """Select default engine based on environment."""
        if in_jupyter():
            log.debug('Setting default plotting engine to Plotly for Jupyter')
            return cls.PLOTLY
        log.debug('Setting default plotting engine to Asciichartpy for console')
        return cls.ASCII

    def description(self) -> str:
        """Human-readable description for UI listings."""
        if self is PlotterEngineEnum.ASCII:
            return 'Console ASCII line charts'
        if self is PlotterEngineEnum.PLOTLY:
            return 'Interactive browser-based graphing library'
        return ''

default() classmethod

Select default engine based on environment.

Source code in src/easydiffraction/display/plotting.py
40
41
42
43
44
45
46
47
@classmethod
def default(cls) -> PlotterEngineEnum:
    """Select default engine based on environment."""
    if in_jupyter():
        log.debug('Setting default plotting engine to Plotly for Jupyter')
        return cls.PLOTLY
    log.debug('Setting default plotting engine to Asciichartpy for console')
    return cls.ASCII

description()

Human-readable description for UI listings.

Source code in src/easydiffraction/display/plotting.py
49
50
51
52
53
54
55
def description(self) -> str:
    """Human-readable description for UI listings."""
    if self is PlotterEngineEnum.ASCII:
        return 'Console ASCII line charts'
    if self is PlotterEngineEnum.PLOTLY:
        return 'Interactive browser-based graphing library'
    return ''

PlotterFactory

Bases: RendererFactoryBase

Factory for plotter implementations.

Source code in src/easydiffraction/display/plotting.py
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
class PlotterFactory(RendererFactoryBase):
    """Factory for plotter implementations."""

    @classmethod
    def _registry(cls) -> dict:
        return {
            PlotterEngineEnum.ASCII.value: {
                'description': PlotterEngineEnum.ASCII.description(),
                'class': AsciiPlotter,
            },
            PlotterEngineEnum.PLOTLY.value: {
                'description': PlotterEngineEnum.PLOTLY.description(),
                'class': PlotlyPlotter,
            },
        }

tablers

Tabular rendering backends.

This subpackage provides concrete implementations for rendering tables in different environments:

  • :mod:.rich for terminal and notebooks using the Rich library. - :mod:.pandas for notebooks using DataFrame Styler.

base

Low-level backends for rendering tables.

This module defines the abstract base for tabular renderers and small helpers for consistent styling across terminal and notebook outputs.

TableBackendBase

Bases: ABC

Abstract base class for concrete table backends.

Subclasses implement the render method which receives an index- aware pandas DataFrame and the alignment for each column header.

Source code in src/easydiffraction/display/tablers/base.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
class TableBackendBase(ABC):
    """
    Abstract base class for concrete table backends.

    Subclasses implement the ``render`` method which receives an index-
    aware pandas DataFrame and the alignment for each column header.
    """

    FLOAT_PRECISION = 5
    RICH_BORDER_DARK_THEME = 'grey35'
    RICH_BORDER_LIGHT_THEME = 'grey85'

    def __init__(self) -> None:
        super().__init__()
        self._float_fmt = f'{{:.{self.FLOAT_PRECISION}f}}'.format

    def _format_value(self, value: object) -> object:
        """
        Format floats with fixed precision and others as strings.

        Parameters
        ----------
        value : object
            Cell value to format.

        Returns
        -------
        object
            A string representation with fixed precision for floats or
            ``str(value)`` for other types.
        """
        return self._float_fmt(value) if isinstance(value, float) else str(value)

    @staticmethod
    def _is_dark_theme() -> bool:
        """
        Return True when a dark theme is detected in Jupyter.

        If not running inside Jupyter, return a sane default (True).
        """
        default = True

        in_jupyter = (
            get_ipython() is not None and get_ipython().__class__.__name__ == 'ZMQInteractiveShell'
        )

        if not in_jupyter:
            return default

        return is_dark()

    @staticmethod
    def _rich_to_hex(color: str) -> str:
        """
        Convert a Rich color name to a CSS-style hex string.

        Parameters
        ----------
        color : str
            Rich color name or specification parsable by :mod:`rich`.

        Returns
        -------
        str
            Hex color string in the form ``#RRGGBB``.
        """
        c = Color.parse(color)
        rgb = c.get_truecolor()
        return '#{:02x}{:02x}{:02x}'.format(*rgb)

    @property
    def _rich_border_color(self) -> str:
        return (
            self.RICH_BORDER_DARK_THEME if self._is_dark_theme() else self.RICH_BORDER_LIGHT_THEME
        )

    @property
    def _pandas_border_color(self) -> str:
        return self._rich_to_hex(self._rich_border_color)

    @abstractmethod
    def render(
        self,
        alignments: object,
        df: object,
        display_handle: object | None = None,
    ) -> object:
        """
        Render the provided DataFrame with backend-specific styling.

        Parameters
        ----------
        alignments : object
            Iterable of column justifications (e.g., ``'left'`` or
            ``'center'``) corresponding to the data columns.
        df : object
            Index-aware DataFrame with data to render.
        display_handle : object | None, default=None
            Optional environment-specific handle to enable in-place
            updates.

        Returns
        -------
        object
            Backend-defined return value (commonly ``None``).
        """
render(alignments, df, display_handle=None) abstractmethod

Render the provided DataFrame with backend-specific styling.

Parameters:

Name Type Description Default
alignments object

Iterable of column justifications (e.g., 'left' or 'center') corresponding to the data columns.

required
df object

Index-aware DataFrame with data to render.

required
display_handle object | None

Optional environment-specific handle to enable in-place updates.

None

Returns:

Type Description
object

Backend-defined return value (commonly None).

Source code in src/easydiffraction/display/tablers/base.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
@abstractmethod
def render(
    self,
    alignments: object,
    df: object,
    display_handle: object | None = None,
) -> object:
    """
    Render the provided DataFrame with backend-specific styling.

    Parameters
    ----------
    alignments : object
        Iterable of column justifications (e.g., ``'left'`` or
        ``'center'``) corresponding to the data columns.
    df : object
        Index-aware DataFrame with data to render.
    display_handle : object | None, default=None
        Optional environment-specific handle to enable in-place
        updates.

    Returns
    -------
    object
        Backend-defined return value (commonly ``None``).
    """

pandas

Pandas-based table renderer for notebooks using DataFrame Styler.

PandasTableBackend

Bases: TableBackendBase

Render tables using the pandas Styler in Jupyter environments.

Source code in src/easydiffraction/display/tablers/pandas.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
 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
class PandasTableBackend(TableBackendBase):
    """Render tables using the pandas Styler in Jupyter environments."""

    @staticmethod
    def _build_base_styles(color: str) -> list[dict]:
        """
        Return base CSS table styles for a given border color.

        Parameters
        ----------
        color : str
            CSS color value (e.g., ``#RRGGBB``) to use for borders and
            header accents.

        Returns
        -------
        list[dict]
            A list of ``Styler.set_table_styles`` dictionaries.
        """
        return [
            # Margins and outer border on the entire table
            {
                'selector': ' ',
                'props': [
                    ('border', f'1px solid {color}'),
                    ('border-collapse', 'collapse'),
                    ('margin-top', '0.5em'),
                    ('margin-left', '0.5em'),
                ],
            },
            # Horizontal border under header row
            {
                'selector': 'thead',
                'props': [
                    ('border-bottom', f'1px solid {color}'),
                ],
            },
            # Cell border, padding and line height
            {
                'selector': 'th, td',
                'props': [
                    ('border', 'none'),
                    ('padding-top', '0.25em'),
                    ('padding-bottom', '0.25em'),
                    ('line-height', '1.15em'),
                ],
            },
            # Style for index column
            {
                'selector': 'th.row_heading',
                'props': [
                    ('color', color),
                    ('font-weight', 'normal'),
                ],
            },
            # Remove zebra-row background
            {
                'selector': 'tbody tr:nth-child(odd), tbody tr:nth-child(even)',
                'props': [
                    ('background-color', 'transparent'),
                ],
            },
        ]

    @staticmethod
    def _build_header_alignment_styles(df: object, alignments: object) -> list[dict]:
        """
        Generate header cell alignment styles per column.

        Parameters
        ----------
        df : object
            DataFrame whose columns are being rendered.
        alignments : object
            Iterable of text alignment values (e.g., ``'left'``,
            ``'center'``) matching ``df`` columns.

        Returns
        -------
        list[dict]
            A list of CSS rules for header cell alignment.
        """
        return [
            {
                'selector': f'th.col{df.columns.get_loc(column)}',
                'props': [('text-align', align)],
            }
            for column, align in zip(df.columns, alignments, strict=False)
        ]

    @staticmethod
    def _strip_rich_markup(df: object) -> tuple[object, object | None]:
        """
        Strip Rich color markup and build a CSS style frame.

        Scans every cell for patterns like ``[red]text[/red]``. Matching
        cells have the markup removed and a corresponding ``color:
        <name>`` CSS entry in the returned style frame.

        Parameters
        ----------
        df : object
            DataFrame whose string cells may contain Rich markup.

        Returns
        -------
        tuple[object, object | None]
            ``(clean_df, style_df)`` where *style_df* is ``None`` when
            no markup was found.
        """
        clean = df.copy()
        styles = df.copy().astype(str)
        found = False
        for col in df.columns:
            for idx in df.index:
                val = str(df.at[idx, col])
                m = _RICH_COLOR_RE.fullmatch(val)
                if m:
                    tag, text = m.groups()
                    clean.at[idx, col] = text
                    styles.at[idx, col] = f'color: {tag}'
                    found = True
                else:
                    styles.at[idx, col] = ''
        return clean, styles if found else None

    def _apply_styling(self, df: object, alignments: object, color: str) -> object:
        """
        Build a configured Styler with alignments and base styles.

        Parameters
        ----------
        df : object
            DataFrame to style.
        alignments : object
            Iterable of text alignment values for columns.
        color : str
            CSS color value used for borders/header.

        Returns
        -------
        object
            A configured pandas Styler ready for display.
        """
        df, color_styles = self._strip_rich_markup(df)

        table_styles = self._build_base_styles(color)
        header_alignment_styles = self._build_header_alignment_styles(df, alignments)

        styler = df.style.format(precision=self.FLOAT_PRECISION)
        if color_styles is not None:
            styler = styler.apply(lambda _: color_styles, axis=None)
        styler = styler.set_table_attributes('class="dataframe"')  # For mkdocs-jupyter
        styler = styler.set_table_styles(table_styles + header_alignment_styles)

        for column, align in zip(df.columns, alignments, strict=False):
            styler = styler.set_properties(
                subset=[column],
                **{'text-align': align},
            )
        return styler

    @staticmethod
    def _update_display(styler: object, display_handle: object) -> None:
        """
        Single, consistent update path for Jupyter.

        If a handle with ``update()`` is provided and it's a
        DisplayHandle, update the output area in-place using HTML.
        Otherwise, display once via IPython ``display()``.

        Parameters
        ----------
        styler : object
            Configured DataFrame Styler to be rendered.
        display_handle : object
            Optional IPython DisplayHandle used for in-place updates.
        """
        # Handle with update() method
        if display_handle is not None and hasattr(display_handle, 'update'):
            # IPython DisplayHandle path
            if can_use_ipython_display(display_handle) and HTML is not None:
                try:
                    html = styler.to_html()
                    display_handle.update(HTML(html))
                except (TypeError, ValueError, AttributeError, RuntimeError, OSError) as err:
                    log.debug(f'Pandas DisplayHandle update failed: {err!r}')
                else:
                    return

            # This should not happen in Pandas backend
            else:
                pass

        # Normal display
        display(styler)

    def render(
        self,
        alignments: object,
        df: object,
        display_handle: object | None = None,
    ) -> object:
        """
        Render a styled DataFrame.

        Parameters
        ----------
        alignments : object
            Iterable of column justifications (e.g. 'left').
        df : object
            DataFrame whose index is displayed as the first column.
        display_handle : object | None, default=None
            Optional IPython DisplayHandle to update an existing output
            area in place when running in Jupyter.

        Returns
        -------
        object
            Backend-defined return value (commonly ``None``).
        """
        color = self._pandas_border_color
        styler = self._apply_styling(df, alignments, color)
        self._update_display(styler, display_handle)
render(alignments, df, display_handle=None)

Render a styled DataFrame.

Parameters:

Name Type Description Default
alignments object

Iterable of column justifications (e.g. 'left').

required
df object

DataFrame whose index is displayed as the first column.

required
display_handle object | None

Optional IPython DisplayHandle to update an existing output area in place when running in Jupyter.

None

Returns:

Type Description
object

Backend-defined return value (commonly None).

Source code in src/easydiffraction/display/tablers/pandas.py
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
def render(
    self,
    alignments: object,
    df: object,
    display_handle: object | None = None,
) -> object:
    """
    Render a styled DataFrame.

    Parameters
    ----------
    alignments : object
        Iterable of column justifications (e.g. 'left').
    df : object
        DataFrame whose index is displayed as the first column.
    display_handle : object | None, default=None
        Optional IPython DisplayHandle to update an existing output
        area in place when running in Jupyter.

    Returns
    -------
    object
        Backend-defined return value (commonly ``None``).
    """
    color = self._pandas_border_color
    styler = self._apply_styling(df, alignments, color)
    self._update_display(styler, display_handle)

rich

Rich-based table renderer for terminals and notebooks.

RichTableBackend

Bases: TableBackendBase

Render tables to terminal or Jupyter using the Rich library.

Source code in src/easydiffraction/display/tablers/rich.py
 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
class RichTableBackend(TableBackendBase):
    """Render tables to terminal or Jupyter using the Rich library."""

    @staticmethod
    def _to_html(table: Table) -> str:
        """
        Render a Rich table to HTML using an off-screen console.

        A fresh ``Console(record=True, file=StringIO())`` avoids private
        attribute access and guarantees no visible output in notebooks.

        Parameters
        ----------
        table : Table
            Rich :class:`~rich.table.Table` to export.

        Returns
        -------
        str
            HTML string with inline styles for notebook display.
        """
        tmp = Console(force_jupyter=False, record=True, file=io.StringIO())
        tmp.print(table)
        html = tmp.export_html(inline_styles=True)
        # Remove margins inside pre blocks and adjust font size
        return html.replace(
            '<pre ',
            "<pre style='margin:0; font-size: 0.9em !important; ' ",
        )

    def _build_table(self, df: object, alignments: object, color: str) -> Table:
        """
        Construct a Rich Table with formatted data and alignment.

        Parameters
        ----------
        df : object
            DataFrame-like object providing rows to render.
        alignments : object
            Iterable of text alignment values for columns.
        color : str
            Rich color name used for borders/index style.

        Returns
        -------
        Table
            A :class:`~rich.table.Table` configured for display.
        """
        table = Table(
            title=None,
            box=RICH_TABLE_BOX,
            show_header=True,
            header_style='bold',
            border_style=color,
        )

        # Index column
        table.add_column(justify='right', style=color)

        # Data columns
        for col, align in zip(df, alignments, strict=False):
            table.add_column(str(col), justify=align, no_wrap=False)

        # Rows
        for idx, row_values in df.iterrows():
            formatted_row = [self._format_value(v) for v in row_values]
            table.add_row(str(idx), *formatted_row)

        return table

    def _update_display(self, table: Table, display_handle: object) -> None:
        """
        Single, consistent update path for Jupyter and terminal.

        - With a handle that has ``update()``: * If it's an IPython
        DisplayHandle, export to HTML and update. * Otherwise, treat it
        as a terminal/live-like handle and update with the Rich
        renderable. - Without a handle, print once to the shared
        console.

        Parameters
        ----------
        table : Table
            Rich :class:`~rich.table.Table` to display.
        display_handle : object
            Optional environment-specific handle for in- place updates
            (IPython or terminal live).
        """
        # Handle with update() method
        if display_handle is not None and hasattr(display_handle, 'update'):
            # IPython DisplayHandle path
            if can_use_ipython_display(display_handle) and HTML is not None:
                try:
                    html = self._to_html(table)
                    display_handle.update(HTML(html))
                except (TypeError, ValueError, AttributeError, RuntimeError, OSError) as err:
                    log.debug(f'Rich to HTML DisplayHandle update failed: {err!r}')
                else:
                    return

            # Assume terminal/live-like handle
            else:
                try:
                    display_handle.update(table)
                except (TypeError, ValueError, AttributeError, RuntimeError, OSError) as err:
                    log.debug(f'Rich live handle update failed: {err!r}')
                else:
                    return

        # Normal print to console
        console = ConsoleManager.get()
        console.print(table)

    def render(
        self,
        alignments: object,
        df: object,
        display_handle: object = None,
    ) -> object:
        """
        Render a styled table using Rich.

        Parameters
        ----------
        alignments : object
            Iterable of text-align values for columns.
        df : object
            Index-aware DataFrame to render.
        display_handle : object, default=None
            Optional environment handle for in-place updates.

        Returns
        -------
        object
            Backend-defined return value (commonly ``None``).
        """
        color = self._rich_border_color
        table = self._build_table(df, alignments, color)
        self._update_display(table, display_handle)
render(alignments, df, display_handle=None)

Render a styled table using Rich.

Parameters:

Name Type Description Default
alignments object

Iterable of text-align values for columns.

required
df object

Index-aware DataFrame to render.

required
display_handle object

Optional environment handle for in-place updates.

None

Returns:

Type Description
object

Backend-defined return value (commonly None).

Source code in src/easydiffraction/display/tablers/rich.py
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
def render(
    self,
    alignments: object,
    df: object,
    display_handle: object = None,
) -> object:
    """
    Render a styled table using Rich.

    Parameters
    ----------
    alignments : object
        Iterable of text-align values for columns.
    df : object
        Index-aware DataFrame to render.
    display_handle : object, default=None
        Optional environment handle for in-place updates.

    Returns
    -------
    object
        Backend-defined return value (commonly ``None``).
    """
    color = self._rich_border_color
    table = self._build_table(df, alignments, color)
    self._update_display(table, display_handle)

tables

Table rendering engines: console (Rich) and Jupyter (pandas).

TableEngineEnum

Bases: StrEnum

Available table rendering backends.

Source code in src/easydiffraction/display/tables.py
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 TableEngineEnum(StrEnum):
    """Available table rendering backends."""

    RICH = 'rich'
    PANDAS = 'pandas'

    @classmethod
    def default(cls) -> TableEngineEnum:
        """
        Select default engine based on environment.

        Returns Pandas when running in Jupyter, otherwise Rich.
        """
        if in_jupyter():
            log.debug('Setting default table engine to Pandas for Jupyter')
            return cls.PANDAS
        log.debug('Setting default table engine to Rich for console')
        return cls.RICH

    def description(self) -> str:
        """
        Return a human-readable description of this table engine.

        Returns
        -------
        str
            Description string for the current enum member.
        """
        if self is TableEngineEnum.RICH:
            return 'Console rendering with Rich'
        if self is TableEngineEnum.PANDAS:
            return 'Jupyter DataFrame rendering with Pandas'
        return ''

default() classmethod

Select default engine based on environment.

Returns Pandas when running in Jupyter, otherwise Rich.

Source code in src/easydiffraction/display/tables.py
26
27
28
29
30
31
32
33
34
35
36
37
@classmethod
def default(cls) -> TableEngineEnum:
    """
    Select default engine based on environment.

    Returns Pandas when running in Jupyter, otherwise Rich.
    """
    if in_jupyter():
        log.debug('Setting default table engine to Pandas for Jupyter')
        return cls.PANDAS
    log.debug('Setting default table engine to Rich for console')
    return cls.RICH

description()

Return a human-readable description of this table engine.

Returns:

Type Description
str

Description string for the current enum member.

Source code in src/easydiffraction/display/tables.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def description(self) -> str:
    """
    Return a human-readable description of this table engine.

    Returns
    -------
    str
        Description string for the current enum member.
    """
    if self is TableEngineEnum.RICH:
        return 'Console rendering with Rich'
    if self is TableEngineEnum.PANDAS:
        return 'Jupyter DataFrame rendering with Pandas'
    return ''

TableRenderer

Bases: RendererBase

Renderer for tabular data with selectable engines (singleton).

Source code in src/easydiffraction/display/tables.py
 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
class TableRenderer(RendererBase):
    """Renderer for tabular data with selectable engines (singleton)."""

    @classmethod
    def _factory(cls) -> RendererFactoryBase:
        return TableRendererFactory

    @classmethod
    def _default_engine(cls) -> str:
        """Default engine derived from TableEngineEnum."""
        return TableEngineEnum.default().value

    def show_config(self) -> None:
        """Display minimal configuration for this renderer."""
        headers = [
            ('Parameter', 'left'),
            ('Value', 'left'),
        ]
        rows = [['engine', self._engine]]
        df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(headers))
        console.paragraph('Current tabler configuration')
        TableRenderer.get().render(df)

    def render(self, df: object, display_handle: object | None = None) -> object:
        """
        Render a DataFrame as a table using the active backend.

        Parameters
        ----------
        df : object
            DataFrame with a two-level column index where the second
            level provides per-column alignment.
        display_handle : object | None, default=None
            Optional environment-specific handle used to update an
            existing output area in-place (e.g., an IPython
            DisplayHandle or a terminal live handle).

        Returns
        -------
        object
            Backend-specific return value (usually ``None``).
        """
        # Work on a copy to avoid mutating the original DataFrame
        df = df.copy()

        # Force starting index from 1
        df.index += 1

        # Extract column alignments
        alignments = df.columns.get_level_values(1)

        # Remove alignments from df (Keep only the first index level)
        df.columns = df.columns.get_level_values(0)

        return self._backend.render(alignments, df, display_handle)

render(df, display_handle=None)

Render a DataFrame as a table using the active backend.

Parameters:

Name Type Description Default
df object

DataFrame with a two-level column index where the second level provides per-column alignment.

required
display_handle object | None

Optional environment-specific handle used to update an existing output area in-place (e.g., an IPython DisplayHandle or a terminal live handle).

None

Returns:

Type Description
object

Backend-specific return value (usually None).

Source code in src/easydiffraction/display/tables.py
 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
def render(self, df: object, display_handle: object | None = None) -> object:
    """
    Render a DataFrame as a table using the active backend.

    Parameters
    ----------
    df : object
        DataFrame with a two-level column index where the second
        level provides per-column alignment.
    display_handle : object | None, default=None
        Optional environment-specific handle used to update an
        existing output area in-place (e.g., an IPython
        DisplayHandle or a terminal live handle).

    Returns
    -------
    object
        Backend-specific return value (usually ``None``).
    """
    # Work on a copy to avoid mutating the original DataFrame
    df = df.copy()

    # Force starting index from 1
    df.index += 1

    # Extract column alignments
    alignments = df.columns.get_level_values(1)

    # Remove alignments from df (Keep only the first index level)
    df.columns = df.columns.get_level_values(0)

    return self._backend.render(alignments, df, display_handle)

show_config()

Display minimal configuration for this renderer.

Source code in src/easydiffraction/display/tables.py
67
68
69
70
71
72
73
74
75
76
def show_config(self) -> None:
    """Display minimal configuration for this renderer."""
    headers = [
        ('Parameter', 'left'),
        ('Value', 'left'),
    ]
    rows = [['engine', self._engine]]
    df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(headers))
    console.paragraph('Current tabler configuration')
    TableRenderer.get().render(df)

TableRendererFactory

Bases: RendererFactoryBase

Factory for creating tabler instances.

Source code in src/easydiffraction/display/tables.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class TableRendererFactory(RendererFactoryBase):
    """Factory for creating tabler instances."""

    @classmethod
    def _registry(cls) -> dict:
        """
        Build registry, adapting available engines to the environment.

        - In Jupyter: expose both 'rich' and 'pandas'. - In terminal:
        expose only 'rich' (pandas is notebook-only).
        """
        base = {
            TableEngineEnum.RICH.value: {
                'description': TableEngineEnum.RICH.description(),
                'class': RichTableBackend,
            }
        }
        if in_jupyter():
            base[TableEngineEnum.PANDAS.value] = {
                'description': TableEngineEnum.PANDAS.description(),
                'class': PandasTableBackend,
            }
        return base

utils

JupyterScrollManager

Ensures Jupyter output cells are not scrollable (once).

Source code in src/easydiffraction/display/utils.py
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
class JupyterScrollManager:
    """Ensures Jupyter output cells are not scrollable (once)."""

    _applied: ClassVar[bool] = False

    @classmethod
    def disable_jupyter_scroll(cls) -> None:
        """Inject CSS to prevent output cells from being scrollable."""
        if cls._applied or not in_jupyter() or display is None or HTML is None:
            return

        css = """
        <style>
        /* Disable scrolling (already present) */
        .jp-OutputArea,
        .jp-OutputArea-child,
        .jp-OutputArea-scrollable,
        .output_scroll {
            max-height: none !important;
            overflow-y: visible !important;
        }
        """
        try:
            display(HTML(css))
            cls._applied = True
        except (TypeError, ValueError, AttributeError, RuntimeError, OSError):
            log.debug('Failed to inject Jupyter CSS to disable scrolling.')

disable_jupyter_scroll() classmethod

Inject CSS to prevent output cells from being scrollable.

Source code in src/easydiffraction/display/utils.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@classmethod
def disable_jupyter_scroll(cls) -> None:
    """Inject CSS to prevent output cells from being scrollable."""
    if cls._applied or not in_jupyter() or display is None or HTML is None:
        return

    css = """
    <style>
    /* Disable scrolling (already present) */
    .jp-OutputArea,
    .jp-OutputArea-child,
    .jp-OutputArea-scrollable,
    .output_scroll {
        max-height: none !important;
        overflow-y: visible !important;
    }
    """
    try:
        display(HTML(css))
        cls._applied = True
    except (TypeError, ValueError, AttributeError, RuntimeError, OSError):
        log.debug('Failed to inject Jupyter CSS to disable scrolling.')