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
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
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  # local import to avoid cycles

        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
81
82
83
84
@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
100
101
102
103
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
86
87
88
89
90
91
92
93
94
95
96
97
98
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  # local import to avoid cycles

    TableRenderer.get().render(df)

RendererFactoryBase

Bases: ABC

Base factory that manages discovery and creation of backends.

Source code in src/easydiffraction/display/base.py
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
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())
            raise ValueError(f"Unsupported engine '{engine_name}'. Supported engines: {supported}")
        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
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
@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())
        raise ValueError(f"Unsupported engine '{engine_name}'. Supported engines: {supported}")
    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
142
143
144
145
146
@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
137
138
139
140
@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
 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
class AsciiPlotter(PlotterBase):
    """Terminal-based plotter using ASCII art."""

    def _get_legend_item(self, 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']
        item = f'{color_start}{line}{color_end} {name}'
        return item

    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_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.

        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]}')

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

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

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

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

    chart = asciichartpy.plot(y_series, config)

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

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

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

Render a scatter plot with error bars in ASCII.

Source code in src/easydiffraction/display/plotters/ascii.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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 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)

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

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

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

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

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

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

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

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

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

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

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

base

Abstract base and shared constants for plotting backends.

PlotterBase

Bases: ABC

Abstract base for plotting backends.

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

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

Source code in src/easydiffraction/display/plotters/base.py
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
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).
    """

    @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).
        """
        pass

    @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).
        """
        pass

    @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).
        """
        pass
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
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
@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).
    """
    pass
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
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
@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).
    """
    pass
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
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
@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).
    """
    pass

XAxisType

Bases: str, Enum

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
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class XAxisType(str, Enum):
    """
    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
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
class PlotlyPlotter(PlotterBase):
    """Interactive plotter using Plotly for notebooks and browsers."""

    pio.templates.default = 'plotly_dark' if darkdetect.isDark() else 'plotly_white'
    if in_pycharm():
        pio.renderers.default = 'browser'

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

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

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

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

        return trace

    def _get_single_crystal_trace(
        self,
        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.
        """
        trace = go.Scatter(
            x=x_calc,
            y=y_meas,
            mode='markers',
            marker=dict(
                symbol='circle',
                size=10,
                line=dict(width=0.5),
                color=DEFAULT_COLORS['meas'],
            ),
            error_y=dict(
                type='data',
                array=y_meas_su,
                visible=True,
            ),
            hovertemplate='calc: %{x}<br>meas: %{y}<br><extra></extra>',
        )

        return trace

    def _get_diagonal_shape(self) -> 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 dict(
            type='line',
            x0=0,
            y0=0,
            x1=1,
            y1=1,
            xref='paper',
            yref='paper',
            layer='below',
            line=dict(width=0.5),
        )

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

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

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

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

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

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

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

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

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

    def _get_layout(
        self,
        title: str,
        axes_labels: object,
        **kwargs: object,
    ) -> object:
        """
        Create a Plotly layout configuration.

        Parameters
        ----------
        title : str
            Figure title.
        axes_labels : object
            Pair of strings for the x and y titles.
        **kwargs : object
            Additional layout parameters (e.g., shapes).

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

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

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

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

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

        layout = self._get_layout(
            title,
            axes_labels,
        )

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

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

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

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

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

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

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

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

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

        layout = self._get_layout(
            title,
            axes_labels,
        )

        fig = self._get_figure(trace, layout)
        self._show_figure(fig)
plot_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
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
def plot_powder(
    self,
    x: object,
    y_series: object,
    labels: object,
    axes_labels: object,
    title: str,
    height: int | None = None,
) -> None:
    """
    Render a line plot for powder diffraction data.

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

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

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

    layout = self._get_layout(
        title,
        axes_labels,
    )

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

Render a scatter plot with error bars via Plotly.

Source code in src/easydiffraction/display/plotters/plotly.py
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
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=dict(
            symbol='circle',
            size=10,
            line=dict(width=0.5),
            color=DEFAULT_COLORS['meas'],
        ),
        line=dict(
            width=1,
            color=DEFAULT_COLORS['meas'],
        ),
        error_y=dict(
            type='data',
            array=sy,
            visible=True,
        ),
        hovertemplate='x: %{x}<br>y: %{y}<br><extra></extra>',
    )

    layout = self._get_layout(
        title,
        axes_labels,
    )

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

Render a scatter plot for single crystal diffraction data.

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

Parameters:

Name Type Description Default
x_calc object

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

required
y_meas object

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

required
y_meas_su object

1D array-like of measurement uncertainties.

required
axes_labels object

Pair of strings for the x and y titles.

required
title str

Figure title.

required
height int | None

Ignored; Plotly auto-sizes based on renderer.

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

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

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

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

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

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

plotting

Plotting facade for measured and calculated patterns.

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

Plotter

Bases: RendererBase

User-facing plotting facade backed by concrete plotters.

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

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

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

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

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

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

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

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

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

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

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

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

        return filtered_y_array

    def _get_axes_labels(
        self,
        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_data(
        self,
        pattern: object,
        expt_name: str,
        expt_type: object,
        x_min: object,
        x_max: object,
        x: object,
        need_meas: bool = False,
        need_calc: bool = False,
        show_residual: bool = False,
    ) -> dict | None:
        """
        Validate, resolve axes, auto-range, and filter arrays.

        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``.
        need_meas : bool, default=False
            Whether ``intensity_meas`` is required.
        need_calc : bool, default=False
            Whether ``intensity_calc`` is required.
        show_residual : bool, default=False
            If ``True``, compute meas − calc residual.

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

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

        # Validate required intensities
        if need_meas and pattern.intensity_meas is None:
            log.error(f'No measured data available for experiment {expt_name}')
            return None
        if need_calc and pattern.intensity_calc is None:
            log.error(f'No calculated data available for experiment {expt_name}')
            return None

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

        # Filter y arrays and build series / labels
        y_series = []
        y_labels = []

        y_meas = None
        if need_meas:
            y_meas = self._filtered_y_array(pattern.intensity_meas, x_array, x_min, x_max)
            y_series.append(y_meas)
            y_labels.append('meas')

        y_calc = None
        if need_calc:
            y_calc = self._filtered_y_array(pattern.intensity_calc, x_array, x_min, x_max)
            y_series.append(y_calc)
            y_labels.append('calc')

        if show_residual and y_meas is not None and y_calc is not None:
            y_resid = y_meas - y_calc
            y_series.append(y_resid)
            y_labels.append('resid')

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

        return {
            'x_filtered': x_filtered,
            'y_series': y_series,
            'y_labels': y_labels,
            'axes_labels': axes_labels,
            'x_axis': x_axis,
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def plot_meas(
        self,
        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 (``'two_theta'``, ``'time_of_flight'``, or
            ``'d_spacing'``). If ``None``, auto-detected from beam mode.
        """
        ctx = self._prepare_powder_data(
            pattern,
            expt_name,
            expt_type,
            x_min,
            x_max,
            x,
            need_meas=True,
        )
        if ctx is None:
            return

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

    def plot_calc(
        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 (``'two_theta'``, ``'time_of_flight'``, or
            ``'d_spacing'``). If ``None``, auto-detected from beam mode.
        """
        ctx = self._prepare_powder_data(
            pattern,
            expt_name,
            expt_type,
            x_min,
            x_max,
            x,
            need_calc=True,
        )
        if ctx is None:
            return

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

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

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

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

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

        Parameters
        ----------
        pattern : object
            Data pattern object with meas/calc arrays.
        expt_name : str
            Experiment name for the title.
        expt_type : object
            Experiment type with sample_form, scattering, and beam
            enums.
        x_min : object, default=None
            Optional minimum x-axis limit.
        x_max : object, default=None
            Optional maximum x-axis limit.
        show_residual : bool, default=False
            If ``True``, add residual series (powder only).
        x : object, default=None
            X-axis type. If ``None``, auto-detected from sample form and
            beam mode.
        """
        x_axis, _, sample_form, scattering_type, _ = self._resolve_x_axis(expt_type, x)

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

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

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

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

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

        # Line plot (PD or SC with d_spacing/sin_theta_over_lambda)
        # TODO: Rename from _prepare_powder_data as it also supports
        #  single crystal line plots
        ctx = self._prepare_powder_data(
            pattern,
            expt_name,
            expt_type,
            x_min,
            x_max,
            x,
            need_meas=True,
            need_calc=True,
            show_residual=show_residual,
        )
        if ctx is None:
            return

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

    def plot_param_series(
        self,
        unique_name: str,
        versus_name: str | None,
        experiments: object,
        parameter_snapshots: dict[str, dict[str, dict]],
    ) -> None:
        """
        Plot a parameter's value across sequential fit results.

        Parameters
        ----------
        unique_name : str
            Unique name of the parameter to plot.
        versus_name : str | None
            Name of the diffrn descriptor to use as the x-axis (e.g.
            ``'ambient_temperature'``).  When ``None``, the experiment
            sequence index is used instead.
        experiments : object
            Experiments collection for accessing diffrn conditions.
        parameter_snapshots : dict[str, dict[str, dict]]
            Per-experiment parameter value snapshots keyed by experiment
            name, then by parameter unique name.
        """
        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(pattern, expt_name, expt_type, x_min=None, x_max=None, x=None)

Plot calculated pattern using the current engine.

Parameters:

Name Type Description Default
pattern object

Object with x-axis arrays (two_theta, time_of_flight, d_spacing) and calc array.

required
expt_name str

Experiment name for the title.

required
expt_type object

Experiment type with scattering/beam enums.

required
x_min object

Optional minimum x-axis limit.

None
x_max object

Optional maximum x-axis limit.

None
x object

X-axis type ('two_theta', 'time_of_flight', or 'd_spacing'). If None, auto-detected from beam mode.

None
Source code in src/easydiffraction/display/plotting.py
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
def plot_calc(
    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 (``'two_theta'``, ``'time_of_flight'``, or
        ``'d_spacing'``). If ``None``, auto-detected from beam mode.
    """
    ctx = self._prepare_powder_data(
        pattern,
        expt_name,
        expt_type,
        x_min,
        x_max,
        x,
        need_calc=True,
    )
    if ctx is None:
        return

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

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

Plot measured pattern using the current engine.

Parameters:

Name Type Description Default
pattern object

Object with x-axis arrays (two_theta, time_of_flight, d_spacing) and meas array.

required
expt_name str

Experiment name for the title.

required
expt_type object

Experiment type with scattering/beam enums.

required
x_min object

Optional minimum x-axis limit.

None
x_max object

Optional maximum x-axis limit.

None
x object

X-axis type ('two_theta', 'time_of_flight', or 'd_spacing'). If None, auto-detected from beam mode.

None
Source code in src/easydiffraction/display/plotting.py
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
def plot_meas(
    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 (``'two_theta'``, ``'time_of_flight'``, or
        ``'d_spacing'``). If ``None``, auto-detected from beam mode.
    """
    ctx = self._prepare_powder_data(
        pattern,
        expt_name,
        expt_type,
        x_min,
        x_max,
        x,
        need_meas=True,
    )
    if ctx is None:
        return

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

plot_meas_vs_calc(pattern, expt_name, expt_type, x_min=None, x_max=None, show_residual=False, x=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:

Name Type Description Default
pattern object

Data pattern object with meas/calc arrays.

required
expt_name str

Experiment name for the title.

required
expt_type object

Experiment type with sample_form, scattering, and beam enums.

required
x_min object

Optional minimum x-axis limit.

None
x_max object

Optional maximum x-axis limit.

None
show_residual bool

If True, add residual series (powder only).

False
x object

X-axis type. If None, auto-detected from sample form and beam mode.

None
Source code in src/easydiffraction/display/plotting.py
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
def plot_meas_vs_calc(
    self,
    pattern: object,
    expt_name: str,
    expt_type: object,
    x_min: object = None,
    x_max: object = None,
    show_residual: bool = False,
    x: object = None,
) -> None:
    """
    Plot measured and calculated series and optional residual.

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

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

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

    Parameters
    ----------
    pattern : object
        Data pattern object with meas/calc arrays.
    expt_name : str
        Experiment name for the title.
    expt_type : object
        Experiment type with sample_form, scattering, and beam
        enums.
    x_min : object, default=None
        Optional minimum x-axis limit.
    x_max : object, default=None
        Optional maximum x-axis limit.
    show_residual : bool, default=False
        If ``True``, add residual series (powder only).
    x : object, default=None
        X-axis type. If ``None``, auto-detected from sample form and
        beam mode.
    """
    x_axis, _, sample_form, scattering_type, _ = self._resolve_x_axis(expt_type, x)

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

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

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

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

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

    # Line plot (PD or SC with d_spacing/sin_theta_over_lambda)
    # TODO: Rename from _prepare_powder_data as it also supports
    #  single crystal line plots
    ctx = self._prepare_powder_data(
        pattern,
        expt_name,
        expt_type,
        x_min,
        x_max,
        x,
        need_meas=True,
        need_calc=True,
        show_residual=show_residual,
    )
    if ctx is None:
        return

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

plot_param_series(unique_name, versus_name, experiments, parameter_snapshots)

Plot a parameter's value across sequential fit results.

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 to use as the x-axis (e.g. 'ambient_temperature'). When None, the experiment sequence index is used instead.

required
experiments object

Experiments collection for accessing diffrn conditions.

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

Per-experiment parameter value snapshots keyed by experiment name, then by parameter unique name.

required
Source code in src/easydiffraction/display/plotting.py
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
def plot_param_series(
    self,
    unique_name: str,
    versus_name: str | None,
    experiments: object,
    parameter_snapshots: dict[str, dict[str, dict]],
) -> None:
    """
    Plot a parameter's value across sequential fit results.

    Parameters
    ----------
    unique_name : str
        Unique name of the parameter to plot.
    versus_name : str | None
        Name of the diffrn descriptor to use as the x-axis (e.g.
        ``'ambient_temperature'``).  When ``None``, the experiment
        sequence index is used instead.
    experiments : object
        Experiments collection for accessing diffrn conditions.
    parameter_snapshots : dict[str, dict[str, dict]]
        Per-experiment parameter value snapshots keyed by experiment
        name, then by parameter unique name.
    """
    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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
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: str, Enum

Available plotting engine backends.

Source code in src/easydiffraction/display/plotting.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class PlotterEngineEnum(str, Enum):
    """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'
        elif 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
37
38
39
40
41
42
43
44
@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
46
47
48
49
50
51
52
def description(self) -> str:
    """Human-readable description for UI listings."""
    if self is PlotterEngineEnum.ASCII:
        return 'Console ASCII line charts'
    elif 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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
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)

    def _is_dark_theme(self) -> 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()

    def _rich_to_hex(self, 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()
        hex_value = '#{:02x}{:02x}{:02x}'.format(*rgb)
        return hex_value

    @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``).
        """
        pass
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
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
@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``).
    """
    pass

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
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
class PandasTableBackend(TableBackendBase):
    """Render tables using the pandas Styler in Jupyter environments."""

    def _build_base_styles(self, 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'),
                ],
            },
        ]

    def _build_header_alignment_styles(self, 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)
        ]

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

    def _update_display(self, 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))
                    return
                except Exception as err:
                    log.debug(f'Pandas DisplayHandle update failed: {err!r}')

            # 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
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
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
class RichTableBackend(TableBackendBase):
    """Render tables to terminal or Jupyter using the Rich library."""

    def _to_html(self, 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
        html = html.replace(
            '<pre ',
            "<pre style='margin:0; font-size: 0.9em !important; ' ",
        )
        return html

    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))
                    return
                except Exception as err:
                    log.debug(f'Rich to HTML DisplayHandle update failed: {err!r}')

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

        # 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
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
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: str, Enum

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(str, Enum):
    """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'
        elif 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'
    elif 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 Exception:
            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 Exception:
        log.debug('Failed to inject Jupyter CSS to disable scrolling.')