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
 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
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)

    def plot_powder_meas_vs_calc(
        self,
        plot_spec: PowderMeasVsCalcSpec,
    ) -> None:
        """
        Render a composite powder plot in the terminal.

        The ASCII backend falls back to the existing single-chart view
        for measured, calculated, and residual series. Bragg tick rows
        are announced but not rendered graphically.
        """
        y_series = [plot_spec.y_meas, plot_spec.y_calc]
        labels = ['meas', 'calc']
        if plot_spec.y_resid is not None:
            y_series.append(plot_spec.y_resid)
            labels.append('resid')

        self.plot_powder(
            x=plot_spec.x,
            y_series=y_series,
            labels=labels,
            axes_labels=plot_spec.axes_labels,
            title=plot_spec.title,
            height=plot_spec.height,
        )
        if plot_spec.bragg_tick_sets:
            console.print('Bragg peak subplot rows are available with the Plotly engine only.')

    @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
 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
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_powder_meas_vs_calc(plot_spec)

Render a composite powder plot in the terminal.

The ASCII backend falls back to the existing single-chart view for measured, calculated, and residual series. Bragg tick rows are announced but not rendered graphically.

Source code in src/easydiffraction/display/plotters/ascii.py
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
def plot_powder_meas_vs_calc(
    self,
    plot_spec: PowderMeasVsCalcSpec,
) -> None:
    """
    Render a composite powder plot in the terminal.

    The ASCII backend falls back to the existing single-chart view
    for measured, calculated, and residual series. Bragg tick rows
    are announced but not rendered graphically.
    """
    y_series = [plot_spec.y_meas, plot_spec.y_calc]
    labels = ['meas', 'calc']
    if plot_spec.y_resid is not None:
        y_series.append(plot_spec.y_resid)
        labels.append('resid')

    self.plot_powder(
        x=plot_spec.x,
        y_series=y_series,
        labels=labels,
        axes_labels=plot_spec.axes_labels,
        title=plot_spec.title,
        height=plot_spec.height,
    )
    if plot_spec.bragg_tick_sets:
        console.print('Bragg peak subplot rows are available with the Plotly engine only.')
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
@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
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
@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.

BraggTickSet dataclass

Bragg tick data for one linked phase row.

The plotting facade converts experiment reflection-category data into this display-specific container so plotting backends stay decoupled from experiment datablock internals.

Source code in src/easydiffraction/display/plotters/base.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@dataclass(frozen=True)
class BraggTickSet:
    """
    Bragg tick data for one linked phase row.

    The plotting facade converts experiment reflection-category data
    into this display-specific container so plotting backends stay
    decoupled from experiment datablock internals.
    """

    phase_id: str
    x: np.ndarray
    h: np.ndarray
    k: np.ndarray
    ell: np.ndarray
    f_squared_calc: np.ndarray
    f_calc: np.ndarray

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
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
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_powder_meas_vs_calc(
        self,
        plot_spec: PowderMeasVsCalcSpec,
    ) -> None:
        """
        Render a composite powder plot with Bragg ticks and residual.

        Parameters
        ----------
        plot_spec : PowderMeasVsCalcSpec
            Composite powder-plot inputs and layout settings.
        """

    @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
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
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
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
@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_powder_meas_vs_calc(plot_spec) abstractmethod

Render a composite powder plot with Bragg ticks and residual.

Parameters:

Name Type Description Default
plot_spec PowderMeasVsCalcSpec

Composite powder-plot inputs and layout settings.

required
Source code in src/easydiffraction/display/plotters/base.py
250
251
252
253
254
255
256
257
258
259
260
261
262
@abstractmethod
def plot_powder_meas_vs_calc(
    self,
    plot_spec: PowderMeasVsCalcSpec,
) -> None:
    """
    Render a composite powder plot with Bragg ticks and residual.

    Parameters
    ----------
    plot_spec : PowderMeasVsCalcSpec
        Composite powder-plot inputs and layout settings.
    """
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
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
@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
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
@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).
    """

PowderMeasVsCalcSpec dataclass

Specification for one composite powder plot.

The plotting facade assembles the measured, background, calculated, residual, and Bragg-tick data into this display-specific object before delegating to a backend.

Source code in src/easydiffraction/display/plotters/base.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass(frozen=True)
class PowderMeasVsCalcSpec:
    """
    Specification for one composite powder plot.

    The plotting facade assembles the measured, background, calculated,
    residual, and Bragg-tick data into this display-specific object
    before delegating to a backend.
    """

    x: np.ndarray
    y_meas: np.ndarray
    y_calc: np.ndarray
    y_resid: np.ndarray | None
    bragg_tick_sets: tuple[BraggTickSet, ...]
    axes_labels: list[str]
    title: str
    residual_height_fraction: float
    bragg_peaks_height_fraction: float
    height: int | None = None
    y_bkg: np.ndarray | None = None

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
  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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
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)'

    @classmethod
    def _legend_background_color(cls) -> str:
        """Return a half-transparent legend background color."""
        if cls._is_dark_mode():
            return 'rgba(0, 0, 0, 0.5)'
        return 'rgba(255, 255, 255, 0.5)'

    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,
        *,
        customdata: object | None = None,
        hovertemplate: str | None = None,
    ) -> 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'``, ``'bkg'``, ``'calc'``, or
            ``'resid'``).
        customdata : object | None, default=None
            Optional per-point payload used by the hover template.
        hovertemplate : str | None, default=None
            Optional hover template overriding the default per-trace
            one.

        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_width = {
            'meas': MEASURED_LINE_WIDTH,
            'bkg': BACKGROUND_LINE_WIDTH,
            'calc': CALCULATED_LINE_WIDTH,
            'resid': RESIDUAL_LINE_WIDTH,
        }[label]
        line = {'color': color, 'width': line_width}
        legend_rank = {
            'meas': 10,
            'bkg': 20,
            'calc': 30,
            'resid': 40,
        }[label]

        return go.Scatter(
            x=x,
            y=y,
            line=line,
            mode=mode,
            name=name,
            legendrank=legend_rank,
            customdata=customdata,
            hovertemplate=(
                hovertemplate
                if hovertemplate is not None
                else f'{name}<br>x: %{{x}}<br>y: %{{y}}<extra></extra>'
            ),
        )

    @staticmethod
    def _powder_meas_vs_calc_hover_data(plot_spec: PowderMeasVsCalcSpec) -> np.ndarray:
        """Return shared hover values for composite powder traces."""
        residual_values = (
            np.asarray(plot_spec.y_resid)
            if plot_spec.y_resid is not None
            else np.asarray(plot_spec.y_meas) - np.asarray(plot_spec.y_calc)
        )
        if plot_spec.y_bkg is None:
            return np.column_stack((
                np.asarray(plot_spec.y_meas),
                np.asarray(plot_spec.y_calc),
                residual_values,
            ))

        return np.column_stack((
            np.asarray(plot_spec.y_meas),
            np.asarray(plot_spec.y_bkg),
            np.asarray(plot_spec.y_calc),
            residual_values,
        ))

    @staticmethod
    def _powder_meas_vs_calc_hover_template(plot_spec: PowderMeasVsCalcSpec) -> str:
        """
        Return a shared hover template for composite powder traces.
        """
        if plot_spec.y_bkg is None:
            return (
                'x: %{x:,.2f}<br>'
                'Imeas: %{customdata[0]:,.2f}<br>'
                'Icalc: %{customdata[1]:,.2f}<br>'
                'Imeas - Icalc: %{customdata[2]:,.2f}'
                '<extra></extra>'
            )

        return (
            'x: %{x:,.2f}<br>'
            'Imeas: %{customdata[0]:,.2f}<br>'
            'Ibkg: %{customdata[1]:,.2f}<br>'
            'Icalc: %{customdata[2]:,.2f}<br>'
            'Imeas - Icalc: %{customdata[3]:,.2f}'
            '<extra></extra>'
        )

    @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 {
            'displayModeBar': True,
            'displaylogo': False,
            'modeBarButtonsToRemove': [
                'select2d',
                'lasso2d',
                'zoomIn2d',
                'zoomOut2d',
                'autoScale2d',
            ],
        }

    @staticmethod
    def _modebar_legend_toggle_post_script() -> str:
        """
        Return client-side code for a legend-toggle modebar button.
        """
        return r"""
const graphDiv = document.getElementById('{plot_id}');
if (!graphDiv) {
    return;
}

const parseColor = function (colorValue) {
    if (!colorValue) {
        return null;
    }

    const rgbMatch = colorValue.match(/^rgba?\(([^)]+)\)$/);
    if (rgbMatch) {
        const channels = rgbMatch[1].split(',').slice(0, 3).map((value) => Number(value.trim()));
        if (channels.every((value) => Number.isFinite(value))) {
            return {red: channels[0], green: channels[1], blue: channels[2]};
        }
    }

    const hexMatch = colorValue.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
    if (!hexMatch) {
        return null;
    }

    const normalizedHex = hexMatch[1].length === 3
        ? hexMatch[1].split('').map((value) => value + value).join('')
        : hexMatch[1];
    return {
        red: Number.parseInt(normalizedHex.slice(0, 2), 16),
        green: Number.parseInt(normalizedHex.slice(2, 4), 16),
        blue: Number.parseInt(normalizedHex.slice(4, 6), 16),
    };
};

const resolveLegendButtonFill = function (opacity) {
    const referencePath = graphDiv.querySelector('.modebar-btn path');
    const referenceFill = referencePath ? window.getComputedStyle(referencePath).fill : null;
    const fontColor = graphDiv._fullLayout && graphDiv._fullLayout.font
        ? graphDiv._fullLayout.font.color
        : null;
    const parsedColor = (
        parseColor(referenceFill)
        || parseColor(fontColor)
        || {red: 68, green: 68, blue: 68}
    );
    return (
        'rgba('
        + parsedColor.red
        + ', '
        + parsedColor.green
        + ', '
        + parsedColor.blue
        + ', '
        + opacity
        + ')'
    );
};

const updateLegendButtonAppearance = function (legendVisible) {
    const legendButton = graphDiv.querySelector('[data-legend-toggle="true"]');
    if (!legendButton) {
        return;
    }

    const legendIconPath = legendButton.querySelector('path');
    if (!legendIconPath) {
        return;
    }

    legendButton.classList.toggle('active', legendVisible);
    legendButton.setAttribute('aria-pressed', String(legendVisible));
    legendIconPath.setAttribute(
        'style',
        'fill: ' + resolveLegendButtonFill(legendVisible ? 0.7 : 0.3) + ';',
    );
};

const applyLegendVisibility = function (legendVisible) {
    const legend = graphDiv.querySelector('.legend');
    if (legend) {
        legend.style.display = legendVisible ? 'inline' : 'none';
        legend.style.visibility = legendVisible ? 'visible' : 'hidden';
        legend.style.pointerEvents = legendVisible ? '' : 'none';
    }

    if (graphDiv.layout) {
        graphDiv.layout.showlegend = legendVisible;
    }

    if (graphDiv._fullLayout) {
        graphDiv._fullLayout.showlegend = legendVisible;
    }
};

const readLegendVisibility = function () {
    if (graphDiv.dataset.legendVisible === 'true') {
        return true;
    }

    if (graphDiv.dataset.legendVisible === 'false') {
        return false;
    }

    const legend = graphDiv.querySelector('.legend');
    if (legend) {
        return (
            window.getComputedStyle(legend).display !== 'none'
            && window.getComputedStyle(legend).visibility !== 'hidden'
        );
    }

    if (graphDiv.layout && typeof graphDiv.layout.showlegend === 'boolean') {
        return graphDiv.layout.showlegend;
    }

    if (graphDiv._fullLayout && typeof graphDiv._fullLayout.showlegend === 'boolean') {
        return graphDiv._fullLayout.showlegend;
    }

    return true;
};

const syncLegendVisibility = function (legendVisible) {
    const resolvedLegendVisible = typeof legendVisible === 'boolean'
        ? legendVisible
        : readLegendVisibility();
    graphDiv.dataset.legendVisible = String(resolvedLegendVisible);
    applyLegendVisibility(resolvedLegendVisible);
    updateLegendButtonAppearance(resolvedLegendVisible);
    return resolvedLegendVisible;
};

const toggleLegend = function (event) {
    if (event) {
        event.preventDefault();
        event.stopPropagation();
    }

    const currentValue = readLegendVisibility();
    const nextValue = !currentValue;
    syncLegendVisibility(nextValue);
};

const installLegendToggleButton = function () {
    const modebar = graphDiv.querySelector('.modebar');
    if (!modebar) {
        return;
    }

    if (!modebar.querySelector('.modebar-group')) {
        return;
    }

    let legendButton = modebar.querySelector('[data-legend-toggle="true"]');
    if (!legendButton) {
        const legendButtonGroup = document.createElement('div');
        legendButtonGroup.className = 'modebar-group';

        legendButton = document.createElement('a');
        legendButton.className = 'modebar-btn';
        legendButton.href = 'javascript:void(0)';
        legendButton.setAttribute('data-title', 'Toggle legend');
        legendButton.setAttribute('data-legend-toggle', 'true');
        legendButton.setAttribute('aria-label', 'Toggle legend');
        legendButton.setAttribute('role', 'button');
        legendButton.setAttribute('tabindex', '0');
        legendButton.innerHTML = [
            '<svg viewBox="0 0 1000 1000"'
            + ' class="icon" height="1em" width="1em"'
            + ' aria-hidden="true">',
            '<path d="M120 160H240V280H120z M120 440H240V560H120z '
            + 'M120 720H240V840H120z M320 200H880V240H320z '
            + 'M320 480H880V520H320z M320 760H880V800H320z"></path>',
            '</svg>',
        ].join('');

        legendButtonGroup.appendChild(legendButton);
        modebar.appendChild(legendButtonGroup);
    }

    legendButton.onclick = toggleLegend;
    legendButton.onkeydown = function (event) {
        if (event.key === 'Enter' || event.key === ' ') {
            toggleLegend(event);
        }
    };

    syncLegendVisibility();
};

if (graphDiv.on) {
    graphDiv.on('plotly_afterplot', installLegendToggleButton);
    graphDiv.on('plotly_relayout', function (eventData) {
        if (eventData && typeof eventData.showlegend === 'boolean') {
            syncLegendVisibility(eventData.showlegend);
            return;
        }

        syncLegendVisibility();
    });
}
syncLegendVisibility();
window.requestAnimationFrame(installLegendToggleButton);
"""

    @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

    @staticmethod
    def _has_visible_legend(fig: object) -> bool:
        """Return whether a figure exposes at least one legend entry."""

        def _trace_value(trace: object, field_name: str) -> object:
            value = getattr(trace, field_name, None)
            if value is not None:
                return value

            trace_kwargs = getattr(trace, 'kwargs', None)
            if isinstance(trace_kwargs, dict):
                return trace_kwargs.get(field_name)

            return None

        layout = getattr(fig, 'layout', None)
        layout_showlegend = getattr(layout, 'showlegend', None)
        if layout_showlegend is False:
            return False

        for trace in getattr(fig, 'data', ()):
            if _trace_value(trace, 'visible') is False:
                continue
            if _trace_value(trace, 'showlegend') is False:
                continue
            if _trace_value(trace, 'name'):
                return True

        return False

    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:
            post_script = None
            if self._has_visible_legend(fig):
                post_script = self._modebar_legend_toggle_post_script()
            html_fig = pio.to_html(
                fig,
                include_plotlyjs='cdn',
                full_html=False,
                config=config,
                post_script=post_script,
            )
            display(HTML(html_fig))

    @classmethod
    def _get_layout(
        cls,
        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={
                'bgcolor': cls._legend_background_color(),
                '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)

    @staticmethod
    def _get_bragg_tick_trace(
        tick_set: BraggTickSet,
        row_y: float,
        color: str,
    ) -> object:
        """
        Create a hover-capable Bragg tick trace for one linked phase.
        """
        y = np.full(tick_set.x.shape, row_y, dtype=float)
        hover_text = []
        for idx, x_value in enumerate(tick_set.x):
            index_h = int(tick_set.h[idx])
            index_k = int(tick_set.k[idx])
            index_l = int(tick_set.ell[idx])
            hover_text.append(
                f'{tick_set.phase_id}<br>'
                f'x: {float(x_value):,.2f}<br>'
                f'Miller indices: ({index_h} {index_k} {index_l})<br>'
                # f'F²cal:{float(tick_set.f_squared_calc[idx]):.6g}<br>'
                # f'Fcalc:{float(tick_set.f_calc[idx]):.6g}'
                '<extra></extra>'
            )

        return go.Scatter(
            x=tick_set.x,
            y=y,
            mode='markers',
            marker={
                'symbol': 'line-ns-open',
                'size': BRAGG_TICK_MARKER_SIZE,
                'line': {'width': BRAGG_TICK_MARKER_LINE_WIDTH},
                'color': color,
            },
            name=f'Bragg peaks: {tick_set.phase_id}',
            text=hover_text,
            hoverlabel={
                'font': {'color': 'white'},
                'bordercolor': 'white',
            },
            hovertemplate='%{text}',
        )

    @staticmethod
    def _nice_axis_limit(raw_limit: float) -> float:
        """Round a positive axis limit up to a readable value."""
        if raw_limit <= 0:
            return 1.0

        exponent = float(np.floor(np.log10(raw_limit)))
        base = 10.0**exponent
        fraction = raw_limit / base

        for nice_fraction in NICE_AXIS_FRACTIONS:
            if fraction <= nice_fraction:
                return nice_fraction * base
        return NICE_AXIS_FRACTIONS[-1] * base

    @staticmethod
    def _get_display_tick_limit(raw_limit: float) -> float:
        """Return a rounded positive tick limit within ``raw_limit``."""
        if raw_limit <= 0:
            return 1.0

        exponent = float(np.floor(np.log10(raw_limit)))
        base = 10.0**exponent
        fraction = raw_limit / base

        for nice_fraction in reversed(DISPLAY_TICK_FRACTIONS):
            if fraction >= nice_fraction:
                return nice_fraction * base
        return DISPLAY_TICK_FRACTIONS[0] * base

    @staticmethod
    def _base_composite_height_pixels(plot_spec: PowderMeasVsCalcSpec) -> float:
        """Return the baseline figure height for a single-phase plot."""
        if plot_spec.height is None:
            return float(DEFAULT_HEIGHT * PLOTLY_HEIGHT_PER_UNIT)
        return float(plot_spec.height)

    @staticmethod
    def _composite_plot_area_height(full_height: float) -> float:
        """
        Return the drawable plot area height after vertical margins.
        """
        return max(full_height - COMPOSITE_MARGIN_TOP - COMPOSITE_MARGIN_BOTTOM, 1.0)

    @staticmethod
    def _subplot_available_height_fraction(row_count: int) -> float:
        """
        Return the fraction of plot height available for subplot rows.
        """
        return 1.0 - COMPOSITE_VERTICAL_SPACING * max(row_count - 1, 0)

    @staticmethod
    def _bragg_tick_symbol_height_pixels() -> float:
        """Return rendered pixel height for one Bragg tick marker."""
        return (
            BRAGG_TICK_MARKER_SIZE * BRAGG_TICK_SYMBOL_HEIGHT_SCALE + BRAGG_TICK_MARKER_LINE_WIDTH
        )

    @staticmethod
    def _bragg_row_height_pixels(plot_spec: PowderMeasVsCalcSpec) -> float:
        """
        Return the exact Bragg-row pixel height for the current phases.
        """
        return float(
            len(plot_spec.bragg_tick_sets) * PlotlyPlotter._bragg_tick_symbol_height_pixels()
        )

    @classmethod
    def _baseline_non_bragg_row_heights(
        cls,
        plot_spec: PowderMeasVsCalcSpec,
        row_count: int,
        *,
        has_bragg_ticks: bool,
        has_residual: bool,
    ) -> tuple[float, float | None]:
        """Return baseline main and residual row heights in pixels."""
        baseline_height = cls._base_composite_height_pixels(plot_spec)
        plot_area_height = cls._composite_plot_area_height(baseline_height)
        available_row_pixels = plot_area_height * cls._subplot_available_height_fraction(row_count)
        baseline_bragg_pixels = float(
            cls._bragg_tick_symbol_height_pixels() if has_bragg_ticks else 0
        )
        non_bragg_pixels = max(available_row_pixels - baseline_bragg_pixels, 1.0)

        if not has_residual:
            return non_bragg_pixels, None

        main_pixels = non_bragg_pixels / (1.0 + plot_spec.residual_height_fraction)
        residual_pixels = main_pixels * plot_spec.residual_height_fraction
        return main_pixels, residual_pixels

    @staticmethod
    def _get_powder_composite_rows(plot_spec: PowderMeasVsCalcSpec) -> PowderCompositeRows:
        """Resolve subplot rows for the composite powder figure."""
        has_bragg_ticks = bool(plot_spec.bragg_tick_sets)
        has_residual = plot_spec.y_resid is not None
        row_count = 1 + int(has_bragg_ticks) + int(has_residual)
        main_row_height, residual_row_height = PlotlyPlotter._baseline_non_bragg_row_heights(
            plot_spec=plot_spec,
            row_count=row_count,
            has_bragg_ticks=has_bragg_ticks,
            has_residual=has_residual,
        )
        row_heights = [main_row_height]
        bragg_row = None
        residual_row = None
        next_row = 2

        if has_bragg_ticks:
            bragg_row = next_row
            next_row += 1
            row_heights.append(PlotlyPlotter._bragg_row_height_pixels(plot_spec))
        if has_residual:
            residual_row = next_row
            row_heights.append(residual_row_height if residual_row_height is not None else 1.0)

        return PowderCompositeRows(
            row_count=row_count,
            row_heights=row_heights,
            bragg_row=bragg_row,
            residual_row=residual_row,
        )

    @classmethod
    def _composite_figure_height(
        cls,
        plot_spec: PowderMeasVsCalcSpec,
        layout: PowderCompositeRows,
    ) -> float:
        """Return figure height for Bragg row growth."""
        base_pixels = cls._base_composite_height_pixels(plot_spec)
        phase_count = len(plot_spec.bragg_tick_sets)
        if phase_count <= 1:
            return base_pixels

        added_bragg_pixels = float((phase_count - 1) * cls._bragg_tick_symbol_height_pixels())
        growth_pixels = added_bragg_pixels / cls._subplot_available_height_fraction(
            layout.row_count
        )
        return base_pixels + growth_pixels

    @classmethod
    def _get_main_intensity_range(cls, plot_spec: PowderMeasVsCalcSpec) -> tuple[float, float]:
        """
        Return an explicit y-range for the main powder intensity row.
        """
        y_meas = np.asarray(plot_spec.y_meas)
        y_calc = np.asarray(plot_spec.y_calc)
        if min(y_meas.size, y_calc.size) == 0:
            return 0.0, 1.0

        main_series = [y_meas, y_calc]
        if plot_spec.y_bkg is not None:
            y_bkg = np.asarray(plot_spec.y_bkg)
            if y_bkg.size > 0:
                main_series.append(y_bkg)

        main_y_min = float(min(np.min(series) for series in main_series))
        main_y_max = float(max(np.max(series) for series in main_series))
        main_y_range = main_y_max - main_y_min
        if main_y_range > 0.0:
            main_y_margin = main_y_range * MAIN_INTENSITY_RANGE_MARGIN_FRACTION
            return main_y_min - main_y_margin, main_y_max + main_y_margin

        return main_y_min - 1.0, main_y_max + 1.0

    @classmethod
    def _get_residual_limit(cls, plot_spec: PowderMeasVsCalcSpec) -> float:
        """Return a symmetric residual limit matched to the main row."""
        if plot_spec.y_resid is None:
            return 1.0

        y_meas = np.asarray(plot_spec.y_meas)
        y_calc = np.asarray(plot_spec.y_calc)
        y_resid = np.asarray(plot_spec.y_resid)
        if min(y_meas.size, y_calc.size, y_resid.size) == 0:
            return 1.0

        main_y_min, main_y_max = cls._get_main_intensity_range(plot_spec)
        main_y_range = max(main_y_max - main_y_min, 0.0)
        scale_matched_half_range = 0.5 * main_y_range * plot_spec.residual_height_fraction
        if scale_matched_half_range > 0.0:
            return scale_matched_half_range

        return cls._nice_axis_limit(float(np.max(np.abs(y_resid))))

    @staticmethod
    def _composite_x_range(x_values: np.ndarray) -> tuple[float | None, float | None]:
        """Return the explicit x-range for the composite powder plot."""
        if x_values.size == 0:
            return None, None
        return float(np.min(x_values)), float(np.max(x_values))

    def plot_powder_meas_vs_calc(
        self,
        plot_spec: PowderMeasVsCalcSpec,
    ) -> None:
        """
        Render a composite powder plot with optional Bragg ticks.

        The main row shows measured and calculated intensities. The
        Bragg row is added only when tick data is available. The
        residual row is added only when residual data is requested.
        """
        layout = self._get_powder_composite_rows(plot_spec)
        x_min, x_max = self._composite_x_range(np.asarray(plot_spec.x))
        main_y_min, main_y_max = self._get_main_intensity_range(plot_spec)
        residual_limit = None
        hover_data = self._powder_meas_vs_calc_hover_data(plot_spec)
        hover_template = self._powder_meas_vs_calc_hover_template(plot_spec)

        fig = make_subplots(
            rows=layout.row_count,
            cols=1,
            shared_xaxes=True,
            vertical_spacing=COMPOSITE_VERTICAL_SPACING,
            row_heights=layout.row_heights,
        )

        main_traces = (
            (
                ('meas', plot_spec.y_meas),
                ('bkg', plot_spec.y_bkg),
                ('calc', plot_spec.y_calc),
            )
            if plot_spec.y_bkg is not None
            else (
                ('meas', plot_spec.y_meas),
                ('calc', plot_spec.y_calc),
            )
        )
        for label, y_values in main_traces:
            fig.add_trace(
                self._get_powder_trace(
                    plot_spec.x,
                    y_values,
                    label,
                    customdata=hover_data,
                    hovertemplate=hover_template,
                ),
                row=1,
                col=1,
            )

        if layout.bragg_row is not None:
            for idx, tick_set in enumerate(plot_spec.bragg_tick_sets):
                color = BRAGG_TICK_COLORS[idx % len(BRAGG_TICK_COLORS)]
                fig.add_trace(
                    self._get_bragg_tick_trace(
                        tick_set=tick_set,
                        row_y=float(idx + 1),
                        color=color,
                    ),
                    row=layout.bragg_row,
                    col=1,
                )

        if layout.residual_row is not None and plot_spec.y_resid is not None:
            residual_limit = self._get_residual_limit(plot_spec)
            fig.add_trace(
                self._get_powder_trace(
                    plot_spec.x,
                    plot_spec.y_resid,
                    'resid',
                    customdata=hover_data,
                    hovertemplate=hover_template,
                ),
                row=layout.residual_row,
                col=1,
            )

        fig.update_layout(
            height=self._composite_figure_height(plot_spec, layout),
            margin={
                'autoexpand': True,
                'r': COMPOSITE_MARGIN_RIGHT,
                't': COMPOSITE_MARGIN_TOP,
                'b': COMPOSITE_MARGIN_BOTTOM,
            },
            title={'text': plot_spec.title},
            legend={
                'bgcolor': self._legend_background_color(),
                'xanchor': 'right',
                'x': 1.0,
                'yanchor': 'top',
                'y': 1.0,
            },
        )

        for row_idx in range(1, layout.row_count + 1):
            x_axis_kwargs = {
                'matches': 'x',
                'showline': True,
                'mirror': True,
                'zeroline': False,
                'tickformat': ',.6~g',
                'separatethousands': True,
            }
            if x_min is not None and x_max is not None:
                x_axis_kwargs['range'] = [x_min, x_max]
            fig.update_xaxes(row=row_idx, col=1, **x_axis_kwargs)
            fig.update_yaxes(
                showline=True,
                mirror=True,
                zeroline=False,
                tickformat=',.6~g',
                separatethousands=True,
                row=row_idx,
                col=1,
            )

        fig.update_xaxes(showticklabels=(layout.row_count == 1), row=1, col=1)
        fig.update_yaxes(
            title_text=plot_spec.axes_labels[1],
            range=[main_y_min, main_y_max],
            row=1,
            col=1,
        )

        if layout.bragg_row is not None:
            fig.update_yaxes(
                # title_text='Bragg peaks',
                tickmode='array',
                tickvals=[float(idx + 1) for idx in range(len(plot_spec.bragg_tick_sets))],
                ticktext=[tick_set.phase_id for tick_set in plot_spec.bragg_tick_sets],
                range=[float(len(plot_spec.bragg_tick_sets)) + 0.5, 0.5],
                showgrid=False,
                row=layout.bragg_row,
                col=1,
            )
            fig.update_xaxes(
                showticklabels=layout.residual_row is None,
                row=layout.bragg_row,
                col=1,
            )

        if layout.residual_row is not None and plot_spec.y_resid is not None:
            residual_tick_limit = self._get_display_tick_limit(residual_limit)
            fig.update_yaxes(
                # title_text='Residual',
                range=[-residual_limit, residual_limit],
                tickmode='array',
                tickvals=[-residual_tick_limit, 0.0, residual_tick_limit],
                scaleanchor='y',
                scaleratio=1,
                zeroline=False,
                row=layout.residual_row,
                col=1,
            )
            fig.update_xaxes(title_text=plot_spec.axes_labels[0], row=layout.residual_row, col=1)
        else:
            terminal_row = layout.bragg_row if layout.bragg_row is not None else 1
            fig.update_xaxes(title_text=plot_spec.axes_labels[0], row=terminal_row, col=1)

        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:,.2f}<br>y: %{y:,.2f}<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
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
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
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
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_powder_meas_vs_calc(plot_spec)

Render a composite powder plot with optional Bragg ticks.

The main row shows measured and calculated intensities. The Bragg row is added only when tick data is available. The residual row is added only when residual data is requested.

Source code in src/easydiffraction/display/plotters/plotly.py
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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
def plot_powder_meas_vs_calc(
    self,
    plot_spec: PowderMeasVsCalcSpec,
) -> None:
    """
    Render a composite powder plot with optional Bragg ticks.

    The main row shows measured and calculated intensities. The
    Bragg row is added only when tick data is available. The
    residual row is added only when residual data is requested.
    """
    layout = self._get_powder_composite_rows(plot_spec)
    x_min, x_max = self._composite_x_range(np.asarray(plot_spec.x))
    main_y_min, main_y_max = self._get_main_intensity_range(plot_spec)
    residual_limit = None
    hover_data = self._powder_meas_vs_calc_hover_data(plot_spec)
    hover_template = self._powder_meas_vs_calc_hover_template(plot_spec)

    fig = make_subplots(
        rows=layout.row_count,
        cols=1,
        shared_xaxes=True,
        vertical_spacing=COMPOSITE_VERTICAL_SPACING,
        row_heights=layout.row_heights,
    )

    main_traces = (
        (
            ('meas', plot_spec.y_meas),
            ('bkg', plot_spec.y_bkg),
            ('calc', plot_spec.y_calc),
        )
        if plot_spec.y_bkg is not None
        else (
            ('meas', plot_spec.y_meas),
            ('calc', plot_spec.y_calc),
        )
    )
    for label, y_values in main_traces:
        fig.add_trace(
            self._get_powder_trace(
                plot_spec.x,
                y_values,
                label,
                customdata=hover_data,
                hovertemplate=hover_template,
            ),
            row=1,
            col=1,
        )

    if layout.bragg_row is not None:
        for idx, tick_set in enumerate(plot_spec.bragg_tick_sets):
            color = BRAGG_TICK_COLORS[idx % len(BRAGG_TICK_COLORS)]
            fig.add_trace(
                self._get_bragg_tick_trace(
                    tick_set=tick_set,
                    row_y=float(idx + 1),
                    color=color,
                ),
                row=layout.bragg_row,
                col=1,
            )

    if layout.residual_row is not None and plot_spec.y_resid is not None:
        residual_limit = self._get_residual_limit(plot_spec)
        fig.add_trace(
            self._get_powder_trace(
                plot_spec.x,
                plot_spec.y_resid,
                'resid',
                customdata=hover_data,
                hovertemplate=hover_template,
            ),
            row=layout.residual_row,
            col=1,
        )

    fig.update_layout(
        height=self._composite_figure_height(plot_spec, layout),
        margin={
            'autoexpand': True,
            'r': COMPOSITE_MARGIN_RIGHT,
            't': COMPOSITE_MARGIN_TOP,
            'b': COMPOSITE_MARGIN_BOTTOM,
        },
        title={'text': plot_spec.title},
        legend={
            'bgcolor': self._legend_background_color(),
            'xanchor': 'right',
            'x': 1.0,
            'yanchor': 'top',
            'y': 1.0,
        },
    )

    for row_idx in range(1, layout.row_count + 1):
        x_axis_kwargs = {
            'matches': 'x',
            'showline': True,
            'mirror': True,
            'zeroline': False,
            'tickformat': ',.6~g',
            'separatethousands': True,
        }
        if x_min is not None and x_max is not None:
            x_axis_kwargs['range'] = [x_min, x_max]
        fig.update_xaxes(row=row_idx, col=1, **x_axis_kwargs)
        fig.update_yaxes(
            showline=True,
            mirror=True,
            zeroline=False,
            tickformat=',.6~g',
            separatethousands=True,
            row=row_idx,
            col=1,
        )

    fig.update_xaxes(showticklabels=(layout.row_count == 1), row=1, col=1)
    fig.update_yaxes(
        title_text=plot_spec.axes_labels[1],
        range=[main_y_min, main_y_max],
        row=1,
        col=1,
    )

    if layout.bragg_row is not None:
        fig.update_yaxes(
            # title_text='Bragg peaks',
            tickmode='array',
            tickvals=[float(idx + 1) for idx in range(len(plot_spec.bragg_tick_sets))],
            ticktext=[tick_set.phase_id for tick_set in plot_spec.bragg_tick_sets],
            range=[float(len(plot_spec.bragg_tick_sets)) + 0.5, 0.5],
            showgrid=False,
            row=layout.bragg_row,
            col=1,
        )
        fig.update_xaxes(
            showticklabels=layout.residual_row is None,
            row=layout.bragg_row,
            col=1,
        )

    if layout.residual_row is not None and plot_spec.y_resid is not None:
        residual_tick_limit = self._get_display_tick_limit(residual_limit)
        fig.update_yaxes(
            # title_text='Residual',
            range=[-residual_limit, residual_limit],
            tickmode='array',
            tickvals=[-residual_tick_limit, 0.0, residual_tick_limit],
            scaleanchor='y',
            scaleratio=1,
            zeroline=False,
            row=layout.residual_row,
            col=1,
        )
        fig.update_xaxes(title_text=plot_spec.axes_labels[0], row=layout.residual_row, col=1)
    else:
        terminal_row = layout.bragg_row if layout.bragg_row is not None else 1
        fig.update_xaxes(title_text=plot_spec.axes_labels[0], row=terminal_row, col=1)

    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
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
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:,.2f}<br>y: %{y:,.2f}<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
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
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)

PowderCompositeRows dataclass

Resolved row layout for the composite powder figure.

Source code in src/easydiffraction/display/plotters/plotly.py
70
71
72
73
74
75
76
77
@dataclass(frozen=True)
class PowderCompositeRows:
    """Resolved row layout for the composite powder figure."""

    row_count: int
    row_heights: list[float]
    bragg_row: int | None
    residual_row: int | None

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
  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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
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
        self._height_is_explicit = False
        # 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

        lower_bound = min(x_min, x_max)
        upper_bound = max(x_min, x_max)
        mask = (x_array >= lower_bound) & (x_array <= upper_bound)
        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)
        resolved_x_min = self.x_min if x_min is None else float(x_min)
        resolved_x_max = self.x_max if x_max is None else float(x_max)
        if x_filtered.size > 0:
            if x_min is None:
                resolved_x_min = float(np.min(x_filtered))
            if x_max is None:
                resolved_x_max = float(np.max(x_filtered))

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

        return {
            'x_filtered': x_filtered,
            'x_array': x_array,
            'x_min': resolved_x_min,
            'x_max': resolved_x_max,
            'x_axis': x_axis,
            '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
            self._height_is_explicit = True
        else:
            self._height = DEFAULT_HEIGHT
            self._height_is_explicit = False

    def _composite_plot_height(self) -> int | None:
        """Return explicit composite height or backend default."""
        if self._height_is_explicit:
            return self._height
        return None

    # ------------------------------------------------------------------
    #  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(
            intensity_category_for(experiment),
            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(
            intensity_category_for(experiment),
            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 | None = None,
        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 | None, default=None
            When ``None``, powder Bragg plots include the residual by
            default while other measured-vs-calculated plots keep the
            historical no-residual default.
        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]
        plot_options = _MeasVsCalcPlotOptions(
            x_min=x_min,
            x_max=x_max,
            show_residual=show_residual,
            x=x,
        )
        self._plot_meas_vs_calc_data(
            experiment=experiment,
            expt_name=expt_name,
            plot_options=plot_options,
        )

    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,
        plot_options: _MeasVsCalcPlotOptions,
    ) -> 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 an intensity category and
            ``.type``.
        expt_name : str
            Experiment name for the title.
        plot_options : _MeasVsCalcPlotOptions
            X-range, residual, and x-axis selection options.
        """
        pattern = intensity_category_for(experiment)
        expt_type = experiment.type

        x_axis, _, sample_form, scattering_type, _ = self._resolve_x_axis(
            expt_type,
            plot_options.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'}:
            self._plot_single_crystal_meas_vs_calc(
                pattern=pattern,
                expt_name=expt_name,
                sample_form=sample_form,
                scattering_type=scattering_type,
                x_axis=x_axis,
                title=title,
            )
            return

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

        y_meas = self._filtered_y_array(
            pattern.intensity_meas, ctx['x_array'], ctx['x_min'], ctx['x_max']
        )
        y_calc = self._filtered_y_array(
            pattern.intensity_calc, ctx['x_array'], ctx['x_min'], ctx['x_max']
        )
        y_bkg_raw = getattr(pattern, 'intensity_bkg', None)
        y_bkg = (
            self._filtered_y_array(y_bkg_raw, ctx['x_array'], ctx['x_min'], ctx['x_max'])
            if y_bkg_raw is not None
            else None
        )

        powder_series = _PowderMeasVsCalcSeries(
            y_meas=y_meas,
            y_calc=y_calc,
            y_bkg=y_bkg,
        )

        if sample_form == SampleFormEnum.POWDER and scattering_type == ScatteringTypeEnum.BRAGG:
            self._plot_powder_bragg_meas_vs_calc(
                experiment=experiment,
                expt_name=expt_name,
                ctx=ctx,
                series=powder_series,
                plot_options=plot_options,
                title=title,
            )
            return

        self._plot_line_meas_vs_calc(
            ctx=ctx,
            y_meas=y_meas,
            y_calc=y_calc,
            show_residual=False
            if plot_options.show_residual is None
            else plot_options.show_residual,
            title=title,
        )

    def _plot_single_crystal_meas_vs_calc(
        self,
        pattern: object,
        expt_name: str,
        sample_form: SampleFormEnum,
        scattering_type: ScatteringTypeEnum,
        x_axis: XAxisType | str,
        title: str,
    ) -> None:
        """
        Render the single-crystal measured-vs-calculated scatter plot.
        """
        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=title,
            height=self.height,
        )

    def _plot_powder_bragg_meas_vs_calc(
        self,
        experiment: object,
        expt_name: str,
        ctx: dict[str, object],
        series: _PowderMeasVsCalcSeries,
        plot_options: _MeasVsCalcPlotOptions,
        title: str,
    ) -> None:
        """
        Render the composite powder Bragg measured-vs-calculated plot.
        """
        show_residual = True if plot_options.show_residual is None else plot_options.show_residual
        y_resid = series.y_meas - series.y_calc if show_residual else None
        if np.asarray(ctx['x_filtered']).size == 0:
            bragg_tick_sets = ()
        else:
            bragg_tick_sets = self._extract_bragg_tick_sets(
                experiment=experiment,
                expt_name=expt_name,
                x_axis=ctx['x_axis'],
                x_min=ctx['x_min'],
                x_max=ctx['x_max'],
            )
        plot_spec = PowderMeasVsCalcSpec(
            x=ctx['x_filtered'],
            y_meas=series.y_meas,
            y_calc=series.y_calc,
            y_resid=y_resid,
            bragg_tick_sets=bragg_tick_sets,
            axes_labels=ctx['axes_labels'],
            title=title,
            residual_height_fraction=DEFAULT_RESID_HEIGHT,
            bragg_peaks_height_fraction=DEFAULT_BRAGG_ROW,
            height=self._composite_plot_height(),
            y_bkg=series.y_bkg,
        )
        self._backend.plot_powder_meas_vs_calc(plot_spec=plot_spec)

    def _plot_line_meas_vs_calc(
        self,
        ctx: dict[str, object],
        y_meas: np.ndarray,
        y_calc: np.ndarray,
        *,
        show_residual: bool,
        title: str,
    ) -> None:
        """
        Render the non-composite line version of measured-vs-calculated.
        """
        y_series = [y_meas, y_calc]
        y_labels = ['meas', '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,
        )

    @staticmethod
    def _extract_bragg_tick_sets(
        experiment: object,
        expt_name: str,
        x_axis: object,
        x_min: float | None,
        x_max: float | None,
    ) -> tuple[BraggTickSet, ...]:
        """
        Convert experiment reflection data into Bragg tick display rows.
        """
        refln = getattr(experiment, 'refln', None)
        if refln is None:
            return ()

        x_values = Plotter._bragg_tick_x_values(
            refln=refln,
            experiment=experiment,
            expt_name=expt_name,
            x_axis=x_axis,
        )
        arrays = Plotter._bragg_tick_arrays(refln=refln, expt_name=expt_name)
        if x_values is None or arrays is None:
            return ()

        arrays['x'] = np.asarray(x_values)
        if arrays['x'].size == 0:
            return ()

        mask = Plotter._bragg_tick_mask(arrays['x'], x_min=x_min, x_max=x_max)
        if not np.any(mask):
            return ()

        return Plotter._group_bragg_tick_sets(arrays=arrays, mask=mask)

    @staticmethod
    def _bragg_tick_x_values(
        *,
        refln: object,
        experiment: object,
        expt_name: str,
        x_axis: object,
    ) -> object | None:
        x_name = getattr(x_axis, 'value', x_axis)
        if x_name == XAxisType.D_SPACING:
            return Plotter._bragg_tick_d_spacing(refln=refln, experiment=experiment)
        if x_name == XAxisType.TWO_THETA:
            return Plotter._bragg_tick_attr(refln, x_name, expt_name)
        if x_name == XAxisType.TIME_OF_FLIGHT:
            return Plotter._bragg_tick_attr(refln, x_name, expt_name)

        log.warning(
            f"Unsupported Bragg tick x axis '{x_name}' for experiment '{expt_name}'. "
            'Skipping the Bragg subplot.',
        )
        return None

    @staticmethod
    def _bragg_tick_attr(
        refln: object,
        name: str,
        expt_name: str,
    ) -> object | None:
        value = getattr(refln, name, None)
        if value is not None:
            return value

        log.warning(
            f"Experiment '{expt_name}' reflection data does not expose '{name}'. "
            'Skipping the Bragg subplot.',
        )
        return None

    @staticmethod
    def _bragg_tick_arrays(
        *,
        refln: object,
        expt_name: str,
    ) -> dict[str, np.ndarray] | None:
        arrays: dict[str, np.ndarray] = {}
        for name in (
            'phase_id',
            'index_h',
            'index_k',
            'index_l',
            'f_squared_calc',
            'f_calc',
        ):
            value = getattr(refln, name, None)
            if value is None:
                log.warning(
                    f"Experiment '{expt_name}' reflection data is missing '{name}'. "
                    'Skipping the Bragg subplot.',
                )
                return None
            arrays[name] = np.asarray(value)
        return arrays

    @staticmethod
    def _bragg_tick_mask(
        x_values: np.ndarray,
        *,
        x_min: float | None,
        x_max: float | None,
    ) -> np.ndarray:
        lower_bound = DEFAULT_MIN if x_min is None else min(x_min, x_max)
        upper_bound = DEFAULT_MAX if x_max is None else max(x_min, x_max)
        return (x_values >= lower_bound) & (x_values <= upper_bound)

    @staticmethod
    def _group_bragg_tick_sets(
        *,
        arrays: dict[str, np.ndarray],
        mask: np.ndarray,
    ) -> tuple[BraggTickSet, ...]:
        phase_ids = arrays['phase_id'][mask]
        unique_phase_ids = []
        for raw_phase_id in phase_ids:
            if not any(
                np.array_equal(raw_phase_id, existing_phase_id)
                for existing_phase_id in unique_phase_ids
            ):
                unique_phase_ids.append(raw_phase_id)

        tick_sets = []
        for raw_phase_id in unique_phase_ids:
            phase_mask = mask & (arrays['phase_id'] == raw_phase_id)
            tick_sets.append(
                BraggTickSet(
                    phase_id=str(raw_phase_id),
                    x=arrays['x'][phase_mask],
                    h=arrays['index_h'][phase_mask],
                    k=arrays['index_k'][phase_mask],
                    ell=arrays['index_l'][phase_mask],
                    f_squared_calc=arrays['f_squared_calc'][phase_mask],
                    f_calc=arrays['f_calc'][phase_mask],
                )
            )

        return tuple(tick_sets)

    @staticmethod
    def _bragg_tick_d_spacing(
        *,
        refln: object,
        experiment: object,
    ) -> object:
        """
        Resolve Bragg tick d-spacing in the plotted coordinate system.
        """
        if hasattr(refln, 'two_theta'):
            return twotheta_to_d(
                refln.two_theta,
                experiment.instrument.setup_wavelength.value,
            )
        if hasattr(refln, 'time_of_flight'):
            return tof_to_d(
                refln.time_of_flight,
                experiment.instrument.calib_d_to_tof_offset.value,
                experiment.instrument.calib_d_to_tof_linear.value,
                experiment.instrument.calib_d_to_tof_quad.value,
            )
        return refln.d_spacing

    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
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
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(
        intensity_category_for(experiment),
        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
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
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(
        intensity_category_for(experiment),
        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=None, 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 | None

When None, powder Bragg plots include the residual by default while other measured-vs-calculated plots keep the historical no-residual default.

None
x object | None

Optional explicit x-axis data to override stored values.

None
Source code in src/easydiffraction/display/plotting.py
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
def plot_meas_vs_calc(
    self,
    expt_name: str,
    x_min: float | None = None,
    x_max: float | None = None,
    *,
    show_residual: bool | None = None,
    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 | None, default=None
        When ``None``, powder Bragg plots include the residual by
        default while other measured-vs-calculated plots keep the
        historical no-residual default.
    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]
    plot_options = _MeasVsCalcPlotOptions(
        x_min=x_min,
        x_max=x_max,
        show_residual=show_residual,
        x=x,
    )
    self._plot_meas_vs_calc_data(
        experiment=experiment,
        expt_name=expt_name,
        plot_options=plot_options,
    )

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
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
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
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
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
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
48
49
50
51
52
53
54
55
@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
57
58
59
60
61
62
63
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
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
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.')