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
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
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):
        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 self._engine

    @engine.setter
    def engine(self, new_engine: str) -> None:
        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}'")

show_config() abstractmethod

Display the current renderer configuration.

Source code in src/easydiffraction/display/base.py
64
65
66
67
@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
83
84
85
86
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
69
70
71
72
73
74
75
76
77
78
79
80
81
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
 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
class RendererFactoryBase(ABC):
    """Base factory that manages discovery and creation of backends."""

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

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

        Returns:
            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 pairs of engine name and human-friendly
        description.
        """
        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
Any

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
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
@classmethod
def create(cls, engine_name: str) -> Any:
    """Create a backend instance for the given engine.

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

    Returns:
        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 pairs of engine name and human-friendly description.

Source code in src/easydiffraction/display/base.py
118
119
120
121
122
123
124
@classmethod
def descriptions(cls) -> List[Tuple[str, str]]:
    """Return pairs of engine name and human-friendly
    description.
    """
    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
113
114
115
116
@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
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
class AsciiPlotter(PlotterBase):
    """Terminal-based plotter using ASCII art."""

    def _get_legend_item(self, label):
        """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`.

        Args:
            label: Series identifier (e.g., ``'meas'``).

        Returns:
            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(
        self,
        x,
        y_series,
        labels,
        axes_labels,
        title,
        height=None,
    ):
        """Render a compact ASCII chart in the terminal.

        Args:
            x: 1D array-like of x values (only used for range
                display).
            y_series: Sequence of y arrays to plot.
            labels: Series identifiers corresponding to y_series.
            axes_labels: Ignored; kept for API compatibility.
            title: Figure title printed above the chart.
            height: 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(x, y_series, labels, axes_labels, title, height=None)

Render a compact ASCII chart in the terminal.

Parameters:

Name Type Description Default
x

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

required
y_series

Sequence of y arrays to plot.

required
labels

Series identifiers corresponding to y_series.

required
axes_labels

Ignored; kept for API compatibility.

required
title

Figure title printed above the chart.

required
height

Number of text rows to allocate for the chart.

None
Source code in src/easydiffraction/display/plotters/ascii.py
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
def plot(
    self,
    x,
    y_series,
    labels,
    axes_labels,
    title,
    height=None,
):
    """Render a compact ASCII chart in the terminal.

    Args:
        x: 1D array-like of x values (only used for range
            display).
        y_series: Sequence of y arrays to plot.
        labels: Series identifiers corresponding to y_series.
        axes_labels: Ignored; kept for API compatibility.
        title: Figure title printed above the chart.
        height: 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)

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.

Source code in src/easydiffraction/display/plotters/base.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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.
    """

    @abstractmethod
    def plot(
        self,
        x,
        y_series,
        labels,
        axes_labels,
        title,
        height,
    ):
        """Render a plot.

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

Render a plot.

Parameters:

Name Type Description Default
x

1D array of x-axis values.

required
y_series

Sequence of y arrays to plot.

required
labels

Identifiers corresponding to y_series.

required
axes_labels

Pair of strings for the x and y titles.

required
title

Figure title.

required
height

Backend-specific height (text rows or pixels).

required
Source code in src/easydiffraction/display/plotters/base.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@abstractmethod
def plot(
    self,
    x,
    y_series,
    labels,
    axes_labels,
    title,
    height,
):
    """Render a plot.

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

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
 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
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_trace(self, x, y, label):
        """Create a Plotly trace for a single data series.

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

        Returns:
            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 plot(
        self,
        x,
        y_series,
        labels,
        axes_labels,
        title,
        height=None,
    ):
        """Render an interactive Plotly figure.

        Args:
            x: 1D array-like of x-axis values.
            y_series: Sequence of y arrays to plot.
            labels: Series identifiers corresponding to y_series.
            axes_labels: Pair of strings for the x and y titles.
            title: Figure title.
            height: 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_trace(x, y, label)
            data.append(trace)

        layout = 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,
            ),
        )

        config = dict(
            displaylogo=False,
            modeBarButtonsToRemove=[
                'select2d',
                'lasso2d',
                'zoomIn2d',
                'zoomOut2d',
                'autoScale2d',
            ],
        )

        fig = go.Figure(
            data=data,
            layout=layout,
        )

        # Format the axes ticks.
        # Keeps decimals for small numbers; groups thousands for large
        # ones
        fig.update_xaxes(tickformat=',.6~g', separatethousands=True)
        fig.update_yaxes(tickformat=',.6~g', separatethousands=True)

        # Show the figure
        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))
plot(x, y_series, labels, axes_labels, title, height=None)

Render an interactive Plotly figure.

Parameters:

Name Type Description Default
x

1D array-like of x-axis values.

required
y_series

Sequence of y arrays to plot.

required
labels

Series identifiers corresponding to y_series.

required
axes_labels

Pair of strings for the x and y titles.

required
title

Figure title.

required
height

Ignored; Plotly auto-sizes based on renderer.

None
Source code in src/easydiffraction/display/plotters/plotly.py
 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
def plot(
    self,
    x,
    y_series,
    labels,
    axes_labels,
    title,
    height=None,
):
    """Render an interactive Plotly figure.

    Args:
        x: 1D array-like of x-axis values.
        y_series: Sequence of y arrays to plot.
        labels: Series identifiers corresponding to y_series.
        axes_labels: Pair of strings for the x and y titles.
        title: Figure title.
        height: 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_trace(x, y, label)
        data.append(trace)

    layout = 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,
        ),
    )

    config = dict(
        displaylogo=False,
        modeBarButtonsToRemove=[
            'select2d',
            'lasso2d',
            'zoomIn2d',
            'zoomOut2d',
            'autoScale2d',
        ],
    )

    fig = go.Figure(
        data=data,
        layout=layout,
    )

    # Format the axes ticks.
    # Keeps decimals for small numbers; groups thousands for large
    # ones
    fig.update_xaxes(tickformat=',.6~g', separatethousands=True)
    fig.update_yaxes(tickformat=',.6~g', separatethousands=True)

    # Show the figure
    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))

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

    def __init__(self):
        super().__init__()
        # X-axis limits
        self._x_min = DEFAULT_MIN
        self._x_max = DEFAULT_MAX
        # Chart height
        self.height = DEFAULT_HEIGHT

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

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

    def show_config(self):
        """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)

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

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

        Args:
            value: 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):
        """Maximum x-axis limit."""
        return self._x_max

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

        Args:
            value: 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):
        """Plot height (rows for ASCII, pixels for Plotly)."""
        return self._height

    @height.setter
    def height(self, value):
        """Set plot height.

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

    def plot_meas(
        self,
        pattern,
        expt_name,
        expt_type,
        x_min=None,
        x_max=None,
        d_spacing=False,
    ):
        """Plot measured pattern using the current engine.

        Args:
            pattern: Object with ``x`` and ``meas`` arrays (and
                ``d`` when ``d_spacing`` is true).
            expt_name: Experiment name for the title.
            expt_type: Experiment type with scattering/beam enums.
            x_min: Optional minimum x-axis limit.
            x_max: Optional maximum x-axis limit.
            d_spacing: If ``True``, plot against d-spacing values.
        """
        if pattern.x is None:
            log.error(f'No data available for experiment {expt_name}')
            return
        if pattern.meas is None:
            log.error(f'No measured data available for experiment {expt_name}')
            return

        # Select x-axis data based on d-spacing or original x values
        x_array = pattern.d if d_spacing else pattern.x

        # For asciichartpy, if x_min or x_max is not provided, center
        # around the maximum intensity peak
        if self._engine == 'asciichartpy' and (x_min is None or x_max is None):
            max_intensity_pos = np.argmax(pattern.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]

        # Filter x, y_meas, and y_calc based on x_min and x_max
        x = self._filtered_y_array(
            y_array=x_array,
            x_array=x_array,
            x_min=x_min,
            x_max=x_max,
        )
        y_meas = self._filtered_y_array(
            y_array=pattern.meas,
            x_array=x_array,
            x_min=x_min,
            x_max=x_max,
        )

        y_series = [y_meas]
        y_labels = ['meas']

        if d_spacing:
            axes_labels = DEFAULT_AXES_LABELS[
                (
                    expt_type.scattering_type.value,
                    'd-spacing',
                )
            ]
        else:
            axes_labels = DEFAULT_AXES_LABELS[
                (
                    expt_type.scattering_type.value,
                    expt_type.beam_mode.value,
                )
            ]

        # TODO: Before, it was self._plotter.plot. Check what is better.
        self._backend.plot(
            x=x,
            y_series=y_series,
            labels=y_labels,
            axes_labels=axes_labels,
            title=f"Measured data for experiment 🔬 '{expt_name}'",
            height=self.height,
        )

    def plot_calc(
        self,
        pattern,
        expt_name,
        expt_type,
        x_min=None,
        x_max=None,
        d_spacing=False,
    ):
        """Plot calculated pattern using the current engine.

        Args:
            pattern: Object with ``x`` and ``calc`` arrays (and
                ``d`` when ``d_spacing`` is true).
            expt_name: Experiment name for the title.
            expt_type: Experiment type with scattering/beam enums.
            x_min: Optional minimum x-axis limit.
            x_max: Optional maximum x-axis limit.
            d_spacing: If ``True``, plot against d-spacing values.
        """
        if pattern.x is None:
            log.error(f'No data available for experiment {expt_name}')
            return
        if pattern.calc is None:
            log.error(f'No calculated data available for experiment {expt_name}')
            return

        # Select x-axis data based on d-spacing or original x values
        x_array = pattern.d if d_spacing else pattern.x

        # For asciichartpy, if x_min or x_max is not provided, center
        # around the maximum intensity peak
        if self._engine == 'asciichartpy' and (x_min is None or x_max is None):
            max_intensity_pos = np.argmax(pattern.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]

        # Filter x, y_meas, and y_calc based on x_min and x_max
        x = self._filtered_y_array(
            y_array=x_array,
            x_array=x_array,
            x_min=x_min,
            x_max=x_max,
        )
        y_calc = self._filtered_y_array(
            y_array=pattern.calc,
            x_array=x_array,
            x_min=x_min,
            x_max=x_max,
        )

        y_series = [y_calc]
        y_labels = ['calc']

        if d_spacing:
            axes_labels = DEFAULT_AXES_LABELS[
                (
                    expt_type.scattering_type.value,
                    'd-spacing',
                )
            ]
        else:
            axes_labels = DEFAULT_AXES_LABELS[
                (
                    expt_type.scattering_type.value,
                    expt_type.beam_mode.value,
                )
            ]

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

    def plot_meas_vs_calc(
        self,
        pattern,
        expt_name,
        expt_type,
        x_min=None,
        x_max=None,
        show_residual=False,
        d_spacing=False,
    ):
        """Plot measured and calculated series and optional residual.

        Args:
            pattern: Object with ``x``, ``meas`` and ``calc`` arrays
                (and ``d`` when ``d_spacing`` is true).
            expt_name: Experiment name for the title.
            expt_type: Experiment type with scattering/beam enums.
            x_min: Optional minimum x-axis limit.
            x_max: Optional maximum x-axis limit.
            show_residual: If ``True``, add residual series.
            d_spacing: If ``True``, plot against d-spacing values.
        """
        if pattern.x is None:
            log.error(f'No data available for experiment {expt_name}')
            return
        if pattern.meas is None:
            log.error(f'No measured data available for experiment {expt_name}')
            return
        if pattern.calc is None:
            log.error(f'No calculated data available for experiment {expt_name}')
            return

        # Select x-axis data based on d-spacing or original x values
        x_array = pattern.d if d_spacing else pattern.x

        # For asciichartpy, if x_min or x_max is not provided, center
        # around the maximum intensity peak
        if self._engine == 'asciichartpy' and (x_min is None or x_max is None):
            max_intensity_pos = np.argmax(pattern.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]

        # Filter x, y_meas, and y_calc based on x_min and x_max
        x = self._filtered_y_array(
            y_array=x_array,
            x_array=x_array,
            x_min=x_min,
            x_max=x_max,
        )
        y_meas = self._filtered_y_array(
            y_array=pattern.meas,
            x_array=x_array,
            x_min=x_min,
            x_max=x_max,
        )
        y_calc = self._filtered_y_array(
            y_array=pattern.calc,
            x_array=x_array,
            x_min=x_min,
            x_max=x_max,
        )

        y_series = [y_meas, y_calc]
        y_labels = ['meas', 'calc']

        if d_spacing:
            axes_labels = DEFAULT_AXES_LABELS[
                (
                    expt_type.scattering_type.value,
                    'd-spacing',
                )
            ]
        else:
            axes_labels = DEFAULT_AXES_LABELS[
                (
                    expt_type.scattering_type.value,
                    expt_type.beam_mode.value,
                )
            ]

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

        self._backend.plot(
            x=x,
            y_series=y_series,
            labels=y_labels,
            axes_labels=axes_labels,
            title=f"Measured vs Calculated data for experiment 🔬 '{expt_name}'",
            height=self.height,
        )

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

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

        Returns:
            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

height property writable

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

plot_calc(pattern, expt_name, expt_type, x_min=None, x_max=None, d_spacing=False)

Plot calculated pattern using the current engine.

Parameters:

Name Type Description Default
pattern

Object with x and calc arrays (and d when d_spacing is true).

required
expt_name

Experiment name for the title.

required
expt_type

Experiment type with scattering/beam enums.

required
x_min

Optional minimum x-axis limit.

None
x_max

Optional maximum x-axis limit.

None
d_spacing

If True, plot against d-spacing values.

False
Source code in src/easydiffraction/display/plotting.py
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
def plot_calc(
    self,
    pattern,
    expt_name,
    expt_type,
    x_min=None,
    x_max=None,
    d_spacing=False,
):
    """Plot calculated pattern using the current engine.

    Args:
        pattern: Object with ``x`` and ``calc`` arrays (and
            ``d`` when ``d_spacing`` is true).
        expt_name: Experiment name for the title.
        expt_type: Experiment type with scattering/beam enums.
        x_min: Optional minimum x-axis limit.
        x_max: Optional maximum x-axis limit.
        d_spacing: If ``True``, plot against d-spacing values.
    """
    if pattern.x is None:
        log.error(f'No data available for experiment {expt_name}')
        return
    if pattern.calc is None:
        log.error(f'No calculated data available for experiment {expt_name}')
        return

    # Select x-axis data based on d-spacing or original x values
    x_array = pattern.d if d_spacing else pattern.x

    # For asciichartpy, if x_min or x_max is not provided, center
    # around the maximum intensity peak
    if self._engine == 'asciichartpy' and (x_min is None or x_max is None):
        max_intensity_pos = np.argmax(pattern.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]

    # Filter x, y_meas, and y_calc based on x_min and x_max
    x = self._filtered_y_array(
        y_array=x_array,
        x_array=x_array,
        x_min=x_min,
        x_max=x_max,
    )
    y_calc = self._filtered_y_array(
        y_array=pattern.calc,
        x_array=x_array,
        x_min=x_min,
        x_max=x_max,
    )

    y_series = [y_calc]
    y_labels = ['calc']

    if d_spacing:
        axes_labels = DEFAULT_AXES_LABELS[
            (
                expt_type.scattering_type.value,
                'd-spacing',
            )
        ]
    else:
        axes_labels = DEFAULT_AXES_LABELS[
            (
                expt_type.scattering_type.value,
                expt_type.beam_mode.value,
            )
        ]

    self._backend.plot(
        x=x,
        y_series=y_series,
        labels=y_labels,
        axes_labels=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, d_spacing=False)

Plot measured pattern using the current engine.

Parameters:

Name Type Description Default
pattern

Object with x and meas arrays (and d when d_spacing is true).

required
expt_name

Experiment name for the title.

required
expt_type

Experiment type with scattering/beam enums.

required
x_min

Optional minimum x-axis limit.

None
x_max

Optional maximum x-axis limit.

None
d_spacing

If True, plot against d-spacing values.

False
Source code in src/easydiffraction/display/plotting.py
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
def plot_meas(
    self,
    pattern,
    expt_name,
    expt_type,
    x_min=None,
    x_max=None,
    d_spacing=False,
):
    """Plot measured pattern using the current engine.

    Args:
        pattern: Object with ``x`` and ``meas`` arrays (and
            ``d`` when ``d_spacing`` is true).
        expt_name: Experiment name for the title.
        expt_type: Experiment type with scattering/beam enums.
        x_min: Optional minimum x-axis limit.
        x_max: Optional maximum x-axis limit.
        d_spacing: If ``True``, plot against d-spacing values.
    """
    if pattern.x is None:
        log.error(f'No data available for experiment {expt_name}')
        return
    if pattern.meas is None:
        log.error(f'No measured data available for experiment {expt_name}')
        return

    # Select x-axis data based on d-spacing or original x values
    x_array = pattern.d if d_spacing else pattern.x

    # For asciichartpy, if x_min or x_max is not provided, center
    # around the maximum intensity peak
    if self._engine == 'asciichartpy' and (x_min is None or x_max is None):
        max_intensity_pos = np.argmax(pattern.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]

    # Filter x, y_meas, and y_calc based on x_min and x_max
    x = self._filtered_y_array(
        y_array=x_array,
        x_array=x_array,
        x_min=x_min,
        x_max=x_max,
    )
    y_meas = self._filtered_y_array(
        y_array=pattern.meas,
        x_array=x_array,
        x_min=x_min,
        x_max=x_max,
    )

    y_series = [y_meas]
    y_labels = ['meas']

    if d_spacing:
        axes_labels = DEFAULT_AXES_LABELS[
            (
                expt_type.scattering_type.value,
                'd-spacing',
            )
        ]
    else:
        axes_labels = DEFAULT_AXES_LABELS[
            (
                expt_type.scattering_type.value,
                expt_type.beam_mode.value,
            )
        ]

    # TODO: Before, it was self._plotter.plot. Check what is better.
    self._backend.plot(
        x=x,
        y_series=y_series,
        labels=y_labels,
        axes_labels=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, d_spacing=False)

Plot measured and calculated series and optional residual.

Parameters:

Name Type Description Default
pattern

Object with x, meas and calc arrays (and d when d_spacing is true).

required
expt_name

Experiment name for the title.

required
expt_type

Experiment type with scattering/beam enums.

required
x_min

Optional minimum x-axis limit.

None
x_max

Optional maximum x-axis limit.

None
show_residual

If True, add residual series.

False
d_spacing

If True, plot against d-spacing values.

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

    Args:
        pattern: Object with ``x``, ``meas`` and ``calc`` arrays
            (and ``d`` when ``d_spacing`` is true).
        expt_name: Experiment name for the title.
        expt_type: Experiment type with scattering/beam enums.
        x_min: Optional minimum x-axis limit.
        x_max: Optional maximum x-axis limit.
        show_residual: If ``True``, add residual series.
        d_spacing: If ``True``, plot against d-spacing values.
    """
    if pattern.x is None:
        log.error(f'No data available for experiment {expt_name}')
        return
    if pattern.meas is None:
        log.error(f'No measured data available for experiment {expt_name}')
        return
    if pattern.calc is None:
        log.error(f'No calculated data available for experiment {expt_name}')
        return

    # Select x-axis data based on d-spacing or original x values
    x_array = pattern.d if d_spacing else pattern.x

    # For asciichartpy, if x_min or x_max is not provided, center
    # around the maximum intensity peak
    if self._engine == 'asciichartpy' and (x_min is None or x_max is None):
        max_intensity_pos = np.argmax(pattern.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]

    # Filter x, y_meas, and y_calc based on x_min and x_max
    x = self._filtered_y_array(
        y_array=x_array,
        x_array=x_array,
        x_min=x_min,
        x_max=x_max,
    )
    y_meas = self._filtered_y_array(
        y_array=pattern.meas,
        x_array=x_array,
        x_min=x_min,
        x_max=x_max,
    )
    y_calc = self._filtered_y_array(
        y_array=pattern.calc,
        x_array=x_array,
        x_min=x_min,
        x_max=x_max,
    )

    y_series = [y_meas, y_calc]
    y_labels = ['meas', 'calc']

    if d_spacing:
        axes_labels = DEFAULT_AXES_LABELS[
            (
                expt_type.scattering_type.value,
                'd-spacing',
            )
        ]
    else:
        axes_labels = DEFAULT_AXES_LABELS[
            (
                expt_type.scattering_type.value,
                expt_type.beam_mode.value,
            )
        ]

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

    self._backend.plot(
        x=x,
        y_series=y_series,
        labels=y_labels,
        axes_labels=axes_labels,
        title=f"Measured vs Calculated data for experiment 🔬 '{expt_name}'",
        height=self.height,
    )

show_config()

Display the current plotting configuration.

Source code in src/easydiffraction/display/plotting.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def show_config(self):
    """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

Source code in src/easydiffraction/display/plotting.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class PlotterEngineEnum(str, Enum):
    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
32
33
34
35
36
37
38
39
@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
41
42
43
44
45
46
47
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
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
 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
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: Any) -> Any:
        """Format floats with fixed precision and others as strings.

        Args:
            value: Cell value to format.

        Returns:
            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):
        """Convert a Rich color name to a CSS-style hex string.

        Args:
            color: Rich color name or specification parsable by
                :mod:`rich`.

        Returns:
            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,
        df,
        display_handle: Any | None = None,
    ) -> Any:
        """Render the provided DataFrame with backend-specific styling.

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

        Returns:
            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

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

required
df

Index-aware DataFrame with data to render.

required
display_handle Any | None

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

None

Returns:

Type Description
Any

Backend-defined return value (commonly None).

Source code in src/easydiffraction/display/tablers/base.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@abstractmethod
def render(
    self,
    alignments,
    df,
    display_handle: Any | None = None,
) -> Any:
    """Render the provided DataFrame with backend-specific styling.

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

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

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

        Returns:
            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, alignments) -> list[dict]:
        """Generate header cell alignment styles per column.

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

        Returns:
            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, alignments, color: str):
        """Build a configured Styler with alignments and base styles.

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

        Returns:
            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, display_handle) -> 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()``.

        Args:
            styler: Configured DataFrame Styler to be rendered.
            display_handle: 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,
        df,
        display_handle: Any | None = None,
    ) -> Any:
        """Render a styled DataFrame.

        Args:
            alignments: Iterable of column justifications (e.g. 'left').
            df: DataFrame whose index is displayed as the first column.
            display_handle: Optional IPython DisplayHandle to update an
                existing output area in place when running in Jupyter.
        """
        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

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

required
df

DataFrame whose index is displayed as the first column.

required
display_handle Any | None

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

None
Source code in src/easydiffraction/display/tablers/pandas.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def render(
    self,
    alignments,
    df,
    display_handle: Any | None = None,
) -> Any:
    """Render a styled DataFrame.

    Args:
        alignments: Iterable of column justifications (e.g. 'left').
        df: DataFrame whose index is displayed as the first column.
        display_handle: Optional IPython DisplayHandle to update an
            existing output area in place when running in Jupyter.
    """
    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
 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
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.

        Args:
            table: Rich :class:`~rich.table.Table` to export.

        Returns:
            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, alignments, color: str) -> Table:
        """Construct a Rich Table with formatted data and alignment.

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

        Returns:
            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) -> 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.

        Args:
            table: Rich :class:`~rich.table.Table` to display.
            display_handle: 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,
        df,
        display_handle=None,
    ) -> Any:
        """Render a styled table using Rich.

        Args:
            alignments: Iterable of text-align values for columns.
            df: Index-aware DataFrame to render.
            display_handle: Optional environment handle for in-place
                updates.
        """
        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

Iterable of text-align values for columns.

required
df

Index-aware DataFrame to render.

required
display_handle

Optional environment handle for in-place updates.

None
Source code in src/easydiffraction/display/tablers/rich.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def render(
    self,
    alignments,
    df,
    display_handle=None,
) -> Any:
    """Render a styled table using Rich.

    Args:
        alignments: Iterable of text-align values for columns.
        df: Index-aware DataFrame to render.
        display_handle: Optional environment handle for in-place
            updates.
    """
    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

Source code in src/easydiffraction/display/tables.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class TableEngineEnum(str, Enum):
    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:
        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
25
26
27
28
29
30
31
32
33
34
35
@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

TableRenderer

Bases: RendererBase

Renderer for tabular data with selectable engines (singleton).

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

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

        Returns:
            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

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

required
display_handle Any | 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
Any

Backend-specific return value (usually None).

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

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

    Returns:
        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
57
58
59
60
61
62
63
64
65
66
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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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 that Jupyter output cells are not scrollable (applied 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
47
48
class JupyterScrollManager:
    """Ensures that Jupyter output cells are not scrollable (applied
    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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@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.')