plotting

nrxrdct.laue.laue_plotting

plot_2theta_chi

plot_2theta_chi(spots_bcc, spots_b2, E_MIN_eV=5000, E_MAX_eV=27000, out_path='laue_2theta_chi.png')

Plot Laue patterns in angular space: two representations side-by-side for each phase (BCC and B2):

Left column – 2θ vs χ scatter plot (LaueTools .cor file convention) Right column – Gnomonic projection (gX, gY) Straight lines = crystallographic zone axes Unit circle = 2θ = 90°

Spots are coloured by photon energy and sized by normalised intensity. Fundamental reflections: circles (○). B2 superlattice reflections: stars (★) in orange.

Parameters:
  • spots_bcc, spots_b2 (lists of spot dicts from simulate_laue()) –
  • out_path (output PNG path, default: 'laue_2theta_chi.png' ) –
Source code in src/nrxrdct/laue/laue_plotting.py
def plot_2theta_chi(
    spots_bcc, spots_b2, E_MIN_eV=5_000, E_MAX_eV=27_000, out_path="laue_2theta_chi.png"
):
    """
    Plot Laue patterns in angular space: two representations side-by-side
    for each phase (BCC and B2):

    Left column  – 2θ vs χ scatter plot  (LaueTools .cor file convention)
    Right column – Gnomonic projection   (gX, gY)
                   Straight lines = crystallographic zone axes
                   Unit circle = 2θ = 90°

    Spots are coloured by photon energy and sized by normalised intensity.
    Fundamental reflections: circles (○).
    B2 superlattice reflections: stars (★) in orange.

    Args:
        spots_bcc, spots_b2 (lists of spot dicts from simulate_laue()):
        out_path (output PNG path):
"""
    import matplotlib.colors as mcolors
    import matplotlib.gridspec as mgridspec
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D

    BG = "#080c14"
    FG = "#ccccee"
    COL_FUND = "#4fc3f7"
    COL_SUPER = "#ff6633"

    all_E = [s["E"] for s in spots_bcc + spots_b2]
    E_norm = mcolors.Normalize(vmin=E_MIN_eV / 1e3, vmax=E_MAX_eV / 1e3)
    cmap = "plasma"

    fig = plt.figure(figsize=(18, 12))
    fig.patch.set_facecolor(BG)

    gs = mgridspec.GridSpec(
        2,
        3,
        width_ratios=[1, 1, 0.06],
        height_ratios=[1, 1],
        hspace=0.38,
        wspace=0.28,
        left=0.07,
        right=0.93,
        top=0.92,
        bottom=0.07,
    )

    ax_bcc_ang = fig.add_subplot(gs[0, 0])
    ax_bcc_gno = fig.add_subplot(gs[0, 1])
    ax_b2_ang = fig.add_subplot(gs[1, 0])
    ax_b2_gno = fig.add_subplot(gs[1, 1])
    ax_cb = fig.add_subplot(gs[:, 2])

    # ── helper: 2theta vs chi scatter ────────────────────────────────────────
    def draw_tth_chi(ax, spots, title):
        _style_angular_ax(ax, title)
        ax.set_ylabel("χ  (degrees)", color="#7788aa", fontsize=8)
        ax.set_xlabel("2θ  (degrees)", color="#7788aa", fontsize=8)
        ax.axvline(0, color="#252b40", lw=0.8)

        fund = [s for s in spots if not s.get("is_superlattice", False)]
        super_ = [s for s in spots if s.get("is_superlattice", False)]

        for subset, mk, ec in [(fund, "o", COL_FUND), (super_, "*", COL_SUPER)]:
            if not subset:
                continue
            chis = [s["chi"] for s in subset]
            tths = [s["tth"] for s in subset]
            Es = [s["E"] / 1e3 for s in subset]
            sz = [max(4, 80 * s["intensity"] ** 0.4) for s in subset]
            ax.scatter(
                tths,
                chis,
                s=sz,
                c=Es,
                cmap=cmap,
                norm=E_norm,
                alpha=0.80,
                edgecolors=ec,
                linewidths=0.35,
                marker=mk,
                zorder=3,
            )

        # Label 8 strongest fundamental spots
        for s in sorted(fund, key=lambda x: -x["intensity"])[:8]:
            h, k, l = s["hkl"]
            ax.annotate(
                f"({h}{k}{l})",
                xy=(s["tth"], s["chi"]),
                xytext=(3, 2),
                textcoords="offset points",
                fontsize=5.5,
                color="#aaccff",
                alpha=0.9,
            )

        # Label 4 strongest superlattice spots
        for s in sorted(super_, key=lambda x: -x["intensity"])[:4]:
            h, k, l = s["hkl"]
            ax.annotate(
                f"({h}{k}{l})",
                xy=(s["tth"], s["chi"]),
                xytext=(3, 2),
                textcoords="offset points",
                fontsize=5.5,
                color=COL_SUPER,
                alpha=0.9,
            )

        # Draw 2theta reference lines
        all_tths = [s["tth"] for s in spots]
        tth_min = max(0, min(all_tths) - 5) if all_tths else 60
        tth_max = min(180, max(all_tths) + 5) if all_tths else 130
        all_chis = [s["chi"] for s in spots]
        chi_min = min(all_chis) - 5 if all_chis else -50
        chi_max = max(all_chis) + 5 if all_chis else 50

        for tth_ref in np.arange(round(tth_min / 10) * 10, tth_max + 1, 10):
            ax.axvline(tth_ref, color="#1a2a3a", lw=0.6, ls="--", alpha=0.7, zorder=1)
            ax.text(
                tth_ref,
                chi_max + 0.5,
                f"{tth_ref:.0f}°",
                color="#445566",
                fontsize=6,
                ha="center",
            )

        ax.set_ylim(chi_min, chi_max)
        ax.set_xlim(tth_min, tth_max)

    # ── helper: gnomonic projection ───────────────────────────────────────────
    def draw_gnomonic(ax, spots, title):
        _style_angular_ax(ax, title)
        ax.set_xlabel("gX  =  −sin2θ·sinχ / (1+cos2θ)", color="#7788aa", fontsize=7)
        ax.set_ylabel("gY  =   sin2θ·cosχ / (1+cos2θ)", color="#7788aa", fontsize=7)
        ax.set_aspect("equal")

        fund = [s for s in spots if not s.get("is_superlattice", False)]
        super_ = [s for s in spots if s.get("is_superlattice", False)]

        for subset, mk, ec in [(fund, "o", COL_FUND), (super_, "*", COL_SUPER)]:
            if not subset:
                continue
            gXs = [_gnomonic(s["tth"], s["chi"])[0] for s in subset]
            gYs = [_gnomonic(s["tth"], s["chi"])[1] for s in subset]
            Es = [s["E"] / 1e3 for s in subset]
            sz = [max(4, 80 * s["intensity"] ** 0.4) for s in subset]
            ax.scatter(
                gXs,
                gYs,
                s=sz,
                c=Es,
                cmap=cmap,
                norm=E_norm,
                alpha=0.80,
                edgecolors=ec,
                linewidths=0.35,
                marker=mk,
                zorder=3,
            )

        # Label strongest fundamental spots
        for s in sorted(fund, key=lambda x: -x["intensity"])[:8]:
            h, k, l = s["hkl"]
            gx, gy = _gnomonic(s["tth"], s["chi"])
            ax.annotate(
                f"({h}{k}{l})",
                xy=(gx, gy),
                xytext=(3, 2),
                textcoords="offset points",
                fontsize=5.5,
                color="#aaccff",
                alpha=0.9,
            )

        for s in sorted(super_, key=lambda x: -x["intensity"])[:4]:
            h, k, l = s["hkl"]
            gx, gy = _gnomonic(s["tth"], s["chi"])
            ax.annotate(
                f"({h}{k}{l})",
                xy=(gx, gy),
                xytext=(3, 2),
                textcoords="offset points",
                fontsize=5.5,
                color=COL_SUPER,
                alpha=0.9,
            )

        # Reference circles: 2theta = 60, 70, 80, 90, 100, 110, 120 deg
        theta_circ = np.linspace(0, 2 * np.pi, 360)
        for tth_ref in range(60, 131, 10):
            gXc, gYc = _gnomonic(np.full(360, tth_ref), np.degrees(theta_circ))
            # Only draw arc where spots exist
            valid = np.isfinite(gXc) & np.isfinite(gYc)
            if valid.any():
                col = "#ffffaa" if tth_ref == 90 else "#1a2a3a"
                lw = 0.9 if tth_ref == 90 else 0.5
                ax.plot(
                    gXc[valid],
                    gYc[valid],
                    color=col,
                    lw=lw,
                    ls="--",
                    alpha=0.7,
                    zorder=1,
                )
                # Label
                ax.text(
                    0,
                    _gnomonic(tth_ref, 0)[1] + 0.02,
                    f"{tth_ref}°",
                    color="#445566" if tth_ref != 90 else "#ffffaa",
                    fontsize=5.5,
                    ha="center",
                    va="bottom",
                )

        # Chi reference lines (radial lines at chi = 0, ±30, ±60, ±90 deg)
        for chi_ref in [0, 30, -30, 60, -60, 90, -90]:
            # Draw radial line from origin
            r_max = 3.0
            gx_r = r_max * (-np.sin(np.radians(chi_ref)))  # at 2theta=90 gX = -sin(chi)
            gy_r = r_max * np.cos(np.radians(chi_ref))
            ax.plot(
                [0, gx_r],
                [0, gy_r],
                color="#1a2a3a",
                lw=0.5,
                ls=":",
                alpha=0.6,
                zorder=1,
            )
            if abs(chi_ref) <= 90:
                ax.text(
                    gx_r * 0.9,
                    gy_r * 0.9,
                    f"χ={chi_ref}°",
                    color="#334455",
                    fontsize=5.5,
                    ha="center",
                    va="center",
                )

        # Origin crosshair (forward beam)
        ax.plot(0, 0, "+", color="#ffffaa", ms=8, mew=1.2, zorder=6)

        # Auto-scale with margin
        all_gx = [_gnomonic(s["tth"], s["chi"])[0] for s in spots]
        all_gy = [_gnomonic(s["tth"], s["chi"])[1] for s in spots]
        all_gx = [v for v in all_gx if np.isfinite(v)]
        all_gy = [v for v in all_gy if np.isfinite(v)]
        if all_gx and all_gy:
            margin = 0.3
            xmin, xmax = min(all_gx) - margin, max(all_gx) + margin
            ymin, ymax = min(all_gy) - margin, max(all_gy) + margin
            # Keep square
            r = max(abs(xmin), abs(xmax), abs(ymin), abs(ymax)) + margin
            ax.set_xlim(-r, r)
            ax.set_ylim(-r, r)

    # ── Draw all four panels ──────────────────────────────────────────────────
    n_super = sum(1 for s in spots_b2 if s.get("is_superlattice", False))

    draw_tth_chi(
        ax_bcc_ang, spots_bcc, f"BCC  Im-3m   –   2θ vs χ   ({len(spots_bcc)} spots)"
    )
    draw_gnomonic(ax_bcc_gno, spots_bcc, f"BCC  Im-3m   –   Gnomonic projection")
    draw_b2_title = (
        f"B2   Pm-3m   –   2θ vs χ   "
        f"({len(spots_b2)} spots, {n_super} superlattice)"
    )
    draw_tth_chi(ax_b2_ang, spots_b2, draw_b2_title)
    draw_gnomonic(ax_b2_gno, spots_b2, f"B2   Pm-3m   –   Gnomonic projection")

    # ── Shared legend ─────────────────────────────────────────────────────────
    leg = [
        Line2D(
            [0],
            [0],
            marker="o",
            lw=0,
            mfc=COL_FUND,
            mec=COL_FUND,
            ms=7,
            label="Fundamental (BCC & B2)",
        ),
        Line2D(
            [0],
            [0],
            marker="*",
            lw=0,
            mfc=COL_SUPER,
            mec=COL_SUPER,
            ms=9,
            label="B2 superlattice  (h+k+l odd)",
        ),
        Line2D(
            [0],
            [0],
            color="#ffffaa",
            lw=1,
            ls="--",
            label="2θ = 90°  (gnomonic unit circle)",
        ),
    ]
    fig.legend(
        handles=leg,
        loc="upper center",
        ncol=3,
        fontsize=8,
        framealpha=0.25,
        facecolor=BG,
        labelcolor="white",
        bbox_to_anchor=(0.5, 0.97),
    )

    # ── Colourbar ─────────────────────────────────────────────────────────────
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=E_norm)
    sm.set_array([])
    cb = fig.colorbar(sm, cax=ax_cb)
    cb.set_label("E  (keV)", color="#8899aa", fontsize=8)
    cb.ax.yaxis.set_tick_params(color="#8899aa", labelsize=7)
    plt.setp(cb.ax.yaxis.get_ticklabels(), color="#8899aa")

    # ── Title ─────────────────────────────────────────────────────────────────
    fig.text(
        0.5,
        0.995,
        "Laue pattern  –  AlCoCrFeNi  –  angular coordinates  "
        "(LaueTools convention: beam ∥ y,  χ = arctan(−uf_x / uf_z))",
        ha="center",
        va="top",
        fontsize=11,
        color="white",
        fontweight="bold",
    )

    plt.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
    print(f"  Angular plot saved -> {out_path}")
    return out_path

plot_compare_spots

plot_compare_spots(spots_a, spots_b, *, space: str = 'angles', label_a: str = 'Set A', label_b: str = 'Set B', E_MIN_eV: float = 5000, E_MAX_eV: float = 27000, n_label: int = 8, out_path: str | None = 'compare_spots.png')

Overlay two spot tables on a single axes for direct comparison.

Parameters:
  • spots_a, spots_b (list of dict) –

    Spot dicts from :func:~nrxrdct.laue.simulation.simulate_laue or compatible sources. Each dict must contain:

  • space (`'angles'` | `'detector'`, default: 'angles' ) –

    'angles' – x-axis = 2θ (degrees), y-axis = χ (degrees). 'detector' – x-axis = column pixel, y-axis = row pixel.

  • label_a, label_b (str) –

    Legend labels for the two spot sets.

  • E_MIN_eV, E_MAX_eV (float) –

    Energy range for the shared colour-map.

  • n_label (int, default: 8 ) –

    Number of strongest spots in each set to annotate with (hkl).

  • out_path (str or None, default: 'compare_spots.png' ) –

    File path for the saved PNG. None → do not save.

Returns:
  • fig( Figure ) –
Source code in src/nrxrdct/laue/laue_plotting.py
def plot_compare_spots(
    spots_a,
    spots_b,
    *,
    space: str = "angles",
    label_a: str = "Set A",
    label_b: str = "Set B",
    E_MIN_eV: float = 5_000,
    E_MAX_eV: float = 27_000,
    n_label: int = 8,
    out_path: str | None = "compare_spots.png",
):
    """
    Overlay two spot tables on a single axes for direct comparison.

    Args:
        spots_a, spots_b (list of dict): Spot dicts from :func:`~nrxrdct.laue.simulation.simulate_laue` or
            compatible sources.  Each dict must contain:

        * `'tth'`         – 2θ in degrees
        * `'chi'`         – χ in degrees
        * `'pix'`         – `(col, row)` pixel coordinate on the detector
        * `'E'`           – photon energy in eV
        * `'hkl'`         – Miller indices tuple `(h, k, l)`
        * `'intensity'`   – normalised intensity [0, 1]
        * `'is_superlattice'` – bool

        space (`'angles'` | `'detector'`): `'angles'`   – x-axis = 2θ (degrees), y-axis = χ (degrees).
            `'detector'` – x-axis = column pixel,  y-axis = row pixel.

        label_a, label_b (str): Legend labels for the two spot sets.

        E_MIN_eV, E_MAX_eV (float): Energy range for the shared colour-map.

        n_label (int): Number of strongest spots in each set to annotate with (hkl).

        out_path (str or None): File path for the saved PNG.  `None` → do not save.

    Returns:
        fig (matplotlib.figure.Figure):
"""
    if space not in ("angles", "detector"):
        raise ValueError(f"space must be 'angles' or 'detector', got {space!r}")

    # ── colour maps: Set A = cool blues, Set B = warm oranges ────────────────
    CMAP_A = "Blues"
    CMAP_B = "Oranges"
    E_norm = mcolors.Normalize(vmin=E_MIN_eV / 1e3, vmax=E_MAX_eV / 1e3)

    fig, ax = plt.subplots(figsize=(9, 7))
    fig.patch.set_facecolor(BG)
    ax.set_facecolor(BG)
    ax.tick_params(colors="#7788aa", labelsize=7)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")

    def _xy(s):
        if space == "angles":
            return s["tth"], s["chi"]
        else:
            pix = s.get("pix")
            if pix is None:
                return None, None
            return float(pix[0]), float(pix[1])

    def _draw(spots, cmap, marker):
        valid = [s for s in spots if _xy(s)[0] is not None]
        if not valid:
            return

        fund = [s for s in valid if not s.get("is_superlattice")]
        super_ = [s for s in valid if s.get("is_superlattice")]

        for subset, mk, alpha in [(fund, marker, 0.85), (super_, "*", 0.75)]:
            if not subset:
                continue
            xs = [_xy(s)[0] for s in subset]
            ys = [_xy(s)[1] for s in subset]
            Es = [s["E"] / 1e3 for s in subset]
            sz = [max(5, 90 * s["intensity"] ** 0.4) for s in subset]
            ax.scatter(
                xs, ys,
                s=sz,
                c=Es,
                cmap=cmap,
                norm=E_norm,
                alpha=alpha,
                marker=mk,
                linewidths=0.4,
                zorder=3,
            )

        # Annotate n_label strongest fundamental spots
        top = sorted(fund, key=lambda s: -s["intensity"])[:n_label]
        for s in top:
            h, k, l = s["hkl"]
            x, y = _xy(s)
            ax.annotate(
                f"({h}{k}{l})",
                xy=(x, y),
                xytext=(3, 2),
                textcoords="offset points",
                fontsize=5.5,
                color="#aaddff",
                alpha=0.9,
            )

    _draw(spots_a, CMAP_A, "o")
    _draw(spots_b, CMAP_B, "D")

    # ── colour bars ───────────────────────────────────────────────────────────
    sm_a = plt.cm.ScalarMappable(cmap=CMAP_A, norm=E_norm)
    sm_b = plt.cm.ScalarMappable(cmap=CMAP_B, norm=E_norm)
    sm_a.set_array([])
    sm_b.set_array([])
    cb_a = fig.colorbar(sm_a, ax=ax, pad=0.01, fraction=0.035, aspect=30)
    cb_b = fig.colorbar(sm_b, ax=ax, pad=0.08, fraction=0.035, aspect=30)
    for cb, lbl in [(cb_a, label_a), (cb_b, label_b)]:
        cb.set_label(f"E  (keV)  [{lbl}]", color="#7788aa", fontsize=7)
        cb.ax.tick_params(colors="#7788aa", labelsize=6)
        cb.outline.set_edgecolor("#1a1f2e")

    # ── legend ────────────────────────────────────────────────────────────────
    legend_elements = [
        Line2D([0], [0], marker="o", color="w", markerfacecolor="#5bc8f5",
               markersize=7, label=f"{label_a} – fundamental", linewidth=0),
        Line2D([0], [0], marker="*", color="w", markerfacecolor="#5bc8f5",
               markersize=9, label=f"{label_a} – superlattice", linewidth=0),
        Line2D([0], [0], marker="D", color="w", markerfacecolor="#f5a845",
               markersize=7, label=f"{label_b} – fundamental", linewidth=0),
        Line2D([0], [0], marker="*", color="w", markerfacecolor="#f5a845",
               markersize=9, label=f"{label_b} – superlattice", linewidth=0),
    ]
    ax.legend(
        handles=legend_elements,
        facecolor="#0d1220",
        edgecolor="#333355",
        labelcolor=FG,
        fontsize=7,
        loc="upper right",
    )

    # ── axis labels & title ───────────────────────────────────────────────────
    if space == "angles":
        ax.set_xlabel("2θ  (degrees)", color="#7788aa", fontsize=9)
        ax.set_ylabel("χ  (degrees)", color="#7788aa", fontsize=9)
        title = f"Laue spot comparison — angular space ({label_a} vs {label_b})"
    else:
        ax.set_xlabel("Column  (pixel)", color="#7788aa", fontsize=9)
        ax.set_ylabel("Row  (pixel)", color="#7788aa", fontsize=9)
        ax.invert_yaxis()   # detector rows increase downward
        title = f"Laue spot comparison — detector space ({label_a} vs {label_b})"

    ax.set_title(title, color=FG, fontsize=10, pad=8)
    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Compare-spots plot saved → {out_path}")

plot_crystals_in_lab

plot_crystals_in_lab(crystals: list, U: ndarray | list[ndarray], hkl: tuple[int, int, int] | list[tuple[int, int, int]] = (1, 1, 1), *, camera: Camera | None = None, plane_offset: int | list[int | None] | None = None, show_normal: bool = True, show_crystal_axes: bool = False, show_lab_axes: bool = True, show_beam: bool = True, show_scattered_rays: bool = True, crystal_colors: str | list[str] | None = None, beam_color: str = 'red', elev: float = 0.0, azim: float = -90.0, figsize: tuple[float, float] = (12, 9), out_path: str | None = None)

Multi-crystal version of :func:plot_unit_cell_in_lab: draws each crystal's unit cell (with one hkl plane cut through it) in the lab frame, one colour per crystal, all anchored at the same lab-frame origin -- as if several grains occupied the same sample position with different orientations, matching how :func:plot_multigrain overlays multiple grains without a spatial offset. The right panel is a shared scattering diagram, exactly as in plot_unit_cell_in_lab, with one normal + one diffracted ray per crystal colour-matched to its cell.

Parameters:
  • crystals (list) –

    List of xrayutilities-compatible crystal objects (see plot_unit_cell).

  • U (ndarray | list[ndarray]) –

    A single (3, 3) orientation matrix applied to every crystal, or a list of one matrix per crystal.

  • hkl (tuple[int, int, int] | list[tuple[int, int, int]], default: (1, 1, 1) ) –

    A single (h, k, l) applied to every crystal, or a list of one (h, k, l) per crystal (one plane per crystal -- for several planes on the same crystal use plot_unit_cell_in_lab instead, whose hkl accepts a list).

  • camera (Camera | None, default: None ) –

    Optional :class:~nrxrdct.laue.camera.Camera; when given, each diffracted ray is labelled with its projected pixel and drawn to true detector scale, as in plot_unit_cell_in_lab.

  • plane_offset (int | list[int | None] | None, default: None ) –

    Override the automatic first-plane choice (see plot_unit_cell); a single value applied to every crystal, or a list matching crystals one-to-one.

  • show_normal (bool, default: True ) –

    Draw each crystal's plane normal in the right panel.

  • show_crystal_axes (bool, default: False ) –

    Draw labelled a, b, c arrows per crystal in the left panel. Off by default here (unlike plot_unit_cell_in_lab) since with several crystals sharing the origin the labels overlap badly.

  • show_lab_axes (bool, default: True ) –

    Draw the fixed lab-frame x/y/z triad in both panels.

  • show_beam (bool, default: True ) –

    Draw the single incident-beam arrow in the right panel.

  • show_scattered_rays (bool, default: True ) –

    Draw each crystal's diffracted-ray direction (dashed, to distinguish it from the solid normal vectors) in the right panel.

  • crystal_colors (str | list[str] | None, default: None ) –

    Fill/line colour(s) for the cells and their matching normal/ray -- a single colour applied to all, a list matching crystals one-to-one, or None to cycle through the project's standard grain palette.

  • beam_color (str, default: 'red' ) –

    Line colour for the incident beam.

  • elev, azim –

    3-D view angle (degrees), shared by both panels. Defaults to a view looking down +y (elev=0, azim=-90).

  • figsize (tuple[float, float], default: (12, 9) ) –

    Figure size in inches.

  • out_path (str | None, default: None ) –

    Save path; None → do not save.

Returns:
  • –

    (fig, (ax_cell, ax_scatter))

Example:

U0 = orientation_along_z(substrate, [0, 0, 1], [1, 0, 0]) U1 = rotate_U_about_axis(U0, 30.0, axis="z") # a twin/second grain plot_crystals_in_lab([substrate, film], [U0, U1], hkl=(0, 0, 1))

Source code in src/nrxrdct/laue/laue_plotting.py
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
def plot_crystals_in_lab(
    crystals: "list",
    U: "np.ndarray | list[np.ndarray]",
    hkl: "tuple[int, int, int] | list[tuple[int, int, int]]" = (1, 1, 1),
    *,
    camera: "Camera | None" = None,
    plane_offset: "int | list[int | None] | None" = None,
    show_normal: bool = True,
    show_crystal_axes: bool = False,
    show_lab_axes: bool = True,
    show_beam: bool = True,
    show_scattered_rays: bool = True,
    crystal_colors: "str | list[str] | None" = None,
    beam_color: str = "red",
    elev: float = 0.0,
    azim: float = -90.0,
    figsize: "tuple[float, float]" = (12, 9),
    out_path: "str | None" = None,
):
    """
    Multi-crystal version of :func:`plot_unit_cell_in_lab`: draws each
    crystal's unit cell (with one `hkl` plane cut through it) in the lab
    frame, one colour per crystal, all anchored at the same lab-frame
    origin -- as if several grains occupied the same sample position with
    different orientations, matching how :func:`plot_multigrain` overlays
    multiple grains without a spatial offset. The right panel is a shared
    scattering diagram, exactly as in `plot_unit_cell_in_lab`, with one
    normal + one diffracted ray per crystal colour-matched to its cell.

    Args:
        crystals: List of xrayutilities-compatible crystal objects (see
            `plot_unit_cell`).
        U: A single `(3, 3)` orientation matrix applied to every crystal,
            or a list of one matrix per crystal.
        hkl: A single `(h, k, l)` applied to every crystal, or a list of
            one `(h, k, l)` per crystal (one plane per crystal -- for
            several planes on the *same* crystal use `plot_unit_cell_in_lab`
            instead, whose `hkl` accepts a list).
        camera: Optional :class:`~nrxrdct.laue.camera.Camera`; when given,
            each diffracted ray is labelled with its projected pixel and
            drawn to true detector scale, as in `plot_unit_cell_in_lab`.
        plane_offset: Override the automatic first-plane choice (see
            `plot_unit_cell`); a single value applied to every crystal, or
            a list matching `crystals` one-to-one.
        show_normal: Draw each crystal's plane normal in the right panel.
        show_crystal_axes: Draw labelled `a`, `b`, `c` arrows per crystal
            in the left panel. Off by default here (unlike
            `plot_unit_cell_in_lab`) since with several crystals sharing
            the origin the labels overlap badly.
        show_lab_axes: Draw the fixed lab-frame x/y/z triad in both panels.
        show_beam: Draw the single incident-beam arrow in the right panel.
        show_scattered_rays: Draw each crystal's diffracted-ray direction
            (dashed, to distinguish it from the solid normal vectors) in
            the right panel.
        crystal_colors: Fill/line colour(s) for the cells and their
            matching normal/ray -- a single colour applied to all, a list
            matching `crystals` one-to-one, or `None` to cycle through the
            project's standard grain palette.
        beam_color: Line colour for the incident beam.
        elev, azim: 3-D view angle (degrees), shared by both panels.
            Defaults to a view looking down +y (elev=0, azim=-90).
        figsize: Figure size in inches.
        out_path: Save path; `None` → do not save.

    Returns:
        `(fig, (ax_cell, ax_scatter))`

    Example:
    >>> U0 = orientation_along_z(substrate, [0, 0, 1], [1, 0, 0])
    >>> U1 = rotate_U_about_axis(U0, 30.0, axis="z")   # a twin/second grain
    >>> plot_crystals_in_lab([substrate, film], [U0, U1], hkl=(0, 0, 1))
    """
    from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 — registers '3d' projection
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection

    n_crys = len(crystals)
    if n_crys == 0:
        raise ValueError("crystals must contain at least one crystal")

    U_arr = np.asarray(U, dtype=float)
    if U_arr.shape == (3, 3):
        Us = [U_arr] * n_crys
    elif U_arr.shape == (n_crys, 3, 3):
        Us = [U_arr[i] for i in range(n_crys)]
    else:
        raise ValueError(
            f"U must be a single (3, 3) matrix (applied to every crystal) or "
            f"a list of {n_crys} (3, 3) matrices, one per crystal; got shape "
            f"{U_arr.shape}"
        )

    hkls = _normalize_hkl_list(hkl)
    if len(hkls) == 1:
        hkls = hkls * n_crys
    elif len(hkls) != n_crys:
        raise ValueError(
            "hkl list must be a single (h, k, l) applied to every crystal, "
            "or match the number of crystals one-to-one"
        )
    if any(h == 0 and k == 0 and l == 0 for h, k, l in hkls):
        raise ValueError("hkl=(0, 0, 0) does not define a plane")

    offsets = plane_offset if isinstance(plane_offset, (list, tuple)) else [plane_offset] * n_crys
    if len(offsets) != n_crys:
        raise ValueError("plane_offset list must match the number of crystals")
    if crystal_colors is None:
        colors = [_GRAIN_COLORS[i % len(_GRAIN_COLORS)] for i in range(n_crys)]
    elif isinstance(crystal_colors, str):
        colors = [crystal_colors] * n_crys
    else:
        colors = list(crystal_colors)
        if len(colors) != n_crys:
            raise ValueError("crystal_colors list must match the number of crystals")

    names = [getattr(c, "name", None) or f"crystal {i}" for i, c in enumerate(crystals)]

    edges = [
        (i, j)
        for i in range(8)
        for j in range(i + 1, 8)
        if np.sum(_CELL_CORNERS_FRAC[i] != _CELL_CORNERS_FRAC[j]) == 1
    ]

    fig = plt.figure(figsize=figsize)
    fig.patch.set_facecolor(BG)
    ax_cell = fig.add_subplot(1, 2, 1, projection="3d")
    ax_scat = fig.add_subplot(1, 2, 2, projection="3d")
    for ax in (ax_cell, ax_scat):
        ax.set_facecolor(BG)
        for pane in (ax.xaxis, ax.yaxis, ax.zaxis):
            pane.set_pane_color((0.03, 0.05, 0.08, 1.0))
            pane._axinfo["grid"]["color"] = (0.1, 0.12, 0.18, 0.6)
        ax.tick_params(colors="#7788aa", labelsize=7)
        ax.view_init(elev=elev, azim=azim)   # shared initial view: same orientation reads on both panels
    _sync_3d_views(fig, ax_cell, ax_scat)   # keep them synced if the user drag-rotates either one

    # ── Left panel: one unit cell + plane per crystal, all anchored at the
    #    shared lab-frame origin ────────────────────────────────────────────
    cell_legend = []
    G_labs = []          # one entry per crystal, aligned with crystals/colors
    all_corners = []     # every crystal's cell corners, for the combined axis span
    for crystal, U_i, (h, k, l), user_offset, crystal_color, name in zip(
        crystals, Us, hkls, offsets, colors, names
    ):
        ai_cry = np.array([crystal.a1, crystal.a2, crystal.a3], dtype=float)
        ai = ai_cry @ U_i.T   # rows a1,a2,a3 rotated into the lab frame
        cart_corners = _CELL_CORNERS_FRAC @ ai
        all_corners.append(cart_corners)

        G_lab = U_i @ crystal.Q(h, k, l)
        G_labs.append(G_lab)

        for i, j in edges:
            p, q = cart_corners[i], cart_corners[j]
            ax_cell.plot(*zip(p, q), color=crystal_color, lw=1.2, alpha=0.6)
        ax_cell.scatter(*cart_corners.T, color=crystal_color, s=12, alpha=0.8)

        if show_crystal_axes:
            for vec, label in zip(ai, ("a", "b", "c")):
                ax_cell.quiver(0, 0, 0, *vec, color=crystal_color, linewidth=1.0,
                                arrow_length_ratio=0.08, alpha=0.9)
                ax_cell.text(*(vec * 1.08), label, color=crystal_color, fontsize=10)

        if user_offset is not None:
            offsets_to_try = [user_offset]
        else:
            f_max = max(h, 0) + max(k, 0) + max(l, 0)
            offsets_to_try = [1, -1] if f_max >= 1 else [-1, 1]

        frac_poly = []
        for m in offsets_to_try:
            frac_poly = _hkl_plane_fractional(h, k, l, m)
            if len(frac_poly) >= 3:
                break

        d_hkl = crystal.planeDistance(h, k, l)
        if len(frac_poly) < 3:
            print(f"  Warning: {name} ({_hkl_label(h, k, l)}) plane does not "
                  f"intersect its unit cell for the offsets tried "
                  f"({offsets_to_try}); pass plane_offset explicitly to pick "
                  f"a different member of the family.")
            continue

        cart_poly = np.array(frac_poly) @ ai
        ax_cell.add_collection3d(Poly3DCollection(
            [cart_poly], facecolor=crystal_color, edgecolor=crystal_color,
            linewidths=1.2, alpha=0.35,
        ))
        cell_legend.append(
            Line2D([0], [0], color=crystal_color, lw=2,
                   label=f"{name}: ({_hkl_label(h, k, l)})  d = {d_hkl:.4f} Å")
        )

    all_corners = np.vstack(all_corners)
    cell_span = np.ptp(all_corners, axis=0)
    cell_scale = float(cell_span.max()) if cell_span.max() > 0 else 1.0
    if show_lab_axes:
        _draw_lab_axes_triad(
            ax_cell, origin=all_corners.min(axis=0) - 0.6 * cell_scale,
            length=0.5 * cell_scale,
        )

    ax_cell.set_xlabel("x  (Å)", color=FG, fontsize=8, labelpad=8)
    ax_cell.set_ylabel("y  (Å)", color=FG, fontsize=8, labelpad=8)
    ax_cell.set_zlabel("z  (Å)", color=FG, fontsize=8, labelpad=8)
    ax_cell.set_title(f"{n_crys} crystals in lab frame", color=FG, fontsize=10, pad=10)
    try:
        ax_cell.set_box_aspect(cell_span)
    except AttributeError:
        pass
    if cell_legend:
        ax_cell.legend(
            handles=cell_legend, fontsize=7, labelcolor=FG,
            facecolor="#1a1f2e", edgecolor="#333355", loc="upper left",
        )

    # ── Right panel: scattering diagram, coincident origin, one normal + one
    #    ray per crystal ───────────────────────────────────────────────────
    origin2 = np.zeros(3)
    scat_legend = []
    has_camera = camera is not None
    all_pts = [origin2]

    kf_hats = []
    hit_lengths = []
    for G_lab in G_labs:
        kf_hat = _bragg_kf_hat(G_lab)
        kf_hats.append(kf_hat)
        if has_camera and kf_hat is not None and camera.project(kf_hat, source_depth_mm=0.0) is not None:
            hit = _camera_hit_point_lab(camera, kf_hat, source_lab_mm=origin2)
            hit_lengths.append(np.linalg.norm(hit))

    if has_camera:
        ray_scale = max(hit_lengths) if hit_lengths else 0.5 * camera.dd
        diagram_scale = 0.3 * ray_scale
    else:
        diagram_scale = 1.0

    if show_beam:
        beam_tail = origin2 - np.array([diagram_scale, 0.0, 0.0])
        ax_scat.quiver(*beam_tail, *(origin2 - beam_tail), color=beam_color,
                       linewidth=2.2, arrow_length_ratio=0.15)
        scat_legend.append(
            Line2D([0], [0], color=beam_color, lw=2, label="incident beam (+x)")
        )
        all_pts.append(beam_tail)

    drew_any_normal = drew_any_ray = False
    for (h, k, l), G_lab, kf_hat, crystal_color, name in zip(
        hkls, G_labs, kf_hats, colors, names
    ):
        if show_normal:
            n_vec = (G_lab / np.linalg.norm(G_lab)) * diagram_scale
            ax_scat.quiver(*origin2, *n_vec, color=crystal_color, linewidth=1.8,
                           arrow_length_ratio=0.15)
            ax_scat.text(*(n_vec * 1.1), f"n({_hkl_label(h, k, l)})",
                         color=crystal_color, fontsize=7)
            all_pts.append(n_vec)
            drew_any_normal = True

        if show_scattered_rays:
            if kf_hat is None:
                print(f"  Note: {name} ({_hkl_label(h, k, l)}) is not excited "
                      f"for a beam along +x (G·x̂ ≥ 0) -- no elastic "
                      f"scattered ray to draw.")
                continue

            if has_camera:
                pix = camera.project(kf_hat, source_depth_mm=0.0)
                if pix is not None:
                    ray_end = _camera_hit_point_lab(camera, kf_hat, source_lab_mm=origin2)
                    linestyle = "-"
                    label = f"{name} ({_hkl_label(h, k, l)}) → px({pix[0]:.0f}, {pix[1]:.0f})"
                else:
                    ray_end, linestyle = kf_hat * diagram_scale, "--"
                    label = f"{name} ({_hkl_label(h, k, l)}) → off detector"
            else:
                ray_end, linestyle = kf_hat * diagram_scale, "-"
                label = f"{name} ({_hkl_label(h, k, l)})"

            ax_scat.quiver(*origin2, *ray_end, color=crystal_color, linewidth=1.6,
                           linestyle=linestyle, arrow_length_ratio=0.1, alpha=0.9)
            ax_scat.text(*ray_end, label, color=crystal_color, fontsize=7)
            all_pts.append(ray_end)
            drew_any_ray = True

    if drew_any_normal:
        scat_legend.append(
            Line2D([0], [0], color=FG, lw=1.8, linestyle="-", label="plane normal")
        )
    if drew_any_ray:
        scat_legend.append(
            Line2D([0], [0], color=FG, lw=1.6, linestyle="--", label="diffracted ray")
        )

    if has_camera:
        def _pixel_point(xcam, ycam):
            kf_hat = camera.pixel_to_kf(np.array([xcam]), np.array([ycam]))[0]
            return _camera_hit_point_lab(camera, kf_hat, source_lab_mm=origin2)

        c_pt = _pixel_point(camera.xcen, camera.ycen)
        r_pt = _pixel_point(camera.xcen + camera.Nh / 2.0, camera.ycen)
        u_pt = _pixel_point(camera.xcen, camera.ycen - camera.Nv / 2.0)
        if c_pt is not None and r_pt is not None and u_pt is not None:
            h_vec, v_vec = r_pt - c_pt, u_pt - c_pt
            det_corners = np.array([
                c_pt + h_vec + v_vec, c_pt - h_vec + v_vec,
                c_pt - h_vec - v_vec, c_pt + h_vec - v_vec,
            ])
            ax_scat.add_collection3d(Poly3DCollection(
                [det_corners], facecolor="#dddddd", edgecolor="#dddddd",
                linewidths=1.4, alpha=0.2,
            ))
            ax_scat.text(*c_pt, f"detector\n(dd = {camera.dd:.1f} mm)",
                         color="#dddddd", fontsize=7, ha="center", va="center")
            scat_legend.append(
                Line2D([0], [0], color="#dddddd", lw=2, label="detector (true scale)")
            )
            all_pts.extend(det_corners)

    pts = np.array(all_pts)
    if show_lab_axes:
        axes_len = diagram_scale * (0.4 if has_camera else 0.5)
        tri_origin = pts.min(axis=0) - 0.3 * axes_len if has_camera else np.array([-1.3, -1.3, -1.3])
        _draw_lab_axes_triad(ax_scat, origin=tri_origin, length=axes_len)

    if has_camera:
        span = np.ptp(pts, axis=0)
        span = np.where(span > 1e-6, span, 1.0)
        center = pts.mean(axis=0)
        pad = 0.15
        for set_lim, c, s in zip(
            (ax_scat.set_xlim, ax_scat.set_ylim, ax_scat.set_zlim), center, span
        ):
            set_lim(c - s * (0.5 + pad), c + s * (0.5 + pad))
        try:
            ax_scat.set_box_aspect(span * (1 + 2 * pad))
        except AttributeError:
            pass
        ax_scat.set_xlabel("x  (mm)", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_ylabel("y  (mm)", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_zlabel("z  (mm)", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_title("Scattering diagram (true detector scale, mm)",
                          color=FG, fontsize=10, pad=10)
    else:
        lim = 1.4
        ax_scat.set_xlim(-lim, lim)
        ax_scat.set_ylim(-lim, lim)
        ax_scat.set_zlim(-lim, lim)
        try:
            ax_scat.set_box_aspect((1, 1, 1))
        except AttributeError:
            pass
        ax_scat.set_xlabel("x", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_ylabel("y", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_zlabel("z", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_title("Scattering diagram (unit vectors)", color=FG, fontsize=10, pad=10)

    if scat_legend:
        ax_scat.legend(
            handles=scat_legend, fontsize=7, labelcolor=FG,
            facecolor="#1a1f2e", edgecolor="#333355", loc="upper left",
        )

    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, (ax_cell, ax_scat)

plot_depth_elongation

plot_depth_elongation(spots: list[dict], stack: LayeredCrystal, camera: Camera, ki_hat: ndarray | None = None, *, top_n: int = 15, min_intensity: float = 0.02, n_steps_per_layer: int = 8, space: str = 'detector', show_divergence: bool = True, divergence_nsigma: float = 2.0, image: ndarray | None = None, figsize: tuple[float, float] = (10, 8), ax: Axes | None = None, out_path: str | None = None)

Visualise depth-parallax spot elongation for each Laue spot.

For every spot three graphical elements are drawn:

  • Trail — a sequence of projected detector positions stepping from the top of the contributing layer to its bottom (or until Beer-Lambert absorption reduces transmission below 1e-4). Line opacity fades with depth to reflect the absorption weight. In 'angles' space a single point is drawn instead (depth does not shift 2θ/χ).
  • Tick markers (|) — low-opacity ticks at the trail endpoints (layer top and bottom).
  • Circle — a filled circle at spot['pix'], i.e. the position the simulation placed the spot. When the simulation was run with correct_depth=True this is the layer-centre depth position; when run without it is the surface position (z = 0).

When show_divergence=True a combined broadening ellipse is drawn, centred at the absorption-weighted mean of the trail. Its covariance is the sum of the depth-parallax covariance (computed from the trail positions weighted by Beer-Lambert absorption) and the beam-divergence covariance stored in spot['cov_px'] (populated by :func:beam_divergence_ellipses when sigma_h/v_mrad are passed to the simulation). The ellipse major axis therefore automatically aligns with the dominant elongation direction — depth-parallax for thick layers, beam divergence for thin layers.

Parameters:
  • spots (list[dict]) –

    Output of :func:simulate_laue_stack or :func:simulate_laue_darwin. Required keys: 'tth', 'chi', 'E', 'pix', 'intensity', 'phase_label'. Optional: 'cov_px' (added by :func:beam_divergence_ellipses).

  • stack (LayeredCrystal) –

    The same :class:LayeredCrystal used to produce spots. Provides layer thicknesses, absorption coefficients, and the surface-normal direction.

  • camera (Camera) –

    Detector geometry used in the simulation.

  • ki_hat (ndarray | None, default: None ) –

    Incident-beam direction in the LT frame (3-vector). Defaults to [1, 0, 0].

  • top_n (int, default: 15 ) –

    Maximum number of spots to plot (strongest first).

  • min_intensity (float, default: 0.02 ) –

    Skip spots below this normalised intensity.

  • n_steps_per_layer (int, default: 8 ) –

    Depth samples taken per layer. More steps give smoother trails at the cost of computation time.

  • space (str, default: 'detector' ) –

    'detector' → pixel (col, row); 'angles' → (2θ °, χ °).

  • show_divergence (bool, default: True ) –

    When True (default) draw the combined depth-parallax + beam-divergence broadening ellipse for each spot. Ellipses are centred at the absorption-weighted mean of the trail, not at the simulation dot.

  • divergence_nsigma (float, default: 2.0 ) –

    Scale factor for the broadening ellipse in units of σ. Default 2.0 (≈ 86 % enclosed probability in 2-D).

  • image (ndarray | None, default: None ) –

    Optional detector image shown as a greyscale background (only used when space='detector').

  • figsize (tuple[float, float], default: (10, 8) ) –

    Figure size in inches.

  • ax (Axes | None, default: None ) –

    Draw into an existing :class:~matplotlib.axes.Axes; None creates a new figure.

  • out_path (str | None, default: None ) –

    Save path; None → do not save.

Returns:
  • –

    (fig, ax)

Source code in src/nrxrdct/laue/laue_plotting.py
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
def plot_depth_elongation(
    spots: list[dict],
    stack: LayeredCrystal,
    camera: Camera,
    ki_hat: "np.ndarray | None" = None,
    *,
    top_n: int = 15,
    min_intensity: float = 0.02,
    n_steps_per_layer: int = 8,
    space: str = "detector",
    show_divergence: bool = True,
    divergence_nsigma: float = 2.0,
    image: "np.ndarray | None" = None,
    figsize: tuple[float, float] = (10, 8),
    ax: "plt.Axes | None" = None,
    out_path: "str | None" = None,
):
    """
    Visualise depth-parallax spot elongation for each Laue spot.

    For every spot three graphical elements are drawn:

    * **Trail** — a sequence of projected detector positions stepping from
      the top of the contributing layer to its bottom (or until Beer-Lambert
      absorption reduces transmission below 1e-4).  Line opacity fades with
      depth to reflect the absorption weight.  In ``'angles'`` space a
      single point is drawn instead (depth does not shift 2θ/χ).
    * **Tick markers** (``|``) — low-opacity ticks at the trail endpoints
      (layer top and bottom).
    * **Circle** — a filled circle at ``spot['pix']``, i.e. the position
      the simulation placed the spot.  When the simulation was run with
      ``correct_depth=True`` this is the layer-centre depth position; when
      run without it is the surface position (z = 0).

    When ``show_divergence=True`` a combined broadening ellipse is drawn,
    centred at the absorption-weighted mean of the trail.  Its covariance is
    the sum of the depth-parallax covariance (computed from the trail
    positions weighted by Beer-Lambert absorption) and the beam-divergence
    covariance stored in ``spot['cov_px']`` (populated by
    :func:`beam_divergence_ellipses` when ``sigma_h/v_mrad`` are passed to
    the simulation).  The ellipse major axis therefore automatically aligns
    with the dominant elongation direction — depth-parallax for thick
    layers, beam divergence for thin layers.

    Args:
        spots: Output of :func:`simulate_laue_stack` or
            :func:`simulate_laue_darwin`.  Required keys: ``'tth'``,
            ``'chi'``, ``'E'``, ``'pix'``, ``'intensity'``, ``'phase_label'``.
            Optional: ``'cov_px'`` (added by :func:`beam_divergence_ellipses`).
        stack: The same :class:`LayeredCrystal` used to produce *spots*.
            Provides layer thicknesses, absorption coefficients, and the
            surface-normal direction.
        camera: Detector geometry used in the simulation.
        ki_hat: Incident-beam direction in the LT frame (3-vector).
            Defaults to ``[1, 0, 0]``.
        top_n: Maximum number of spots to plot (strongest first).
        min_intensity: Skip spots below this normalised intensity.
        n_steps_per_layer: Depth samples taken per layer.  More steps give
            smoother trails at the cost of computation time.
        space: ``'detector'`` → pixel (col, row); ``'angles'`` → (2θ °, χ °).
        show_divergence: When ``True`` (default) draw the combined
            depth-parallax + beam-divergence broadening ellipse for each
            spot.  Ellipses are centred at the absorption-weighted mean of
            the trail, not at the simulation dot.
        divergence_nsigma: Scale factor for the broadening ellipse in units
            of σ.  Default 2.0 (≈ 86 % enclosed probability in 2-D).
        image: Optional detector image shown as a greyscale background
            (only used when ``space='detector'``).
        figsize: Figure size in inches.
        ax: Draw into an existing :class:`~matplotlib.axes.Axes`; ``None``
            creates a new figure.
        out_path: Save path; ``None`` → do not save.

    Returns:
        ``(fig, ax)``
    """
    from matplotlib.collections import LineCollection
    from matplotlib.cm import get_cmap

    ki = np.asarray(ki_hat if ki_hat is not None else [1.0, 0.0, 0.0], dtype=float)
    ki /= np.linalg.norm(ki)

    # cos(angle between surface normal and beam) — used for depth→beam conversion
    cos_in = max(abs(float(np.dot(ki, stack.n_hat))), 1e-3)

    # Layer sequence from surface to deep
    segments = _surface_to_depth_segments(stack)
    total_thickness_mm = sum(seg[1] - seg[0] for seg in segments) * 1e-7  # Å→mm

    # ── Filter spots ──────────────────────────────────────────────────────────
    candidates = [s for s in spots
                  if s.get("pix") is not None
                  and float(s.get("intensity", 1.0)) >= min_intensity]
    candidates.sort(key=lambda s: s.get("intensity", 0.0), reverse=True)
    candidates = candidates[:top_n]

    if not candidates:
        raise ValueError("No spots survive the intensity / top_n filter.")

    # ── Colour palette — one colour per phase label ───────────────────────────
    phase_labels = list(dict.fromkeys(
        s.get("phase_label", "unknown") for s in candidates
    ))
    palette = get_cmap("tab10")
    phase_color = {ph: palette(i % 10) for i, ph in enumerate(phase_labels)}

    # ── Set up axes ───────────────────────────────────────────────────────────
    standalone = ax is None
    if standalone:
        fig, ax = plt.subplots(figsize=figsize)
        fig.patch.set_facecolor(BG)
    else:
        fig = ax.figure

    ax.set_facecolor(BG)
    ax.tick_params(colors=FG, labelsize=8)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")

    if space == "detector" and image is not None:
        vmax = np.percentile(image, 99.9)
        ax.imshow(image, cmap="gray", vmin=0, vmax=vmax,
                  aspect="equal", interpolation="nearest")

    # ── Per-spot depth trails ─────────────────────────────────────────────────
    legend_handles = {}

    for spot in candidates:
        phase = spot.get("phase_label", "unknown")
        color = phase_color[phase]
        E_eV  = float(spot["E"])
        kf_hat = _kf_hat_from_spot(spot)
        cos_out = max(abs(float(np.dot(stack.n_hat, kf_hat))), 1e-3)

        # Build depth samples: (z_from_surface_mm, absorption_weight)
        # Only sample depths within the layer that produced this spot —
        # T_above is still accumulated through ALL overlying layers so that
        # absorption by the film is correctly applied to substrate spots.
        depth_samples = []   # (z_mm, weight)
        T_above = 1.0        # cumulative transmission from surface to current layer top
        spot_phase = spot.get("phase_label")

        for z_start_ang, z_end_ang, layer in segments:
            thick_mm = (z_end_ang - z_start_ang) * 1e-7  # Å → mm
            mu = layer._linear_mu(E_eV) * 1e7             # Å⁻¹ → mm⁻¹

            # Only collect depth samples from the layer that produced this spot
            if spot_phase is None or layer.label == spot_phase:
                n_samp = max(1, n_steps_per_layer)
                zs_rel = np.linspace(0.0, thick_mm, n_samp + 1)[:-1]
                for dz in zs_rel:
                    z_mm = z_start_ang * 1e-7 + dz
                    T_partial = (np.exp(-mu * dz * (1.0 / cos_in + 1.0 / cos_out))
                                 if mu > 0 else 1.0)
                    depth_samples.append((z_mm, T_above * T_partial))

            # Always advance T_above through every layer (correct absorption)
            if mu > 0:
                T_above *= np.exp(-mu * thick_mm * (1.0 / cos_in + 1.0 / cos_out))

            # Stop early once signal is negligible
            if T_above < 1e-4:
                break

        if not depth_samples:
            continue

        # Project each depth sample onto the detector
        pix_trail = []
        weights   = []
        for z_mm, w in depth_samples:
            # source_depth_mm: displacement along beam = depth × cos_in
            src_mm = z_mm / cos_in
            if space == "detector":
                pix = camera.project(kf_hat, source_depth_mm=src_mm)
                if pix is not None:
                    pix_trail.append(pix)
                    weights.append(w)
            else:
                # angles space: depth doesn't shift 2θ/χ — only pixel position
                # We still show the surface point only for clarity
                pix_trail.append((float(spot["tth"]), float(spot["chi"])))
                weights.append(w)
                break  # single point in angle space

        if not pix_trail:
            continue

        pix_trail = np.array(pix_trail)
        weights   = np.array(weights)
        weights  /= weights.max()

        xs = pix_trail[:, 0]
        ys = pix_trail[:, 1]

        # Draw the trail as a sequence of line segments with fading alpha
        if len(xs) > 1:
            points  = np.column_stack([xs, ys]).reshape(-1, 1, 2)
            segs    = np.concatenate([points[:-1], points[1:]], axis=1)
            alphas  = 0.1 + 0.85 * weights[:-1]   # surface → opaque, deep → faint
            rgba    = np.array([(*mcolors.to_rgb(color), a) for a in alphas])
            lc = LineCollection(segs, colors=rgba, linewidths=1.5, zorder=2)
            ax.add_collection(lc)

        # Trail endpoints
        ax.scatter(xs[0], ys[0], s=10, color=color, alpha=0.4,
                   zorder=3, marker="|")
        ax.scatter(xs[-1], ys[-1], s=10, color=color, alpha=0.4,
                   zorder=3, marker="|")

        # Simulation spot position — Circle in data coords so it grows on zoom
        if space == "angles":
            sim_x, sim_y = float(spot["tth"]), float(spot["chi"])
        else:
            sim_x, sim_y = float(spot["pix"][0]), float(spot["pix"][1])
        ax.add_patch(Circle((sim_x, sim_y), radius=1.5, facecolor=color,
                            edgecolor="white", linewidth=0.5, alpha=0.5, zorder=5))

        # Combined ellipse: depth-parallax covariance + beam-divergence covariance.
        # Centred at the absorption-weighted mean of the trail so it spans
        # the same region as the trail itself.
        if show_divergence and space == "detector" and len(xs) > 1:
            from matplotlib.patches import Ellipse as _Ellipse
            w_norm = weights / weights.sum()
            mx = float(np.dot(w_norm, xs))
            my = float(np.dot(w_norm, ys))
            dx = xs - mx
            dy = ys - my
            cov_depth = np.array([
                [float(np.dot(w_norm, dx * dx)), float(np.dot(w_norm, dx * dy))],
                [float(np.dot(w_norm, dx * dy)), float(np.dot(w_norm, dy * dy))],
            ])
            cov_div = np.asarray(spot.get("cov_px", np.zeros((2, 2))), dtype=float)
            cov_total = cov_depth + cov_div
            try:
                eigvals, eigvecs = np.linalg.eigh(cov_total)
                eigvals = np.maximum(eigvals, 0.0)
                idx = int(np.argmax(eigvals))
                sig_maj = float(np.sqrt(eigvals[idx]))
                sig_min = float(np.sqrt(eigvals[1 - idx]))
                if sig_maj > 0.0:
                    v = eigvecs[:, idx]
                    ang = float(np.degrees(np.arctan2(v[1], v[0])))
                    ax.add_patch(_Ellipse(
                        xy=(mx, my),
                        width=2.0 * divergence_nsigma * sig_maj,
                        height=2.0 * divergence_nsigma * sig_min,
                        angle=ang,
                        linewidth=0.8, edgecolor=color, facecolor="none",
                        alpha=0.6, zorder=3,
                    ))
            except Exception:
                pass

        # hkl annotation at the simulation spot position
        h, k, l = spot["hkl"]
        ax.annotate(
            f"({h}{k}{l})",
            (sim_x, sim_y),
            xytext=(4, 4), textcoords="offset points",
            fontsize=5, color=color, alpha=0.85, zorder=6,
        )

        if phase not in legend_handles:
            legend_handles[phase] = plt.Line2D(
                [], [], color=color, linewidth=2,
                label=phase, marker="o", markersize=4,
            )

    # ── Axes decoration ───────────────────────────────────────────────────────
    if space == "detector":
        ax.set_xlabel("x  (px)", color=FG, fontsize=9)
        ax.set_ylabel("y  (px)", color=FG, fontsize=9)
        ax.set_aspect("equal")
    else:
        ax.set_xlabel("2θ  (°)", color=FG, fontsize=9)
        ax.set_ylabel("χ  (°)",  color=FG, fontsize=9)

    depth_lim_um = min(total_thickness_mm * 1e3,
                       max(seg[1] - seg[0] for seg in segments) * 1e-4)
    ax.set_title(
        f"Depth-parallax elongation  "
        f"(total stack {total_thickness_mm*1e3:.0f} µm, "
        f"surface → deep,  cos_in = {cos_in:.3f})",
        color=FG, fontsize=8,
    )

    if legend_handles:
        leg = ax.legend(
            handles=list(legend_handles.values()),
            fontsize=7, labelcolor=FG,
            facecolor="#1a1f2e", edgecolor="#333355",
            loc="upper right",
        )

    if standalone:
        fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, ax

plot_depth_scan_image

plot_depth_scan_image(result: dict, stack: LayeredCrystal | None = None, *, top_n_spots: int = 20, figsize: tuple[float, float] = (12, 8), cmap_matrix: str = 'inferno', out_path: str | None = None, ax_score: Axes | None = None) -> tuple

Visualise the output of :func:~nrxrdct.laue.simulation.depth_scan_image.

Three panels are drawn:

  • Left — Global depth score profile (total + per-phase).
  • Centre — Score matrix heat-map: rows are depth steps, columns are the top_n_spots most responsive spots (sorted by peak score). The colour scale is per-column so dim spots are not swamped by bright ones.
  • Right (optional inset) — Score matrix for all valid spots so that the column ordering can be inspected.
Parameters:
  • result (dict) –

    Dict returned by :func:depth_scan_image.

  • top_n_spots (int, default: 20 ) –

    Number of highest-scoring spot columns to show in the centre heatmap.

  • figsize (tuple[float, float], default: (12, 8) ) –

    Figure size (width, height) in inches.

  • cmap_matrix (str, default: 'inferno' ) –

    Colormap name for the score matrix.

  • out_path (str | None, default: None ) –

    If given, save the figure to this path.

  • ax_score (Axes | None, default: None ) –

    Optional pre-existing :class:~matplotlib.axes.Axes for the score profile. If supplied the figure is not created internally and only the score axes is drawn (useful for inline notebooks).

Returns:
  • tuple –

    (fig, axes) where axes is a list

  • tuple –

    [ax_score, ax_heatmap] (ax_heatmap is None when

  • tuple –

    ax_score was supplied externally).

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_depth_scan_image(
    result: dict,
    stack: "LayeredCrystal | None" = None,
    *,
    top_n_spots: int = 20,
    figsize: tuple[float, float] = (12, 8),
    cmap_matrix: str = "inferno",
    out_path: "str | None" = None,
    ax_score: "plt.Axes | None" = None,
) -> tuple:
    """
    Visualise the output of :func:`~nrxrdct.laue.simulation.depth_scan_image`.

    Three panels are drawn:

    * **Left** — Global depth score profile (total + per-phase).
    * **Centre** — Score matrix heat-map: rows are depth steps, columns are the
      ``top_n_spots`` most responsive spots (sorted by peak score).  The
      colour scale is per-column so dim spots are not swamped by bright ones.
    * **Right** (optional inset) — Score matrix for *all* valid spots so that
      the column ordering can be inspected.

    Args:
        result: Dict returned by :func:`depth_scan_image`.
        top_n_spots: Number of highest-scoring spot columns to show in the
            centre heatmap.
        figsize: Figure size ``(width, height)`` in inches.
        cmap_matrix: Colormap name for the score matrix.
        out_path: If given, save the figure to this path.
        ax_score: Optional pre-existing :class:`~matplotlib.axes.Axes` for the
            score profile.  If supplied the figure is *not* created internally
            and only the score axes is drawn (useful for inline notebooks).

    Returns:
        ``(fig, axes)`` where *axes* is a list
        ``[ax_score, ax_heatmap]`` (``ax_heatmap`` is ``None`` when
        *ax_score* was supplied externally).
    """
    z_mm         = result["z_mm"]
    score        = result["score"]
    score_phase  = result["score_per_phase"]
    score_matrix = result["score_matrix"]   # (n_steps, n_valid)
    phases       = list(score_phase.keys())

    PHASE_COLS = ["#4fc3f7", "#ff6633", "#ffffaa", "#aaffaa", "#ff88ff"]
    phase_color = {ph: PHASE_COLS[i % len(PHASE_COLS)] for i, ph in enumerate(phases)}

    # ── Figure layout ─────────────────────────────────────────────────────────
    if ax_score is not None:
        fig = ax_score.get_figure()
        ax_s = ax_score
        ax_h = None
        axes_out = [ax_s, ax_h]
    else:
        fig, (ax_s, ax_h) = plt.subplots(
            1, 2,
            figsize=figsize,
            gridspec_kw={"width_ratios": [1, 2]},
            facecolor=BG,
        )
        axes_out = [ax_s, ax_h]

    for ax in [ax_s] + ([ax_h] if ax_h is not None else []):
        ax.set_facecolor(BG)
        ax.tick_params(colors=FG, labelsize=7)
        for sp in ax.spines.values():
            sp.set_edgecolor("#1a1f2e")

    # ── Score profile (left panel) ────────────────────────────────────────────
    ax_s.plot(z_mm * 1e3, score, color=FG, lw=1.5, label="total", zorder=5)
    for ph in phases:
        ax_s.plot(z_mm * 1e3, score_phase[ph], lw=1, color=phase_color[ph],
                  linestyle="--", label=ph, alpha=0.8)

    z_best = float(z_mm[np.argmax(score)])
    ax_s.axvline(z_best * 1e3, color="orange", lw=1, linestyle=":",
                 label=f"peak z={z_best*1e3:.1f} µm")
    ax_s.set_xlabel("depth  (µm)", color=FG, fontsize=8)
    ax_s.set_ylabel("image score  (a.u.)", color=FG, fontsize=8)
    ax_s.set_title("Depth score profile", color=FG, fontsize=9)
    ax_s.legend(fontsize=7, labelcolor=FG, facecolor="#1a1f2e", edgecolor="#333355")

    # ── Layer interfaces ──────────────────────────────────────────────────────
    if stack is not None:
        _ifaces = _stack_interface_depths_mm(stack)
        z_plot_min = float(z_mm[0]) * 1e3
        for z_iface_mm, ilabel in _ifaces:
            z_iface_um = z_iface_mm * 1e3
            if z_iface_um <= z_plot_min:
                continue  # skip the surface line (left edge)
            ax_s.axvline(z_iface_um, color="#888888", lw=0.8,
                         linestyle="--", alpha=0.6, zorder=2)
            ax_s.text(
                z_iface_um, 1.0, ilabel,
                transform=ax_s.get_xaxis_transform(),
                color="#888888", fontsize=6, rotation=90,
                va="top", ha="right", alpha=0.8,
            )

    # ── Score matrix heatmap (right panel) ───────────────────────────────────
    if ax_h is not None:
        n_valid = score_matrix.shape[1]
        n_show  = min(top_n_spots, n_valid)

        # Sort by peak score, take top_n_spots
        peak_per_spot = score_matrix.max(axis=0)
        top_idx = np.argsort(peak_per_spot)[::-1][:n_show]
        sub = score_matrix[:, top_idx]

        # Normalise each column independently (0→1) so dim spots are visible
        col_max = sub.max(axis=0, keepdims=True)
        col_max[col_max == 0] = 1.0
        sub_norm = sub / col_max

        im = ax_h.imshow(
            sub_norm.T,
            aspect="auto",
            origin="lower",
            extent=[z_mm[0] * 1e3, z_mm[-1] * 1e3, 0, n_show],
            cmap=cmap_matrix,
            vmin=0, vmax=1,
            interpolation="nearest",
        )
        ax_h.axvline(z_best * 1e3, color="orange", lw=1, linestyle=":",
                     alpha=0.8)
        if stack is not None:
            for z_iface_mm, _ in _ifaces:
                z_iface_um = z_iface_mm * 1e3
                if z_iface_um <= z_plot_min:
                    continue
                ax_h.axvline(z_iface_um, color="#888888", lw=0.8,
                             linestyle="--", alpha=0.6, zorder=2)
        ax_h.set_xlabel("depth  (µm)", color=FG, fontsize=8)
        ax_h.set_ylabel(f"spot rank (top {n_show})", color=FG, fontsize=8)
        ax_h.set_title("Per-spot depth profile (col-normalised)", color=FG, fontsize=9)

        cbar = fig.colorbar(im, ax=ax_h, fraction=0.03, pad=0.01)
        cbar.ax.tick_params(colors=FG, labelsize=6)
        cbar.set_label("score / max", color=FG, fontsize=7)

    fig.tight_layout()
    if out_path is not None:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=BG)

    _force_draw(fig)
    return fig, axes_out

plot_detector_projection

plot_detector_projection(vol_or_vols, *, image: ndarray | None = None, camera: Camera | None = None, pad_px: int = 20, log_intensity: bool = True, psf_sigma_px: float = 1.0, exclude_bragg_along: float | None = None, vmin_percentile: float = 0.0, vmax_percentile: float = 99.5, figsize: tuple[float, float] | None = None, out_path: str | None = None) -> tuple

Plot the Q-space projection onto detector pixels produced by :func:~nrxrdct.laue.simulation.project_to_detector.

When image (a full measured detector frame) is supplied the function shows two panels side by side — simulated (left) and measured patch (right) — so you can compare them directly.

Normalisation

Each panel is independently normalised by I/I_max before the log-stretch: the simulated panel divides by its own peak intensity, the measured panel divides by the measured intensity at the simulated spot positions (or by its own peak if none are non-zero). A shared percentile-based colour scale (vmin_percentile / vmax_percentile) is then derived from the combined non-zero pixels of both stretched panels so that faint features (e.g. superlattice satellites) are visible at the same visual level.

Auto-crop

After the PSF convolution the function crops the arrays to the bounding box of non-zero simulated pixels, expanded by pad_px on every side. This is done even when a full-frame camera is supplied (where :func:~nrxrdct.laue.simulation.project_to_detector returns a ~2k × 2k frame) so that a 1–2 pixel spot is never lost in an empty field.

Parameters:
  • vol_or_vols –

    A single vol dict from qspace_around_spot or a list of such dicts (e.g. from qspace_per_layer). Multiple volumes are summed onto the same pixel grid.

  • image (ndarray | None, default: None ) –

    Full measured detector frame (ndarray, shape (Nv, Nh)). When given a second panel is added showing the corresponding patch.

  • camera (Camera | None, default: None ) –

    :class:~nrxrdct.laue.camera.Camera. If None the output is cropped to the spot bounding box (+ pad_px).

  • pad_px (int, default: 20 ) –

    Extra margin (pixels) around the bounding box patch.

  • log_intensity (bool, default: True ) –

    Apply log1p stretch to both panels.

  • psf_sigma_px (float, default: 1.0 ) –

    Gaussian PSF sigma in pixels applied to the simulated image before normalisation. Models detector point-spread (charge sharing, optical blur). Set to 0 to disable.

  • exclude_bragg_along (float | None, default: None ) –

    float or None. When set, voxels with |along| < exclude_bragg_along (Å⁻¹) are stripped from the simulated projection so that the kinematical Bragg peak does not flood the image. A good starting value is π / Λ (e.g. 0.03 for Λ=100 Å).

  • vmin_percentile (float, default: 0.0 ) –

    Percentile (0–100) of the combined non-zero pixels from both panels used as the colour-scale minimum. Default 0 (true minimum — no black-level clipping). Increase to suppress faint background; e.g. 5 clips the bottom 5 % of signal.

  • vmax_percentile (float, default: 99.5 ) –

    Percentile (0–100) used as the colour-scale maximum. Default 99.5 — clips the top 0.5 % so a single bright outlier (e.g. unsuppressed Bragg peak) does not compress the satellite colour range. Set to 100 for the true maximum.

  • figsize (tuple[float, float] | None, default: None ) –

    Figure size. Defaults to (8, 5) (one panel) or (14, 5) (two panels).

  • out_path (str | None, default: None ) –

    If given, save the figure to this path.

Returns:
  • tuple –

    (fig, axes) where axes is a 1- or 2-element list.

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_detector_projection(
    vol_or_vols,
    *,
    image: "np.ndarray | None" = None,
    camera: "Camera | None" = None,
    pad_px: int = 20,
    log_intensity: bool = True,
    psf_sigma_px: float = 1.0,
    exclude_bragg_along: "float | None" = None,
    vmin_percentile: float = 0.0,
    vmax_percentile: float = 99.5,
    figsize: "tuple[float, float] | None" = None,
    out_path: "str | None" = None,
) -> tuple:
    """
    Plot the Q-space projection onto detector pixels produced by
    :func:`~nrxrdct.laue.simulation.project_to_detector`.

    When *image* (a full measured detector frame) is supplied the function
    shows two panels side by side — simulated (left) and measured patch
    (right) — so you can compare them directly.

    **Normalisation**

    Each panel is independently normalised by ``I/I_max`` before the
    log-stretch: the simulated panel divides by its own peak intensity, the
    measured panel divides by the measured intensity at the simulated spot
    positions (or by its own peak if none are non-zero).  A shared
    percentile-based colour scale (*vmin_percentile* / *vmax_percentile*)
    is then derived from the combined non-zero pixels of both stretched
    panels so that faint features (e.g. superlattice satellites) are
    visible at the same visual level.

    **Auto-crop**

    After the PSF convolution the function crops the arrays to the
    bounding box of non-zero simulated pixels, expanded by *pad_px* on
    every side.  This is done even when a full-frame *camera* is supplied
    (where :func:`~nrxrdct.laue.simulation.project_to_detector` returns a
    ~2k × 2k frame) so that a 1–2 pixel spot is never lost in an empty
    field.

    Args:
        vol_or_vols: A single vol dict from ``qspace_around_spot`` or a list
            of such dicts (e.g. from ``qspace_per_layer``).  Multiple volumes
            are summed onto the same pixel grid.
        image: Full measured detector frame (``ndarray``, shape ``(Nv, Nh)``).
            When given a second panel is added showing the corresponding patch.
        camera: :class:`~nrxrdct.laue.camera.Camera`.  If ``None`` the output
            is cropped to the spot bounding box (+ *pad_px*).
        pad_px: Extra margin (pixels) around the bounding box patch.
        log_intensity: Apply ``log1p`` stretch to both panels.
        psf_sigma_px: Gaussian PSF sigma in pixels applied to the simulated
            image before normalisation.  Models detector point-spread (charge
            sharing, optical blur).  Set to 0 to disable.
        exclude_bragg_along: float or None.  When set, voxels with
            ``|along| < exclude_bragg_along`` (Å⁻¹) are stripped from the
            simulated projection so that the kinematical Bragg peak does not
            flood the image.  A good starting value is ``π / Λ`` (e.g. 0.03
            for Λ=100 Å).
        vmin_percentile: Percentile (0–100) of the combined non-zero pixels
            from both panels used as the colour-scale minimum.  Default 0
            (true minimum — no black-level clipping).  Increase to suppress
            faint background; e.g. 5 clips the bottom 5 % of signal.
        vmax_percentile: Percentile (0–100) used as the colour-scale maximum.
            Default 99.5 — clips the top 0.5 % so a single bright outlier
            (e.g. unsuppressed Bragg peak) does not compress the satellite
            colour range.  Set to 100 for the true maximum.
        figsize: Figure size.  Defaults to ``(8, 5)`` (one panel) or
            ``(14, 5)`` (two panels).
        out_path: If given, save the figure to this path.

    Returns:
        ``(fig, axes)`` where *axes* is a 1- or 2-element list.
    """
    from .simulation import project_to_detector

    sim, x0, y0 = project_to_detector(
        vol_or_vols, pad_px=pad_px, camera=camera,
        exclude_bragg_along=exclude_bragg_along,
    )
    Ny, Nx = sim.shape

    # ── PSF convolution (before normalisation so it acts on raw flux) ────────
    if psf_sigma_px > 0:
        from scipy.ndimage import gaussian_filter as _gf
        sim = _gf(sim, sigma=psf_sigma_px)

    # ── crop to bounding box of non-zero pixels ───────────────────────────────
    # project_to_detector already crops when camera=None.  When camera is
    # supplied it returns the full detector frame, making any spot invisible.
    # Crop here so the display always focuses on the simulated region.
    nz = np.argwhere(sim > 0)
    if len(nz):
        ry0, rx0 = nz[:, 0].min(), nz[:, 1].min()
        ry1, rx1 = nz[:, 0].max() + 1, nz[:, 1].max() + 1
        ry0 = max(ry0 - pad_px, 0)
        rx0 = max(rx0 - pad_px, 0)
        ry1 = min(ry1 + pad_px, Ny)
        rx1 = min(rx1 + pad_px, Nx)
        sim = sim[ry0:ry1, rx0:rx1]
        x0, y0 = x0 + rx0, y0 + ry0
        Ny, Nx = sim.shape

    # pixel-space extent for imshow: (left, right, bottom, top) with origin='upper'
    ext = [x0, x0 + Nx, y0 + Ny, y0]

    has_meas = image is not None
    n_panels = 2 if has_meas else 1
    if figsize is None:
        figsize = (14.0, 5.5) if has_meas else (7.0, 5.5)

    fig, axes_arr = plt.subplots(
        1, n_panels, figsize=figsize,
        facecolor=BG, squeeze=False,
        sharex=True, sharey=True,
    )
    axes = list(axes_arr[0])
    cmap = mcolors.LinearSegmentedColormap.from_list(
        "qvol_warm", [_QVOL_LOW, _QVOL_MID, _QVOL_HIGH]
    )

    def _stretch(arr):
        if log_intensity:
            return np.log1p(arr)
        return arr.copy()

    vols_list = [vol_or_vols] if isinstance(vol_or_vols, dict) else list(vol_or_vols)

    # ── I / I_max normalisation ───────────────────────────────────────────────
    # Simulated panel: divide by its own maximum so the brightest simulated
    # feature (satellite peak with exclude_bragg_along set, or Bragg peak
    # otherwise) maps to 1.0.
    I_max_sim = float(sim.max()) if sim.max() > 0 else 1.0
    sim = sim / I_max_sim

    if has_meas:
        img_arr = np.asarray(image, dtype=float)
        meas_patch = img_arr[y0:y0 + Ny, x0:x0 + Nx]
        I_max_meas = float(meas_patch.max()) if meas_patch.max() > 0 else 1.0
        meas_norm = meas_patch / I_max_meas

    sim_s = _stretch(sim)

    # ── colour-scale limits from percentiles of non-zero pixels ───────────────
    # Collect stretched values from both panels (non-zero only so the large
    # empty background does not pull the percentiles to zero).
    _nz_vals = [sim_s[sim_s > 0]]
    if has_meas:
        meas_s_tmp = _stretch(meas_norm)
        _nz_m = meas_s_tmp[meas_s_tmp > 0]
        if len(_nz_m):
            _nz_vals.append(_nz_m)
    _all_nz = np.concatenate(_nz_vals) if _nz_vals else np.array([0.0, 1.0])
    vmin_s = float(np.percentile(_all_nz, vmin_percentile)) if len(_all_nz) else 0.0
    vmax_s = float(np.percentile(_all_nz, vmax_percentile)) if len(_all_nz) else 1.0
    if vmax_s <= vmin_s:
        vmax_s = vmin_s + 1e-6

    for ax in axes:
        _ax_style(ax, "")
        ax.set_xlabel("xcam  (px)", color=FG, fontsize=8)
        ax.set_ylabel("ycam  (px)", color=FG, fontsize=8)

    # ── left panel: simulated ─────────────────────────────────────────────────
    ax_sim = axes[0]
    _sim_title = "Simulated"
    ax_sim.set_title(_sim_title, color=FG, fontsize=9, pad=4)
    im_s = ax_sim.imshow(
        sim_s, origin="upper", extent=ext,
        cmap=cmap, vmin=vmin_s, vmax=vmax_s,
        aspect="equal", interpolation="nearest",
    )
    cbar_s = fig.colorbar(im_s, ax=ax_sim, shrink=0.85, pad=0.03)
    cbar_s.set_label("log(1+counts)" if log_intensity else "counts", color=FG, fontsize=7)
    cbar_s.ax.yaxis.set_tick_params(color="#7788aa", labelsize=6)
    plt.setp(cbar_s.ax.get_yticklabels(), color=FG)
    cbar_s.outline.set_edgecolor("#333355")

    # ── right panel: measured patch ───────────────────────────────────────────
    if has_meas:
        ax_meas = axes[1]
        ax_meas.set_title("Measured", color=FG, fontsize=9, pad=4)
        meas_s = meas_s_tmp
        im_m = ax_meas.imshow(
            meas_s, origin="upper", extent=ext,
            cmap="gray", vmin=vmin_s, vmax=vmax_s,
            aspect="equal", interpolation="nearest",
        )
        cbar_m = fig.colorbar(im_m, ax=ax_meas, shrink=0.85, pad=0.03)
        cbar_m.set_label("log(1+counts)" if log_intensity else "counts", color=FG, fontsize=7)
        cbar_m.ax.yaxis.set_tick_params(color="#7788aa", labelsize=6)
        plt.setp(cbar_m.ax.get_yticklabels(), color=FG)
        cbar_m.outline.set_edgecolor("#333355")

    # ── crosshair at nominal Bragg pixel (along=0, lateral centre) ───────────
    # Draw one + per unique HKL using the first vol for that HKL that has a
    # finite (on-detector) G0 pixel.  Using vols_list[0] blindly fails when
    # the first vol is a substrate layer whose G0 is off-detector.
    seen_hkls: set = set()
    for _vol in vols_list:
        _hkl = _vol.get("hkl")
        if _hkl in seen_hkls:
            continue
        _pix = _vol.get("pix")
        _along = _vol.get("along")
        if _pix is None or _along is None:
            continue
        _i0 = int(np.argmin(np.abs(_along)))
        _j0 = _pix.shape[1] // 2
        _k0 = _pix.shape[2] // 2
        _cx = float(_pix[_i0, _j0, _k0, 0])
        _cy = float(_pix[_i0, _j0, _k0, 1])
        if np.isfinite(_cx) and np.isfinite(_cy):
            for ax in axes:
                ax.plot(_cx, _cy, "+", color=FG, ms=10, mew=1.2, zorder=5)
            seen_hkls.add(_hkl)

    # ── build title ───────────────────────────────────────────────────────────
    unique_hkls = list(dict.fromkeys(str(v.get("hkl", "?")) for v in vols_list))
    unique_layers = list(dict.fromkeys(str(v.get("layer", "?")) for v in vols_list))
    hkl_str = unique_hkls[0] if len(unique_hkls) == 1 else f"{len(unique_hkls)} reflections"
    layer_str = unique_layers[0] if len(unique_layers) == 1 else f"{len(unique_layers)} layers"
    title = f"Detector projection — hkl={hkl_str}  ({layer_str})"

    fig.suptitle(title, color=FG, fontsize=10, y=1.01)
    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, axes

plot_hkl_family_classification

plot_hkl_family_classification(image, peaklist, spots, hkl, *, n_multiples: int = 5, i_thresh: float = 0.0, crop_half_size: int = 20, n_cols: int = 5, color_by: str = 'order', spot_size: float = 90.0, spot_alpha: float = 1.0, cmap: str = 'inferno', figsize: tuple | None = None, out_path: str | None = None)

Zoom into the surroundings of a lattice-plane (hkl) family and let you manually pick, per zoomed panel, which candidate simulated spot is the real origin of the measured peak there.

Why this exists: a systematic row of satellite reflections (m=0 Bragg peak plus m=±1, ±2, … satellites) often lands so close together on the detector that several candidates fall inside the same few pixels, and it isn't obvious by eye — or by simple nearest-neighbour matching — which one a given measured peak actually corresponds to. This function crops the raw image around each such cluster so you can zoom in and decide by hand.

Simulated spots matching hkl = m * (h, k, l) (for m = ±1 … ±n_multiples, see :func:print_hkl_family) are grouped into panels: spots that land close enough together on the detector to fit in one crop window (typically a Bragg reflection together with its satellite orders) share a single panel. Each panel shows two different things overlaid on the same crop — don't confuse them:

  • coloured markers — predictions: where the simulation says each candidate spot should be. One marker per candidate in the group, colour-coded by color_by and shaped by which phase it originates from (hover a marker for its full details — hkl, energy, intensity, satellite order, phase).
  • hollow white circles — observations: real peaks found by the segmentation pipeline (from peaklist) that fall inside the crop. There may be zero, one, or several.

Example: a panel shows one white circle (a real peak) sitting right on top of the orange '+' (predicted m=+1 satellite) but 4 px away from the blue '+' (predicted m=0 Bragg spot). Clicking the orange marker records "this measured peak is the m=+1 satellite, not the Bragg spot" as that panel's classification.

Mechanically, clicking is just picking one of the candidate markers as your answer for that panel — it does not move, fit, or alter anything, it only records a label:

  • click near a candidate marker → that candidate is stored as the panel's classification; the panel border is recoloured to match it and the title shows the chosen (hkl) / satellite order.
  • click on empty space inside a panel (not near any marker) → clears that panel's classification.

Classifications are visual bookkeeping only, kept in memory as fig._classifications (dict: panel index → the classified spot's dict) for as long as the figure stays open — there is no auto-save; read that attribute yourself if you want to keep the picks.

Parameters:
  • image ((Nv, Nh) array) –

    Raw detector image, in the same pixel frame as peaklist and the 'pix' key of spots.

  • peaklist (ndarray (N, >=2), or DataFrame) –

    Segmented peak table. Columns 0, 1 (or 'peak_X', 'peak_Y') are pixel positions.

  • spots (list[dict]) –

    Spot list from any simulate_laue* function. Each dict must contain 'hkl' and 'pix'.

  • hkl ((int, int, int)) –

    Base Miller indices (h, k, l) of the lattice-plane family to inspect.

  • n_multiples (int, default: 5 ) –

    Highest multiple of hkl to search for. Default 5.

  • i_thresh (float, default: 0.0 ) –

    Minimum intensity / max(intensity), evaluated over the matched family only, for a candidate to be shown. Default 0.0 (show every match).

  • crop_half_size (int, default: 20 ) –

    Half-width, in pixels, of each crop window. Also the clustering radius: simulated spots within 2 * crop_half_size of each other share one panel.

  • n_cols (int, default: 5 ) –

    Number of panels per row.

  • color_by (`'order'` | `'phase'`, default: 'order' ) –

    Candidate colour coding. 'order' — satellite order m (coolwarm, m=0 = Bragg peak). 'phase' — phase_label (tab10). Independently of color_by, candidates are also given a marker shape per phase_label (e.g. all 'bcc' candidates drawn as '+', all 'fcc' as 'x', a third phase as '^', …) so the phase a diffraction event originates from stays visible even when color_by is 'order'. 'o' is never used for a candidate — it is reserved for the measured-peak circles. A marker-shape legend is added automatically when more than one phase is present.

  • spot_size (float, default: 90.0 ) –

    Marker area (points²) for the candidate simulated-spot markers. Default 90.0.

  • spot_alpha (float, default: 1.0 ) –

    Opacity of the candidate simulated-spot markers, in [0, 1]. Default 1.0 (opaque). Lower it to make an occluding candidate marker translucent so a measured-peak circle underneath it, or an overlapping candidate, stays visible.

  • cmap (str, default: 'inferno' ) –

    Colormap for the background image crops.

  • figsize ((float, float), default: None ) –

    Figure size in inches. Defaults to a size scaled to the number of panels.

  • out_path (str or None, default: None ) –

    Save a static PNG snapshot (before any classification clicks) if provided.

Returns:
  • fig( Figure ) –
  • axes( list[Axes] ) –

    One axes per panel, in display order.

Source code in src/nrxrdct/laue/laue_plotting.py
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
def plot_hkl_family_classification(
    image,
    peaklist,
    spots,
    hkl,
    *,
    n_multiples: int = 5,
    i_thresh: float = 0.0,
    crop_half_size: int = 20,
    n_cols: int = 5,
    color_by: str = "order",
    spot_size: float = 90.0,
    spot_alpha: float = 1.0,
    cmap: str = "inferno",
    figsize: tuple | None = None,
    out_path: str | None = None,
):
    """
    Zoom into the surroundings of a lattice-plane (hkl) family and let you
    manually pick, per zoomed panel, which candidate simulated spot is the
    real origin of the measured peak there.

    Why this exists: a systematic row of satellite reflections (m=0 Bragg
    peak plus m=±1, ±2, … satellites) often lands so close together on the
    detector that several candidates fall inside the same few pixels, and
    it isn't obvious by eye — or by simple nearest-neighbour matching —
    which one a given measured peak actually corresponds to. This function
    crops the raw image around each such cluster so you can zoom in and
    decide by hand.

    Simulated spots matching `hkl = m * (h, k, l)` (for `m = ±1 …
    ±n_multiples`, see :func:`print_hkl_family`) are grouped into panels:
    spots that land close enough together on the detector to fit in one
    crop window (typically a Bragg reflection together with its satellite
    orders) share a single panel. Each panel shows two *different* things
    overlaid on the same crop — don't confuse them:

    * coloured markers — **predictions**: where the simulation says each
      candidate spot should be. One marker per candidate in the group,
      colour-coded by *color_by* and shaped by which phase it originates
      from (hover a marker for its full details — hkl, energy, intensity,
      satellite order, phase).
    * hollow white circles — **observations**: real peaks found by the
      segmentation pipeline (from *peaklist*) that fall inside the crop.
      There may be zero, one, or several.

    Example: a panel shows one white circle (a real peak) sitting right on
    top of the orange `'+'` (predicted m=+1 satellite) but 4 px away from
    the blue `'+'` (predicted m=0 Bragg spot). Clicking the orange marker
    records "this measured peak is the m=+1 satellite, not the Bragg
    spot" as that panel's classification.

    Mechanically, clicking is just picking one of the candidate markers as
    your answer for that panel — it does not move, fit, or alter anything,
    it only records a label:

    * click near a candidate marker → that candidate is stored as the
      panel's classification; the panel border is recoloured to match it
      and the title shows the chosen `(hkl)` / satellite order.
    * click on empty space inside a panel (not near any marker) → clears
      that panel's classification.

    Classifications are visual bookkeeping only, kept in memory as
    `fig._classifications` (dict: panel index → the classified spot's
    dict) for as long as the figure stays open — there is no auto-save;
    read that attribute yourself if you want to keep the picks.

    Args:
        image ((Nv, Nh) array): Raw detector image, in the same pixel frame as *peaklist* and the
            `'pix'` key of *spots*.
        peaklist (ndarray (N, >=2), or DataFrame): Segmented peak table. Columns 0, 1 (or `'peak_X'`, `'peak_Y'`)
            are pixel positions.
        spots (list[dict]): Spot list from any `simulate_laue*` function. Each dict must contain
            `'hkl'` and `'pix'`.
        hkl ((int, int, int)): Base Miller indices `(h, k, l)` of the lattice-plane family to
            inspect.
        n_multiples (int): Highest multiple of *hkl* to search for. Default 5.
        i_thresh (float): Minimum `intensity / max(intensity)`, evaluated over the matched
            family only, for a candidate to be shown. Default `0.0` (show
            every match).
        crop_half_size (int): Half-width, in pixels, of each crop window. Also the clustering
            radius: simulated spots within `2 * crop_half_size` of each
            other share one panel.
        n_cols (int): Number of panels per row.
        color_by (`'order'` | `'phase'`): Candidate *colour* coding. `'order'` — satellite order `m`
            (coolwarm, `m=0` = Bragg peak). `'phase'` — `phase_label`
            (tab10). Independently of *color_by*, candidates are also given
            a marker *shape* per `phase_label` (e.g. all `'bcc'` candidates
            drawn as `'+'`, all `'fcc'` as `'x'`, a third phase as `'^'`,
            …) so the phase a diffraction event originates from stays
            visible even when *color_by* is `'order'`. `'o'` is never used
            for a candidate — it is reserved for the measured-peak
            circles. A marker-shape legend is added automatically when
            more than one phase is present.
        spot_size (float): Marker area (points²) for the candidate simulated-spot markers.
            Default `90.0`.
        spot_alpha (float): Opacity of the candidate simulated-spot markers, in `[0, 1]`.
            Default `1.0` (opaque). Lower it to make an occluding candidate
            marker translucent so a measured-peak circle underneath it, or
            an overlapping candidate, stays visible.
        cmap (str): Colormap for the background image crops.
        figsize ((float, float), optional): Figure size in inches. Defaults to a size scaled to
            the number of panels.
        out_path (str or None): Save a static PNG snapshot (before any classification clicks)
            if provided.

    Returns:
        fig (matplotlib.figure.Figure):
        axes (list[matplotlib.axes.Axes]): One axes per panel, in display order.
"""
    if color_by not in ("order", "phase"):
        raise ValueError(f"color_by must be 'order' or 'phase', got {color_by!r}")

    # ── select the (h,k,l) family ──────────────────────────────────────────────
    h0, k0, l0 = (int(v) for v in hkl)
    targets = set()
    for m in range(1, int(n_multiples) + 1):
        targets.add((m * h0, m * k0, m * l0))
        targets.add((-m * h0, -m * k0, -m * l0))

    matches = [
        s for s in spots
        if s.get("pix") is not None
        and tuple(int(x) for x in s["hkl"]) in targets
    ]
    if not matches:
        raise ValueError(
            f"No spots with a 'pix' position found for hkl family {hkl} "
            f"(multiples 1..{n_multiples})."
        )
    if i_thresh > 0.0:
        i_ref = max(s["intensity"] for s in matches)
        matches = [s for s in matches if s["intensity"] >= i_thresh * i_ref]

    # ── group nearby candidates so they share one crop window ─────────────────
    xy = np.array([s["pix"] for s in matches], dtype=float)
    tree = KDTree(xy)
    parent = list(range(len(matches)))

    def _find(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    for i, j in tree.query_pairs(r=2.0 * crop_half_size):
        ri, rj = _find(i), _find(j)
        if ri != rj:
            parent[ri] = rj

    groups = {}
    for i in range(len(matches)):
        groups.setdefault(_find(i), []).append(matches[i])

    sites = []
    for cand in groups.values():
        cx = float(np.mean([c["pix"][0] for c in cand]))
        cy = float(np.mean([c["pix"][1] for c in cand]))
        sites.append({"candidates": cand, "center": (cx, cy)})
    sites.sort(key=lambda site: site["center"][1])

    # ── parse the measured peaklist ─────────────────────────────────────────
    try:
        import pandas as pd
        if isinstance(peaklist, pd.DataFrame):
            pk_xy = peaklist[["peak_X", "peak_Y"]].to_numpy(dtype=float)
        else:
            pk_xy = np.asarray(peaklist, dtype=float)[:, :2]
    except ImportError:
        pk_xy = np.asarray(peaklist, dtype=float)[:, :2]

    # ── candidate colour coding (shared across all panels) ─────────────────
    labels = list(dict.fromkeys(s.get("phase_label", "sim") for s in matches))
    if color_by == "order":
        orders = np.array([s.get("satellite_order", 0) for s in matches])
        omax = max(abs(int(orders.min())), abs(int(orders.max())), 1)
        norm = mcolors.Normalize(vmin=-omax, vmax=omax)
        order_cmap = plt.get_cmap("coolwarm")
        color_of = lambda s: order_cmap(norm(s.get("satellite_order", 0)))
    else:
        tab10 = plt.get_cmap("tab10")
        lc = {lb: tab10(i / max(len(labels) - 1, 1)) for i, lb in enumerate(labels)}
        color_of = lambda s: lc[s.get("phase_label", "sim")]

    # ── candidate marker shape, one per phase (independent of colour) ──────
    # "o" is reserved for measured-peak circles, so it is never used here.
    _CANDIDATE_MARKERS = ["+", "x", "^", "s", "D", "v", "p", "h", "P", "*"]
    marker_of_phase = {
        lb: _CANDIDATE_MARKERS[i % len(_CANDIDATE_MARKERS)]
        for i, lb in enumerate(labels)
    }
    marker_of = lambda s: marker_of_phase[s.get("phase_label", "sim")]

    # ── figure / axes grid ───────────────────────────────────────────────────
    n_sites = len(sites)
    n_cols = max(1, min(n_cols, n_sites))
    n_rows = int(np.ceil(n_sites / n_cols))
    if figsize is None:
        figsize = (2.6 * n_cols, 2.6 * n_rows + 0.7)

    fig, axes_grid = plt.subplots(n_rows, n_cols, figsize=figsize, facecolor=BG)
    axes = np.atleast_1d(axes_grid).ravel().tolist()
    for ax in axes[n_sites:]:
        ax.set_visible(False)
    axes = axes[:n_sites]

    img = np.asarray(image, dtype=float)
    Nv, Nh = img.shape

    classifications = {}
    UNSET_EDGE = "#1a1f2e"

    def _panel_title(i, n_cand):
        return f"panel {i}  ·  {n_cand} candidate(s)"

    for i, (ax, site) in enumerate(zip(axes, sites)):
        cx, cy = site["center"]
        r0 = int(round(cy - crop_half_size))
        r1 = int(round(cy + crop_half_size))
        c0 = int(round(cx - crop_half_size))
        c1 = int(round(cx + crop_half_size))
        r0c, r1c = max(r0, 0), min(r1, Nv)
        c0c, c1c = max(c0, 0), min(c1, Nh)
        crop = img[r0c:r1c, c0c:c1c]

        ax.set_facecolor("#000000")
        ax.tick_params(colors="#7788aa", labelsize=6)
        for sp in ax.spines.values():
            sp.set_edgecolor(UNSET_EDGE)
            sp.set_linewidth(1.5)

        disp = np.where(np.isfinite(crop) & (crop > 0), crop, np.nan)
        ax.imshow(
            np.log1p(disp), origin="upper", cmap=cmap,
            extent=[c0c - 0.5, c1c - 0.5, r1c - 0.5, r0c - 0.5],
            interpolation="nearest", aspect="equal",
        )

        # measured peaks inside this crop
        if pk_xy.shape[0] > 0:
            in_crop = (
                (pk_xy[:, 0] >= c0c) & (pk_xy[:, 0] < c1c)
                & (pk_xy[:, 1] >= r0c) & (pk_xy[:, 1] < r1c)
            )
            if in_crop.any():
                ax.scatter(
                    pk_xy[in_crop, 0], pk_xy[in_crop, 1],
                    s=70, marker="o", facecolors="none",
                    edgecolors="white", linewidths=1.0, alpha=0.85, zorder=3,
                )

        cand = site["candidates"]
        xs = np.array([c["pix"][0] for c in cand])
        ys = np.array([c["pix"][1] for c in cand])
        cols = [color_of(c) for c in cand]
        mks = [marker_of(c) for c in cand]
        # scatter() takes one marker per call, so candidates with different
        # phases (=> different marker shapes) are drawn in separate calls.
        for mk in set(mks):
            sel = [j for j, m in enumerate(mks) if m == mk]
            is_line_marker = mk in ("+", "x")
            ax.scatter(
                xs[sel], ys[sel], c=[cols[j] for j in sel],
                marker=mk, s=spot_size, alpha=spot_alpha, linewidths=1.4,
                edgecolors=None if is_line_marker else "white",
                zorder=4,
            )
        _attach_hover_tooltip(fig, ax, cand, xs, ys)

        ax.set_xlim(c0c - 0.5, c1c - 0.5)
        ax.set_ylim(r1c - 0.5, r0c - 0.5)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_title(_panel_title(i, len(cand)), color=FG, fontsize=7, pad=3)

        ax._family_candidates = cand
        ax._family_colors = cols
        ax._family_xy = np.column_stack([xs, ys])
        ax._family_index = i

    # ── click-to-classify ────────────────────────────────────────────────────
    def _on_click(event):
        ax = event.inaxes
        if ax is None or not hasattr(ax, "_family_candidates"):
            return

        cand = ax._family_candidates
        xy_disp = ax.transData.transform(ax._family_xy)
        mouse_disp = np.array([event.x, event.y])
        dists = np.linalg.norm(xy_disp - mouse_disp, axis=1)
        threshold_px = 10.0 * fig.dpi / 72.0
        idx = int(np.argmin(dists))
        i = ax._family_index

        if dists[idx] <= threshold_px:
            chosen = cand[idx]
            classifications[i] = chosen
            hh, kk, ll = chosen["hkl"]
            order = chosen.get("satellite_order", 0)
            order_txt = f"  m={order:+d}" if order else ""
            phase_txt = f"  [{chosen.get('phase_label')}]" if len(labels) > 1 else ""
            ax.set_title(f"({hh:+d}{kk:+d}{ll:+d}){order_txt}{phase_txt}  ✓",
                         color=FG, fontsize=7, pad=3)
            edge_col = ax._family_colors[idx]
            lw = 2.5
        else:
            classifications.pop(i, None)
            ax.set_title(_panel_title(i, len(cand)), color=FG, fontsize=7, pad=3)
            edge_col = UNSET_EDGE
            lw = 1.5

        for sp in ax.spines.values():
            sp.set_edgecolor(edge_col)
            sp.set_linewidth(lw)
        fig.canvas.draw_idle()

    fig.canvas.mpl_connect("button_press_event", _on_click)
    fig._classifications = classifications

    fig.suptitle(
        f"({h0:+d}{k0:+d}{l0:+d}) family  —  {n_sites} panel(s), "
        f"{len(matches)} candidate spot(s)  |  click a marker to classify, "
        f"click empty space to clear",
        color=FG, fontsize=9, y=0.995,
    )
    fig.tight_layout(rect=[0, 0, 0.93, 0.96])

    # ── shared colour legend (added after layout so it gets its own space) ────
    if color_by == "order":
        cax = fig.add_axes([0.945, 0.15, 0.015, 0.7])
        sm = plt.cm.ScalarMappable(cmap=order_cmap, norm=norm)
        sm.set_array([])
        cb = fig.colorbar(sm, cax=cax)
        cb.set_label("satellite order  m", color=FG, fontsize=8)
        cb.ax.tick_params(colors="#7788aa", labelsize=7)
        cb.outline.set_edgecolor("#1a1f2e")
        phase_legend_color = FG   # colour already used for order; keep markers neutral
    else:
        phase_legend_color = None  # use each phase's own colour from lc

    # Marker-shape legend — only meaningful when more than one phase is present.
    if len(labels) > 1:
        handles = [
            Line2D([0], [0], linestyle="none", marker=marker_of_phase[lb],
                   color=lc[lb] if phase_legend_color is None else phase_legend_color,
                   markersize=8, label=lb)
            for lb in labels
        ]
        fig.legend(
            handles=handles, loc="upper right", fontsize=7,
            framealpha=0.5, facecolor="#1a1f2e", edgecolor="#3a3f4e",
            labelcolor=FG, title="phase (marker shape)",
            title_fontsize=7,
        )

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  HKL-family classification plot saved -> {out_path}")

    _force_draw(fig)
    return fig, axes

plot_interactive_tth_chi

plot_interactive_tth_chi(spots, *, color_by: str = 'energy', i_thresh: float = 0.01, size_scale: float = 120.0, min_size: float = 10.0, figsize=(9, 7), out_path: str | None = None)

Interactive 2θ / χ scatter plot with per-spot hover tooltips.

Hovering the mouse over a marker displays a tooltip containing:

  • Miller indices (hkl)
  • 2θ and χ in degrees
  • Photon energy (eV)
  • Normalised intensity
  • Whether the reflection is a Bragg peak, superlattice / superstructure reflection, or a satellite fringe (with order m)
  • Phase label (when present)

The function works with spot lists from all three simulation functions: :func:~nrxrdct.laue.simulate_laue, :func:~nrxrdct.laue.simulate_laue_stack, and :func:~nrxrdct.laue.simulate_mixed_phases.

Parameters:
  • spots (list[dict]) –

    Spot list from any simulate_laue* function. Required keys: 'tth', 'chi', 'hkl', 'E', 'intensity'. Optional: 'satellite_order', 'is_superlattice', 'phase_label'.

  • i_thresh (float, default: 0.01 ) –

    Minimum intensity threshold as a fraction of the brightest Bragg peak (satellite_order == 0). Spots with intensity < i_thresh * I_bragg_max are dropped before plotting. Default: 0.01 (1 % of the strongest Bragg peak). Pass 0.0 to show all spots.

  • color_by (`'energy'` | `'intensity'` | `'phase'`, default: 'energy' ) –

    Quantity mapped to spot colour:

  • size_scale (float, default: 120.0 ) –

    Maximum marker area (s in scatter).

  • min_size (float, default: 10.0 ) –

    Minimum marker area so that weak spots remain visible.

  • figsize ((float, float), default: (9, 7) ) –

    Figure size in inches.

  • out_path (str or None, default: None ) –

    If given, save a static PNG snapshot on figure close. None (default) → do not save.

Returns:
  • fig( Figure ) –
  • ax( Axes ) –

Note: The interactive hover is implemented with matplotlib's built-in event system (no extra dependencies). Call plt.show() after this function to display the interactive window.

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_interactive_tth_chi(
    spots,
    *,
    color_by: str = "energy",
    i_thresh: float = 0.01,
    size_scale: float = 120.0,
    min_size: float = 10.0,
    figsize=(9, 7),
    out_path: str | None = None,
):
    """
    Interactive 2θ / χ scatter plot with per-spot hover tooltips.

    Hovering the mouse over a marker displays a tooltip containing:

    * Miller indices `(hkl)`
    * 2θ and χ in degrees
    * Photon energy (eV)
    * Normalised intensity
    * Whether the reflection is a **Bragg peak**, **superlattice / superstructure**
      reflection, or a **satellite fringe** (with order *m*)
    * Phase label (when present)

    The function works with spot lists from all three simulation functions:
    :func:`~nrxrdct.laue.simulate_laue`,
    :func:`~nrxrdct.laue.simulate_laue_stack`, and
    :func:`~nrxrdct.laue.simulate_mixed_phases`.

    Args:
        spots (list[dict]): Spot list from any `simulate_laue*` function.  Required keys:
            `'tth'`, `'chi'`, `'hkl'`, `'E'`, `'intensity'`.
            Optional: `'satellite_order'`, `'is_superlattice'`,
            `'phase_label'`.
        i_thresh (float): Minimum intensity threshold as a fraction of the brightest **Bragg
            peak** (`satellite_order == 0`).  Spots with
            `intensity < i_thresh * I_bragg_max` are dropped before plotting.
            Default: `0.01` (1 % of the strongest Bragg peak).
            Pass `0.0` to show all spots.
        color_by (`'energy'` | `'intensity'` | `'phase'`): Quantity mapped to spot colour:

        * `'energy'`    — photon energy (plasma colormap)
        * `'intensity'` — normalised intensity (viridis colormap)
        * `'phase'`     — phase label (tab10; requires `'phase_label'` key)
        size_scale (float): Maximum marker area (`s` in `scatter`).
        min_size (float): Minimum marker area so that weak spots remain visible.
        figsize ((float, float)): Figure size in inches.
        out_path (str or None): If given, save a **static** PNG snapshot on figure close.
            `None` (default) → do not save.

    Returns:
        fig (matplotlib.figure.Figure):
        ax (matplotlib.axes.Axes):

    Note:
    The interactive hover is implemented with matplotlib's built-in event
    system (no extra dependencies).  Call `plt.show()` after this function
    to display the interactive window.
"""
    if not spots:
        raise ValueError("spots list is empty")

    # ── Intensity threshold — relative to brightest Bragg peak ────────────────
    if i_thresh > 0.0:
        bragg_spots = [s for s in spots if s.get("satellite_order", 0) == 0
                       and not s.get("is_superlattice", False)]
        if bragg_spots:
            i_bragg_max = max(s["intensity"] for s in bragg_spots)
        else:
            i_bragg_max = max(s["intensity"] for s in spots)
        cutoff = i_thresh * i_bragg_max
        spots = [s for s in spots if s["intensity"] >= cutoff]
        if not spots:
            raise ValueError(
                f"No spots survive the intensity threshold "
                f"(i_thresh={i_thresh}, cutoff={cutoff:.4f}).  "
                f"Lower i_thresh or pass i_thresh=0.0 to show all."
            )

    # ── Colour mapping ────────────────────────────────────────────────────────
    if color_by == "energy":
        cvals = np.array([s["E"] / 1e3 for s in spots])
        norm = mcolors.Normalize(vmin=cvals.min(), vmax=cvals.max())
        cmap = plt.get_cmap("plasma")
        colors = [cmap(norm(v)) for v in cvals]
        cbar_label = "Energy  (keV)"
    elif color_by == "intensity":
        cvals = np.array([s["intensity"] for s in spots])
        norm = mcolors.Normalize(vmin=0.0, vmax=1.0)
        cmap = plt.get_cmap("viridis")
        colors = [cmap(norm(v)) for v in cvals]
        cbar_label = "Normalised intensity"
    elif color_by == "phase":
        labels = [s.get("phase_label", "unknown") for s in spots]
        unique_labels = list(dict.fromkeys(labels))
        tab10 = plt.get_cmap("tab10")
        label_color = {lb: tab10(i / max(len(unique_labels) - 1, 1))
                       for i, lb in enumerate(unique_labels)}
        colors = [label_color[lb] for lb in labels]
        cvals = None
        cbar_label = None
    else:
        raise ValueError(f"color_by must be 'energy', 'intensity', or 'phase'")

    sizes = np.array([max(min_size, size_scale * s["intensity"]) for s in spots])
    tths = np.array([s["tth"] for s in spots])
    chis = np.array([s["chi"] for s in spots])

    # ── Figure & axes ─────────────────────────────────────────────────────────
    fig, ax = plt.subplots(figsize=figsize)
    fig.patch.set_facecolor(BG)
    ax.set_facecolor(BG)
    ax.tick_params(colors="#7788aa", labelsize=7)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")
    ax.set_xlabel("2θ  (°)", color="#7788aa", fontsize=9)
    ax.set_ylabel("χ  (°)", color="#7788aa", fontsize=9)

    # ── Scatter ───────────────────────────────────────────────────────────────
    ax.scatter(
        tths, chis,
        s=sizes,
        c=colors,
        marker="o",
        linewidths=0.4,
        edgecolors="#ffffff44",
        alpha=0.90,
        zorder=3,
        picker=False,   # we handle picking manually via motion_notify_event
    )

    # ── Colorbar (energy / intensity modes) ───────────────────────────────────
    if cvals is not None:
        sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
        sm.set_array([])
        cb = fig.colorbar(sm, ax=ax, pad=0.02, fraction=0.03)
        cb.set_label(cbar_label, color=FG, fontsize=8)
        cb.ax.tick_params(colors="#7788aa", labelsize=7)
    elif color_by == "phase":
        # Phase legend patches
        from matplotlib.patches import Patch
        handles = [Patch(color=label_color[lb], label=lb)
                   for lb in unique_labels]
        ax.legend(handles=handles, loc="upper right", fontsize=7.5,
                  framealpha=0.5, facecolor="#1a1f2e", edgecolor="#3a3f4e",
                  labelcolor=FG)

    # ── Title ─────────────────────────────────────────────────────────────────
    ax.set_title(
        f"2θ / χ map  —  {len(spots)} spots   (hover for details)",
        color=FG, fontsize=9, pad=6,
    )

    # ── Hover tooltip ─────────────────────────────────────────────────────────
    _attach_hover_tooltip(fig, ax, spots, tths, chis)

    if out_path:
        import atexit
        atexit.register(
            lambda: fig.savefig(out_path, dpi=150, bbox_inches="tight",
                                facecolor=fig.get_facecolor())
        )

    fig.tight_layout()
    _force_draw(fig)
    return fig, ax

plot_laue_comparison

plot_laue_comparison(exp_image, sim_image, camera, spots=None, *, frame: str = 'tth_chi', tth_range=None, chi_range=None, n_tth: int = 600, n_chi: int = 600, cmap: str = 'gray', spot_marker: str = '+', sat_marker: str = 'x', spot_size: float = 60.0, spot_color=None, color_spots_by: str = 'phase', i_thresh: float = 0.01, show_divergence: bool = True, divergence_nsigma: float = 2.0, figsize=(18, 7), out_path: str | None = None)

Side-by-side comparison of an experimental Laue image and a simulated one, with simulated spot positions overlaid on the right panel.

Parameters:
  • exp_image ((array - like, shape(Nv, Nh))) –

    Experimental detector image.

  • sim_image ((array - like, shape(Nv, Nh))) –

    Simulated detector image from :meth:~Camera.render.

  • camera (Camera) –

    Detector geometry (shared by both panels).

  • spots (list[dict], default: None ) –

    Spot list from any simulate_laue* function. Overlaid on the right (simulation) panel only.

  • frame (`'tth_chi'` | `'detector'`, default: 'tth_chi' ) –

    Display coordinate frame.

  • tth_range, chi_range ((float, float)) –

    Angular display range (tth_chi frame only).

  • n_tth, n_chi (int) –

    Warp resolution (tth_chi frame only).

  • cmap (str, default: 'gray' ) –

    Matplotlib colormap (applied to both panels).

  • spot_marker (str, default: '+' ) –

    Marker style for Bragg (satellite_order == 0) spots (default '+').

  • sat_marker (str, default: 'x' ) –

    Marker style for satellite spots (default 'x'), kept visually distinct from spot_marker so Bragg and satellite reflections don't have to be told apart by size/alpha alone.

  • spot_size (float, default: 60.0 ) –

    Marker size.

  • spot_color (str or None, default: None ) –

    Fixed colour for all spots. None → colour by color_spots_by.

  • color_spots_by (`'phase'` | `'order'` | `'energy'`, default: 'phase' ) –

    Colouring scheme when spot_color is None.

  • i_thresh (float, default: 0.01 ) –

    Minimum I/Imax to show a spot (0 = show all). Spots with intensity < i_thresh are hidden. The toggle button shows / hides satellite spots on top of this threshold.

  • figsize ((float, float), default: (18, 7) ) –
  • out_path (str or None, default: None ) –

    Save figure to this path if provided.

Returns:
  • fig( Figure ) –
  • ax_exp( Axes ) –

    left (experimental) panel

  • ax_sim( Axes ) –

    right (simulation) panel

Source code in src/nrxrdct/laue/laue_plotting.py
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
def plot_laue_comparison(
    exp_image,
    sim_image,
    camera,
    spots=None,
    *,
    frame: str = "tth_chi",
    tth_range=None,
    chi_range=None,
    n_tth: int = 600,
    n_chi: int = 600,
    cmap: str = "gray",
    spot_marker: str = "+",
    sat_marker: str = "x",
    spot_size: float = 60.0,
    spot_color=None,
    color_spots_by: str = "phase",
    i_thresh: float = 0.01,
    show_divergence: bool = True,
    divergence_nsigma: float = 2.0,
    figsize=(18, 7),
    out_path: str | None = None,
):
    """
    Side-by-side comparison of an experimental Laue image and a simulated one,
    with simulated spot positions overlaid on the right panel.

    Args:
        exp_image (array-like, shape (Nv, Nh)): Experimental detector image.
        sim_image (array-like, shape (Nv, Nh)): Simulated detector image from :meth:`~Camera.render`.
        camera (Camera): Detector geometry (shared by both panels).
        spots (list[dict], optional): Spot list from any `simulate_laue*` function.  Overlaid on the
            right (simulation) panel only.
        frame (`'tth_chi'` | `'detector'`): Display coordinate frame.

        * `'tth_chi'` — both images are warped to an evenly-spaced 2θ / χ
          grid; spots are placed at their angular coordinates.
        * `'detector'` — raw pixel images; spots projected via their
          `'pix'` key or back-projected from 2θ / χ.
        tth_range, chi_range ((float, float), optional): Angular display range (*tth_chi* frame only).
        n_tth, n_chi (int): Warp resolution (*tth_chi* frame only).
        cmap (str): Matplotlib colormap (applied to both panels).
        spot_marker (str): Marker style for Bragg (satellite_order == 0) spots (default `'+'`).
        sat_marker (str): Marker style for satellite spots (default `'x'`), kept visually
            distinct from *spot_marker* so Bragg and satellite reflections
            don't have to be told apart by size/alpha alone.
        spot_size (float): Marker size.
        spot_color (str or None): Fixed colour for all spots.  `None` → colour by `color_spots_by`.
        color_spots_by (`'phase'` | `'order'` | `'energy'`): Colouring scheme when *spot_color* is `None`.
        i_thresh (float): Minimum `I/Imax` to show a spot (0 = show all).  Spots with
            `intensity < i_thresh` are hidden.  The toggle button shows /
            hides satellite spots on top of this threshold.
        figsize ((float, float)):
        out_path (str or None): Save figure to this path if provided.

    Returns:
        fig (matplotlib.figure.Figure):
        ax_exp (matplotlib.axes.Axes): left (experimental) panel
        ax_sim (matplotlib.axes.Axes): right (simulation) panel
"""
    from matplotlib.widgets import CheckButtons

    if frame not in ("tth_chi", "detector"):
        raise ValueError(f"frame must be 'tth_chi' or 'detector', got {frame!r}")

    # ── Apply intensity threshold ─────────────────────────────────────────────
    spots_all = list(spots) if spots else []
    if spots_all and i_thresh > 0.0:
        i_ref = max(s["intensity"] for s in spots_all)
        spots_all = [s for s in spots_all if s["intensity"] >= i_thresh * i_ref]

    # Split into Bragg and satellite lists
    spots_bragg = [s for s in spots_all if s.get("satellite_order", 0) == 0]
    spots_sat   = [s for s in spots_all if s.get("satellite_order", 0) != 0]

    # ── Figure layout ─────────────────────────────────────────────────────────
    fig = plt.figure(figsize=figsize, facecolor=BG)
    # Reserve a thin strip on the right for the checkbox widget
    gs = mgridspec.GridSpec(
        1, 3,
        figure=fig,
        width_ratios=[1, 1, 0.12],
        wspace=0.08,
    )
    ax_exp = fig.add_subplot(gs[0, 0])
    ax_sim = fig.add_subplot(gs[0, 1], sharex=ax_exp, sharey=ax_exp)
    ax_cb  = fig.add_subplot(gs[0, 2])   # checkbox lives here
    ax_cb.set_axis_off()

    for ax in (ax_exp, ax_sim):
        ax.set_facecolor("#000000")
        ax.tick_params(colors="#7788aa", labelsize=7)
        for sp in ax.spines.values():
            sp.set_edgecolor("#1a1f2e")

    # ── Helper: prepare one image for display ─────────────────────────────────
    def _prepare(raw_arr):
        """Return (display_array, extent) ready for imshow."""
        arr = np.asarray(raw_arr, dtype=np.float64)
        if frame == "tth_chi":
            warped, tth_ax, chi_ax = warp_image_to_tth_chi(
                arr, camera,
                tth_range=tth_range, chi_range=chi_range,
                n_tth=n_tth, n_chi=n_chi,
            )
            # Extend by half a pixel so that axis values (pixel centres) align
            # with the markers placed at (tth, chi) coordinates.
            dt = (tth_ax[-1] - tth_ax[0]) / max(len(tth_ax) - 1, 1)
            dc = (chi_ax[-1] - chi_ax[0]) / max(len(chi_ax) - 1, 1)
            ext = [
                tth_ax[0] - dt / 2, tth_ax[-1] + dt / 2,
                chi_ax[0] - dc / 2, chi_ax[-1] + dc / 2,
            ]
            return warped, ext
        else:
            # Use pixel-centre convention: array pixel [r, c] has its centre at
            # data coordinate (c, r).  The default matplotlib imshow extent
            # [-0.5, Nh-0.5, Nv-0.5, -0.5] achieves this.  Without this
            # correction every pixel centre would be shifted +0.5 px in x and y
            # relative to the scatter markers plotted at (xcam, ycam).
            #
            # Derived from arr.shape rather than camera.Nh/Nv: if the raw
            # frame's actual dimensions ever disagree with the camera
            # calibration (crop, binning, stale .det file), an extent based
            # on camera.Nh/Nv silently stretches the background relative to
            # the markers — which are placed independently via camera.project()
            # — while arr.shape always matches what's actually on screen.
            ext = [-0.5, arr.shape[1] - 0.5, arr.shape[0] - 0.5, -0.5]
            return arr, ext

    exp_disp, ext = _prepare(exp_image)
    sim_disp, _   = _prepare(sim_image)

    # ── Build LogNorm for simulation panel ───────────────────────────────────
    def _lognorm(arr):
        vals = arr[np.isfinite(arr) & (arr > 0)]
        if vals.size == 0:
            return mcolors.Normalize(vmin=0, vmax=1)
        return mcolors.LogNorm(vmin=vals.min(), vmax=vals.max())

    origin = "lower" if frame == "tth_chi" else "upper"
    aspect = "auto"  if frame == "tth_chi" else "equal"

    # Experimental panel — simple linear log1p scaling
    exp_plot = np.where(np.isfinite(exp_disp) & (exp_disp > 0), exp_disp, np.nan)
    exp_log  = np.log1p(exp_plot)
    im_exp = ax_exp.imshow(
        exp_log, origin=origin, aspect=aspect, extent=ext,
        cmap=cmap, interpolation="nearest",
    )
    cb_exp = fig.colorbar(im_exp, ax=ax_exp, pad=0.02, fraction=0.04)
    cb_exp.set_label("log₁₊(intensity)", color=FG, fontsize=7)
    cb_exp.ax.tick_params(colors="#7788aa", labelsize=6)

    # Simulation panel — LogNorm
    sim_plot = np.where(np.isfinite(sim_disp) & (sim_disp > 0), sim_disp, np.nan)
    sim_norm = _lognorm(sim_plot)
    im_sim = ax_sim.imshow(
        sim_plot, origin=origin, aspect=aspect, extent=ext,
        cmap=cmap, norm=sim_norm, interpolation="nearest",
    )
    cb_sim = fig.colorbar(im_sim, ax=ax_sim, pad=0.02, fraction=0.04)
    cb_sim.set_label("intensity (LogNorm)", color=FG, fontsize=7)
    cb_sim.ax.tick_params(colors="#7788aa", labelsize=6)

    # ── Axis labels ───────────────────────────────────────────────────────────
    if frame == "tth_chi":
        for ax in (ax_exp, ax_sim):
            ax.set_xlabel("2θ  (°)", color="#7788aa", fontsize=9)
        ax_exp.set_ylabel("χ  (°)", color="#7788aa", fontsize=9)
    else:
        for ax in (ax_exp, ax_sim):
            ax.set_xlabel("x  (px)", color="#7788aa", fontsize=9)
        ax_exp.set_ylabel("y  (px)", color="#7788aa", fontsize=9)
    # Hide redundant y tick labels on the shared right panel
    plt.setp(ax_sim.get_yticklabels(), visible=False)

    ax_exp.set_title("Experiment", color=FG, fontsize=9, pad=6)
    ax_sim.set_title("Simulation", color=FG, fontsize=9, pad=6)

    # ── Helper: compute (xs, ys) in display coordinates for a spot list ───────
    def _spot_coords(slist):
        if not slist:
            return np.array([]), np.array([]), slist
        if frame == "tth_chi":
            xs = np.array([s["tth"] for s in slist])
            ys = np.array([s["chi"] for s in slist])
            return xs, ys, slist
        else:
            xs_l, ys_l = [], []
            for s in slist:
                pix = s.get("pix")
                if pix is not None:
                    xs_l.append(pix[0]); ys_l.append(pix[1])
                else:
                    tth_r = np.radians(s["tth"]); chi_r = np.radians(s["chi"])
                    st = np.sin(tth_r)
                    kf = np.array([[np.cos(tth_r), st * np.sin(chi_r), st * np.cos(chi_r)]])
                    xc, yc = camera.kf_to_pixel(kf)
                    xs_l.append(float(xc[0])); ys_l.append(float(yc[0]))
            xs = np.array(xs_l); ys = np.array(ys_l)
            on_det = (
                np.isfinite(xs) & np.isfinite(ys)
                & (xs >= 0) & (xs < camera.Nh)
                & (ys >= 0) & (ys < camera.Nv)
            )
            return xs[on_det], ys[on_det], [s for s, ok in zip(slist, on_det) if ok]

    # ── Colour helper ─────────────────────────────────────────────────────────
    _tab10 = plt.get_cmap("tab10")
    _all_labels = list(dict.fromkeys(
        s.get("phase_label", "sim") for s in spots_all
    ))
    _lc = {lb: _tab10(i / max(len(_all_labels) - 1, 1))
           for i, lb in enumerate(_all_labels)}

    def _colors(slist):
        if spot_color is not None:
            return spot_color
        if color_spots_by == "phase":
            return [_lc[s.get("phase_label", "sim")] for s in slist]
        if color_spots_by == "order":
            ords = np.array([s.get("satellite_order", 0) for s in slist])
            nm = mcolors.Normalize(vmin=ords.min(), vmax=ords.max())
            return plt.get_cmap("coolwarm")(nm(ords))
        if color_spots_by == "energy":
            en = np.array([s["E"] / 1e3 for s in slist])
            nm = mcolors.Normalize(vmin=en.min(), vmax=en.max())
            return plt.get_cmap("plasma")(nm(en))
        return "#ff4444"

    # ── Draw Bragg spots on both panels (always visible) ─────────────────────
    xb, yb, sb = _spot_coords(spots_bragg)
    if sb:
        cb = _colors(sb)
        for _ax in (ax_exp, ax_sim):
            _ax.scatter(
                xb, yb, c=cb,
                s=spot_size, marker=spot_marker, linewidths=1.4, zorder=4,
            )
            if show_divergence:
                _draw_divergence_ellipses(_ax, sb, xb, yb, frame,
                                          divergence_nsigma, cb)
        _attach_hover_tooltip(fig, ax_exp, sb, xb, yb)
        _attach_hover_tooltip(fig, ax_sim, sb, xb, yb)

    # ── Draw satellite spots on both panels (toggleable) ──────────────────────
    xs, ys, ss = _spot_coords(spots_sat)
    sc_sat_exp = sc_sat_sim = None
    if ss:
        cs = _colors(ss)
        sc_sat_exp = ax_exp.scatter(
            xs, ys, c=cs,
            s=spot_size * 0.7, marker=sat_marker, linewidths=1.1,
            zorder=3, alpha=0.75,
        )
        sc_sat_sim = ax_sim.scatter(
            xs, ys, c=cs,
            s=spot_size * 0.7, marker=sat_marker, linewidths=1.1,
            zorder=3, alpha=0.75,
        )
        if show_divergence:
            for _ax in (ax_exp, ax_sim):
                _draw_divergence_ellipses(_ax, ss, xs, ys, frame,
                                          divergence_nsigma, cs)
        _attach_hover_tooltip(fig, ax_exp, ss, xs, ys)
        _attach_hover_tooltip(fig, ax_sim, ss, xs, ys)

    # ── Phase legend ──────────────────────────────────────────────────────────
    phase_legend = None
    if spots_all and spot_color is None and color_spots_by == "phase" and _all_labels:
        handles = [
            Line2D([0], [0], linestyle="none", marker=spot_marker,
                   color=_lc[lb], markersize=7, label=lb)
            for lb in _all_labels
        ]
        phase_legend = ax_sim.legend(
            handles=handles, loc="upper right", fontsize=7,
            framealpha=0.5, facecolor="#1a1f2e", edgecolor="#3a3f4e",
            labelcolor=FG,
        )

    # ── Marker-shape legend (Bragg vs satellite) ─────────────────────────────
    if sb or ss:
        shape_handles = []
        if sb:
            shape_handles.append(Line2D([0], [0], linestyle="none", marker=spot_marker,
                                         color="#cccccc", markersize=7, label="Bragg"))
        if ss:
            shape_handles.append(Line2D([0], [0], linestyle="none", marker=sat_marker,
                                         color="#cccccc", markersize=7, label="satellite"))
        ax_sim.legend(
            handles=shape_handles, loc="lower right", fontsize=7,
            framealpha=0.5, facecolor="#1a1f2e", edgecolor="#3a3f4e",
            labelcolor=FG,
        )
        if phase_legend is not None:
            ax_sim.add_artist(phase_legend)

    # ── Satellite toggle checkbox ─────────────────────────────────────────────
    # Store the widget on the figure so it is not garbage-collected.
    chk_ax = fig.add_axes([0.91, 0.46, 0.08, 0.08], facecolor="#1a1f2e")
    fig._sat_chk = CheckButtons(chk_ax, ["satellites"], [sc_sat_sim is not None])
    fig._sat_chk.labels[0].set_color(FG)
    fig._sat_chk.labels[0].set_fontsize(8)

    def _toggle_sat(_):
        for sc in (sc_sat_exp, sc_sat_sim):
            if sc is not None:
                sc.set_visible(not sc.get_visible())
        fig.canvas.draw_idle()

    fig._sat_chk.on_clicked(_toggle_sat)

    n_spots = len(spots_all)
    ax_sim.set_title(
        f"Simulation  |  {n_spots} spots  (hover for details)",
        color=FG, fontsize=9, pad=6,
    )

    fig.tight_layout(rect=[0, 0, 0.90, 1.0])
    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Comparison saved → {out_path}")

plot_laue_stack_spots

plot_laue_stack_spots(spots, *, space: str = 'angles', n_label: int = 5, size_scale: float = 80.0, min_size: float = 8.0, show_divergence: bool = True, divergence_nsigma: float = 2.0, image=None, log_scale: bool = True, image_alpha: float = 0.6, figsize=(9, 7), ax=None, out_path: str | None = 'laue_stack_spots.png')

Visualise the spot table from :func:~nrxrdct.laue.simulate_laue_stack.

Each phase (unique phase_label) gets a distinct marker shape. Within a phase, the marker colour encodes the satellite / fringe order:

  • satellite_order = 0 — Bragg peak: brightest colour of the phase palette.
  • satellite_order = ±m — fringe / superlattice satellite: progressively darker / more saturated shades along the same palette (negative and positive orders share the same colour sequence, distinguished by the legend).

Marker size scales with normalised intensity.

Parameters:
  • spots (list[dict]) –

    Spot list returned by :func:~nrxrdct.laue.simulate_laue_stack. Required keys: 'phase_label', 'satellite_order', 'tth', 'chi', 'pix', 'intensity'.

  • space (`'angles'` | `'detector'`, default: 'angles' ) –

    Coordinate space to plot in.

  • n_label (int, default: 5 ) –

    Number of the strongest spots to annotate with (hkl) labels.

  • size_scale (float, default: 80.0 ) –

    Maximum marker area (s kwarg in ax.scatter).

  • min_size (float, default: 8.0 ) –

    Minimum marker area so that weak spots remain visible.

  • show_divergence (bool, default: True ) –

    When True (default), draw a divergence-broadening ellipse around each spot that carries the keys added by :func:~nrxrdct.laue.beam_divergence_ellipses. Ellipses are shown at the divergence_nsigma-σ confidence level. No ellipses are drawn for spots with zero broadening (i.e. when the simulation was run without divergence parameters).

  • divergence_nsigma (float, default: 2.0 ) –

    Size of the drawn ellipse in units of σ. Default 2.0 (≈ 86 % enclosed probability in 2-D).

  • image (ndarray of shape (Nv, Nh) or None, default: None ) –

    Raw detector image shown as a background. Only used when space='detector'. None → no background.

  • log_scale (bool, default: True ) –

    Apply logarithmic normalisation to image before display. Default True.

  • image_alpha (float, default: 0.6 ) –

    Opacity of the background image. Default 0.6.

  • figsize ((float, float), default: (9, 7) ) –

    Figure size in inches (ignored if ax is supplied).

  • ax (Axes, default: None ) –

    Draw into an existing Axes; if None a new figure is created.

  • out_path (str or None, default: 'laue_stack_spots.png' ) –

    Save the figure to this path. None → do not save.

Returns:
  • fig( Figure ) –
  • ax( Axes ) –
Source code in src/nrxrdct/laue/laue_plotting.py
def plot_laue_stack_spots(
    spots,
    *,
    space: str = "angles",
    n_label: int = 5,
    size_scale: float = 80.0,
    min_size: float = 8.0,
    show_divergence: bool = True,
    divergence_nsigma: float = 2.0,
    image=None,
    log_scale: bool = True,
    image_alpha: float = 0.6,
    figsize=(9, 7),
    ax=None,
    out_path: str | None = "laue_stack_spots.png",
):
    """
    Visualise the spot table from :func:`~nrxrdct.laue.simulate_laue_stack`.

    Each phase (unique `phase_label`) gets a distinct **marker shape**.
    Within a phase, the **marker colour** encodes the satellite / fringe order:

    * `satellite_order = 0`   — Bragg peak:  brightest colour of the phase palette.
    * `satellite_order = ±m`  — fringe / superlattice satellite:  progressively
      darker / more saturated shades along the same palette (negative and positive
      orders share the same colour sequence, distinguished by the legend).

    Marker *size* scales with normalised intensity.

    Args:
        spots (list[dict]): Spot list returned by :func:`~nrxrdct.laue.simulate_laue_stack`.
            Required keys: `'phase_label'`, `'satellite_order'`, `'tth'`,
            `'chi'`, `'pix'`, `'intensity'`.
        space (`'angles'` | `'detector'`): Coordinate space to plot in.

        * `'angles'`   — x = 2θ (°), y = χ (°).
        * `'detector'` — x = column pixel, y = row pixel.
        n_label (int): Number of the strongest spots to annotate with `(hkl)` labels.
        size_scale (float): Maximum marker area (`s` kwarg in `ax.scatter`).
        min_size (float): Minimum marker area so that weak spots remain visible.
        show_divergence (bool): When `True` (default), draw a divergence-broadening ellipse around
            each spot that carries the keys added by
            :func:`~nrxrdct.laue.beam_divergence_ellipses`.  Ellipses are shown
            at the `divergence_nsigma`-σ confidence level.  No ellipses are
            drawn for spots with zero broadening (i.e. when the simulation was
            run without divergence parameters).
        divergence_nsigma (float): Size of the drawn ellipse in units of σ.  Default `2.0` (≈ 86 %
            enclosed probability in 2-D).
        image (ndarray of shape (Nv, Nh) or None): Raw detector image shown as a background.
            Only used when `space='detector'`.  `None` → no background.
        log_scale (bool): Apply logarithmic normalisation to *image* before display.
            Default `True`.
        image_alpha (float): Opacity of the background image.  Default `0.6`.
        figsize ((float, float)): Figure size in inches (ignored if *ax* is supplied).
        ax (matplotlib.axes.Axes, optional): Draw into an existing Axes; if *None* a new figure is created.
        out_path (str or None): Save the figure to this path.  `None` → do not save.

    Returns:
        fig (matplotlib.figure.Figure):
        ax (matplotlib.axes.Axes):
"""
    if not spots:
        raise ValueError("spots list is empty")

    standalone = ax is None
    if standalone:
        fig, ax = plt.subplots(figsize=figsize)
        fig.patch.set_facecolor(BG)
    else:
        fig = ax.figure

    ax.set_facecolor(BG)
    ax.tick_params(colors="#7788aa", labelsize=7)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")

    # ── Coordinate helper ─────────────────────────────────────────────────────
    def _xy(s):
        if space == "angles":
            return float(s["tth"]), float(s["chi"])
        pix = s.get("pix")
        if pix is None:
            return None, None
        return float(pix[0]), float(pix[1])

    # ── Gather phase / order metadata ─────────────────────────────────────────
    # Preserve insertion order (phase order as they appear in the spot list)
    phases = list(dict.fromkeys(s["phase_label"] for s in spots))
    all_orders = sorted({s["satellite_order"] for s in spots})

    phase_marker = {ph: _PHASE_MARKERS[i % len(_PHASE_MARKERS)]
                    for i, ph in enumerate(phases)}

    # Build colour lookup: (phase, order) → RGBA
    # For each phase use a sequential palette; index 0 = Bragg, higher = fringes.
    # Negative and positive orders with the same |m| share the same colour so
    # that the legend stays compact.
    abs_orders_sorted = sorted({abs(m) for m in all_orders})

    def _phase_color(phase_idx, abs_order):
        """Map phase + |satellite_order| → colour from the phase palette."""
        cmap_name = _PHASE_PALETTES[phase_idx % len(_PHASE_PALETTES)]
        cmap_fn = plt.get_cmap(cmap_name)
        n = len(abs_orders_sorted)
        if n == 1:
            # Only one level → use brightest (low value in _r maps)
            return cmap_fn(0.15)
        # Map index 0 → 0.15 (bright), index n-1 → 0.85 (dark/saturated)
        idx = abs_orders_sorted.index(abs_order)
        t = 0.15 + 0.70 * idx / (n - 1)
        return cmap_fn(t)

    phase_order_color = {
        (ph, abs_m): _phase_color(i, abs_m)
        for i, ph in enumerate(phases)
        for abs_m in abs_orders_sorted
    }

    # ── Background detector image ─────────────────────────────────────────────
    if image is not None and space == "detector":
        img = np.asarray(image, dtype=float)
        if log_scale:
            vmin = max(img[img > 0].min(), 1.0) if np.any(img > 0) else 1.0
            norm_img = mcolors.LogNorm(vmin=vmin, vmax=img.max())
        else:
            norm_img = mcolors.Normalize(vmin=img.min(), vmax=img.max())
        ax.imshow(
            img,
            origin="upper",
            cmap="inferno",
            norm=norm_img,
            aspect="equal",
            interpolation="nearest",
            alpha=image_alpha,
            zorder=1,
        )

    # ── Plot ──────────────────────────────────────────────────────────────────
    # Group by (phase, satellite_order) so each group is one scatter call
    from collections import defaultdict
    groups = defaultdict(list)
    for s in spots:
        xy = _xy(s)
        if xy[0] is None:
            continue
        groups[(s["phase_label"], s["satellite_order"])].append((xy, s))

    for (phase, order), members in sorted(groups.items(),
                                          key=lambda kv: (phases.index(kv[0][0]),
                                                          kv[0][1])):
        xs = [m[0][0] for m in members]
        ys = [m[0][1] for m in members]
        sizes = [max(min_size, size_scale * m[1]["intensity"]) for m in members]
        marker = phase_marker[phase]
        color = phase_order_color[(phase, abs(order))]
        ax.scatter(xs, ys, s=sizes, c=[color], marker=marker,
                   linewidths=0.4, edgecolors="white", alpha=0.90, zorder=3)

    # ── Divergence ellipses ───────────────────────────────────────────────────
    valid = [s for s in spots if _xy(s)[0] is not None]
    if show_divergence:
        frame = "tth_chi" if space == "angles" else "detector"
        div_spots, div_xs, div_ys = [], [], []
        for s in valid:
            x, y = _xy(s)
            if x is not None:
                div_spots.append(s)
                div_xs.append(x)
                div_ys.append(y)
        if div_spots:
            cols = [phase_order_color[(s["phase_label"], abs(s["satellite_order"]))]
                    for s in div_spots]
            _draw_divergence_ellipses(ax, div_spots,
                                      np.array(div_xs), np.array(div_ys),
                                      frame, divergence_nsigma, cols)

    # ── Annotate strongest spots ───────────────────────────────────────────────
    top_n = sorted(valid, key=lambda s: s["intensity"], reverse=True)[:n_label]
    for s in top_n:
        x, y = _xy(s)
        h, k, l = s["hkl"]
        m = s["satellite_order"]
        lbl = f"({h}{k}{l})" if m == 0 else f"({h}{k}{l})\nm={m:+d}"
        ax.text(x + 0.1, y + 0.1, lbl, color=FG, fontsize=6, va="bottom",
                zorder=5)

    # ── Legend ────────────────────────────────────────────────────────────────
    legend_handles = []

    # Phase markers (shape legend)
    for ph in phases:
        c = phase_order_color[(ph, 0)]          # Bragg colour for this phase
        h = Line2D([0], [0], linestyle="none", marker=phase_marker[ph],
                   color=c, markeredgecolor="white", markeredgewidth=0.5,
                   markersize=7, label=ph)
        legend_handles.append(h)

    # Satellite-order colours (shared across all phases; use phase 0 colours)
    ph0 = phases[0]
    for abs_m in abs_orders_sorted:
        if abs_m == 0:
            lbl = "Bragg  (m=0)"
        elif abs_m == 1:
            lbl = "satellite  m=±1"
        else:
            lbl = f"satellite  m=±{abs_m}"
        c = phase_order_color[(ph0, abs_m)]
        h = Line2D([0], [0], linestyle="none", marker="o",
                   color=c, markeredgecolor="white", markeredgewidth=0.5,
                   markersize=7, label=lbl)
        legend_handles.append(h)

    ax.legend(
        handles=legend_handles, loc="upper right", fontsize=7.5,
        framealpha=0.5, facecolor="#1a1f2e", edgecolor="#3a3f4e",
        labelcolor=FG, handlelength=1.0, handleheight=1.0,
        title="phase  /  order", title_fontsize=7.5,
    )

    # ── Axis labels & title ───────────────────────────────────────────────────
    if space == "angles":
        ax.set_xlabel("2θ  (°)", color="#7788aa", fontsize=8)
        ax.set_ylabel("χ  (°)", color="#7788aa", fontsize=8)
    else:
        ax.set_xlabel("column  (px)", color="#7788aa", fontsize=8)
        ax.set_ylabel("row  (px)", color="#7788aa", fontsize=8)

    n_phases = len(phases)
    n_sats = len([m for m in all_orders if m != 0])
    ax.set_title(
        f"Laue stack — {n_phases} phase{'s' if n_phases != 1 else ''}  |  "
        f"{len(valid)} spots  |  {n_sats} satellite orders",
        color=FG, fontsize=9, pad=6,
    )

    if standalone:
        fig.tight_layout()
    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Stack spot map saved → {out_path}")
    if standalone:
        _force_draw(fig)
    return fig, ax

plot_layer_contributions

plot_layer_contributions(spots, stack, camera, space='detector', image=None, out_path=None)

Visualise per-layer intensity contributions, either across the detector image or in 2theta/chi space.

Produces a figure with one scatter panel per layer, coloured by each layer's fractional intensity contribution at that spot position, plus a summary panel showing the dominant-layer map and a bar chart of mean per-layer contribution. All position panels (per-layer + dominant-layer) share their x/y axes, and the panel grid is laid out as close to square as possible for the number of layers.

Parameters:
  • spots (list of dicts from `layer_contributions_spots()`) –
  • stack (LayeredCrystal) –
  • camera (Camera) –
  • space –

    {'detector', 'angular'}, optional Coordinate system for the position panels. 'detector' (default) plots detector pixel position (col vs row). 'angular' plots 2theta vs chi (2θ on x, χ on y -- LaueTools .cor file convention).

  • image (ndarray of shape (Nv, Nh) or None, default: None ) –

    Optional raw/rendered detector image (e.g. from camera.render() or a real measured frame) shown as a dimmed background on every position panel, log-normalised with the 'inferno' colormap -- same convention as :func:plot_measured_vs_simulated. Only used when space='detector'; ignored (with a note printed) for space='angular'.

  • out_path (str, default: None ) –

    Save figure to this path if provided. If None (default), the figure is not saved to disk.

Returns:
  • –

    fig

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_layer_contributions(
    spots,
    stack,
    camera,
    space="detector",
    image=None,
    out_path=None,
):
    """
    Visualise per-layer intensity contributions, either across the detector
    image or in 2theta/chi space.

    Produces a figure with one scatter panel per layer, coloured by each
    layer's fractional intensity contribution at that spot position, plus a
    summary panel showing the dominant-layer map and a bar chart of mean
    per-layer contribution. All position panels (per-layer + dominant-layer)
    share their x/y axes, and the panel grid is laid out as close to square
    as possible for the number of layers.

    Args:
        spots (list of dicts from `layer_contributions_spots()`):
        stack (LayeredCrystal):
        camera (Camera):
        space : {'detector', 'angular'}, optional
            Coordinate system for the position panels. `'detector'`
            (default) plots detector pixel position (col vs row).
            `'angular'` plots 2theta vs chi (2θ on x, χ on y -- LaueTools
            `.cor` file convention).
        image (ndarray of shape (Nv, Nh) or None): Optional raw/rendered detector image (e.g. from `camera.render()`
            or a real measured frame) shown as a dimmed background on every
            position panel, log-normalised with the `'inferno'` colormap --
            same convention as :func:`plot_measured_vs_simulated`. Only
            used when `space='detector'`; ignored (with a note printed)
            for `space='angular'`.
        out_path (str, optional): Save figure to this path if provided.  If
            `None` (default), the figure is not saved to disk.

    Returns:
        fig
"""
    import matplotlib.colors as mcolors
    import matplotlib.gridspec as mgridspec
    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.lines import Line2D

    if space not in ("detector", "angular"):
        raise ValueError(f"space must be 'detector' or 'angular', got {space!r}")

    img_arr, img_norm = None, None
    if image is not None:
        if space != "detector":
            print("  Note: `image` is only drawn for space='detector'; ignored for 'angular'.")
        else:
            img_arr = np.asarray(image, dtype=float)
            if img_arr.shape != (camera.Nv, camera.Nh):
                raise ValueError(
                    f"image shape {img_arr.shape} does not match "
                    f"(camera.Nv, camera.Nh) = {(camera.Nv, camera.Nh)}"
                )
            vmin = max(img_arr[img_arr > 0].min(), 1.0) if np.any(img_arr > 0) else 1.0
            img_norm = mcolors.LogNorm(vmin=vmin, vmax=img_arr.max())

    if not spots or "layer_I_frac" not in spots[0]:
        raise ValueError("Call layer_contributions_spots(spots, stack) first.")

    # De-duplicated, first-seen order: a label can legitimately appear on
    # more than one Layer object (e.g. the same material reused across two
    # different repeating blocks), but layer_contributions_spots() already
    # merges those into a single layer_I_frac[label] entry -- one panel per
    # label, not per Layer instance.
    labels = list(dict.fromkeys(layer.label for layer in stack.layers))
    n_layers = len(labels)

    # Layer colours
    layer_cols = [
        "#4fc3f7",
        "#ff9f43",
        "#ff6b6b",
        "#a29bfe",
        "#55efc4",
        "#fd79a8",
        "#fdcb6e",
    ][:n_layers]

    BG = "#080c14"

    # ── Position-panel coordinate system ────────────────────────────────────
    if space == "detector":
        Nh, Nv = camera.Nh, camera.Nv
        xlim, ylim = (0, Nh), (Nv, 0)
        xlabel, ylabel = "col", "row"

        def get_xy(s):
            return s["pix"][0], s["pix"][1]

    else:
        tths_all = [s["tth"] for s in spots]
        chis_all = [s["chi"] for s in spots]
        xlim = (min(tths_all) - 3, max(tths_all) + 3) if tths_all else (60, 130)
        ylim = (min(chis_all) - 3, max(chis_all) + 3) if chis_all else (-50, 50)
        xlabel, ylabel = "2theta (deg)", "chi (deg)"

        def get_xy(s):
            return s["tth"], s["chi"]

    def style_position_ax(ax, title, title_color):
        ax.set_facecolor("#04060e")
        ax.set_xlim(*xlim)
        ax.set_ylim(*ylim)
        ax.set_title(title, color=title_color, fontsize=8, pad=4)
        ax.set_xlabel(xlabel, color="#7788aa", fontsize=6)
        ax.set_ylabel(ylabel, color="#7788aa", fontsize=6)
        ax.tick_params(colors="#7788aa", labelsize=5)
        for sp in ax.spines.values():
            sp.set_edgecolor("#1a1f2e")
        if space == "angular":
            ax.grid(True, ls=":", lw=0.3, color="#181e2e")
            ax.axhline(0, color="#222244", lw=0.5)
        if img_arr is not None:
            ax.imshow(
                img_arr,
                origin="upper",
                cmap="inferno",
                norm=img_norm,
                aspect="auto",
                interpolation="antialiased",
                filternorm=True,
                alpha=0.6,
                zorder=1,
            )

    # ── Squarish grid layout: n_layers position panels + dominant-layer
    # summary + bar chart ────────────────────────────────────────────────────
    n_slots = n_layers + 2
    ncols = int(np.ceil(np.sqrt(n_slots)))
    nrows = int(np.ceil(n_slots / ncols))

    fig = plt.figure(figsize=(4.6 * ncols, 4.2 * nrows))
    fig.patch.set_facecolor(BG)

    gs = mgridspec.GridSpec(
        nrows,
        ncols,
        hspace=0.4,
        wspace=0.3,
        left=0.04,
        right=0.97,
        top=0.90,
        bottom=0.06,
    )

    def slot(i, **kw):
        r, c = divmod(i, ncols)
        return fig.add_subplot(gs[r, c], **kw)

    # ── Per-layer position panels (sharex/sharey linked) ────────────────────
    shared_ax = None
    for li, (label, col) in enumerate(zip(labels, layer_cols)):
        ax = slot(li, sharex=shared_ax, sharey=shared_ax)
        shared_ax = shared_ax or ax
        style_position_ax(ax, label, col)

        sel = [s for s in spots if label in s.get("layer_I_frac", {})]
        if sel:
            xs, ys = zip(*(get_xy(s) for s in sel))
            cs = [max(-1, min(1, s["layer_I_frac"][label])) for s in sel]
            sz = [max(2, 40 * s["intensity"] ** 0.4) for s in sel]
            sc = ax.scatter(
                xs,
                ys,
                s=sz,
                c=cs,
                cmap="RdYlGn",
                vmin=-0.2,
                vmax=1.0,
                alpha=0.85,
                edgecolors="none",
                zorder=3,
            )
            cbar = plt.colorbar(sc, ax=ax, fraction=0.04, pad=0.02)
            cbar.set_label("I_frac", color="#7788aa", fontsize=5)
            cbar.ax.tick_params(colors="#7788aa", labelsize=5)

        if space == "detector":
            CC, RR, TTH = camera.tth_grid(step=max(1, Nh // 15))
            tc, _ = camera.pixel_to_2theta_chi(camera.xcen, camera.ycen)
            lvls = [tc - 20, tc, tc + 20]
            lvls = [l for l in lvls if TTH.min() < l < TTH.max()]
            if lvls:
                ax.contour(
                    CC, RR, TTH, levels=lvls, colors="#1a2a3a", linewidths=0.5, alpha=0.6
                )

    # ── Dominant-layer summary panel (same shared axes) ─────────────────────
    ax_dom = slot(n_layers, sharex=shared_ax, sharey=shared_ax)
    style_position_ax(ax_dom, "Dominant layer", "#ccccee")

    for s in spots:
        if "layer_I_frac" not in s:
            continue
        dom_idx = max(
            range(n_layers), key=lambda i: s["layer_I_frac"].get(labels[i], -np.inf)
        )
        col = layer_cols[dom_idx]
        sz = max(2, 50 * s["intensity"] ** 0.4)
        x, y = get_xy(s)
        ax_dom.scatter(x, y, s=sz, color=col, alpha=0.8, edgecolors="none", zorder=3)

    leg = [
        Line2D([0], [0], marker="o", lw=0, mfc=layer_cols[i], ms=6, label=labels[i])
        for i in range(n_layers)
    ]
    ax_dom.legend(
        handles=leg,
        fontsize=5.5,
        framealpha=0.25,
        facecolor=BG,
        labelcolor="white",
        loc="upper right",
    )

    # ── Bar chart: mean intensity fraction per layer (own axes) ─────────────
    ax_bar = slot(n_layers + 1)
    ax_bar.set_facecolor("#04060e")
    for sp in ax_bar.spines.values():
        sp.set_edgecolor("#1a1f2e")
    ax_bar.tick_params(colors="#7788aa", labelsize=7)

    avg_fracs = {}
    for label in labels:
        fracs = [s["layer_I_frac"].get(label, 0) for s in spots if "layer_I_frac" in s]
        avg_fracs[label] = np.mean(fracs) * 100 if fracs else 0.0

    ax_bar.barh(labels, [avg_fracs[l] for l in labels], color=layer_cols, alpha=0.8)
    ax_bar.axvline(0, color="#555566", lw=0.7)
    ax_bar.set_xlabel("Mean intensity fraction (%)", color="#7788aa", fontsize=7)
    ax_bar.set_title("Mean layer contribution", color="#ccccee", fontsize=8, pad=4)

    # ── Hide unused trailing grid slots ──────────────────────────────────────
    for i in range(n_slots, nrows * ncols):
        slot(i).axis("off")

    # ── Title ─────────────────────────────────────────────────────────────────
    fig.text(
        0.5,
        0.96,
        f"Per-layer intensity decomposition ({space})  |  {stack.name}  |  "
        f"{len(spots)} spots  |  total thickness {stack.total_thickness / 1e4:.3f} µm",
        ha="center",
        fontsize=10,
        color="white",
        fontweight="bold",
    )

    if out_path is not None:
        plt.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Figure -> {out_path}")
    _force_draw(fig)
    return fig

plot_layer_scheme

plot_layer_scheme(stack, figsize=(10, 7), layer_width=10, max_reps=6, min_display_frac=0.01, ax=None, out_path=None)

Render a schematic cross-section of a LayeredCrystal stack oriented in the LaueTools lab frame (x = beam direction, z = vertical up).

The view is the XZ side-plane. Each layer is drawn as a scaled parallelogram whose normal is stack.n_hat projected onto XZ. Layers too thin to label inside (< min_display_frac of total height) are annotated with an external callout.

Buffer layers are drawn at the bottom at a fixed display height (they're usually far thicker than everything else and are flagged "not to scale"). Every repeating block (see stack.blocks / :meth:LayeredCrystal.add_layer) is drawn above them in sequence, each at real relative scale, with a dashed boundary line between the buffer section and the first block and between consecutive blocks. Every repetition of a block is still drawn as its own coloured slab, but gets exactly one text label for the whole block (its layer name(s), period, and repeat count), centred on the block's full drawn span -- with n_rep in the tens, labelling every repetition individually would be unreadable.

Parameters:
  • stack (LayeredCrystal) –
  • figsize ((float, float), default: (10, 7) ) –
  • layer_width (float, default: 10 ) –

    Half-width of the layer slabs in display units.

  • max_reps (int, default: 6 ) –

    Maximum number of repetitions to draw per block. Blocks with more repetitions than this show an ellipsis annotation at their own top boundary.

  • min_display_frac (float, default: 0.01 ) –

    Layers thinner than this fraction of the drawn stack height have their label placed outside with a leader line instead of inside.

  • ax (matplotlib Axes, default: None ) –

    Draw into an existing Axes. If None a new figure is created.

  • out_path (str, default: None ) –

    Save figure to this path if provided.

Returns:
  • –

    fig, ax

Source code in src/nrxrdct/laue/laue_plotting.py
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
def plot_layer_scheme(
    stack,
    figsize=(10, 7),
    layer_width=10,
    max_reps=6,
    min_display_frac=0.01,
    ax=None,
    out_path=None,
):
    """
    Render a schematic cross-section of a LayeredCrystal stack oriented in
    the LaueTools lab frame (x = beam direction, z = vertical up).

    The view is the XZ side-plane.  Each layer is drawn as a scaled
    parallelogram whose normal is `stack.n_hat` projected onto XZ.
    Layers too thin to label inside (< `min_display_frac` of total height)
    are annotated with an external callout.

    Buffer layers are drawn at the bottom at a fixed display height (they're
    usually far thicker than everything else and are flagged "not to
    scale"). Every repeating block (see `stack.blocks` /
    :meth:`LayeredCrystal.add_layer`) is drawn above them in sequence, each
    at real relative scale, with a dashed boundary line between the buffer
    section and the first block and between consecutive blocks. Every
    repetition of a block is still drawn as its own coloured slab, but gets
    exactly *one* text label for the whole block (its layer name(s), period,
    and repeat count), centred on the block's full drawn span -- with
    `n_rep` in the tens, labelling every repetition individually would be
    unreadable.

    Args:
        stack (LayeredCrystal):
        figsize ((float, float)):
        layer_width (float): Half-width of the layer slabs in display units.
        max_reps (int): Maximum number of repetitions to draw *per block*.  Blocks with
            more repetitions than this show an ellipsis annotation at their
            own top boundary.
        min_display_frac (float): Layers thinner than this fraction of the drawn stack height have
            their label placed outside with a leader line instead of inside.
        ax (matplotlib Axes, optional): Draw into an existing Axes.  If None a new figure is created.
        out_path (str, optional): Save figure to this path if provided.

    Returns:
        fig, ax
"""
    import matplotlib.patches as mpatches

    standalone = ax is None
    if standalone:
        fig, ax = plt.subplots(figsize=figsize, facecolor=BG)
    else:
        fig = ax.figure
    ax.set_facecolor(BG)

    # ── Stacking direction projected onto XZ ─────────────────────────────────
    nh = np.asarray(stack.n_hat, dtype=float)
    nh_2d = np.array([nh[0], nh[2]])           # (x, z) display components
    norm2d = np.linalg.norm(nh_2d)
    if norm2d < 1e-6:                           # n_hat purely along y
        nh_2d = np.array([0.0, 1.0])
    else:
        nh_2d /= norm2d
    th_2d = np.array([-nh_2d[1], nh_2d[0]])   # tangent ⊥ nh_2d in XZ

    # Text rotation matching the layer-dividing lines (which run along th_2d).
    # Folded into (-90, 90] so labels stay upright rather than appearing
    # upside-down for steeply tilted stacking directions.
    label_angle_deg = float(np.degrees(np.arctan2(th_2d[1], th_2d[0])))
    if label_angle_deg > 90:
        label_angle_deg -= 180
    elif label_angle_deg <= -90:
        label_angle_deg += 180

    # ── Build layer list (with repetitions) ──────────────────────────────────
    stack._update_offsets()
    blocks = [blk for blk in stack.blocks if blk.layers]
    has_rep = bool(blocks)
    has_buf = bool(stack.buffer_layers)

    if not has_rep and not has_buf:
        if standalone:
            _force_draw(fig)
            return fig, ax
        return ax

    # Repetition-limited drawn height of each block, in Å
    block_draw = []   # (block, n_reps_draw, drawn_thickness_ang)
    for blk in blocks:
        n_draw = min(blk.n_rep, max_reps)
        block_draw.append((blk, n_draw, n_draw * blk._period))
    total_rep_ang = sum(t for _, _, t in block_draw)

    # ── Scaling ───────────────────────────────────────────────────────────────
    DISP_H = 5.0   # display height reserved for the repeating section (display units)
    W      = layer_width

    if has_rep and total_rep_ang > 1e-9:
        scale = DISP_H / total_rep_ang          # Å → display units (repeating blocks only)
        # Buffer layers are drawn at a fixed height = thickest repeated layer,
        # shared across all blocks so buffer layers read consistently.
        max_rep_ang = max(lyr.thickness for blk, _, _ in block_draw for lyr in blk.layers)
        buf_disp_h  = max_rep_ang * scale
    else:
        # No repeating blocks — fall back to normal scaling for buffer-only stacks
        scale      = DISP_H / stack._buffer_thickness
        buf_disp_h = None   # use real thickness

    # ── Build (layer, s0_disp, s1_disp, is_buffer) list ───────────────────────
    # Display positions are computed independently for buffers (fixed height)
    # and repeating-block layers (real scale, shared across all blocks).
    # Every repetition of a block is drawn as its own coloured parallelogram,
    # but individual repetitions/sub-layers never get their own text -- with
    # n_rep in the tens that would be a wall of duplicate, overlapping
    # labels.  Instead each block gets exactly *one* label, centred on its
    # full drawn span (see `block_labels` below); only buffer layers (which
    # never repeat) keep their per-layer inline label.
    layers_to_draw = []      # (layer, s0, s1, is_buffer)
    boundary_lines = []      # display positions s where a dashed section boundary is drawn
    ellipsis_notes = []      # (s_position, text) for blocks clipped by max_reps
    block_labels = []        # (center_s, span_disp, text, color) -- one per block

    # Buffer layers stacked from z_disp=0, each at a fixed display height
    z_disp = 0.0
    for layer in stack.buffer_layers:
        h = buf_disp_h if buf_disp_h is not None else layer.thickness * scale
        layers_to_draw.append((layer, z_disp, z_disp + h, True))
        z_disp += h

    if has_buf and has_rep:
        boundary_lines.append(z_disp)   # buffer → first repeating block

    # Repeating blocks, each at real scale, stacked in sequence
    for bi, (blk, n_draw, _drawn_ang) in enumerate(block_draw):
        block_start_disp = z_disp
        for _rep in range(n_draw):
            for layer, z0_local in zip(blk.layers, blk._z_offsets):
                s0 = z_disp + z0_local * scale
                s1 = s0 + layer.thickness * scale
                layers_to_draw.append((layer, s0, s1, False))
            z_disp += blk._period * scale

        block_names = list(dict.fromkeys(lyr.label for lyr in blk.layers))
        period_nm = blk._period / 10.0
        block_text = (
            f"{' + '.join(block_names)}\n"
            f"{period_nm:.1f} nm period  ×{blk.n_rep}"
        )
        block_labels.append(
            # colour resolved below, once cmap exists -- store the label
            # name as a placeholder in its slot for now.
            [(block_start_disp + z_disp) * 0.5, z_disp - block_start_disp,
             block_text, blk.layers[0].label]
        )

        if blk.n_rep > max_reps:
            ellipsis_notes.append((z_disp, f"⋮  ({blk.n_rep} repetitions total)"))
        if bi < len(block_draw) - 1:
            boundary_lines.append(z_disp)   # this block → the next one

    total_disp_h = z_disp

    # ── Colour map (unique layer labels) ─────────────────────────────────────
    unique_labels = list(dict.fromkeys(t[0].label for t in layers_to_draw))
    palette = plt.cm.Set2(np.linspace(0.0, 0.85, max(len(unique_labels), 1)))
    cmap = {lbl: palette[i] for i, lbl in enumerate(unique_labels)}
    # Resolve each block label's representative colour now that cmap exists.
    block_labels = [
        (center, span, text, cmap[first_label])
        for center, span, text, first_label in block_labels
    ]

    # ── Draw section boundary markers (buffer→block and block→block) ─────────
    for s_bound in boundary_lines:
        pt_l = s_bound * nh_2d - W * th_2d
        pt_r = s_bound * nh_2d + W * th_2d
        ax.plot(
            [pt_l[0], pt_r[0]], [pt_l[1], pt_r[1]],
            color="#ffdd55", linewidth=1.8, linestyle="--", zorder=4,
        )

    # ── Draw layers ───────────────────────────────────────────────────────────
    callout_labels = []   # [(center_xy, text, color)] for thin-layer callouts

    for layer, s0, s1, is_buffer in layers_to_draw:
        color = cmap[layer.label]

        # Parallelogram corners in (x_display, z_display)
        c0 = s0 * nh_2d - W * th_2d
        c1 = s0 * nh_2d + W * th_2d
        c2 = s1 * nh_2d + W * th_2d
        c3 = s1 * nh_2d - W * th_2d
        edge_lw    = 1.2 if is_buffer else 0.7
        edge_color = "#ffdd55" if is_buffer else "white"
        poly = plt.Polygon(
            [c0, c1, c2, c3], closed=True,
            facecolor=color, edgecolor=edge_color, linewidth=edge_lw,
            alpha=0.88, zorder=2,
        )
        ax.add_patch(poly)

        if not is_buffer:
            # Repeating-block layers get one label for the whole block
            # (below), not one per individual layer/repetition.
            continue

        cx = ((s0 + s1) * 0.5) * nh_2d   # centre of parallelogram
        ds = s1 - s0
        thick_nm = layer.thickness / 10.0
        thick_um = layer.thickness / 1e4
        thick_str = f"{thick_um:.2f} µm" if thick_um >= 0.1 else f"{thick_nm:.1f} nm"
        label_str = f"{layer.label}  {thick_str}  (not to scale)"

        if ds >= min_display_frac * DISP_H:
            ax.text(
                cx[0], cx[1], label_str,
                ha="center", va="center", fontsize=7.5, fontweight="bold",
                rotation=label_angle_deg, rotation_mode="anchor",
                color="black", zorder=3, clip_on=True,
            )
        else:
            # Too thin to label inside — queue a callout
            callout_labels.append((cx, label_str, color))

    # ── One label per repeating block, centred on its full drawn span ────────
    for center_s, span_disp, block_text, block_color in block_labels:
        cx = center_s * nh_2d
        if span_disp >= min_display_frac * DISP_H:
            ax.text(
                cx[0], cx[1], block_text,
                ha="center", va="center", fontsize=7.5, fontweight="bold",
                rotation=label_angle_deg, rotation_mode="anchor",
                color="black", zorder=3, clip_on=True,
            )
        else:
            callout_labels.append((cx, block_text, block_color))

    # Callouts for thin layers (placed to the right of the stack)
    if callout_labels:
        right_edge = W * th_2d   # XZ vector to the right edge of the slab
        offset_step = 0.45
        for i, (cx, txt, col) in enumerate(callout_labels):
            tip   = cx + right_edge + np.array([0.15, 0.0])
            label_xy = tip + np.array([0.35 + i * 0.0, i * offset_step - len(callout_labels) * offset_step * 0.4])
            ax.annotate(
                txt,
                xy=tip, xytext=label_xy,
                fontsize=7, color="black", fontweight="bold",
                bbox=dict(boxstyle="round,pad=0.2", fc=col, ec="white", lw=0.5),
                arrowprops=dict(arrowstyle="-", color="white", lw=0.8),
                zorder=4,
            )

    # Clipped-reps markers -- one per block that exceeded max_reps
    for s_pos, text in ellipsis_notes:
        tip_pos = s_pos * nh_2d
        ax.text(
            tip_pos[0] + 0.05, tip_pos[1] + 0.12,
            text,
            color=FG, fontsize=8, va="bottom", zorder=4,
        )

    # ── Incident beam arrow ───────────────────────────────────────────────────
    # The beam (+x) hits the last layer (largest z0 = surface-facing end).
    surf_ctr  = total_disp_h * nh_2d
    beam_tip  = surf_ctr - 0.2 * nh_2d              # slightly inset
    beam_tail = beam_tip + np.array([-(W + 1.5), 0.0])   # start outside the slab
    ax.annotate(
        "", xy=beam_tip, xytext=beam_tail,
        arrowprops=dict(arrowstyle="->", color=COL_DB, lw=2.5, mutation_scale=20),
        zorder=5,
    )
    mid_beam = 0.5 * (beam_tip + beam_tail)
    ax.text(
        mid_beam[0], mid_beam[1] + 0.25,
        "incident beam  (+x)",
        color=COL_DB, fontsize=8, ha="center", va="bottom",
    )

    # ── Beam path inside sample (dashed red) ─────────────────────────────────
    beam_exit = beam_tip + np.array([2.0 * W, 0.0])
    ax.plot(
        [beam_tip[0], beam_exit[0]], [beam_tip[1], beam_exit[1]],
        color="red", lw=1.5, linestyle="--", zorder=4,
    )

    # ── Surface-normal arrow ──────────────────────────────────────────────────
    n_base = surf_ctr
    n_tip  = surf_ctr + 1.2 * nh_2d
    ax.annotate(
        "", xy=n_tip, xytext=n_base,
        arrowprops=dict(arrowstyle="->", color="white", lw=1.8, mutation_scale=12),
        zorder=5,
    )
    nh_label = (
        "n̂"
        f"  [{nh[0]:+.2f}, {nh[1]:+.2f}, {nh[2]:+.2f}]"
        "\n(stacking direction)"
    )
    ax.text(
        n_tip[0] + 0.1 * nh_2d[0],
        n_tip[1] + 0.12,
        nh_label,
        color="white", fontsize=8, ha="center", va="bottom",
    )

    # ── Surface / substrate edge labels ──────────────────────────────────────
    surf_edge_r = surf_ctr + (W + 0.12) * th_2d
    subs_edge_r = 0 * nh_2d + (W + 0.12) * th_2d
    ax.text(surf_edge_r[0], surf_edge_r[1], "surface ▶",
            color="white", fontsize=9.5, fontweight="bold", va="center", ha="left",
            rotation=label_angle_deg, rotation_mode="anchor")
    ax.text(subs_edge_r[0], subs_edge_r[1], "substrate ▶",
            color="white", fontsize=9.5, fontweight="bold", va="center", ha="left",
            rotation=label_angle_deg, rotation_mode="anchor")

    # ── Lab frame axes (bottom-left corner) ──────────────────────────────────
    ax_len  = 1.5
    # Find a comfortable lower-left position
    all_pts = np.array([s * nh_2d + sign * W * th_2d
                        for s in [0, total_disp_h]
                        for sign in [-1, 1]])
    x_min = all_pts[:, 0].min() - 4.0
    z_min = all_pts[:, 1].min() - 0.5
    orig  = np.array([x_min, z_min])

    def _axis_arrow(direction, color, label, label_offset):
        end = orig + ax_len * direction
        ax.annotate(
            "", xy=end, xytext=orig,
            arrowprops=dict(arrowstyle="->", color=color, lw=2.0, mutation_scale=16),
            zorder=6,
        )
        lp = end + label_offset
        ax.text(lp[0], lp[1], label, color=color, fontsize=9,
                fontweight="bold", ha="center", va="center")

    _axis_arrow(np.array([1.0, 0.0]), "#4fc3f7", "x\n(beam)",   np.array([0.45, 0.0]))
    _axis_arrow(np.array([0.0, 1.0]), "#ff9f43", "z\n(up)",     np.array([0.0,  0.45]))

    # y-axis: out-of-plane, shown as ⊙
    ax.plot(*orig, "o", color="#88cc88", ms=8, zorder=6)
    ax.plot(*orig, ".", color="#88cc88", ms=3, zorder=7)
    ax.text(orig[0] - 0.45, orig[1], "y\n(out)", color="#88cc88",
            fontsize=9, fontweight="bold", ha="center", va="center")

    # ── n_hat numeric annotation ──────────────────────────────────────────────
    nh_str = (f"n̂ = [{nh[0]:+.3f},  {nh[1]:+.3f},  {nh[2]:+.3f}]"
              + ("  (XZ projection)" if abs(nh[1]) > 1e-3 else ""))
    ax.text(
        0.5, 0.01, nh_str,
        transform=ax.transAxes, color="#8899bb", fontsize=8,
        ha="center", va="bottom",
    )

    # ── Legend ────────────────────────────────────────────────────────────────
    handles = [
        mpatches.Patch(facecolor=cmap[lbl], edgecolor="white", lw=0.5, label=lbl)
        for lbl in unique_labels
    ]
    ax.legend(
        handles=handles, loc="lower right", fontsize=8.5,
        framealpha=0.45, facecolor="#1a1f2e", edgecolor="#3a3f4e",
        labelcolor="white", handlelength=1.2, handleheight=0.9,
    )

    # ── Title ─────────────────────────────────────────────────────────────────
    total_um  = stack.total_thickness / 1e4
    n_clipped = sum(1 for blk, _, _ in block_draw if blk.n_rep > max_reps)
    reps_note = (f"  [{n_clipped} block(s) capped at {max_reps} reps for display]"
                 if n_clipped else "")
    ax.set_title(
        f"{stack.name}   —   total thickness {total_um:.3f} µm{reps_note}",
        color=FG, fontsize=9, pad=7,
    )

    # ── Final styling ─────────────────────────────────────────────────────────
    ax.set_aspect("equal")
    ax.axis("off")
    ax.autoscale_view()

    fig.patch.set_facecolor(BG)
    if standalone:
        fig.tight_layout()
    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Layer scheme saved → {out_path}")
    _force_draw(fig)
    return fig, ax

plot_measured_vs_simulated

plot_measured_vs_simulated(peaklist, spots, *, image=None, camera=None, n_label: int = 8, E_min_eV: float = 5000, E_max_eV: float = 27000, figsize: tuple = (14, 6), show_arrows: bool = True, max_match_dist: float = 50.0, out_path: str | None = None)

Side-by-side comparison of segmented measured spots and simulated Laue spots in detector pixel coordinates.

Parameters:
  • peaklist ((ndarray, shape(N, 9))) –

    Output of :func:~nrxrdct.laue.segmentation.convert_spotsfile2peaklist. Columns: peak_X (col), peak_Y (row), peak_I, peak_fwaxmaj, peak_fwaxmin, peak_inclination, Xdev, Ydev, peak_bkg.

  • spots (list of dict) –

    Output of :func:~nrxrdct.laue.simulation.simulate_laue or compatible functions. Each dict must contain 'pix' (col, row), 'E', 'intensity', and 'hkl'.

  • image (ndarray of shape (Nv, Nh) or None, default: None ) –

    Optional raw detector image shown as a background on both panels. Displayed with a logarithmic normalisation and the 'inferno' colormap.

  • camera (Camera or None, default: None ) –

    When provided, camera.Nh and camera.Nv are used to set fixed axis limits. If None, limits are derived from the data extent.

  • n_label (int, default: 8 ) –

    Number of strongest simulated spots to annotate with their (hkl) Miller indices on the right panel.

  • E_min_eV, E_max_eV (float) –

    Energy range for the simulated-spot colour scale (keV).

  • figsize (tuple of (float, float), default: (14, 6) ) –

    Figure size in inches passed to plt.subplots. Default (14, 6).

  • show_arrows (bool, default: True ) –

    When True (default), draw displacement arrows on the simulated panel from each simulated spot to its nearest measured spot. Arrows are coloured by displacement distance; a mean-displacement annotation and colour bar are added automatically.

  • max_match_dist (float, default: 50.0 ) –

    Maximum nearest-neighbour distance in pixels below which a simulated spot is matched to a measured spot and an arrow is drawn. Default 50.0 pixels.

  • out_path (str or None, default: None ) –

    Path to save the PNG figure. None (default) → do not save.

Returns:
  • fig( Figure ) –
Source code in src/nrxrdct/laue/laue_plotting.py
def plot_measured_vs_simulated(
    peaklist,
    spots,
    *,
    image=None,
    camera=None,
    n_label: int = 8,
    E_min_eV: float = 5_000,
    E_max_eV: float = 27_000,
    figsize: tuple = (14, 6),
    show_arrows: bool = True,
    max_match_dist: float = 50.0,
    out_path: str | None = None,
):
    """
    Side-by-side comparison of segmented measured spots and simulated Laue spots
    in detector pixel coordinates.

    Args:
        peaklist (ndarray, shape (N, 9)): Output of :func:`~nrxrdct.laue.segmentation.convert_spotsfile2peaklist`.
            Columns: peak_X (col), peak_Y (row), peak_I, peak_fwaxmaj, peak_fwaxmin,
            peak_inclination, Xdev, Ydev, peak_bkg.

        spots (list of dict): Output of :func:`~nrxrdct.laue.simulation.simulate_laue` or compatible
            functions.  Each dict must contain `'pix'` (col, row), `'E'`,
            `'intensity'`, and `'hkl'`.

        image (ndarray of shape (Nv, Nh) or None): Optional raw detector image shown as a background on both panels.
            Displayed with a logarithmic normalisation and the `'inferno'`
            colormap.

        camera (Camera or None): When provided, `camera.Nh` and `camera.Nv` are used to set fixed
            axis limits.  If `None`, limits are derived from the data extent.

        n_label (int): Number of strongest simulated spots to annotate with their (hkl) Miller
            indices on the right panel.

        E_min_eV, E_max_eV (float): Energy range for the simulated-spot colour scale (keV).

        figsize (tuple of (float, float)): Figure size in inches passed to `plt.subplots`.  Default `(14, 6)`.

        show_arrows (bool): When `True` (default), draw displacement arrows on the simulated panel
            from each simulated spot to its nearest measured spot.  Arrows are
            coloured by displacement distance; a mean-displacement annotation and
            colour bar are added automatically.

        max_match_dist (float): Maximum nearest-neighbour distance in pixels below which a simulated
            spot is matched to a measured spot and an arrow is drawn.
            Default `50.0` pixels.

        out_path (str or None): Path to save the PNG figure.  `None` (default) → do not save.

    Returns:
        fig (matplotlib.figure.Figure):
"""
    peaklist = np.asarray(peaklist, dtype=float)

    fig, (ax_m, ax_s) = plt.subplots(
        1, 2, figsize=figsize, sharex=True, sharey=True
    )
    fig.patch.set_facecolor(BG)

    for ax in (ax_m, ax_s):
        ax.set_facecolor(BG)
        ax.tick_params(colors="#7788aa", labelsize=6)
        for sp in ax.spines.values():
            sp.set_edgecolor("#1a1f2e")
        ax.set_xlabel("Column  (pixel)", color="#7788aa", fontsize=9)
        ax.set_ylabel("Row  (pixel)", color="#7788aa", fontsize=9)

    # ── background image (both panels) ───────────────────────────────────────
    if image is not None:
        img = np.asarray(image, dtype=float)
        vmin = max(img[img > 0].min(), 1.0) if np.any(img > 0) else 1.0
        norm_img = mcolors.LogNorm(vmin=vmin, vmax=img.max())
        for ax in (ax_m, ax_s):
            ax.imshow(
                img,
                origin="upper",
                cmap="inferno",
                norm=norm_img,
                aspect="equal",
                interpolation="nearest",
                alpha=0.6,
                zorder=1,
            )

    # ── measured spots (left panel) ──────────────────────────────────────────
    if peaklist.shape[0] > 0:
        col_m = peaklist[:, 0]
        row_m = peaklist[:, 1]
        I_m = peaklist[:, 2]
        I_pos = np.clip(I_m, 1e-6 * I_m.max() if I_m.max() > 0 else 1e-6, None)
        log_I = np.log10(I_pos)
        log_I_norm = (log_I - log_I.min()) / (log_I.max() - log_I.min() + 1e-12)
        sz_m = np.clip(20 + 200 * log_I_norm**0.4, 5, 300)
        sc_m = ax_m.scatter(
            col_m, row_m,
            s=sz_m,
            c=log_I_norm,
            cmap="viridis",
            vmin=0,
            vmax=1,
            alpha=0.85,
            marker="o",
            linewidths=0.3,
            edgecolors="#ffffff44",
            zorder=3,
        )
        cb_m = fig.colorbar(sc_m, ax=ax_m, pad=0.02, fraction=0.035, aspect=30)
        cb_m.set_label("log₁₀ intensity  (measured, normalised)", color="#7788aa", fontsize=7)
        cb_m.ax.tick_params(colors="#7788aa", labelsize=6)
        cb_m.outline.set_edgecolor("#1a1f2e")

    ax_m.set_title("Measured  (segmentation)", color=FG, fontsize=10, pad=6)

    # ── simulated spots (right panel) ────────────────────────────────────────
    valid = [s for s in spots if s.get("pix") is not None]
    if valid:
        E_norm = mcolors.Normalize(vmin=E_min_eV / 1e3, vmax=E_max_eV / 1e3)

        fund = [s for s in valid if not s.get("is_superlattice")]
        super_ = [s for s in valid if s.get("is_superlattice")]

        for subset, marker, alpha in [(fund, "o", 0.85), (super_, "*", 0.75)]:
            if not subset:
                continue
            col_s = [float(s["pix"][0]) for s in subset]
            row_s = [float(s["pix"][1]) for s in subset]
            Es = [s["E"] / 1e3 for s in subset]
            sz_s = [max(5, 90 * s["intensity"] ** 0.4) for s in subset]
            ax_s.scatter(
                col_s, row_s,
                s=sz_s,
                c=Es,
                cmap="plasma",
                norm=E_norm,
                alpha=alpha,
                marker=marker,
                linewidths=0.4,
                edgecolors="#ffffff33",
                zorder=3,
            )

        # colour bar for energy
        sm = plt.cm.ScalarMappable(cmap="plasma", norm=E_norm)
        sm.set_array([])
        cb_s = fig.colorbar(sm, ax=ax_s, pad=0.02, fraction=0.035, aspect=30)
        cb_s.set_label("E  (keV)  [simulated]", color="#7788aa", fontsize=7)
        cb_s.ax.tick_params(colors="#7788aa", labelsize=6)
        cb_s.outline.set_edgecolor("#1a1f2e")

        # HKL labels on n_label strongest fundamental spots
        top = sorted(fund, key=lambda s: -s["intensity"])[:n_label]
        for s in top:
            h, k, l = s["hkl"]
            ax_s.annotate(
                f"({h}{k}{l})",
                xy=(float(s["pix"][0]), float(s["pix"][1])),
                xytext=(3, 2),
                textcoords="offset points",
                fontsize=5.5,
                color="#aaddff",
                alpha=0.9,
                zorder=4,
            )

    ax_s.set_title("Simulated", color=FG, fontsize=10, pad=6)

    # ── displacement arrows: simulated → nearest measured ────────────────────
    if show_arrows and peaklist.shape[0] > 0 and valid:
        sim_xy = np.array([[float(s["pix"][0]), float(s["pix"][1])] for s in valid])
        meas_xy = peaklist[:, :2]  # (N_meas, 2): col, row

        # Brute-force nearest-neighbour
        diff = sim_xy[:, None, :] - meas_xy[None, :, :]  # (N_sim, N_meas, 2)
        dist_mat = np.linalg.norm(diff, axis=-1)          # (N_sim, N_meas)
        nn_idx = np.argmin(dist_mat, axis=1)               # (N_sim,)
        nn_dist = dist_mat[np.arange(len(sim_xy)), nn_idx] # (N_sim,)

        mask = nn_dist <= max_match_dist
        if mask.any():
            x0 = sim_xy[mask, 0]
            y0 = sim_xy[mask, 1]
            dx = meas_xy[nn_idx[mask], 0] - x0   # measured − simulated
            dy = meas_xy[nn_idx[mask], 1] - y0
            dists = nn_dist[mask]

            vmax_cb = float(np.percentile(dists, 95)) or 1.0
            dist_norm = mcolors.Normalize(vmin=0, vmax=vmax_cb)
            qv = ax_s.quiver(
                x0, y0, dx, dy, dists,
                cmap="RdYlGn_r",
                norm=dist_norm,
                angles="xy",
                scale_units="xy",
                scale=1,
                units="dots",
                width=2.0,
                headwidth=5,
                headlength=6,
                alpha=0.9,
                zorder=5,
            )
            cb_q = fig.colorbar(qv, ax=ax_s, pad=0.14, fraction=0.035, aspect=30)
            cb_q.set_label("Displacement  (pixel)", color="#7788aa", fontsize=7)
            cb_q.ax.tick_params(colors="#7788aa", labelsize=6)
            cb_q.outline.set_edgecolor("#1a1f2e")

            mean_d = dists.mean()
            ax_s.text(
                0.02, 0.02,
                f"mean Δ = {mean_d:.2f} px  (n={mask.sum()})",
                transform=ax_s.transAxes,
                color="#aaddff",
                fontsize=7,
                va="bottom",
                zorder=6,
            )

    # ── axis limits ──────────────────────────────────────────────────────────
    if camera is not None:
        for ax in (ax_m, ax_s):
            ax.set_xlim(0, camera.Nh)
            ax.set_ylim(camera.Nv, 0)   # rows increase downward
    else:
        # derive from data; rows still increase downward
        all_cols, all_rows = [], []
        if peaklist.shape[0] > 0:
            all_cols.extend(peaklist[:, 0].tolist())
            all_rows.extend(peaklist[:, 1].tolist())
        for s in valid:
            all_cols.append(float(s["pix"][0]))
            all_rows.append(float(s["pix"][1]))
        if all_cols:
            margin = 50
            c0, c1 = min(all_cols) - margin, max(all_cols) + margin
            r0, r1 = min(all_rows) - margin, max(all_rows) + margin
            for ax in (ax_m, ax_s):
                ax.set_xlim(c0, c1)
                ax.set_ylim(r1, r0)   # inverted

    fig.suptitle("Measured vs Simulated — detector space", color=FG, fontsize=11, y=1.01)
    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Measured-vs-simulated plot saved → {out_path}")

    _force_draw(fig)

    return fig

plot_multigrain

plot_multigrain(obs_xy: ndarray, spots_per_grain: list[list[dict]], camera, *, image: ndarray | None = None, match_px: float = 10.0, color_obs_by_grain: bool = True, figsize: tuple = (9, 8), out_path: str | None = None)

Overlay observed spots and per-grain simulations on the detector plane.

Each grain's simulated spots are drawn in a distinct colour; thin lines connect each simulated spot to its nearest observed counterpart (within match_px). When color_obs_by_grain is True the observed spots are also coloured by whichever grain's simulation is closest to them, giving an immediate visual assignment map.

Typical usage::

# simulate each grain after fit_orientation_mixed
spots_per_grain = [
    laue.simulate_laue(crystal, U, camera, f2_thresh=0.01)
    for U in result.U_phases
]
fig, ax = plot_multigrain(peaks[:, :2], spots_per_grain, camera)
Parameters:
  • obs_xy ((N, 2) array-like) –

    Observed pixel positions [xcam, ycam].

  • spots_per_grain (list of spot-lists) –

    One spot list per grain, each in the format returned by :func:~nrxrdct.laue.simulation.simulate_laue. Each spot dict must contain a 'pix' key (xcam, ycam).

  • camera (Camera) –

    Detector geometry; camera.Nh and camera.Nv set the axis limits.

  • image ((Nv, Nh) array or None, default: None ) –

    Optional raw detector image displayed as a log-scaled background.

  • match_px (float, default: 10.0 ) –

    Maximum pixel distance for drawing a match line between a simulated spot and its nearest observed spot. Default 10.0.

  • color_obs_by_grain (bool, default: True ) –

    When True (default), repaint each observed spot in the colour of its closest grain. Unmatched spots (all grains farther than match_px) are shown in white.

  • figsize ((float, float), default: (9, 8) ) –

    Figure size in inches.

  • out_path (str or None, default: None ) –

    If given, save the figure to this path at 150 dpi.

Returns:
  • fig( Figure ) –
  • ax( Axes ) –
Source code in src/nrxrdct/laue/laue_plotting.py
def plot_multigrain(
    obs_xy: "np.ndarray",
    spots_per_grain: "list[list[dict]]",
    camera,
    *,
    image: "np.ndarray | None" = None,
    match_px: float = 10.0,
    color_obs_by_grain: bool = True,
    figsize: tuple = (9, 8),
    out_path: "str | None" = None,
):
    """
    Overlay observed spots and per-grain simulations on the detector plane.

    Each grain's simulated spots are drawn in a distinct colour; thin lines
    connect each simulated spot to its nearest observed counterpart (within
    *match_px*).  When *color_obs_by_grain* is `True` the observed spots are
    also coloured by whichever grain's simulation is closest to them, giving an
    immediate visual assignment map.

    Typical usage::

        # simulate each grain after fit_orientation_mixed
        spots_per_grain = [
            laue.simulate_laue(crystal, U, camera, f2_thresh=0.01)
            for U in result.U_phases
        ]
        fig, ax = plot_multigrain(peaks[:, :2], spots_per_grain, camera)

    Args:
        obs_xy ((N, 2) array-like): Observed pixel positions `[xcam, ycam]`.
        spots_per_grain (list of spot-lists): One spot list per grain, each in the format returned by
            :func:`~nrxrdct.laue.simulation.simulate_laue`.
            Each spot dict must contain a `'pix'` key `(xcam, ycam)`.
        camera (Camera): Detector geometry; `camera.Nh` and `camera.Nv` set the axis limits.
        image ((Nv, Nh) array or None): Optional raw detector image displayed as a log-scaled background.
        match_px (float): Maximum pixel distance for drawing a match line between a simulated
            spot and its nearest observed spot.  Default `10.0`.
        color_obs_by_grain (bool): When `True` (default), repaint each observed spot in the colour of
            its closest grain.  Unmatched spots (all grains farther than
            *match_px*) are shown in white.
        figsize ((float, float)): Figure size in inches.
        out_path (str or None): If given, save the figure to this path at 150 dpi.

    Returns:
        fig (matplotlib.figure.Figure):
        ax (matplotlib.axes.Axes):
"""
    obs_xy = np.asarray(obs_xy, dtype=float)

    fig, ax = plt.subplots(figsize=figsize)
    fig.patch.set_facecolor(BG)
    ax.set_facecolor(BG)

    # ── optional background image ─────────────────────────────────────────────
    if image is not None:
        img = np.asarray(image, dtype=float)
        vmin = np.percentile(img, 1)
        ax.imshow(
            np.log1p(np.clip(img - vmin, 0, None)),
            origin="upper",
            cmap="inferno",
            extent=[0, camera.Nh, camera.Nv, 0],
            aspect="auto",
            interpolation="nearest",
            alpha=0.6,
            zorder=0,
        )

    # ── collect simulated xy arrays per grain ─────────────────────────────────
    sim_xys = []
    for spots in spots_per_grain:
        xy = np.array(
            [s["pix"] for s in spots if s.get("pix") is not None],
            dtype=float,
        )
        sim_xys.append(xy if len(xy) else np.empty((0, 2), dtype=float))

    # ── assign each observed spot to its closest grain ────────────────────────
    obs_grain = np.full(len(obs_xy), -1, dtype=int)   # -1 = unmatched
    if color_obs_by_grain and sim_xys:
        best_dist = np.full(len(obs_xy), np.inf)
        for gi, sxy in enumerate(sim_xys):
            if len(sxy) == 0:
                continue
            diff = obs_xy[:, None, :] - sxy[None, :, :]           # (N_obs, N_sim, 2)
            d = np.sqrt((diff ** 2).sum(axis=-1)).min(axis=1)      # (N_obs,)
            closer = d < best_dist
            best_dist = np.where(closer, d, best_dist)
            obs_grain = np.where(closer, gi, obs_grain)
        obs_grain[best_dist > match_px] = -1

    # ── draw observed spots ───────────────────────────────────────────────────
    unmatched = obs_grain == -1
    if unmatched.any():
        ax.scatter(
            obs_xy[unmatched, 0], obs_xy[unmatched, 1],
            s=40, facecolors="none", edgecolors="white", lw=0.8, zorder=2,
        )
    if color_obs_by_grain:
        for gi in range(len(spots_per_grain)):
            mask = obs_grain == gi
            if mask.any():
                ax.scatter(
                    obs_xy[mask, 0], obs_xy[mask, 1],
                    s=40, facecolors="none",
                    edgecolors=_GRAIN_COLORS[gi % len(_GRAIN_COLORS)],
                    lw=1.2, zorder=2,
                )

    # ── draw simulated spots + match lines per grain ──────────────────────────
    legend_handles = [
        Line2D(
            [0], [0], linestyle="none", marker="o", markersize=6,
            markerfacecolor="none", markeredgecolor="white", lw=0.8,
            label="observed",
        ),
    ]

    for gi, (spots, sxy) in enumerate(zip(spots_per_grain, sim_xys)):
        color = _GRAIN_COLORS[gi % len(_GRAIN_COLORS)]
        n_sim = len(sxy)
        if n_sim == 0:
            continue

        ax.scatter(sxy[:, 0], sxy[:, 1], s=80, marker="+",
                   color=color, lw=1.2, zorder=3)

        nn_dist = np.full(n_sim, np.inf)
        if len(obs_xy):
            diff = sxy[:, None, :] - obs_xy[None, :, :]           # (N_sim, N_obs, 2)
            dist = np.sqrt((diff ** 2).sum(axis=-1))               # (N_sim, N_obs)
            nn_idx = dist.argmin(axis=1)
            nn_dist = dist[np.arange(n_sim), nn_idx]
            for j in range(n_sim):
                if nn_dist[j] < match_px:
                    ox, oy = obs_xy[nn_idx[j]]
                    ax.plot([sxy[j, 0], ox], [sxy[j, 1], oy],
                            color=color, lw=0.5, alpha=0.4, zorder=1)

        n_matched = int((nn_dist < match_px).sum())
        rate = n_matched / max(n_sim, 1)
        legend_handles.append(
            Line2D(
                [0], [0], linestyle="none", marker="+", markersize=8,
                color=color, lw=1.2,
                label=f"grain {gi + 1}  ({n_matched}/{n_sim}, {rate:.0%})",
            )
        )

    # ── axes styling ──────────────────────────────────────────────────────────
    ax.set_xlim(0, camera.Nh)
    ax.set_ylim(camera.Nv, 0)
    ax.set_xlabel("xcam  (px)", color=FG, fontsize=8)
    ax.set_ylabel("ycam  (px)", color=FG, fontsize=8)
    ax.tick_params(colors="#7788aa", labelsize=7)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")
    ax.set_title(
        f"Multi-grain Laue  —  {len(spots_per_grain)} grain(s)",
        color=FG, fontsize=9, pad=5,
    )
    ax.legend(
        handles=legend_handles,
        facecolor="#1a1f2e", edgecolor="#3a3f4e",
        labelcolor=FG, fontsize=8, loc="upper right",
    )

    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

plot_pix_deviation

plot_pix_deviation(spots: list[dict], peaklist: ndarray, *, max_dist_px: float = 15.0, properties: list[str] | None = None, figsize: tuple[float, float] = (14, 10), out_path: str | None = None) -> tuple

Match simulated spots to measured peaks and plot pixel deviations as a function of spot properties.

Each simulated spot is paired with the nearest measured peak within max_dist_px pixels (Euclidean distance in detector pixel space). Unmatched spots are excluded. The deviation is defined as:

Δcol = sim_col − meas_col
Δrow = sim_row − meas_row
Parameters:
  • spots (list[dict]) –

    output of any simulate_laue_* function.

  • peaklist (ndarray) –

    (N, ≥2) array with columns [col, row, ...] (same format as :func:convert_spotsfile2peaklist).

  • max_dist_px (float, default: 15.0 ) –

    matching radius in pixels.

  • properties (list[str] | None, default: None ) –

    spot dict keys to plot against deviations. Default: ['E', 'tth', 'chi', 'intensity']. Any key present in the spot dicts is valid (e.g. 'az', 'lambda', 'source_depth_mm').

  • figsize (tuple[float, float], default: (14, 10) ) –

    figure size.

  • out_path (str | None, default: None ) –

    save path; None → do not save.

Returns:
  • tuple –

    (fig, axes, matched) where matched is a list of dicts with

  • tuple –

    keys 'spot', 'peak_idx', 'meas_col', 'meas_row',

  • tuple –

    'dx', 'dy', 'dist', 'phase'.

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_pix_deviation(
    spots: list[dict],
    peaklist: "np.ndarray",
    *,
    max_dist_px: float = 15.0,
    properties: list[str] | None = None,
    figsize: tuple[float, float] = (14, 10),
    out_path: "str | None" = None,
) -> tuple:
    """
    Match simulated spots to measured peaks and plot pixel deviations
    as a function of spot properties.

    Each simulated spot is paired with the nearest measured peak within
    *max_dist_px* pixels (Euclidean distance in detector pixel space).
    Unmatched spots are excluded.  The deviation is defined as:

        Δcol = sim_col − meas_col
        Δrow = sim_row − meas_row

    Args:
        spots: output of any ``simulate_laue_*`` function.
        peaklist: ``(N, ≥2)`` array with columns ``[col, row, ...]``
            (same format as :func:`convert_spotsfile2peaklist`).
        max_dist_px: matching radius in pixels.
        properties: spot dict keys to plot against deviations.
            Default: ``['E', 'tth', 'chi', 'intensity']``.
            Any key present in the spot dicts is valid (e.g.
            ``'az'``, ``'lambda'``, ``'source_depth_mm'``).
        figsize: figure size.
        out_path: save path; ``None`` → do not save.

    Returns:
        ``(fig, axes, matched)`` where *matched* is a list of dicts with
        keys ``'spot'``, ``'peak_idx'``, ``'meas_col'``, ``'meas_row'``,
        ``'dx'``, ``'dy'``, ``'dist'``, ``'phase'``.
    """
    from scipy.spatial import cKDTree

    if properties is None:
        properties = ["E", "tth", "chi", "intensity"]

    pl = np.asarray(peaklist, dtype=float)
    meas_xy = pl[:, :2]
    tree = cKDTree(meas_xy)

    matched: list[dict] = []
    for spot in spots:
        pix = spot.get("pix")
        if pix is None:
            continue
        sim_col, sim_row = float(pix[0]), float(pix[1])
        dist, idx = tree.query([sim_col, sim_row], k=1)
        if dist <= max_dist_px:
            matched.append({
                "spot":      spot,
                "peak_idx":  int(idx),
                "meas_col":  float(meas_xy[idx, 0]),
                "meas_row":  float(meas_xy[idx, 1]),
                "dx":        sim_col - float(meas_xy[idx, 0]),
                "dy":        sim_row - float(meas_xy[idx, 1]),
                "dist":      float(dist),
                "phase":     spot.get("phase_label", "unknown"),
            })

    if not matched:
        raise ValueError(
            f"No spots matched within {max_dist_px} px. "
            "Try increasing max_dist_px."
        )

    phases = list(dict.fromkeys(m["phase"] for m in matched))
    palette = plt.get_cmap("tab10")
    phase_color = {ph: palette(i % 10) for i, ph in enumerate(phases)}

    dx_all = np.array([m["dx"] for m in matched])
    dy_all = np.array([m["dy"] for m in matched])
    dist_all = np.sqrt(dx_all ** 2 + dy_all ** 2)
    med = float(np.median(dist_all))
    rms = float(np.sqrt(np.mean(dist_all ** 2)))

    # ── Layout: row 0 = 2D scatter + histogram; rows 1+ = 2 props per row ────
    n_props = len(properties)
    n_prop_rows = (n_props + 1) // 2   # ceil(n_props / 2)
    n_rows = 1 + n_prop_rows
    fig, axes = plt.subplots(n_rows, 2, figsize=figsize,
                             gridspec_kw={"hspace": 0.45, "wspace": 0.35})
    if n_rows == 1:
        axes = axes[np.newaxis, :]   # ensure 2D
    fig.patch.set_facecolor(BG)
    for ax in axes.flat:
        ax.set_facecolor(BG)
        ax.tick_params(colors=FG, labelsize=7)
        for sp in ax.spines.values():
            sp.set_edgecolor("#1a1f2e")

    # ── Row 0 left: 2D (Δcol, Δrow) scatter ──────────────────────────────────
    ax_2d = axes[0, 0]
    for ph in phases:
        ms = [m for m in matched if m["phase"] == ph]
        ax_2d.scatter(
            [m["dx"] for m in ms], [m["dy"] for m in ms],
            s=14, color=phase_color[ph], alpha=0.75, label=ph, zorder=3,
            edgecolors="none",
        )
    ax_2d.axhline(0, color=FG, lw=0.5, alpha=0.4)
    ax_2d.axvline(0, color=FG, lw=0.5, alpha=0.4)
    ax_2d.set_xlabel("Δcol  (px)", color=FG, fontsize=8)
    ax_2d.set_ylabel("Δrow  (px)", color=FG, fontsize=8)
    ax_2d.set_title("Sim − Meas  (2D)", color=FG, fontsize=8)
    ax_2d.set_aspect("equal")
    if len(phases) > 1:
        ax_2d.legend(fontsize=7, labelcolor=FG,
                     facecolor="#1a1f2e", edgecolor="#333355")

    # ── Row 0 right: |Δpix| histogram ────────────────────────────────────────
    ax_hist = axes[0, 1]
    ax_hist.hist(dist_all, bins=min(40, max(len(matched) // 2, 5)),
                 color="#4488cc", alpha=0.85, edgecolor="none")
    ax_hist.axvline(med, color="orange", lw=1, label=f"median {med:.2f} px")
    ax_hist.axvline(rms, color="#ee4444", lw=1, linestyle="--",
                    label=f"RMS {rms:.2f} px")
    ax_hist.set_xlabel("|Δpix|  (px)", color=FG, fontsize=8)
    ax_hist.set_ylabel("count", color=FG, fontsize=8)
    ax_hist.set_title(f"|Δpix| distribution  ({len(matched)} matched)",
                      color=FG, fontsize=8)
    ax_hist.legend(fontsize=7, labelcolor=FG,
                   facecolor="#1a1f2e", edgecolor="#333355")

    # ── Rows 1+: |Δpix| vs each property, 2 per row ──────────────────────────
    _labels = {
        "E":               "E  (keV)",
        "tth":             "2θ  (°)",
        "chi":             "χ  (°)",
        "az":              "az  (°)",
        "intensity":       "intensity  (norm.)",
        "lambda":          "λ  (Å)",
        "source_depth_mm": "depth  (mm)",
        "F2":              "F²",
    }
    _scale = {"E": 1e-3}

    for i, prop in enumerate(properties):
        row = 1 + i // 2
        col = i % 2
        ax = axes[row, col]
        xlabel = _labels.get(prop, prop)
        scale = _scale.get(prop, 1.0)

        for ph in phases:
            ms = [m for m in matched if m["phase"] == ph]
            vals = [m["spot"].get(prop, np.nan) * scale for m in ms]
            dists = [m["dist"] for m in ms]
            ax.scatter(vals, dists, s=10, color=phase_color[ph], alpha=0.7,
                       edgecolors="none", zorder=3, label=ph)

        ax.set_xlabel(xlabel, color=FG, fontsize=8)
        ax.set_ylabel("|Δpix|  (px)", color=FG, fontsize=8)
        if len(phases) > 1:
            ax.legend(fontsize=6, labelcolor=FG,
                      facecolor="#1a1f2e", edgecolor="#333355")

    # hide unused axes if n_props is odd
    if n_props % 2 == 1:
        axes[-1, -1].set_visible(False)

    fig.suptitle(
        f"Pixel deviation: simulation vs measurement  "
        f"({len(matched)} matched, max_dist={max_dist_px:.0f} px  |  "
        f"RMS={rms:.2f} px  |  median={med:.2f} px)",
        color=FG, fontsize=9, y=1.01,
    )

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())

    _force_draw(fig)
    return fig, axes, matched

plot_qspace_around_spot

plot_qspace_around_spot(vol: dict, *, log_intensity: bool = False, intensity_floor: float = 1e-06, show_window_surface: bool = True, show_off_detector: bool = True, elev: float = 22.0, azim: float = -60.0, figsize: tuple[float, float] = (9, 8), ax: Axes | None = None, out_path: str | None = None)

Render the 3-D reciprocal-space volume returned by :func:~nrxrdct.laue.simulation.qspace_around_spot and overlay the boundary of the accessible white-beam energy window, to show why some fringe/satellite points along the rod turn into detector spots and others don't.

Three things have to go right before a voxel of the reconstructed volume can appear as a spot on the detector image, and this plot makes all three visible at once:

  1. Structure-factor intensity — vol['I']. Destructive interference along the rod (finite-thickness fringes, superlattice satellites) drives some voxels to ~0 even though they are otherwise fully reachable. Encoded as marker colour + size (sequential warm ramp: near-black → orange → pale yellow, matching this project's existing satellite / direct-beam accent colours).
  2. Energy window — a voxel needs a photon energy inside [E_min_eV, E_max_eV] to be excited at all. Drawn as a translucent blue surface: the boundary where vol['reachable'] flips off. Rod points beyond this surface cannot appear on any detector, at any intensity, in this beam.
  3. Detector footprint — even within the energy window, the diffracted ray must land on the physical detector. Voxels that are reachable but off-detector (vol['on_detector'] == False) are drawn as small hollow markers instead of filled ones.
Parameters:
  • vol (dict) –

    Return value of :func:~nrxrdct.laue.simulation.qspace_around_spot.

  • log_intensity (bool, default: False ) –

    Colour/size by log10(I / I_max + floor) instead of the raw ratio. Structure-factor intensities span many orders of magnitude near a fringe minimum, so this is True by default.

  • intensity_floor (float, default: 1e-06 ) –

    Added (as a fraction of the volume's max intensity) before taking the log, so exact zeros stay finite.

  • show_window_surface (bool, default: True ) –

    Draw the translucent energy-window boundary surface. It is only drawn where the boundary actually falls inside the grid — a box entirely inside or entirely outside the window has no boundary to show (widen extent_along / max_satellites in qspace_around_spot to bring it into view).

  • show_off_detector (bool, default: True ) –

    Draw reachable-but-off-detector voxels as hollow markers. Has no effect if vol was built without a camera (no on/off-detector information exists in that case).

  • elev, azim –

    3-D view angle (degrees), forwarded to Axes3D.view_init.

  • figsize (tuple[float, float], default: (9, 8) ) –

    Figure size in inches (only used when ax is None).

  • ax (Axes | None, default: None ) –

    Draw into an existing 3-D :class:~matplotlib.axes.Axes (created with projection='3d'); None creates a new figure.

  • out_path (str | None, default: None ) –

    Save path; None → do not save.

Returns:
  • –

    (fig, ax)

Example:

vol = qspace_around_spot(stack, (0, 0, 2), camera=cam) plot_qspace_around_spot(vol, out_path="qspace_002.png")

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_qspace_around_spot(
    vol: dict,
    *,
    log_intensity: bool = False,
    intensity_floor: float = 1e-6,
    show_window_surface: bool = True,
    show_off_detector: bool = True,
    elev: float = 22.0,
    azim: float = -60.0,
    figsize: tuple[float, float] = (9, 8),
    ax: "plt.Axes | None" = None,
    out_path: "str | None" = None,
):
    """
    Render the 3-D reciprocal-space volume returned by
    :func:`~nrxrdct.laue.simulation.qspace_around_spot` and overlay the
    boundary of the accessible white-beam energy window, to show why some
    fringe/satellite points along the rod turn into detector spots and
    others don't.

    Three things have to go right before a voxel of the reconstructed
    volume can appear as a spot on the detector image, and this plot makes
    all three visible at once:

    1. **Structure-factor intensity** — `vol['I']`.  Destructive
       interference along the rod (finite-thickness fringes, superlattice
       satellites) drives some voxels to ~0 even though they are otherwise
       fully reachable.  Encoded as marker colour + size (sequential warm
       ramp: near-black → orange → pale yellow, matching this project's
       existing satellite / direct-beam accent colours).
    2. **Energy window** — a voxel needs a photon energy inside
       `[E_min_eV, E_max_eV]` to be excited at all.  Drawn as a translucent
       blue surface: the boundary where `vol['reachable']` flips off.  Rod
       points beyond this surface cannot appear on any detector, at any
       intensity, in this beam.
    3. **Detector footprint** — even within the energy window, the
       diffracted ray must land on the physical detector.  Voxels that are
       reachable but off-detector (`vol['on_detector'] == False`) are drawn
       as small hollow markers instead of filled ones.

    Args:
        vol: Return value of
            :func:`~nrxrdct.laue.simulation.qspace_around_spot`.
        log_intensity: Colour/size by `log10(I / I_max + floor)` instead of
            the raw ratio.  Structure-factor intensities span many orders
            of magnitude near a fringe minimum, so this is `True` by default.
        intensity_floor: Added (as a fraction of the volume's max
            intensity) before taking the log, so exact zeros stay finite.
        show_window_surface: Draw the translucent energy-window boundary
            surface.  It is only drawn where the boundary actually falls
            inside the grid — a box entirely inside or entirely outside the
            window has no boundary to show (widen `extent_along` /
            `max_satellites` in `qspace_around_spot` to bring it into view).
        show_off_detector: Draw reachable-but-off-detector voxels as hollow
            markers.  Has no effect if `vol` was built without a `camera`
            (no on/off-detector information exists in that case).
        elev, azim: 3-D view angle (degrees), forwarded to `Axes3D.view_init`.
        figsize: Figure size in inches (only used when `ax is None`).
        ax: Draw into an existing 3-D :class:`~matplotlib.axes.Axes`
            (created with `projection='3d'`); `None` creates a new figure.
        out_path: Save path; `None` → do not save.

    Returns:
        `(fig, ax)`

    Example:
    >>> vol = qspace_around_spot(stack, (0, 0, 2), camera=cam)
    >>> plot_qspace_around_spot(vol, out_path="qspace_002.png")
    """
    from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 — registers '3d' projection

    along = np.asarray(vol["along"])
    lat1 = np.asarray(vol["lateral1"])
    lat2 = np.asarray(vol["lateral2"])
    I = vol["I"]
    reachable = vol["reachable"]
    on_det = vol["on_detector"]
    shape = I.shape

    AA, T1, T2 = np.meshgrid(along, lat1, lat2, indexing="ij")

    # ── colour / size by intensity ────────────────────────────────────────────
    Imax = float(I.max()) if I.size and I.max() > 0 else 1.0
    if log_intensity:
        val = np.log10(I / Imax + intensity_floor)
        vmin, vmax = np.log10(intensity_floor), 0.0
    else:
        val = I / Imax
        vmin, vmax = 0.0, 1.0

    cmap = mcolors.LinearSegmentedColormap.from_list(
        "qvol_warm", [_QVOL_LOW, _QVOL_MID, _QVOL_HIGH]
    )
    norm = mcolors.Normalize(vmin=vmin, vmax=vmax)

    frac = np.clip((val - vmin) / max(vmax - vmin, 1e-12), 0.0, 1.0)
    sizes = 3.0 + 40.0 * frac ** 1.5

    # ── which voxels get a marker at all ──────────────────────────────────────
    has_camera = on_det is not None
    if has_camera:
        filled = on_det                       # on_detector already implies reachable
        hollow = reachable & ~on_det
    else:
        filled = reachable
        hollow = np.zeros(shape, dtype=bool)

    # ── set up axes ────────────────────────────────────────────────────────────
    standalone = ax is None
    if standalone:
        fig = plt.figure(figsize=figsize)
        fig.patch.set_facecolor(BG)
        ax = fig.add_subplot(111, projection="3d")
    else:
        fig = ax.figure

    ax.set_facecolor(BG)
    fig.patch.set_facecolor(BG)
    for pane in (ax.xaxis, ax.yaxis, ax.zaxis):
        pane.set_pane_color((0.03, 0.05, 0.08, 1.0))
        pane._axinfo["grid"]["color"] = (0.1, 0.12, 0.18, 0.6)
    ax.tick_params(colors="#7788aa", labelsize=7)

    sc = ax.scatter(
        AA[filled], T1[filled], T2[filled],
        c=val[filled], cmap=cmap, norm=norm,
        s=sizes[filled], marker="o", linewidths=0, alpha=0.9, depthshade=True,
    )

    legend_handles = []
    if show_off_detector and has_camera and hollow.any():
        edge_colors = cmap(norm(val[hollow]))
        ax.scatter(
            AA[hollow], T1[hollow], T2[hollow],
            s=np.clip(sizes[hollow], 6, None), marker="o",
            facecolors="none", edgecolors=edge_colors,
            linewidths=0.6, alpha=0.85,
        )
        legend_handles.append(
            Line2D([0], [0], marker="o", linestyle="", markerfacecolor="none",
                   markeredgecolor=FG, markersize=7,
                   label="reachable, off detector")
        )

    # ── energy-window boundary surface ────────────────────────────────────────
    if show_window_surface:
        # For each (lateral1, lateral2) column, find where `reachable` flips
        # off along the rod axis. A column that is entirely True or entirely
        # False has no boundary within this grid and is left as NaN.
        n_lat1, n_lat2 = shape[1], shape[2]
        drew_surface = False
        for edge in ("lo", "hi"):
            boundary = np.full((n_lat1, n_lat2), np.nan)
            for j in range(n_lat1):
                for k in range(n_lat2):
                    col = reachable[:, j, k]
                    if not col.any() or col.all():
                        continue
                    idxs = np.where(col)[0]
                    boundary[j, k] = along[idxs.min() if edge == "lo" else idxs.max()]
            if np.isnan(boundary).all():
                continue
            T1g, T2g = np.meshgrid(lat1, lat2, indexing="ij")
            ax.plot_surface(
                np.ma.masked_invalid(boundary), T1g, T2g,
                color=_QVOL_WINDOW, alpha=0.18, linewidth=0, shade=False,
            )
            drew_surface = True
        if drew_surface:
            legend_handles.append(
                Line2D([0], [0], marker="s", linestyle="", color=_QVOL_WINDOW,
                       alpha=0.5, markersize=9,
                       label="energy-window boundary (E_min/E_max)")
            )

    # ── labels / colorbar / legend ────────────────────────────────────────────
    hkl = vol.get("hkl")
    layer_label = vol.get("layer")
    ax.set_xlabel("ΔQ ∥ n̂  (Å⁻¹)", color=FG, fontsize=8, labelpad=8)
    ax.set_ylabel("ΔQ transverse 1  (Å⁻¹)", color=FG, fontsize=8, labelpad=8)
    ax.set_zlabel("ΔQ transverse 2  (Å⁻¹)", color=FG, fontsize=8, labelpad=8)
    ax.set_title(
        f"Q-space reconstruction around hkl={hkl}  (layer '{layer_label}')",
        color=FG, fontsize=10, pad=10,
    )
    ax.view_init(elev=elev, azim=azim)

    cbar = fig.colorbar(sc, ax=ax, shrink=0.6, pad=0.1)
    cbar.set_label("log₁₀ I / I_max" if log_intensity else "I / I_max", color=FG, fontsize=8)
    cbar.ax.yaxis.set_tick_params(color="#7788aa", labelsize=7)
    plt.setp(cbar.ax.get_yticklabels(), color=FG)
    cbar.outline.set_edgecolor("#333355")

    if legend_handles:
        ax.legend(
            handles=legend_handles, fontsize=7, labelcolor=FG,
            facecolor="#1a1f2e", edgecolor="#333355", loc="upper left",
        )

    if standalone:
        fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, ax

plot_qspace_on_detector

plot_qspace_on_detector(vol: dict, *, camera: Camera | None = None, image: ndarray | None = None, log_intensity: bool = False, intensity_floor: float = 1e-06, figsize: tuple[float, float] = (8, 8), ax: Axes | None = None, out_path: str | None = None)

Project the Q-space volume from :func:~nrxrdct.laue.simulation.qspace_around_spot onto the detector, so the same rod shown by :func:plot_qspace_around_spot can be compared directly against a real (or simulated) detector image.

Every voxel with vol['on_detector'] == True is drawn at its actual (xcam, ycam) pixel position, using the same colour/size intensity encoding as :func:plot_qspace_around_spot (and the same normalisation, I / I.max() over the whole volume — pass matching log_intensity / intensity_floor to both calls) so the two plots read as two projections of one object: the 3-D view shows why a voxel is bright or excluded, this view shows where the surviving voxels actually land. Voxels that are reachable but off-detector, outside the energy window, or destructively cancelled to zero are simply absent here — exactly as they would be absent from a real exposure.

The nominal reflection (ΔQ = 0, i.e. hkl itself) is marked with a crosshair so satellites can be read as offsets from it.

Parameters:
  • vol (dict) –

    Return value of :func:~nrxrdct.laue.simulation.qspace_around_spot, built with a camera (raises ValueError otherwise — there is no pixel information to plot without one).

  • camera (Camera | None, default: None ) –

    Same Camera used to build vol. Used to draw the detector's pixel-area outline/limits; safe to omit if image is given (its shape is used instead) or if you just want the scatter auto-scaled to the data.

  • image (ndarray | None, default: None ) –

    Optional measured/simulated detector image (shape (Nv, Nh)), shown as a greyscale background so the projected rod can be matched against real spots.

  • log_intensity, intensity_floor –

    Same meaning as in :func:plot_qspace_around_spot.

  • figsize (tuple[float, float], default: (8, 8) ) –

    Figure size in inches (only used when ax is None).

  • ax (Axes | None, default: None ) –

    Draw into an existing 2-D :class:~matplotlib.axes.Axes; None creates a new figure.

  • out_path (str | None, default: None ) –

    Save path; None → do not save.

Returns:
  • –

    (fig, ax)

Example:

vol = qspace_around_spot(stack, (0, 0, 2), camera=cam) plot_qspace_around_spot(vol) # the rod, in Q plot_qspace_on_detector(vol, camera=cam, image=img) # same rod, on the chip

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_qspace_on_detector(
    vol: dict,
    *,
    camera: "Camera | None" = None,
    image: "np.ndarray | None" = None,
    log_intensity: bool = False,
    intensity_floor: float = 1e-6,
    figsize: tuple[float, float] = (8, 8),
    ax: "plt.Axes | None" = None,
    out_path: "str | None" = None,
):
    """
    Project the Q-space volume from
    :func:`~nrxrdct.laue.simulation.qspace_around_spot` onto the detector,
    so the same rod shown by :func:`plot_qspace_around_spot` can be compared
    directly against a real (or simulated) detector image.

    Every voxel with `vol['on_detector'] == True` is drawn at its actual
    `(xcam, ycam)` pixel position, using the same colour/size intensity
    encoding as :func:`plot_qspace_around_spot` (and the same
    normalisation, `I / I.max()` over the *whole* volume — pass matching
    `log_intensity` / `intensity_floor` to both calls) so the two plots read
    as two projections of one object: the 3-D view shows *why* a voxel is
    bright or excluded, this view shows *where* the surviving voxels
    actually land. Voxels that are reachable but off-detector, outside the
    energy window, or destructively cancelled to zero are simply absent
    here — exactly as they would be absent from a real exposure.

    The nominal reflection (`ΔQ = 0`, i.e. `hkl` itself) is marked with a
    crosshair so satellites can be read as offsets from it.

    Args:
        vol: Return value of
            :func:`~nrxrdct.laue.simulation.qspace_around_spot`, built
            **with a `camera`** (raises `ValueError` otherwise — there is
            no pixel information to plot without one).
        camera: Same `Camera` used to build `vol`. Used to draw the
            detector's pixel-area outline/limits; safe to omit if `image`
            is given (its shape is used instead) or if you just want the
            scatter auto-scaled to the data.
        image: Optional measured/simulated detector image (shape
            `(Nv, Nh)`), shown as a greyscale background so the projected
            rod can be matched against real spots.
        log_intensity, intensity_floor: Same meaning as in
            :func:`plot_qspace_around_spot`.
        figsize: Figure size in inches (only used when `ax is None`).
        ax: Draw into an existing 2-D :class:`~matplotlib.axes.Axes`;
            `None` creates a new figure.
        out_path: Save path; `None` → do not save.

    Returns:
        `(fig, ax)`

    Example:
    >>> vol = qspace_around_spot(stack, (0, 0, 2), camera=cam)
    >>> plot_qspace_around_spot(vol)                          # the rod, in Q
    >>> plot_qspace_on_detector(vol, camera=cam, image=img)   # same rod, on the chip
    """
    if vol.get("pix") is None:
        raise ValueError(
            "vol['pix'] is None — qspace_around_spot() must be called with "
            "camera=<Camera instance> to compute detector positions."
        )

    along = np.asarray(vol["along"])
    lat1 = np.asarray(vol["lateral1"])
    lat2 = np.asarray(vol["lateral2"])
    I = vol["I"]
    on_det = vol["on_detector"]
    pix = vol["pix"]

    pix_flat = pix.reshape(-1, 2)
    I_flat = I.reshape(-1)
    on_flat = on_det.reshape(-1)

    Imax = float(I.max()) if I.size and I.max() > 0 else 1.0
    if log_intensity:
        val_flat = np.log10(I_flat / Imax + intensity_floor)
        vmin, vmax = np.log10(intensity_floor), 0.0
    else:
        val_flat = I_flat / Imax
        vmin, vmax = 0.0, 1.0

    cmap = mcolors.LinearSegmentedColormap.from_list(
        "qvol_warm", [_QVOL_LOW, _QVOL_MID, _QVOL_HIGH]
    )
    norm = mcolors.Normalize(vmin=vmin, vmax=vmax)
    frac = np.clip((val_flat - vmin) / max(vmax - vmin, 1e-12), 0.0, 1.0)
    sizes = 6.0 + 90.0 * frac ** 1.5

    keep = on_flat
    xs, ys = pix_flat[keep, 0], pix_flat[keep, 1]
    vals = val_flat[keep]

    # ── nearest-to-G0 voxel (ΔQ = 0), for the crosshair ───────────────────────
    i0 = int(np.argmin(np.abs(along)))
    j0 = int(np.argmin(np.abs(lat1)))
    k0 = int(np.argmin(np.abs(lat2)))
    g0_pix = pix[i0, j0, k0] if on_det[i0, j0, k0] else None

    standalone = ax is None
    if standalone:
        fig, ax = plt.subplots(figsize=figsize)
        fig.patch.set_facecolor(BG)
    else:
        fig = ax.figure

    ax.set_facecolor(BG)
    ax.tick_params(colors="#7788aa", labelsize=8)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")

    if image is not None:
        img = np.asarray(image, dtype=float)
        vmax_im = np.percentile(img[img > 0], 99) if img.max() > 0 else 1.0
        ax.imshow(
            np.log1p(img / vmax_im * 1000), origin="upper",
            cmap="gray", aspect="equal", interpolation="nearest",
        )
    elif camera is not None:
        ax.add_patch(Rectangle(
            (0, 0), camera.Nh, camera.Nv,
            linewidth=0.8, edgecolor="#333355", facecolor="none", zorder=0,
        ))

    sc = ax.scatter(
        xs, ys, c=vals, cmap=cmap, norm=norm, s=sizes[keep],
        marker="o", linewidths=0, alpha=0.9, zorder=3,
    )

    if g0_pix is not None:
        ax.scatter(
            [g0_pix[0]], [g0_pix[1]], s=140, marker="+",
            color=FG, linewidths=1.4, zorder=4,
        )

    if camera is not None:
        ax.set_xlim(0, camera.Nh)
        ax.set_ylim(camera.Nv, 0)
    elif len(xs):
        pad = 0.1 * max(xs.max() - xs.min(), ys.max() - ys.min(), 1.0)
        ax.set_xlim(xs.min() - pad, xs.max() + pad)
        ax.set_ylim(ys.max() + pad, ys.min() - pad)
    ax.set_aspect("equal")

    ax.set_xlabel("xcam  (px)", color=FG, fontsize=9)
    ax.set_ylabel("ycam  (px)", color=FG, fontsize=9)
    hkl = vol.get("hkl")
    layer_label = vol.get("layer")
    n_shown = int(keep.sum())
    n_total = int(on_flat.size)
    ax.set_title(
        f"Q-space rod projected onto detector — hkl={hkl}  (layer '{layer_label}')\n"
        f"{n_shown}/{n_total} voxels on-detector",
        color=FG, fontsize=9, pad=8,
    )

    cbar = fig.colorbar(sc, ax=ax, shrink=0.8, pad=0.03)
    cbar.set_label("log₁₀ I / I_max" if log_intensity else "I / I_max", color=FG, fontsize=8)
    cbar.ax.yaxis.set_tick_params(color="#7788aa", labelsize=7)
    plt.setp(cbar.ax.get_yticklabels(), color=FG)
    cbar.outline.set_edgecolor("#333355")

    if standalone:
        fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, ax

plot_qspace_summary

plot_qspace_summary(vol: dict, *, per_layer_vols: list[dict] | None = None, camera: Camera | None = None, image: ndarray | None = None, log_intensity: bool = False, intensity_floor: float = 1e-06, resolution_dq: float = 0.01, figsize: tuple[float, float] = (18, 8), out_path: str | None = None)

Four-panel summary of the Q-space volume from :func:~nrxrdct.laue.simulation.qspace_around_spot.

Panel 1 — Rod profile (top, full width): intensity averaged over the two transverse axes vs ΔQ along the rod direction. A shaded band marks the accessible energy window; yellow dots mark voxels that reach the detector. A secondary (right) y-axis overlays the photon energy E(ΔQ) along the rod centre, so fringe positions can be read directly in keV.

Panel 2 — Mid-plane heatmap (bottom-left): pcolormesh of the volume slice at ΔQ_lateral₁ = 0 (i.e. I[:, n_lat//2, :]), showing the rod shape and any lateral asymmetry in a legible 2-D image. A contour marks the energy-window boundary.

Panel 3 — Detector projection (bottom-centre): the same projection as :func:plot_qspace_on_detector, included only when vol['pix'] is available. Omitted (panel 2 widens) when no camera was used.

Panel 4 — Intensity comparison along the rod (bottom-right): simulated intensity vs ΔQ_along for the primary vol, restricted to on-detector voxels and normalised to its own peak. When image is provided, the measured pixel intensity sampled along the same path is overlaid (also normalised). When per_layer_vols is supplied (from :func:~nrxrdct.laue.simulation.qspace_per_layer), the x-axis switches to absolute Q · n̂ so all layers' profiles can be compared on the same axis: each layer's on-detector 1D profile is drawn with a distinct colour, and the measured profile (if image is given) is drawn on top.

Parameters:
  • vol (dict) –

    Primary return value of :func:~nrxrdct.laue.simulation.qspace_around_spot — used for panels 1–3 and as the source of pixel positions for the measured intensity in panel 4.

  • per_layer_vols (list[dict] | None, default: None ) –

    Optional list of vol dicts returned by :func:~nrxrdct.laue.simulation.qspace_per_layer. When given, each layer's simulated 1D profile is overlaid in panel 4 on an absolute Q · n̂ axis so layers with different lattice parameters can be compared directly.

  • camera (Camera | None, default: None ) –

    Same Camera used to build vol; draws the detector boundary in the projection panel.

  • image (ndarray | None, default: None ) –

    Optional measured/simulated detector image (shape (Nv, Nh)). Shown as a grey background in the projection panel, and sampled along the rod path for the intensity-comparison panel.

  • log_intensity (bool, default: False ) –

    Colour/scale by log₁₀(I) rather than raw I (default False).

  • intensity_floor (float, default: 1e-06 ) –

    Floor added before the log (as a fraction of I_max). Only used when log_intensity=True.

  • figsize (tuple[float, float], default: (18, 8) ) –

    Figure size in inches.

  • out_path (str | None, default: None ) –

    Save path; None → do not save.

Returns:
  • –

    (fig, axes) — axes is a list of 2, 3, or 4

  • –

    class:~matplotlib.axes.Axes objects.

Example:

vols = qspace_per_layer(stack, (0, 0, 2), camera=cam) plot_qspace_summary(vols[0], per_layer_vols=vols, camera=cam, ... image=img, out_path="summary_002.png")

Source code in src/nrxrdct/laue/laue_plotting.py
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
def plot_qspace_summary(
    vol: dict,
    *,
    per_layer_vols: "list[dict] | None" = None,
    camera: "Camera | None" = None,
    image: "np.ndarray | None" = None,
    log_intensity: bool = False,
    intensity_floor: float = 1e-6,
    resolution_dq: float = 0.01,
    figsize: tuple[float, float] = (18, 8),
    out_path: "str | None" = None,
):
    """
    Four-panel summary of the Q-space volume from
    :func:`~nrxrdct.laue.simulation.qspace_around_spot`.

    **Panel 1 — Rod profile** (top, full width): intensity averaged over the
    two transverse axes vs ΔQ along the rod direction.  A shaded band marks
    the accessible energy window; yellow dots mark voxels that reach the
    detector.  A secondary (right) y-axis overlays the photon energy E(ΔQ)
    along the rod centre, so fringe positions can be read directly in keV.

    **Panel 2 — Mid-plane heatmap** (bottom-left): ``pcolormesh`` of the
    volume slice at ΔQ_lateral₁ = 0 (i.e. ``I[:, n_lat//2, :]``), showing
    the rod shape and any lateral asymmetry in a legible 2-D image.  A
    contour marks the energy-window boundary.

    **Panel 3 — Detector projection** (bottom-centre): the same projection as
    :func:`plot_qspace_on_detector`, included only when ``vol['pix']`` is
    available.  Omitted (panel 2 widens) when no camera was used.

    **Panel 4 — Intensity comparison along the rod** (bottom-right): simulated
    intensity vs ΔQ_along for the primary ``vol``, restricted to on-detector
    voxels and normalised to its own peak.  When ``image`` is provided, the
    measured pixel intensity sampled along the same path is overlaid (also
    normalised).  When ``per_layer_vols`` is supplied (from
    :func:`~nrxrdct.laue.simulation.qspace_per_layer`), the x-axis switches
    to **absolute Q · n̂** so all layers' profiles can be compared on the same
    axis: each layer's on-detector 1D profile is drawn with a distinct colour,
    and the measured profile (if ``image`` is given) is drawn on top.

    Args:
        vol: Primary return value of
            :func:`~nrxrdct.laue.simulation.qspace_around_spot` — used for
            panels 1–3 and as the source of pixel positions for the measured
            intensity in panel 4.
        per_layer_vols: Optional list of vol dicts returned by
            :func:`~nrxrdct.laue.simulation.qspace_per_layer`.  When given,
            each layer's simulated 1D profile is overlaid in panel 4 on an
            absolute Q · n̂ axis so layers with different lattice parameters
            can be compared directly.
        camera: Same ``Camera`` used to build ``vol``; draws the detector
            boundary in the projection panel.
        image: Optional measured/simulated detector image (shape ``(Nv, Nh)``).
            Shown as a grey background in the projection panel, and sampled
            along the rod path for the intensity-comparison panel.
        log_intensity: Colour/scale by log₁₀(I) rather than raw I
            (default ``False``).
        intensity_floor: Floor added before the log (as a fraction of I_max).
            Only used when ``log_intensity=True``.
        figsize: Figure size in inches.
        out_path: Save path; ``None`` → do not save.

    Returns:
        ``(fig, axes)`` — axes is a list of 2, 3, or 4
        :class:`~matplotlib.axes.Axes` objects.

    Example:
    >>> vols = qspace_per_layer(stack, (0, 0, 2), camera=cam)
    >>> plot_qspace_summary(vols[0], per_layer_vols=vols, camera=cam,
    ...                     image=img, out_path="summary_002.png")
    """
    from scipy.ndimage import map_coordinates

    along = np.asarray(vol["along"])
    lat1 = np.asarray(vol["lateral1"])
    lat2 = np.asarray(vol["lateral2"])
    I = vol["I"]
    E = vol["E"]
    reachable = vol["reachable"]
    on_det = vol["on_detector"]
    has_pix = on_det is not None and vol.get("pix") is not None
    hkl = vol.get("hkl")
    layer_label = vol.get("layer")

    Imax = float(I.max()) if I.size and I.max() > 0 else 1.0
    if log_intensity:
        def _val(arr):
            return np.log10(np.asarray(arr) / Imax + intensity_floor)
        vlabel = "log₁₀ I / I_max"
        vmin, vmax_c = np.log10(intensity_floor), 0.0
    else:
        def _val(arr):
            return np.asarray(arr) / Imax
        vlabel = "I / I_max"
        vmin, vmax_c = 0.0, 1.0

    cmap = mcolors.LinearSegmentedColormap.from_list(
        "qvol_warm", [_QVOL_LOW, _QVOL_MID, _QVOL_HIGH]
    )
    norm = mcolors.Normalize(vmin=vmin, vmax=vmax_c)

    j0 = len(lat1) // 2
    k0 = len(lat2) // 2

    # ── figure / axes layout ──────────────────────────────────────────────────
    fig = plt.figure(figsize=figsize)
    fig.patch.set_facecolor(BG)
    if has_pix:
        gs = mgridspec.GridSpec(2, 3, figure=fig,
                                height_ratios=[1, 1.4], hspace=0.42, wspace=0.36)
        ax_rod = fig.add_subplot(gs[0, :])
        ax_heat = fig.add_subplot(gs[1, 0])
        ax_det = fig.add_subplot(gs[1, 1])
        ax_prof = fig.add_subplot(gs[1, 2])
        axes = [ax_rod, ax_heat, ax_det, ax_prof]
    else:
        gs = mgridspec.GridSpec(2, 1, figure=fig,
                                height_ratios=[1, 1.4], hspace=0.42)
        ax_rod = fig.add_subplot(gs[0])
        ax_heat = fig.add_subplot(gs[1])
        ax_det = None
        ax_prof = None
        axes = [ax_rod, ax_heat]

    # ══════════════════════════════════════════════════════════════════════════
    # Panel 1 — rod profile
    # ══════════════════════════════════════════════════════════════════════════
    _ax_style(ax_rod, f"Rod profile — hkl={hkl}  (layer '{layer_label}')")
    ax_rod.set_xlabel("ΔQ ∥ n̂  (Å⁻¹)", color=FG, fontsize=8)
    ax_rod.set_ylabel(vlabel, color=FG, fontsize=8)

    I_rod = I.mean(axis=(1, 2))
    val_rod = _val(I_rod)
    reach_rod = reachable.any(axis=(1, 2))

    if reach_rod.any():
        ax_rod.axvspan(
            along[reach_rod].min(), along[reach_rod].max(),
            color=_QVOL_WINDOW, alpha=0.10,
        )

    ax_rod.plot(along, val_rod, color=COL_SUP, lw=1.3, zorder=3)

    legend_h = []
    if has_pix:
        on_rod = on_det.any(axis=(1, 2))
        if on_rod.any():
            ax_rod.scatter(
                along[on_rod], val_rod[on_rod],
                s=20, color=COL_DB, zorder=4, linewidths=0,
            )
            legend_h.append(
                Line2D([0], [0], marker="o", linestyle="", color=COL_DB,
                       markersize=5, label="on detector")
            )
    if reach_rod.any():
        legend_h.append(
            Line2D([0], [0], color=_QVOL_WINDOW, lw=6, alpha=0.4,
                   label="energy window")
        )
    if legend_h:
        ax_rod.legend(handles=legend_h, fontsize=7, labelcolor=FG,
                      facecolor="#1a1f2e", edgecolor="#333355", loc="upper right")

    # right y-axis: photon energy along the rod centre
    E_rod = E[:, j0, k0]
    valid_E = np.isfinite(E_rod)
    if valid_E.sum() >= 2:
        ax_e = ax_rod.twinx()
        ax_e.set_facecolor(BG)
        ax_e.plot(along[valid_E], E_rod[valid_E] / 1000,
                  "--", color=COL_BCC, lw=0.9, alpha=0.75)
        ax_e.set_ylabel("E  (keV)", color=COL_BCC, fontsize=7, labelpad=4)
        ax_e.tick_params(colors=COL_BCC, labelsize=6)
        ax_e.yaxis.label.set_color(COL_BCC)
        for sp in ax_e.spines.values():
            sp.set_edgecolor("#1a1f2e")

    # ══════════════════════════════════════════════════════════════════════════
    # Panel 2 — mid-plane heatmap  I(ΔQ_along, ΔQ_lat2)  at ΔQ_lat1 = 0
    # ══════════════════════════════════════════════════════════════════════════
    _ax_style(ax_heat, "Mid-plane heatmap  (ΔQ_lat₁ = 0)")
    ax_heat.set_xlabel("ΔQ ∥ n̂  (Å⁻¹)", color=FG, fontsize=8)
    ax_heat.set_ylabel("ΔQ transverse  (Å⁻¹)", color=FG, fontsize=8)

    slice2d = I[:, j0, :]                 # (n_along, n_lat2)
    heat_val = _val(slice2d).T            # (n_lat2, n_along) → rows = y, cols = x

    im = ax_heat.pcolormesh(
        along, lat2, heat_val, cmap=cmap, norm=norm, shading="nearest",
    )
    cbar_h = fig.colorbar(im, ax=ax_heat, shrink=0.9, pad=0.03)
    cbar_h.set_label(vlabel, color=FG, fontsize=7)
    cbar_h.ax.yaxis.set_tick_params(color="#7788aa", labelsize=6)
    plt.setp(cbar_h.ax.get_yticklabels(), color=FG)
    cbar_h.outline.set_edgecolor("#333355")

    reach_slice = reachable[:, j0, :]    # (n_along, n_lat2)
    if reach_slice.any() and not reach_slice.all():
        ax_heat.contour(
            along, lat2, reach_slice.T.astype(float),
            levels=[0.5], colors=[_QVOL_WINDOW], linewidths=0.8, alpha=0.8,
        )

    # ══════════════════════════════════════════════════════════════════════════
    # Panel 3 — detector projection.
    #
    # One marker per along step: coherent intensity |F_total|² and pixel
    # position are both averaged over all on-detector lateral (j,k) voxels
    # at that step, so each dot represents the full lateral footprint collapsed
    # to a single coherent-sum value.
    # ══════════════════════════════════════════════════════════════════════════
    if ax_det is not None:
        _ax_style(ax_det, "Detector projection")
        ax_det.set_xlabel("xcam  (px)", color=FG, fontsize=8)
        ax_det.set_ylabel("ycam  (px)", color=FG, fontsize=8)

        pix = vol["pix"]

        # collapse lateral: one (I, xcam, ycam) per along step
        n_on_lat_d = on_det.sum(axis=(1, 2))          # (n_along,)
        has_on = n_on_lat_d > 0
        denom = np.maximum(n_on_lat_d, 1)
        I_avg_d = np.where(has_on, (I * on_det).sum(axis=(1, 2)) / denom, np.nan)
        pix_x_avg = np.where(has_on, (pix[..., 0] * on_det).sum(axis=(1, 2)) / denom, np.nan)
        pix_y_avg = np.where(has_on, (pix[..., 1] * on_det).sum(axis=(1, 2)) / denom, np.nan)

        xs_d = pix_x_avg[has_on]
        ys_d = pix_y_avg[has_on]
        val_d = _val(I_avg_d[has_on])
        frac_d = np.clip((val_d - vmin) / max(vmax_c - vmin, 1e-12), 0.0, 1.0)
        sizes_d = 8.0 + 100.0 * frac_d ** 1.5

        if image is not None:
            img_arr = np.asarray(image, dtype=float)
            vmax_im = np.percentile(img_arr[img_arr > 0], 99) if img_arr.max() > 0 else 1.0
            ax_det.imshow(
                np.log1p(img_arr / vmax_im * 1000), origin="upper",
                cmap="gray", aspect="equal", interpolation="nearest",
            )
        if camera is not None:
            ec = "#6688bb" if image is not None else "#333355"
            ax_det.add_patch(Rectangle(
                (0, 0), camera.Nh, camera.Nv,
                linewidth=0.8, edgecolor=ec, facecolor="none", zorder=5,
            ))

        rgba_d = cmap(norm(val_d)).copy()
        rgba_d[:, 3] = np.clip(0.15 + 0.8 * frac_d, 0.15, 0.95)
        sc_d = ax_det.scatter(
            xs_d, ys_d, facecolors=rgba_d,
            s=sizes_d, marker="o", linewidths=0, zorder=3,
        )

        # crosshair at G0 (ΔQ = 0)
        i0 = int(np.argmin(np.abs(along)))
        if has_on[i0]:
            ax_det.scatter(
                [pix_x_avg[i0]], [pix_y_avg[i0]], s=120, marker="+",
                color=FG, linewidths=1.2, zorder=4,
            )

        if camera is not None:
            ax_det.set_xlim(0, camera.Nh)
            ax_det.set_ylim(camera.Nv, 0)
        elif len(xs_d):
            pad = 0.1 * max(xs_d.max() - xs_d.min(), ys_d.max() - ys_d.min(), 1.0)
            ax_det.set_xlim(xs_d.min() - pad, xs_d.max() + pad)
            ax_det.set_ylim(ys_d.max() + pad, ys_d.min() - pad)
        ax_det.set_aspect("equal")

        _sm_d = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
        _sm_d.set_array([])
        cbar_d = fig.colorbar(_sm_d, ax=ax_det, shrink=0.8, pad=0.03)
        cbar_d.set_label(vlabel, color=FG, fontsize=7)
        cbar_d.ax.yaxis.set_tick_params(color="#7788aa", labelsize=6)
        plt.setp(cbar_d.ax.get_yticklabels(), color=FG)
        cbar_d.outline.set_edgecolor("#333355")

    # ══════════════════════════════════════════════════════════════════════════
    # Panel 4 — coherent total intensity along the on-detector rod path.
    #
    # vol["I"] = |F_total|²  where  F_total = Σ_layer F_layer·exp(iφ_layer)
    # is the coherent structure-factor sum already computed by
    # structure_factor_batch — phase shifts between layers are included.
    # Intensities are averaged over ALL on-detector (j,k) lateral voxels at
    # each along step, then normalised to their on-detector maximum.
    # ══════════════════════════════════════════════════════════════════════════
    if ax_prof is not None:
        _ax_style(ax_prof, "Coherent intensity along detector projection")
        ax_prof.set_xlabel("ΔQ ∥ n̂  (Å⁻¹)", color=FG, fontsize=8)
        ax_prof.set_ylabel("I / I_max", color=FG, fontsize=8)
        ax_prof.grid(True, ls=":", lw=0.35, color="#181e2e")

        n_on_lat = on_det.sum(axis=(1, 2))          # (n_along,)
        has_any = n_on_lat > 0
        I_sum_lat = (I * on_det).sum(axis=(1, 2))
        I_sim_avg = np.where(has_any, I_sum_lat / np.maximum(n_on_lat, 1), np.nan)
        along_on = along[has_any]
        I_sim_on = I_sim_avg[has_any]
        peak_sim = float(np.nanmax(I_sim_on)) if np.any(np.isfinite(I_sim_on)) else 1.0
        I_sim_norm = I_sim_on / max(peak_sim, 1e-30)

        prof_handles = []
        if has_any.any():
            from scipy.ndimage import gaussian_filter1d as _gf1d
            dq_step = float(np.diff(along_on).mean()) if len(along_on) > 1 else 1.0
            sigma_px = max(resolution_dq / abs(dq_step), 0.5)
            _env = _gf1d(I_sim_norm, sigma=sigma_px)
            _env_label = f"convolved (σ={resolution_dq*1e3:.1f} mÅ⁻¹)"

            if image is not None and has_pix:
                img_arr = np.asarray(image, dtype=float)
                pix_v = vol["pix"]
                on_flat_idx = np.where(on_det.reshape(len(along), -1))
                i_idx, jk_flat = on_flat_idx
                n_lat2 = on_det.shape[2]
                j_idx = jk_flat // n_lat2
                k_idx = jk_flat % n_lat2
                pix_sel = pix_v[i_idx, j_idx, k_idx]
                coords = np.array([pix_sel[:, 1], pix_sel[:, 0]])
                meas_vals = map_coordinates(img_arr, coords, order=1, mode="nearest")
                I_meas_sum = np.zeros(len(along))
                np.add.at(I_meas_sum, i_idx, meas_vals)
                I_meas_avg = np.where(has_any, I_meas_sum / np.maximum(n_on_lat, 1), np.nan)
                I_meas_on = I_meas_avg[has_any]
                peak_meas = float(np.nanmax(I_meas_on)) if np.any(np.isfinite(I_meas_on)) else 1.0
                ax_prof.plot(along_on, I_meas_on / max(peak_meas, 1e-30),
                             color=FG, lw=1.3, zorder=3)
                ax_prof.plot(along_on, I_sim_norm, color=COL_SUP, lw=1.3,
                             ls="--", zorder=4)
                ax_prof.plot(along_on, _env, color=COL_BCC, lw=1.5,
                             ls="-", alpha=0.75, zorder=5)
                prof_handles = [
                    Line2D([0], [0], color=FG, lw=1.3, label="measured"),
                    Line2D([0], [0], color=COL_SUP, lw=1.3, ls="--",
                           label="simulated (coherent)"),
                    Line2D([0], [0], color=COL_BCC, lw=1.5,
                           alpha=0.75, label=_env_label),
                ]
            else:
                ax_prof.plot(along_on, I_sim_norm, color=COL_SUP, lw=1.3, zorder=3)
                ax_prof.plot(along_on, _env, color=COL_BCC, lw=1.5,
                             ls="-", alpha=0.75, zorder=4)
                prof_handles = [
                    Line2D([0], [0], color=COL_SUP, lw=1.3,
                           label="simulated (coherent)"),
                    Line2D([0], [0], color=COL_BCC, lw=1.5,
                           alpha=0.75, label=_env_label),
                ]
            ax_prof.set_ylim(bottom=0)
            ax_prof.legend(
                handles=prof_handles, fontsize=7, labelcolor=FG,
                facecolor="#1a1f2e", edgecolor="#333355",
                loc="upper left", bbox_to_anchor=(1.01, 1.0),
                borderaxespad=0, handlelength=1.4,
            )
        else:
            ax_prof.text(0.5, 0.5, "no on-detector voxels",
                         color="#7788aa", ha="center", va="center",
                         transform=ax_prof.transAxes, fontsize=8)

    fig.suptitle(
        f"Q-space summary — hkl={hkl}  (layer '{layer_label}')",
        color=FG, fontsize=11, y=1.01,
    )

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, axes

plot_rod_qspace_warp

plot_rod_qspace_warp(stack, hkl, image, layer=None, camera=None, *, ki_hat=None, q_par_range=None, q_perp_range=None, n_par: int = 300, n_perp: int = 300, half_size_px: float = 40.0, perp_probe_px: float = 5.0, interp_order: int = 1, max_satellites=0, show_relaxed_buffer: bool = False, show_profile: bool = False, profile_halfwidth_bins: int = 3, ncols: int = 3, log_scale: bool = True, cmap: str = 'inferno', ax=None, figsize=(6.5, 5.5), out_path=None)

Display the (q_parallel, q_perp) warp of a reflection's local image patch produced by :func:warp_rod_to_qspace. q_parallel is the vertical axis, q_perp the horizontal one.

layer accepts a single Layer/label/None (default), or a list of them, same as plot_rod_tangency's own layer argument — but 'all' means something different here: one panel per block, not per individual Layer. Concretely, 'all' resolves to stack.buffer_layers[1:] + [blk.layers[0] for blk in stack._blocks] — every buffer layer except the substrate (stack.buffer_layers[0], typically a dissimilar material not worth a panel of its own), plus each repeating block's own first layer, with no crystal+orientation dedup — different blocks routinely share a base material but have different periods/satellite combs, and deduping on crystal+U alone would silently hide that (see :func:_block_representative_layers). Sub-layers within one repeating block (e.g. the well vs barrier of an MQW) share one effective diffraction geometry in that average picture, so plotting every individual sub-layer would just repeat near-identical panels for layers that were never treated as independently coherent to begin with; pass an explicit list of specific Layer/labels instead if you do want individual sub-layers compared side by side.

However resolved, the layers can't be overlaid on one shared image (unlike plot_rod_tangency): each layer's own (q_par, q_perp) frame is anchored to its own G0/n̂/ê⊥ (generally at a different pixel, energy, and even tangency direction), so instead one panel per layer is drawn in a small-multiples grid — same ncols idea as plot_rod_tangency_blocks/plot_rod_tangency_harmonics — that wraps to a new row after ncols panels, in a figure that scales with the number of rows/columns actually used (figsize is treated as the size of one panel, not the whole figure). The shared profile panel, if show_profile=True, occupies one more grid slot at the end (after every image panel), not a separate row of its own. Layers that are unreachable or fall entirely off-detector are skipped with a printed note, same as plot_rod_tangency.

A crosshair marks each panel's own G0 (q_par=q_perp=0 by construction, always labelled G0). With max_satellites > 0, the discrete satellite comb (same one rod_tangency/plot_rod_tangency compute, m = -max_satellites, ..., max_satellites including m=0) is also marked, each at its own exact sat['along'] position from rod_tangency — not naively m·(2π/Λ); for a true superlattice (is_superlattice=True) the comb is anchored to the nearest real Sₙ maximum, and for an isolated finite layer it's probed at half-integer positions (rod_tangency's own docstring explains why). Every satellite (including m=0, the nearest comb tooth) lies exactly on the q_par axis at q_perp=0 by construction (along·n̂ has no ê⊥ component) — note this "0th satellite" position can differ slightly from G0 itself for a true superlattice, which is why it's marked separately from the G0 crosshair rather than assumed identical to it.

With show_relaxed_buffer=True, the same hkl's position using the shallowest buffer layer's own (relaxed/bulk) lattice is also marked, on every panel — a grey diamond, same convention as plot_rod_tangency's own show_relaxed_buffer — projected into that layer's own (q_par, q_perp) frame via ((G0_buffer - G0) @ n_hat, (G0_buffer - G0) @ perp_hat), so it shows how far each layer's peak has moved from the unstrained template, directly in physical Q units rather than pixels.

With show_profile=True, one shared profile axis is added (not one per layer) — every plotted layer's own intensity-along-q_parallel line (see profile_halfwidth_bins below) is overlaid there in its own colour, satellite orders included, so the profiles line up directly comparable the same way plot_rod_tangency's own show_profile overlays multiple layers' streak profiles on one shared axis.

Parameters:
  • stack, hkl, camera, ki_hat –

    Forwarded to :func:warp_rod_to_qspace (and, for satellites/the relaxed buffer, to :func:~nrxrdct.laue.simulation.rod_tangency).

  • layer –

    Single layer/label/None (default stack.layers[0]), a list of them, or 'all' — see above.

  • image ((ndarray, shape(Nv, Nh))) –

    Detector frame to warp and display.

  • max_satellites (int or (int, int), default: 0 ) –

    0 (default) shows only the crosshair at G0. A single int > 0 marks that many satellite orders on either side, plus m=0 (see above), same as before. A (neg, pos) tuple marks an independent count on each side of the branch — neg orders for m < 0, pos orders for m > 0 — for a rod whose comb is meaningfully asymmetric (e.g. is_superlattice=False's half-integer probing already isn't symmetric about m=0) or when you only care about one direction. m=0 is always shown regardless of either count (it isn't "on a side"). Internally still solves rod_tangency once for max(neg, pos) orders and only displays the requested side counts, so this is purely a display filter, not a cheaper/more expensive computation.

  • show_relaxed_buffer (bool, default: False ) –

    Mark the same hkl's relaxed-buffer position on every panel (see above). Skipped per-panel (with a printed note) if the stack has no buffer layers, the buffer layer is the one being plotted, or its own hkl is unreachable/off-detector.

  • show_profile (bool, default: False ) –

    Add, for every panel, a paired axis with the intensity along q_parallel, integrated over ±profile_halfwidth_bins grid columns around q_perp=0 — the same kind of 1-D line profile plot_rod_tangency's own show_profile adds, except read directly off the already-computed warp instead of re-sampling the raw image (no separate lateral-integration pass needed, since the warp is already gridded in physical q units). The y-axis (intensity) is log-scaled, same reasoning as plot_rod_tangency: weak far orders stay visible alongside the main peak. For a single layer, the profile is a spacious axis of its own with full SL0/±N satellite labels and a legend, same as before; for multiple layers/blocks, each panel gets its own compact profile beside it (small ticks on the right, satellite orders as dotted lines only, no text labels/legend) — a single shared profile axis across several layers/blocks becomes a tangle of overlapping lines and stacked labels fast, so each one gets its own instead. Every profile also gets a dashed baseline (see :func:_estimate_baseline) — a straight line through the median level at each edge of the q_parallel window, extrapolated across the whole profile — as a visual reference for the background level the peak/satellites sit on. Requires ax=None (a fresh figure is always created).

  • profile_halfwidth_bins (int, default: 3 ) –

    Lateral integration half-width, in q_perp grid columns (not Å⁻¹) — e.g. 3 sums 7 columns (-3, ..., +3) around the column nearest q_perp=0. Unused unless show_profile=True.

  • ncols (int, default: 3 ) –

    For multiple layers/blocks only — panel columns before wrapping to a new row, same idea as plot_rod_tangency_blocks/ plot_rod_tangency_harmonics's own ncols. Unused for a single layer (always one row).

  • log_scale (bool, default: True ) –

    Apply log1p scaling to the warped image before display.

  • cmap (str, default: 'inferno' ) –

    Matplotlib colormap.

  • ax (Axes, default: None ) –

    Draw into an existing axes instead of creating a new figure. Only valid for a single layer with show_profile=False; raises otherwise.

  • figsize –

    Size of one panel (ignored if ax is given) — see above for how the overall figure size scales with panel count.

  • out_path (str or None, default: None ) –

    Save figure to this path if given.

Returns:
  • –

    Single layer, show_profile=False (default, and the only

  • –

    backward-compatible case with a plain single-Axes return):

  • –

    (fig, ax, warped, q_par_ax, q_perp_ax, info).

  • –

    Single layer, show_profile=True:

  • –

    (fig, (ax, ax_profile), warped, q_par_ax, q_perp_ax, info).

  • –

    Multiple layers (list or 'all', however many actually succeed):

  • –

    (fig, axes, results), where axes is img_axes (a list, one

  • –

    per plotted layer) when show_profile=False, or

  • –

    (img_axes, profile_axes) — two parallel lists, one profile axis

  • –

    per image axis, in the same order — when show_profile=True.

  • –

    results is a list of

  • –

    {'layer', 'warped', 'q_par_ax', 'q_perp_ax', 'info'} dicts, one

  • –

    per plotted layer, in the same order as axes/img_axes.

Source code in src/nrxrdct/laue/laue_plotting.py
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
def plot_rod_qspace_warp(
    stack,
    hkl,
    image,
    layer=None,
    camera=None,
    *,
    ki_hat=None,
    q_par_range=None,
    q_perp_range=None,
    n_par: int = 300,
    n_perp: int = 300,
    half_size_px: float = 40.0,
    perp_probe_px: float = 5.0,
    interp_order: int = 1,
    max_satellites=0,
    show_relaxed_buffer: bool = False,
    show_profile: bool = False,
    profile_halfwidth_bins: int = 3,
    ncols: int = 3,
    log_scale: bool = True,
    cmap: str = "inferno",
    ax=None,
    figsize=(6.5, 5.5),
    out_path=None,
):
    """
    Display the `(q_parallel, q_perp)` warp of a reflection's local image
    patch produced by :func:`warp_rod_to_qspace`. `q_parallel` is the
    vertical axis, `q_perp` the horizontal one.

    `layer` accepts a single `Layer`/label/`None` (default), or a list of
    them, same as `plot_rod_tangency`'s own `layer` argument — but `'all'`
    means something different here: **one panel per block**, not per
    individual `Layer`. Concretely, `'all'` resolves to
    `stack.buffer_layers[1:] + [blk.layers[0] for blk in stack._blocks]`
    — every buffer layer except the substrate (`stack.buffer_layers[0]`,
    typically a dissimilar material not worth a panel of its own), plus
    each repeating block's own first layer, with **no** crystal+orientation
    dedup — different blocks routinely share a base material but have
    different periods/satellite combs, and deduping on crystal+`U` alone
    would silently hide that (see :func:`_block_representative_layers`).
    Sub-layers within one repeating block (e.g. the well vs barrier of an
    MQW) share one effective diffraction geometry in that average picture,
    so plotting
    every individual sub-layer would just repeat near-identical panels for
    layers that were never treated as independently coherent to begin
    with; pass an explicit list of specific `Layer`/labels instead if you
    do want individual sub-layers compared side by side.

    However resolved, the layers can't be overlaid on one shared image
    (unlike `plot_rod_tangency`): each layer's own `(q_par, q_perp)` frame
    is anchored to its *own* `G0`/`n̂`/`ê⊥` (generally at a different pixel,
    energy, and even tangency direction), so instead one panel per layer is
    drawn in a small-multiples grid — same `ncols` idea as
    `plot_rod_tangency_blocks`/`plot_rod_tangency_harmonics` — that wraps to
    a new row after `ncols` panels, in a figure that scales with the number
    of rows/columns actually used (`figsize` is treated as the size of *one*
    panel, not the whole figure). The shared profile panel, if
    `show_profile=True`, occupies one more grid slot at the end (after every
    image panel), not a separate row of its own. Layers that are
    unreachable or fall entirely off-detector are skipped with a printed
    note, same as `plot_rod_tangency`.

    A crosshair marks each panel's own `G0` (`q_par=q_perp=0` by
    construction, always labelled `G0`). With `max_satellites > 0`, the
    discrete satellite comb (same one `rod_tangency`/`plot_rod_tangency`
    compute, `m = -max_satellites, ..., max_satellites` including `m=0`)
    is also marked, each at its own exact `sat['along']` position from
    `rod_tangency` — **not** naively `m·(2π/Λ)`; for a true superlattice
    (`is_superlattice=True`) the comb is anchored to the nearest real
    `Sₙ` maximum, and for an isolated finite layer it's probed at
    half-integer positions (`rod_tangency`'s own docstring explains why).
    Every satellite (including `m=0`, the nearest comb tooth) lies exactly
    on the `q_par` axis at `q_perp=0` by construction (`along·n̂` has no
    `ê⊥` component) — note this "0th satellite" position can differ
    slightly from `G0` itself for a true superlattice, which is why it's
    marked separately from the `G0` crosshair rather than assumed
    identical to it.

    With `show_relaxed_buffer=True`, the same `hkl`'s position using the
    shallowest buffer layer's own (relaxed/bulk) lattice is also marked, on
    every panel — a grey diamond, same convention as `plot_rod_tangency`'s
    own `show_relaxed_buffer` — projected into *that* layer's own
    `(q_par, q_perp)` frame via
    `((G0_buffer - G0) @ n_hat, (G0_buffer - G0) @ perp_hat)`, so it shows
    how far each layer's peak has moved from the unstrained template,
    directly in physical Q units rather than pixels.

    With `show_profile=True`, one shared profile axis is added (not one
    per layer) — every plotted layer's own intensity-along-`q_parallel`
    line (see `profile_halfwidth_bins` below) is overlaid there in its own
    colour, satellite orders included, so the profiles line up directly
    comparable the same way `plot_rod_tangency`'s own `show_profile`
    overlays multiple layers' streak profiles on one shared axis.

    Args:
        stack, hkl, camera, ki_hat: Forwarded to :func:`warp_rod_to_qspace`
            (and, for satellites/the relaxed buffer, to
            :func:`~nrxrdct.laue.simulation.rod_tangency`).
        layer: Single layer/label/`None` (default `stack.layers[0]`), a
            list of them, or `'all'` — see above.
        image (ndarray, shape (Nv, Nh)): Detector frame to warp and display.
        q_par_range, q_perp_range, n_par, n_perp, half_size_px,
            perp_probe_px, interp_order: Forwarded to
            :func:`warp_rod_to_qspace`, same for every layer.
        max_satellites (int or (int, int)): `0` (default) shows only the
            crosshair at `G0`. A single `int > 0` marks that many satellite
            orders on either side, plus `m=0` (see above), same as before.
            A `(neg, pos)` tuple marks an independent count on each side of
            the branch — `neg` orders for `m < 0`, `pos` orders for
            `m > 0` — for a rod whose comb is meaningfully asymmetric (e.g.
            `is_superlattice=False`'s half-integer probing already isn't
            symmetric about `m=0`) or when you only care about one
            direction. `m=0` is always shown regardless of either count
            (it isn't "on a side"). Internally still solves
            `rod_tangency` once for `max(neg, pos)` orders and only
            displays the requested side counts, so this is purely a
            display filter, not a cheaper/more expensive computation.
        show_relaxed_buffer (bool): Mark the same `hkl`'s relaxed-buffer
            position on every panel (see above). Skipped per-panel (with a
            printed note) if the stack has no buffer layers, the buffer
            layer is the one being plotted, or its own `hkl` is
            unreachable/off-detector.
        show_profile (bool): Add, for every panel, a paired axis with the
            intensity along `q_parallel`, integrated over
            `±profile_halfwidth_bins` grid columns around `q_perp=0` — the
            same kind of 1-D line profile `plot_rod_tangency`'s own
            `show_profile` adds, except read directly off the
            already-computed warp instead of re-sampling the raw image (no
            separate lateral-integration pass needed, since the warp *is*
            already gridded in physical `q` units). The y-axis (intensity)
            is log-scaled, same reasoning as `plot_rod_tangency`: weak far
            orders stay visible alongside the main peak. For a single
            layer, the profile is a spacious axis of its own with full
            `SL0`/`±N` satellite labels and a legend, same as before; for
            multiple layers/blocks, each panel gets its own *compact*
            profile beside it (small ticks on the right, satellite orders
            as dotted lines only, no text labels/legend) — a single shared
            profile axis across several layers/blocks becomes a tangle of
            overlapping lines and stacked labels fast, so each one gets its
            own instead. Every profile also gets a dashed baseline (see
            :func:`_estimate_baseline`) — a straight line through the
            median level at each edge of the `q_parallel` window,
            extrapolated across the whole profile — as a visual reference
            for the background level the peak/satellites sit on. Requires
            `ax=None` (a fresh figure is always created).
        profile_halfwidth_bins (int): Lateral integration half-width, in
            `q_perp` **grid columns** (not Å⁻¹) — e.g. `3` sums 7 columns
            (`-3, ..., +3`) around the column nearest `q_perp=0`. Unused
            unless `show_profile=True`.
        ncols (int): For multiple layers/blocks only — panel columns before
            wrapping to a new row, same idea as `plot_rod_tangency_blocks`/
            `plot_rod_tangency_harmonics`'s own `ncols`. Unused for a
            single layer (always one row).
        log_scale (bool): Apply `log1p` scaling to the warped image before
            display.
        cmap (str): Matplotlib colormap.
        ax (matplotlib.axes.Axes, optional): Draw into an existing axes
            instead of creating a new figure. Only valid for a single
            layer with `show_profile=False`; raises otherwise.
        figsize: Size of *one* panel (ignored if `ax` is given) — see
            above for how the overall figure size scales with panel count.
        out_path (str or None): Save figure to this path if given.

    Returns:
        Single layer, `show_profile=False` (default, and the only
        backward-compatible case with a plain single-`Axes` return):
        `(fig, ax, warped, q_par_ax, q_perp_ax, info)`.

        Single layer, `show_profile=True`:
        `(fig, (ax, ax_profile), warped, q_par_ax, q_perp_ax, info)`.

        Multiple layers (list or `'all'`, however many actually succeed):
        `(fig, axes, results)`, where `axes` is `img_axes` (a list, one
        per plotted layer) when `show_profile=False`, or
        `(img_axes, profile_axes)` — two parallel lists, one profile axis
        per image axis, in the same order — when `show_profile=True`.
        `results` is a list of
        `{'layer', 'warped', 'q_par_ax', 'q_perp_ax', 'info'}` dicts, one
        per plotted layer, in the same order as `axes`/`img_axes`.
    """
    from .simulation import rod_tangency

    if isinstance(max_satellites, (tuple, list)):
        max_sat_neg, max_sat_pos = int(max_satellites[0]), int(max_satellites[1])
    else:
        max_sat_neg = max_sat_pos = int(max_satellites)
    max_sat_request = max(max_sat_neg, max_sat_pos)  # how many rod_tangency solves for; display is filtered below

    if layer is None or isinstance(layer, str) and layer != "all":
        layers_to_plot = [layer]
    elif isinstance(layer, str) and layer == "all":
        layers_to_plot = _block_representative_layers(stack)
    elif isinstance(layer, (list, tuple)):
        layers_to_plot = list(layer)
    else:
        layers_to_plot = [layer]

    multi = len(layers_to_plot) > 1
    if (multi or show_profile) and ax is not None:
        raise ValueError(
            "multiple layers and/or show_profile=True always create their own figure; pass ax=None"
        )

    results = []
    for ly in layers_to_plot:
        try:
            warped, q_par_ax, q_perp_ax, info = warp_rod_to_qspace(
                stack, hkl, image, layer=ly, camera=camera, ki_hat=ki_hat,
                q_par_range=q_par_range, q_perp_range=q_perp_range,
                n_par=n_par, n_perp=n_perp, half_size_px=half_size_px,
                perp_probe_px=perp_probe_px, interp_order=interp_order,
            )
        except ValueError as e:
            print(f"  plot_rod_qspace_warp: skipping layer {ly!r} — {e}")
            continue
        results.append(
            {"layer": info["layer"], "warped": warped, "q_par_ax": q_par_ax, "q_perp_ax": q_perp_ax, "info": info}
        )
    if not results:
        raise ValueError(f"hkl={tuple(int(x) for x in hkl)} could not be warped for any of the requested layers")

    multi = len(results) > 1  # a requested layer may have been skipped, revisit after the fact
    n_img_panels = len(results)

    if n_img_panels == 1 and not show_profile and ax is not None:
        fig = ax.figure
        img_axes = [ax]
        profile_axes = [None]
    elif n_img_panels == 1:
        # Single layer: spacious side-by-side (image, profile), exactly as before.
        if show_profile:
            fig = plt.figure(figsize=figsize, facecolor=BG)
            gs = mgridspec.GridSpec(1, 2, figure=fig, width_ratios=[1, 1], wspace=0.3, top=0.8)
            img_axes = [fig.add_subplot(gs[0, 0])]
            profile_axes = [fig.add_subplot(gs[0, 1])]
        else:
            fig, ax0 = plt.subplots(figsize=figsize, facecolor=BG)
            img_axes = [ax0]
            profile_axes = [None]
    else:
        # Multiple layers/blocks: small-multiples grid, wrapped after `ncols`
        # panels, each optionally paired with its own compact profile axis --
        # a single shared profile axis across many layers/blocks turns into a
        # tangle of overlapping lines and stacked labels, so each layer gets
        # its own instead (same idea as plot_rod_tangency_blocks's per-panel
        # image+profile pairing).
        ncols_eff = max(1, min(ncols, n_img_panels))
        nrows = int(np.ceil(n_img_panels / ncols_eff))
        if show_profile:
            fig = plt.figure(figsize=(figsize[0] * 1.7 * ncols_eff, figsize[1] * nrows), facecolor=BG)
            outer_gs = mgridspec.GridSpec(nrows, ncols_eff, figure=fig, hspace=0.7, wspace=0.45, top=0.88)
        else:
            fig = plt.figure(figsize=(figsize[0] * ncols_eff, figsize[1] * nrows), facecolor=BG)
            outer_gs = mgridspec.GridSpec(nrows, ncols_eff, figure=fig, hspace=0.55, wspace=0.35, top=0.9)

        # Image panels are linked via sharex/sharey (matplotlib's native axis
        # linking): every panel shows the exact same absolute (q_perp, q_par)
        # window, set once from the first (reference) panel after the drawing
        # loop below, rather than each panel independently autoscaling to its
        # own (generally different) q-range. Linked axes always stay in sync --
        # zooming/panning one moves all of them together too. Same reasoning
        # `_plot_rod_tangency_multi` already uses for its own pixel-space grid.
        ref_img_ax = None
        img_axes, profile_axes = [], []
        for idx in range(n_img_panels):
            row, col = divmod(idx, ncols_eff)
            if show_profile:
                inner_gs = mgridspec.GridSpecFromSubplotSpec(
                    1, 2, subplot_spec=outer_gs[row, col], width_ratios=[1.3, 1], wspace=0.12,
                )
                ax_img = fig.add_subplot(inner_gs[0, 0], sharex=ref_img_ax, sharey=ref_img_ax)
                img_axes.append(ax_img)
                profile_axes.append(fig.add_subplot(inner_gs[0, 1]))
            else:
                ax_img = fig.add_subplot(outer_gs[row, col], sharex=ref_img_ax, sharey=ref_img_ax)
                img_axes.append(ax_img)
                profile_axes.append(None)
            if ref_img_ax is None:
                ref_img_ax = ax_img

    for idx, (ax_i, res) in enumerate(zip(img_axes, results)):
        warped, q_par_ax, q_perp_ax, info = res["warped"], res["q_par_ax"], res["q_perp_ax"], res["info"]
        color = _ROD_TANGENCY_PALETTE[idx % len(_ROD_TANGENCY_PALETTE)] if multi else COL_SUP

        _ax_style(ax_i, "")

        display = np.where(np.isnan(warped), 0.0, warped)
        if log_scale and display.max() > 0:
            display = np.log1p(display / display.max() * 1000.0)
        display[np.isnan(warped)] = np.nan
        display = display.T  # (n_perp, n_par) -> (n_par, n_perp): rows=q_par, cols=q_perp

        extent = [q_perp_ax[0], q_perp_ax[-1], q_par_ax[0], q_par_ax[-1]]
        im = ax_i.imshow(
            display, origin="lower", aspect="auto", extent=extent,
            cmap=cmap, interpolation="nearest",
        )
        cb = fig.colorbar(im, ax=ax_i, pad=0.02, fraction=0.045)
        cb.set_label("log intensity" if log_scale else "intensity", color=FG, fontsize=8)
        cb.ax.tick_params(colors="#7788aa", labelsize=7)

        ax_i.plot(0.0, 0.0, "+", color=FG, ms=10, mew=1.4, zorder=5)
        ax_i.annotate(
            "G0", (0.0, 0.0), xytext=(8, 8),
            textcoords="offset points", color=FG, fontsize=7, zorder=6,
        )

        sat_info = None
        if max_sat_request > 0:
            sat_info = rod_tangency(
                stack, hkl, layer=info["layer"], camera=camera, ki_hat=ki_hat,
                max_satellites=max_sat_request,
            )
            for m, sat in sat_info["satellites"].items():
                if m < -max_sat_neg or m > max_sat_pos:
                    continue
                if sat["pix"] is None or not sat["on_detector"]:
                    continue
                q_m = sat["along"]
                if q_par_ax[0] <= q_m <= q_par_ax[-1]:
                    ax_i.plot(0.0, q_m, "o", color=color, ms=6, mec=BG, mew=0.6, zorder=4)
                    ax_i.annotate(
                        "SL0" if m == 0 else f"{m:+d}", (0.0, q_m), xytext=(8, 0),
                        textcoords="offset points", color=color, fontsize=7, va="center", zorder=6,
                    )

        if show_relaxed_buffer:
            if not stack.buffer_layers:
                print("  plot_rod_qspace_warp: show_relaxed_buffer skipped — stack has no buffer layers")
            elif stack.buffer_layers[-1].label == info["layer"]:
                print(f"  plot_rod_qspace_warp: show_relaxed_buffer skipped — "
                      f"{info['layer']!r} is already the plotted layer")
            else:
                buf_layer = stack.buffer_layers[-1]
                try:
                    buf_info = rod_tangency(stack, hkl, layer=buf_layer, camera=camera, ki_hat=ki_hat)
                except ValueError as e:
                    buf_info = None
                    print(f"  plot_rod_qspace_warp: show_relaxed_buffer skipped — {e}")
                if buf_info is not None and not buf_info["on_detector"]:
                    print(
                        f"  plot_rod_qspace_warp: show_relaxed_buffer skipped — "
                        f"hkl={buf_info['hkl']} is off-detector for buffer layer {buf_info['layer']!r}"
                    )
                elif buf_info is not None:
                    h, k, l = info["hkl"]
                    G0_buf = buf_layer.U @ buf_layer.crystal.Q(h, k, l)
                    dQ = G0_buf - info["G0"]
                    q_par_buf = float(np.dot(dQ, info["n_hat"]))
                    q_perp_buf = float(np.dot(dQ, info["perp_hat"]))
                    ax_i.plot(
                        q_perp_buf, q_par_buf, "D", color="#9ca3af", ms=8, mfc="none", mew=1.6, zorder=6,
                        label=f"relaxed buffer ({buf_info['layer']})",
                    )
                    leg = ax_i.legend(loc="upper right", fontsize=6.5, facecolor=BG, edgecolor="#333355", labelcolor=FG)
                    leg.get_frame().set_alpha(0.85)

        ax_i.set_xlabel(r"$q_\perp$  (Å⁻¹)", color=FG, fontsize=8)
        ax_i.set_ylabel(r"$q_\parallel$  (Å⁻¹)", color=FG, fontsize=8)
        title = f"hkl={info['hkl']}  ({info['layer']})  E0={info['E0']:.0f} eV"
        if multi:
            title += f"  |{info['dpix_dalong']:.1e} px/Å⁻¹"
        ax_i.set_title(title, color=FG, fontsize=9, pad=6)

        ax_p = profile_axes[idx]
        if ax_p is not None:
            iperp0 = int(np.argmin(np.abs(q_perp_ax)))
            lo = max(iperp0 - profile_halfwidth_bins, 0)
            hi = min(iperp0 + profile_halfwidth_bins + 1, len(q_perp_ax))
            profile = np.nansum(warped[lo:hi, :], axis=0)  # (n_perp, n_par) -> (n_par,)
            baseline = _estimate_baseline(q_par_ax, profile)

            _ax_style(ax_p, "")
            ax_p.axvline(0.0, color=FG, lw=0.8 if not multi else 0.6, alpha=0.4)
            if not multi:
                # Single layer: spacious, fully-labelled profile, as before.
                ax_p.plot(
                    q_par_ax, baseline, "--", color=FG, lw=1.0, alpha=0.5,
                    label="baseline (extrapolated from edges)",
                )
                ax_p.plot(
                    q_par_ax, profile, "-", color=color, lw=1.3,
                    label="measured (± " + f"{profile_halfwidth_bins} bins lateral)",
                )
                ax_p.set_yscale("log")
                ax_p.set_xlabel(r"$q_\parallel$  (Å⁻¹)", color=FG, fontsize=8)
                ax_p.set_ylabel(
                    f"intensity  (Σ over ±{profile_halfwidth_bins} bins lateral)", color=FG, fontsize=8
                )
                if sat_info is not None:
                    for m, sat in sat_info["satellites"].items():
                        if m < -max_sat_neg or m > max_sat_pos:
                            continue
                        if sat["pix"] is None or not sat["on_detector"]:
                            continue
                        q_m = sat["along"]
                        if q_par_ax[0] <= q_m <= q_par_ax[-1]:
                            ax_p.axvline(q_m, color=color, lw=0.8, ls=":", alpha=0.6)
                            ax_p.text(
                                q_m, 1.02, "SL0" if m == 0 else f"{m:+d}",
                                transform=ax_p.get_xaxis_transform(),
                                color=color, fontsize=7, ha="center", va="bottom", clip_on=False,
                            )
                leg_p = ax_p.legend(loc="upper right", fontsize=6.5, facecolor=BG, edgecolor="#333355", labelcolor=FG)
                leg_p.get_frame().set_alpha(0.85)
                ax_p.set_title(r"Warped intensity along $q_\parallel$", color=FG, fontsize=9, pad=20)
            else:
                # Several layers/blocks: compact per-panel profile -- no legend
                # (colour + the paired image panel's own title already identify
                # it), but satellite orders still get a small label each, since
                # each panel now has its own profile axis, not one shared one --
                # the earlier "messy" overlap was several *layers'* labels
                # competing for the same axis, not labels within one panel.
                ax_p.plot(q_par_ax, baseline, "--", color=FG, lw=0.7, alpha=0.4)
                ax_p.plot(q_par_ax, profile, "-", color=color, lw=1.1)
                ax_p.set_yscale("log")
                ax_p.tick_params(labelsize=6)
                ax_p.set_xlabel(r"$q_\parallel$ (Å⁻¹)", color=FG, fontsize=6.5)
                ax_p.yaxis.tick_right()
                if sat_info is not None:
                    for m, sat in sat_info["satellites"].items():
                        if m < -max_sat_neg or m > max_sat_pos:
                            continue
                        if sat["pix"] is None or not sat["on_detector"]:
                            continue
                        q_m = sat["along"]
                        if q_par_ax[0] <= q_m <= q_par_ax[-1]:
                            ax_p.axvline(q_m, color=color, lw=0.6, ls=":", alpha=0.5)
                            ax_p.text(
                                q_m, 1.02, "SL0" if m == 0 else f"{m:+d}",
                                transform=ax_p.get_xaxis_transform(),
                                color=color, fontsize=5.5, ha="center", va="bottom", clip_on=False,
                            )

    if multi:
        # Fix the shared (linked) view once, from the first panel's own
        # window -- must happen after every panel's imshow() above, or a
        # later panel's own autoscale would just re-centre the shared view
        # on itself.
        ref_q_par_ax, ref_q_perp_ax = results[0]["q_par_ax"], results[0]["q_perp_ax"]
        img_axes[0].set_xlim(ref_q_perp_ax[0], ref_q_perp_ax[-1])
        img_axes[0].set_ylim(ref_q_par_ax[0], ref_q_par_ax[-1])

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    if not multi:
        r0 = results[0]
        if show_profile:
            return fig, (img_axes[0], profile_axes[0]), r0["warped"], r0["q_par_ax"], r0["q_perp_ax"], r0["info"]
        return fig, img_axes[0], r0["warped"], r0["q_par_ax"], r0["q_perp_ax"], r0["info"]

    axes_ret = (img_axes, profile_axes) if show_profile else img_axes
    return fig, axes_ret, results

plot_rod_tangency

plot_rod_tangency(stack, hkl, layer=None, camera=None, *, ki_hat=None, max_satellites=0, n_harmonics=1, arrow_length_px=60, image=None, pad_px=40, show_profile=False, profile_halfwidth_px=3, profile_step_px=1.0, show_relaxed_buffer=False, alpha=0.85, ax=None, figsize=(6.0, 6.0), out_path=None)

Show a reflection's superlattice-rod orientation relative to the detector — the streak elongation direction (d(pixel)/d(along) from :func:~nrxrdct.laue.simulation.rod_tangency) with a perpendicular reference line (a display axis only — the streak's width comes from off-rod structure-factor decay, not something derived here).

layer accepts several forms so the same hkl can be compared across every layer in the stack at once — since each layer generally has its own (possibly pseudomorphically strained) lattice, "the same" Miller indices land at a slightly different G0, hence a different pixel, energy, and streak direction, for each one:

  • a single Layer/label (or None, the default stack.layers[0]) — one coloured line, as before;
  • a list of Layer/label — one coloured line per entry;
  • 'all' — every layer in stack.all_layers.

With max_satellites > 0, each layer's own discrete satellite comb (m = -max_satellites, ..., max_satellites, at that layer's own period) is marked with small dots along its streak line — so you can directly compare where each layer's satellite orders would land, not just the fundamental's direction.

What to actually compare across candidates is info['dpix_dalong'] (shown in the title for a single layer, or in the legend per layer for several) — large means a given accessible Qn range maps to a long streak on the detector, small means the rod stays compact even over several satellite orders. Overlay this on a measured/simulated image to see whether a line's direction tracks a real elongated feature.

Whenever more than one m=0 peak is drawn — multiple layers, and/or n_harmonics > 1 adding harmonic peaks — a white star marks the unweighted average of all those peaks' pixel positions (not shown for a single peak, since it would just duplicate that peak's own + marker). Satellite-order dots are not included, only the fundamental pix0/harmonic markers.

Parameters:
  • stack, hkl, camera, ki_hat –

    Forwarded to :func:~nrxrdct.laue.simulation.rod_tangency.

  • layer –

    Single layer/label/None, a list of them, or 'all' — see above.

  • max_satellites (int, default: 0 ) –

    Forwarded to rod_tangency for every layer — 0 (default) shows only the streak-direction line; > 0 also marks each layer's own satellite-order positions.

  • n_harmonics (int, default: 1 ) –

    1 (default) plots only the fundamental hkl. N > 1 also evaluates rod_tangency for the harmonic reflections 2·hkl, ..., N·hkl of every plotted layer — same Q-space direction as the fundamental (Q_n = n·Q_1 exactly, so its m=0 peak lands on essentially the same pixel), the classic Laue harmonic-overlap reflections excited at n·E0. Each harmonic's own m=0 peak (triangle marker, labelled n2, n3, ...) and satellite comb are drawn in their own colour (cycled through the same palette, offset from the layer's own) at reduced alpha, so a harmonic's rod can be compared against the fundamental's — useful since a higher harmonic can fan out to a different streak length/direction even though it starts at (almost) the same spot. If max_satellites > 0, the number of satellite orders solved for each harmonic doubles with every successive harmonic (max_satellites × 2**(n-1) for harmonic n) — a higher harmonic sits at a larger |Q| where the same physical fringe spacing subtends more orders before falling off the detector/energy window, so a fixed count would under-sample it. When show_profile=True, each harmonic's m=0/satellite pixels are also projected onto the fundamental's own rod axis and drawn as dotted vertical lines on the profile panel, in the same colour as their main-axis markers. Skipped per-harmonic (with a printed note) if unreachable or off-detector; not included in the returned infos (those stay fundamental-only).

  • arrow_length_px (float or (float, float), default: 60 ) –

    Approximate half-length of the streak-direction line (pixels), and (when show_profile=True) of the profile's sampled extent. A single number (default 60) draws/samples symmetrically, ±arrow_length_px from pix0. A (neg, pos) tuple draws/samples asymmetrically — neg pixels against streak_dir_px and pos pixels along it — e.g. to extend further toward one satellite order than the other, or to frame a show_relaxed_buffer marker that sits off to one side. The perpendicular reference line's half-length is (neg + pos) / 6. Internally converted to a ΔQ extent via the local dpix_dalong at along=0 and then sampled exactly along the true rod (rod_positions) — since the pixel↔Q map is generally nonlinear, the drawn line's actual on-detector pixel length can differ somewhat from arrow_length_px (this is the trade-off for the line and its satellite dots agreeing everywhere, not just near along=0).

  • image ((ndarray, shape(Nv, Nh)), default: None ) –

    Measured or simulated detector frame to show cropped behind the arrows, for context. None (default) shows a plain dark background.

  • pad_px (float, default: 40 ) –

    Half-size of the cropped window shown, centred on the mean of every plotted layer's pix0.

  • show_profile (bool, default: False ) –

    Add a second axis with the intensity extracted from image along each layer's own rod — a line profile, not just a 2-D overlay. Sample points are the exact rod trajectory (rod_positions, not a straight pixel-space line through streak_dir_px), so the sampled path tracks a curved rod instead of drifting off it away from along=0. At each sample point, profile_halfwidth_px pixels are summed on either side perpendicular to the local streak direction (i.e. along perp_dir_px) via bilinear interpolation (scipy.ndimage.map_coordinates), so the profile isn't dominated by single-pixel noise. The x-axis is the exact ΔQ (Å⁻¹) each sample point was solved at — not a linear pixel-offset/dpix_dalong rescaling — so it stays correct far from along=0 and lines up exactly with the satellite markers, which are solved the same way. dpix_dalong is only used to pick a sampling range/step from arrow_length_px/ profile_step_px (both given in pixels for convenience); it does not affect where samples actually land. Satellite orders are labelled (SL0, SL±N) same as the main axis. The y-axis (intensity) is log-scaled, so weak far orders remain visible alongside the main peak — points with zero/negative summed intensity are simply omitted by matplotlib, not an error. Requires image; requires ax=None (a fresh figure is always created, so the two axes can be laid out side by side).

  • profile_halfwidth_px (int, default: 3 ) –

    Lateral integration half-width (pixels) for show_profile — e.g. 3 sums 7 pixels (-3, ..., +3) perpendicular to the local streak direction at each point along the rod. Unused unless show_profile=True.

  • profile_step_px (float, default: 1.0 ) –

    Approximate sampling step (pixels, via the local dpix_dalong — see show_profile) for show_profile, over the same extent as arrow_length_px. Unused unless show_profile=True.

  • show_relaxed_buffer (bool, default: False ) –

    Mark where the same hkl would fall using the shallowest buffer layer's own (relaxed/bulk, since rod_tangency always evaluates layer.crystal.Q(h,k,l) — never strain-corrected) lattice — stack.buffer_layers[-1], the template a repeating block is grown on. A grey diamond, distinct from every plotted layer's own marker, so you can see at a glance how far a pseudomorphically strained layer's peak has moved from the unstrained template's position for the same nominal reflection. Skipped (with a note) if that buffer layer's own hkl is off-detector, and not duplicated if it's already one of the plotted layers. When show_profile=True, also marked ("buf", dotted grey line, same styling as the diamond) on every plotted layer's own profile axis — an approximate marker, since the buffer's own rod generally doesn't coincide with a strained layer's rod at all (that's the point of this option), so its pixel position is projected onto each layer's local streak direction rather than given an exact ΔQ, the same approximation used for the harmonic overlay markers.

  • alpha (float, default: 0.85 ) –

    Opacity applied to each layer's own streak-direction line and satellite-order markers (default 0.85); harmonics already draw at their own fixed, lower alpha regardless of this.

  • ax (Axes, default: None ) –

    Draw into an existing axes instead of creating a new figure. Incompatible with show_profile=True (raises).

  • figsize –

    Figure size (ignored if ax is given; when show_profile=True this is the size of the combined two-panel figure).

  • out_path (str or None, default: None ) –

    Save figure to this path if given.

Returns:
  • –

    show_profile=False (default): (fig, ax, infos).

  • –

    show_profile=True: (fig, (ax, ax_profile), infos).

  • –

    infos is a list of rod_tangency's own return dicts, one per

  • –

    plotted layer, in the same order as drawn.

Source code in src/nrxrdct/laue/laue_plotting.py
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
def plot_rod_tangency(
    stack,
    hkl,
    layer=None,
    camera=None,
    *,
    ki_hat=None,
    max_satellites=0,
    n_harmonics=1,
    arrow_length_px=60,
    image=None,
    pad_px=40,
    show_profile=False,
    profile_halfwidth_px=3,
    profile_step_px=1.0,
    show_relaxed_buffer=False,
    alpha=0.85,
    ax=None,
    figsize=(6.0, 6.0),
    out_path=None,
):
    """
    Show a reflection's superlattice-rod orientation relative to the
    detector — the streak elongation direction (`d(pixel)/d(along)` from
    :func:`~nrxrdct.laue.simulation.rod_tangency`) with a perpendicular
    reference line (a display axis only — the streak's *width* comes from
    off-rod structure-factor decay, not something derived here).

    `layer` accepts several forms so the **same** `hkl` can be compared
    across every layer in the stack at once — since each layer generally
    has its own (possibly pseudomorphically strained) lattice, "the same"
    Miller indices land at a slightly different `G0`, hence a different
    pixel, energy, and streak direction, for each one:

    * a single `Layer`/label (or `None`, the default `stack.layers[0]`) —
      one coloured line, as before;
    * a list of `Layer`/label — one coloured line per entry;
    * `'all'` — every layer in `stack.all_layers`.

    With `max_satellites > 0`, each layer's own discrete satellite comb
    (`m = -max_satellites, ..., max_satellites`, at that layer's own
    period) is marked with small dots along its streak line — so you can
    directly compare *where* each layer's satellite orders would land,
    not just the fundamental's direction.

    What to actually compare across candidates is `info['dpix_dalong']`
    (shown in the title for a single layer, or in the legend per layer for
    several) — large means a given accessible `Qn` range maps to a long
    streak on the detector, small means the rod stays compact even over
    several satellite orders. Overlay this on a measured/simulated `image`
    to see whether a line's direction tracks a real elongated feature.

    Whenever more than one `m=0` peak is drawn — multiple layers, and/or
    `n_harmonics > 1` adding harmonic peaks — a white star marks the
    unweighted average of all those peaks' pixel positions (not shown for
    a single peak, since it would just duplicate that peak's own `+`
    marker). Satellite-order dots are not included, only the fundamental
    `pix0`/harmonic markers.

    Args:
        stack, hkl, camera, ki_hat: Forwarded to
            :func:`~nrxrdct.laue.simulation.rod_tangency`.
        layer: Single layer/label/`None`, a list of them, or `'all'` — see
            above.
        max_satellites (int): Forwarded to `rod_tangency` for every layer —
            `0` (default) shows only the streak-direction line; `> 0` also
            marks each layer's own satellite-order positions.
        n_harmonics (int): `1` (default) plots only the fundamental `hkl`.
            `N > 1` also evaluates `rod_tangency` for the harmonic
            reflections `2·hkl, ..., N·hkl` of every plotted layer — same
            Q-space direction as the fundamental (`Q_n = n·Q_1` exactly,
            so its `m=0` peak lands on essentially the same pixel), the
            classic Laue harmonic-overlap reflections excited at `n·E0`.
            Each harmonic's own `m=0` peak (triangle marker, labelled
            `n2`, `n3`, ...) and satellite comb are drawn in their own
            colour (cycled through the same palette, offset from the
            layer's own) at reduced alpha, so a harmonic's rod can be
            compared against the fundamental's — useful since a higher
            harmonic can fan out to a different streak length/direction
            even though it starts at (almost) the same spot. If
            `max_satellites > 0`, the number of satellite orders solved
            for each harmonic doubles with every successive harmonic
            (`max_satellites × 2**(n-1)` for harmonic `n`) — a higher
            harmonic sits at a larger `|Q|` where the same physical
            fringe spacing subtends more orders before falling off the
            detector/energy window, so a fixed count would under-sample
            it. When `show_profile=True`, each harmonic's `m=0`/satellite
            pixels are also projected onto the fundamental's own rod axis
            and drawn as dotted vertical lines on the profile panel, in
            the same colour as their main-axis markers. Skipped
            per-harmonic (with a printed note) if unreachable or
            off-detector; not included in the returned `infos` (those
            stay fundamental-only).
        arrow_length_px (float or (float, float)): Approximate half-length
            of the streak-direction line (pixels), and (when
            `show_profile=True`) of the profile's sampled extent. A single
            number (default `60`) draws/samples symmetrically,
            `±arrow_length_px` from `pix0`. A `(neg, pos)` tuple
            draws/samples asymmetrically — `neg` pixels against
            `streak_dir_px` and `pos` pixels along it — e.g. to extend
            further toward one satellite order than the other, or to frame
            a `show_relaxed_buffer` marker that sits off to one side. The
            perpendicular reference line's half-length is `(neg + pos) / 6`.
            Internally converted to a `ΔQ` extent via the local
            `dpix_dalong` at `along=0` and then sampled *exactly* along the
            true rod (`rod_positions`) — since the pixel↔Q map is generally
            nonlinear, the drawn line's actual on-detector pixel length can
            differ somewhat from `arrow_length_px` (this is the trade-off
            for the line and its satellite dots agreeing everywhere, not
            just near `along=0`).
        image (ndarray, shape (Nv, Nh), optional): Measured or simulated
            detector frame to show cropped behind the arrows, for context.
            `None` (default) shows a plain dark background.
        pad_px (float): Half-size of the cropped window shown, centred on
            the mean of every plotted layer's `pix0`.
        show_profile (bool): Add a second axis with the intensity
            extracted from `image` along each layer's own rod — a line
            profile, not just a 2-D overlay. Sample points are the *exact*
            rod trajectory (`rod_positions`, not a straight pixel-space line
            through `streak_dir_px`), so the sampled path tracks a curved
            rod instead of drifting off it away from `along=0`. At each
            sample point, `profile_halfwidth_px` pixels are summed on
            either side *perpendicular* to the local streak direction (i.e.
            along `perp_dir_px`) via bilinear interpolation
            (`scipy.ndimage.map_coordinates`), so the profile isn't
            dominated by single-pixel noise. The x-axis is the exact `ΔQ`
            (Å⁻¹) each sample point was solved at — not a linear
            pixel-offset/`dpix_dalong` rescaling — so it stays correct far
            from `along=0` and lines up exactly with the satellite markers,
            which are solved the same way. `dpix_dalong` is only used to
            pick a sampling range/step from `arrow_length_px`/
            `profile_step_px` (both given in pixels for convenience); it
            does not affect where samples actually land. Satellite orders
            are labelled (`SL0`, `SL±N`) same as the main axis. The y-axis
            (intensity) is log-scaled, so weak far orders remain visible
            alongside the main peak — points with zero/negative summed
            intensity are simply omitted by matplotlib, not an error.
            Requires `image`; requires `ax=None` (a fresh figure is always
            created, so the two axes can be laid out side by side).
        profile_halfwidth_px (int): Lateral integration half-width
            (pixels) for `show_profile` — e.g. `3` sums 7 pixels
            (`-3, ..., +3`) perpendicular to the local streak direction at
            each point along the rod. Unused unless `show_profile=True`.
        profile_step_px (float): Approximate sampling step (pixels, via the
            local `dpix_dalong` — see `show_profile`) for `show_profile`,
            over the same extent as `arrow_length_px`. Unused unless
            `show_profile=True`.
        show_relaxed_buffer (bool): Mark where the *same* `hkl` would fall
            using the shallowest buffer layer's own (relaxed/bulk, since
            `rod_tangency` always evaluates `layer.crystal.Q(h,k,l)` —
            never strain-corrected) lattice — `stack.buffer_layers[-1]`,
            the template a repeating block is grown on.  A grey diamond,
            distinct from every plotted layer's own marker, so you can see
            at a glance how far a pseudomorphically strained layer's peak
            has moved from the unstrained template's position for the
            same nominal reflection.  Skipped (with a note) if that buffer
            layer's own `hkl` is off-detector, and not duplicated if it's
            already one of the plotted layers. When `show_profile=True`, also
            marked (`"buf"`, dotted grey line, same styling as the diamond)
            on every plotted layer's own profile axis — an *approximate*
            marker, since the buffer's own rod generally doesn't coincide
            with a strained layer's rod at all (that's the point of this
            option), so its pixel position is projected onto each layer's
            local streak direction rather than given an exact ΔQ, the same
            approximation used for the harmonic overlay markers.
        alpha (float): Opacity applied to each layer's own streak-direction
            line and satellite-order markers (default `0.85`); harmonics
            already draw at their own fixed, lower alpha regardless of this.
        ax (matplotlib.axes.Axes, optional): Draw into an existing axes
            instead of creating a new figure.  Incompatible with
            `show_profile=True` (raises).
        figsize: Figure size (ignored if `ax` is given; when
            `show_profile=True` this is the size of the *combined*
            two-panel figure).
        out_path (str or None): Save figure to this path if given.

    Returns:
        `show_profile=False` (default): ``(fig, ax, infos)``.
        `show_profile=True`: ``(fig, (ax, ax_profile), infos)``.
        `infos` is a list of `rod_tangency`'s own return dicts, one per
        plotted layer, in the same order as drawn.
    """
    from .simulation import rod_tangency, rod_positions

    if show_profile:
        if image is None:
            raise ValueError("show_profile=True requires `image`")
        if ax is not None:
            raise ValueError("show_profile=True always creates its own two-panel figure; pass ax=None")

    if layer is None or isinstance(layer, str) and layer != "all":
        layers_to_plot = [layer]
    elif isinstance(layer, str) and layer == "all":
        layers_to_plot = list(stack.all_layers)
    elif isinstance(layer, (list, tuple)):
        layers_to_plot = list(layer)
    else:
        layers_to_plot = [layer]

    infos = []
    for ly in layers_to_plot:
        try:
            info = rod_tangency(stack, hkl, layer=ly, camera=camera, ki_hat=ki_hat, max_satellites=max_satellites)
        except ValueError as e:
            print(f"  plot_rod_tangency: skipping layer {ly!r} — {e}")
            continue
        if not info["on_detector"]:
            print(f"  plot_rod_tangency: skipping layer {info['layer']!r} — hkl={info['hkl']} is off-detector")
            continue
        infos.append(info)
    if not infos:
        raise ValueError(f"hkl={tuple(int(x) for x in hkl)} lands on-detector for none of the requested layers")

    cx = float(np.mean([info["pix0"][0] for info in infos]))
    cy = float(np.mean([info["pix0"][1] for info in infos]))

    ax_profile = None
    if show_profile:
        fig = plt.figure(figsize=figsize, facecolor=BG)
        gs = mgridspec.GridSpec(1, 2, figure=fig, width_ratios=[1, 1], wspace=0.3, top=0.8)
        ax = fig.add_subplot(gs[0, 0])
        ax_profile = fig.add_subplot(gs[0, 1])
    elif ax is None:
        fig, ax = plt.subplots(figsize=figsize, facecolor=BG)
    else:
        fig = ax.figure
    _ax_style(ax, "")
    ax.set_xlabel("xcam  (px)", color=FG, fontsize=8)
    ax.set_ylabel("ycam  (px)", color=FG, fontsize=8)

    if image is not None:
        img_arr = np.asarray(image, dtype=float)
        Ny, Nx = img_arr.shape
        x0 = max(int(cx - pad_px), 0)
        x1 = min(int(cx + pad_px), Nx)
        y0 = max(int(cy - pad_px), 0)
        y1 = min(int(cy + pad_px), Ny)
        patch = img_arr[y0:y1, x0:x1]
        ax.imshow(
            np.log1p(patch), origin="upper", extent=[x0, x1, y1, y0],
            cmap="gray", aspect="equal",
        )

    if isinstance(arrow_length_px, (tuple, list)):
        arrow_neg, arrow_pos = float(arrow_length_px[0]), float(arrow_length_px[1])
    else:
        arrow_neg = arrow_pos = float(arrow_length_px)
    perp_len = (arrow_neg + arrow_pos) / 6.0
    multi = len(infos) > 1
    peak_points = []

    # Resolved once, up front, so the per-layer loop below can also mark it
    # on each layer's own profile-panel axis (not just the left/image panel,
    # where it's drawn further down after the loop).
    buf_info = None
    if show_relaxed_buffer:
        plotted_labels = {info["layer"] for info in infos}
        if not stack.buffer_layers:
            print("  plot_rod_tangency: show_relaxed_buffer skipped — stack has no buffer layers")
        else:
            buf_layer = stack.buffer_layers[-1]
            if buf_layer.label in plotted_labels:
                print(f"  plot_rod_tangency: show_relaxed_buffer skipped — "
                      f"{buf_layer.label!r} is already one of the plotted layers")
            else:
                try:
                    buf_info = rod_tangency(stack, hkl, layer=buf_layer, camera=camera, ki_hat=ki_hat)
                except ValueError as e:
                    print(f"  plot_rod_tangency: show_relaxed_buffer skipped — {e}")
                if buf_info is not None and not buf_info["on_detector"]:
                    print(
                        f"  plot_rod_tangency: show_relaxed_buffer skipped — "
                        f"hkl={buf_info['hkl']} is off-detector for buffer layer {buf_info['layer']!r}"
                    )
                    buf_info = None

    for i, info in enumerate(infos):
        color = _ROD_TANGENCY_PALETTE[i % len(_ROD_TANGENCY_PALETTE)]
        px0, py0 = info["pix0"]
        streak = info["streak_dir_px"]
        perp = info["perp_dir_px"]

        # The true rod is only a straight line in pixel space to first order
        # (streak/dpix_dalong are the local Jacobian at along=0); for a
        # non-negligible extent it generally curves, same as the discrete
        # satellite dots below (already solved exactly, not off this line).
        # Sample it exactly with rod_positions instead of drawing the naive
        # 2-point straight segment, so the line tracks where those dots (and
        # the profile panel, further below) actually are.
        jac_mag_i = info["dpix_dalong"]
        along_neg = arrow_neg / jac_mag_i if jac_mag_i > 1e-12 else arrow_neg
        along_pos = arrow_pos / jac_mag_i if jac_mag_i > 1e-12 else arrow_pos
        along_line = np.linspace(-along_neg, along_pos, 81)
        rp_line = rod_positions(stack, hkl, layer=info["layer"], along=along_line, camera=camera, ki_hat=ki_hat)
        line_pix = rp_line["pix"]

        label = f"{info['layer']}  ({info['dpix_dalong']:.1e} px/Å⁻¹)" if multi else "streak direction (d(pixel)/d(along))"
        ax.plot(
            line_pix[:, 0], line_pix[:, 1],
            "-", color=color, lw=2.5, alpha=alpha, solid_capstyle="round", label=label,
        )
        if not multi:
            ax.plot(
                [px0 - perp_len * perp[0], px0 + perp_len * perp[0]],
                [py0 - perp_len * perp[1], py0 + perp_len * perp[1]],
                "--", color=COL_BCC, lw=1.5, solid_capstyle="round",
                label="perpendicular (reference axis only)",
            )
        ax.plot(px0, py0, "+", color=color if multi else FG, ms=10, mew=1.4, zorder=5)
        peak_points.append((px0, py0))

        label_off = 8.0 * perp  # small perpendicular offset so text doesn't sit on the marker/line
        if max_satellites > 0:
            ax.annotate(
                "SL0", (px0, py0), xytext=(px0 + label_off[0], py0 + label_off[1]),
                color=color, fontsize=7, ha="center", va="center", zorder=6,
            )

        for m, sat in info["satellites"].items():
            if sat["pix"] is None or not sat["on_detector"]:
                continue
            if m == 0 and abs(sat["along"]) < 1e-9:
                # Coincides with the "SL0"/"+" marker already drawn above
                # (always true when is_superlattice=False; only true for
                # is_superlattice=True if G0 happens to be exactly
                # commensurate with the block period).
                continue
            sx, sy = sat["pix"]
            ax.plot(sx, sy, "o", color=color, ms=6, mfc=color, mec=BG, mew=0.6, alpha=alpha, zorder=4)
            # m=0 here means "the true comb peak nearest hkl", offset from
            # the exact-hkl "SL0" marker -- label "0", not "+0", so it isn't
            # mistaken for the +1 order.
            mlabel = "0" if m == 0 else f"{m:+d}"
            ax.annotate(
                mlabel, (sx, sy), xytext=(sx + label_off[0], sy + label_off[1]),
                color=color, fontsize=7, ha="center", va="center", zorder=6,
            )

        if show_profile:
            from scipy.ndimage import map_coordinates

            # Sample the image along the *exact* rod trajectory (rod_positions),
            # not a straight pixel-space line through px0 in the streak
            # direction — that direction is only the local (along=0) Jacobian,
            # and the true pixel↔Q map is nonlinear, so a straight line drifts
            # off the real (generally curved) feature away from the centre.
            # Using the same `along` (ΔQ) array both to pick the sample points
            # and as the plotted x-axis (no separate pixel→Q rescaling) keeps
            # this panel exactly consistent with the satellite markers below,
            # which are already solved exactly at their own `along` values.
            along_step = profile_step_px / jac_mag_i if jac_mag_i > 1e-12 else profile_step_px
            along_neg_p = arrow_neg / jac_mag_i if jac_mag_i > 1e-12 else arrow_neg
            along_pos_p = arrow_pos / jac_mag_i if jac_mag_i > 1e-12 else arrow_pos
            q_vals = np.arange(-along_neg_p, along_pos_p + 0.5 * along_step, along_step)

            rp_prof = rod_positions(stack, hkl, layer=info["layer"], along=q_vals, camera=camera, ki_hat=ki_hat)
            center_pts = rp_prof["pix"]  # (N, 2); NaN rows -> gaps in the line/sum below

            profile = np.zeros(len(q_vals))
            for off in range(-profile_halfwidth_px, profile_halfwidth_px + 1):
                pts = center_pts + off * perp[None, :]
                coords = np.array([pts[:, 1], pts[:, 0]])  # map_coordinates wants [row, col] = [y, x]
                with np.errstate(invalid="ignore"):
                    profile += map_coordinates(img_arr, coords, order=1, mode="nearest")

            plabel = f"{info['layer']}" if multi else "measured (± " + f"{profile_halfwidth_px} px lateral sum)"
            ax_profile.plot(q_vals, profile, "-", color=color, lw=1.3, label=plabel)

            label_y = 1.03 + 0.07 * i  # stagger per layer, outside the axes proper
            if max_satellites > 0:
                ax_profile.text(
                    0.0, label_y, "SL0", transform=ax_profile.get_xaxis_transform(),
                    color=color, fontsize=7, ha="center", va="bottom", clip_on=False,
                )
            for m, sat in info["satellites"].items():
                if sat["pix"] is None or not sat["on_detector"]:
                    continue
                if m == 0 and abs(sat["along"]) < 1e-9:
                    continue  # coincides with "SL0" already drawn at 0.0 above
                # Use rod_tangency's own exact `along` for this order directly
                # -- it already accounts for is_superlattice's comb-anchoring
                # (nearest true tooth, not naively at G0) and the m±0.5
                # bright-fringe offset for a single layer; recomputing it here
                # from `m`/`period` alone would silently drop that anchoring.
                q_m = sat["along"]
                mlabel = "0" if m == 0 else f"{m:+d}"
                if q_vals[0] <= q_m <= q_vals[-1]:
                    ax_profile.axvline(q_m, color=color, lw=0.8, ls=":", alpha=0.6)
                    ax_profile.text(
                        q_m, label_y, mlabel, transform=ax_profile.get_xaxis_transform(),
                        color=color, fontsize=7, ha="center", va="bottom", clip_on=False,
                    )

            if buf_info is not None:
                # Same approximate projection as the harmonic markers below:
                # the relaxed buffer's own G0 generally sits off *this*
                # layer's rod entirely (that's the whole point -- showing how
                # far a strained layer's peak has moved from the unstrained
                # template), so there is no exact ΔQ "along this rod" for it.
                # Project its pixel position onto the local streak direction
                # as a readable approximation, same grey styling as the
                # left-panel diamond.
                buf_s = float(np.dot(np.array(buf_info["pix0"]) - np.array([px0, py0]), streak))
                if -arrow_neg <= buf_s <= arrow_pos:
                    buf_q = buf_s / jac_mag_i if jac_mag_i > 1e-12 else buf_s
                    ax_profile.axvline(buf_q, color="#9ca3af", lw=0.8, ls=":", alpha=0.6)
                    ax_profile.text(
                        buf_q, label_y, "buf", transform=ax_profile.get_xaxis_transform(),
                        color="#9ca3af", fontsize=7, ha="center", va="bottom", clip_on=False,
                    )

        if n_harmonics > 1:
            h0, k0, l0 = info["hkl"]
            for n in range(2, n_harmonics + 1):
                h_max_sat = max_satellites * (2 ** (n - 1))
                try:
                    hinfo = rod_tangency(
                        stack, (n * h0, n * k0, n * l0), layer=info["layer"], camera=camera,
                        ki_hat=ki_hat, max_satellites=h_max_sat,
                    )
                except ValueError as e:
                    print(f"  plot_rod_tangency: skipping harmonic n={n} of layer {info['layer']!r} — {e}")
                    continue
                if not hinfo["on_detector"]:
                    print(f"  plot_rod_tangency: skipping harmonic n={n} of layer {info['layer']!r} — off-detector")
                    continue
                hcolor = _ROD_TANGENCY_PALETTE[(i + n - 1) % len(_ROD_TANGENCY_PALETTE)]
                hx, hy = hinfo["pix0"]
                peak_points.append((hx, hy))
                ax.plot(hx, hy, "^", color=hcolor, alpha=0.55, ms=7, mec=BG, mew=0.5, zorder=3)
                ax.annotate(
                    f"n{n}", (hx, hy), xytext=(hx + label_off[0], hy + label_off[1]),
                    color=hcolor, alpha=0.85, fontsize=7, ha="center", va="center", zorder=3,
                )
                if show_profile:
                    hs0 = float(np.dot(np.array(hinfo["pix0"]) - np.array([px0, py0]), streak))
                    if -arrow_neg <= hs0 <= arrow_pos:
                        hq0 = hs0 / info["dpix_dalong"]
                        ax_profile.axvline(hq0, color=hcolor, lw=0.8, ls=":", alpha=0.6)
                        ax_profile.text(
                            hq0, label_y, f"n{n}", transform=ax_profile.get_xaxis_transform(),
                            color=hcolor, fontsize=7, ha="center", va="bottom", clip_on=False,
                        )
                for m, sat in hinfo["satellites"].items():
                    if sat["pix"] is None or not sat["on_detector"]:
                        continue
                    if m == 0 and abs(sat["along"]) < 1e-9:
                        continue  # coincides with the "n{n}" marker already drawn above
                    sx, sy = sat["pix"]
                    ax.plot(sx, sy, "o", color=hcolor, alpha=0.55, ms=5, mec=BG, mew=0.4, zorder=2)
                    mlabel = "0" if m == 0 else f"{m:+d}"
                    ax.annotate(
                        mlabel, (sx, sy), xytext=(sx + label_off[0], sy + label_off[1]),
                        color=hcolor, alpha=0.85, fontsize=6, ha="center", va="center", zorder=2,
                    )
                    if show_profile:
                        # Window check stays an approximate pixel-space
                        # projection onto the *fundamental's* streak (placing
                        # a harmonic's own comb, generally at a different
                        # absolute Q, onto the fundamental's exact curved-rod
                        # axis is a harder "nearest point on that curve"
                        # problem not solved here) -- but the plotted value
                        # itself is rod_tangency's own exact `along` for this
                        # harmonic satellite (already correctly comb-anchored
                        # for is_superlattice=True, same fix as the
                        # fundamental's satellites above), not a recomputed
                        # m/period formula that would silently drop that.
                        hs_m = float(np.dot(np.array(sat["pix"]) - np.array([px0, py0]), streak))
                        if -arrow_neg <= hs_m <= arrow_pos:
                            hq_m = sat["along"]
                            ax_profile.axvline(hq_m, color=hcolor, lw=0.8, ls=":", alpha=0.6)
                            ax_profile.text(
                                hq_m, label_y, mlabel, transform=ax_profile.get_xaxis_transform(),
                                color=hcolor, fontsize=6, ha="center", va="bottom", clip_on=False,
                            )

    if len(peak_points) > 1:
        avg_x = float(np.mean([p[0] for p in peak_points]))
        avg_y = float(np.mean([p[1] for p in peak_points]))
        ax.plot(
            avg_x, avg_y, "*", color=FG, ms=14, mec=BG, mew=0.8, zorder=7,
            label=f"average peak position ({len(peak_points)} peaks)",
        )

    if buf_info is not None:
        bx, by = buf_info["pix0"]
        ax.plot(
            bx, by, "D", color="#9ca3af", ms=8, mfc="none", mew=1.6, zorder=6,
            label=f"relaxed buffer ({buf_info['layer']})",
        )

    ax.set_xlim(cx - pad_px, cx + pad_px)
    ax.set_ylim(cy + pad_px, cy - pad_px)
    ax.set_aspect("equal")

    leg = ax.legend(loc="upper right", fontsize=6.5, facecolor=BG, edgecolor="#333355", labelcolor=FG)
    leg.get_frame().set_alpha(0.85)

    if multi:
        title = f"hkl={infos[0]['hkl']}  — {len(infos)} layers compared"
    else:
        info = infos[0]
        title = (
            f"hkl={info['hkl']}  ({info['layer']})  E0={info['E0']:.0f} eV\n"
            f"|d(pixel)/d(along)| = {info['dpix_dalong']:.2e} px/Å⁻¹"
        )
    ax.set_title(title, color=FG, fontsize=9, pad=6)

    if show_profile:
        _ax_style(ax_profile, "")
        ax_profile.set_xlabel("ΔQ along rod  (Å⁻¹)", color=FG, fontsize=8)
        ax_profile.set_ylabel(f"intensity  (Σ over ±{profile_halfwidth_px} px lateral)", color=FG, fontsize=8)
        ax_profile.set_yscale("log")
        ax_profile.axvline(0.0, color=FG, lw=0.8, ls=":", alpha=0.4)
        leg_p = ax_profile.legend(loc="upper right", fontsize=6.5, facecolor=BG, edgecolor="#333355", labelcolor=FG)
        leg_p.get_frame().set_alpha(0.85)
        ax_profile.set_title("Measured intensity along streak direction", color=FG, fontsize=9, pad=6)

    if not show_profile:
        fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)

    if show_profile:
        return fig, (ax, ax_profile), infos
    return fig, ax, infos

plot_rod_tangency_blocks

plot_rod_tangency_blocks(stack, hkl, camera=None, *, ki_hat=None, blocks=None, max_satellites=0, ncols=3, arrow_length_px=60, image=None, pad_px=40, show_profile=None, profile_halfwidth_px=3, profile_step_px=1.0, show_relaxed_buffer=False, alpha=0.9, figsize=None, out_path=None)

Small-multiples comparison of one reflection's satellite comb across the stack's different repeating blocks of pseudomorphic layers — one panel per block (stack.blocks), each computed from that block's own period and its first layer. Useful for a multi-section device stack (e.g. a defect-filtering superlattice, an active region, and a cladding section stacked on top of each other — see Layered Structures §1.1/§10.2) to see at a glance how the satellite comb (spacing, streak direction, intensity envelope) differs from one repeating section to the next for the same nominal reflection.

Same visual design and shared-ΔQ-window reasoning as plot_rod_tangency_harmonics — see that function's docstring. The only thing that differs panel to panel here is which block's period/layer was used to compute the rod, not harmonic order (hkl is identical for every panel, unlike there).

Parameters:
  • stack, hkl, camera, ki_hat –

    Same meaning as :func:~nrxrdct.laue.simulation.rod_tangency.

  • blocks (list of int, list of str, or None, default: None ) –

    Which of stack.blocks to show. None (default) shows all of them, bottom to top. A list of integers indexes stack.blocks directly. A list of strings selects, for each entry, the first block containing a layer with that label — convenient for naming a block by one of its layers (e.g. blocks=['QW']) rather than its position, which shifts if the stack is edited. Blocks that are unreachable or land off-detector for hkl are skipped with a printed note rather than raising.

  • max_satellites (int, default: 0 ) –

    Forwarded to rod_tangency unchanged for every block — no harmonic-order rescaling here, since hkl itself is the same for every panel.

  • figsize, out_path –

    Same meaning as in plot_rod_tangency_harmonics.

Returns:
  • –

    (fig, infos) — infos is the list of rod_tangency return dicts

  • –

    actually plotted, each with added 'block_index' (its index into

  • –

    stack.blocks), 'block_layers' (labels of every layer in that

  • –

    block, bottom to top), and 'block_n_rep' keys, and using that

  • –

    block's first layer as layer.

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_rod_tangency_blocks(
    stack,
    hkl,
    camera=None,
    *,
    ki_hat=None,
    blocks=None,
    max_satellites=0,
    ncols=3,
    arrow_length_px=60,
    image=None,
    pad_px=40,
    show_profile=None,
    profile_halfwidth_px=3,
    profile_step_px=1.0,
    show_relaxed_buffer=False,
    alpha=0.9,
    figsize=None,
    out_path=None,
):
    """
    Small-multiples comparison of one reflection's satellite comb across the
    stack's different repeating blocks of pseudomorphic layers — one panel
    per block (`stack.blocks`), each computed from that block's own period
    and its first layer. Useful for a multi-section device stack (e.g. a
    defect-filtering superlattice, an active region, and a cladding section
    stacked on top of each other — see Layered Structures §1.1/§10.2) to see
    at a glance how the satellite comb (spacing, streak direction, intensity
    envelope) differs from one repeating section to the next for the *same*
    nominal reflection.

    Same visual design and shared-ΔQ-window reasoning as
    `plot_rod_tangency_harmonics` — see that function's docstring. The only
    thing that differs panel to panel here is *which block's* period/layer
    was used to compute the rod, not harmonic order (`hkl` is identical for
    every panel, unlike there).

    Args:
        stack, hkl, camera, ki_hat: Same meaning as
            :func:`~nrxrdct.laue.simulation.rod_tangency`.
        blocks (list of int, list of str, or None): Which of `stack.blocks`
            to show. `None` (default) shows all of them, bottom to top. A
            list of integers indexes `stack.blocks` directly. A list of
            strings selects, for each entry, the first block containing a
            layer with that label — convenient for naming a block by one of
            its layers (e.g. `blocks=['QW']`) rather than its position,
            which shifts if the stack is edited. Blocks that are unreachable
            or land off-detector for `hkl` are skipped with a printed note
            rather than raising.
        max_satellites (int): Forwarded to `rod_tangency` unchanged for
            every block — no harmonic-order rescaling here, since `hkl`
            itself is the same for every panel.
        ncols, arrow_length_px, pad_px, image, show_profile,
        profile_halfwidth_px, profile_step_px, show_relaxed_buffer, alpha,
        figsize, out_path: Same meaning as in `plot_rod_tangency_harmonics`.

    Returns:
        `(fig, infos)` — `infos` is the list of `rod_tangency` return dicts
        actually plotted, each with added `'block_index'` (its index into
        `stack.blocks`), `'block_layers'` (labels of every layer in that
        block, bottom to top), and `'block_n_rep'` keys, and using that
        block's first layer as `layer`.
    """
    from .simulation import rod_tangency

    stack_blocks = stack.blocks
    if not stack_blocks:
        raise ValueError("plot_rod_tangency_blocks: stack has no repeating blocks (stack.blocks is empty)")

    if blocks is None:
        block_indices = list(range(len(stack_blocks)))
    else:
        block_indices = []
        for b in blocks:
            if isinstance(b, str):
                idx = next(
                    (i for i, blk in enumerate(stack_blocks) if any(lyr.label == b for lyr in blk.layers)),
                    None,
                )
                if idx is None:
                    raise ValueError(f"no block contains a layer labeled {b!r}")
                block_indices.append(idx)
            else:
                idx = int(b)
                if not (0 <= idx < len(stack_blocks)):
                    raise ValueError(f"block index {idx} out of range (stack has {len(stack_blocks)} blocks)")
                block_indices.append(idx)
        block_indices = sorted(set(block_indices))

    h0, k0, l0 = (int(x) for x in hkl)
    block_hits = []
    for idx in block_indices:
        block = stack_blocks[idx]
        rep_layer = block.layers[0]
        try:
            info = rod_tangency(
                stack, (h0, k0, l0), layer=rep_layer, camera=camera,
                ki_hat=ki_hat, max_satellites=max_satellites,
            )
        except ValueError as e:
            print(f"  plot_rod_tangency_blocks: skipping block {idx} ({rep_layer.label!r}) — {e}")
            continue
        if not info["on_detector"]:
            print(f"  plot_rod_tangency_blocks: skipping block {idx} ({rep_layer.label!r}) — off-detector")
            continue
        info["block_index"] = idx
        info["block_layers"] = [lyr.label for lyr in block.layers]
        info["block_n_rep"] = block.n_rep
        block_hits.append(info)
    if not block_hits:
        raise ValueError(
            f"hkl={(h0, k0, l0)} lands on-detector for none of the requested blocks {block_indices}"
        )

    panels = [
        {
            "hkl": info["hkl"],
            "layer": info["layer"],
            "info": info,
            "title": (
                f"block {info['block_index']}: {'+'.join(info['block_layers'])} ×{info['block_n_rep']}\n"
                f"E0={info['E0']:.0f} eV   |d(pix)/d(along)|={info['dpix_dalong']:.2e} px/Å⁻¹"
            ),
        }
        for info in block_hits
    ]
    suptitle = f"hkl={(h0, k0, l0)}  — blocks {[info['block_index'] for info in block_hits]}"

    fig = _plot_rod_tangency_multi(
        stack, panels, camera, ki_hat=ki_hat, ncols=ncols, arrow_length_px=arrow_length_px,
        image=image, pad_px=pad_px, show_profile=show_profile,
        profile_halfwidth_px=profile_halfwidth_px, profile_step_px=profile_step_px,
        show_relaxed_buffer=show_relaxed_buffer, alpha=alpha, figsize=figsize,
        out_path=out_path, suptitle=suptitle, caller_name="plot_rod_tangency_blocks",
    )
    return fig, block_hits

plot_rod_tangency_harmonics

plot_rod_tangency_harmonics(stack, hkl, layer=None, camera=None, *, ki_hat=None, n_harmonics=3, max_satellites=0, ncols=3, arrow_length_px=60, image=None, pad_px=40, show_profile=None, profile_halfwidth_px=3, profile_step_px=1.0, show_relaxed_buffer=False, alpha=0.9, figsize=None, out_path=None)

Small-multiples comparison of a reflection's harmonics — one panel per harmonic order n·hkl, each with its own cropped image + rod overlay side by side with its own intensity profile (when image is given), arranged in a grid that wraps after ncols harmonics per row.

plot_rod_tangency(..., n_harmonics=N) overlays every harmonic onto one shared panel — compact, but colour-coding N rods and satellite combs together gets hard to read past 2–3 orders. This instead gives each harmonic its own panel, so differences in streak direction, dpix_dalong, and satellite spacing are visible by scanning across panels rather than by disentangling colours. See also plot_rod_tangency_blocks, the same idea varying by repeating block instead of by harmonic order.

Unlike plot_rod_tangency, layer here must resolve to a single layer — this function compares harmonics of one reflection/layer, not layers of one reflection; use plot_rod_tangency (optionally with layer='all') for the latter.

Parameters:
  • stack, hkl, layer, camera, ki_hat –

    Same meaning as :func:~nrxrdct.laue.simulation.rod_tangency; layer must be a single layer/label/None, not 'all' or a list.

  • n_harmonics (int or list of int, default: 3 ) –

    Either a count — orders n = 1, ..., n_harmonics (n=1 is the fundamental hkl itself) — or an explicit list of the specific orders to show, e.g. [1, 3, 5], when you only want a few rather than every consecutive one. Harmonics that are unreachable (elastic condition fails) or land off-detector are skipped with a printed note rather than raising, same as plot_rod_tangency's n_harmonics — the panel grid simply has fewer panels than requested in that case.

  • max_satellites (int, default: 0 ) –

    Forwarded to rod_tangency for n=1; scaled as max_satellites * 2**(n-1) for n > 1, same reasoning as plot_rod_tangency (a higher harmonic sits at larger |Q| where the same physical fringe spacing subtends more orders).

  • ncols (int, default: 3 ) –

    Panel columns before wrapping to a new row.

  • arrow_length_px (float or (float, float), default: 60 ) –

    Sets the ΔQ window shown by the first successfully displayed harmonic (converted via that harmonic's own dpix_dalong, same as plot_rod_tangency) — every other panel then shows that exact same ΔQ window (not its own, generally larger or smaller, one) so panels are directly comparable in physical units, not just in pixels. Practically: each panel's rod line/profile covers less of its own crop window at higher harmonics, since the same ΔQ span maps to fewer pixels there (dpix_dalong shrinks with harmonic order) — that shrinkage is the comparison.

  • pad_px –

    Same meaning as in plot_rod_tangency, applied independently to every panel (each panel is centred and cropped on its own pix0, not a shared window) — unlike the ΔQ extent, the pixel crop size itself is not forced to match across panels.

  • image (ndarray, default: None ) –

    Measured/simulated detector frame shown cropped behind each panel's overlay, and sampled for the profile row if show_profile ends up True. None (default) shows a plain dark background and skips profiles regardless of show_profile.

  • show_profile (bool or None, default: None ) –

    None (default) shows an intensity profile beside each image panel when image is given, and omits it entirely (rather than empty panels) when image is None. Force True/False to override either way; forcing True without image draws a placeholder "no image provided" panel.

  • profile_halfwidth_px, profile_step_px –

    Same meaning as in plot_rod_tangency.

  • show_relaxed_buffer (bool, default: False ) –

    Mark (grey diamond on the image panel, grey dotted line on the profile panel) where the shallowest buffer layer's own n-th harmonic would fall, for each panel's own n — same purpose as plot_rod_tangency's option of the same name. No-op if layer already is that buffer layer.

  • alpha (float, default: 0.9 ) –

    Opacity for each panel's streak line and satellite markers.

  • figsize ((float, float) or None, default: None ) –

    Size of the combined figure, inches. None (default) auto-scales from a fixed per-harmonic panel size and ncols/nrows (wider per harmonic when show_profile is active, since the profile sits beside the image rather than under it); pass an explicit (width, height) to override that and fix the overall figure size directly.

  • out_path (str or None, default: None ) –

    Save the combined figure to this path if given.

Returns:
  • –

    (fig, infos) — infos is the list of rod_tangency return dicts

  • –

    actually plotted (skipped harmonics excluded), each with an added

  • –

    'harmonic_n' key recording which order it is.

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_rod_tangency_harmonics(
    stack,
    hkl,
    layer=None,
    camera=None,
    *,
    ki_hat=None,
    n_harmonics=3,
    max_satellites=0,
    ncols=3,
    arrow_length_px=60,
    image=None,
    pad_px=40,
    show_profile=None,
    profile_halfwidth_px=3,
    profile_step_px=1.0,
    show_relaxed_buffer=False,
    alpha=0.9,
    figsize=None,
    out_path=None,
):
    """
    Small-multiples comparison of a reflection's harmonics — one panel per
    harmonic order `n·hkl`, each with its own cropped image + rod overlay
    side by side with its own intensity profile (when `image` is given),
    arranged in a grid that wraps after `ncols` harmonics per row.

    `plot_rod_tangency(..., n_harmonics=N)` overlays every harmonic onto one
    shared panel — compact, but colour-coding `N` rods and satellite combs
    together gets hard to read past 2–3 orders. This instead gives each
    harmonic its own panel, so differences in streak direction,
    `dpix_dalong`, and satellite spacing are visible by scanning across
    panels rather than by disentangling colours. See also
    `plot_rod_tangency_blocks`, the same idea varying by repeating block
    instead of by harmonic order.

    Unlike `plot_rod_tangency`, `layer` here must resolve to a single layer
    — this function compares harmonics of *one* reflection/layer, not
    layers of one reflection; use `plot_rod_tangency` (optionally with
    `layer='all'`) for the latter.

    Args:
        stack, hkl, layer, camera, ki_hat: Same meaning as
            :func:`~nrxrdct.laue.simulation.rod_tangency`; `layer` must be a
            single layer/label/`None`, not `'all'` or a list.
        n_harmonics (int or list of int): Either a count — orders
            `n = 1, ..., n_harmonics` (`n=1` is the fundamental `hkl`
            itself) — or an explicit list of the specific orders to show,
            e.g. `[1, 3, 5]`, when you only want a few rather than every
            consecutive one. Harmonics that are unreachable (elastic
            condition fails) or land off-detector are skipped with a
            printed note rather than raising, same as `plot_rod_tangency`'s
            `n_harmonics` — the panel grid simply has fewer panels than
            requested in that case.
        max_satellites (int): Forwarded to `rod_tangency` for `n=1`; scaled
            as `max_satellites * 2**(n-1)` for `n > 1`, same reasoning as
            `plot_rod_tangency` (a higher harmonic sits at larger `|Q|`
            where the same physical fringe spacing subtends more orders).
        ncols (int): Panel columns before wrapping to a new row.
        arrow_length_px (float or (float, float)): Sets the `ΔQ` window
            shown by the *first successfully displayed* harmonic (converted
            via that harmonic's own `dpix_dalong`, same as
            `plot_rod_tangency`) — every other panel then shows that exact
            same `ΔQ` window (not its own, generally larger or smaller, one)
            so panels are directly comparable in physical units, not just in
            pixels. Practically: each panel's rod line/profile covers less
            of its own crop window at higher harmonics, since the same `ΔQ`
            span maps to fewer pixels there (`dpix_dalong` shrinks with
            harmonic order) — that shrinkage *is* the comparison.
        pad_px: Same meaning as in `plot_rod_tangency`, applied independently
            to every panel (each panel is centred and cropped on *its own*
            `pix0`, not a shared window) — unlike the `ΔQ` extent, the pixel
            crop size itself is not forced to match across panels.
        image (ndarray, optional): Measured/simulated detector frame shown
            cropped behind each panel's overlay, and sampled for the profile
            row if `show_profile` ends up `True`. `None` (default) shows a
            plain dark background and skips profiles regardless of
            `show_profile`.
        show_profile (bool or None): `None` (default) shows an intensity
            profile beside each image panel when `image` is given, and omits
            it entirely (rather than empty panels) when `image` is `None`.
            Force `True`/`False` to override either way; forcing `True`
            without `image` draws a placeholder "no `image` provided" panel.
        profile_halfwidth_px, profile_step_px: Same meaning as in
            `plot_rod_tangency`.
        show_relaxed_buffer (bool): Mark (grey diamond on the image panel,
            grey dotted line on the profile panel) where the shallowest
            buffer layer's own *n*-th harmonic would fall, for each panel's
            own `n` — same purpose as `plot_rod_tangency`'s option of the
            same name. No-op if `layer` already *is* that buffer layer.
        alpha (float): Opacity for each panel's streak line and satellite
            markers.
        figsize ((float, float) or None): Size of the *combined* figure,
            inches. `None` (default) auto-scales from a fixed per-harmonic
            panel size and `ncols`/`nrows` (wider per harmonic when
            `show_profile` is active, since the profile sits beside the
            image rather than under it); pass an explicit `(width, height)`
            to override that and fix the overall figure size directly.
        out_path (str or None): Save the combined figure to this path if
            given.

    Returns:
        `(fig, infos)` — `infos` is the list of `rod_tangency` return dicts
        actually plotted (skipped harmonics excluded), each with an added
        `'harmonic_n'` key recording which order it is.
    """
    from .simulation import rod_tangency

    if isinstance(layer, (list, tuple)) or (isinstance(layer, str) and layer == "all"):
        raise ValueError(
            "plot_rod_tangency_harmonics compares harmonics of one layer/reflection, "
            "not multiple layers -- pass a single layer/label/None, or use "
            "plot_rod_tangency(..., layer=..., n_harmonics=...) for overlaying "
            "several layers and/or harmonics onto one shared panel instead."
        )

    h0, k0, l0 = (int(x) for x in hkl)

    if isinstance(n_harmonics, (list, tuple, np.ndarray)):
        harmonic_orders = sorted({int(n) for n in n_harmonics})
        if any(n < 1 for n in harmonic_orders):
            raise ValueError(f"n_harmonics list entries must be >= 1, got {n_harmonics}")
    else:
        harmonic_orders = list(range(1, int(n_harmonics) + 1))

    harmonics = []
    for n in harmonic_orders:
        h_max_sat = max_satellites if n == 1 else max_satellites * (2 ** (n - 1))
        try:
            info = rod_tangency(
                stack, (n * h0, n * k0, n * l0), layer=layer, camera=camera,
                ki_hat=ki_hat, max_satellites=h_max_sat,
            )
        except ValueError as e:
            print(f"  plot_rod_tangency_harmonics: skipping n={n} — {e}")
            continue
        if not info["on_detector"]:
            print(f"  plot_rod_tangency_harmonics: skipping n={n} — hkl={info['hkl']} is off-detector")
            continue
        info["harmonic_n"] = n
        harmonics.append(info)
    if not harmonics:
        raise ValueError(
            f"hkl={(h0, k0, l0)} lands on-detector for none of the requested harmonics {harmonic_orders}"
        )

    panels = [
        {
            "hkl": info["hkl"],
            "layer": info["layer"],
            "info": info,
            "title": (
                f"n={info['harmonic_n']}   E0={info['E0']:.0f} eV\n"
                f"|d(pix)/d(along)|={info['dpix_dalong']:.2e} px/Å⁻¹"
            ),
        }
        for info in harmonics
    ]
    suptitle = f"hkl={(h0, k0, l0)}  ({harmonics[0]['layer']})  — harmonics n={harmonic_orders}"

    fig = _plot_rod_tangency_multi(
        stack, panels, camera, ki_hat=ki_hat, ncols=ncols, arrow_length_px=arrow_length_px,
        image=image, pad_px=pad_px, show_profile=show_profile,
        profile_halfwidth_px=profile_halfwidth_px, profile_step_px=profile_step_px,
        show_relaxed_buffer=show_relaxed_buffer, alpha=alpha, figsize=figsize,
        out_path=out_path, suptitle=suptitle, caller_name="plot_rod_tangency_harmonics",
    )
    return fig, harmonics

plot_segmentation

plot_segmentation(image: ndarray, peaklist: ndarray, *, log_scale: bool = True, color_by_intensity: bool = True, show_ellipses: bool = False, marker_size: float = 60.0, cmap_image: str = 'inferno', cmap_markers: str = 'plasma', vmin_pct: float = 1.0, vmax_pct: float = 99.5, figsize: tuple = (10, 8), title: str | None = None, ax=None)

Display a detector image with segmented peak positions overlaid as "+" symbols.

Typical usage::

image    = load_images("scan.h5")[0]
peaklist = convert_spotsfile2peaklist("scan_spots.h5")
fig, ax  = plot_segmentation(image, peaklist)
Parameters:
  • image ((Nv, Nh) array) –

    Raw detector frame.

  • peaklist ((N, ≥2) array) –

    Peak table from :func:~nrxrdct.laue.convert_spotsfile2peaklist. Column layout (from that function):

  • log_scale (bool, default: True ) –

    Apply log1p compression to the image before display (default True).

  • color_by_intensity (bool, default: True ) –

    Colour "+" markers by peak intensity (log-scaled, column 2). Falls back to a fixed green if column 2 is absent.

  • show_ellipses (bool, default: False ) –

    Overlay the fitted peak ellipses (columns 3-5 required).

  • marker_size (float, default: 60.0 ) –

    Marker area in points².

  • cmap_image (str, default: 'inferno' ) –

    Colormap for the image (default "inferno").

  • cmap_markers (str, default: 'plasma' ) –

    Colormap for intensity-coded markers (default "plasma").

  • vmin_pct, vmax_pct (float) –

    Percentile clip for the image display range.

  • figsize ((w, h), default: (10, 8) ) –

    Figure size in inches (ignored when ax is supplied).

  • title (str or None, default: None ) –

    Axes title. Defaults to "Segmentation — N spots found".

  • ax (Axes or None, default: None ) –

    Draw into an existing axes rather than creating a new figure.

Returns:
  • fig( Figure ) –
  • ax( Axes ) –
Source code in src/nrxrdct/laue/laue_plotting.py
def plot_segmentation(
    image: "np.ndarray",
    peaklist: "np.ndarray",
    *,
    log_scale: bool = True,
    color_by_intensity: bool = True,
    show_ellipses: bool = False,
    marker_size: float = 60.0,
    cmap_image: str = "inferno",
    cmap_markers: str = "plasma",
    vmin_pct: float = 1.0,
    vmax_pct: float = 99.5,
    figsize: tuple = (10, 8),
    title: str | None = None,
    ax=None,
):
    """
    Display a detector image with segmented peak positions overlaid as "+"
    symbols.

    Typical usage::

        image    = load_images("scan.h5")[0]
        peaklist = convert_spotsfile2peaklist("scan_spots.h5")
        fig, ax  = plot_segmentation(image, peaklist)

    Args:
        image ((Nv, Nh) array): Raw detector frame.
        peaklist ((N, ≥2) array): Peak table from :func:`~nrxrdct.laue.convert_spotsfile2peaklist`.
            Column layout (from that function):

        * 0 – `peak_X`  (xcam, column pixel)
        * 1 – `peak_Y`  (ycam, row pixel)
        * 2 – `peak_I`  (fitted peak intensity, optional)
        * 3 – `peak_fwaxmaj`   \\
        * 4 – `peak_fwaxmin`    > required for *show_ellipses*
        * 5 – `peak_inclination` (degrees) /

        A plain (N, 2) array of pixel positions also works.
        log_scale (bool): Apply `log1p` compression to the image before display (default
            `True`).
        color_by_intensity (bool): Colour "+" markers by peak intensity (log-scaled, column 2).
            Falls back to a fixed green if column 2 is absent.
        show_ellipses (bool): Overlay the fitted peak ellipses (columns 3-5 required).
        marker_size (float): Marker area in points².
        cmap_image (str): Colormap for the image (default `"inferno"`).
        cmap_markers (str): Colormap for intensity-coded markers (default `"plasma"`).
        vmin_pct, vmax_pct (float): Percentile clip for the image display range.
        figsize ((w, h)): Figure size in inches (ignored when *ax* is supplied).
        title (str or None): Axes title.  Defaults to `"Segmentation — N spots found"`.
        ax (matplotlib.axes.Axes or None): Draw into an existing axes rather than creating a new figure.

    Returns:
        fig (matplotlib.figure.Figure):
        ax (matplotlib.axes.Axes):
"""
    pl  = np.asarray(peaklist, dtype=float)
    img = np.asarray(image, dtype=float)
    n_spots = len(pl)
    xcam = pl[:, 0]
    ycam = pl[:, 1]

    # ── axes setup ────────────────────────────────────────────────────────────
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.get_figure()

    fig.patch.set_facecolor(BG)
    ax.set_facecolor(BG)
    ax.tick_params(colors="#7788aa", labelsize=7)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")

    # ── image display ─────────────────────────────────────────────────────────
    positive = img[img > 0]
    if positive.size:
        v0 = np.percentile(positive, vmin_pct)
        v1 = np.percentile(positive, vmax_pct)
    else:
        v0, v1 = 0.0, 1.0

    if log_scale:
        denom = max(v1, 1e-10)
        disp = np.log1p(np.clip(img, 0.0, None) / denom * 1000.0)
    else:
        disp = np.clip(img, v0, v1)

    ax.imshow(disp, origin="upper", cmap=cmap_image, aspect="equal", zorder=0)

    # ── spot markers ──────────────────────────────────────────────────────────
    has_intensity = pl.shape[1] >= 3

    if color_by_intensity and has_intensity:
        log_I = np.log1p(np.clip(pl[:, 2], 0.0, None))
        norm  = mcolors.Normalize(
            vmin=np.percentile(log_I, 5) if len(log_I) > 1 else 0.0,
            vmax=np.percentile(log_I, 99) if len(log_I) > 1 else 1.0,
        )
        sc = ax.scatter(
            xcam, ycam,
            s=marker_size, c=log_I, cmap=cmap_markers, norm=norm,
            marker="+", linewidths=1.2, zorder=3,
        )
        cb = fig.colorbar(sc, ax=ax, fraction=0.025, pad=0.01, shrink=0.85)
        cb.set_label("log(I + 1)", color=FG, fontsize=8)
        cb.ax.tick_params(colors="#7788aa", labelsize=7)
    else:
        ax.scatter(
            xcam, ycam,
            s=marker_size, c="#00ff88",
            marker="+", linewidths=1.2, zorder=3,
        )

    # ── optional fitted ellipses ──────────────────────────────────────────────
    if show_ellipses and pl.shape[1] >= 6:
        from matplotlib.patches import Ellipse

        fwmaj  = pl[:, 3]
        fwmin  = pl[:, 4]
        angles = pl[:, 5]
        for x, y, a, b, theta in zip(xcam, ycam, fwmaj, fwmin, angles):
            ell = Ellipse(
                (x, y), width=float(a), height=float(b), angle=float(theta),
                fill=False, edgecolor="#44dd66",
                linewidth=0.6, alpha=0.7, zorder=2,
            )
            ax.add_patch(ell)

    # ── labels ────────────────────────────────────────────────────────────────
    ax.set_xlabel("xcam  (px)", color=FG, fontsize=8)
    ax.set_ylabel("ycam  (px)", color=FG, fontsize=8)

    _title = title if title is not None else f"Segmentation — {n_spots} spots found"
    ax.set_title(_title, color=FG, fontsize=9, pad=5)

    fig.tight_layout()
    _force_draw(fig)
    return fig, ax

plot_simulated_qspace_around_spot

plot_simulated_qspace_around_spot(vol: dict, *, log_intensity: bool = True, intensity_floor: float = 1e-06, elev: float = 22.0, azim: float = -60.0, figsize: tuple[float, float] = (9, 8), ax: Axes | None = None, out_path: str | None = None)

Render the 3-D fixed-energy structure-factor volume returned by :func:~nrxrdct.laue.simulation.simulate_qspace_around_spot — the simulation-only counterpart of :func:plot_qspace_around_spot, which instead shows the elastic-condition-filtered volume from :func:~nrxrdct.laue.simulation.qspace_around_spot.

plot_qspace_around_spot has to distinguish why a voxel fails to reach the detector — destructive interference (I near zero), outside the accessible energy window, or reachable but off-detector — since those are three physically distinct fates for a real white-beam exposure. None of that applies here: vol['F2'] was evaluated at one fixed energy for the entire grid with no elastic-condition/camera filtering (see simulate_qspace_around_spot's docstring), so every voxel already has a well-defined value. There is accordingly no energy window surface and no filled/hollow on-detector distinction to draw — every point gets one filled marker, coloured/sized purely by F2. The warm colour ramp and marker-size-by-intensity convention otherwise match plot_qspace_around_spot exactly, so the two read as the same kind of picture.

Parameters:
  • vol (dict) –

    Return value of :func:~nrxrdct.laue.simulation.simulate_qspace_around_spot.

  • log_intensity (bool, default: True ) –

    Colour/size by log10(F2 / F2_max + floor) instead of the raw ratio. True by default — structure-factor intensities span many orders of magnitude near a fringe minimum.

  • intensity_floor (float, default: 1e-06 ) –

    Added (as a fraction of the volume's max intensity) before taking the log, so exact zeros stay finite.

  • elev, azim –

    3-D view angle (degrees), forwarded to Axes3D.view_init.

  • figsize (tuple[float, float], default: (9, 8) ) –

    Figure size in inches (only used when ax is None).

  • ax (Axes | None, default: None ) –

    Draw into an existing 3-D :class:~matplotlib.axes.Axes (created with projection='3d'); None creates a new figure.

  • out_path (str | None, default: None ) –

    Save path; None → do not save.

Returns:
  • –

    (fig, ax)

Example:

vol = simulate_qspace_around_spot(stack, (0, 0, 2), energy_eV=17000) plot_simulated_qspace_around_spot(vol, out_path="sim_qspace_002.png")

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_simulated_qspace_around_spot(
    vol: dict,
    *,
    log_intensity: bool = True,
    intensity_floor: float = 1e-6,
    elev: float = 22.0,
    azim: float = -60.0,
    figsize: tuple[float, float] = (9, 8),
    ax: "plt.Axes | None" = None,
    out_path: "str | None" = None,
):
    """
    Render the 3-D fixed-energy structure-factor volume returned by
    :func:`~nrxrdct.laue.simulation.simulate_qspace_around_spot` — the
    simulation-only counterpart of :func:`plot_qspace_around_spot`, which
    instead shows the elastic-condition-filtered volume from
    :func:`~nrxrdct.laue.simulation.qspace_around_spot`.

    `plot_qspace_around_spot` has to distinguish *why* a voxel fails to
    reach the detector — destructive interference (`I` near zero), outside
    the accessible energy window, or reachable but off-detector — since
    those are three physically distinct fates for a real white-beam
    exposure. None of that applies here: `vol['F2']` was evaluated at one
    fixed energy for the *entire* grid with no elastic-condition/camera
    filtering (see `simulate_qspace_around_spot`'s docstring), so every
    voxel already has a well-defined value. There is accordingly no energy
    window surface and no filled/hollow on-detector distinction to draw —
    every point gets one filled marker, coloured/sized purely by `F2`. The
    warm colour ramp and marker-size-by-intensity convention otherwise
    match `plot_qspace_around_spot` exactly, so the two read as the same
    kind of picture.

    Args:
        vol: Return value of
            :func:`~nrxrdct.laue.simulation.simulate_qspace_around_spot`.
        log_intensity: Colour/size by `log10(F2 / F2_max + floor)` instead
            of the raw ratio. `True` by default — structure-factor
            intensities span many orders of magnitude near a fringe
            minimum.
        intensity_floor: Added (as a fraction of the volume's max
            intensity) before taking the log, so exact zeros stay finite.
        elev, azim: 3-D view angle (degrees), forwarded to `Axes3D.view_init`.
        figsize: Figure size in inches (only used when `ax is None`).
        ax: Draw into an existing 3-D :class:`~matplotlib.axes.Axes`
            (created with `projection='3d'`); `None` creates a new figure.
        out_path: Save path; `None` → do not save.

    Returns:
        `(fig, ax)`

    Example:
    >>> vol = simulate_qspace_around_spot(stack, (0, 0, 2), energy_eV=17000)
    >>> plot_simulated_qspace_around_spot(vol, out_path="sim_qspace_002.png")
    """
    from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 — registers '3d' projection

    along = np.asarray(vol["along"])
    lat1 = np.asarray(vol["lateral1"])
    lat2 = np.asarray(vol["lateral2"])
    F2 = vol["F2"]

    AA, T1, T2 = np.meshgrid(along, lat1, lat2, indexing="ij")

    # ── colour / size by intensity ────────────────────────────────────────────
    F2max = float(F2.max()) if F2.size and F2.max() > 0 else 1.0
    if log_intensity:
        val = np.log10(F2 / F2max + intensity_floor)
        vmin, vmax = np.log10(intensity_floor), 0.0
    else:
        val = F2 / F2max
        vmin, vmax = 0.0, 1.0

    cmap = mcolors.LinearSegmentedColormap.from_list(
        "qvol_warm", [_QVOL_LOW, _QVOL_MID, _QVOL_HIGH]
    )
    norm = mcolors.Normalize(vmin=vmin, vmax=vmax)

    frac = np.clip((val - vmin) / max(vmax - vmin, 1e-12), 0.0, 1.0)
    sizes = 3.0 + 40.0 * frac ** 1.5

    # ── set up axes ────────────────────────────────────────────────────────────
    standalone = ax is None
    if standalone:
        fig = plt.figure(figsize=figsize)
        fig.patch.set_facecolor(BG)
        ax = fig.add_subplot(111, projection="3d")
    else:
        fig = ax.figure

    ax.set_facecolor(BG)
    fig.patch.set_facecolor(BG)
    for pane in (ax.xaxis, ax.yaxis, ax.zaxis):
        pane.set_pane_color((0.03, 0.05, 0.08, 1.0))
        pane._axinfo["grid"]["color"] = (0.1, 0.12, 0.18, 0.6)
    ax.tick_params(colors="#7788aa", labelsize=7)

    sc = ax.scatter(
        AA.ravel(), T1.ravel(), T2.ravel(),
        c=val.ravel(), cmap=cmap, norm=norm,
        s=sizes.ravel(), marker="o", linewidths=0, alpha=0.9, depthshade=True,
    )

    # ── labels / colorbar ──────────────────────────────────────────────────────
    hkl = vol.get("hkl")
    layer_label = vol.get("layer")
    energy_eV = vol.get("energy_eV")
    ax.set_xlabel("ΔQ ∥ n̂  (Å⁻¹)", color=FG, fontsize=8, labelpad=8)
    ax.set_ylabel("ΔQ transverse 1  (Å⁻¹)", color=FG, fontsize=8, labelpad=8)
    ax.set_zlabel("ΔQ transverse 2  (Å⁻¹)", color=FG, fontsize=8, labelpad=8)
    ax.set_title(
        f"Simulated Q-space intensity around hkl={hkl}  (layer '{layer_label}')  E={energy_eV:.0f} eV",
        color=FG, fontsize=10, pad=10,
    )
    ax.view_init(elev=elev, azim=azim)

    cbar = fig.colorbar(sc, ax=ax, shrink=0.6, pad=0.1)
    cbar.set_label("log₁₀ |F|² / |F|²_max" if log_intensity else "|F|² / |F|²_max", color=FG, fontsize=8)
    cbar.ax.yaxis.set_tick_params(color="#7788aa", labelsize=7)
    plt.setp(cbar.ax.get_yticklabels(), color=FG)
    cbar.outline.set_edgecolor("#333355")

    if standalone:
        fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, ax

plot_simulated_rod_qspace

plot_simulated_rod_qspace(stack, hkl, energy_eV, layer=None, *, camera=None, ki_hat=None, q_par_range=None, q_perp_range=None, n_par: int = 300, n_perp: int = 300, half_size_px: float = 40.0, perp_probe_px: float = 5.0, max_satellites: int = 0, structure_model: str = 'coherent', show_profile: bool = False, profile_halfwidth_bins: int = 3, log_scale: bool = True, cmap: str = 'inferno', ax=None, figsize=(6.5, 5.5), out_path=None)

Display the (q_parallel, q_perp) simulated intensity map produced by :func:~nrxrdct.laue.simulation.simulate_rod_qspace — the simulation-only counterpart of :func:plot_rod_qspace_warp, which instead displays a measured detector image warped onto the same axes. Same axis convention (q_parallel vertical, q_perp horizontal) and, when camera is given, the same perp_hat anchoring as warp_rod_to_qspace — call both functions for the same hkl/layer/camera (matching q_par_range/q_perp_range, e.g. by passing the info from one call's q_par_range=(q_par_ax[0], q_par_ax[-1]) to the other) to compare simulation against measured data on identical axes.

Unlike plot_rod_qspace_warp, this only ever handles a single layer (matching :func:~nrxrdct.laue.simulation.simulate_rod_qspace's own interface) — call it once per layer/block for a side-by-side comparison instead of the small-multiples grid plot_rod_qspace_warp builds for layer='all'/a list.

With max_satellites > 0, the satellite comb is marked using :func:~nrxrdct.laue.simulation.rod_satellite_along_positions — pure Q-space geometry (same anchoring convention as rod_tangency's own 'satellites'), so this works whether or not camera was given, and markers are never filtered by on-detector status (there is no detector notion in a fixed-energy structure-factor map).

Parameters:
  • structure_model (str, default: 'coherent' ) –

    Forwarded to :func:~nrxrdct.laue.simulation.simulate_rod_qspace.

  • max_satellites (int, default: 0 ) –

    0 (default) shows only the crosshair at G0. N > 0 also marks satellite orders m = -N, ..., N (see above).

  • show_profile (bool, default: False ) –

    Add a paired axis with the intensity along q_parallel, summed over ±profile_halfwidth_bins grid columns around q_perp=0 — same idea as plot_rod_qspace_warp's own show_profile, read directly off the already-computed simulated grid. Requires ax=None.

  • profile_halfwidth_bins (int, default: 3 ) –

    Lateral summation half-width, in q_perp grid columns. Unused unless show_profile=True.

  • log_scale (bool, default: True ) –

    Apply log1p scaling to the map before display.

  • cmap (str, default: 'inferno' ) –

    Matplotlib colormap.

  • ax (Axes, default: None ) –

    Draw into an existing axes instead of creating a new figure. Only valid when show_profile=False; raises otherwise.

  • figsize –

    Figure size (ignored if ax is given).

  • out_path (str or None, default: None ) –

    Save figure to this path if given.

Returns:
  • –

    show_profile=False (default): (fig, ax, F2, q_par_ax, q_perp_ax, info).

  • –

    show_profile=True: (fig, (ax, ax_profile), F2, q_par_ax, q_perp_ax, info).

  • –

    F2, q_par_ax, q_perp_ax, info are exactly

  • –

    func:~nrxrdct.laue.simulation.simulate_rod_qspace's own return

  • –

    values.

Example:

plot_simulated_rod_qspace(stack, (0, 0, 2), energy_eV=17000, camera=cam, max_satellites=3)

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_simulated_rod_qspace(
    stack,
    hkl,
    energy_eV,
    layer=None,
    *,
    camera=None,
    ki_hat=None,
    q_par_range=None,
    q_perp_range=None,
    n_par: int = 300,
    n_perp: int = 300,
    half_size_px: float = 40.0,
    perp_probe_px: float = 5.0,
    max_satellites: int = 0,
    structure_model: str = "coherent",
    show_profile: bool = False,
    profile_halfwidth_bins: int = 3,
    log_scale: bool = True,
    cmap: str = "inferno",
    ax=None,
    figsize=(6.5, 5.5),
    out_path=None,
):
    """
    Display the `(q_parallel, q_perp)` simulated intensity map produced by
    :func:`~nrxrdct.laue.simulation.simulate_rod_qspace` — the
    simulation-only counterpart of :func:`plot_rod_qspace_warp`, which
    instead displays a *measured* detector image warped onto the same
    axes. Same axis convention (`q_parallel` vertical, `q_perp`
    horizontal) and, when `camera` is given, the same `perp_hat` anchoring
    as `warp_rod_to_qspace` — call both functions for the same
    `hkl`/`layer`/`camera` (matching `q_par_range`/`q_perp_range`, e.g. by
    passing the `info` from one call's `q_par_range=(q_par_ax[0],
    q_par_ax[-1])` to the other) to compare simulation against measured
    data on identical axes.

    Unlike `plot_rod_qspace_warp`, this only ever handles a single layer
    (matching :func:`~nrxrdct.laue.simulation.simulate_rod_qspace`'s own
    interface) — call it once per layer/block for a side-by-side
    comparison instead of the small-multiples grid `plot_rod_qspace_warp`
    builds for `layer='all'`/a list.

    With `max_satellites > 0`, the satellite comb is marked using
    :func:`~nrxrdct.laue.simulation.rod_satellite_along_positions` — pure
    Q-space geometry (same anchoring convention as `rod_tangency`'s own
    `'satellites'`), so this works whether or not `camera` was given, and
    markers are never filtered by on-detector status (there is no detector
    notion in a fixed-energy structure-factor map).

    Args:
        stack, hkl, energy_eV, layer, camera, ki_hat, q_par_range,
        q_perp_range, n_par, n_perp, half_size_px, perp_probe_px,
        structure_model: Forwarded to
            :func:`~nrxrdct.laue.simulation.simulate_rod_qspace`.
        max_satellites (int): `0` (default) shows only the crosshair at `G0`. `N > 0` also marks
            satellite orders `m = -N, ..., N` (see above).
        show_profile (bool): Add a paired axis with the intensity along `q_parallel`, summed
            over `±profile_halfwidth_bins` grid columns around `q_perp=0` —
            same idea as `plot_rod_qspace_warp`'s own `show_profile`, read
            directly off the already-computed simulated grid. Requires
            `ax=None`.
        profile_halfwidth_bins (int): Lateral summation half-width, in `q_perp` **grid columns**. Unused
            unless `show_profile=True`.
        log_scale (bool): Apply `log1p` scaling to the map before display.
        cmap (str): Matplotlib colormap.
        ax (matplotlib.axes.Axes, optional): Draw into an existing axes instead of creating a new figure. Only
            valid when `show_profile=False`; raises otherwise.
        figsize: Figure size (ignored if `ax` is given).
        out_path (str or None): Save figure to this path if given.

    Returns:
        `show_profile=False` (default): `(fig, ax, F2, q_par_ax, q_perp_ax, info)`.
        `show_profile=True`: `(fig, (ax, ax_profile), F2, q_par_ax, q_perp_ax, info)`.

        `F2`, `q_par_ax`, `q_perp_ax`, `info` are exactly
        :func:`~nrxrdct.laue.simulation.simulate_rod_qspace`'s own return
        values.

    Example:
    >>> plot_simulated_rod_qspace(stack, (0, 0, 2), energy_eV=17000, camera=cam, max_satellites=3)
    """
    from .simulation import rod_satellite_along_positions, simulate_rod_qspace

    if show_profile and ax is not None:
        raise ValueError("show_profile=True always creates its own figure; pass ax=None")

    F2, q_par_ax, q_perp_ax, info = simulate_rod_qspace(
        stack, hkl, energy_eV, layer=layer, camera=camera, ki_hat=ki_hat,
        q_par_range=q_par_range, q_perp_range=q_perp_range,
        n_par=n_par, n_perp=n_perp, half_size_px=half_size_px,
        perp_probe_px=perp_probe_px, max_satellites=max_satellites,
        structure_model=structure_model, verbose=False,
    )

    standalone = ax is None
    if standalone:
        if show_profile:
            fig = plt.figure(figsize=figsize, facecolor=BG)
            gs = mgridspec.GridSpec(1, 2, figure=fig, width_ratios=[1, 1], wspace=0.3, top=0.8)
            ax_i = fig.add_subplot(gs[0, 0])
            ax_p = fig.add_subplot(gs[0, 1])
        else:
            fig, ax_i = plt.subplots(figsize=figsize, facecolor=BG)
            ax_p = None
    else:
        fig = ax.figure
        ax_i = ax
        ax_p = None

    _ax_style(ax_i, "")

    display = F2.T  # (n_perp, n_par) -> (n_par, n_perp): rows=q_par, cols=q_perp
    if log_scale and display.max() > 0:
        display = np.log1p(display / display.max() * 1000.0)

    extent = [q_perp_ax[0], q_perp_ax[-1], q_par_ax[0], q_par_ax[-1]]
    im = ax_i.imshow(
        display, origin="lower", aspect="auto", extent=extent,
        cmap=cmap, interpolation="nearest",
    )
    cb = fig.colorbar(im, ax=ax_i, pad=0.02, fraction=0.045)
    cb.set_label("log intensity" if log_scale else "|F|²", color=FG, fontsize=8)
    cb.ax.tick_params(colors="#7788aa", labelsize=7)

    ax_i.plot(0.0, 0.0, "+", color=FG, ms=10, mew=1.4, zorder=5)
    ax_i.annotate(
        "G0", (0.0, 0.0), xytext=(8, 8),
        textcoords="offset points", color=FG, fontsize=7, zorder=6,
    )

    sat_along = None
    if max_satellites > 0:
        sat_along = rod_satellite_along_positions(
            info["stack_flat"], info["layer_obj"], info["G0"], info["n_hat"], max_satellites
        )
        for m, q_m in sat_along.items():
            if q_par_ax[0] <= q_m <= q_par_ax[-1]:
                ax_i.plot(0.0, q_m, "o", color=COL_SUP, ms=6, mec=BG, mew=0.6, zorder=4)
                ax_i.annotate(
                    "SL0" if m == 0 else f"{m:+d}", (0.0, q_m), xytext=(8, 0),
                    textcoords="offset points", color=COL_SUP, fontsize=7, va="center", zorder=6,
                )

    ax_i.set_xlabel(r"$q_\perp$  (Å⁻¹)", color=FG, fontsize=8)
    ax_i.set_ylabel(r"$q_\parallel$  (Å⁻¹)", color=FG, fontsize=8)
    ax_i.set_title(
        f"simulated  hkl={info['hkl']}  ({info['layer']})  E={info['energy_eV']:.0f} eV",
        color=FG, fontsize=9, pad=6,
    )

    if ax_p is not None:
        iperp0 = int(np.argmin(np.abs(q_perp_ax)))
        lo = max(iperp0 - profile_halfwidth_bins, 0)
        hi = min(iperp0 + profile_halfwidth_bins + 1, len(q_perp_ax))
        profile = np.sum(F2[lo:hi, :], axis=0)  # (n_perp, n_par) -> (n_par,)

        _ax_style(ax_p, "")
        ax_p.axvline(0.0, color=FG, lw=0.8, alpha=0.4)
        ax_p.plot(q_par_ax, profile, "-", color=COL_SUP, lw=1.3, label="simulated")
        ax_p.set_yscale("log")
        ax_p.set_xlabel(r"$q_\parallel$  (Å⁻¹)", color=FG, fontsize=8)
        ax_p.set_ylabel(
            f"|F|²  (Σ over ±{profile_halfwidth_bins} bins lateral)", color=FG, fontsize=8
        )
        if sat_along is not None:
            for m, q_m in sat_along.items():
                if q_par_ax[0] <= q_m <= q_par_ax[-1]:
                    ax_p.axvline(q_m, color=COL_SUP, lw=0.8, ls=":", alpha=0.6)
                    ax_p.text(
                        q_m, 1.02, "SL0" if m == 0 else f"{m:+d}",
                        transform=ax_p.get_xaxis_transform(),
                        color=COL_SUP, fontsize=7, ha="center", va="bottom", clip_on=False,
                    )
        leg = ax_p.legend(loc="upper right", fontsize=6.5, facecolor=BG, edgecolor="#333355", labelcolor=FG)
        leg.get_frame().set_alpha(0.85)
        ax_p.set_title(r"Simulated intensity along $q_\parallel$", color=FG, fontsize=9, pad=34)

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)

    if show_profile:
        return fig, (ax_i, ax_p), F2, q_par_ax, q_perp_ax, info
    return fig, ax_i, F2, q_par_ax, q_perp_ax, info

plot_spot_image

plot_spot_image(img, *, exp_image=None, log_intensity=True, vmin_percentile=0.0, vmax_percentile=99.5, figsize=None, out_path=None)

Plot the output of :func:~nrxrdct.laue.simulation.simulate_spot_image, optionally next to the matching patch cropped from a real measured detector frame.

Normalisation. Each panel is independently normalised by its own I / I_max before the log-stretch — the simulated panel by its own peak, the measured patch by its own peak within the cropped window. A shared percentile-based colour scale (vmin_percentile / vmax_percentile) is then derived from the combined non-zero pixels of both stretched panels, so faint features are visible at the same visual level in both — same convention as :func:plot_detector_projection.

Parameters:
  • img (dict) –

    Return value of :func:~nrxrdct.laue.simulation.simulate_spot_image.

  • exp_image ((ndarray, shape(Nv, Nh)), default: None ) –

    Full measured detector frame, in the same pixel convention as the camera used to build img. When given, a second "Measured" panel is added, cropped to img['x0'] / img['y0'].

  • log_intensity (bool, default: True ) –

    Apply log1p stretch to both panels.

  • vmin_percentile, vmax_percentile (float) –

    Percentile (0-100) of the combined non-zero stretched pixels used as the colour-scale min/max. Defaults 0 / 99.5 — true minimum, top 0.5% clipped.

  • figsize –

    Figure size. Defaults to (7, 5.5) (one panel) or (14, 5.5) (two panels).

  • out_path (str or None, default: None ) –

    Save figure to this path if given.

Returns:
  • –

    (fig, axes) where axes is a 1- or 2-element list.

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_spot_image(
    img,
    *,
    exp_image=None,
    log_intensity=True,
    vmin_percentile=0.0,
    vmax_percentile=99.5,
    figsize=None,
    out_path=None,
):
    """
    Plot the output of :func:`~nrxrdct.laue.simulation.simulate_spot_image`,
    optionally next to the matching patch cropped from a real measured
    detector frame.

    **Normalisation.** Each panel is independently normalised by its own
    `I / I_max` before the log-stretch — the simulated panel by its own
    peak, the measured patch by its own peak within the cropped window.
    A shared percentile-based colour scale (`vmin_percentile` /
    `vmax_percentile`) is then derived from the combined non-zero pixels of
    both stretched panels, so faint features are visible at the same
    visual level in both — same convention as
    :func:`plot_detector_projection`.

    Args:
        img (dict): Return value of
            :func:`~nrxrdct.laue.simulation.simulate_spot_image`.
        exp_image (ndarray, shape (Nv, Nh), optional): Full measured
            detector frame, in the same pixel convention as the `camera`
            used to build `img`.  When given, a second "Measured" panel is
            added, cropped to `img['x0']` / `img['y0']`.
        log_intensity (bool): Apply `log1p` stretch to both panels.
        vmin_percentile, vmax_percentile (float): Percentile (0-100) of the
            combined non-zero stretched pixels used as the colour-scale
            min/max.  Defaults `0` / `99.5` — true minimum, top 0.5% clipped.
        figsize: Figure size.  Defaults to `(7, 5.5)` (one panel) or
            `(14, 5.5)` (two panels).
        out_path (str or None): Save figure to this path if given.

    Returns:
        ``(fig, axes)`` where *axes* is a 1- or 2-element list.
    """
    sim = np.asarray(img["I"], dtype=float)
    x0, y0 = img["x0"], img["y0"]
    ext = [x0[0] - 0.5, x0[-1] + 0.5, y0[-1] + 0.5, y0[0] - 0.5]

    has_meas = exp_image is not None
    n_panels = 2 if has_meas else 1
    if figsize is None:
        figsize = (14.0, 5.5) if has_meas else (7.0, 5.5)

    fig, axes_arr = plt.subplots(
        1, n_panels, figsize=figsize, facecolor=BG, squeeze=False,
        sharex=True, sharey=True,
    )
    axes = list(axes_arr[0])
    cmap = mcolors.LinearSegmentedColormap.from_list(
        "qvol_warm", [_QVOL_LOW, _QVOL_MID, _QVOL_HIGH]
    )

    def _stretch(arr):
        return np.log1p(arr) if log_intensity else arr.copy()

    I_max_sim = float(sim.max()) if sim.max() > 0 else 1.0
    sim_n = sim / I_max_sim
    sim_s = _stretch(sim_n)

    if has_meas:
        img_arr = np.asarray(exp_image, dtype=float)
        iy0, iy1 = int(round(y0[0])), int(round(y0[-1])) + 1
        ix0, ix1 = int(round(x0[0])), int(round(x0[-1])) + 1
        meas_patch = img_arr[iy0:iy1, ix0:ix1]
        I_max_meas = float(meas_patch.max()) if meas_patch.max() > 0 else 1.0
        meas_n = meas_patch / I_max_meas
        meas_s = _stretch(meas_n)

    _nz_vals = [sim_s[sim_s > 0]]
    if has_meas:
        _nz_m = meas_s[meas_s > 0]
        if len(_nz_m):
            _nz_vals.append(_nz_m)
    _all_nz = np.concatenate(_nz_vals) if _nz_vals else np.array([0.0, 1.0])
    vmin_s = float(np.percentile(_all_nz, vmin_percentile)) if len(_all_nz) else 0.0
    vmax_s = float(np.percentile(_all_nz, vmax_percentile)) if len(_all_nz) else 1.0
    if vmax_s <= vmin_s:
        vmax_s = vmin_s + 1e-6

    for ax in axes:
        _ax_style(ax, "")
        ax.set_xlabel("xcam  (px)", color=FG, fontsize=8)
        ax.set_ylabel("ycam  (px)", color=FG, fontsize=8)

    ax_sim = axes[0]
    ax_sim.set_title("Simulated", color=FG, fontsize=9, pad=4)
    im_s = ax_sim.imshow(
        sim_s, origin="upper", extent=ext, cmap=cmap,
        vmin=vmin_s, vmax=vmax_s, aspect="equal", interpolation="nearest",
    )
    cbar_s = fig.colorbar(im_s, ax=ax_sim, shrink=0.85, pad=0.03)
    cbar_s.set_label("log(1+I/I_max)" if log_intensity else "I/I_max", color=FG, fontsize=7)
    cbar_s.ax.yaxis.set_tick_params(color="#7788aa", labelsize=6)
    plt.setp(cbar_s.ax.get_yticklabels(), color=FG)
    cbar_s.outline.set_edgecolor("#333355")

    if has_meas:
        ax_meas = axes[1]
        ax_meas.set_title("Measured", color=FG, fontsize=9, pad=4)
        im_m = ax_meas.imshow(
            meas_s, origin="upper", extent=ext, cmap="gray",
            vmin=vmin_s, vmax=vmax_s, aspect="equal", interpolation="nearest",
        )
        cbar_m = fig.colorbar(im_m, ax=ax_meas, shrink=0.85, pad=0.03)
        cbar_m.set_label("log(1+I/I_max)" if log_intensity else "I/I_max", color=FG, fontsize=7)
        cbar_m.ax.yaxis.set_tick_params(color="#7788aa", labelsize=6)
        plt.setp(cbar_m.ax.get_yticklabels(), color=FG)
        cbar_m.outline.set_edgecolor("#333355")

    ref_x, ref_y = img.get("ref_pix", (None, None))
    if ref_x is not None:
        for ax in axes:
            ax.plot(ref_x, ref_y, "+", color=FG, ms=10, mew=1.2, zorder=5)

    hkl_str = str(img.get("hkl", "?"))
    layer_str = str(img.get("layer", "?"))
    E0 = img.get("E0")
    n_harm = img.get("n_harmonics")
    title = f"hkl={hkl_str}  ({layer_str})  E0={E0:.0f} eV  harmonics=1..{n_harm}"
    fig.suptitle(title, color=FG, fontsize=10, y=1.01)
    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, axes

plot_strain_broadening

plot_strain_broadening(spots_b, camera, jacobians=None, out_path='strain_broadening.png', top_n=12)

Three-panel summary of strain-induced spot broadening.

Panel A — Detector map Each spot is drawn as an ellipse whose semi-axes come from the eigenvalues of the 2×2 pixel-space covariance cov_pix, coloured by sigma_strain_pix (semi-major axis).

Panel B — σ_strain vs 2θ Scatter plot of the major (solid) and minor (dashed) broadening semi-axes versus 2θ for every spot. The most-broadened spots are labelled with their (hkl) index.

Panel C — Jacobian heat-map (only when jacobians is provided) Rows = top_n most-broadened spots; columns = the 6 Voigt strain components. Cell colour = |∂xcam/∂εᵢⱼ| or |∂ycam/∂εᵢⱼ| (RMS of both rows of J), so you can read off which strain components most affect which spots.

Parameters:
  • spots_b (list of dict) –

    Output of :func:~nrxrdct.laue.simulation.strain_broadening. Must contain 'cov_pix', 'sigma_strain_pix', 'sigma_strain_minor', 'pix', 'tth', 'hkl'.

  • camera (Camera) –

    Used for detector dimensions in Panel A.

  • jacobians (dict {(h,k,l, default: None ) –

    ndarray (2,6)}, optional): Output of :func:~nrxrdct.laue.simulation.strain_spot_jacobian. When supplied, Panel C is drawn; otherwise it is replaced with a colour-bar for Panel A.

  • out_path (str, default: 'strain_broadening.png' ) –

    File path to save the figure. None → do not save.

  • top_n (int, default: 12 ) –

    Number of most-broadened spots to label / show in Panel C.

Returns:
  • fig( Figure ) –
Source code in src/nrxrdct/laue/laue_plotting.py
def plot_strain_broadening(
    spots_b,
    camera,
    jacobians=None,
    out_path="strain_broadening.png",
    top_n=12,
):
    """
    Three-panel summary of strain-induced spot broadening.

    Panel A — Detector map
        Each spot is drawn as an ellipse whose semi-axes come from the
        eigenvalues of the 2×2 pixel-space covariance `cov_pix`, coloured
        by `sigma_strain_pix` (semi-major axis).

    Panel B — σ_strain vs 2θ
        Scatter plot of the major (solid) and minor (dashed) broadening
        semi-axes versus 2θ for every spot.  The most-broadened spots are
        labelled with their (hkl) index.

    Panel C — Jacobian heat-map  *(only when* `jacobians` *is provided)*
        Rows = top_n most-broadened spots; columns = the 6 Voigt strain
        components.  Cell colour = |∂xcam/∂εᵢⱼ| or |∂ycam/∂εᵢⱼ|
        (RMS of both rows of J), so you can read off which strain components
        most affect which spots.

    Args:
        spots_b (list of dict): Output of :func:`~nrxrdct.laue.simulation.strain_broadening`.
            Must contain `'cov_pix'`, `'sigma_strain_pix'`,
            `'sigma_strain_minor'`, `'pix'`, `'tth'`, `'hkl'`.
        camera (Camera): Used for detector dimensions in Panel A.
        jacobians (dict {(h,k,l): ndarray (2,6)}, optional): Output of :func:`~nrxrdct.laue.simulation.strain_spot_jacobian`.
            When supplied, Panel C is drawn; otherwise it is replaced with a
            colour-bar for Panel A.
        out_path (str, optional): File path to save the figure.  `None` → do not save.
        top_n (int, optional): Number of most-broadened spots to label / show in Panel C.

    Returns:
        fig (matplotlib.figure.Figure):
"""
    from matplotlib.patches import Ellipse

    has_jac = jacobians is not None
    ncols = 3 if has_jac else 2
    fig, axes = plt.subplots(
        1, ncols,
        figsize=(6 * ncols, 6),
        gridspec_kw={"width_ratios": [2, 1.2, 1.4] if has_jac else [2, 1.2]},
    )
    fig.patch.set_facecolor(BG)
    ax_det, ax_scatter = axes[0], axes[1]
    ax_jac = axes[2] if has_jac else None

    # ── colour scale (shared) ─────────────────────────────────────────────────
    sigmas = [s["sigma_strain_pix"] for s in spots_b if s.get("pix") is not None]
    vmax = max(sigmas) if sigmas else 1.0
    cmap_s = "inferno"
    norm_s = mcolors.Normalize(vmin=0, vmax=vmax)

    # ── Panel A: detector map ─────────────────────────────────────────────────
    ax_det.set_facecolor(BG)
    ax_det.set_xlim(0, camera.Nh)
    ax_det.set_ylim(camera.Nv, 0)          # pixel row increases downward
    ax_det.set_aspect("equal")
    ax_det.set_xlabel("xcam  (pixel)", color=FG, fontsize=8)
    ax_det.set_ylabel("ycam  (pixel)", color=FG, fontsize=8)
    ax_det.tick_params(colors="#7788aa", labelsize=6)
    ax_det.set_title("Detector: strain broadening ellipses", color=FG, fontsize=9)
    for sp in ax_det.spines.values():
        sp.set_edgecolor("#1a1f2e")

    for s in spots_b:
        if s.get("pix") is None:
            continue
        xc, yc = s["pix"]
        cov = s.get("cov_pix", np.zeros((2, 2)))
        sigma_maj = s.get("sigma_strain_pix", 0.0)
        col = plt.cm.get_cmap(cmap_s)(norm_s(sigma_maj))

        if sigma_maj < 0.05:
            # Too small to show as ellipse — draw a dot
            ax_det.plot(xc, yc, ".", ms=2, color=col, alpha=0.7)
            continue

        # Compute ellipse orientation from eigenvectors of cov_pix
        eigvals, eigvecs = np.linalg.eigh(cov)
        eigvals = np.maximum(eigvals, 0.0)
        angle_deg = np.degrees(np.arctan2(eigvecs[1, -1], eigvecs[0, -1]))

        ell = Ellipse(
            xy=(xc, yc),
            width=2 * np.sqrt(eigvals[-1]),   # 1-sigma semi-major (diameter)
            height=2 * np.sqrt(eigvals[0]),   # 1-sigma semi-minor
            angle=angle_deg,
            linewidth=0.8,
            edgecolor=col,
            facecolor="none",
            alpha=0.85,
            zorder=3,
        )
        ax_det.add_patch(ell)
        ax_det.plot(xc, yc, "+", ms=3, color=col, lw=0.5, alpha=0.6)

    # Label top_n broadened spots
    top_spots = sorted(
        [s for s in spots_b if s.get("pix") is not None],
        key=lambda s: -s.get("sigma_strain_pix", 0),
    )[:top_n]
    for s in top_spots:
        h, k, l = s["hkl"]
        xc, yc = s["pix"]
        ax_det.annotate(
            f"({h}{k}{l})",
            xy=(xc, yc), xytext=(4, -4),
            textcoords="offset points",
            fontsize=5, color="#aaccff", alpha=0.9,
        )

    sm = plt.cm.ScalarMappable(cmap=cmap_s, norm=norm_s)
    sm.set_array([])
    cb = fig.colorbar(sm, ax=ax_det, fraction=0.03, pad=0.02)
    cb.set_label("σ_strain  (px, semi-major)", color="#7788aa", fontsize=7)
    cb.ax.tick_params(colors="#7788aa", labelsize=6)
    cb.outline.set_edgecolor("#1a1f2e")

    # ── Panel B: σ_strain vs 2θ ───────────────────────────────────────────────
    ax_scatter.set_facecolor(BG)
    ax_scatter.tick_params(colors="#7788aa", labelsize=6)
    ax_scatter.set_xlabel("2θ  (degrees)", color=FG, fontsize=8)
    ax_scatter.set_ylabel("broadening  (px, 1σ)", color=FG, fontsize=8)
    ax_scatter.set_title("Broadening vs 2θ", color=FG, fontsize=9)
    for sp in ax_scatter.spines.values():
        sp.set_edgecolor("#1a1f2e")
    ax_scatter.grid(True, ls=":", lw=0.3, color="#181e2e")

    valid = [s for s in spots_b if s.get("pix") is not None]
    tths = [s["tth"] for s in valid]
    sig_maj = [s["sigma_strain_pix"] for s in valid]
    sig_min = [s["sigma_strain_minor"] for s in valid]
    cols = [plt.cm.get_cmap(cmap_s)(norm_s(v)) for v in sig_maj]

    ax_scatter.scatter(tths, sig_maj, c=cols, s=18, zorder=3, label="semi-major σ")
    ax_scatter.scatter(tths, sig_min, c=cols, s=8, marker="^", alpha=0.5,
                       zorder=2, label="semi-minor σ")

    # Connect major/minor for each spot
    for t, sj, sn in zip(tths, sig_maj, sig_min):
        ax_scatter.plot([t, t], [sn, sj], color="#334455", lw=0.4, zorder=1)

    # Label the top_n most broadened
    top_tth = sorted(valid, key=lambda s: -s["sigma_strain_pix"])[:top_n]
    for s in top_tth:
        h, k, l = s["hkl"]
        ax_scatter.annotate(
            f"({h}{k}{l})",
            xy=(s["tth"], s["sigma_strain_pix"]),
            xytext=(3, 2), textcoords="offset points",
            fontsize=5, color="#aaccff",
        )

    ax_scatter.legend(fontsize=6, framealpha=0.2, facecolor=BG, labelcolor="white",
                      loc="upper right")

    # ── Panel C: Jacobian heat-map ────────────────────────────────────────────
    if has_jac and ax_jac is not None:
        ax_jac.set_facecolor(BG)
        ax_jac.set_title(
            "Strain sensitivity  |∂pix/∂εᵢⱼ|  (px per unit strain)",
            color=FG, fontsize=8,
        )
        ax_jac.tick_params(colors="#7788aa", labelsize=6)
        for sp in ax_jac.spines.values():
            sp.set_edgecolor("#1a1f2e")

        top_hkl = [s["hkl"] for s in top_spots]
        # Build heatmap matrix: rows = spots, cols = Voigt components
        # Cell value = RMS of the two rows of J (xcam and ycam sensitivity)
        heat = np.zeros((len(top_hkl), 6))
        for ri, hkl in enumerate(top_hkl):
            J = jacobians.get(hkl)
            if J is not None:
                heat[ri] = np.sqrt(0.5 * (J[0] ** 2 + J[1] ** 2))

        im_j = ax_jac.imshow(
            heat,
            aspect="auto",
            cmap="YlOrRd",
            interpolation="nearest",
        )
        ax_jac.set_xticks(range(6))
        ax_jac.set_xticklabels(_VOIGT_LABELS, fontsize=7, color=FG)
        ax_jac.set_yticks(range(len(top_hkl)))
        ax_jac.set_yticklabels(
            [f"({h}{k}{l})" for h, k, l in top_hkl], fontsize=6, color=FG
        )
        ax_jac.set_xlabel("Voigt strain component", color=FG, fontsize=7)

        # Annotate cells with the value
        for ri in range(len(top_hkl)):
            for ci in range(6):
                v = heat[ri, ci]
                if v > 0.01:
                    ax_jac.text(
                        ci, ri, f"{v:.1f}",
                        ha="center", va="center",
                        fontsize=5,
                        color="white" if v > heat.max() * 0.6 else "black",
                    )

        cb_j = fig.colorbar(im_j, ax=ax_jac, fraction=0.05, pad=0.02)
        cb_j.set_label("px / unit strain", color="#7788aa", fontsize=6)
        cb_j.ax.tick_params(colors="#7788aa", labelsize=5)
        cb_j.outline.set_edgecolor("#1a1f2e")

    fig.suptitle("Laue spot broadening due to elastic strain", color=FG,
                 fontsize=11, y=1.01)
    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Strain broadening plot saved → {out_path}")

    _force_draw(fig)
    return fig

plot_tth_chi_overlay

plot_tth_chi_overlay(image, camera, spots=None, *, frame: str = 'tth_chi', tth_range=None, chi_range=None, n_tth: int = 600, n_chi: int = 600, log_scale: bool = True, cmap: str = 'gray', spot_marker: str = '+', spot_size: float = 60.0, spot_color: str | None = None, color_spots_by: str = 'phase', i_thresh: float = 0.01, show_divergence: bool = True, divergence_nsigma: float = 2.0, figsize=(10, 7), out_path: str | None = None)

Overlay simulated spot positions on a detector image.

Two display frames are available via the frame parameter:

  • 'tth_chi' (default) — the detector image is warped from pixel coordinates into an evenly-spaced 2θ / χ grid using :func:warp_image_to_tth_chi, and simulated spots are overlaid at their angular positions.
  • 'detector' — the raw pixel image is displayed without any remapping. Simulated spots are projected to detector pixel coordinates (using the 'pix' key when present, or back-projected from their 2θ / χ angles via :meth:~Camera.kf_to_pixel).

Hovering over a spot in either frame shows the same tooltip (hkl, 2θ, χ, energy, intensity, reflection type, phase).

Parameters:
  • image ((array - like, shape(Nv, Nh))) –

    Detector image in pixel space.

  • camera (Camera) –

    Detector geometry.

  • spots (list[dict], default: None ) –

    Spot list from :func:~nrxrdct.laue.simulate_laue, :func:~nrxrdct.laue.simulate_laue_stack, or :func:~nrxrdct.laue.simulate_mixed_phases. Required keys: 'tth', 'chi'.

  • frame (`'tth_chi'` | `'detector'`, default: 'tth_chi' ) –

    Coordinate frame for the display (see above).

  • tth_range, chi_range ((float, float)) –

    Angular range to display (tth_chi frame only). Defaults to full detector coverage.

  • n_tth, n_chi (int) –

    Warp output resolution (tth_chi frame only).

  • log_scale (bool, default: True ) –

    Apply log1p scaling to the image before display.

  • cmap (str, default: 'gray' ) –

    Matplotlib colormap for the image.

  • spot_marker (str, default: '+' ) –

    Marker style for simulated spots (default '+').

  • spot_size (float, default: 60.0 ) –

    Marker size for simulated spots.

  • spot_color (str or None, default: None ) –

    Single colour for all spots. When None, colours are assigned per color_spots_by.

  • color_spots_by (`'phase'` | `'order'` | `'energy'`, default: 'phase' ) –

    How to colour spots when spot_color is None.

  • i_thresh (float, default: 0.01 ) –

    Minimum intensity as a fraction of the brightest Bragg peak (satellite_order == 0). Spots below the cutoff are not overlaid. Default: 0.01 (1 %). Pass 0.0 to show all spots.

  • figsize ((float, float), default: (10, 7) ) –
  • out_path (str or None, default: None ) –

    Save figure to this path if provided.

Returns:
  • fig( Figure ) –
  • ax( Axes ) –
  • display_image( ndarray ) –

    The image array that was actually plotted — the warped 2θ / χ grid when frame='tth_chi', or the (optionally log-scaled) raw pixel image when frame='detector'.

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_tth_chi_overlay(
    image,
    camera,
    spots=None,
    *,
    frame: str = "tth_chi",
    tth_range=None,
    chi_range=None,
    n_tth: int = 600,
    n_chi: int = 600,
    log_scale: bool = True,
    cmap: str = "gray",
    spot_marker: str = "+",
    spot_size: float = 60.0,
    spot_color: str | None = None,
    color_spots_by: str = "phase",
    i_thresh: float = 0.01,
    show_divergence: bool = True,
    divergence_nsigma: float = 2.0,
    figsize=(10, 7),
    out_path: str | None = None,
):
    """
    Overlay simulated spot positions on a detector image.

    Two display frames are available via the *frame* parameter:

    * `'tth_chi'` *(default)* — the detector image is warped from pixel
      coordinates into an evenly-spaced 2θ / χ grid using
      :func:`warp_image_to_tth_chi`, and simulated spots are overlaid at
      their angular positions.
    * `'detector'` — the raw pixel image is displayed without any
      remapping.  Simulated spots are projected to detector pixel coordinates
      (using the `'pix'` key when present, or back-projected from their
      2θ / χ angles via :meth:`~Camera.kf_to_pixel`).

    Hovering over a spot in either frame shows the same tooltip (hkl, 2θ,
    χ, energy, intensity, reflection type, phase).

    Args:
        image (array-like, shape (Nv, Nh)): Detector image in pixel space.
        camera (Camera): Detector geometry.
        spots (list[dict], optional): Spot list from :func:`~nrxrdct.laue.simulate_laue`,
            :func:`~nrxrdct.laue.simulate_laue_stack`, or
            :func:`~nrxrdct.laue.simulate_mixed_phases`.
            Required keys: `'tth'`, `'chi'`.
        frame (`'tth_chi'` | `'detector'`): Coordinate frame for the display (see above).
        tth_range, chi_range ((float, float), optional): Angular range to display (*tth_chi* frame only).
            Defaults to full detector coverage.
        n_tth, n_chi (int): Warp output resolution (*tth_chi* frame only).
        log_scale (bool): Apply `log1p` scaling to the image before display.
        cmap (str): Matplotlib colormap for the image.
        spot_marker (str): Marker style for simulated spots (default `'+'`).
        spot_size (float): Marker size for simulated spots.
        spot_color (str or None): Single colour for all spots.  When `None`, colours are assigned
            per `color_spots_by`.
        color_spots_by (`'phase'` | `'order'` | `'energy'`): How to colour spots when `spot_color` is `None`.
        i_thresh (float): Minimum intensity as a fraction of the brightest Bragg peak
            (`satellite_order == 0`).  Spots below the cutoff are not
            overlaid.  Default: `0.01` (1 %).  Pass `0.0` to show all spots.
        figsize ((float, float)):
        out_path (str or None): Save figure to this path if provided.

    Returns:
        fig (matplotlib.figure.Figure):
        ax (matplotlib.axes.Axes):
        display_image (ndarray): The image array that was actually plotted — the warped 2θ / χ grid
            when `frame='tth_chi'`, or the (optionally log-scaled) raw pixel
            image when `frame='detector'`.
"""
    if frame not in ("tth_chi", "detector"):
        raise ValueError(f"frame must be 'tth_chi' or 'detector', got {frame!r}")

    # ── Intensity threshold ───────────────────────────────────────────────────
    if spots and i_thresh > 0.0:
        bragg = [s for s in spots if s.get("satellite_order", 0) == 0]
        i_ref = max(s["intensity"] for s in bragg) if bragg else max(s["intensity"] for s in spots)
        spots = [s for s in spots if s["intensity"] >= i_thresh * i_ref]

    fig, ax = plt.subplots(figsize=figsize)
    fig.patch.set_facecolor(BG)
    ax.set_facecolor("#000000")

    # ── Image ─────────────────────────────────────────────────────────────────
    if frame == "tth_chi":
        warped, tth_ax, chi_ax = warp_image_to_tth_chi(
            image, camera,
            tth_range=tth_range, chi_range=chi_range,
            n_tth=n_tth, n_chi=n_chi,
        )
        display = np.where(np.isnan(warped), 0.0, warped)
        if log_scale and display.max() > 0:
            display = np.log1p(display / display.max() * 1000.0)
        display[np.isnan(warped)] = np.nan
        extent = [tth_ax[0], tth_ax[-1], chi_ax[0], chi_ax[-1]]
        im = ax.imshow(display, origin="lower", aspect="auto",
                       extent=extent, cmap=cmap, interpolation="nearest")
        ax.set_xlabel("2θ  (°)", color="#7788aa", fontsize=9)
        ax.set_ylabel("χ  (°)", color="#7788aa", fontsize=9)
        frame_label = "2θ / χ frame"
    else:  # 'detector'
        raw = np.asarray(image, dtype=np.float64)
        display = raw.copy()
        if log_scale and display.max() > 0:
            display = np.log1p(display / display.max() * 1000.0)
        # imshow with pixel-coordinate extent; origin='upper' so row 0 is at top
        im = ax.imshow(display, origin="upper", aspect="equal",
                       extent=[0, camera.Nh, camera.Nv, 0],
                       cmap=cmap, interpolation="nearest")
        ax.set_xlabel("x  (px)", color="#7788aa", fontsize=9)
        ax.set_ylabel("y  (px)", color="#7788aa", fontsize=9)
        frame_label = "detector frame"

    cb = fig.colorbar(im, ax=ax, pad=0.02, fraction=0.025)
    cb.set_label("log intensity" if log_scale else "intensity",
                 color=FG, fontsize=8)
    cb.ax.tick_params(colors="#7788aa", labelsize=7)

    # ── Overlay spots ─────────────────────────────────────────────────────────
    lc = {}
    unique = []
    if spots:
        if frame == "tth_chi":
            xs = np.array([s["tth"] for s in spots])
            ys = np.array([s["chi"] for s in spots])
        else:
            # Prefer pre-computed pixel positions; fall back to projection
            xs_list, ys_list = [], []
            for s in spots:
                pix = s.get("pix")
                if pix is not None:
                    xs_list.append(pix[0])
                    ys_list.append(pix[1])
                else:
                    tth_r = np.radians(s["tth"])
                    chi_r = np.radians(s["chi"])
                    st = np.sin(tth_r)
                    kf = np.array([[np.cos(tth_r),
                                    st * np.sin(chi_r),
                                    st * np.cos(chi_r)]])
                    xc, yc = camera.kf_to_pixel(kf)
                    xs_list.append(float(xc[0]))
                    ys_list.append(float(yc[0]))
            xs = np.array(xs_list)
            ys = np.array(ys_list)
            # Drop spots that project off the detector
            on_det = (
                np.isfinite(xs) & np.isfinite(ys)
                & (xs >= 0) & (xs < camera.Nh)
                & (ys >= 0) & (ys < camera.Nv)
            )
            spots = [s for s, ok in zip(spots, on_det) if ok]
            xs = xs[on_det]
            ys = ys[on_det]

        if spot_color is not None:
            colors = spot_color
        elif color_spots_by == "phase":
            labels = [s.get("phase_label", "sim") for s in spots]
            unique = list(dict.fromkeys(labels))
            tab10 = plt.get_cmap("tab10")
            lc = {lb: tab10(i / max(len(unique) - 1, 1)) for i, lb in enumerate(unique)}
            colors = [lc[lb] for lb in labels]
        elif color_spots_by == "order":
            orders = np.array([s.get("satellite_order", 0) for s in spots])
            norm = mcolors.Normalize(vmin=orders.min(), vmax=orders.max())
            colors = plt.get_cmap("coolwarm")(norm(orders))
        elif color_spots_by == "energy":
            energies = np.array([s["E"] / 1e3 for s in spots])
            norm = mcolors.Normalize(vmin=energies.min(), vmax=energies.max())
            colors = plt.get_cmap("plasma")(norm(energies))
        else:
            colors = "#ff4444"

        ax.scatter(xs, ys, c=colors, s=spot_size, marker=spot_marker,
                   linewidths=0.9, zorder=4, label="simulated spots")
        if show_divergence:
            _draw_divergence_ellipses(ax, spots, xs, ys, frame,
                                      divergence_nsigma, colors)

        # Hover tooltip — pass axes coordinates (tth/chi or xcam/ycam)
        _attach_hover_tooltip(fig, ax, spots, xs, ys)

    # ── Axes styling ──────────────────────────────────────────────────────────
    ax.tick_params(colors="#7788aa", labelsize=7)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")

    n_spots = len(spots) if spots else 0
    hover_hint = "   (hover for details)" if n_spots else ""
    ax.set_title(
        f"Detector image — {frame_label}"
        + (f"   |   {n_spots} simulated spots{hover_hint}" if n_spots else ""),
        color=FG, fontsize=9, pad=6,
    )

    if spots and spot_color is None and color_spots_by == "phase" and unique:
        from matplotlib.lines import Line2D
        handles = [
            Line2D([0], [0], linestyle="none", marker=spot_marker,
                   color=lc[lb], markersize=7, label=lb)
            for lb in unique
        ]
        ax.legend(handles=handles, loc="upper right", fontsize=7.5,
                  framealpha=0.5, facecolor="#1a1f2e", edgecolor="#3a3f4e",
                  labelcolor=FG)

    fig.tight_layout()
    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
        print(f"  Overlay saved → {out_path}")

    _force_draw(fig)
    return fig, ax, display
plot_twin_search(image, crystal, camera, U0, twin_result, *, peaklist=None, match_px: float = 10.0, i_thresh: float = 0.01, n_label: int = 6, vmin_pct: float = 1.0, vmax_pct: float = 99.9, E_min_eV: float = 5000, E_max_eV: float = 27000, allowed_hkl=None, figsize: tuple = (10, 9), out_path: str | None = None)

Overlay a primary orientation and a twin candidate on the raw image.

Simulates both U0 and the twin candidate's orientation and draws each one's predicted spot positions over the raw detector frame, together with the measured peak list if supplied. When peaklist is given, the title reports the :func:~nrxrdct.laue.fitting.classify_spot_matches counts directly, so you can see at a glance whether the twin candidate explains any real, independent intensity or is just re-explaining U0's own spots.

Parameters:
  • image ((Nv, Nh) array) –

    Raw detector frame.

  • crystal –

    Crystal object passed to :func:~nrxrdct.laue.simulation.simulate_laue.

  • camera (Camera) –

    Detector geometry.

  • U0 ((3, 3) ndarray) –

    Primary/reference orientation matrix.

  • twin_result (TwinCandidateResult or (3, 3) ndarray) –

    Output of :func:~nrxrdct.laue.fitting.search_twin_orientation_image (a single candidate, e.g. results[0]), or a bare orientation matrix.

  • peaklist (ndarray (N, >=2) or None, default: None ) –

    Segmented peak table (peaklist[:, :2] = pixel positions). When given, measured peaks are overlaid and the title shows the U0/twin/both/neither match breakdown from :func:~nrxrdct.laue.fitting.classify_spot_matches.

  • match_px (float, default: 10.0 ) –

    Match radius (px) for the peak classification. Default 10.0.

  • i_thresh (float, default: 0.01 ) –

    Minimum I/Imax for a simulated spot to be shown. Default 0.01.

  • n_label (int, default: 6 ) –

    Number of strongest spots per candidate to annotate with their (hkl). Default 6.

  • vmin_pct, vmax_pct (float) –

    Percentiles of the raw image (over positive pixels) used as the LogNorm display range. Default 1.0, 99.9 — robust to a handful of extreme/saturated pixels without needing manual tuning.

  • E_min_eV, E_max_eV (float) –

    Energy range for spot simulation.

  • allowed_hkl –

    Pre-computed allowed-HKL frozenset (see :func:~nrxrdct.laue.simulation.precompute_allowed_hkl). Strongly recommended.

  • figsize (tuple, default: (10, 9) ) –

    Figure size in inches. Default (10, 9).

  • out_path (str or None, default: None ) –

    Save the figure to this path if given.

Returns:
  • fig( Figure ) –
  • ax( Axes ) –
Source code in src/nrxrdct/laue/laue_plotting.py
def plot_twin_search(
    image,
    crystal,
    camera,
    U0,
    twin_result,
    *,
    peaklist=None,
    match_px: float = 10.0,
    i_thresh: float = 0.01,
    n_label: int = 6,
    vmin_pct: float = 1.0,
    vmax_pct: float = 99.9,
    E_min_eV: float = 5_000,
    E_max_eV: float = 27_000,
    allowed_hkl=None,
    figsize: tuple = (10, 9),
    out_path: "str | None" = None,
):
    """
    Overlay a primary orientation and a twin candidate on the raw image.

    Simulates both `U0` and the twin candidate's orientation and draws each
    one's predicted spot positions over the raw detector frame, together with
    the measured peak list if supplied.  When *peaklist* is given, the title
    reports the :func:`~nrxrdct.laue.fitting.classify_spot_matches` counts
    directly, so you can see at a glance whether the twin candidate explains
    any real, independent intensity or is just re-explaining `U0`'s own spots.

    Args:
        image ((Nv, Nh) array): Raw detector frame.
        crystal: Crystal object passed to :func:`~nrxrdct.laue.simulation.simulate_laue`.
        camera (Camera): Detector geometry.
        U0 ((3, 3) ndarray): Primary/reference orientation matrix.
        twin_result (TwinCandidateResult or (3, 3) ndarray): Output of
            :func:`~nrxrdct.laue.fitting.search_twin_orientation_image` (a
            single candidate, e.g. `results[0]`), or a bare orientation matrix.
        peaklist (ndarray (N, >=2) or None): Segmented peak table
            (`peaklist[:, :2]` = pixel positions).  When given, measured
            peaks are overlaid and the title shows the U0/twin/both/neither
            match breakdown from :func:`~nrxrdct.laue.fitting.classify_spot_matches`.
        match_px (float): Match radius (px) for the peak classification.
            Default `10.0`.
        i_thresh (float): Minimum `I/Imax` for a simulated spot to be shown.
            Default `0.01`.
        n_label (int): Number of strongest spots per candidate to annotate
            with their `(hkl)`.  Default `6`.
        vmin_pct, vmax_pct (float): Percentiles of the raw image (over
            positive pixels) used as the `LogNorm` display range.  Default
            `1.0`, `99.9` — robust to a handful of extreme/saturated pixels
            without needing manual tuning.
        E_min_eV, E_max_eV (float): Energy range for spot simulation.
        allowed_hkl: Pre-computed allowed-HKL frozenset (see
            :func:`~nrxrdct.laue.simulation.precompute_allowed_hkl`).
            Strongly recommended.
        figsize (tuple): Figure size in inches.  Default `(10, 9)`.
        out_path (str or None): Save the figure to this path if given.

    Returns:
        fig (matplotlib.figure.Figure):
        ax (matplotlib.axes.Axes):
"""
    from .fitting import TwinCandidateResult, classify_spot_matches
    from .simulation import simulate_laue as _sim_laue

    U_twin = (
        twin_result.U if isinstance(twin_result, TwinCandidateResult)
        else np.asarray(twin_result, dtype=float)
    )

    spots_u0 = _sim_laue(crystal, U0, camera, E_min=E_min_eV, E_max=E_max_eV,
                          allowed_hkl=allowed_hkl)
    spots_tw = _sim_laue(crystal, U_twin, camera, E_min=E_min_eV, E_max=E_max_eV,
                          allowed_hkl=allowed_hkl)
    spots_u0 = [s for s in spots_u0 if s["intensity"] >= i_thresh]
    spots_tw = [s for s in spots_tw if s["intensity"] >= i_thresh]

    img = np.asarray(image, dtype=float)
    pos = img[img > 0]
    vmin = float(np.percentile(pos, vmin_pct)) if pos.size else 1.0
    vmax = float(np.percentile(pos, vmax_pct)) if pos.size else 1.0
    vmax = max(vmax, vmin * 1.001)

    fig, ax = plt.subplots(figsize=figsize, facecolor=BG)
    ax.set_facecolor(BG)
    ax.imshow(
        img, origin="upper", cmap="inferno",
        norm=mcolors.LogNorm(vmin=max(vmin, 1e-6), vmax=vmax),
        aspect="equal", interpolation="nearest", alpha=0.75, zorder=1,
    )

    title_extra = ""
    if peaklist is not None:
        pk = np.asarray(peaklist, dtype=float)
        if pk.shape[0] > 0:
            ax.scatter(
                pk[:, 0], pk[:, 1], s=30,
                facecolors="none", edgecolors="white", linewidths=0.8,
                zorder=2, label=f"measured (n={pk.shape[0]})",
            )
            cls = classify_spot_matches(
                pk[:, :2], spots_u0, spots_tw,
                match_px=match_px, label_a="U0", label_b="twin",
            )
            title_extra = (
                f"  |  U0 only {int(cls.a_only.sum())}  "
                f"twin only {int(cls.b_only.sum())}  "
                f"both {int(cls.both.sum())}  "
                f"neither {int(cls.neither.sum())}"
            )

    def _scatter(spots, color, label, marker):
        if not spots:
            return
        xy = np.array([s["pix"] for s in spots])
        I  = np.array([s["intensity"] for s in spots])
        ax.scatter(
            xy[:, 0], xy[:, 1], s=30 + 120 * I,
            facecolors="none", edgecolors=color, marker=marker,
            linewidths=1.3, zorder=3, label=f"{label}  (n={len(spots)})",
        )
        for i in np.argsort(I)[::-1][:n_label]:
            h, k, l = spots[i]["hkl"]
            ax.annotate(
                f"({h:.0f}{k:.0f}{l:.0f})", xy[i], xytext=(4, 4),
                textcoords="offset points", fontsize=7, color=color, zorder=4,
            )

    _scatter(spots_u0, COL_BCC, "primary (U0)", "o")
    _scatter(spots_tw, COL_SUP, "twin candidate", "s")

    ax.set_xlim(-0.5, img.shape[1] - 0.5)
    ax.set_ylim(img.shape[0] - 0.5, -0.5)
    ax.set_xlabel("Column  (pixel)", color=FG, fontsize=9)
    ax.set_ylabel("Row  (pixel)", color=FG, fontsize=9)
    ax.tick_params(colors="#7788aa", labelsize=7)
    for sp in ax.spines.values():
        sp.set_edgecolor("#1a1f2e")
    ax.set_title(
        "Primary vs. twin-candidate simulated spots" + title_extra,
        color=FG, fontsize=9, pad=6,
    )
    ax.legend(
        loc="upper right", fontsize=7, framealpha=0.4,
        facecolor="#1a1f2e", edgecolor="#3a3f4e", labelcolor=FG,
    )
    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Twin-search plot saved → {out_path}")

    return fig, ax

plot_unit_cell

plot_unit_cell(crystal, hkl: tuple[int, int, int] | list[tuple[int, int, int]] = (1, 1, 1), *, plane_offset: int | list[int | None] | None = None, show_normal: bool = True, show_axes_arrows: bool = True, cell_color: str = FG, plane_colors: str | list[str] | None = None, normal_color: str = COL_DB, elev: float = 20.0, azim: float = -50.0, figsize: tuple[float, float] = (7, 7), ax: Axes | None = None, out_path: str | None = None)

Draw the full (conventional, non-reduced) unit cell of crystal in 3-D and overlay one or more representative planes from the hkl families for visualization.

The cell is the parallelepiped spanned by crystal.a1, crystal.a2, crystal.a3 (the real-space lattice vectors exactly as built by xrayutilities.materials.SGLattice/Crystal — no Niggli/Delaunay reduction is applied, matching what CIF or build_bcc/build_b2 etc. hand back). Each (hkl) plane is found as the intersection of h·u + k·v + l·w = m (fractional coordinates u,v,w, the textbook Miller-index construction) with the unit cell cube, then mapped back to Cartesian space through crystal.a1/a2/a3. m (the plane's distance from the origin, in lattice-plane units) defaults to whichever of ±1 actually intersects the cell interior, so both all-positive and mixed-sign index families render a sensible cross-section.

Parameters:
  • crystal –

    An xrayutilities-compatible crystal object exposing .a1 .a2 .a3 (Cartesian real-space cell vectors, Å), .Q(h, k, l) (reciprocal-lattice vector) and .planeDistance(h, k, l) (d-spacing).

  • hkl (tuple[int, int, int] | list[tuple[int, int, int]], default: (1, 1, 1) ) –

    Miller indices of the plane to draw, e.g. (1, 1, 1), or a list of several, e.g. [(1, 1, 1), (1, 0, 0)].

  • plane_offset (int | list[int | None] | None, default: None ) –

    Override the automatic choice of m above (e.g. 2 to draw the second plane of the family instead of the first). Either a single value applied to every plane in hkl, or a list matching hkl one-to-one.

  • show_normal (bool, default: True ) –

    Draw an arrow along crystal.Q(hkl) (the plane normal), anchored at that plane's own centroid.

  • show_axes_arrows (bool, default: True ) –

    Draw labelled a, b, c arrows from the origin.

  • cell_color, normal_color –

    Line colours.

  • plane_colors (str | list[str] | None, default: None ) –

    Fill/edge colour(s) for the plane(s). A single colour applied to all planes, a list matching hkl one-to-one, or None to cycle through the project's standard grain palette.

  • elev, azim –

    3-D view angle (degrees), forwarded to Axes3D.view_init.

  • figsize (tuple[float, float], default: (7, 7) ) –

    Figure size in inches (only used when ax is None).

  • ax (Axes | None, default: None ) –

    Draw into an existing 3-D :class:~matplotlib.axes.Axes (created with projection='3d'); None creates a new figure.

  • out_path (str | None, default: None ) –

    Save path; None → do not save.

Returns:
  • –

    (fig, ax)

Example:

crystal = crystal_from_cif("Al2O3.cif") plot_unit_cell(crystal, hkl=[(1, 0, 4), (0, 0, 1)], out_path="al2o3.png")

Source code in src/nrxrdct/laue/laue_plotting.py
def plot_unit_cell(
    crystal,
    hkl: "tuple[int, int, int] | list[tuple[int, int, int]]" = (1, 1, 1),
    *,
    plane_offset: "int | list[int | None] | None" = None,
    show_normal: bool = True,
    show_axes_arrows: bool = True,
    cell_color: str = FG,
    plane_colors: "str | list[str] | None" = None,
    normal_color: str = COL_DB,
    elev: float = 20.0,
    azim: float = -50.0,
    figsize: "tuple[float, float]" = (7, 7),
    ax: "plt.Axes | None" = None,
    out_path: "str | None" = None,
):
    """
    Draw the full (conventional, non-reduced) unit cell of *crystal* in 3-D
    and overlay one or more representative planes from the `hkl` families
    for visualization.

    The cell is the parallelepiped spanned by `crystal.a1`, `crystal.a2`,
    `crystal.a3` (the real-space lattice vectors exactly as built by
    `xrayutilities.materials.SGLattice`/`Crystal` — no Niggli/Delaunay
    reduction is applied, matching what CIF or `build_bcc`/`build_b2` etc.
    hand back). Each `(hkl)` plane is found as the intersection of
    `h·u + k·v + l·w = m` (fractional coordinates `u,v,w`, the textbook
    Miller-index construction) with the unit cell cube, then mapped back to
    Cartesian space through `crystal.a1/a2/a3`. `m` (the plane's distance
    from the origin, in lattice-plane units) defaults to whichever of ±1
    actually intersects the cell interior, so both all-positive and
    mixed-sign index families render a sensible cross-section.

    Args:
        crystal: An *xrayutilities*-compatible crystal object exposing
            `.a1 .a2 .a3` (Cartesian real-space cell vectors, Å),
            `.Q(h, k, l)` (reciprocal-lattice vector) and
            `.planeDistance(h, k, l)` (d-spacing).
        hkl: Miller indices of the plane to draw, e.g. `(1, 1, 1)`, or a
            list of several, e.g. `[(1, 1, 1), (1, 0, 0)]`.
        plane_offset: Override the automatic choice of `m` above (e.g. `2`
            to draw the second plane of the family instead of the first).
            Either a single value applied to every plane in `hkl`, or a
            list matching `hkl` one-to-one.
        show_normal: Draw an arrow along `crystal.Q(hkl)` (the plane
            normal), anchored at that plane's own centroid.
        show_axes_arrows: Draw labelled `a`, `b`, `c` arrows from the
            origin.
        cell_color, normal_color: Line colours.
        plane_colors: Fill/edge colour(s) for the plane(s). A single colour
            applied to all planes, a list matching `hkl` one-to-one, or
            `None` to cycle through the project's standard grain palette.
        elev, azim: 3-D view angle (degrees), forwarded to `Axes3D.view_init`.
        figsize: Figure size in inches (only used when `ax is None`).
        ax: Draw into an existing 3-D :class:`~matplotlib.axes.Axes`
            (created with `projection='3d'`); `None` creates a new figure.
        out_path: Save path; `None` → do not save.

    Returns:
        `(fig, ax)`

    Example:
    >>> crystal = crystal_from_cif("Al2O3.cif")
    >>> plot_unit_cell(crystal, hkl=[(1, 0, 4), (0, 0, 1)], out_path="al2o3.png")
    """
    from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 — registers '3d' projection
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection

    hkls = _normalize_hkl_list(hkl)
    if any(h == 0 and k == 0 and l == 0 for h, k, l in hkls):
        raise ValueError("hkl=(0, 0, 0) does not define a plane")

    n_planes = len(hkls)
    offsets = plane_offset if isinstance(plane_offset, (list, tuple)) else [plane_offset] * n_planes
    if len(offsets) != n_planes:
        raise ValueError("plane_offset list must match the number of hkl planes")
    if plane_colors is None:
        colors = [_GRAIN_COLORS[i % len(_GRAIN_COLORS)] for i in range(n_planes)]
    elif isinstance(plane_colors, str):
        colors = [plane_colors] * n_planes
    else:
        colors = list(plane_colors)
        if len(colors) != n_planes:
            raise ValueError("plane_colors list must match the number of hkl planes")

    ai = np.array([crystal.a1, crystal.a2, crystal.a3], dtype=float)
    cart_corners = _CELL_CORNERS_FRAC @ ai
    edges = [
        (i, j)
        for i in range(8)
        for j in range(i + 1, 8)
        if np.sum(_CELL_CORNERS_FRAC[i] != _CELL_CORNERS_FRAC[j]) == 1
    ]

    standalone = ax is None
    if standalone:
        fig = plt.figure(figsize=figsize)
        fig.patch.set_facecolor(BG)
        ax = fig.add_subplot(111, projection="3d")
    else:
        fig = ax.figure

    ax.set_facecolor(BG)
    fig.patch.set_facecolor(BG)
    for pane in (ax.xaxis, ax.yaxis, ax.zaxis):
        pane.set_pane_color((0.03, 0.05, 0.08, 1.0))
        pane._axinfo["grid"]["color"] = (0.1, 0.12, 0.18, 0.6)
    ax.tick_params(colors="#7788aa", labelsize=7)

    for i, j in edges:
        p, q = cart_corners[i], cart_corners[j]
        ax.plot(*zip(p, q), color=cell_color, lw=1.2, alpha=0.6)
    ax.scatter(*cart_corners.T, color=cell_color, s=12, alpha=0.8)

    legend_handles = []
    drew_any_normal = False
    normal_arrow_len = 0.6 * min(np.linalg.norm(v) for v in ai)
    for (h, k, l), user_offset, plane_color in zip(hkls, offsets, colors):
        if user_offset is not None:
            offsets_to_try = [user_offset]
        else:
            f_max = max(h, 0) + max(k, 0) + max(l, 0)
            offsets_to_try = [1, -1] if f_max >= 1 else [-1, 1]

        frac_poly = []
        for m in offsets_to_try:
            frac_poly = _hkl_plane_fractional(h, k, l, m)
            if len(frac_poly) >= 3:
                break

        d_hkl = crystal.planeDistance(h, k, l)
        if len(frac_poly) < 3:
            print(f"  Warning: ({_hkl_label(h, k, l)}) plane does not intersect "
                  f"the unit cell for the offsets tried ({offsets_to_try}); pass "
                  f"plane_offset explicitly to pick a different member of "
                  f"the family.")
            continue

        cart_poly = np.array(frac_poly) @ ai
        ax.add_collection3d(Poly3DCollection(
            [cart_poly], facecolor=plane_color, edgecolor=plane_color,
            linewidths=1.2, alpha=0.35,
        ))
        legend_handles.append(
            Line2D([0], [0], color=plane_color, lw=2,
                   label=f"({_hkl_label(h, k, l)})  d = {d_hkl:.4f} Å")
        )

        if show_normal:
            # Anchored at this plane's own centroid (not the cell centroid)
            # so the arrow sits flush against the plane it belongs to.
            plane_centroid = cart_poly.mean(axis=0)
            n_hat = crystal.Q(h, k, l)
            n_hat = n_hat / np.linalg.norm(n_hat)
            ax.quiver(*plane_centroid, *(n_hat * normal_arrow_len),
                       color=normal_color, linewidth=1.8, arrow_length_ratio=0.15)
            drew_any_normal = True

    if drew_any_normal:
        legend_handles.append(
            Line2D([0], [0], color=normal_color, lw=2, label="plane normal (Q_hkl)")
        )

    if show_axes_arrows:
        for vec, label in zip(ai, ("a", "b", "c")):
            ax.quiver(0, 0, 0, *vec, color=cell_color, linewidth=1.0,
                      arrow_length_ratio=0.08, alpha=0.9)
            ax.text(*(vec * 1.08), label, color=cell_color, fontsize=10)

    ax.set_xlabel("x  (Å)", color=FG, fontsize=8, labelpad=8)
    ax.set_ylabel("y  (Å)", color=FG, fontsize=8, labelpad=8)
    ax.set_zlabel("z  (Å)", color=FG, fontsize=8, labelpad=8)
    title = ", ".join(f"({_hkl_label(h, k, l)})" for h, k, l in hkls) if n_planes <= 3 else f"{n_planes} planes"
    ax.set_title(f"Unit cell — {title}", color=FG, fontsize=10, pad=10)
    ax.view_init(elev=elev, azim=azim)
    try:
        ax.set_box_aspect(np.ptp(cart_corners, axis=0))
    except AttributeError:
        pass

    if legend_handles:
        ax.legend(
            handles=legend_handles, fontsize=7, labelcolor=FG,
            facecolor="#1a1f2e", edgecolor="#333355", loc="upper left",
        )

    if standalone:
        fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, ax

plot_unit_cell_in_lab

plot_unit_cell_in_lab(crystal, U: ndarray, hkl: tuple[int, int, int] | list[tuple[int, int, int]] = (1, 1, 1), *, camera: Camera | None = None, plane_offset: int | list[int | None] | None = None, show_normal: bool = True, show_crystal_axes: bool = True, show_lab_axes: bool = True, show_beam: bool = True, show_scattered_rays: bool = True, cell_color: str = FG, plane_colors: str | list[str] | None = None, beam_color: str = 'red', elev: float = 0.0, azim: float = -90.0, figsize: tuple[float, float] = (12, 9), out_path: str | None = None)

Two-panel 3-D view of a crystal's unit cell rotated into the lab frame via the orientation matrix U.

Left panel: the real-space cell with hkl plane(s) cut through it, as in :func:plot_unit_cell. Right panel: a scattering diagram -- one incident beam and every plane's normal and elastically diffracted-ray direction, all sharing a common origin and colour-coded to match their plane in the left panel. Both panels start at the same view angle (elev, azim) and stay in lock-step afterwards: on an interactive backend, mouse-drag-rotating either panel rotates the other to match, so a plane's cut in the cell and its normal/ray direction in the diagram can always be read together for the current orientation (a no-op when rendering straight to a static image via out_path).

Lab frame convention (LaueTools / this project, matching plot_layer_scheme): x = incident beam direction, z = vertical up, y completes the right-handed frame. v_lab = U @ v_crystal for any crystal-frame vector -- the same convention used throughout nrxrdct.laue.simulation (e.g. layer.U @ layer.crystal.Q(h, k, l)).

The right-hand diagram is deliberately decoupled from the cell's Å scale: every vector there is unit length, regardless of camera or physical distance. A future version could rescale it into true detector millimetres (reintroducing a to-scale detector) without touching the cell panel, as long as both keep using the same U and lab-frame axis convention.

Each hkl's elastically diffracted direction is found by solving the Laue condition |k0·x̂ + G_lab| = k0 (see _bragg_kf_hat); reflections with no elastic solution for a beam along +x are skipped with a printed note. Passing a camera adds a projected-pixel label at each ray tip (via camera.project) without otherwise changing the diagram.

Parameters:
  • crystal –

    xrayutilities-compatible crystal object (see plot_unit_cell).

  • U (ndarray) –

    (3, 3) orientation matrix rotating crystal-frame vectors into the lab frame.

  • hkl (tuple[int, int, int] | list[tuple[int, int, int]], default: (1, 1, 1) ) –

    Miller indices of the plane(s) to draw (single tuple or list).

  • camera (Camera | None, default: None ) –

    Optional :class:~nrxrdct.laue.camera.Camera; when given, each diffracted ray is labelled with its projected pixel.

  • plane_offset, plane_colors –

    see plot_unit_cell.

  • show_normal (bool, default: True ) –

    Draw each plane's normal vector in the right panel.

  • show_crystal_axes (bool, default: True ) –

    Draw labelled a, b, c arrows (rotated into the lab frame) in the left (cell) panel.

  • show_lab_axes (bool, default: True ) –

    Draw the fixed lab-frame x/y/z triad in both panels.

  • show_beam (bool, default: True ) –

    Draw the single incident-beam arrow in the right panel.

  • show_scattered_rays (bool, default: True ) –

    Draw each plane's diffracted-ray direction (dashed, to distinguish it from the solid normal vectors) in the right panel.

  • cell_color, beam_color –

    Line colours.

  • elev, azim –

    3-D view angle (degrees), shared by both panels. Defaults to a view looking down +y (elev=0, azim=-90), so the beam (x) / up (z) plane is seen face-on.

  • figsize (tuple[float, float], default: (12, 9) ) –

    Figure size in inches.

  • out_path (str | None, default: None ) –

    Save path; None → do not save.

Returns:
  • –

    (fig, (ax_cell, ax_scatter))

Example:

U = euler_to_U(10, 20, 30) plot_unit_cell_in_lab(crystal, U, hkl=[(1, 1, 1), (1, 0, 0)], camera=cam)

Source code in src/nrxrdct/laue/laue_plotting.py
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
def plot_unit_cell_in_lab(
    crystal,
    U: "np.ndarray",
    hkl: "tuple[int, int, int] | list[tuple[int, int, int]]" = (1, 1, 1),
    *,
    camera: "Camera | None" = None,
    plane_offset: "int | list[int | None] | None" = None,
    show_normal: bool = True,
    show_crystal_axes: bool = True,
    show_lab_axes: bool = True,
    show_beam: bool = True,
    show_scattered_rays: bool = True,
    cell_color: str = FG,
    plane_colors: "str | list[str] | None" = None,
    beam_color: str = "red",
    elev: float = 0.0,
    azim: float = -90.0,
    figsize: "tuple[float, float]" = (12, 9),
    out_path: "str | None" = None,
):
    """
    Two-panel 3-D view of a crystal's unit cell rotated into the lab frame
    via the orientation matrix `U`.

    Left panel: the real-space cell with `hkl` plane(s) cut through it, as
    in :func:`plot_unit_cell`. Right panel: a scattering diagram -- one
    incident beam and every plane's normal and elastically diffracted-ray
    direction, all sharing a common origin and colour-coded to match their
    plane in the left panel. Both panels start at the same view angle
    (`elev`, `azim`) and stay in lock-step afterwards: on an interactive
    backend, mouse-drag-rotating either panel rotates the other to match,
    so a plane's cut in the cell and its normal/ray direction in the
    diagram can always be read together for the current orientation
    (a no-op when rendering straight to a static image via `out_path`).

    Lab frame convention (LaueTools / this project, matching
    `plot_layer_scheme`): x = incident beam direction, z = vertical up,
    y completes the right-handed frame. `v_lab = U @ v_crystal` for any
    crystal-frame vector -- the same convention used throughout
    `nrxrdct.laue.simulation` (e.g. `layer.U @ layer.crystal.Q(h, k, l)`).

    The right-hand diagram is deliberately decoupled from the cell's Å
    scale: every vector there is unit length, regardless of `camera` or
    physical distance. A future version could rescale it into true
    detector millimetres (reintroducing a to-scale detector) without
    touching the cell panel, as long as both keep using the same `U` and
    lab-frame axis convention.

    Each `hkl`'s elastically diffracted direction is found by solving the
    Laue condition `|k0·x̂ + G_lab| = k0` (see `_bragg_kf_hat`); reflections
    with no elastic solution for a beam along +x are skipped with a
    printed note. Passing a `camera` adds a projected-pixel label at each
    ray tip (via `camera.project`) without otherwise changing the diagram.

    Args:
        crystal: xrayutilities-compatible crystal object (see `plot_unit_cell`).
        U: `(3, 3)` orientation matrix rotating crystal-frame vectors into
            the lab frame.
        hkl: Miller indices of the plane(s) to draw (single tuple or list).
        camera: Optional :class:`~nrxrdct.laue.camera.Camera`; when given,
            each diffracted ray is labelled with its projected pixel.
        plane_offset, plane_colors: see `plot_unit_cell`.
        show_normal: Draw each plane's normal vector in the right panel.
        show_crystal_axes: Draw labelled `a`, `b`, `c` arrows (rotated into
            the lab frame) in the left (cell) panel.
        show_lab_axes: Draw the fixed lab-frame x/y/z triad in both panels.
        show_beam: Draw the single incident-beam arrow in the right panel.
        show_scattered_rays: Draw each plane's diffracted-ray direction
            (dashed, to distinguish it from the solid normal vectors) in
            the right panel.
        cell_color, beam_color: Line colours.
        elev, azim: 3-D view angle (degrees), shared by both panels.
            Defaults to a view looking down +y (elev=0, azim=-90), so the
            beam (x) / up (z) plane is seen face-on.
        figsize: Figure size in inches.
        out_path: Save path; `None` → do not save.

    Returns:
        `(fig, (ax_cell, ax_scatter))`

    Example:
    >>> U = euler_to_U(10, 20, 30)
    >>> plot_unit_cell_in_lab(crystal, U, hkl=[(1, 1, 1), (1, 0, 0)], camera=cam)
    """
    from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 — registers '3d' projection
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection

    U = np.asarray(U, dtype=float)
    hkls = _normalize_hkl_list(hkl)
    if any(h == 0 and k == 0 and l == 0 for h, k, l in hkls):
        raise ValueError("hkl=(0, 0, 0) does not define a plane")

    n_planes = len(hkls)
    offsets = plane_offset if isinstance(plane_offset, (list, tuple)) else [plane_offset] * n_planes
    if len(offsets) != n_planes:
        raise ValueError("plane_offset list must match the number of hkl planes")
    if plane_colors is None:
        colors = [_GRAIN_COLORS[i % len(_GRAIN_COLORS)] for i in range(n_planes)]
    elif isinstance(plane_colors, str):
        colors = [plane_colors] * n_planes
    else:
        colors = list(plane_colors)
        if len(colors) != n_planes:
            raise ValueError("plane_colors list must match the number of hkl planes")

    ai_cry = np.array([crystal.a1, crystal.a2, crystal.a3], dtype=float)
    ai = ai_cry @ U.T   # rows a1,a2,a3 rotated into the lab frame
    cart_corners = _CELL_CORNERS_FRAC @ ai
    edges = [
        (i, j)
        for i in range(8)
        for j in range(i + 1, 8)
        if np.sum(_CELL_CORNERS_FRAC[i] != _CELL_CORNERS_FRAC[j]) == 1
    ]

    fig = plt.figure(figsize=figsize)
    fig.patch.set_facecolor(BG)
    ax_cell = fig.add_subplot(1, 2, 1, projection="3d")
    ax_scat = fig.add_subplot(1, 2, 2, projection="3d")
    for ax in (ax_cell, ax_scat):
        ax.set_facecolor(BG)
        for pane in (ax.xaxis, ax.yaxis, ax.zaxis):
            pane.set_pane_color((0.03, 0.05, 0.08, 1.0))
            pane._axinfo["grid"]["color"] = (0.1, 0.12, 0.18, 0.6)
        ax.tick_params(colors="#7788aa", labelsize=7)
        ax.view_init(elev=elev, azim=azim)   # shared initial view: same orientation reads on both panels
    _sync_3d_views(fig, ax_cell, ax_scat)   # keep them synced if the user drag-rotates either one

    # ── Left panel: real-space cell + hkl plane(s) ─────────────────────────────
    for i, j in edges:
        p, q = cart_corners[i], cart_corners[j]
        ax_cell.plot(*zip(p, q), color=cell_color, lw=1.2, alpha=0.6)
    ax_cell.scatter(*cart_corners.T, color=cell_color, s=12, alpha=0.8)

    cell_legend = []
    G_labs = []   # one entry per hkl, aligned with hkls/colors
    for (h, k, l), user_offset, plane_color in zip(hkls, offsets, colors):
        G_lab = U @ crystal.Q(h, k, l)
        G_labs.append(G_lab)

        if user_offset is not None:
            offsets_to_try = [user_offset]
        else:
            f_max = max(h, 0) + max(k, 0) + max(l, 0)
            offsets_to_try = [1, -1] if f_max >= 1 else [-1, 1]

        frac_poly = []
        for m in offsets_to_try:
            frac_poly = _hkl_plane_fractional(h, k, l, m)
            if len(frac_poly) >= 3:
                break

        d_hkl = crystal.planeDistance(h, k, l)
        if len(frac_poly) < 3:
            print(f"  Warning: ({_hkl_label(h, k, l)}) plane does not intersect "
                  f"the unit cell for the offsets tried ({offsets_to_try}); pass "
                  f"plane_offset explicitly to pick a different member of "
                  f"the family.")
            continue

        cart_poly = np.array(frac_poly) @ ai
        ax_cell.add_collection3d(Poly3DCollection(
            [cart_poly], facecolor=plane_color, edgecolor=plane_color,
            linewidths=1.2, alpha=0.35,
        ))
        cell_legend.append(
            Line2D([0], [0], color=plane_color, lw=2,
                   label=f"({_hkl_label(h, k, l)})  d = {d_hkl:.4f} Å")
        )

    if show_crystal_axes:
        for vec, label in zip(ai, ("a", "b", "c")):
            ax_cell.quiver(0, 0, 0, *vec, color=cell_color, linewidth=1.0,
                            arrow_length_ratio=0.08, alpha=0.9)
            ax_cell.text(*(vec * 1.08), label, color=cell_color, fontsize=10)

    cell_span = np.ptp(cart_corners, axis=0)
    cell_scale = float(cell_span.max()) if cell_span.max() > 0 else 1.0
    if show_lab_axes:
        _draw_lab_axes_triad(
            ax_cell, origin=cart_corners.min(axis=0) - 0.6 * cell_scale,
            length=0.5 * cell_scale,
        )

    ax_cell.set_xlabel("x  (Å)", color=FG, fontsize=8, labelpad=8)
    ax_cell.set_ylabel("y  (Å)", color=FG, fontsize=8, labelpad=8)
    ax_cell.set_zlabel("z  (Å)", color=FG, fontsize=8, labelpad=8)
    title = ", ".join(f"({_hkl_label(h, k, l)})" for h, k, l in hkls) if n_planes <= 3 else f"{n_planes} planes"
    ax_cell.set_title(f"Unit cell in lab frame — {title}", color=FG, fontsize=10, pad=10)
    try:
        ax_cell.set_box_aspect(cell_span)
    except AttributeError:
        pass
    if cell_legend:
        ax_cell.legend(
            handles=cell_legend, fontsize=7, labelcolor=FG,
            facecolor="#1a1f2e", edgecolor="#333355", loc="upper left",
        )

    # ── Right panel: scattering diagram, coincident origin ─────────────────────
    # Without a camera this is a schematic unit-vector diagram (direction
    # only). With one, it switches to the camera's true millimetre scale --
    # the detector panel and the rays reaching it are drawn to real geometry.
    # This panel is decoupled from the cell's Å scale (unlike the left one),
    # so a to-scale detector fits here without swallowing the cell.
    origin2 = np.zeros(3)
    scat_legend = []
    has_camera = camera is not None
    all_pts = [origin2]   # tracks extent for axis limits when a camera is given

    # Pre-pass: find each hkl's Bragg direction and (if it truly lands on
    # the active detector) its real landing distance, *before* drawing
    # anything. The beam/normal-vector arrows are then sized as a fraction
    # of the longest real ray instead of a fixed length disconnected from
    # it -- otherwise they'd look like a tiny cluster next to a ray that
    # actually reaches all the way to the detector.
    kf_hats = []
    hit_lengths = []
    for G_lab in G_labs:
        kf_hat = _bragg_kf_hat(G_lab)
        kf_hats.append(kf_hat)
        if has_camera and kf_hat is not None and camera.project(kf_hat, source_depth_mm=0.0) is not None:
            hit = _camera_hit_point_lab(camera, kf_hat, source_lab_mm=origin2)
            hit_lengths.append(np.linalg.norm(hit))

    if has_camera:
        ray_scale = max(hit_lengths) if hit_lengths else 0.5 * camera.dd
        diagram_scale = 0.3 * ray_scale
    else:
        diagram_scale = 1.0

    if show_beam:
        beam_tail = origin2 - np.array([diagram_scale, 0.0, 0.0])
        ax_scat.quiver(*beam_tail, *(origin2 - beam_tail), color=beam_color,
                       linewidth=2.2, arrow_length_ratio=0.15)
        scat_legend.append(
            Line2D([0], [0], color=beam_color, lw=2, label="incident beam (+x)")
        )
        all_pts.append(beam_tail)

    drew_any_normal = drew_any_ray = False
    for (h, k, l), G_lab, kf_hat, plane_color in zip(hkls, G_labs, kf_hats, colors):
        if show_normal:
            n_vec = (G_lab / np.linalg.norm(G_lab)) * diagram_scale
            ax_scat.quiver(*origin2, *n_vec, color=plane_color, linewidth=1.8,
                           arrow_length_ratio=0.15)
            ax_scat.text(*(n_vec * 1.1), f"n({_hkl_label(h, k, l)})",
                         color=plane_color, fontsize=7)
            all_pts.append(n_vec)
            drew_any_normal = True

        if show_scattered_rays:
            if kf_hat is None:
                print(f"  Note: ({_hkl_label(h, k, l)}) is not excited for a "
                      f"beam along +x (G·x̂ ≥ 0) -- no elastic scattered ray "
                      f"to draw.")
                continue

            if has_camera:
                # camera.project's bounds check is the sole authority for
                # "really lands on the panel" -- a raw plane intersection
                # can land arbitrarily far away for a near-grazing ray (the
                # infinite plane extends well past the finite panel), which
                # would blow up the axis scale for the whole diagram.
                pix = camera.project(kf_hat, source_depth_mm=0.0)
                if pix is not None:
                    ray_end = _camera_hit_point_lab(camera, kf_hat, source_lab_mm=origin2)
                    linestyle = "-"
                    label = f"({_hkl_label(h, k, l)}) → px({pix[0]:.0f}, {pix[1]:.0f})"
                else:
                    ray_end, linestyle = kf_hat * diagram_scale, "--"
                    label = f"({_hkl_label(h, k, l)}) → off detector"
            else:
                ray_end, linestyle = kf_hat * diagram_scale, "-"
                label = f"({_hkl_label(h, k, l)})"

            ax_scat.quiver(*origin2, *ray_end, color=plane_color, linewidth=1.6,
                           linestyle=linestyle, arrow_length_ratio=0.1, alpha=0.9)
            ax_scat.text(*ray_end, label, color=plane_color, fontsize=7)
            all_pts.append(ray_end)
            drew_any_ray = True

    if drew_any_normal:
        scat_legend.append(
            Line2D([0], [0], color=FG, lw=1.8, linestyle="-", label="plane normal")
        )
    if drew_any_ray:
        scat_legend.append(
            Line2D([0], [0], color=FG, lw=1.6, linestyle="--", label="diffracted ray")
        )

    if has_camera:
        # True detector position/orientation/size, via the same pixel -> 3-D
        # point math used internally by Camera.project.
        def _pixel_point(xcam, ycam):
            kf_hat = camera.pixel_to_kf(np.array([xcam]), np.array([ycam]))[0]
            return _camera_hit_point_lab(camera, kf_hat, source_lab_mm=origin2)

        c_pt = _pixel_point(camera.xcen, camera.ycen)
        r_pt = _pixel_point(camera.xcen + camera.Nh / 2.0, camera.ycen)
        u_pt = _pixel_point(camera.xcen, camera.ycen - camera.Nv / 2.0)
        if c_pt is not None and r_pt is not None and u_pt is not None:
            h_vec, v_vec = r_pt - c_pt, u_pt - c_pt
            det_corners = np.array([
                c_pt + h_vec + v_vec, c_pt - h_vec + v_vec,
                c_pt - h_vec - v_vec, c_pt + h_vec - v_vec,
            ])
            ax_scat.add_collection3d(Poly3DCollection(
                [det_corners], facecolor="#dddddd", edgecolor="#dddddd",
                linewidths=1.4, alpha=0.2,
            ))
            ax_scat.text(*c_pt, f"detector\n(dd = {camera.dd:.1f} mm)",
                         color="#dddddd", fontsize=7, ha="center", va="center")
            scat_legend.append(
                Line2D([0], [0], color="#dddddd", lw=2, label="detector (true scale)")
            )
            all_pts.extend(det_corners)

    pts = np.array(all_pts)
    if show_lab_axes:
        axes_len = diagram_scale * (0.4 if has_camera else 0.5)
        tri_origin = pts.min(axis=0) - 0.3 * axes_len if has_camera else np.array([-1.3, -1.3, -1.3])
        _draw_lab_axes_triad(ax_scat, origin=tri_origin, length=axes_len)

    if has_camera:
        span = np.ptp(pts, axis=0)
        span = np.where(span > 1e-6, span, 1.0)
        center = pts.mean(axis=0)
        pad = 0.15
        for set_lim, c, s in zip(
            (ax_scat.set_xlim, ax_scat.set_ylim, ax_scat.set_zlim), center, span
        ):
            set_lim(c - s * (0.5 + pad), c + s * (0.5 + pad))
        try:
            ax_scat.set_box_aspect(span * (1 + 2 * pad))
        except AttributeError:
            pass
        ax_scat.set_xlabel("x  (mm)", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_ylabel("y  (mm)", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_zlabel("z  (mm)", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_title("Scattering diagram (true detector scale, mm)",
                          color=FG, fontsize=10, pad=10)
    else:
        lim = 1.4
        ax_scat.set_xlim(-lim, lim)
        ax_scat.set_ylim(-lim, lim)
        ax_scat.set_zlim(-lim, lim)
        try:
            ax_scat.set_box_aspect((1, 1, 1))
        except AttributeError:
            pass
        ax_scat.set_xlabel("x", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_ylabel("y", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_zlabel("z", color=FG, fontsize=8, labelpad=8)
        ax_scat.set_title("Scattering diagram (unit vectors)", color=FG, fontsize=10, pad=10)

    if scat_legend:
        ax_scat.legend(
            handles=scat_legend, fontsize=7, labelcolor=FG,
            facecolor="#1a1f2e", edgecolor="#333355", loc="upper left",
        )

    fig.tight_layout()

    if out_path:
        fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
        print(f"  Saved → {out_path}")

    _force_draw(fig)
    return fig, (ax_cell, ax_scat)

warp_image_to_tth_chi

warp_image_to_tth_chi(image, camera, *, tth_range=None, chi_range=None, n_tth: int = 600, n_chi: int = 600, interp_order: int = 1)

Remap a detector image from pixel space into an evenly-spaced 2θ / χ grid.

For each point (2θ, χ) in the output grid the corresponding scattered unit vector is computed, projected back onto the detector via :meth:~nrxrdct.laue.Camera.kf_to_pixel, and the source image is sampled by bilinear interpolation. Output pixels that map outside the detector active area are set to NaN.

Parameters:
  • image ((array - like, shape(Nv, Nh))) –

    Detector image in pixel space (e.g. from :meth:~Camera.render or a real experimental frame loaded as a numpy array).

  • camera (Camera) –

    Detector geometry used for the forward/inverse projections.

  • tth_range ((float, float), default: None ) –

    2θ range in degrees (tth_min, tth_max). Defaults to the range covered by the four detector corners.

  • chi_range ((float, float), default: None ) –

    χ range in degrees (chi_min, chi_max). Defaults to the range covered by the four detector corners.

  • n_tth, n_chi (int) –

    Number of output pixels along the 2θ and χ axes.

  • interp_order (int, default: 1 ) –

    Interpolation order passed to :func:scipy.ndimage.map_coordinates (0 = nearest, 1 = bilinear (default), 3 = cubic).

Returns:
  • warped( (ndarray, shape(n_chi, n_tth)) ) –

    Remapped image. NaN where the output pixel falls outside the detector.

  • tth_ax( (ndarray, shape(n_tth)) ) –

    2θ values of the output columns (degrees).

  • chi_ax( (ndarray, shape(n_chi)) ) –

    χ values of the output rows (degrees).

Source code in src/nrxrdct/laue/laue_plotting.py
def warp_image_to_tth_chi(
    image,
    camera,
    *,
    tth_range=None,
    chi_range=None,
    n_tth: int = 600,
    n_chi: int = 600,
    interp_order: int = 1,
):
    """
    Remap a detector image from pixel space into an evenly-spaced 2θ / χ grid.

    For each point (2θ, χ) in the output grid the corresponding scattered
    unit vector is computed, projected back onto the detector via
    :meth:`~nrxrdct.laue.Camera.kf_to_pixel`, and the source image is
    sampled by bilinear interpolation.  Output pixels that map outside the
    detector active area are set to `NaN`.

    Args:
        image (array-like, shape (Nv, Nh)): Detector image in pixel space (e.g. from :meth:`~Camera.render` or
            a real experimental frame loaded as a numpy array).
        camera (Camera): Detector geometry used for the forward/inverse projections.
        tth_range ((float, float), optional): 2θ range in degrees `(tth_min, tth_max)`.  Defaults to the range
            covered by the four detector corners.
        chi_range ((float, float), optional): χ range in degrees `(chi_min, chi_max)`.  Defaults to the range
            covered by the four detector corners.
        n_tth, n_chi (int): Number of output pixels along the 2θ and χ axes.
        interp_order (int): Interpolation order passed to :func:`scipy.ndimage.map_coordinates`
            (0 = nearest, 1 = bilinear (default), 3 = cubic).

    Returns:
        warped (ndarray, shape (n_chi, n_tth)): Remapped image.  NaN where the output pixel falls outside the detector.
        tth_ax (ndarray, shape (n_tth,)): 2θ values of the output columns (degrees).
        chi_ax (ndarray, shape (n_chi,)): χ values of the output rows (degrees).
"""
    from scipy.ndimage import map_coordinates

    image = np.asarray(image, dtype=np.float64)

    # ── Auto-range from detector corners ─────────────────────────────────────
    corner_px = np.array([
        [0,              0],
        [camera.Nh - 1,  0],
        [0,              camera.Nv - 1],
        [camera.Nh - 1,  camera.Nv - 1],
        [camera.xcen,    camera.ycen],
    ])
    ufs = camera.pixel_to_kf(corner_px[:, 0], corner_px[:, 1])
    tths_c = np.degrees(np.arccos(np.clip(ufs[:, 0], -1.0, 1.0)))
    chis_c = np.degrees(np.arctan2(ufs[:, 1], ufs[:, 2] + 1e-17))

    if tth_range is None:
        tth_range = (float(tths_c.min()), float(tths_c.max()))
    if chi_range is None:
        chi_range = (float(chis_c.min()), float(chis_c.max()))

    # ── Output grid ───────────────────────────────────────────────────────────
    tth_ax = np.linspace(tth_range[0], tth_range[1], n_tth)
    chi_ax = np.linspace(chi_range[0], chi_range[1], n_chi)

    # meshgrid: rows = chi, cols = tth  →  shape (n_chi, n_tth)
    TTH, CHI = np.meshgrid(tth_ax, chi_ax)
    tth_r = np.radians(TTH.ravel())
    chi_r = np.radians(CHI.ravel())

    # kf unit vectors in LT frame (x // beam):
    #   kf = [cos 2θ,  sin 2θ · sin χ,  sin 2θ · cos χ]
    sin_tth = np.sin(tth_r)
    kf_arr = np.column_stack([
        np.cos(tth_r),
        sin_tth * np.sin(chi_r),
        sin_tth * np.cos(chi_r),
    ])

    # ── Back-project to detector pixels ──────────────────────────────────────
    xcam, ycam = camera.kf_to_pixel(kf_arr)

    valid = (
        np.isfinite(xcam) & np.isfinite(ycam)
        & (xcam >= 0) & (xcam < camera.Nh)
        & (ycam >= 0) & (ycam < camera.Nv)
    )

    # map_coordinates expects [row, col] = [ycam, xcam]
    coords = np.array([
        np.where(valid, ycam, 0.0),
        np.where(valid, xcam, 0.0),
    ])

    warped_flat = map_coordinates(
        image, coords, order=interp_order, mode="constant", cval=0.0
    )
    warped_flat[~valid] = np.nan

    return warped_flat.reshape(n_chi, n_tth), tth_ax, chi_ax

warp_rod_to_qspace

warp_rod_to_qspace(stack, hkl, image, layer=None, camera=None, *, ki_hat=None, q_par_range=None, q_perp_range=None, n_par: int = 300, n_perp: int = 300, half_size_px: float = 40.0, perp_probe_px: float = 5.0, interp_order: int = 1)

Remap a detector image from pixel space into a (q_parallel, q_perp) grid centred on one reflection's rod — the reciprocal-space analogue of :func:warp_image_to_tth_chi, but anchored to :func:~nrxrdct.laue.simulation.rod_tangency's own rod geometry instead of instrument angles.

For each output grid point Q = G0 + q_par·n̂ + q_perp·ê⊥, the exact elastic condition is solved (same formula rod_tangency/ qspace_around_spot use for the satellite comb — energy and pixel co-vary, not held fixed) to get the (E, pixel) that would actually produce that Q, and image is bilinear-sampled there. So every output point corresponds to a real, physically achievable photon in the white beam, not a local-linear approximation.

n̂ is rod_tangency's own rod direction (the layer's stacking-axis reciprocal vector) — this is q_parallel, same physical quantity already shown as the streak direction in plot_rod_tangency. ê⊥ ("q_perp") is a Q-space unit vector, orthogonalised against n̂, chosen so that a small step along it backprojects (at fixed E0) onto rod_tangency's own perp_dir_px — i.e. this warp's two axes line up with the streak/perpendicular lines already drawn by plot_rod_tangency, rather than introducing a second, unrelated convention. (Q-space orthogonal to n̂ is technically a 2-D subspace; this pins down the one in-plane direction that matches the existing display convention.)

Parameters:
  • stack, hkl, camera, ki_hat –

    Forwarded to :func:~nrxrdct.laue.simulation.rod_tangency.

  • image ((ndarray, shape(Nv, Nh))) –

    Detector frame (measured or simulated) to warp.

  • layer –

    Single layer/label/None — see rod_tangency (None defaults to stack.layers[0]).

  • q_par_range, q_perp_range ((float, float)) –

    Output range in Å⁻¹, (min, max), centred on G0. Default (None): ±half_size_px / dpix_dalong for q_par, and the analogous ±half_size_px / dpix_dperp for q_perp (dpix_dperp found the same way rod_tangency finds dpix_dalong — a two-point finite difference — but stepping along ê⊥ instead of n̂) — i.e. by default both axes cover roughly the same pixel extent around pix0, just expressed in each direction's own physical Q scale.

  • n_par, n_perp (int) –

    Output grid size along each axis.

  • half_size_px (float, default: 40.0 ) –

    Half-window (pixels) used to auto-derive q_par_range/q_perp_range when not given explicitly. Unused if both ranges are given.

  • perp_probe_px (float, default: 5.0 ) –

    Pixel step used to bootstrap ê⊥ (see above) — small enough to stay a good local approximation of perp_dir_px, large enough to avoid floating-point noise.

  • interp_order (int, default: 1 ) –

    Interpolation order passed to :func:scipy.ndimage.map_coordinates (0=nearest, 1=bilinear (default), 3=cubic).

Returns:
  • warped( (ndarray, shape(n_perp, n_par)) ) –

    Remapped image. NaN where the output point has no elastic solution (Q·k̂i ≥ 0) or falls outside the detector.

  • q_par_ax( (ndarray, shape(n_par)) ) –

    q_parallel values (Å⁻¹) of the output columns.

  • q_perp_ax( (ndarray, shape(n_perp)) ) –

    q_perp values (Å⁻¹) of the output rows.

  • info( dict ) –

    hkl, layer, E0, pix0, G0 (3,, the Q-space point pixel/E were computed from), n_hat (3,), perp_hat (3,, the ê⊥ used), dpix_dalong, dpix_dperp — for axis labelling/titling, or projecting other Q-space points into this same (q_par, q_perp) frame via ((Q - G0) @ n_hat, (Q - G0) @ perp_hat).

Source code in src/nrxrdct/laue/laue_plotting.py
def warp_rod_to_qspace(
    stack,
    hkl,
    image,
    layer=None,
    camera=None,
    *,
    ki_hat=None,
    q_par_range=None,
    q_perp_range=None,
    n_par: int = 300,
    n_perp: int = 300,
    half_size_px: float = 40.0,
    perp_probe_px: float = 5.0,
    interp_order: int = 1,
):
    """
    Remap a detector image from pixel space into a (q_parallel, q_perp)
    grid centred on one reflection's rod — the reciprocal-space analogue of
    :func:`warp_image_to_tth_chi`, but anchored to
    :func:`~nrxrdct.laue.simulation.rod_tangency`'s own rod geometry
    instead of instrument angles.

    For each output grid point `Q = G0 + q_par·n̂ + q_perp·ê⊥`, the *exact*
    elastic condition is solved (same formula `rod_tangency`/
    `qspace_around_spot` use for the satellite comb — energy and pixel
    co-vary, not held fixed) to get the `(E, pixel)` that would actually
    produce that `Q`, and `image` is bilinear-sampled there. So every
    output point corresponds to a real, physically achievable photon in
    the white beam, not a local-linear approximation.

    `n̂` is `rod_tangency`'s own rod direction (the layer's stacking-axis
    reciprocal vector) — this *is* `q_parallel`, same physical quantity
    already shown as the streak direction in `plot_rod_tangency`. `ê⊥`
    ("q_perp") is a Q-space unit vector, orthogonalised against `n̂`, chosen
    so that a small step along it backprojects (at fixed `E0`) onto
    `rod_tangency`'s own `perp_dir_px` — i.e. this warp's two axes line up
    with the streak/perpendicular lines already drawn by `plot_rod_tangency`,
    rather than introducing a second, unrelated convention. (Q-space
    orthogonal to `n̂` is technically a 2-D subspace; this pins down the one
    in-plane direction that matches the existing display convention.)

    Args:
        stack, hkl, camera, ki_hat: Forwarded to
            :func:`~nrxrdct.laue.simulation.rod_tangency`.
        image (ndarray, shape (Nv, Nh)): Detector frame (measured or
            simulated) to warp.
        layer: Single layer/label/`None` — see `rod_tangency` (`None`
            defaults to `stack.layers[0]`).
        q_par_range, q_perp_range ((float, float), optional): Output range
            in Å⁻¹, `(min, max)`, centred on `G0`. Default (`None`):
            `±half_size_px / dpix_dalong` for `q_par`, and the analogous
            `±half_size_px / dpix_dperp` for `q_perp` (`dpix_dperp` found
            the same way `rod_tangency` finds `dpix_dalong` — a two-point
            finite difference — but stepping along `ê⊥` instead of `n̂`) —
            i.e. by default both axes cover roughly the same *pixel*
            extent around `pix0`, just expressed in each direction's own
            physical Q scale.
        n_par, n_perp (int): Output grid size along each axis.
        half_size_px (float): Half-window (pixels) used to auto-derive
            `q_par_range`/`q_perp_range` when not given explicitly. Unused
            if both ranges are given.
        perp_probe_px (float): Pixel step used to bootstrap `ê⊥` (see
            above) — small enough to stay a good local approximation of
            `perp_dir_px`, large enough to avoid floating-point noise.
        interp_order (int): Interpolation order passed to
            :func:`scipy.ndimage.map_coordinates` (0=nearest, 1=bilinear
            (default), 3=cubic).

    Returns:
        warped (ndarray, shape (n_perp, n_par)): Remapped image. `NaN`
            where the output point has no elastic solution (`Q·k̂i ≥ 0`)
            or falls outside the detector.
        q_par_ax (ndarray, shape (n_par,)): `q_parallel` values (Å⁻¹) of
            the output columns.
        q_perp_ax (ndarray, shape (n_perp,)): `q_perp` values (Å⁻¹) of the
            output rows.
        info (dict): `hkl`, `layer`, `E0`, `pix0`, `G0` (3,, the Q-space
            point pixel/E were computed from), `n_hat` (3,), `perp_hat`
            (3,, the `ê⊥` used), `dpix_dalong`, `dpix_dperp` — for axis
            labelling/titling, or projecting other Q-space points into
            this same `(q_par, q_perp)` frame via
            `((Q - G0) @ n_hat, (Q - G0) @ perp_hat)`.
    """
    from scipy.ndimage import map_coordinates
    from .simulation import rod_tangency, HC, KI_HAT

    if camera is None:
        raise ValueError("camera is required")

    info0 = rod_tangency(stack, hkl, layer=layer, camera=camera, ki_hat=ki_hat)
    if not info0["on_detector"]:
        raise ValueError(f"hkl={info0['hkl']} is off-detector for layer {info0['layer']!r}")

    if layer is None:
        if not stack.layers:
            raise ValueError("stack has no repeating/film layers; pass `layer` explicitly")
        ly = stack.layers[0]
    elif isinstance(layer, str):
        ly = next((l for l in stack.all_layers if l.label == layer), None)
        if ly is None:
            available = [l.label for l in stack.all_layers]
            raise ValueError(f"no layer labeled {layer!r}; available labels: {available}")
    else:
        ly = layer

    h, k, l = info0["hkl"]
    G0 = ly.U @ ly.crystal.Q(h, k, l)
    n_hat = np.asarray(ly.n_hat, dtype=float)
    n_hat = n_hat / np.linalg.norm(n_hat)

    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki = ki / np.linalg.norm(ki)

    def _solve(Q):
        """Exact elastic condition at Q -- same formula as rod_tangency/qspace_around_spot."""
        kdG = float(Q @ ki)
        Gm2 = float(Q @ Q)
        if kdG >= 0:
            return None
        lam = -4.0 * np.pi * kdG / Gm2
        E = HC / lam
        km = 2.0 * np.pi / lam
        kf = ki * km + Q
        kf /= np.linalg.norm(kf)
        pix, on_det = camera.project_batch(kf[None, :])
        return float(E), pix[0].copy(), bool(on_det[0])

    # ── ê⊥: the Q-space direction that, at fixed E0, backprojects onto
    # rod_tangency's own perp_dir_px — ties this warp's axes to the same
    # streak/perpendicular convention plot_rod_tangency already draws.
    px0, py0 = info0["pix0"]
    perp_px = info0["perp_dir_px"]
    kf_probe_hat = camera.pixel_to_kf(
        np.array([px0 + perp_probe_px * perp_px[0]]),
        np.array([py0 + perp_probe_px * perp_px[1]]),
    )[0]
    lam0 = HC / info0["E0"]
    k0 = 2.0 * np.pi / lam0
    Q_probe = k0 * (kf_probe_hat - ki)
    dQ_perp = Q_probe - G0
    dQ_perp -= np.dot(dQ_perp, n_hat) * n_hat  # orthogonalise against n_hat
    perp_hat = dQ_perp / np.linalg.norm(dQ_perp)

    # ── dpix_dperp, the transverse analogue of rod_tangency's dpix_dalong,
    # for auto-ranging q_perp the same way q_par is auto-ranged.
    d_step = 1e-4
    res_plus = _solve(G0 + d_step * perp_hat)
    res_minus = _solve(G0 - d_step * perp_hat)
    if res_plus is not None and res_minus is not None:
        dpix_dperp = float(np.linalg.norm(res_plus[1] - res_minus[1]) / (2.0 * d_step))
    else:
        raise ValueError("could not evaluate d(pixel)/d(q_perp) near this reflection")

    if q_par_range is None:
        q_par_half = half_size_px / info0["dpix_dalong"]
        q_par_range = (-q_par_half, q_par_half)
    if q_perp_range is None:
        q_perp_half = half_size_px / dpix_dperp
        q_perp_range = (-q_perp_half, q_perp_half)

    q_par_ax = np.linspace(q_par_range[0], q_par_range[1], n_par)
    q_perp_ax = np.linspace(q_perp_range[0], q_perp_range[1], n_perp)

    # ── Output grid, in Q-space ──────────────────────────────────────────────
    QPAR, QPERP = np.meshgrid(q_par_ax, q_perp_ax)  # shape (n_perp, n_par)
    Q_flat = (
        G0[None, :]
        + QPAR.ravel()[:, None] * n_hat[None, :]
        + QPERP.ravel()[:, None] * perp_hat[None, :]
    )

    # ── Vectorised exact elastic solve (same formula as `_solve` above) ──────
    kdG = Q_flat @ ki
    Gm2 = np.sum(Q_flat**2, axis=1)
    elastic_ok = kdG < 0
    Gm2_safe = np.where(elastic_ok, Gm2, 1.0)
    kdG_safe = np.where(elastic_ok, kdG, -1.0)
    lam = -4.0 * np.pi * kdG_safe / Gm2_safe
    km = 2.0 * np.pi / lam
    kf = ki[None, :] * km[:, None] + Q_flat
    kf_norm = np.linalg.norm(kf, axis=1)
    kf_norm_safe = np.where(kf_norm > 1e-12, kf_norm, 1.0)
    kf_hat = kf / kf_norm_safe[:, None]

    pix, on_det = camera.project_batch(kf_hat)
    valid = elastic_ok & on_det & np.isfinite(pix[:, 0]) & np.isfinite(pix[:, 1])

    coords = np.array([
        np.where(valid, pix[:, 1], 0.0),  # row = ycam
        np.where(valid, pix[:, 0], 0.0),  # col = xcam
    ])
    warped_flat = map_coordinates(
        np.asarray(image, dtype=np.float64), coords, order=interp_order, mode="constant", cval=0.0
    )
    warped_flat = np.where(valid, warped_flat, np.nan)

    info = {
        "hkl": info0["hkl"],
        "layer": info0["layer"],
        "E0": info0["E0"],
        "pix0": info0["pix0"],
        "G0": G0,
        "n_hat": n_hat,
        "perp_hat": perp_hat,
        "dpix_dalong": info0["dpix_dalong"],
        "dpix_dperp": dpix_dperp,
    }

    return warped_flat.reshape(n_perp, n_par), q_par_ax, q_perp_ax, info