xrdkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xrdkit/plotting.py ADDED
@@ -0,0 +1,1072 @@
1
+ """Publication quality plotting for X-ray diffraction patterns."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from collections.abc import Mapping, Sequence
8
+ from pathlib import Path
9
+
10
+ import matplotlib as mpl
11
+ import numpy as np
12
+ from matplotlib.axes import Axes
13
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
14
+ from matplotlib.figure import Figure
15
+ from matplotlib.lines import Line2D
16
+ from matplotlib.text import Text
17
+ from matplotlib.ticker import MultipleLocator
18
+ from matplotlib.transforms import Bbox
19
+
20
+ from xrdkit.broadening import Caglioti
21
+ from xrdkit.indexing import IndexedPeak, Reflection
22
+ from xrdkit.io import XRDScan
23
+
24
+ __all__ = [
25
+ "annotate_hkl",
26
+ "apply_style",
27
+ "mark_peaks",
28
+ "plot_caglioti",
29
+ "plot_pattern",
30
+ "plot_rietveld",
31
+ "plot_stacked",
32
+ "save_figure",
33
+ ]
34
+
35
+ SCALES = ("linear", "sqrt", "log")
36
+
37
+ X_LABEL = "2θ (degrees)"
38
+ Y_LABEL = "Intensity (arb. units)"
39
+ FWHM_LABEL = "FWHM (degrees)"
40
+
41
+ # Legend entries of plot_caglioti: the curve, the widths it was fitted to and
42
+ # those left out.
43
+ CAGLIOTI_LABELS = ("Caglioti fit", "Used in fit", "Excluded")
44
+
45
+ SINGLE_COLUMN = (3.5, 2.6)
46
+
47
+ X_MAJOR_TICK = 10.0
48
+ X_MINOR_TICK = 2.0
49
+
50
+ # Automatic stack spacing, as a multiple of the tallest scaled trace.
51
+ OFFSET_FACTOR = 1.2
52
+
53
+ # Stack labels sit this far below the top of their slot, and this fraction of
54
+ # the x range in from the right-hand end of the data.
55
+ LABEL_HEIGHT = 0.92
56
+ LABEL_MARGIN = 0.02
57
+
58
+ # The defaults of annotate_hkl, which together set the standing rule for hkl
59
+ # annotation: the labels go in a single row, only the major peaks are labelled,
60
+ # a weaker peak that would collide with a stronger one loses its label, and
61
+ # labels are never stacked into a column.
62
+ #
63
+ # Every peak of any visible size competes for room; which of them actually get
64
+ # a label is settled by what fits, not by this, so the cut-off only has to keep
65
+ # noise out of the running.
66
+ HKL_MIN_RELATIVE_INTENSITY = 5.0
67
+
68
+ HKL_FONTSIZE = 7
69
+
70
+ # Upright labels take the least horizontal room, which is what a crowded 2theta
71
+ # axis is short of.
72
+ HKL_ROTATION = 90
73
+
74
+ # One row. Raising this stacks labels into a column, which is off by default
75
+ # because a column drifts away from the peaks it names.
76
+ HKL_MAX_LEVELS = 1
77
+
78
+ # A peak that matched more than one reflection is labelled with the one it was
79
+ # assigned; see AMBIGUOUS_MODES for the alternatives.
80
+ HKL_AMBIGUOUS = "first"
81
+
82
+ # Fallback separation, in degrees, for a caller that wants a fixed one rather
83
+ # than the value annotate_hkl works out from the rendered label size.
84
+ HKL_MIN_SEPARATION = 0.6
85
+
86
+ # Clear space left between two neighbouring labels, in points.
87
+ LABEL_GAP_POINTS = 1.0
88
+
89
+ # Clear space left between a label and the top of its own peak, in points.
90
+ LABEL_PAD_POINTS = 2
91
+
92
+ # How far either side of a peak to look along a trace for its top, in degrees.
93
+ LABEL_PEAK_WINDOW = 0.15
94
+
95
+ # One level up, as a fraction of the y range of the axes.
96
+ HKL_LABEL_HEIGHT = 0.04
97
+
98
+ # How annotate_hkl treats a peak that matched more than one reflection.
99
+ AMBIGUOUS_MODES = ("first", "all", "skip")
100
+
101
+ # Joins the candidate labels of an ambiguous peak under ambiguous="all".
102
+ AMBIGUOUS_SEPARATOR = "/"
103
+
104
+ # plot_rietveld: the pattern columns the GSAS-II driver exports, the legend
105
+ # entries of the four curves, and how each is drawn. The package draws in
106
+ # black and white, so the observed points are grey to let the black
107
+ # calculated line show through them.
108
+ RIETVELD_COLUMNS = ("two_theta", "observed", "calculated", "background", "difference")
109
+ RIETVELD_LABELS = ("Observed", "Calculated", "Background", "Difference")
110
+ RIETVELD_FIGSIZE = (3.5, 3.0)
111
+ OBSERVED_STYLE = {
112
+ "linestyle": "none",
113
+ "marker": "o",
114
+ "markersize": 1.6,
115
+ "markerfacecolor": "none",
116
+ "markeredgecolor": "0.45",
117
+ "markeredgewidth": 0.4,
118
+ }
119
+ CALCULATED_STYLE = {"color": "black", "linewidth": 0.7}
120
+ BACKGROUND_STYLE = {"color": "0.55", "linewidth": 0.5}
121
+ DIFFERENCE_STYLE = {"color": "black", "linewidth": 0.5}
122
+
123
+ # Reflection ticks: one row per phase, the first black and the rest in
124
+ # lighter greys, each row this fraction of the pattern's height below the
125
+ # one above, with the difference curve a further row below the last.
126
+ TICK_COLOURS = ("black", "0.5", "0.7", "0.3")
127
+ TICK_MARKER_SIZE = 4.0
128
+ TICK_MARKER_WIDTH = 0.6
129
+ TICK_ROW_FRACTION = 0.06
130
+
131
+ # Room left above the pattern and below the difference curve, as a fraction
132
+ # of the whole height plotted.
133
+ RIETVELD_MARGIN = 0.03
134
+
135
+ # The block of fit statistics goes this many points below the legend.
136
+ STATISTICS_GAP_POINTS = 4.0
137
+ STATISTICS_FONTSIZE = 7
138
+
139
+ # The top of the y axis is raised until the pattern under the legend and the
140
+ # statistics stops this fraction of the axes height below them.
141
+ LEGEND_CLEARANCE = 0.02
142
+
143
+ # Two lattice parameters closer than this are taken as equal, and an angle
144
+ # this close to 90 degrees as a right angle, when the cell is written out.
145
+ CELL_TOLERANCE = 1e-6
146
+
147
+ # Written above a peak that the cell does not account for.
148
+ PEAK_MARKER = "*"
149
+ PEAK_MARKER_FONTSIZE = 9
150
+
151
+ # An index of 10 or more makes the compact form ambiguous, since (10 0 2) and
152
+ # (1 0 0) both run together as 1002. Those labels are spaced with a thin space,
153
+ # which separates the indices without opening the gap a full space would.
154
+ HKL_THIN_SPACE = "\u2009"
155
+ HKL_WIDE_INDEX = 10
156
+
157
+
158
+ def apply_style() -> None:
159
+ """Set global rcParams to a clean single-column journal style."""
160
+ families = {font.name for font in mpl.font_manager.fontManager.ttflist}
161
+ sans = ["Arial", "DejaVu Sans"] if "Arial" in families else ["DejaVu Sans"]
162
+
163
+ mpl.rcParams.update(
164
+ {
165
+ "font.family": "sans-serif",
166
+ "font.sans-serif": sans,
167
+ "font.size": 9,
168
+ "axes.labelsize": 9,
169
+ "axes.titlesize": 9,
170
+ "xtick.labelsize": 8,
171
+ "ytick.labelsize": 8,
172
+ "legend.fontsize": 8,
173
+ # Keep the full box: all four spines stay on.
174
+ "axes.linewidth": 0.8,
175
+ "axes.spines.top": True,
176
+ "axes.spines.right": True,
177
+ "axes.spines.left": True,
178
+ "axes.spines.bottom": True,
179
+ "axes.grid": False,
180
+ # Inward ticks on all four sides, minor ticks on x only.
181
+ "xtick.direction": "in",
182
+ "ytick.direction": "in",
183
+ "xtick.top": True,
184
+ "ytick.right": True,
185
+ "xtick.minor.visible": True,
186
+ "ytick.minor.visible": False,
187
+ "xtick.major.width": 0.8,
188
+ "ytick.major.width": 0.8,
189
+ "xtick.minor.width": 0.6,
190
+ "lines.linewidth": 0.7,
191
+ "savefig.dpi": 300,
192
+ "savefig.bbox": "tight",
193
+ }
194
+ )
195
+
196
+
197
+ def _scaled(intensity: np.ndarray, scale: str, normalise: bool) -> np.ndarray:
198
+ """Apply ``scale`` to ``intensity``, normalised to a maximum of 1 if asked.
199
+
200
+ Normalisation is applied to the transformed values so the result always
201
+ peaks at 1. For ``"linear"`` and ``"sqrt"`` that is identical to normalising
202
+ the counts first; for ``"log"`` it is the only meaningful order, since
203
+ normalised counts would all clip to the floor of 1 and vanish.
204
+ """
205
+ if scale not in SCALES:
206
+ raise ValueError(f"Unknown scale {scale!r}; expected one of {SCALES}")
207
+
208
+ values = np.asarray(intensity, dtype=float)
209
+ if scale == "sqrt":
210
+ values = np.sqrt(np.clip(values, 0.0, None))
211
+ elif scale == "log":
212
+ values = np.log10(np.clip(values, 1.0, None))
213
+
214
+ if normalise:
215
+ peak = float(np.max(values)) if values.size else 0.0
216
+ if peak > 0.0:
217
+ values = values / peak
218
+ return values
219
+
220
+
221
+ def _format_axes(ax: Axes, x_min: float, x_max: float) -> None:
222
+ """Apply the shared pattern axis labelling, ticks and limits."""
223
+ ax.set_xlabel(X_LABEL)
224
+ ax.set_ylabel(Y_LABEL)
225
+ ax.set_xlim(x_min, x_max)
226
+ # Fixed 10 degree major ticks so a scan running to nearly 100 degrees is
227
+ # still labelled at its far end, which the automatic locator does not do.
228
+ ax.xaxis.set_major_locator(MultipleLocator(X_MAJOR_TICK))
229
+ ax.xaxis.set_minor_locator(MultipleLocator(X_MINOR_TICK))
230
+ # Intensities are arbitrary units, so the y scale carries no ticks.
231
+ ax.set_yticks([])
232
+ ax.tick_params(axis="y", which="both", left=False, right=False, labelleft=False)
233
+
234
+
235
+ def plot_pattern(
236
+ scan: XRDScan,
237
+ ax: Axes | None = None,
238
+ scale: str = "linear",
239
+ normalise: bool = False,
240
+ label: str | None = None,
241
+ colour: str = "black",
242
+ linewidth: float = 0.7,
243
+ ) -> tuple[Figure, Axes]:
244
+ """Plot a single diffraction pattern.
245
+
246
+ Parameters
247
+ ----------
248
+ scan
249
+ The scan to plot.
250
+ ax
251
+ Axes to draw on. A new single-column figure is created if omitted.
252
+ scale
253
+ Intensity scale: ``"linear"``, ``"sqrt"`` or ``"log"``.
254
+ normalise
255
+ Scale the trace to a maximum of 1.
256
+ label
257
+ Legend label for the line.
258
+ colour, linewidth
259
+ Line appearance.
260
+
261
+ Raises
262
+ ------
263
+ ValueError
264
+ If ``scale`` is not a known scale.
265
+ """
266
+ values = _scaled(scan.intensity, scale, normalise)
267
+
268
+ if ax is None:
269
+ fig = Figure(figsize=SINGLE_COLUMN)
270
+ ax = fig.add_subplot()
271
+ else:
272
+ fig = ax.figure
273
+
274
+ ax.plot(scan.two_theta, values, color=colour, linewidth=linewidth, label=label)
275
+ _format_axes(ax, float(scan.two_theta[0]), float(scan.two_theta[-1]))
276
+ return fig, ax
277
+
278
+
279
+ def plot_stacked(
280
+ scans: list[XRDScan],
281
+ labels: list[str] | None = None,
282
+ offset: float | None = None,
283
+ scale: str = "linear",
284
+ normalise: bool = True,
285
+ colour: str = "black",
286
+ linewidth: float = 0.7,
287
+ figsize: tuple[float, float] = (3.5, 5.0),
288
+ ) -> tuple[Figure, Axes, list[float], list[Line2D]]:
289
+ """Plot several patterns stacked vertically with a constant offset.
290
+
291
+ Parameters
292
+ ----------
293
+ scans
294
+ Scans to stack, drawn bottom to top in the order given.
295
+ labels
296
+ One label per scan, written at the upper right of each trace. Defaults
297
+ to each scan's ``sample_id``.
298
+ offset
299
+ Vertical spacing between traces. Defaults to 1.2 times the tallest
300
+ scaled trace, which keeps the tallest peak clear of the trace above.
301
+ scale, normalise, colour, linewidth
302
+ As for :func:`plot_pattern`.
303
+ figsize
304
+ Figure size in inches.
305
+
306
+ Returns
307
+ -------
308
+ tuple[Figure, Axes, list[float], list[Line2D]]
309
+ The figure, the axes, the vertical base of each slot, and the line
310
+ drawn for each scan, both in the order the scans were given. The bases
311
+ and the lines are what :func:`annotate_hkl` and :func:`mark_peaks` need
312
+ to place labels against a chosen trace.
313
+
314
+ Raises
315
+ ------
316
+ ValueError
317
+ If ``scans`` is empty, ``scale`` is unknown, or ``labels`` has a
318
+ different length to ``scans``.
319
+ """
320
+ if not scans:
321
+ raise ValueError("plot_stacked needs at least one scan")
322
+ if labels is not None and len(labels) != len(scans):
323
+ raise ValueError(
324
+ f"Got {len(labels)} labels for {len(scans)} scans; lengths must match"
325
+ )
326
+
327
+ traces = [_scaled(scan.intensity, scale, normalise) for scan in scans]
328
+ if labels is None:
329
+ labels = [scan.sample_id for scan in scans]
330
+
331
+ if offset is None:
332
+ offset = OFFSET_FACTOR * max(float(np.max(trace)) for trace in traces)
333
+
334
+ x_min = min(float(scan.two_theta[0]) for scan in scans)
335
+ x_max = max(float(scan.two_theta[-1]) for scan in scans)
336
+ label_x = x_max - LABEL_MARGIN * (x_max - x_min)
337
+
338
+ fig = Figure(figsize=figsize)
339
+ ax = fig.add_subplot()
340
+
341
+ bases: list[float] = []
342
+ lines: list[Line2D] = []
343
+ for index, (scan, trace, text) in enumerate(zip(scans, traces, labels)):
344
+ base = index * offset
345
+ bases.append(base)
346
+ drawn = ax.plot(
347
+ scan.two_theta, trace + base, color=colour, linewidth=linewidth, label=text
348
+ )
349
+ lines.append(drawn[0])
350
+ # Anchored to the slot, not to the trace's peak, so a strong high angle
351
+ # reflection cannot push a label into the trace above it.
352
+ ax.text(
353
+ label_x,
354
+ base + LABEL_HEIGHT * offset,
355
+ text,
356
+ ha="right",
357
+ va="top",
358
+ fontsize=8,
359
+ )
360
+
361
+ _format_axes(ax, x_min, x_max)
362
+ # Every slot gets the same height, so the topmost label always has room.
363
+ ax.set_ylim(min(0.0, float(np.min(traces[0]))), (len(scans) - 1) * offset + offset)
364
+ return fig, ax, bases, lines
365
+
366
+
367
+ def _hkl_label(reflection: Reflection) -> str:
368
+ """Return the Miller indices as a label, so ``(3 1 1)`` becomes ``311``.
369
+
370
+ Indices below 10 run together. As soon as one reaches ``HKL_WIDE_INDEX`` the
371
+ compact form stops being readable, so every index of that label is separated
372
+ by a thin space instead: ``(10 0 2)`` becomes ``10 0 2`` rather than
373
+ ``1002``, which would otherwise be indistinguishable from ``(1 0 0)`` with a
374
+ trailing 2.
375
+ """
376
+ indices = reflection.hkl
377
+ separator = HKL_THIN_SPACE if max(indices) >= HKL_WIDE_INDEX else ""
378
+ return separator.join(str(index) for index in indices)
379
+
380
+
381
+ def _renderer_for(figure: Figure) -> object:
382
+ """Return a renderer able to measure text on ``figure``.
383
+
384
+ A figure built directly, rather than through a backend, carries a plain
385
+ ``FigureCanvasBase``, which cannot rasterise and so offers no renderer at
386
+ all. Attaching an Agg canvas gives one without going near pyplot.
387
+ """
388
+ canvas = figure.canvas
389
+ if not hasattr(canvas, "get_renderer"):
390
+ canvas = FigureCanvasAgg(figure)
391
+ try:
392
+ return canvas.get_renderer()
393
+ except AttributeError:
394
+ canvas.draw()
395
+ return canvas.get_renderer()
396
+
397
+
398
+ def _write_label(
399
+ ax: Axes,
400
+ position: float,
401
+ height: float,
402
+ label: str,
403
+ fontsize: float,
404
+ rotation: float,
405
+ ) -> Text:
406
+ """Write one hkl label with its bottom centre exactly at ``(position, height)``.
407
+
408
+ The alignment is applied to the text as rotated, which is what
409
+ ``rotation_mode="default"`` means and what puts the middle of the drawn
410
+ label over its peak at any angle. Aligning before rotating instead, with
411
+ ``rotation_mode="anchor"``, swings a label upright about its own baseline
412
+ and leaves it a third of a degree to the left of the peak it names.
413
+ """
414
+ return ax.text(
415
+ position,
416
+ height,
417
+ label,
418
+ ha="center",
419
+ va="bottom",
420
+ fontsize=fontsize,
421
+ rotation=rotation,
422
+ rotation_mode="default",
423
+ )
424
+
425
+
426
+ def _peak_top(
427
+ line: Line2D, position: float, window: float = LABEL_PEAK_WINDOW
428
+ ) -> float:
429
+ """Return the highest point of ``line`` within ``window`` of ``position``.
430
+
431
+ Falls back to the nearest point it has when nothing lies inside the window,
432
+ so a label is never stranded at the foot of the axes.
433
+ """
434
+ x = np.asarray(line.get_xdata(), dtype=float)
435
+ values = np.asarray(line.get_ydata(), dtype=float)
436
+ near = np.abs(x - position) <= window
437
+ if not np.any(near):
438
+ return float(values[np.argmin(np.abs(x - position))])
439
+ return float(np.max(values[near]))
440
+
441
+
442
+ def _points_in_data(ax: Axes, points: float) -> float:
443
+ """Return ``points`` as a vertical distance in the data units of ``ax``."""
444
+ pixels = points * ax.figure.dpi / 72.0
445
+ inverse = ax.transData.inverted()
446
+ return inverse.transform((0.0, pixels))[1] - inverse.transform((0.0, 0.0))[1]
447
+
448
+
449
+ def annotate_hkl(
450
+ ax: Axes,
451
+ indexed: list[IndexedPeak],
452
+ y: float = 0.0,
453
+ min_relative_intensity: float = HKL_MIN_RELATIVE_INTENSITY,
454
+ fontsize: float = HKL_FONTSIZE,
455
+ rotation: float = HKL_ROTATION,
456
+ min_separation: float | None = None,
457
+ label_height: float | None = None,
458
+ ambiguous: str = HKL_AMBIGUOUS,
459
+ max_levels: int = HKL_MAX_LEVELS,
460
+ line: Line2D | None = None,
461
+ ) -> list[Text]:
462
+ """Write an hkl label above the indexed peaks of one trace, strongest first.
463
+
464
+ By default the labels go in a single row, only the major peaks are
465
+ labelled, a weaker peak that would collide with a stronger one loses its
466
+ label, and labels are never stacked into a column.
467
+
468
+ Given a ``line``, each label rides on top of its own peak, a couple of
469
+ points above the highest the trace reaches nearby, which keeps a label and
470
+ the reflection it names together however the pattern rises and falls.
471
+ Without one they share a fixed row with their base at ``y``, normally the
472
+ base of the slot the trace occupies plus enough room to clear its tallest
473
+ peak. Either way the bottom centre of the label sits exactly over the
474
+ observed peak position. Peaks with no assignment are skipped; use
475
+ :func:`mark_peaks` for those.
476
+
477
+ Room is allotted by priority rather than by position. The peaks are taken
478
+ strongest first, and each is given the lowest level on which no label has
479
+ yet been placed within ``min_separation`` degrees of it. Level 0 has its
480
+ base at ``y`` and every level above it is raised by another
481
+ ``label_height``. **A peak that finds no free level keeps no label**, so in
482
+ a crowded stretch it is the weaker peaks that lose theirs and the strong
483
+ reflections a reader is looking for stay labelled. With the default
484
+ ``max_levels`` of 1 the annotation is a single row.
485
+
486
+ By default nothing is estimated: each label is written, its rendered
487
+ bounding box measured, and kept only if that box, widened by
488
+ ``LABEL_GAP_POINTS``, clears every box already placed. Riding the peaks
489
+ puts the labels at all sorts of heights, so with a ``line`` a box is
490
+ compared with every other and two labels a tenth of a degree apart both
491
+ stay as long as their peaks differ enough in height; without one the
492
+ comparison is per level. This packs
493
+ the labels as tightly as the text really allows, whatever they say and at
494
+ whatever angle. **The figure size and the x limits are read as they
495
+ stand**, so set both before calling this; annotating and then resizing the
496
+ figure or changing the limits will leave the labels where the old geometry
497
+ put them.
498
+
499
+ Parameters
500
+ ----------
501
+ ax
502
+ Axes to write on.
503
+ indexed
504
+ Result of :func:`~xrdkit.indexing.index_peaks` for the trace.
505
+ y
506
+ Base of the level 0 labels, in data coordinates.
507
+ min_relative_intensity
508
+ Skip peaks below this percentage of the strongest peak of the scan.
509
+ fontsize, rotation
510
+ Label appearance. The rotation is in degrees, anticlockwise.
511
+ min_separation
512
+ Two labels on the same level must be at least this far apart, in
513
+ degrees. ``None``, the default, measures the rendered labels instead
514
+ and keeps whichever ones do not overlap.
515
+ label_height
516
+ Height of one level, in data coordinates. Defaults to
517
+ ``HKL_LABEL_HEIGHT`` times the y range of ``ax``.
518
+ ambiguous
519
+ What to do with a peak that matched more than one reflection:
520
+ ``"first"`` labels the assigned one, ``"all"`` joins every candidate
521
+ with a solidus, ``"skip"`` leaves the peak unlabelled.
522
+ max_levels
523
+ How many levels to try. One keeps every label in a single row. Ignored
524
+ when ``line`` is given, since a label then sits on its own peak rather
525
+ than on a level.
526
+ line
527
+ The trace the peaks belong to, as returned by :func:`plot_stacked`. Its
528
+ y data is what each label is stood on. ``None`` puts them all in a row
529
+ at ``y`` instead. Giving one always measures, so ``min_separation`` has
530
+ no effect.
531
+
532
+ Returns
533
+ -------
534
+ list[Text]
535
+ The labels written, in 2theta order. Peaks that found no free level are
536
+ not represented, so this can be shorter than the peaks given.
537
+
538
+ Raises
539
+ ------
540
+ ValueError
541
+ If ``ambiguous`` is not one of ``AMBIGUOUS_MODES``, or ``max_levels`` is
542
+ below one.
543
+ """
544
+ if ambiguous not in AMBIGUOUS_MODES:
545
+ raise ValueError(
546
+ f"Unknown ambiguous mode {ambiguous!r}; expected one of {AMBIGUOUS_MODES}"
547
+ )
548
+ if max_levels < 1:
549
+ raise ValueError(f"Need at least one level, got {max_levels}")
550
+
551
+ if label_height is None:
552
+ low, high = ax.get_ylim()
553
+ label_height = HKL_LABEL_HEIGHT * (high - low)
554
+
555
+ entries = [
556
+ entry
557
+ for entry in indexed
558
+ if entry.is_indexed
559
+ and entry.peak.relative_intensity >= min_relative_intensity
560
+ and not (ambiguous == "skip" and len(entry.candidates) > 1)
561
+ ]
562
+ # Strongest first, so the peaks that matter claim their room before the
563
+ # weak ones. Ties fall back on position to keep the choice reproducible.
564
+ entries.sort(
565
+ key=lambda entry: (-entry.peak.relative_intensity, entry.peak.two_theta)
566
+ )
567
+
568
+ labelled = [
569
+ (
570
+ entry,
571
+ AMBIGUOUS_SEPARATOR.join(
572
+ _hkl_label(reflection) for reflection in entry.candidates
573
+ )
574
+ if ambiguous == "all" and len(entry.candidates) > 1
575
+ else _hkl_label(entry.reflection),
576
+ )
577
+ for entry in entries
578
+ ]
579
+
580
+ # Standing the labels on their peaks always measures, since their heights
581
+ # are then all different and only the boxes can say what really clashes.
582
+ measuring = line is not None or min_separation is None
583
+ renderer = _renderer_for(ax.figure) if measuring else None
584
+ # A point is this many pixels, and the gap is left on each side of the box.
585
+ gap = LABEL_GAP_POINTS * ax.figure.dpi / 72.0 if measuring else 0.0
586
+ pad = _points_in_data(ax, LABEL_PAD_POINTS) if line is not None else 0.0
587
+
588
+ # One list of levels to try, or a single pass when each label has its own
589
+ # height and there are no levels to speak of.
590
+ levels = 1 if line is not None else max_levels
591
+ boxes: list[list[Bbox]] = [[] for _ in range(levels)]
592
+ taken: list[list[float]] = [[] for _ in range(levels)]
593
+ placed: list[tuple[float, Text]] = []
594
+
595
+ for entry, label in labelled:
596
+ position = entry.peak.two_theta
597
+ for level in range(levels):
598
+ if line is not None:
599
+ height = _peak_top(line, position) + pad
600
+ else:
601
+ height = y + level * label_height
602
+
603
+ if not measuring:
604
+ if any(
605
+ abs(position - other) < min_separation for other in taken[level]
606
+ ):
607
+ continue
608
+ taken[level].append(position)
609
+ placed.append(
610
+ (
611
+ position,
612
+ _write_label(ax, position, height, label, fontsize, rotation),
613
+ )
614
+ )
615
+ break
616
+
617
+ # Written before it is measured, since only a real Text knows how
618
+ # much room it takes, and taken away again if it does not fit.
619
+ text = _write_label(ax, position, height, label, fontsize, rotation)
620
+ box = text.get_window_extent(renderer)
621
+ widened = Bbox.from_extents(box.x0 - gap, box.y0, box.x1 + gap, box.y1)
622
+ if any(widened.overlaps(other) for other in boxes[level]):
623
+ text.remove()
624
+ continue
625
+ boxes[level].append(box)
626
+ placed.append((position, text))
627
+ break
628
+
629
+ placed.sort(key=lambda item: item[0])
630
+ return [text for _, text in placed]
631
+
632
+
633
+ def mark_peaks(
634
+ ax: Axes,
635
+ positions: list[float],
636
+ y: float,
637
+ marker: str = PEAK_MARKER,
638
+ fontsize: float = PEAK_MARKER_FONTSIZE,
639
+ ) -> list[Text]:
640
+ """Write ``marker`` above each 2theta in ``positions``, with its base at ``y``.
641
+
642
+ For the peaks a cell does not account for, whether unindexed or from a
643
+ second phase, which are worth pointing at even though they carry no hkl.
644
+
645
+ Returns
646
+ -------
647
+ list[Text]
648
+ One marker per position, in the order given.
649
+ """
650
+ return [
651
+ ax.text(position, y, marker, ha="center", va="bottom", fontsize=fontsize)
652
+ for position in positions
653
+ ]
654
+
655
+
656
+ def plot_caglioti(
657
+ fit: Caglioti,
658
+ two_theta: np.ndarray,
659
+ fwhm: np.ndarray,
660
+ esd: np.ndarray | None = None,
661
+ included: np.ndarray | None = None,
662
+ ax: Axes | None = None,
663
+ two_theta_range: tuple[float, float] | None = None,
664
+ labels: tuple[str, str, str] = CAGLIOTI_LABELS,
665
+ ) -> tuple[Figure, Axes]:
666
+ """Plot measured peak widths against 2theta with a fitted Caglioti curve.
667
+
668
+ Widths used in the fit are drawn as filled circles and the rest as open
669
+ ones, so the two can be told apart without colour. With other ``labels``
670
+ the same figure serves for sample widths against the instrumental curve,
671
+ the open circles then marking whatever the caller singles out.
672
+
673
+ Parameters
674
+ ----------
675
+ fit
676
+ The Caglioti function to draw.
677
+ two_theta, fwhm
678
+ The measured positions and widths, in degrees.
679
+ esd
680
+ Esds of the widths, drawn as error bars when given.
681
+ included
682
+ Which widths the fit used. All of them by default.
683
+ ax
684
+ Axes to draw on. A new single-column figure is created if omitted.
685
+ two_theta_range
686
+ ``(low, high)`` x limits. By default the data span, widened out to
687
+ whole major ticks.
688
+ labels
689
+ Legend entries for the curve, the filled points and the open points.
690
+ """
691
+ two_theta = np.asarray(two_theta, dtype=float)
692
+ fwhm = np.asarray(fwhm, dtype=float)
693
+ curve_label, filled_label, open_label = labels
694
+ used = (
695
+ np.ones(two_theta.size, dtype=bool)
696
+ if included is None
697
+ else np.asarray(included, dtype=bool)
698
+ )
699
+
700
+ if ax is None:
701
+ fig = Figure(figsize=SINGLE_COLUMN)
702
+ ax = fig.add_subplot()
703
+ else:
704
+ fig = ax.figure
705
+
706
+ if two_theta_range is None:
707
+ two_theta_range = (
708
+ X_MAJOR_TICK * np.floor(two_theta.min() / X_MAJOR_TICK),
709
+ X_MAJOR_TICK * np.ceil(two_theta.max() / X_MAJOR_TICK),
710
+ )
711
+ low, high = two_theta_range
712
+ # The curve is undefined at 0 degrees, so it starts just above it.
713
+ curve = np.linspace(max(low, 0.5), high, 400)
714
+ ax.plot(curve, fit.fwhm(curve), color="black", label=curve_label)
715
+
716
+ for mask, face, label in (
717
+ (used, "black", filled_label),
718
+ (~used, "white", open_label),
719
+ ):
720
+ if not np.any(mask):
721
+ continue
722
+ ax.errorbar(
723
+ two_theta[mask],
724
+ fwhm[mask],
725
+ yerr=None if esd is None else np.asarray(esd, dtype=float)[mask],
726
+ fmt="o",
727
+ markersize=4,
728
+ markerfacecolor=face,
729
+ markeredgecolor="black",
730
+ markeredgewidth=0.8,
731
+ ecolor="black",
732
+ elinewidth=0.6,
733
+ capsize=1.5,
734
+ label=label,
735
+ )
736
+
737
+ ax.set_xlabel(X_LABEL)
738
+ ax.set_ylabel(FWHM_LABEL)
739
+ ax.set_xlim(low, high)
740
+ ax.xaxis.set_major_locator(MultipleLocator(X_MAJOR_TICK))
741
+ ax.xaxis.set_minor_locator(MultipleLocator(X_MINOR_TICK))
742
+ ax.legend(frameon=False)
743
+ return fig, ax
744
+
745
+
746
+ def _read_table(table: object, columns: Sequence[str], what: str) -> list[np.ndarray]:
747
+ """The named columns of a CSV file or of anything indexed by column name.
748
+
749
+ A path is read as a CSV file with a header row. Anything else is indexed
750
+ by the column names, which covers a dict of arrays, a numpy structured
751
+ array and a pandas DataFrame alike without importing pandas.
752
+ """
753
+ if isinstance(table, (str, Path)):
754
+ table = np.atleast_1d(np.genfromtxt(table, delimiter=",", names=True))
755
+ names = table.dtype.names or ()
756
+ else:
757
+ names = None
758
+ values = []
759
+ for column in columns:
760
+ if names is not None and column not in names:
761
+ raise ValueError(f"{what} has no {column!r} column")
762
+ try:
763
+ values.append(np.asarray(table[column], dtype=float).ravel())
764
+ except (KeyError, ValueError, IndexError) as error:
765
+ raise ValueError(f"{what} has no {column!r} column") from error
766
+ return values
767
+
768
+
769
+ def _format_esd(value: float, esd: float | None) -> str:
770
+ """``value`` with its esd in brackets, as 4.15683(2).
771
+
772
+ The esd keeps one significant figure, or two when it begins with a 1, and
773
+ the value is rounded to match. With no esd, or a zero one for a value
774
+ held fixed, the value is written as it stands.
775
+ """
776
+ if esd is None or not esd > 0.0 or not math.isfinite(esd):
777
+ return f"{value:.10g}"
778
+ decimals = -math.floor(math.log10(esd))
779
+ if round(esd * 10.0**decimals) == 1:
780
+ decimals += 1
781
+ decimals = max(decimals, 0)
782
+ digits = round(esd * 10.0**decimals)
783
+ return f"{value:.{decimals}f}({digits})"
784
+
785
+
786
+ def _cell_text(cell: Mapping[str, float], esd: Mapping[str, float] | None) -> str:
787
+ """The lattice parameters a reader needs, with the cell's symmetry used.
788
+
789
+ Lengths that are equal are given once, as a for a cubic cell and a and c
790
+ for a tetragonal or hexagonal one, and only angles other than 90 degrees
791
+ are written.
792
+ """
793
+ esd = esd or {}
794
+ a, b, c = (cell[f"length_{axis}"] for axis in "abc")
795
+ if abs(a - b) < CELL_TOLERANCE and abs(b - c) < CELL_TOLERANCE:
796
+ lengths = "a"
797
+ elif abs(a - b) < CELL_TOLERANCE:
798
+ lengths = "ac"
799
+ else:
800
+ lengths = "abc"
801
+ parts = [
802
+ f"{axis} = {_format_esd(cell[f'length_{axis}'], esd.get(f'length_{axis}'))} Å"
803
+ for axis in lengths
804
+ ]
805
+ for key, symbol in (("alpha", "α"), ("beta", "β"), ("gamma", "γ")):
806
+ angle = cell[f"angle_{key}"]
807
+ if abs(angle - 90.0) > CELL_TOLERANCE:
808
+ parts.append(f"{symbol} = {_format_esd(angle, esd.get(f'angle_{key}'))}°")
809
+ return ", ".join(parts)
810
+
811
+
812
+ def _statistics_text(result: Mapping | str | Path) -> str:
813
+ """Rwp, GOF and the refined cells of a GSAS-II refine result.
814
+
815
+ The figures of merit are those of the last stage that succeeded, and the
816
+ cells those of the result's final values.
817
+ """
818
+ if isinstance(result, (str, Path)):
819
+ result = json.loads(Path(result).read_text(encoding="utf-8"))
820
+ lines = []
821
+ good = [stage for stage in result.get("stages", []) if "error" not in stage]
822
+ if good:
823
+ last = good[-1]
824
+ lines.append(
825
+ rf"$\mathregular{{R_{{wp}}}}$ = {last['rwp']:.2f}%, GOF = {last['gof']:.2f}"
826
+ )
827
+ for phase in result.get("final", {}).get("phases", []):
828
+ lines.append(
829
+ f"{phase['name']}: {_cell_text(phase['cell'], phase.get('cell_esd'))}"
830
+ )
831
+ return "\n".join(lines)
832
+
833
+
834
+ def _below_legend(ax: Axes, legend: object, text: str) -> Text:
835
+ """Write ``text`` right-aligned just below ``legend``, in axes coordinates."""
836
+ renderer = _renderer_for(ax.figure)
837
+ box = legend.get_window_extent(renderer)
838
+ gap = STATISTICS_GAP_POINTS * ax.figure.dpi / 72.0
839
+ x, y = ax.transAxes.inverted().transform((box.x1, box.y0 - gap))
840
+ return ax.text(
841
+ x,
842
+ y,
843
+ text,
844
+ transform=ax.transAxes,
845
+ ha="right",
846
+ va="top",
847
+ fontsize=STATISTICS_FONTSIZE,
848
+ linespacing=1.3,
849
+ )
850
+
851
+
852
+ def _clear_of(
853
+ ax: Axes, artists: list, two_theta: np.ndarray, curves: list[np.ndarray]
854
+ ) -> None:
855
+ """Raise the top of the y axis until ``curves`` pass under ``artists``.
856
+
857
+ The legend and the statistics are placed in axes coordinates, so they
858
+ keep their place in the frame as the y limits change while the pattern
859
+ shrinks beneath them. Only the stretch of 2theta they span is considered,
860
+ so a pattern whose tall peaks lie elsewhere is not squashed for nothing.
861
+ """
862
+ renderer = _renderer_for(ax.figure)
863
+ box = Bbox.union([artist.get_window_extent(renderer) for artist in artists])
864
+ low, high = sorted(
865
+ ax.transData.inverted().transform([(box.x0, 0.0), (box.x1, 0.0)])[:, 0]
866
+ )
867
+ bottom = ax.transAxes.inverted().transform((box.x0, box.y0))[1] - LEGEND_CLEARANCE
868
+ under = (two_theta >= low) & (two_theta <= high)
869
+ if not np.any(under) or bottom <= 0.0:
870
+ return
871
+ peak = max(float(np.max(curve[under])) for curve in curves)
872
+ y_min, y_max = ax.get_ylim()
873
+ needed = y_min + (peak - y_min) / bottom
874
+ if needed > y_max:
875
+ ax.set_ylim(y_min, needed)
876
+
877
+
878
+ def plot_rietveld(
879
+ pattern: object,
880
+ reflections: Mapping[str, object] | Sequence[object] | None = None,
881
+ title: str | None = None,
882
+ phase_labels: Sequence[str] | None = None,
883
+ ax: Axes | None = None,
884
+ sqrt_scale: bool = False,
885
+ difference_offset: float | None = None,
886
+ result: Mapping | str | Path | None = None,
887
+ ) -> tuple[Figure, Axes]:
888
+ """Plot a Rietveld fit: observed, calculated, background and difference.
889
+
890
+ The observed points are small open grey circles, the calculated pattern a
891
+ black line through them and the background a thin grey line. Below the
892
+ pattern each phase has a row of tick marks at its reflections, the first
893
+ phase at the top, and below those the observed less the calculated
894
+ pattern is drawn about a zero of its own. Every curve and tick row is
895
+ named in the legend.
896
+
897
+ Parameters
898
+ ----------
899
+ pattern
900
+ The pattern as the GSAS-II driver exports it, with columns
901
+ ``two_theta``, ``observed``, ``calculated``, ``background`` and
902
+ ``difference``: the path of its CSV file, or a table indexed by
903
+ column name such as a pandas DataFrame or a dict of arrays.
904
+ reflections
905
+ Reflection lists, each with a ``two_theta`` column, as paths or
906
+ tables: a mapping of phase name to list, such as the driver result's
907
+ ``exports["reflections"]``, or a sequence of lists. Reflections
908
+ outside the pattern's range are left out.
909
+ title
910
+ Axes title.
911
+ phase_labels
912
+ Legend names of the phases, in the order of ``reflections``. By
913
+ default the mapping's keys, or "Phase 1", "Phase 2" and so on for a
914
+ sequence.
915
+ ax
916
+ Axes to draw on. A new figure is created if omitted.
917
+ sqrt_scale
918
+ Plot the square root of the counts, which brings up weak reflections.
919
+ The difference is then that of the square roots, so that it is on the
920
+ scale of the curves above it.
921
+ difference_offset
922
+ Height of the zero of the difference curve. By default it is put
923
+ below zero and below the lowest tick row, clear of both.
924
+ result
925
+ The result of the driver's refine action, as a dict or the path of
926
+ its JSON file. Given, Rwp and GOF of the last stage that succeeded and
927
+ each phase's refined cell are written in a small block below the
928
+ legend.
929
+
930
+ Returns
931
+ -------
932
+ tuple[Figure, Axes]
933
+ The figure and the axes drawn on. The whole fit shares one Axes: the
934
+ curves, the tick rows and the difference are all drawn on it, so there
935
+ is no further panel to return.
936
+
937
+ Raises
938
+ ------
939
+ ValueError
940
+ If a table lacks a column, or ``phase_labels`` does not have one name
941
+ per reflection list.
942
+ """
943
+ two_theta, observed, calculated, background, difference = _read_table(
944
+ pattern, RIETVELD_COLUMNS, "pattern"
945
+ )
946
+ if sqrt_scale:
947
+ observed, calculated, background = (
948
+ np.sqrt(np.clip(values, 0.0, None))
949
+ for values in (observed, calculated, background)
950
+ )
951
+ difference = observed - calculated
952
+
953
+ if reflections is None:
954
+ tables, names = [], []
955
+ elif isinstance(reflections, Mapping):
956
+ tables, names = list(reflections.values()), [str(name) for name in reflections]
957
+ else:
958
+ tables = list(reflections)
959
+ names = [f"Phase {index}" for index in range(1, len(tables) + 1)]
960
+ if phase_labels is not None:
961
+ if len(phase_labels) != len(tables):
962
+ raise ValueError(
963
+ f"Got {len(phase_labels)} phase labels for {len(tables)} "
964
+ "reflection lists; lengths must match"
965
+ )
966
+ names = list(phase_labels)
967
+ positions = [
968
+ _read_table(table, ("two_theta",), f"reflections of {name}")[0]
969
+ for table, name in zip(tables, names)
970
+ ]
971
+
972
+ if ax is None:
973
+ fig = Figure(figsize=RIETVELD_FIGSIZE)
974
+ ax = fig.add_subplot()
975
+ else:
976
+ fig = ax.figure
977
+
978
+ low, high = float(np.min(two_theta)), float(np.max(two_theta))
979
+ top = float(max(np.max(observed), np.max(calculated)))
980
+ # The tick rows start below zero, or below the pattern should it dip
981
+ # under zero, and step down by a fixed share of the pattern's height.
982
+ base = min(0.0, float(min(np.min(observed), np.min(calculated))))
983
+ step = TICK_ROW_FRACTION * (top - base)
984
+ rows = [base - (index + 1) * step for index in range(len(positions))]
985
+ if difference_offset is None:
986
+ lowest = rows[-1] if rows else base
987
+ difference_offset = lowest - step - float(np.max(difference))
988
+
989
+ observed_label, calculated_label, background_label, difference_label = (
990
+ RIETVELD_LABELS
991
+ )
992
+ # The background goes down before the calculated line, which then lies
993
+ # over it where the two meet between the peaks.
994
+ ax.plot(two_theta, observed, label=observed_label, **OBSERVED_STYLE)
995
+ ax.plot(two_theta, background, label=background_label, **BACKGROUND_STYLE)
996
+ ax.plot(two_theta, calculated, label=calculated_label, **CALCULATED_STYLE)
997
+ ax.plot(
998
+ two_theta,
999
+ difference + difference_offset,
1000
+ label=difference_label,
1001
+ **DIFFERENCE_STYLE,
1002
+ )
1003
+ for index, (ticks, name, row) in enumerate(zip(positions, names, rows)):
1004
+ inside = ticks[(ticks >= low) & (ticks <= high)]
1005
+ ax.plot(
1006
+ inside,
1007
+ np.full(inside.shape, row),
1008
+ linestyle="none",
1009
+ marker="|",
1010
+ markersize=TICK_MARKER_SIZE,
1011
+ markeredgewidth=TICK_MARKER_WIDTH,
1012
+ color=TICK_COLOURS[index % len(TICK_COLOURS)],
1013
+ label=name,
1014
+ )
1015
+
1016
+ _format_axes(ax, low, high)
1017
+ if sqrt_scale:
1018
+ ax.set_ylabel("√" + Y_LABEL)
1019
+ bottom = float(np.min(difference)) + difference_offset
1020
+ margin = RIETVELD_MARGIN * (top - bottom)
1021
+ ax.set_ylim(bottom - margin, top + margin)
1022
+ if title:
1023
+ ax.set_title(title)
1024
+
1025
+ # Observed first in the legend, then the curves drawn over it.
1026
+ handles, texts = ax.get_legend_handles_labels()
1027
+ order = [texts.index(label) for label in RIETVELD_LABELS] + list(
1028
+ range(len(RIETVELD_LABELS), len(texts))
1029
+ )
1030
+ legend = ax.legend(
1031
+ [handles[i] for i in order],
1032
+ [texts[i] for i in order],
1033
+ loc="upper right",
1034
+ frameon=False,
1035
+ markerscale=2.0,
1036
+ handlelength=1.5,
1037
+ labelspacing=0.3,
1038
+ borderaxespad=0.4,
1039
+ )
1040
+ artists = [legend]
1041
+ if result is not None:
1042
+ text = _statistics_text(result)
1043
+ if text:
1044
+ artists.append(_below_legend(ax, legend, text))
1045
+ _clear_of(ax, artists, two_theta, [observed, calculated])
1046
+ return fig, ax
1047
+
1048
+
1049
+ def save_figure(
1050
+ fig: Figure,
1051
+ path: str | Path,
1052
+ formats: tuple[str, ...] = ("png", "pdf"),
1053
+ dpi: int = 300,
1054
+ ) -> list[Path]:
1055
+ """Save ``fig`` once per format next to ``path``, returning the paths written.
1056
+
1057
+ ``path`` is treated as a stem: an extension already naming one of ``formats``
1058
+ is replaced, so ``"pattern.png"`` and ``"pattern"`` behave the same. Other
1059
+ dots are kept, which matters for names like ``"x0.10_calcined"``.
1060
+ """
1061
+ path = Path(path)
1062
+ known = {fmt.lower().lstrip(".") for fmt in formats}
1063
+ stem = path.with_suffix("") if path.suffix.lower().lstrip(".") in known else path
1064
+ stem.parent.mkdir(parents=True, exist_ok=True)
1065
+
1066
+ written: list[Path] = []
1067
+ for fmt in formats:
1068
+ suffix = fmt.lower().lstrip(".")
1069
+ out = stem.parent / f"{stem.name}.{suffix}"
1070
+ fig.savefig(out, format=suffix, dpi=dpi)
1071
+ written.append(out)
1072
+ return written