"""
stacked_xrd.py — publication-ready stacked XRD patterns with Matplotlib.

Hu Lab · https://hulab.pages.dev/en/guides/stacked-xrd-plot-python/
Free to use and modify. Requires: numpy, matplotlib (scipy optional, for smoothing).

Edit the SETTINGS block, then run:  python stacked_xrd.py
"""
import math
import re
import numpy as np
import matplotlib.pyplot as plt

# ============================ SETTINGS =====================================
SAMPLES = [                      # (file, label) — first one is drawn at the bottom
    ("S200.txt", "200 °C"),
    ("S250.txt", "250 °C"),
    ("S300.txt", "300 °C"),
]
TWO_THETA = (25, 85)             # plotted range (degrees)
NORMALIZE = "max"                # "max" (strongest peak = 1) or "none"
SMOOTH = 0                       # Savitzky–Golay window (odd number, e.g. 11); 0 = off
SPACING = 1.1                    # vertical gap between patterns (in normalised units)
COLORS = ["#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00"]

# Reference phase: lattice parameter (Å), reflections and relative intensities.
# Intensities are NOT predicted by Bragg's law — take them from your card / CIF.
REF_NAME = "Cu (fcc)"
REF_A = 3.615
REF_PEAKS = {(1, 1, 1): 100, (2, 0, 0): 46, (2, 2, 0): 20, (3, 1, 1): 17}
WAVELENGTH = 1.5406              # Cu Kα1 (Å)

INSET = (42.0, 44.5)             # zoom window for a peak-shift inset, or None
FIG_SIZE_MM = (90, 85)           # Elsevier single column = 90 mm wide
DPI = 600                        # 600 for most journals; 1000 for Elsevier line art
OUTPUT = "xrd_stacked"           # writes .tiff, .png and .svg
# ===========================================================================


def load_xrd(path):
    """Return 2θ, intensity from a text/CSV export, skipping header lines.

    Handles comma, tab, semicolon and space separators, and decimal commas
    (e.g. '43,316;1520' from European-locale software).
    """
    rows = []
    with open(path, encoding="utf-8", errors="ignore") as f:
        for line in f:
            s = line.strip()
            if ";" in s or "\t" in s:              # decimal commas are only safe here
                s = re.sub(r"(\d),(\d)", r"\1.\2", s)
            parts = re.split(r"[,;\s]+", s)
            try:
                rows.append([float(parts[0]), float(parts[1])])
            except (ValueError, IndexError):
                continue                           # header, units or comment line
    if not rows:
        raise ValueError(f"No numeric data in {path}. Is it a binary file (.raw/.brml)? "
                         "Export it as .xy/.txt from the instrument software first.")
    data = np.array(rows)
    order = np.argsort(data[:, 0])
    return data[order, 0], data[order, 1]


def bragg_2theta(a, hkl, wavelength=WAVELENGTH):
    """2θ (degrees) of a cubic (hkl) reflection; None if it is not reachable."""
    d = a / math.sqrt(sum(i * i for i in hkl))
    s = wavelength / (2 * d)
    return 2 * math.degrees(math.asin(s)) if s <= 1 else None


def prepare(x, y):
    m = (x >= TWO_THETA[0]) & (x <= TWO_THETA[1])
    x, y = x[m], y[m].astype(float)
    if SMOOTH:
        from scipy.signal import savgol_filter
        y = savgol_filter(y, SMOOTH, 3)
    y = y - y.min()                                # put the baseline at zero
    if NORMALIZE == "max":
        y = y / y.max()
    return x, y


plt.rcParams.update({
    "font.family": ["Arial", "DejaVu Sans"], "font.size": 8, "axes.linewidth": 0.6,
    "xtick.direction": "in", "ytick.direction": "in", "xtick.top": True,
    "svg.fonttype": "none",
})
MM = 1 / 25.4
# constrained layout keeps the saved file exactly FIG_SIZE_MM wide (bbox_inches="tight"
# would crop it narrower, lowering the effective dpi when the journal scales it up)
fig, ax = plt.subplots(figsize=(FIG_SIZE_MM[0] * MM, FIG_SIZE_MM[1] * MM), layout="constrained")

# reference sticks at the bottom
ref_pos = {hkl: bragg_2theta(REF_A, hkl) for hkl in REF_PEAKS}
ref_pos = {k: v for k, v in ref_pos.items() if v and TWO_THETA[0] < v < TWO_THETA[1]}
for hkl, pos in ref_pos.items():
    ax.vlines(pos, 0, 0.5 * REF_PEAKS[hkl] / 100, color="0.3", lw=0.9)
ax.text(TWO_THETA[1] - 1, 0.3, REF_NAME, ha="right", color="0.3", fontsize=7)

patterns = []
for i, (fname, label) in enumerate(SAMPLES):
    x, y = prepare(*load_xrd(fname))
    offset = 0.7 + i * SPACING
    color = COLORS[i % len(COLORS)]
    ax.plot(x, y + offset, color=color, lw=1)
    ax.text(TWO_THETA[1] - 1, offset + 0.12, label, color=color, ha="right", fontsize=7.5)
    patterns.append((x, y, offset, color, label))

# (hkl) labels above the measured peaks of the top pattern
x, y, top, color, _ = patterns[-1]
for hkl, pos in ref_pos.items():
    window = (x > pos - 0.3) & (x < pos + 0.3)
    if window.any():
        ax.text(pos, top + y[window].max() + 0.04, "(%d%d%d)" % hkl, rotation=90,
                ha="center", va="bottom", fontsize=6.5, color=color)

ax.set_xlim(*TWO_THETA)
ax.set_ylim(-0.05, top + 1.55)
ax.set_yticks([])
ax.set_xlabel("2θ (degree)")
ax.set_ylabel("Intensity (a.u.)" if NORMALIZE != "none" else "Intensity (counts)")

# optional inset: overlay (not stacked) to show a peak shift clearly
if INSET:
    ins = ax.inset_axes([0.50, 0.76, 0.25, 0.20])   # empty area above the top pattern
    for x, y, _, color, _ in patterns:
        m = (x >= INSET[0]) & (x <= INSET[1])
        ins.plot(x[m], y[m] / y[m].max(), color=color, lw=0.8)
    ins.set_xlim(*INSET)
    ins.set_yticks([])
    ins.tick_params(labelsize=6, length=2)
    ins.tick_params(top=False)
    ins.text(0.04, 0.9, "zoom", transform=ins.transAxes, fontsize=6, va="top")

fig.savefig(f"{OUTPUT}.png", dpi=DPI, facecolor="white")
fig.savefig(f"{OUTPUT}.svg", facecolor="white")
# TIFF: RGB without transparency, LZW-compressed, with the dpi tag — what submission systems expect
from PIL import Image
Image.open(f"{OUTPUT}.png").convert("RGB").save(f"{OUTPUT}.tiff", compression="tiff_lzw", dpi=(DPI, DPI))
print(f"Saved {OUTPUT}.tiff / .png / .svg")
