simulation

nrxrdct.laue.simulation

White-Beam Synchrotron Laue Diffraction – Reflection Geometry

Simulates single-crystal Laue diffraction with a synchrotron white beam in reflection geometry, with a full pixelated camera model.

System : equiatomic AlCoCrFeNi HEA – BCC (Im-3m) + B2 (Pm-3m)

Physics

Laue condition (Ewald construction):

\[ \lambda_{hkl} = -\frac{4\pi\,(\hat{k}_i \cdot \mathbf{G}_{hkl})}{|\mathbf{G}_{hkl}|^2} \]

Spot intensity:

\[ I(hkl) = |F(\mathbf{G}, E)|^2 \cdot LP(2\theta) \cdot S(E) \]

where

  • \(F(\mathbf{G}, E)\) — structure factor via xrayutilities (Cromer–Mann \(f^0\) + Henke \(f'(E)\), \(f''(E)\) anomalous corrections)
  • \(LP(2\theta, E)\) — Lorentz–polarisation factor for Laue (polychromatic, stationary crystal, unpolarised beam):
\[ LP = \frac{1 + \cos^2 2\theta}{2} \cdot \frac{\lambda^2}{\sin 2\theta}, \qquad \lambda = hc/E \]
  • \(S(E)\) — synchrotron spectrum (bending magnet, wiggler, or undulator); no bremsstrahlung

Synchrotron spectra

Bending magnet / wiggler (on-axis, Kim 1989):

\[ S(E) \propto \left(\frac{E}{E_c}\right)^2 K_{2/3}^2\!\left(\frac{E}{2E_c}\right) \]

Peak at \(E \approx 0.83\,E_c\). Wiggler: flux \(\times 2N_\text{poles}\).

Undulator (planar, odd harmonics):

\[ S(E) = \sum_n \frac{1}{n}\exp\!\left[-\tfrac{1}{2} \left(\frac{E - nE_1}{\sigma_n}\right)^2\right] \]

Camera model

The detector is a flat pixelated area detector (e.g. Eiger, Pilatus, MAR, Perkin-Elmer, …) described by:

  • PIXEL_SIZE_MM — pixel pitch (mm)
  • N_PIX_H, N_PIX_V — number of pixels (horizontal, vertical)
  • DET_DIST_MM — sample-to-detector-centre distance (mm)
  • TTH_CENTER_DEG — \(2\theta\) angle at the detector centre (deg); can be any angle, not restricted to 90°
  • NU_DEG — out-of-plane (elevation) angle of detector centre
  • CHI_DEG — in-plane rotation of detector about its own normal

For each diffracted beam direction \(\hat{k}_f\) the code:

  1. Intersects the ray with the detector plane (exact geometry).
  2. Converts the hit position to (col, row) pixel coordinates.
  3. Renders a synthetic image with Gaussian spot profiles whose width is set by SPOT_SIGMA_PIX.

The direct-beam footprint on the detector is also computed (if it would hit) so you can check the geometry is sensible.

Orientation

Full orientation via Bunge ZXZ Euler angles \((\phi_1, \Phi, \phi_2)\). A Bragg-energy reference table is printed at runtime.

U_from_matstarlab

U_from_matstarlab(matstarlab, crystal)

Convert a LaueTools matstarlab (LT2/OR frame, no 2π) into an effective orientation matrix for simulate_laue (LT frame, with 2π from xrayutilities).

This function returns the full deformation gradient F = U @ P, which combines the pure crystal rotation U with the right-stretch tensor P (lattice distortion due to strain). Passing F to simulate_laue gives spot positions that account for both the orientation and any elastic strain in the grain.

To separate rotation from strain use :func:decompose_matstarlab.

LaueTools defines (LT2 frame, no 2π)::

G_LT2 = matstarlab @ [h, k, l]

This function applies two corrections:

  1. Frame change LT2→LT: x_LT = y_LT2, y_LT = −x_LT2, z_LT = z_LT2
  2. 2π rescaling: LaueTools uses |G| = 1/d; xrayutilities uses |G| = 2π/d.

matstarlab : array-like, shape (3, 3) LaueTools grain matrix in LT2/OR frame (columns = a, b, c in lab, in Å⁻¹ without* the 2π factor). crystal : xu.materials.Crystal Reference (unstrained) phase — same object passed to simulate_laue.

F : ndarray, shape (3, 3) Deformation gradient in LT frame. Pass directly to simulate_laue as the U argument to include strain in the spot geometry. For a strain-free grain F is a pure rotation matrix.

Source code in src/nrxrdct/laue/simulation.py
def U_from_matstarlab(matstarlab, crystal):
    """
    Convert a LaueTools `matstarlab` (LT2/OR frame, no 2π) into an effective
    orientation matrix for `simulate_laue` (LT frame, with 2π from xrayutilities).

    This function returns the **full deformation gradient** F = U @ P, which
    combines the pure crystal rotation U with the right-stretch tensor P
    (lattice distortion due to strain).  Passing F to `simulate_laue` gives
    spot positions that account for both the orientation **and** any elastic
    strain in the grain.

    To separate rotation from strain use :func:`decompose_matstarlab`.

    LaueTools defines (LT2 frame, no 2π)::

        G_LT2 = matstarlab @ [h, k, l]

    This function applies two corrections:

    1. **Frame change LT2→LT**: `x_LT = y_LT2`, `y_LT = −x_LT2`, `z_LT = z_LT2`
    2. **2π rescaling**: LaueTools uses |G| = 1/d; xrayutilities uses |G| = 2π/d.

    Args:
    matstarlab : array-like, shape (3, 3)
        LaueTools grain matrix in LT2/OR frame (columns = a*, b*, c* in lab,
        in Å⁻¹ **without** the 2π factor).
    crystal : xu.materials.Crystal
        Reference (unstrained) phase — same object passed to `simulate_laue`.

    Returns:
    F : ndarray, shape (3, 3)
        Deformation gradient in LT frame.  Pass directly to `simulate_laue`
        as the `U` argument to include strain in the spot geometry.
        For a strain-free grain F is a pure rotation matrix.
"""
    return _matstarlab_to_F(matstarlab, crystal)

beam_divergence_ellipses

beam_divergence_ellipses(spots: list, camera, sigma_h_mrad: float = 0.0, sigma_v_mrad: float = 0.0, ki_hat=None, sigma_beam_h_nm: float = 0.0, sigma_beam_v_nm: float = 0.0, n_hat_sample=None) -> list

Add per-spot detector broadening from beam angular divergence and geometric footprint elongation due to a tilted sample surface.

Two independent broadening mechanisms are modelled and combined:

  1. Angular divergence — the incident beam has an angular spread (σ_h, σ_v). Each k̂_i direction satisfying the Laue condition maps the G-vector to a slightly different pixel. The pixel-space Jacobian J_div = ∂pix/∂(δ_h, δ_v) is estimated by central differences on the perturbed beam direction.

  2. Geometric footprint — the beam illuminates a finite area on the sample surface. When the surface is tilted relative to the beam (as in reflection geometry), the footprint is elongated by 1/sin(α_inc). Each illuminated point scatters from a displaced origin, shifting the pixel hit via geometric parallax. The sample-plane Jacobian is computed analytically:

    δr_sample = δr_beam − k̂_i (δr_beam · n̂_sample) / (k̂_i · n̂_sample)

and the resulting pixel shift is evaluated by central differences on the camera ray-intersection formula for a displaced source.

The two pixel covariances add:

C_total = C_divergence + C_footprint

A second Jacobian J_pa = ∂(2θ, χ)/∂pix maps the combined result into angle space. Both representations are stored in each spot dict.

New keys written to every spot cov_px (2, 2) ndarray total pixel covariance (px²) sigma_major_px float semi-major axis, 1σ (px) sigma_minor_px float semi-minor axis, 1σ (px) ellipse_angle_px_degfloat major-axis angle, CCW from +x (°) cov_ang (2, 2) ndarray angle covariance in (2θ, χ) (deg²) sigma_major_ang_deg float semi-major axis, 1σ (°) sigma_minor_ang_deg float semi-minor axis, 1σ (°) ellipse_angle_ang_degfloat major-axis angle in (2θ, χ) space (°) sigma_tth_deg float marginal 1σ along 2θ (°) sigma_chi_deg float marginal 1σ along χ (°)

Args: spots : list of dicts from :func:simulate_laue_stack etc. camera : Camera sigma_h_mrad : float horizontal beam divergence 1σ (mrad). Typical BM32/ESRF: 2–3 mrad. sigma_v_mrad : float vertical beam divergence 1σ (mrad). Typical BM32/ESRF: 0.2–0.5 mrad. ki_hat : array-like (3,), optional Incident beam direction (LT frame, x // beam). Default: [1, 0, 0]. sigma_beam_h_nm : float horizontal (in-plane) beam size 1σ at the sample (nm). Footprint broadening requires n_hat_sample. sigma_beam_v_nm : float vertical beam size 1σ at the sample (nm). n_hat_sample : array-like (3,), optional Unit normal to the sample surface in the LT frame. Required to activate footprint broadening. For a sample with its surface normal pointing toward the detector ( typical reflection geometry with ~45° sample tilt) use e.g. [0, 0, 1] for a horizontal flat sample or the crystal normal obtained from the orientation matrix.

Returns: spots (modified in-place and returned for chaining)

Note: The divergence Jacobian is evaluated with a 0.5 mrad central-difference step; the footprint Jacobian with a 10 µm step. Spots whose G vector does not satisfy the Laue condition after perturbation are assigned zero broadening for that direction.

Source code in src/nrxrdct/laue/simulation.py
def beam_divergence_ellipses(
    spots: list,
    camera,
    sigma_h_mrad: float = 0.0,
    sigma_v_mrad: float = 0.0,
    ki_hat=None,
    sigma_beam_h_nm: float = 0.0,
    sigma_beam_v_nm: float = 0.0,
    n_hat_sample=None,
) -> list:
    """
    Add per-spot detector broadening from beam angular divergence and geometric
    footprint elongation due to a tilted sample surface.

    Two independent broadening mechanisms are modelled and combined:

    1. **Angular divergence** — the incident beam has an angular spread
       (σ_h, σ_v).  Each k̂_i direction satisfying the Laue condition maps
       the G-vector to a slightly different pixel.  The pixel-space Jacobian
       J_div = ∂pix/∂(δ_h, δ_v) is estimated by central differences on the
       perturbed beam direction.

    2. **Geometric footprint** — the beam illuminates a finite area on the
       sample surface.  When the surface is tilted relative to the beam (as
       in reflection geometry), the footprint is elongated by 1/sin(α_inc).
       Each illuminated point scatters from a displaced origin, shifting the
       pixel hit via geometric parallax.  The sample-plane Jacobian is
       computed analytically:

           δr_sample = δr_beam − k̂_i (δr_beam · n̂_sample) / (k̂_i · n̂_sample)

       and the resulting pixel shift is evaluated by central differences on
       the camera ray-intersection formula for a displaced source.

    The two pixel covariances add:

        C_total = C_divergence + C_footprint

    A second Jacobian  J_pa = ∂(2θ, χ)/∂pix  maps the combined result into
    angle space.  Both representations are stored in each spot dict.

    **New keys written to every spot**
    `cov_px`              (2, 2) ndarray  total pixel covariance (px²)
    `sigma_major_px`      float           semi-major axis, 1σ (px)
    `sigma_minor_px`      float           semi-minor axis, 1σ (px)
    `ellipse_angle_px_deg`float           major-axis angle, CCW from +x (°)
    `cov_ang`             (2, 2) ndarray  angle covariance in (2θ, χ) (deg²)
    `sigma_major_ang_deg` float           semi-major axis, 1σ (°)
    `sigma_minor_ang_deg` float           semi-minor axis, 1σ (°)
    `ellipse_angle_ang_deg`float          major-axis angle in (2θ, χ) space (°)
    `sigma_tth_deg`       float           marginal 1σ along 2θ (°)
    `sigma_chi_deg`       float           marginal 1σ along χ  (°)

    Args:
    spots         : list of dicts from :func:`simulate_laue_stack` etc.
    camera        : Camera
    sigma_h_mrad  : float  horizontal beam divergence 1σ (mrad).
                    Typical BM32/ESRF: 2–3 mrad.
    sigma_v_mrad  : float  vertical beam divergence 1σ (mrad).
                    Typical BM32/ESRF: 0.2–0.5 mrad.
    ki_hat        : array-like (3,), optional
                    Incident beam direction (LT frame, x // beam).
                    Default: `[1, 0, 0]`.
    sigma_beam_h_nm : float  horizontal (in-plane) beam size 1σ at the sample
                    (nm).  Footprint broadening requires `n_hat_sample`.
    sigma_beam_v_nm : float  vertical beam size 1σ at the sample (nm).
    n_hat_sample  : array-like (3,), optional
                    Unit normal to the sample surface in the LT frame.
                    Required to activate footprint broadening.  For a sample
                    with its surface normal pointing toward the detector (
                    typical reflection geometry with ~45° sample tilt) use
                    e.g. `[0, 0, 1]` for a horizontal flat sample or the
                    crystal normal obtained from the orientation matrix.

    Returns:
    spots  (modified in-place and returned for chaining)

    Note:
    The divergence Jacobian is evaluated with a 0.5 mrad central-difference
    step; the footprint Jacobian with a 10 µm step.  Spots whose G vector
    does not satisfy the Laue condition after perturbation are assigned zero
    broadening for that direction.
"""
    _zero2 = np.zeros((2, 2))
    _zero_keys = {
        "cov_px": _zero2, "sigma_major_px": 0.0, "sigma_minor_px": 0.0,
        "ellipse_angle_px_deg": 0.0,
        "cov_ang": _zero2, "sigma_major_ang_deg": 0.0, "sigma_minor_ang_deg": 0.0,
        "ellipse_angle_ang_deg": 0.0, "sigma_tth_deg": 0.0, "sigma_chi_deg": 0.0,
    }

    _no_divergence = sigma_h_mrad <= 0.0 and sigma_v_mrad <= 0.0
    _no_footprint = (
        (sigma_beam_h_nm <= 0.0 and sigma_beam_v_nm <= 0.0)
        or n_hat_sample is None
    )
    if _no_divergence and _no_footprint:
        for s in spots:
            s.update(_zero_keys)
        return spots

    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki /= np.linalg.norm(ki)

    # Horizontal and vertical directions perpendicular to ki.
    # For a beam along x:  ê_h ≈ ŷ (horizontal),  ê_v ≈ ẑ (vertical).
    z_hat = np.array([0.0, 0.0, 1.0])
    cross_zk = np.cross(z_hat, ki)
    if np.linalg.norm(cross_zk) > 1e-6:
        e_h = cross_zk / np.linalg.norm(cross_zk)
    else:
        e_h = np.array([0.0, 1.0, 0.0])
    e_v = np.cross(ki, e_h)
    e_v /= np.linalg.norm(e_v)

    sigma_h = sigma_h_mrad * 1e-3  # rad
    sigma_v = sigma_v_mrad * 1e-3  # rad
    _H = 5e-4  # 0.5 mrad central-difference step (rad)

    # ── Footprint: directions in the sample plane per mm of beam offset ────────
    # A point at δr_beam = δh·ê_h + δv·ê_v in the beam cross-section hits the
    # sample at δr_sample = δr_beam − k̂_i·(δr_beam·n̂)/(k̂_i·n̂), giving a
    # 3-vector footprint direction per mm of beam displacement.
    do_footprint = not _no_footprint
    if do_footprint:
        n_s = np.asarray(n_hat_sample, dtype=float)
        n_s = n_s / np.linalg.norm(n_s)
        ki_dot_n = float(np.dot(ki, n_s))
        if abs(ki_dot_n) < 1e-3:  # beam nearly parallel to surface
            do_footprint = False
        else:
            drs_dh = e_h - ki * float(np.dot(e_h, n_s)) / ki_dot_n  # (mm/mm)
            drs_dv = e_v - ki * float(np.dot(e_v, n_s)) / ki_dot_n
            _S = 0.01  # 10 µm central-difference step (mm)

    def _perturbed_pix(G, e, delta):
        ki_p = ki + delta * e
        ki_p /= np.linalg.norm(ki_p)
        Gm2 = float(np.dot(G, G))
        kdG = float(np.dot(ki_p, G))
        if kdG >= 0:
            return None
        lam = -4.0 * np.pi * kdG / Gm2
        kf = (2.0 * np.pi / lam) * ki_p + G
        return camera.project(kf / np.linalg.norm(kf))

    def _project_from_source(kf_hat_lt, src_lt):
        """Project kf_hat onto the detector for a source displaced from origin."""
        # LT → LT2: x_LT2 = -y_LT,  y_LT2 = x_LT,  z_LT2 = z_LT
        kf_lt2 = np.array([-kf_hat_lt[1], kf_hat_lt[0], kf_hat_lt[2]])
        src_lt2 = np.array([-src_lt[1], src_lt[0], src_lt[2]])
        scal = float(np.dot(kf_lt2, camera.normal))
        if scal < 1e-8:
            return None
        dd_eff = camera.dd - float(np.dot(src_lt2, camera.normal))
        IM = src_lt2 + kf_lt2 * (dd_eff / scal)
        OM = IM - camera.IOlab
        xca0 = float(OM[0])
        yca0 = (
            float(OM[1]) / camera._sinbeta
            if abs(camera._sinbeta) > 1e-8
            else -float(OM[2]) / camera._cosbeta
        )
        xcam1 = camera._cosgam * xca0 + camera._singam * yca0
        ycam1 = -camera._singam * xca0 + camera._cosgam * yca0
        return np.array([
            camera.xcen + xcam1 / camera.pixel_mm,
            camera.ycen + ycam1 / camera.pixel_mm,
        ])

    def _pix_to_angles(x, y):
        ufs = camera.pixel_to_kf(np.array([x]), np.array([y]))
        tth = float(np.degrees(np.arccos(np.clip(ufs[0, 0], -1.0, 1.0))))
        chi = float(np.degrees(np.arctan2(float(ufs[0, 1]), float(ufs[0, 2]) + 1e-17)))
        return tth, chi

    def _ellipse_params(cov):
        """Return (sigma_major, sigma_minor, angle_deg) from a 2×2 covariance."""
        try:
            eigvals, eigvecs = np.linalg.eigh(cov)
            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]))
            v = eigvecs[:, idx]
            ang = float(np.degrees(np.arctan2(v[1], v[0])))
            return sig_maj, sig_min, ang
        except Exception:
            return 0.0, 0.0, 0.0

    for s in spots:
        G = np.asarray(s["G_lab"], dtype=float)
        pix0 = np.asarray(s["pix"], dtype=float)

        # ── Beam-divergence pixel Jacobian ────────────────────────────────
        J_div = np.zeros((2, 2))
        if not _no_divergence:
            for col, e in enumerate([e_h, e_v]):
                pp = _perturbed_pix(G, e, +_H)
                pm = _perturbed_pix(G, e, -_H)
                if pp is not None and pm is not None:
                    J_div[:, col] = (np.asarray(pp) - np.asarray(pm)) / (2.0 * _H)

        D_beam = np.diag([sigma_h ** 2, sigma_v ** 2])
        cov_div = J_div @ D_beam @ J_div.T

        # ── Footprint pixel Jacobian ──────────────────────────────────────
        # k̂_f is the same for all source positions (same G, same λ).
        cov_fp = _zero2.copy()
        if do_footprint:
            lam_s = float(s["lam"])
            kf_vec = (2.0 * np.pi / lam_s) * ki + G
            kf_hat_s = kf_vec / np.linalg.norm(kf_vec)
            J_fp = np.zeros((2, 2))
            for col, d_src in enumerate([drs_dh, drs_dv]):
                pp = _project_from_source(kf_hat_s, +_S * d_src)
                pm = _project_from_source(kf_hat_s, -_S * d_src)
                if pp is not None and pm is not None:
                    J_fp[:, col] = (pp - pm) / (2.0 * _S)
            D_fp = np.diag([(sigma_beam_h_nm * 1e-6) ** 2, (sigma_beam_v_nm * 1e-6) ** 2])
            cov_fp = J_fp @ D_fp @ J_fp.T

        # ── Combined pixel covariance ─────────────────────────────────────
        cov_px = cov_div + cov_fp
        s["cov_px"] = cov_px
        s["sigma_major_px"], s["sigma_minor_px"], s["ellipse_angle_px_deg"] = (
            _ellipse_params(cov_px)
        )

        # ── Pixel→angle Jacobian ──────────────────────────────────────────
        try:
            _dp = 1.0  # 1-pixel step
            J_pa = np.zeros((2, 2))
            tp, cp = _pix_to_angles(pix0[0] + _dp, pix0[1])
            tm, cm = _pix_to_angles(pix0[0] - _dp, pix0[1])
            J_pa[0, 0] = (tp - tm) / (2 * _dp)   # ∂tth/∂x
            J_pa[1, 0] = (cp - cm) / (2 * _dp)   # ∂chi/∂x
            tp, cp = _pix_to_angles(pix0[0], pix0[1] + _dp)
            tm, cm = _pix_to_angles(pix0[0], pix0[1] - _dp)
            J_pa[0, 1] = (tp - tm) / (2 * _dp)   # ∂tth/∂y
            J_pa[1, 1] = (cp - cm) / (2 * _dp)   # ∂chi/∂y
            cov_ang = J_pa @ cov_px @ J_pa.T
        except Exception:
            cov_ang = _zero2.copy()

        s["cov_ang"] = cov_ang
        s["sigma_major_ang_deg"], s["sigma_minor_ang_deg"], s["ellipse_angle_ang_deg"] = (
            _ellipse_params(cov_ang)
        )
        s["sigma_tth_deg"] = float(np.sqrt(max(cov_ang[0, 0], 0.0)))
        s["sigma_chi_deg"] = float(np.sqrt(max(cov_ang[1, 1], 0.0)))

    return spots

beam_in_crystal

beam_in_crystal(U)

Crystal-frame direction of the incident beam (x in LT lab frame). U must already be in the lab frame (use sample_tilt_deg in euler_to_U).

Source code in src/nrxrdct/laue/simulation.py
def beam_in_crystal(U):
    """Crystal-frame direction of the incident beam (x in LT lab frame).
    U must already be in the lab frame (use sample_tilt_deg in euler_to_U)."""
    return U.T @ np.array([1.0, 0.0, 0.0])

clear_allowed_hkl_cache

clear_allowed_hkl_cache() -> None

Clear the module-level cache used by :func:precompute_allowed_hkl.

Source code in src/nrxrdct/laue/simulation.py
def clear_allowed_hkl_cache() -> None:
    """Clear the module-level cache used by :func:`precompute_allowed_hkl`."""
    _allowed_hkl_cache.clear()
    _hkl_arrays_cache.clear()

collect_full_detector_image

collect_full_detector_image(base_dir, out_h5_path)

Stitch the row-chunk .npz files from :func:submit_full_detector_image into a single HDF5 file ('I', 'x0', 'y0' datasets + a 'meta' group with the full run configuration and per-chunk timing).

Parameters:
  • base_dir (str) –

    Same base_dir passed to submit_full_detector_image.

  • out_h5_path (str) –

    Path of the combined HDF5 file to write.

Returns:
  • dict –

    {'I', 'x0', 'y0'} — the same arrays just written to disk.

Raises:
  • RuntimeError –

    If any row chunk is missing (job still running, failed, or never submitted) — names the missing chunk indices and their expected row ranges so you know what to resubmit.

Source code in src/nrxrdct/laue/simulation.py
def collect_full_detector_image(base_dir, out_h5_path):
    """
    Stitch the row-chunk `.npz` files from :func:`submit_full_detector_image`
    into a single HDF5 file (`'I'`, `'x0'`, `'y0'` datasets + a `'meta'`
    group with the full run configuration and per-chunk timing).

    Args:
        base_dir (str): Same `base_dir` passed to `submit_full_detector_image`.
        out_h5_path (str): Path of the combined HDF5 file to write.

    Returns:
        dict: `{'I', 'x0', 'y0'}` — the same arrays just written to disk.

    Raises:
        RuntimeError: If any row chunk is missing (job still running,
            failed, or never submitted) — names the missing chunk indices
            and their expected row ranges so you know what to resubmit.
    """
    import h5py

    job_meta_dir = os.path.join(base_dir, "job_meta")
    chunks_dir = os.path.join(base_dir, "chunks")
    meta_path = os.path.join(job_meta_dir, "full_detector_image_meta.json")
    with open(meta_path) as fh:
        meta = json.load(fh)

    n_rows_total = meta["n_rows_total"]
    bin_px = meta["bin_px"]

    chunk_files = sorted(
        f for f in os.listdir(chunks_dir) if f.startswith("chunk_") and f.endswith(".npz")
    )
    chunks = []
    for fname in chunk_files:
        d = np.load(os.path.join(chunks_dir, fname))
        chunks.append(
            dict(row_start=int(d["row_start"]), row_end=int(d["row_end"]),
                 I=d["I"], x0=d["x0"], y0=d["y0"],
                 elapsed_seconds=float(d["elapsed_seconds"]))
        )
    chunks.sort(key=lambda c: c["row_start"])

    covered = np.zeros(n_rows_total, dtype=bool)
    for c in chunks:
        covered[c["row_start"]:c["row_end"]] = True
    if not covered.all():
        missing_rows = np.flatnonzero(~covered)
        raise RuntimeError(
            f"collect_full_detector_image: {len(missing_rows)}/{n_rows_total} "
            f"rows missing (chunk jobs still running, failed, or not yet "
            f"submitted) — first few missing row indices: "
            f"{missing_rows[:10].tolist()}"
        )

    x0 = chunks[0]["x0"]
    I = np.concatenate([c["I"] for c in chunks], axis=0)
    y0 = np.concatenate([c["y0"] for c in chunks], axis=0)
    total_cpu_seconds = sum(c["elapsed_seconds"] for c in chunks)

    with h5py.File(out_h5_path, "w") as f:
        f.create_dataset("I", data=I, compression="gzip")
        f.create_dataset("x0", data=x0, compression="gzip")
        f.create_dataset("y0", data=y0, compression="gzip")

        mgrp = f.create_group("meta")
        for key in (
            "bin_px", "n_energy", "E_min_eV", "E_max_eV", "source",
            "structure_model", "darwin", "sigma_h_mrad", "sigma_v_mrad",
            "n_div", "n_rows_total",
        ):
            mgrp.attrs[key] = meta[key]
        mgrp.attrs["exclude_layers"] = json.dumps(meta.get("exclude_layers"))
        mgrp.attrs["source_kwargs"] = json.dumps(meta.get("source_kwargs"))
        mgrp.attrs["kb_params"] = json.dumps(meta.get("kb_params"))
        mgrp.attrs["n_chunks"] = len(chunks)
        mgrp.attrs["total_worker_cpu_seconds"] = total_cpu_seconds

        cam_grp = mgrp.create_group("camera")
        for k, v in meta["camera"].items():
            cam_grp.attrs[k] = v

    print(f"collect_full_detector_image: {len(chunks)} chunks -> {out_h5_path}")
    return {"I": I, "x0": x0, "y0": y0}

decompose_matstarlab

decompose_matstarlab(matstarlab, crystal)

Decompose a LaueTools matstarlab into pure rotation and elastic strain.

Uses the right polar decomposition of the deformation gradient F:

$$ F = U \cdot P $$ where:

  • F — full deformation gradient (LT frame) = what U_from_matstarlab returns
  • U — pure rotation (orthogonal, det = +1): the rigid crystal orientation
  • P — right-stretch tensor (symmetric positive-definite): the lattice distortion

The small-strain tensor is extracted from P as ε = P − I.

matstarlab : array-like, shape (3, 3) LaueTools grain matrix in LT2/OR frame (no 2π). crystal : xu.materials.Crystal Reference (unstrained) crystal — same object passed to simulate_laue.

U : ndarray, shape (3, 3) Pure rotation in LT frame (orthogonal, det ≈ +1). Use this in simulate_laue when you want rotation-only simulation (strain effects on peak positions are ignored). F : ndarray, shape (3, 3) Full deformation gradient (= U_from_matstarlab output). Use this in simulate_laue to include strain in the spot geometry. eps : ndarray, shape (3, 3) Small-strain tensor in the crystal frame: ε = P − I. Diagonal entries are normal strains (ε₁₁, ε₂₂, ε₃₃); off-diagonal entries are shear strains (engineering convention ×½). eps_voigt : ndarray, shape (6,) Voigt representation [ε₁₁, ε₂₂, ε₃₃, ε₂₃, ε₁₃, ε₁₂].

Note: * The decomposition is exact (no small-strain approximation). * For strains ≲ 10⁻³ (typical elastic), P ≈ I and F ≈ U. * The strain ε is expressed in the crystal frame (principal axes of P). To express it in the lab frame: ε_lab = U @ ε @ U.T. * To check: np.allclose(U @ (eps + np.eye(3)) @ B0, F @ B0) should hold.

Example:

U, F, eps, eps_v = decompose_matstarlab(matstarlab, crystal) spots_rot_only = simulate_laue(crystal, U, camera) # rotation only spots_with_strain = simulate_laue(crystal, F, camera) # rotation + strain print("normal strains:", np.diag(eps)) print("shear strains:", eps[0,1], eps[0,2], eps[1,2])

Source code in src/nrxrdct/laue/simulation.py
def decompose_matstarlab(matstarlab, crystal):
    """
    Decompose a LaueTools `matstarlab` into pure rotation and elastic strain.

    Uses the **right polar decomposition** of the deformation gradient F:

    $$
    F = U \\cdot P
    $$
    where:

    * **F** — full deformation gradient (LT frame) = what `U_from_matstarlab` returns
    * **U** — pure rotation (orthogonal, det = +1): the rigid crystal orientation
    * **P** — right-stretch tensor (symmetric positive-definite): the lattice distortion

    The small-strain tensor is extracted from P as `ε = P − I`.

    Args:
    matstarlab : array-like, shape (3, 3)
        LaueTools grain matrix in LT2/OR frame (no 2π).
    crystal : xu.materials.Crystal
        Reference (unstrained) crystal — same object passed to `simulate_laue`.

    Returns:
    U : ndarray, shape (3, 3)
        Pure rotation in LT frame (orthogonal, det ≈ +1).  Use this in
        `simulate_laue` when you want rotation-only simulation (strain
        effects on peak positions are ignored).
    F : ndarray, shape (3, 3)
        Full deformation gradient (= `U_from_matstarlab` output).  Use
        this in `simulate_laue` to include strain in the spot geometry.
    eps : ndarray, shape (3, 3)
        Small-strain tensor in the crystal frame: `ε = P − I`.
        Diagonal entries are normal strains (ε₁₁, ε₂₂, ε₃₃);
        off-diagonal entries are shear strains (engineering convention ×½).
    eps_voigt : ndarray, shape (6,)
        Voigt representation `[ε₁₁, ε₂₂, ε₃₃, ε₂₃, ε₁₃, ε₁₂]`.

    Note:
    * The decomposition is exact (no small-strain approximation).
    * For strains ≲ 10⁻³ (typical elastic), P ≈ I and F ≈ U.
    * The strain ε is expressed in the **crystal frame** (principal axes of P).
      To express it in the lab frame: `ε_lab = U @ ε @ U.T`.
    * To check: `np.allclose(U @ (eps + np.eye(3)) @ B0, F @ B0)` should hold.

    Example:
    >>> U, F, eps, eps_v = decompose_matstarlab(matstarlab, crystal)
    >>> spots_rot_only = simulate_laue(crystal, U, camera)   # rotation only
    >>> spots_with_strain = simulate_laue(crystal, F, camera) # rotation + strain
    >>> print("normal strains:", np.diag(eps))
    >>> print("shear  strains:", eps[0,1], eps[0,2], eps[1,2])
"""
    from scipy.linalg import polar

    F = _matstarlab_to_F(matstarlab, crystal)

    # Right polar decomposition: F = U @ P
    # U: orthogonal (rotation),  P: symmetric positive-definite (stretch)
    U, P = polar(F, side="right")

    # Small-strain tensor: ε = P − I  (exact for symmetric P)
    eps = P - np.eye(3)

    # Voigt: [e11, e22, e33, e23, e13, e12]
    eps_voigt = np.array(
        [
            eps[0, 0],
            eps[1, 1],
            eps[2, 2],
            eps[1, 2],
            eps[0, 2],
            eps[0, 1],
        ]
    )

    return U, F, eps, eps_voigt

depth_scan_image

depth_scan_image(spots: list[dict], image: ndarray, camera, stack, ki_hat=None, *, n_steps: int = 100, z_min_mm: float = 0.0, z_max_mm: float | None = None, min_intensity: float = 0.01, score_weighted: bool = True, interp_order: int = 1) -> dict

Image-based depth-resolved Laue reconstruction by parallax sampling.

For every simulated spot and every candidate depth z, the expected detector position is computed via the exact linear parallax formula and the raw pixel intensity is sampled from the detector image using bilinear interpolation. No peak extraction is required.

The full depth × spot intensity matrix is returned in a single batched :func:scipy.ndimage.map_coordinates call, making it fast even for large spot lists and fine depth grids.

Two outputs are provided:

  • Score profile score[z] — sum (optionally intensity-weighted) of all sampled image values at depth z; its peak indicates the depth of dominant diffracting volume.
  • Score matrix score_matrix[z, spot] — per-spot depth profiles; each column is the raw image signal along the parallax trail of one spot. Bright columns mark spots that are genuinely localised at a specific depth; broad columns indicate depth-spread (thick diffracting layers).
Parameters:
  • spots (list[dict]) –

    Simulated spot list from :func:simulate_laue_darwin or :func:simulate_laue_stack.

  • image (ndarray) –

    Raw detector image (Nv, Nh) float array.

  • camera –

    :class:Camera used in the simulation.

  • stack –

    :class:LayeredCrystal used in the simulation.

  • ki_hat –

    Incident beam direction (3-vector, LT frame). Default [1, 0, 0].

  • n_steps (int, default: 100 ) –

    Number of depth values to sample.

  • z_min_mm (float, default: 0.0 ) –

    Minimum physical depth (mm, along surface normal).

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

    Maximum physical depth (mm). Defaults to total stack thickness.

  • min_intensity (float, default: 0.01 ) –

    Skip simulated spots below this normalised intensity.

  • score_weighted (bool, default: True ) –

    If True each sampled value is multiplied by the spot's normalised intensity before summing into score.

  • interp_order (int, default: 1 ) –

    Interpolation order for :func:~scipy.ndimage.map_coordinates (1 = bilinear, 3 = bicubic). Default 1.

Returns:
  • dict –

    dict with keys:

  • dict –

    'z_mm' ndarray (n_steps,) — physical depth values (mm).

  • dict –

    'score' ndarray (n_steps,) — aggregated image signal at each depth.

  • dict –

    'score_per_phase' dict {phase: ndarray(n_steps,)} — per-phase score.

  • dict –

    'score_matrix' ndarray (n_steps, n_valid_spots) — raw sampled intensities; columns are spots, rows are depths.

  • dict –

    'spot_phases' list (n_valid_spots,) — phase label for each column of score_matrix.

  • dict –

    'spot_hkls' list (n_valid_spots,) — (h, k, l) for each column.

  • dict –

    'cos_in' float — |k̂_i · n̂|.

Source code in src/nrxrdct/laue/simulation.py
def depth_scan_image(
    spots: list[dict],
    image: "np.ndarray",
    camera,
    stack,
    ki_hat=None,
    *,
    n_steps: int = 100,
    z_min_mm: float = 0.0,
    z_max_mm: "float | None" = None,
    min_intensity: float = 0.01,
    score_weighted: bool = True,
    interp_order: int = 1,
) -> dict:
    """
    Image-based depth-resolved Laue reconstruction by parallax sampling.

    For every simulated spot and every candidate depth *z*, the expected
    detector position is computed via the exact linear parallax formula and
    the raw pixel intensity is sampled from the detector image using
    bilinear interpolation.  No peak extraction is required.

    The full depth × spot intensity matrix is returned in a single batched
    :func:`scipy.ndimage.map_coordinates` call, making it fast even for
    large spot lists and fine depth grids.

    Two outputs are provided:

    * **Score profile** ``score[z]`` — sum (optionally intensity-weighted)
      of all sampled image values at depth *z*; its peak indicates the
      depth of dominant diffracting volume.
    * **Score matrix** ``score_matrix[z, spot]`` — per-spot depth profiles;
      each column is the raw image signal along the parallax trail of one
      spot.  Bright columns mark spots that are genuinely localised at a
      specific depth; broad columns indicate depth-spread (thick diffracting
      layers).

    Args:
        spots: Simulated spot list from :func:`simulate_laue_darwin` or
            :func:`simulate_laue_stack`.
        image: Raw detector image ``(Nv, Nh)`` float array.
        camera: :class:`Camera` used in the simulation.
        stack: :class:`LayeredCrystal` used in the simulation.
        ki_hat: Incident beam direction (3-vector, LT frame). Default
            ``[1, 0, 0]``.
        n_steps: Number of depth values to sample.
        z_min_mm: Minimum physical depth (mm, along surface normal).
        z_max_mm: Maximum physical depth (mm). Defaults to total stack
            thickness.
        min_intensity: Skip simulated spots below this normalised intensity.
        score_weighted: If ``True`` each sampled value is multiplied by the
            spot's normalised intensity before summing into ``score``.
        interp_order: Interpolation order for
            :func:`~scipy.ndimage.map_coordinates` (1 = bilinear,
            3 = bicubic). Default 1.

    Returns:
        dict with keys:

        ``'z_mm'``
            ndarray (n_steps,) — physical depth values (mm).
        ``'score'``
            ndarray (n_steps,) — aggregated image signal at each depth.
        ``'score_per_phase'``
            dict ``{phase: ndarray(n_steps,)}`` — per-phase score.
        ``'score_matrix'``
            ndarray (n_steps, n_valid_spots) — raw sampled intensities;
            columns are spots, rows are depths.
        ``'spot_phases'``
            list (n_valid_spots,) — phase label for each column of
            ``score_matrix``.
        ``'spot_hkls'``
            list (n_valid_spots,) — ``(h, k, l)`` for each column.
        ``'cos_in'``
            float — ``|k̂_i · n̂|``.
    """
    from scipy.ndimage import map_coordinates

    stack = _flatten_if_multiblock(stack)
    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki = ki / np.linalg.norm(ki)
    n_hat = np.asarray(stack.n_hat, dtype=float)
    n_hat = n_hat / np.linalg.norm(n_hat)
    cos_in = float(abs(np.dot(ki, n_hat)))
    if cos_in < 1e-6:
        raise ValueError("ki is nearly parallel to the sample surface — cos_in ≈ 0")

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

    total_mm = sum(
        lyr.thickness for lyr in (stack.layers * stack.n_rep + stack.buffer_layers)
    ) * 1e-7
    if z_max_mm is None:
        z_max_mm = total_mm

    z_mm = np.linspace(z_min_mm, z_max_mm, n_steps)

    # ── Filter spots and precompute parallax geometry ─────────────────────────
    filtered = [
        s for s in spots
        if s.get("pix") is not None and float(s.get("intensity", 0)) >= min_intensity
    ]
    if not filtered:
        raise ValueError("No spots pass the min_intensity filter.")

    _EPS = 0.01  # mm
    p0_list, slope_list, valid_mask = [], [], []

    for s in filtered:
        tth = float(np.radians(s["tth"]))
        chi = float(np.radians(s["chi"]))
        kf = np.array([np.cos(tth),
                        np.sin(tth) * np.sin(chi),
                        np.sin(tth) * np.cos(chi)])
        p0 = camera.project(kf, source_depth_mm=0.0)
        p1 = camera.project(kf, source_depth_mm=_EPS / cos_in)
        if p0 is None or p1 is None:
            valid_mask.append(False)
            p0_list.append([np.nan, np.nan])
            slope_list.append([0.0, 0.0])
        else:
            valid_mask.append(True)
            p0_list.append(list(p0))
            slope_list.append([(p1[0] - p0[0]) / _EPS, (p1[1] - p0[1]) / _EPS])

    valid = np.array(valid_mask)
    p0_arr    = np.array(p0_list)[valid]     # (n_valid, 2)  [col, row]
    slope_arr = np.array(slope_list)[valid]  # (n_valid, 2)  [px / mm]
    w_arr     = np.array([float(s.get("intensity", 1.0)) for s in filtered])[valid]
    phase_arr = [s.get("phase_label", "unknown") for i, s in enumerate(filtered) if valid[i]]
    hkl_arr   = [s.get("hkl", (0, 0, 0))        for i, s in enumerate(filtered) if valid[i]]
    phases    = list(dict.fromkeys(phase_arr))

    n_valid = int(valid.sum())

    # ── Batch all (z, spot) positions into one map_coordinates call ───────────
    # p_all shape: (n_steps, n_valid, 2)
    p_all = p0_arr[None, :, :] + z_mm[:, None, None] * slope_arr[None, :, :]  # (n_steps, n_valid, 2)

    # map_coordinates expects (row, col) = (y, x)
    rows = p_all[:, :, 1].ravel()   # (n_steps * n_valid,)
    cols = p_all[:, :, 0].ravel()

    # Out-of-bounds positions → 0 via cval
    sampled = map_coordinates(
        img, [rows, cols],
        order=interp_order, mode="constant", cval=0.0,
    )
    score_matrix = sampled.reshape(n_steps, n_valid)  # (n_steps, n_valid)

    # Zero out off-detector entries
    on_det = (
        (p_all[:, :, 0] >= 0) & (p_all[:, :, 0] < Nh)
        & (p_all[:, :, 1] >= 0) & (p_all[:, :, 1] < Nv)
    )
    score_matrix = np.where(on_det, score_matrix, 0.0)

    # ── Aggregate scores ──────────────────────────────────────────────────────
    if score_weighted:
        score = (score_matrix * w_arr[None, :]).sum(axis=1)
    else:
        score = score_matrix.sum(axis=1)

    phase_arr_np = np.array(phase_arr)
    score_per_phase = {}
    for ph in phases:
        mask_ph = (phase_arr_np == ph)
        if score_weighted:
            score_per_phase[ph] = (score_matrix[:, mask_ph] * w_arr[None, mask_ph]).sum(axis=1)
        else:
            score_per_phase[ph] = score_matrix[:, mask_ph].sum(axis=1)

    return {
        "z_mm":            z_mm,
        "score":           score,
        "score_per_phase": score_per_phase,
        "score_matrix":    score_matrix,
        "spot_phases":     phase_arr,
        "spot_hkls":       hkl_arr,
        "cos_in":          cos_in,
    }

depth_scan_reconstruction

depth_scan_reconstruction(spots: list[dict], peaklist: ndarray, camera, stack, ki_hat=None, *, n_steps: int = 100, z_min_mm: float = 0.0, z_max_mm: float | None = None, tolerance_px: float = 5.0, min_intensity: float = 0.01, score_weighted: bool = True) -> dict

Poor man's depth-resolved Laue reconstruction by parallax scanning.

For each candidate depth z below the surface, every simulated spot is projected to its expected detector position using the depth-parallax model. A hit-or-miss score counts how many projections land within tolerance_px of a measured peak. The score profile over z reveals which depths are actively diffracting.

Additionally, for each measured peak the depth of origin is estimated by linearly inverting the parallax model against the best-matching simulated spot — giving a per-peak depth assignment without scanning.

The projection is exactly linear in depth (camera.project uses a linear formula), so only two calls per spot are needed to precompute the exact slope; subsequent depth evaluations are pure array operations.

Parameters:
  • spots (list[dict]) –

    Simulated spot list from :func:simulate_laue_darwin or :func:simulate_laue_stack.

  • peaklist (ndarray) –

    (N, ≥2) array [col, row, ...] as returned by :func:convert_spotsfile2peaklist.

  • camera –

    :class:Camera used in the simulation.

  • stack –

    :class:LayeredCrystal used in the simulation. Provides the surface normal and total thickness.

  • ki_hat –

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

  • n_steps (int, default: 100 ) –

    Number of depth values to scan.

  • z_min_mm (float, default: 0.0 ) –

    Minimum physical depth (mm, along surface normal).

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

    Maximum physical depth (mm). Defaults to total stack thickness.

  • tolerance_px (float, default: 5.0 ) –

    Matching radius in pixels for hit-or-miss counting and per-peak depth inversion.

  • min_intensity (float, default: 0.01 ) –

    Skip spots below this normalised intensity.

  • score_weighted (bool, default: True ) –

    If True each hit is weighted by the spot's normalised intensity; if False every hit counts as 1.

Returns:
  • dict –

    dict with keys:

  • dict –

    'z_mm' ndarray (n_steps,) — physical depth values scanned (mm).

  • dict –

    'score' ndarray (n_steps,) — total hit score at each depth.

  • dict –

    'score_per_phase' dict {phase_label: ndarray(n_steps,)} — score broken out by phase.

  • dict –

    'z_est_per_peak' ndarray (N_peaks,) — estimated depth of origin for each measured peak (NaN if no simulated spot matched within tolerance_px).

  • dict –

    'phase_per_peak' list (N_peaks,) — phase label of the best-matching simulated spot for each peak (None if unmatched).

  • dict –

    'spot_idx_per_peak' list (N_peaks,) — index into the filtered spot list for each peak.

  • dict –

    'cos_in' float — |k̂_i · n̂|, used to convert beam-path depth to physical depth.

Source code in src/nrxrdct/laue/simulation.py
def depth_scan_reconstruction(
    spots: list[dict],
    peaklist: "np.ndarray",
    camera,
    stack,
    ki_hat=None,
    *,
    n_steps: int = 100,
    z_min_mm: float = 0.0,
    z_max_mm: "float | None" = None,
    tolerance_px: float = 5.0,
    min_intensity: float = 0.01,
    score_weighted: bool = True,
) -> dict:
    """
    Poor man's depth-resolved Laue reconstruction by parallax scanning.

    For each candidate depth *z* below the surface, every simulated spot is
    projected to its expected detector position using the depth-parallax
    model.  A **hit-or-miss** score counts how many projections land within
    *tolerance_px* of a measured peak.  The score profile over *z* reveals
    which depths are actively diffracting.

    Additionally, for each measured peak the depth of origin is estimated by
    linearly inverting the parallax model against the best-matching simulated
    spot — giving a per-peak depth assignment without scanning.

    The projection is **exactly linear** in depth (``camera.project`` uses a
    linear formula), so only two calls per spot are needed to precompute the
    exact slope; subsequent depth evaluations are pure array operations.

    Args:
        spots: Simulated spot list from :func:`simulate_laue_darwin` or
            :func:`simulate_laue_stack`.
        peaklist: ``(N, ≥2)`` array ``[col, row, ...]`` as returned by
            :func:`convert_spotsfile2peaklist`.
        camera: :class:`Camera` used in the simulation.
        stack: :class:`LayeredCrystal` used in the simulation.  Provides the
            surface normal and total thickness.
        ki_hat: Incident beam direction (3-vector, LT frame).  Defaults to
            ``[1, 0, 0]``.
        n_steps: Number of depth values to scan.
        z_min_mm: Minimum physical depth (mm, along surface normal).
        z_max_mm: Maximum physical depth (mm).  Defaults to total stack
            thickness.
        tolerance_px: Matching radius in pixels for hit-or-miss counting and
            per-peak depth inversion.
        min_intensity: Skip spots below this normalised intensity.
        score_weighted: If ``True`` each hit is weighted by the spot's
            normalised intensity; if ``False`` every hit counts as 1.

    Returns:
        dict with keys:

        ``'z_mm'``
            ndarray (n_steps,) — physical depth values scanned (mm).
        ``'score'``
            ndarray (n_steps,) — total hit score at each depth.
        ``'score_per_phase'``
            dict ``{phase_label: ndarray(n_steps,)}`` — score broken out by
            phase.
        ``'z_est_per_peak'``
            ndarray (N_peaks,) — estimated depth of origin for each measured
            peak (NaN if no simulated spot matched within *tolerance_px*).
        ``'phase_per_peak'``
            list (N_peaks,) — phase label of the best-matching simulated spot
            for each peak (``None`` if unmatched).
        ``'spot_idx_per_peak'``
            list (N_peaks,) — index into the filtered spot list for each peak.
        ``'cos_in'``
            float — ``|k̂_i · n̂|``, used to convert beam-path depth to
            physical depth.
    """
    from scipy.spatial import cKDTree

    stack = _flatten_if_multiblock(stack)
    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki = ki / np.linalg.norm(ki)
    n_hat = np.asarray(stack.n_hat, dtype=float)
    n_hat = n_hat / np.linalg.norm(n_hat)
    cos_in = float(abs(np.dot(ki, n_hat)))
    if cos_in < 1e-6:
        raise ValueError("ki is nearly parallel to the sample surface — cos_in ≈ 0")

    # Total stack thickness in mm (Å → mm)
    total_mm = sum(
        lyr.thickness for lyr in (stack.layers * stack.n_rep + stack.buffer_layers)
    ) * 1e-7
    if z_max_mm is None:
        z_max_mm = total_mm

    z_mm = np.linspace(z_min_mm, z_max_mm, n_steps)

    # ── Filter spots ──────────────────────────────────────────────────────────
    filtered = [
        s for s in spots
        if s.get("pix") is not None and float(s.get("intensity", 0)) >= min_intensity
    ]
    if not filtered:
        raise ValueError("No spots pass the min_intensity filter.")

    phases = list(dict.fromkeys(s.get("phase_label", "unknown") for s in filtered))

    # ── Precompute surface positions and parallax slopes ──────────────────────
    # Projection is exact-linear in source_depth_mm, so two calls suffice.
    _EPS = 0.01  # mm — finite-difference step (along surface normal)
    p0_list: list[np.ndarray] = []
    slope_list: list[np.ndarray] = []
    valid_mask: list[bool] = []

    for s in filtered:
        tth = float(np.radians(s["tth"]))
        chi = float(np.radians(s["chi"]))
        kf = np.array([np.cos(tth),
                        np.sin(tth) * np.sin(chi),
                        np.sin(tth) * np.cos(chi)])
        p0 = camera.project(kf, source_depth_mm=0.0)
        p1 = camera.project(kf, source_depth_mm=_EPS / cos_in)
        if p0 is None or p1 is None:
            valid_mask.append(False)
            p0_list.append(np.array([np.nan, np.nan]))
            slope_list.append(np.array([0.0, 0.0]))
        else:
            valid_mask.append(True)
            p0_arr = np.array(p0, dtype=float)
            slope = (np.array(p1, dtype=float) - p0_arr) / _EPS
            p0_list.append(p0_arr)
            slope_list.append(slope)

    valid = np.array(valid_mask)
    p0_arr    = np.array(p0_list)     # (n_spots, 2)
    slope_arr = np.array(slope_list)  # (n_spots, 2)  [px / mm of physical depth]
    w_arr = np.array([float(s.get("intensity", 1.0)) for s in filtered])

    phase_arr = np.array([s.get("phase_label", "unknown") for s in filtered])

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

    # ── Depth scan — hit-or-miss scoring ──────────────────────────────────────
    score       = np.zeros(n_steps)
    score_phase = {ph: np.zeros(n_steps) for ph in phases}

    for i_z, z in enumerate(z_mm):
        p_z = p0_arr + z * slope_arr           # (n_spots, 2)
        on_det = (
            valid
            & (p_z[:, 0] >= 0) & (p_z[:, 0] < camera.Nh)
            & (p_z[:, 1] >= 0) & (p_z[:, 1] < camera.Nv)
        )
        if not on_det.any():
            continue
        dists, _ = tree.query(p_z[on_det])
        hits = dists <= tolerance_px
        w_hit = w_arr[on_det][hits] if score_weighted else hits.astype(float)
        score[i_z] = float(w_hit.sum())
        for ph in phases:
            mask_ph = (phase_arr[on_det][hits] == ph)
            score_phase[ph][i_z] = float(
                (w_arr[on_det][hits][mask_ph] if score_weighted
                 else mask_ph.astype(float)).sum()
            )

    # ── Per-peak depth inversion ──────────────────────────────────────────────
    # For each measured peak p_m, find the spot i that minimises the residual
    # |p0_i + z_opt_i * slope_i - p_m| with z_opt_i clipped to [z_min, z_max].
    z_est_per_peak  = np.full(len(meas_xy), np.nan)
    phase_per_peak  = [None] * len(meas_xy)
    sidx_per_peak   = [None] * len(meas_xy)

    valid_p0    = p0_arr[valid]
    valid_slope = slope_arr[valid]
    valid_w     = w_arr[valid]
    valid_phase = phase_arr[valid]
    valid_indices = np.where(valid)[0]

    denom = np.einsum("ij,ij->i", valid_slope, valid_slope)
    denom_safe = np.where(denom > 1e-12, denom, 1.0)

    for j, p_m in enumerate(meas_xy):
        dp = p_m[None, :] - valid_p0                         # (n_valid, 2)
        z_num = np.einsum("ij,ij->i", dp, valid_slope)
        z_opt = np.clip(z_num / denom_safe, z_min_mm, z_max_mm)
        p_opt = valid_p0 + z_opt[:, None] * valid_slope
        residuals = np.linalg.norm(p_opt - p_m[None], axis=1)
        best = int(np.argmin(residuals))
        if residuals[best] <= tolerance_px:
            z_est_per_peak[j] = float(z_opt[best])
            phase_per_peak[j] = str(valid_phase[best])
            sidx_per_peak[j]  = int(valid_indices[best])

    return {
        "z_mm":             z_mm,
        "score":            score,
        "score_per_phase":  score_phase,
        "z_est_per_peak":   z_est_per_peak,
        "phase_per_peak":   phase_per_peak,
        "spot_idx_per_peak": sidx_per_peak,
        "cos_in":           cos_in,
    }

disorientation

disorientation(U1: ndarray, U2: ndarray, symmetry: str = 'cubic') -> tuple[float, np.ndarray]

Disorientation between two orientation matrices with crystal symmetry.

The disorientation is the symmetry-equivalent misorientation \(\mathbf{M} = \mathbf{U}_2 \mathbf{U}_1^T\) with the smallest rotation angle, minimised over all pairs of point-group operators:

\[ \omega_\text{dis} = \min_{S_i,\,S_j \in G}\; \bigl|\!\operatorname{angle}(S_i\,\mathbf{M}\,S_j^T)\bigr| \]

Vectorised over all pairs of point-group operators using pure numpy — no dependency on orix internals.

Parameters:
  • U1 ((3, 3) ndarray) –

    First orientation matrix.

  • U2 ((3, 3) ndarray) –

    Second orientation matrix.

  • symmetry (str, default: 'cubic' ) –

    Crystal point-group symmetry — same options as :func:map_to_fundamental_zone.

Returns:
  • angle_deg( float ) –

    Disorientation angle in degrees.

  • R_dis( (3, 3) ndarray ) –

    The disorientation rotation matrix (minimum-angle symmetry-equivalent misorientation).

Example::

angle, R = disorientation(U1, U2, symmetry='cubic')
print(f"disorientation = {angle:.3f}°")
Source code in src/nrxrdct/laue/simulation.py
def disorientation(
    U1: "np.ndarray",
    U2: "np.ndarray",
    symmetry: str = "cubic",
) -> "tuple[float, np.ndarray]":
    """
    Disorientation between two orientation matrices with crystal symmetry.

    The disorientation is the symmetry-equivalent misorientation
    $\\mathbf{M} = \\mathbf{U}_2 \\mathbf{U}_1^T$ with the smallest rotation
    angle, minimised over all pairs of point-group operators:

    $$
    \\omega_\\text{dis} =
        \\min_{S_i,\\,S_j \\in G}\\;
        \\bigl|\\!\\operatorname{angle}(S_i\\,\\mathbf{M}\\,S_j^T)\\bigr|
    $$

    Vectorised over all pairs of point-group operators using pure numpy —
    no dependency on orix internals.

    Args:
        U1 ((3, 3) ndarray): First orientation matrix.
        U2 ((3, 3) ndarray): Second orientation matrix.
        symmetry (str): Crystal point-group symmetry — same options as
            :func:`map_to_fundamental_zone`.

    Returns:
        angle_deg (float): Disorientation angle in degrees.
        R_dis ((3, 3) ndarray): The disorientation rotation matrix
            (minimum-angle symmetry-equivalent misorientation).

    Example::

        angle, R = disorientation(U1, U2, symmetry='cubic')
        print(f"disorientation = {angle:.3f}°")
    """
    ops = _symmetry_ops_np(symmetry)                          # (N, 3, 3)

    # Project both inputs to SO(3) so non-orthogonal matrices such as
    # U_eff = U @ (I + ε) from strain fits give correct results.
    R1 = Rotation.from_matrix(np.asarray(U1, dtype=float)).as_matrix()
    R2 = Rotation.from_matrix(np.asarray(U2, dtype=float)).as_matrix()
    R_mis = R2 @ R1.T

    # Candidates: S_i @ R_mis @ S_j^T  for all (i, j) pairs → (N*N, 3, 3)
    ops_R = ops @ R_mis                     # (N, 3, 3)  S_i @ R_mis
    ops_T = ops.transpose(0, 2, 1)         # (N, 3, 3)  S_j^T
    candidates = (ops_R[:, None] @ ops_T[None]).reshape(-1, 3, 3)

    traces = candidates[:, 0, 0] + candidates[:, 1, 1] + candidates[:, 2, 2]
    angles = np.arccos(np.clip((traces - 1.0) / 2.0, -1.0, 1.0))

    best = int(np.argmin(angles))
    return float(np.degrees(angles[best])), candidates[best]

estimate_instrument_broadening

estimate_instrument_broadening(spots, sigma_meas_pix, mode='constant', tth_range=None, chi_range=None, min_spots=3)

Estimate the instrumental spot broadening from a calibrant measurement.

For a strain-free calibrant (e.g. Si, CeO₂, LaB₆), all measured spot widths arise from instrumental contributions only (beam divergence, detector point-spread, geometric aberrations). This function fits a model σ_instrument(2θ, χ) to those widths.

The returned scalar 'sigma_instrument' (or the callable model) can be passed directly to :func:fit_strain_distribution to subtract the instrumental baseline before fitting strain.

spots : list of dicts Simulated spots for the calibrant crystal, from :func:simulate_laue. Must contain hkl, tth, and chi keys. sigma_meas_pix : dict {(h, k, l): float} Measured semi-major spot width (pixels, 1σ) for each indexed reflection of the calibrant, obtained by fitting a 2-D Gaussian to the detector image. mode : {'constant', 'linear_tth', 'quadratic_tth'} Model for the angular dependence of instrumental broadening:

`'constant'`
    Single value for all spots: median of the measured widths.
    Robust to outliers; use when the detector is well-focused.

`'linear_tth'`
    σ_inst(2θ) = a + b · 2θ (degrees).
    Captures defocus that increases with scattering angle.

`'quadratic_tth'`
    σ_inst(2θ) = a + b · 2θ + c · 2θ².
    Fits a second-order trend; requires ≥ 5 spots.
(float, float), optional

Only include spots with 2θ in this range (degrees). Useful to exclude regions where the model fit is unreliable.

chi_range : (float, float), optional Only include spots with χ in this range (degrees). min_spots : int, optional Minimum number of matching spots required. Default: 3.

Returns: result : dict with keys:

`'sigma_instrument'` : float
    Scalar estimate of σ_instrument (pixels).
    For `'constant'` mode: the median.
    For parametric modes: the median of the fitted values at each spot.
`'model'` : callable  f(tth_deg) → float
    Model function for σ_instrument as a function of 2θ (degrees).
    Always returned; for `'constant'` mode it returns the same scalar
    for any input.
`'params'` : ndarray
    Fitted polynomial coefficients [a] or [a, b] or [a, b, c].
`'sigma_per_spot'` : dict  {(h,k,l): float}
    Model-predicted σ_instrument for each spot used in the fit.
`'residuals_pix'` : ndarray
    Measured − fitted σ_instrument per spot (pixels).
`'rmse_pix'` : float
    Root-mean-square of residuals (pixels).
`'hkl_used'` : list of tuples
    hkl of the spots that entered the fit.
`'n_spots'` : int
    Number of spots used.
`'mode'` : str
    The mode that was used.

ValueError If fewer than min_spots spots match (wrong hkl, out of range filters, or too few calibrant reflections on the detector).

Note: * Robust to a few outlier spots in 'constant' mode (median used). * For parametric modes the fit is an ordinary least-squares polynomial; strongly deviant spots can be manually excluded via tth_range. * The model is evaluated at 2θ only. If broadening has a strong χ dependence (e.g. astigmatism), measure and apply it separately. * A good calibrant should have sharp, well-separated spots with low absorption and no texture — Si (powder or single crystal cut along low-index direction), CeO₂, LaB₆, or Al₂O₃ are common choices.

Example:

Simulate calibrant spots

si = crystal_from_cif('silicon.cif') U_si = np.eye(3) # known orientation spots_cal = simulate_laue(si, U_si, camera)

Measure widths from experiment

sigma_meas_cal = {(1,1,1): 2.3, (2,2,0): 2.8, (3,1,1): 3.1, ... (4,0,0): 3.5, (3,3,1): 3.4}

res = estimate_instrument_broadening( ... spots_cal, sigma_meas_cal, mode='linear_tth') print(f"σ_inst(2θ=30°) = {res'model':.2f} px")

Use in strain fitting

sigma_inst_fn = res['model'] # or res['sigma_instrument'] (scalar) J = strain_spot_jacobian(spots_sample, crystal, U, camera)

Build per-spot sigma_instrument dict for fit_strain_distribution:

sigma_inst_per_spot = { ... hkl: sigma_inst_fn(spots_sample_dict[hkl]['two_theta']) ... for hkl in J}

Source code in src/nrxrdct/laue/simulation.py
def estimate_instrument_broadening(
    spots,
    sigma_meas_pix,
    mode="constant",
    tth_range=None,
    chi_range=None,
    min_spots=3,
):
    """
    Estimate the instrumental spot broadening from a calibrant measurement.

    For a strain-free calibrant (e.g. Si, CeO₂, LaB₆), all measured spot
    widths arise from instrumental contributions only (beam divergence, detector
    point-spread, geometric aberrations).  This function fits a model
    σ_instrument(2θ, χ) to those widths.

    The returned scalar `'sigma_instrument'` (or the callable model) can be
    passed directly to :func:`fit_strain_distribution` to subtract the
    instrumental baseline before fitting strain.

    Args:
    spots : list of dicts
        Simulated spots for the **calibrant** crystal, from :func:`simulate_laue`.
        Must contain `hkl`, `tth`, and `chi` keys.
    sigma_meas_pix : dict  {(h, k, l): float}
        Measured semi-major spot width (pixels, 1σ) for each indexed reflection
        of the calibrant, obtained by fitting a 2-D Gaussian to the detector image.
    mode : {'constant', 'linear_tth', 'quadratic_tth'}
        Model for the angular dependence of instrumental broadening:

        `'constant'`
            Single value for all spots: median of the measured widths.
            Robust to outliers; use when the detector is well-focused.

        `'linear_tth'`
            σ_inst(2θ) = a + b · 2θ (degrees).
            Captures defocus that increases with scattering angle.

        `'quadratic_tth'`
            σ_inst(2θ) = a + b · 2θ + c · 2θ².
            Fits a second-order trend; requires ≥ 5 spots.

    tth_range : (float, float), optional
        Only include spots with 2θ in this range (degrees).
        Useful to exclude regions where the model fit is unreliable.
    chi_range : (float, float), optional
        Only include spots with χ in this range (degrees).
    min_spots : int, optional
        Minimum number of matching spots required. Default: 3.

    Returns:
    result : dict with keys:

        `'sigma_instrument'` : float
            Scalar estimate of σ_instrument (pixels).
            For `'constant'` mode: the median.
            For parametric modes: the median of the fitted values at each spot.
        `'model'` : callable  f(tth_deg) → float
            Model function for σ_instrument as a function of 2θ (degrees).
            Always returned; for `'constant'` mode it returns the same scalar
            for any input.
        `'params'` : ndarray
            Fitted polynomial coefficients [a] or [a, b] or [a, b, c].
        `'sigma_per_spot'` : dict  {(h,k,l): float}
            Model-predicted σ_instrument for each spot used in the fit.
        `'residuals_pix'` : ndarray
            Measured − fitted σ_instrument per spot (pixels).
        `'rmse_pix'` : float
            Root-mean-square of residuals (pixels).
        `'hkl_used'` : list of tuples
            hkl of the spots that entered the fit.
        `'n_spots'` : int
            Number of spots used.
        `'mode'` : str
            The mode that was used.

    Raises:
    ValueError
        If fewer than `min_spots` spots match (wrong hkl, out of range filters,
        or too few calibrant reflections on the detector).

    Note:
    * Robust to a few outlier spots in `'constant'` mode (median used).
    * For parametric modes the fit is an ordinary least-squares polynomial;
      strongly deviant spots can be manually excluded via `tth_range`.
    * The model is evaluated at 2θ only.  If broadening has a strong χ
      dependence (e.g. astigmatism), measure and apply it separately.
    * A good calibrant should have sharp, well-separated spots with low
      absorption and no texture — Si (powder or single crystal cut along
      low-index direction), CeO₂, LaB₆, or Al₂O₃ are common choices.

    Example:
    >>> # Simulate calibrant spots
    >>> si = crystal_from_cif('silicon.cif')
    >>> U_si = np.eye(3)  # known orientation
    >>> spots_cal = simulate_laue(si, U_si, camera)
    >>>
    >>> # Measure widths from experiment
    >>> sigma_meas_cal = {(1,1,1): 2.3, (2,2,0): 2.8, (3,1,1): 3.1,
    ...                   (4,0,0): 3.5, (3,3,1): 3.4}
    >>>
    >>> res = estimate_instrument_broadening(
    ...     spots_cal, sigma_meas_cal, mode='linear_tth')
    >>> print(f"σ_inst(2θ=30°) = {res['model'](30):.2f} px")
    >>>
    >>> # Use in strain fitting
    >>> sigma_inst_fn = res['model']   # or res['sigma_instrument'] (scalar)
    >>> J = strain_spot_jacobian(spots_sample, crystal, U, camera)
    >>> # Build per-spot sigma_instrument dict for fit_strain_distribution:
    >>> sigma_inst_per_spot = {
    ...     hkl: sigma_inst_fn(spots_sample_dict[hkl]['two_theta'])
    ...     for hkl in J}
"""
    # ── Build a lookup: hkl → (two_theta, chi) from simulated spots ──────────
    spot_info = {}
    for s in spots:
        hkl = tuple(s["hkl"])
        spot_info[hkl] = (float(s["tth"]), float(s["chi"]))

    # ── Intersect with measured keys ──────────────────────────────────────────
    common = set(spot_info.keys()) & set(sigma_meas_pix.keys())

    rows = []  # (hkl, tth, chi, sigma_meas)
    for hkl in common:
        tth, chi = spot_info[hkl]
        if tth_range is not None and not (tth_range[0] <= tth <= tth_range[1]):
            continue
        if chi_range is not None and not (chi_range[0] <= chi <= chi_range[1]):
            continue
        rows.append((hkl, tth, chi, float(sigma_meas_pix[hkl])))

    if len(rows) < min_spots:
        raise ValueError(
            f"Only {len(rows)} calibrant spot(s) matched (need ≥ {min_spots}). "
            "Check that sigma_meas_pix keys match the hkl in spots, "
            "or relax tth_range / chi_range."
        )

    hkl_used = [r[0] for r in rows]
    tth_arr = np.array([r[1] for r in rows])
    sigma_arr = np.array([r[3] for r in rows])

    # ── Fit model ─────────────────────────────────────────────────────────────
    if mode == "constant":
        params = np.array([float(np.median(sigma_arr))])

        def model(_tth_deg):
            return float(params[0])

    elif mode in ("linear_tth", "quadratic_tth"):
        deg = 1 if mode == "linear_tth" else 2
        if len(rows) < deg + 2:
            raise ValueError(
                f"mode='{mode}' requires ≥ {deg + 2} spots, got {len(rows)}."
            )
        params = np.polyfit(tth_arr, sigma_arr, deg)

        def model(tth_deg, _p=params):
            return float(np.polyval(_p, tth_deg))

    else:
        raise ValueError(
            f"mode must be 'constant', 'linear_tth', or 'quadratic_tth', got {mode!r}"
        )

    # ── Evaluate model at each spot ───────────────────────────────────────────
    fitted = np.array([model(t) for t in tth_arr])
    residuals = sigma_arr - fitted
    rmse = float(np.sqrt(np.mean(residuals**2)))

    sigma_per_spot = {hkl: float(model(tth)) for hkl, tth, *_ in rows}

    # Scalar summary: median of fitted values (constant mode → same as params[0])
    sigma_instrument = float(np.median(fitted))

    return {
        "sigma_instrument": sigma_instrument,
        "model": model,
        "params": params,
        "sigma_per_spot": sigma_per_spot,
        "residuals_pix": residuals,
        "rmse_pix": rmse,
        "hkl_used": hkl_used,
        "n_spots": len(rows),
        "mode": mode,
    }

euler_to_U

euler_to_U(phi1, Phi, phi2, sample_tilt_deg=0.0)

Bunge ZXZ Euler angles (deg) → 3×3 orientation matrix in the LT lab frame.

Bunge Euler angles describe the crystal orientation relative to the sample surface frame (z = surface normal, x/y in the surface plane). simulate_laue expects U in the lab frame (x // beam). When the sample is tilted on the stage the two frames differ by a rotation around the horizontal axis (y in LT).

phi1, Phi, phi2 : float Bunge ZXZ Euler angles in degrees. sample_tilt_deg : float, optional Tilt of the sample surface relative to the horizontal plane (deg). Positive = front edge of sample tilted downward so the surface faces the incoming beam (standard reflection geometry).

U : ndarray, shape (3, 3) Orientation matrix such that G_lab = U @ G_crystal.

Note: The sample tilt is the sample→lab rotation about +y (horizontal axis perpendicular to the beam) by sample_tilt_deg:

R_tilt = Ry(+sample_tilt_deg)

This maps the sample surface normal from +z (horizontal surface) to (sin θ, 0, cos θ) in the lab frame, which for θ = 40° gives a grazing angle of 40° with the beam and a specular 2θ of 80°, consistent with the BM32 Z>0 top-camera geometry.

This is the inverse of the LaueTools matstarlab_to_matstarsample3x3 convention, which applies Rx_LT2(+omega) (rotation around x in the LT2 frame) as the lab→sample direction. Because x_LT2 = −y_LT, that operation equals Ry_LT(−omega) (lab→sample), so the sample→lab direction used here is Ry_LT(+omega).

When Euler angles come from a LaueTools indexing result (grain_matrix / deviatoric matrix) they are already expressed in the lab frame; pass sample_tilt_deg=0 (the default) in that case.

Source code in src/nrxrdct/laue/simulation.py
def euler_to_U(phi1, Phi, phi2, sample_tilt_deg=0.0):
    """
    Bunge ZXZ Euler angles (deg) → 3×3 orientation matrix in the LT lab frame.

    Bunge Euler angles describe the crystal orientation relative to the
    **sample surface frame** (z = surface normal, x/y in the surface plane).
    `simulate_laue` expects U in the **lab frame** (x // beam).  When the
    sample is tilted on the stage the two frames differ by a rotation around
    the horizontal axis (y in LT).

    Args:
    phi1, Phi, phi2 : float
        Bunge ZXZ Euler angles in degrees.
    sample_tilt_deg : float, optional
        Tilt of the sample surface relative to the horizontal plane (deg).
        Positive = front edge of sample tilted downward so the surface faces
        the incoming beam (standard reflection geometry).

    Returns:
    U : ndarray, shape (3, 3)
        Orientation matrix such that `G_lab = U @ G_crystal`.

    Note:
    The sample tilt is the **sample→lab** rotation about **+y** (horizontal
    axis perpendicular to the beam) by `sample_tilt_deg`:

        R_tilt = Ry(+sample_tilt_deg)

    This maps the sample surface normal from +z (horizontal surface) to
    (sin θ, 0, cos θ) in the lab frame, which for θ = 40° gives a grazing
    angle of 40° with the beam and a specular 2θ of 80°, consistent with the
    BM32 Z>0 top-camera geometry.

    This is the **inverse** of the LaueTools `matstarlab_to_matstarsample3x3`
    convention, which applies `Rx_LT2(+omega)` (rotation around x in the LT2
    frame) as the lab→sample direction.  Because `x_LT2 = −y_LT`, that
    operation equals `Ry_LT(−omega)` (lab→sample), so the sample→lab
    direction used here is `Ry_LT(+omega)`.

    When Euler angles come from a LaueTools indexing result (grain_matrix /
    deviatoric matrix) they are already expressed in the lab frame; pass
    `sample_tilt_deg=0` (the default) in that case.
"""
    U_sample = Rotation.from_euler("ZXZ", [phi1, Phi, phi2], degrees=True).as_matrix()
    if sample_tilt_deg == 0.0:
        return U_sample
    # Rx_LT2(+omega) is the LaueTools lab→sample rotation (matstarlab_to_matstarsample3x3).
    # x_LT2 = −y_LT, so Rx_LT2(omega) = Ry_LT(−omega).
    # We need the inverse (sample→lab): Ry_LT(+omega).
    R_tilt = Rotation.from_euler("Y", +sample_tilt_deg, degrees=True).as_matrix()
    return R_tilt @ U_sample

filter_spots_by_peaks

filter_spots_by_peaks(spots, peaks, tol_pix=5.0)

Keep only simulated spots that have a measured peak within tol_pix pixels.

spots : list of dict Output of any simulate_laue* function. Each dict must contain a 'pix' key with a (xcam, ycam) tuple (column, row) in detector pixel coordinates. Spots whose 'pix' is None are always dropped. peaks : array-like, shape (N, ≥2), or DataFrame with columns peak_X, peak_Y Measured peak positions from the segmentation pipeline. The first two columns (or peak_X / peak_Y columns) are interpreted as (x_col, y_row) pixel coordinates, matching the 'pix' convention used by the spot dicts. Accepted inputs:

* ``(N, ≥2)`` ndarray — columns 0 and 1 are ``peak_X`` and ``peak_Y``.
  This is the format returned by :func:`~nrxrdct.laue.segmentation.convert_spotsfile2peaklist`.
* pandas DataFrame with ``'peak_X'`` and ``'peak_Y'`` columns.
* Any sequence of *(x, y)* pairs.
float, optional

Maximum Euclidean distance (pixels) between a simulated spot and a measured peak for the spot to be retained. Default: 5.0.

list of dict Subset of spots — same dict objects, same order — containing only spots for which at least one peak lies within tol_pix pixels.

Example:

peaklist = convert_spotsfile2peaklist('frame_00001.h5') spots = simulate_laue(crystal, U, camera) matched = filter_spots_by_peaks(spots, peaklist, tol_pix=8.0) print(f"{len(matched)}/{len(spots)} simulated spots matched a peak")

Source code in src/nrxrdct/laue/simulation.py
def filter_spots_by_peaks(spots, peaks, tol_pix=5.0):
    """
    Keep only simulated spots that have a measured peak within *tol_pix* pixels.

    Args:
    spots : list of dict
        Output of any ``simulate_laue*`` function.  Each dict must contain a
        ``'pix'`` key with a ``(xcam, ycam)`` tuple (column, row) in detector
        pixel coordinates.  Spots whose ``'pix'`` is ``None`` are always dropped.
    peaks : array-like, shape (N, ≥2), or DataFrame with columns ``peak_X``, ``peak_Y``
        Measured peak positions from the segmentation pipeline.
        The first two columns (or ``peak_X`` / ``peak_Y`` columns) are interpreted
        as *(x_col, y_row)* pixel coordinates, matching the ``'pix'`` convention
        used by the spot dicts.
        Accepted inputs:

        * ``(N, ≥2)`` ndarray — columns 0 and 1 are ``peak_X`` and ``peak_Y``.
          This is the format returned by :func:`~nrxrdct.laue.segmentation.convert_spotsfile2peaklist`.
        * pandas DataFrame with ``'peak_X'`` and ``'peak_Y'`` columns.
        * Any sequence of *(x, y)* pairs.

    tol_pix : float, optional
        Maximum Euclidean distance (pixels) between a simulated spot and a
        measured peak for the spot to be retained.  Default: 5.0.

    Returns:
    list of dict
        Subset of *spots* — same dict objects, same order — containing only
        spots for which at least one peak lies within *tol_pix* pixels.

    Example:
    >>> peaklist = convert_spotsfile2peaklist('frame_00001.h5')
    >>> spots = simulate_laue(crystal, U, camera)
    >>> matched = filter_spots_by_peaks(spots, peaklist, tol_pix=8.0)
    >>> print(f"{len(matched)}/{len(spots)} simulated spots matched a peak")
    """
    from scipy.spatial import KDTree

    # ── Build (N, 2) array of measured peak positions ─────────────────────────
    try:
        import pandas as pd
        if isinstance(peaks, pd.DataFrame):
            xy_peaks = peaks[["peak_X", "peak_Y"]].to_numpy(dtype=float)
        else:
            xy_peaks = np.asarray(peaks, dtype=float)[:, :2]
    except ImportError:
        xy_peaks = np.asarray(peaks, dtype=float)[:, :2]

    if len(xy_peaks) == 0:
        return []

    tree = KDTree(xy_peaks)

    matched = []
    for s in spots:
        pix = s.get("pix")
        if pix is None:
            continue
        dist, _ = tree.query(pix, workers=1)
        if dist <= tol_pix:
            matched.append(s)

    return matched

fit_strain_distribution

fit_strain_distribution(jacobians, sigma_meas_pix, sigma_instrument, mode='isotropic', min_sensitivity=0.1)

Estimate the strain distribution from measured Laue spot widths (inverse problem).

Solves for Σ_ε given the measured semi-major broadening of each spot:

$$ \sigma_{\text{meas},k}^2 = \sigma_{\text{inst}}^2 + \lambda_{\max}(J_k \, \Sigma_\varepsilon \, J_k^\top) $$ Two modes are supported:

isotropic — single scalar σ_ε (Σ_ε = σ²I) The equation becomes linear in σ²:

$$
y_k = \sigma^2 \cdot \lambda_{\max}(J_k J_k^\top)
$$
Solved by weighted least squares over all spots.

diagonal — six independent variances σᵢ² (Σ_ε = diag(σ₁²,…,σ₆²)) λ_max is non-linear in σᵢ², so the trace is used as a linear proxy:

$$
y_k \approx \sum_i \sigma_i^2 \, \|J_{k,i}\|^2
$$
(exact when the two eigenvalues of J Σ Jᵀ are equal; conservative
otherwise, since trace ≥ λ_max).
Solved by non-negative least squares (:func:`scipy.optimize.nnls`).

jacobians : dict {(h,k,l): ndarray (2, 6)} Output of :func:strain_spot_jacobian. sigma_meas_pix : dict {(h,k,l): float} Measured semi-major spot width (pixels, 1σ) for each indexed reflection, obtained by fitting a 2-D Gaussian to the experimental detector image. Only hkl keys present in both jacobians and this dict are used. sigma_instrument : float or dict or result dict from :func:estimate_instrument_broadening Instrument broadening (pixels, 1σ), subtracted in quadrature per spot. Three forms are accepted:

* **float** — the same value is applied to all spots.
* **dict {(h,k,l): float}** — per-spot instrumental width (e.g. the
  `'sigma_per_spot'` entry from :func:`estimate_instrument_broadening`).
* **result dict** — the full dict returned by
  :func:`estimate_instrument_broadening`; the `'sigma_per_spot'` field
  is extracted automatically.  For spots not covered by the calibrant,
  the scalar `'sigma_instrument'` fallback is used.

mode : {'isotropic', 'diagonal'} Fitting model. 'isotropic' fits a single σ_ε; 'diagonal' fits all six Voigt variances independently. min_sensitivity : float, optional Minimum RMS Jacobian magnitude (px per unit strain) required for a spot to be included. Spots with sqrt(mean(J**2)) < min_sensitivity are insensitive to strain and are excluded. Default: 0.1.

Returns: result : dict with keys:

`'sigma_eps'` : float
    Isotropic RMS strain (scalar).  For `mode='isotropic'` this is
    the direct fit result; for `mode='diagonal'` it is
    `sqrt(mean(eps_voigt_std**2))`.
`'eps_voigt_std'` : ndarray, shape (6,)
    Per-component standard deviation
    [σ₁₁, σ₂₂, σ₃₃, σ₂₃, σ₁₃, σ₁₂].
    For `mode='isotropic'` all six entries are equal.
`'Sigma_eps'` : ndarray, shape (6, 6)
    Fitted covariance matrix (diagonal for both modes).
    Pass directly to :func:`strain_broadening` as `eps_cov`.
`'residuals_pix'` : ndarray
    Per-spot residual: measured − predicted broadening (pixels).
`'hkl_used'` : list of tuples
    hkl indices of the spots that entered the fit.
`'n_spots'` : int
    Number of spots used.
`'mode'` : str
    The mode that was used.

ValueError If fewer than 2 spots survive the sensitivity cut.

Note: * Feed the returned 'Sigma_eps' to :func:strain_broadening to verify the fit: the predicted sigma_strain_pix values should match sigma_meas_pix - sigma_instrument (in quadrature). * For mode='diagonal', the system is underdetermined if fewer than 6 spots are available. In that case, prefer mode='isotropic'. * Negative excess variance (sigma_meas < sigma_instrument) is clamped to zero rather than treated as an error.

Example:

Calibrate instrument broadening from a strain-free reference

res_cal = estimate_instrument_broadening(spots_cal, sigma_meas_cal, ... mode='linear_tth')

Measure spot widths from experimental image (e.g. with a 2-D Gaussian fit)

sigma_meas = {(1,1,0): 4.2, (2,0,0): 3.8, (1,1,2): 5.1, ...} J = strain_spot_jacobian(spots, crystal, U, camera)

Pass the calibration result directly — per-spot σ_inst is applied

res = fit_strain_distribution(J, sigma_meas, sigma_instrument=res_cal) print(f"σ_ε = {res['sigma_eps']:.2e}") spots_check = strain_broadening(spots, crystal, U, camera, ... eps_cov=res['Sigma_eps'])

Source code in src/nrxrdct/laue/simulation.py
def fit_strain_distribution(
    jacobians,
    sigma_meas_pix,
    sigma_instrument,
    mode="isotropic",
    min_sensitivity=0.1,
):
    """
    Estimate the strain distribution from measured Laue spot widths (inverse problem).

    Solves for Σ_ε given the measured semi-major broadening of each spot:

    $$
    \\sigma_{\\text{meas},k}^2 = \\sigma_{\\text{inst}}^2
                               + \\lambda_{\\max}(J_k \\, \\Sigma_\\varepsilon \\, J_k^\\top)
    $$
    Two modes are supported:

    **isotropic** — single scalar σ_ε (Σ_ε = σ²I)
        The equation becomes linear in σ²:

        $$
        y_k = \\sigma^2 \\cdot \\lambda_{\\max}(J_k J_k^\\top)
        $$
        Solved by weighted least squares over all spots.

    **diagonal** — six independent variances σᵢ² (Σ_ε = diag(σ₁²,…,σ₆²))
        λ_max is non-linear in σᵢ², so the **trace** is used as a linear proxy:

        $$
        y_k \\approx \\sum_i \\sigma_i^2 \\, \\|J_{k,i}\\|^2
        $$
        (exact when the two eigenvalues of J Σ Jᵀ are equal; conservative
        otherwise, since trace ≥ λ_max).
        Solved by non-negative least squares (:func:`scipy.optimize.nnls`).

    Args:
    jacobians : dict  {(h,k,l): ndarray (2, 6)}
        Output of :func:`strain_spot_jacobian`.
    sigma_meas_pix : dict  {(h,k,l): float}
        Measured semi-major spot width (pixels, 1σ) for each indexed
        reflection, obtained by fitting a 2-D Gaussian to the experimental
        detector image.  Only hkl keys present in both `jacobians` and
        this dict are used.
    sigma_instrument : float or dict or result dict from :func:`estimate_instrument_broadening`
        Instrument broadening (pixels, 1σ), subtracted in quadrature per spot.
        Three forms are accepted:

        * **float** — the same value is applied to all spots.
        * **dict {(h,k,l): float}** — per-spot instrumental width (e.g. the
          `'sigma_per_spot'` entry from :func:`estimate_instrument_broadening`).
        * **result dict** — the full dict returned by
          :func:`estimate_instrument_broadening`; the `'sigma_per_spot'` field
          is extracted automatically.  For spots not covered by the calibrant,
          the scalar `'sigma_instrument'` fallback is used.
    mode : {'isotropic', 'diagonal'}
        Fitting model.  `'isotropic'` fits a single σ_ε;
        `'diagonal'` fits all six Voigt variances independently.
    min_sensitivity : float, optional
        Minimum RMS Jacobian magnitude (px per unit strain) required for a
        spot to be included.  Spots with `sqrt(mean(J**2)) < min_sensitivity`
        are insensitive to strain and are excluded.  Default: 0.1.

    Returns:
    result : dict with keys:

        `'sigma_eps'` : float
            Isotropic RMS strain (scalar).  For `mode='isotropic'` this is
            the direct fit result; for `mode='diagonal'` it is
            `sqrt(mean(eps_voigt_std**2))`.
        `'eps_voigt_std'` : ndarray, shape (6,)
            Per-component standard deviation
            [σ₁₁, σ₂₂, σ₃₃, σ₂₃, σ₁₃, σ₁₂].
            For `mode='isotropic'` all six entries are equal.
        `'Sigma_eps'` : ndarray, shape (6, 6)
            Fitted covariance matrix (diagonal for both modes).
            Pass directly to :func:`strain_broadening` as `eps_cov`.
        `'residuals_pix'` : ndarray
            Per-spot residual: measured − predicted broadening (pixels).
        `'hkl_used'` : list of tuples
            hkl indices of the spots that entered the fit.
        `'n_spots'` : int
            Number of spots used.
        `'mode'` : str
            The mode that was used.

    Raises:
    ValueError
        If fewer than 2 spots survive the sensitivity cut.

    Note:
    * Feed the returned `'Sigma_eps'` to :func:`strain_broadening` to verify
      the fit: the predicted `sigma_strain_pix` values should match
      `sigma_meas_pix - sigma_instrument` (in quadrature).
    * For `mode='diagonal'`, the system is underdetermined if fewer than
      6 spots are available.  In that case, prefer `mode='isotropic'`.
    * Negative excess variance (`sigma_meas < sigma_instrument`) is clamped
      to zero rather than treated as an error.

    Example:
    >>> # Calibrate instrument broadening from a strain-free reference
    >>> res_cal = estimate_instrument_broadening(spots_cal, sigma_meas_cal,
    ...                                          mode='linear_tth')
    >>>
    >>> # Measure spot widths from experimental image (e.g. with a 2-D Gaussian fit)
    >>> sigma_meas = {(1,1,0): 4.2, (2,0,0): 3.8, (1,1,2): 5.1, ...}
    >>> J = strain_spot_jacobian(spots, crystal, U, camera)
    >>>
    >>> # Pass the calibration result directly — per-spot σ_inst is applied
    >>> res = fit_strain_distribution(J, sigma_meas, sigma_instrument=res_cal)
    >>> print(f"σ_ε = {res['sigma_eps']:.2e}")
    >>> spots_check = strain_broadening(spots, crystal, U, camera,
    ...                                 eps_cov=res['Sigma_eps'])
"""
    from scipy.optimize import nnls

    # ── Resolve sigma_instrument → per-spot lookup + scalar fallback ─────────
    if isinstance(sigma_instrument, dict):
        if "sigma_per_spot" in sigma_instrument:
            # Full result dict from estimate_instrument_broadening
            _per_spot = sigma_instrument["sigma_per_spot"]
            _fallback = float(sigma_instrument.get("sigma_instrument", 0.0))
        else:
            # Plain {hkl: float} dict
            _per_spot = sigma_instrument
            _fallback = (
                float(np.median(list(sigma_instrument.values())))
                if sigma_instrument
                else 0.0
            )
    else:
        _per_spot = {}
        _fallback = float(sigma_instrument)

    def _sig_inst(hkl):
        return _per_spot.get(tuple(hkl), _fallback)

    # ── Collect common hkl keys, apply sensitivity filter ────────────────────
    common = set(jacobians.keys()) & set(sigma_meas_pix.keys())

    rows = []  # (hkl, J, sigma_meas, sigma_inst)
    for hkl in common:
        J = jacobians[hkl]
        if J is None or not np.any(J != 0):
            continue
        rms_J = np.sqrt(np.mean(J**2))
        if rms_J < min_sensitivity:
            continue
        rows.append((hkl, J, float(sigma_meas_pix[hkl]), _sig_inst(hkl)))

    if len(rows) < 2:
        raise ValueError(
            f"Only {len(rows)} spot(s) survived the sensitivity cut "
            f"(min_sensitivity={min_sensitivity} px/unit strain). "
            "Lower min_sensitivity or provide more measured spots."
        )

    hkl_used = [r[0] for r in rows]

    # ── Per-spot excess variance: y_k = max(0, σ_meas_k² − σ_inst_k²) ───────
    sig_inst2_arr = np.array([r[3] ** 2 for r in rows])
    y = np.array([max(0.0, r[2] ** 2 - r[3] ** 2) for r in rows])

    Js = [r[1] for r in rows]

    # ── Mode: isotropic ───────────────────────────────────────────────────────
    if mode == "isotropic":
        # y_k = σ² · λ_max(J_k J_kᵀ)
        x = np.array([np.linalg.eigvalsh(J @ J.T).max() for J in Js])
        # Weighted least squares: σ² = (xᵀy) / (xᵀx)
        denom = float(x @ x)
        if denom < 1e-30:
            raise ValueError("All Jacobian sensitivities are zero.")
        sigma_eps2 = max(0.0, float(x @ y) / denom)
        sigma_eps = float(np.sqrt(sigma_eps2))
        eps_voigt_std = np.full(6, sigma_eps)
        Sigma_eps = np.eye(6) * sigma_eps2

        # Residuals
        predicted = np.sqrt(sig_inst2_arr + x * sigma_eps2)
        residuals = np.array([r[2] for r in rows]) - predicted

    # ── Mode: diagonal ────────────────────────────────────────────────────────
    elif mode == "diagonal":
        # y_k ≈ Σᵢ σᵢ² · ‖J_k[:,i]‖²   (trace proxy)
        # A[k, i] = J_k[0,i]² + J_k[1,i]²
        A = np.array([J[0] ** 2 + J[1] ** 2 for J in Js])  # (n_spots, 6)
        v, _ = nnls(A, y)  # v[i] = σᵢ²
        eps_voigt_std = np.sqrt(v)
        Sigma_eps = np.diag(v)
        sigma_eps = float(np.sqrt(np.mean(v)))

        # Residuals (using trace proxy for consistency)
        predicted = np.sqrt(sig_inst2_arr + A @ v)
        residuals = np.array([r[2] for r in rows]) - predicted

    else:
        raise ValueError(f"mode must be 'isotropic' or 'diagonal', got {mode!r}")

    return {
        "sigma_eps": sigma_eps,
        "eps_voigt_std": eps_voigt_std,
        "Sigma_eps": Sigma_eps,
        "residuals_pix": residuals,
        "hkl_used": hkl_used,
        "n_spots": len(rows),
        "mode": mode,
    }

kb_reflectivity

kb_reflectivity(energy_eV, material: str = 'Ir', grazing_angle_mrad: float = 2.8, n_mirrors: int = 2, roughness_ang: float = 3.0) -> float

Fresnel reflectivity of a KB mirror system (s-polarisation, kinematical limit).

Uses the optical constants δ, β of the coating material (via xrayutilities) to compute the critical-angle total-external-reflection profile, with Névot–Croce roughness damping. The result is raised to the power n_mirrors to model paired mirrors.

energy_eV : float Photon energy (eV). material : str Coating material name recognised by xrayutilities (e.g. 'Rh', 'Pt', 'Si'). grazing_angle_mrad : float Nominal grazing incidence angle of each mirror (mrad). n_mirrors : int Number of mirrors in the KB system (typically 2). roughness_ang : float RMS surface roughness (Å). Used in the Névot–Croce factor exp(-(2 k sinθ σ)²).

float Total reflectivity in [0, 1].

Note: The Fresnel reflectivity for s-polarisation is:

$$ r_s = \frac{\sin\theta - \sqrt{n^2 - \cos^2\theta}} {\sin\theta + \sqrt{n^2 - \cos^2\theta}} $$ where \(n = 1 - \delta + i\beta\) and \(\theta\) is the grazing angle. The Névot–Croce roughness correction is applied as:

$$ R_{\text{rough}} = R_{\text{smooth}} \cdot \exp!\left[-(2 k \sin\theta\,\sigma)^2\right] $$ The two KB mirrors are assumed identical, giving \(R_{\text{total}} = R_{\text{single}}^{n_{\text{mirrors}}}\).

Source code in src/nrxrdct/laue/simulation.py
def kb_reflectivity(
    energy_eV,
    material: str = "Ir",
    grazing_angle_mrad: float = 2.8,
    n_mirrors: int = 2,
    roughness_ang: float = 3.0,
) -> float:
    """
    Fresnel reflectivity of a KB mirror system (s-polarisation, kinematical limit).

    Uses the optical constants δ, β of the coating material (via *xrayutilities*)
    to compute the critical-angle total-external-reflection profile, with
    Névot–Croce roughness damping.  The result is raised to the power
    `n_mirrors` to model paired mirrors.

    Args:
    energy_eV : float
        Photon energy (eV).
    material : str
        Coating material name recognised by *xrayutilities*
        (e.g. `'Rh'`, `'Pt'`, `'Si'`).
    grazing_angle_mrad : float
        Nominal grazing incidence angle of each mirror (mrad).
    n_mirrors : int
        Number of mirrors in the KB system (typically 2).
    roughness_ang : float
        RMS surface roughness (Å).  Used in the Névot–Croce factor
        `exp(-(2 k sinθ σ)²)`.

    Returns:
    float
        Total reflectivity in [0, 1].

    Note:
    The Fresnel reflectivity for s-polarisation is:

    $$
    r_s = \\frac{\\sin\\theta - \\sqrt{n^2 - \\cos^2\\theta}}
               {\\sin\\theta + \\sqrt{n^2 - \\cos^2\\theta}}
    $$
    where $n = 1 - \\delta + i\\beta$ and $\\theta$ is the
    grazing angle.  The Névot–Croce roughness correction is applied as:

    $$
    R_{\\text{rough}} = R_{\\text{smooth}} \\cdot
        \\exp\\!\\left[-(2 k \\sin\\theta\\,\\sigma)^2\\right]
    $$
    The two KB mirrors are assumed identical, giving
    $R_{\\text{total}} = R_{\\text{single}}^{n_{\\text{mirrors}}}$.
"""
    import xrayutilities as xu

    theta = grazing_angle_mrad * 1e-3  # rad
    lam_ang = en2lam(energy_eV)  # Å
    k = 2.0 * np.pi / lam_ang  # Å⁻¹

    # Optical constants via xrayutilities
    # xu.materials.Rh is an Element object, which has no delta_beta method.
    # Wrap it in Amorphous (which accepts element name + density) to get δ, β.
    try:
        mat = getattr(xu.materials, material, None)
        if mat is None or not hasattr(mat, "delta_beta"):
            # Element objects don't have delta_beta — create an Amorphous proxy
            elem = getattr(xu.materials.elements, material, None)
            if elem is None:
                return 1.0  # unknown material: assume perfect (no correction)
            density = getattr(elem, "density", None)
            if not density:
                return 1.0
            mat = xu.materials.Amorphous(material, density)
        delta, beta = mat.delta_beta(energy_eV)
    except Exception:
        # If xrayutilities fails for any reason, skip the correction rather
        # than zeroing out all spectral weights (which produces 0 spots).
        return 1.0

    n_sq = (1.0 - delta + 1j * beta) ** 2  # n²

    sin_th = np.sin(theta)
    cos_th = np.cos(theta)

    # sqrt(n² - cos²θ)  — complex
    sq = np.sqrt(n_sq - cos_th**2 + 0j)

    denom = sin_th + sq
    if abs(denom) < 1e-15:
        return 0.0

    r_s = (sin_th - sq) / denom
    R_smooth = float(abs(r_s) ** 2)

    # Névot–Croce roughness factor
    nc = np.exp(-((2.0 * k * sin_th * roughness_ang) ** 2))
    R_single = R_smooth * float(nc)
    R_single = max(0.0, min(1.0, R_single))

    return R_single**n_mirrors

layer_contributions_spots

layer_contributions_spots(spots, stack)

Decompose the intensity of each Laue spot into per-layer contributions.

For each spot the total structure factor is

F_total(Q) = S_rep(Q) · Σ_l F_layer_l(Q)

where S_rep is the geometric factor for bilayer repetitions. Each layer contributes a complex amplitude F_l = S_rep · F_layer_l.

The intensity is decomposed as

I_total = |F_total|² I_l = Re(F_l · F_total*) / |F_total|² × I_total

This is the coherent intensity contribution of layer l. It sums exactly to I_total over all layers (including interference terms): Σ_l Re(F_l · F_total*) = |F_total|²

spots : list of dicts Output of simulate_laue_stack(). Must contain 'G_lab' and 'E' keys (present by default). stack : LayeredCrystal

spots : the same list, each dict extended with: 'layer_F' : dict { label : complex amplitude F_l } 'layer_I' : dict { label : float absolute intensity I_l } 'layer_I_frac' : dict { label : float fraction 0-1 (sums to 1) }

Note: Negative fractions are physically meaningful — they indicate a layer that destructively interferes with the rest of the stack at that Q. The sum over all layers is still exactly 1.

Example:

spots = simulate_laue_stack(stack, camera) spots = layer_contributions_spots(spots, stack) for s in spots[:5]: ... print(s['hkl'], s['layer_I_frac'])

Source code in src/nrxrdct/laue/simulation.py
def layer_contributions_spots(spots, stack):
    """
    Decompose the intensity of each Laue spot into per-layer contributions.

    For each spot the total structure factor is:
        F_total(Q) = S_rep(Q) · Σ_l  F_layer_l(Q)

    where S_rep is the geometric factor for bilayer repetitions.
    Each layer contributes a complex amplitude F_l = S_rep · F_layer_l.

    The intensity is decomposed as:
        I_total = |F_total|²
        I_l     = Re(F_l · F_total*) / |F_total|²  × I_total

    This is the **coherent intensity contribution** of layer l.  It sums
    exactly to I_total over all layers (including interference terms):
        Σ_l  Re(F_l · F_total*) = |F_total|²

    Args:
    spots : list of dicts
        Output of `simulate_laue_stack()`.  Must contain `'G_lab'` and
        `'E'` keys (present by default).
    stack : LayeredCrystal

    Returns:
    spots : the same list, each dict extended with:
        `'layer_F'`      : dict  { label : complex amplitude F_l }
        `'layer_I'`      : dict  { label : float  absolute intensity I_l }
        `'layer_I_frac'` : dict  { label : float  fraction 0-1 (sums to 1) }

    Note:
    Negative fractions are physically meaningful — they indicate a layer
    that **destructively interferes** with the rest of the stack at that Q.
    The sum over all layers is still exactly 1.

    Example:
    >>> spots = simulate_laue_stack(stack, camera)
    >>> spots = layer_contributions_spots(spots, stack)
    >>> for s in spots[:5]:
    ...     print(s['hkl'], s['layer_I_frac'])
"""
    stack = _flatten_if_multiblock(stack)
    stack._update_offsets()
    Lambda = stack._bilayer_thickness
    n_rep = stack.n_rep
    # Hoisted out of the spot loop: `.layers` is a property that rebuilds its
    # list on every access, and a flattened (unrolled) multi-block stack often
    # repeats the same (crystal, U, thickness) many times.
    layers_z0 = list(zip(stack.layers, stack._z_offsets))
    labels = [layer.label for layer in stack.layers]

    for s in spots:
        Q = np.asarray(s["G_lab"], dtype=float)
        E = float(s["E"])
        Qz = Q[2]

        # Geometric repetition factor S_rep
        phi_rep = Qz * Lambda
        phi_mod = phi_rep % (2.0 * np.pi)
        if abs(phi_mod) < 1e-10 or abs(phi_mod - 2 * np.pi) < 1e-10:
            S_rep = float(n_rep) + 0j
        else:
            S_rep = (1.0 - np.exp(1j * n_rep * phi_rep)) / (
                1.0 - np.exp(1j * phi_rep)
            )

        # Per-layer amplitude (including S_rep).  structure_factor(Q, E, z0)
        # factors exactly as F0(Q, E) * exp(i * Qn * z0), so layer instances
        # sharing the same (crystal, U, thickness) -- e.g. repeated bilayers
        # from an unrolled multi-block stack -- can reuse one F0/Qn evaluation
        # instead of recomputing the (relatively expensive) crystal structure
        # factor for every repetition.
        f0_cache = {}
        layer_F = {}
        for layer, z0 in layers_z0:
            key = (id(layer.crystal), layer.U.tobytes(), layer.thickness)
            cached = f0_cache.get(key)
            if cached is None:
                F0 = layer.structure_factor(Q, E, z0=0.0)
                Qn = float(np.dot(Q, layer.n_hat))
                cached = (F0, Qn)
                f0_cache[key] = cached
            F0, Qn = cached
            F_l = F0 * np.exp(1j * Qn * z0) * S_rep
            lbl = layer.label
            layer_F[lbl] = layer_F.get(lbl, 0j) + F_l

        # Total F (should match s['F2'] ** 0.5 up to LP/spectrum)
        F_total = sum(layer_F.values())
        F2_total = abs(F_total) ** 2

        # Coherent intensity fractions
        if F2_total > 1e-30:
            layer_I_frac = {
                lbl: float((F * F_total.conjugate()).real / F2_total)
                for lbl, F in layer_F.items()
            }
        else:
            layer_I_frac = {lbl: 0.0 for lbl in layer_F}

        # Absolute per-layer intensities (×LP×S for comparison with spots)
        I_total = s["I_raw"]
        layer_I = {lbl: frac * I_total for lbl, frac in layer_I_frac.items()}

        s["layer_F"] = layer_F
        s["layer_I"] = layer_I
        s["layer_I_frac"] = layer_I_frac

    return spots

lorentz_pol

lorentz_pol(tth_deg, energy_eV=None, chi_deg=None)

Lorentz–polarisation factor.

When energy_eV is supplied the correct Laue (polychromatic, stationary-crystal) peak-intensity formula is used::

LP = P · λ² / sin(2θ),   λ = hc/E

The polarisation factor P depends on the beam polarisation state:

  • chi_deg given — exact formula for horizontal synchrotron polarisation (ê_pol = lab y)::

    P = 1 − sin²(2θ) · sin²(χ)

where χ = arctan2(k_f,y, k_f,z) is the azimuthal angle of the diffracted beam (0° = vertical, 90° = horizontal). Ranges from cos²(2θ) (horizontal scatter) to 1 (vertical scatter).

  • chi_deg not given — unpolarised approximation::

    P = (1 + cos²2θ) / 2

This equals the azimuthal average of the exact formula and is adequate when spot positions cover the full azimuthal range symmetrically, but wrong by up to ~30% for individual spots near the horizontal or vertical planes.

Without energy_eV the rotating-crystal formula is returned::

LP = (1 + cos²2θ) / (2 sin²θ cosθ)
Source code in src/nrxrdct/laue/simulation.py
def lorentz_pol(tth_deg, energy_eV=None, chi_deg=None):
    r"""Lorentz–polarisation factor.

    When *energy_eV* is supplied the correct **Laue** (polychromatic,
    stationary-crystal) peak-intensity formula is used::

        LP = P · λ² / sin(2θ),   λ = hc/E

    The polarisation factor *P* depends on the beam polarisation state:

    * *chi_deg* given — exact formula for **horizontal** synchrotron
      polarisation (ê_pol = lab y)::

          P = 1 − sin²(2θ) · sin²(χ)

      where χ = arctan2(k_f,y, k_f,z) is the azimuthal angle of the
      diffracted beam (0° = vertical, 90° = horizontal).  Ranges from
      ``cos²(2θ)`` (horizontal scatter) to ``1`` (vertical scatter).

    * *chi_deg* not given — unpolarised approximation::

          P = (1 + cos²2θ) / 2

      This equals the azimuthal average of the exact formula and is
      adequate when spot positions cover the full azimuthal range
      symmetrically, but wrong by up to ~30% for individual spots near
      the horizontal or vertical planes.

    Without *energy_eV* the rotating-crystal formula is returned::

        LP = (1 + cos²2θ) / (2 sin²θ cosθ)
    """
    r = np.radians(tth_deg)
    if energy_eV is not None:
        if chi_deg is not None:
            P = 1.0 - (np.sin(r) * np.sin(np.radians(chi_deg))) ** 2
        else:
            P = (1.0 + np.cos(r) ** 2) * 0.5
        lam = 12398.419843 / float(energy_eV)
        sin2th = abs(float(np.sin(r)))
        return float(P * lam ** 2 / sin2th) if sin2th >= 1e-8 else 0.0
    s, c = np.sin(r / 2), np.cos(r / 2)
    if abs(s) < 1e-8 or abs(c) < 1e-8:
        return 0.0
    return abs((1 + np.cos(r) ** 2) / (2 * s**2 * c))

map_to_fundamental_zone

map_to_fundamental_zone(U: ndarray, symmetry: str = 'cubic') -> np.ndarray

Map orientation matrix/matrices to the fundamental zone.

For each input rotation the symmetry-equivalent member with the smallest rotation angle from the identity is selected. Only proper rotations (det = +1) from the crystal point group are considered, so every output matrix is a valid rotation matrix.

The equivalent is chosen by right-multiplication: U_fz = U @ ops[s*] where s* = argmax trace(U @ ops[s]). Maximising the trace is equivalent to minimising the geodesic angle to the identity, consistent with the convention used in :func:disorientation.

Parameters:
  • U ((3, 3) or (..., 3, 3) ndarray) –

    Rotation matrix/matrices. Any number of leading batch dimensions is supported.

  • symmetry (str, default: 'cubic' ) –

    Crystal point-group symmetry. One of 'cubic' (24 proper rotations), 'hexagonal' (12), 'tetragonal' (8), 'orthorhombic' (4).

Returns:
  • U_fz( same shape as *U*, float64 ) –

    Orientation matrices reduced to the fundamental zone.

Example::

U_fz = map_to_fundamental_zone(U_raw, symmetry='cubic')
Source code in src/nrxrdct/laue/simulation.py
def map_to_fundamental_zone(
    U: "np.ndarray",
    symmetry: str = "cubic",
) -> "np.ndarray":
    """
    Map orientation matrix/matrices to the fundamental zone.

    For each input rotation the symmetry-equivalent member with the smallest
    rotation angle from the identity is selected.  Only **proper rotations**
    (det = +1) from the crystal point group are considered, so every output
    matrix is a valid rotation matrix.

    The equivalent is chosen by right-multiplication:
    ``U_fz = U @ ops[s*]``  where  ``s* = argmax trace(U @ ops[s])``.
    Maximising the trace is equivalent to minimising the geodesic angle to
    the identity, consistent with the convention used in
    :func:`disorientation`.

    Args:
        U ((3, 3) or (..., 3, 3) ndarray): Rotation matrix/matrices.
            Any number of leading batch dimensions is supported.
        symmetry (str): Crystal point-group symmetry.  One of ``'cubic'``
            (24 proper rotations), ``'hexagonal'`` (12), ``'tetragonal'``
            (8), ``'orthorhombic'`` (4).

    Returns:
        U_fz (same shape as *U*, float64): Orientation matrices reduced to
            the fundamental zone.

    Example::

        U_fz = map_to_fundamental_zone(U_raw, symmetry='cubic')
    """
    ops = _symmetry_ops_np(symmetry)   # (N_sym, 3, 3)  proper rotations only

    U = np.asarray(U, dtype=float)
    shape = U.shape
    U_flat = U.reshape(-1, 3, 3)      # (M, 3, 3)

    # Project to nearest SO(3) element via SVD so that non-orthogonal inputs
    # (e.g. U_eff = U @ (I + ε) from strain fits) are handled correctly.
    U_flat = Rotation.from_matrix(U_flat).as_matrix()

    # All equivalents: U_equiv[s, m] = U_flat[m] @ ops[s]
    # U_flat[None]: (1, M, 3, 3)  ops[:, None]: (N_sym, 1, 3, 3)
    U_equiv = U_flat[None] @ ops[:, None]               # (N_sym, M, 3, 3)

    # Trace of each equivalent — maximise ↔ minimise angle to identity
    traces = U_equiv[:, :, 0, 0] + U_equiv[:, :, 1, 1] + U_equiv[:, :, 2, 2]  # (N_sym, M)
    best   = np.argmax(traces, axis=0)                  # (M,)

    # Gather: U_fz[m] = U_flat[m] @ ops[best[m]]
    ops_sel = ops[best]                                 # (M, 3, 3)
    U_fz    = np.einsum("...ij,...jk->...ik", U_flat, ops_sel)  # (M, 3, 3)
    return U_fz.reshape(shape)

measure_spot_widths

measure_spot_widths(spots, meas, window: int = 9)

Fit a 2-D Gaussian to each simulated spot position in a detector image and return the measured 1σ widths as a dict compatible with :func:estimate_instrument_broadening.

spots : list of dicts Spot list from any simulate_laue* function. Required keys: 'hkl', 'pix' (pixel position as (xcam, ycam)). meas : ndarray, shape (Nv, Nh) Detector image (raw counts). window : int Half-width of the fitting sub-window in pixels. A 2*window × 2*window patch centred on each spot is extracted for the Gaussian fit. Default: 9.

sigma_meas_pix : dict {(h, k, l): float} Measured 1σ spot width in pixels (mean of σ_x and σ_y from the 2-D Gaussian fit) for each indexed reflection. Spots whose fit fails or whose window falls outside the detector are silently skipped. Pass directly to :func:estimate_instrument_broadening as sigma_meas_pix.

Source code in src/nrxrdct/laue/simulation.py
def measure_spot_widths(
    spots,
    meas,
    window: int = 9,
):
    """
    Fit a 2-D Gaussian to each simulated spot position in a detector image
    and return the measured 1σ widths as a dict compatible with
    :func:`estimate_instrument_broadening`.

    Args:
    spots : list of dicts
        Spot list from any `simulate_laue*` function.
        Required keys: `'hkl'`, `'pix'` (pixel position as (xcam, ycam)).
    meas : ndarray, shape (Nv, Nh)
        Detector image (raw counts).
    window : int
        Half-width of the fitting sub-window in pixels.  A `2*window × 2*window`
        patch centred on each spot is extracted for the Gaussian fit.
        Default: 9.

    Returns:
    sigma_meas_pix : dict  {(h, k, l): float}
        Measured 1σ spot width in pixels (mean of σ_x and σ_y from the
        2-D Gaussian fit) for each indexed reflection.
        Spots whose fit fails or whose window falls outside the detector are
        silently skipped.
        Pass directly to :func:`estimate_instrument_broadening` as
        `sigma_meas_pix`.
"""
    from .segmentation import auto_init_gaussian_mixture_global, fit_gaussian_mixture_2d

    meas = np.asarray(meas)
    nv, nh = meas.shape
    sigma_meas_pix = {}

    for spot in spots:
        hkl = spot.get("hkl")
        pix = spot.get("pix")
        if hkl is None or pix is None:
            continue

        key = tuple(int(x) for x in hkl)
        xcen, ycen = round(pix[0]), round(pix[1])

        # Skip spots whose window would reach outside the detector
        if (ycen - window < 0 or ycen + window >= nv
                or xcen - window < 0 or xcen + window >= nh):
            continue

        pk = meas[ycen - window: ycen + window,
                  xcen - window: xcen + window]

        try:
            init = auto_init_gaussian_mixture_global(pk, n_components=1)
            popt = fit_gaussian_mixture_2d(pk, 1, init)[0]
            sigma_x, sigma_y = popt[3], popt[4]
            sigma_meas_pix[key] = float(np.mean([sigma_x, sigma_y]))
        except Exception:
            continue

    return sigma_meas_pix

precompute_allowed_hkl

precompute_allowed_hkl(crystal, E_max_eV: float = E_MAX_eV, E_ref_eV: float | None = None, f2_thresh: float = F2_THRESHOLD) -> frozenset

Return the frozenset of (h, k, l) tuples whose structure factor exceeds f2_thresh at a single reference energy.

Enumerates candidate (h, k, l) reflections using a physically correct sphere criterion: only reflections with |G_hkl| ≤ G_max are considered, where G_max = 4π · E_max_eV / 12398.4 Å⁻¹ (back-reflection limit). This correctly handles anisotropic unit cells (e.g. hexagonal with large c/a) by computing per-axis index limits from the reciprocal lattice parameters.

The result can then be passed as allowed_hkl to :func:simulate_laue or :func:simulate_laue_stack to skip all per-spot structure factor calls during fitting while still respecting systematic absences.

For a :class:~nrxrdct.laue.layers.LayeredCrystal, the union of allowed sets across all unique constituent crystals is returned.

Args: crystal : Crystal or LayeredCrystal E_max_eV : float Maximum photon energy (eV) that controls the enumeration cutoff via G_max = 4π·E_max_eV/12398.4. Default: E_MAX_eV. E_ref_eV : float Reference photon energy (eV) for structure factor evaluation. Defaults to the midpoint of the default energy window (E_MIN_eV + E_MAX_eV) / 2. Must be a valid energy within the Henke table range. f2_thresh : float Same threshold used in the simulation.

frozenset of (int, int, int) Immutable, hashable set; safe to share across threads.

Source code in src/nrxrdct/laue/simulation.py
def precompute_allowed_hkl(
    crystal,
    E_max_eV: float = E_MAX_eV,
    E_ref_eV: float | None = None,
    f2_thresh: float = F2_THRESHOLD,
) -> frozenset:
    """
    Return the frozenset of (h, k, l) tuples whose structure factor exceeds
    `f2_thresh` at a single reference energy.

    Enumerates candidate (h, k, l) reflections using a physically correct
    sphere criterion: only reflections with |G_hkl| ≤ G_max are considered,
    where G_max = 4π · E_max_eV / 12398.4 Å⁻¹ (back-reflection limit).
    This correctly handles anisotropic unit cells (e.g. hexagonal with large
    c/a) by computing per-axis index limits from the reciprocal lattice
    parameters.

    The result can then be passed as `allowed_hkl` to :func:`simulate_laue`
    or :func:`simulate_laue_stack` to skip all per-spot structure factor calls
    during fitting while still respecting systematic absences.

    For a :class:`~nrxrdct.laue.layers.LayeredCrystal`, the union of allowed
    sets across all unique constituent crystals is returned.

    Args:
    crystal   : Crystal or LayeredCrystal
    E_max_eV  : float   Maximum photon energy (eV) that controls the
                        enumeration cutoff via G_max = 4π·E_max_eV/12398.4.
                        Default: `E_MAX_eV`.
    E_ref_eV  : float   Reference photon energy (eV) for structure factor
                        evaluation.  Defaults to the midpoint of the default
                        energy window `(E_MIN_eV + E_MAX_eV) / 2`.
                        Must be a valid energy within the Henke table range.
    f2_thresh : float   Same threshold used in the simulation.

    Returns:
    frozenset of (int, int, int)
        Immutable, hashable set; safe to share across threads.
"""
    from .layers import LayeredCrystal

    # Resolve default before building the cache key so that None and the
    # explicit midpoint value always hit the same cache entry.
    if E_ref_eV is None:
        E_ref_eV = (E_MIN_eV + E_MAX_eV) / 2.0

    if type(crystal).__name__ == "LayeredCrystal":
        _lc_key = (
            tuple(sorted({l.crystal.name for l in crystal.all_layers})),
            E_max_eV, E_ref_eV, f2_thresh,
        )
        if _lc_key in _allowed_hkl_cache:
            return _allowed_hkl_cache[_lc_key]
        allowed: set = set()
        seen_names: set = set()
        for layer in crystal.all_layers:
            if layer.crystal.name not in seen_names:
                seen_names.add(layer.crystal.name)
                allowed |= precompute_allowed_hkl(
                    layer.crystal, E_max_eV=E_max_eV, E_ref_eV=E_ref_eV,
                    f2_thresh=f2_thresh
                )
        result = frozenset(allowed)
        _allowed_hkl_cache[_lc_key] = result
        return result

    _key = (crystal.name, E_max_eV, E_ref_eV, f2_thresh)
    if _key in _allowed_hkl_cache:
        return _allowed_hkl_cache[_key]

    HC_eV_ANG = 12398.4
    G_max = 4.0 * np.pi * E_max_eV / HC_eV_ANG
    G_max_sq = G_max ** 2

    # Build the reciprocal-lattice matrix B (columns = a*, b*, c* in Å⁻¹).
    # Q(h,k,l) = B @ [h,k,l] by linearity, so we can replace (2·h_lim+1)³
    # individual crystal.Q calls with three calls + one numpy matmul.
    B = np.column_stack([crystal.Q(1, 0, 0), crystal.Q(0, 1, 0), crystal.Q(0, 0, 1)])
    a_star = float(np.linalg.norm(B[:, 0]))
    b_star = float(np.linalg.norm(B[:, 1]))
    c_star = float(np.linalg.norm(B[:, 2]))
    h_lim = int(G_max / a_star) + 1
    k_lim = int(G_max / b_star) + 1
    l_lim = int(G_max / c_star) + 1

    # Generate the full bounding-box grid and filter to the sphere in one pass.
    h_vals = np.arange(-h_lim, h_lim + 1, dtype=np.int32)
    k_vals = np.arange(-k_lim, k_lim + 1, dtype=np.int32)
    l_vals = np.arange(-l_lim, l_lim + 1, dtype=np.int32)
    H, K, L = np.meshgrid(h_vals, k_vals, l_vals, indexing="ij")
    hkl_all = np.column_stack([H.ravel(), K.ravel(), L.ravel()])

    # Remove (0, 0, 0)
    hkl_all = hkl_all[np.any(hkl_all != 0, axis=1)]

    # Single matmul replaces N individual crystal.Q calls.
    G_all = (B @ hkl_all.T).T          # (N, 3)
    G_sq  = np.einsum("ij,ij->i", G_all, G_all)  # (N,) squared norms

    # Sphere filter: only keep |G| ≤ G_max.
    in_sphere = G_sq <= G_max_sq
    hkl_sphere = hkl_all[in_sphere]
    G_sphere   = G_all[in_sphere]

    F2_arr = np.abs(crystal.StructureFactorForQ(G_sphere, en0=E_ref_eV)) ** 2
    mask   = F2_arr >= f2_thresh
    result = frozenset(map(tuple, hkl_sphere[mask].tolist()))
    _allowed_hkl_cache[_key] = result
    return result

print_absorption_table

print_absorption_table(stack, energy_eV=None, E_min_eV=None, E_max_eV=None)

Print the linear absorption coefficient μ (Å⁻¹) and absorption length 1/μ (μm) for every layer in stack at the given energy (or range).

Useful for diagnosing whether the automatic μ lookup succeeds for all materials and for choosing manual layer.mu_Ang overrides.

Parameters:
  • stack –

    :class:~nrxrdct.laue.layers.LayeredCrystal stack.

  • energy_eV –

    Photon energy in eV (float or list). If None, uses the midpoint of [E_min_eV, E_max_eV].

  • E_min_eV, E_max_eV –

    Energy range; only used when energy_eV is None. Defaults to 5 000 and 27 000 eV.

Source code in src/nrxrdct/laue/simulation.py
def print_absorption_table(stack, energy_eV=None, E_min_eV=None, E_max_eV=None):
    """
    Print the linear absorption coefficient μ (Å⁻¹) and absorption length
    1/μ (μm) for every layer in *stack* at the given energy (or range).

    Useful for diagnosing whether the automatic μ lookup succeeds for all
    materials and for choosing manual ``layer.mu_Ang`` overrides.

    Args:
        stack: :class:`~nrxrdct.laue.layers.LayeredCrystal` stack.
        energy_eV: Photon energy in eV (float or list).  If ``None``, uses
            the midpoint of ``[E_min_eV, E_max_eV]``.
        E_min_eV, E_max_eV: Energy range; only used when *energy_eV* is
            ``None``.  Defaults to 5 000 and 27 000 eV.
    """
    if energy_eV is None:
        lo = E_min_eV or 5_000
        hi = E_max_eV or 27_000
        energies = [0.5 * (lo + hi)]
    elif np.isscalar(energy_eV):
        energies = [float(energy_eV)]
    else:
        energies = list(energy_eV)

    stack._update_offsets()
    all_layers = stack.all_layers
    depths_mm = _layer_depths_mm(stack)

    print(f"{'Layer':<30}  {'t (Å)':>10}  {'depth (μm)':>10}", end="")
    for E in energies:
        print(f"  {'μ @ '+f'{E/1000:.1f}keV':>14}  {'1/μ (μm)':>10}", end="")
    print()
    print("-" * (55 + len(energies) * 27))

    for lyr in reversed(all_layers):   # surface → substrate order
        depth_um = depths_mm.get(id(lyr), 0.0) * 1e4
        row = f"{lyr.label:<30}  {lyr.thickness:>10.1f}  {depth_um:>10.2f}"
        for E in energies:
            mu = lyr._linear_mu(E)
            if mu > 0:
                row += f"  {mu:>12.3e} Å⁻¹  {1e-4/mu:>10.2f}"
            else:
                row += f"  {'(no data)':>14}  {'—':>10}"
        print(row)

print_hkl_family

print_hkl_family(spots: list, h: int, k: int, l: int, n: int = 5) -> None

Print all spots whose Miller indices are integer multiples of (h, k, l).

Searches for spots with hkl = m*(h, k, l) for m = 1, 2, …, n, covering both positive and negative orders (m and -m).

spots : list[dict] Spot list from any simulate_laue* function. h, k, l : int Base Miller indices of the family. n : int Highest multiple to include (default 5). Checks ±1·hkl … ±n·hkl.

Source code in src/nrxrdct/laue/simulation.py
def print_hkl_family(spots: list, h: int, k: int, l: int, n: int = 5) -> None:
    """
    Print all spots whose Miller indices are integer multiples of (h, k, l).

    Searches for spots with hkl = m*(h, k, l) for m = 1, 2, …, n, covering
    both positive and negative orders (m and -m).

    Args:
    spots : list[dict]
        Spot list from any `simulate_laue*` function.
    h, k, l : int
        Base Miller indices of the family.
    n : int
        Highest multiple to include (default 5).  Checks ±1·hkl … ±n·hkl.
"""
    h0, k0, l0 = int(h), int(k), int(l)
    targets = set()
    for m in range(1, n + 1):
        targets.add(( m * h0,  m * k0,  m * l0))
        targets.add((-m * h0, -m * k0, -m * l0))

    matches = [s for s in spots if tuple(int(x) for x in s["hkl"]) in targets]
    matches.sort(key=lambda s: (
        abs(round(s["hkl"][0] / h0)) if h0 else
        abs(round(s["hkl"][1] / k0)) if k0 else
        abs(round(s["hkl"][2] / l0)),
        s["tth"],
    ))

    title = f"({h0:+d}{k0:+d}{l0:+d}) family  [multiples 1 … {n}]"
    print(f"\n  ── {title} ──  ({len(matches)} spots found)")
    if not matches:
        return

    print(
        f"  {'hkl':^10} {'E(keV)':>7} {'lambda(A)':>9} {'2th(deg)':>9} "
        f"{'az(deg)':>8} {'col':>6} {'row':>6} "
        f"{'|F|^2':>8} {'LP':>7} {'S(E)':>7} {'I_raw':>11} {'I/Imax':>7}  satellite"
    )
    print("  " + "-" * 124)
    for s in matches:
        hh, kk, ll = s["hkl"]
        c, r = s["pix"]
        order = s.get("satellite_order", 0)
        sat_col = f"m={order:+d}" if order != 0 else "—"
        print(
            f"  ({hh:+2d}{kk:+2d}{ll:+2d})  "
            f"{s['E']/1e3:7.3f}  {s['lambda']:9.5f}  "
            f"{s['tth']:9.3f}  {s['az']:8.2f}  "
            f"{c:6.0f}  {r:6.0f}  "
            f"{s['F2']:8.2f}  {s['LP']:7.4f}  "
            f"{s['sw']:7.4f}  {s['I_raw']:11.3e}  {s['intensity']:7.4f}  {sat_col:>9s}"
        )

print_layer_contributions

print_layer_contributions(spots, n=15)

Pretty-print per-layer intensity contributions for the top N spots. Requires layer_contributions_spots() to have been called first.

Source code in src/nrxrdct/laue/simulation.py
def print_layer_contributions(spots, n=15):
    """
    Pretty-print per-layer intensity contributions for the top N spots.
    Requires `layer_contributions_spots()` to have been called first.
"""
    if not spots or "layer_I_frac" not in spots[0]:
        raise ValueError("Call layer_contributions_spots(spots, stack) first.")

    labels = list(spots[0]["layer_I_frac"].keys())
    col_w = max(12, max(len(l) for l in labels))

    header = (
        f"  {'phase':12s} {'hkl':^10} {'order':>6} {'satellite':>10} "
        f"{'E(keV)':>7} {'2th':>6} {'I_raw':>11} {'I/Imax':>7}  "
        + "  ".join(f"{l[:col_w]:>{col_w}}" for l in labels)
    )
    print(f"\n  Per-layer intensity fractions  (top {n} spots)")
    print("  " + "─" * len(header))
    print(header)
    print("  " + "─" * len(header))

    for s in spots[:n]:
        h, k, l = s["hkl"]
        order = s.get("satellite_order", 0)
        sat_tag = f"m={order:+d}" if order != 0 else "—"
        fracs = "  ".join(
            f"{s['layer_I_frac'].get(lbl, 0.)*100:>{col_w}.1f}%" for lbl in labels
        )
        print(
            f"  {s['phase_label']:12s} ({h:+d}{k:+d}{l:+d})  "
            f"{order:>6d} {sat_tag:>10s} "
            f"{s['E']/1e3:7.3f} {s['tth']:6.1f} "
            f"{s['I_raw']:11.3e} {s['intensity']:7.4f}  {fracs}"
        )

print_mixed_summary

print_mixed_summary(spots, top_n=20)

Print a summary table of the strongest spots in a mixed-phase pattern, grouped by phase.

Args: spots : list of dicts from simulate_mixed_phases() top_n : int number of strongest spots to list per phase

Source code in src/nrxrdct/laue/simulation.py
def print_mixed_summary(spots, top_n=20):
    """
    Print a summary table of the strongest spots in a mixed-phase pattern,
    grouped by phase.

    Args:
    spots : list of dicts from `simulate_mixed_phases()`
    top_n : int  number of strongest spots to list per phase
"""
    from collections import defaultdict

    import numpy as np

    # Group by phase
    by_phase = defaultdict(list)
    for s in spots:
        by_phase[s["phase_label"]].append(s)

    print(f"\n  Mixed-phase Laue spot summary")
    print(f"  Total spots: {len(spots)}")

    for label, phase_spots in by_phase.items():
        f = phase_spots[0]["volume_fraction"]
        w = phase_spots[0]["phase_weight"]
        print(
            f"\n  ── {label}  (f={f:.3f}  weight={w:.6f})"
            f"  –  {len(phase_spots)} spots ──"
        )
        print(
            f"  {'hkl':^10} {'E(keV)':>7} {'2th':>7} {'chi':>7} "
            f"{'I_raw':>11} {'I/Imax':>8} {'I_phase':>8}  type"
        )
        print("  " + "─" * 82)
        top = sorted(phase_spots, key=lambda s: s["intensity"], reverse=True)
        for s in top[:top_n]:
            h, k, l = s["hkl"]
            print(
                f"  ({h:+d}{k:+d}{l:+d})  "
                f"{s['E']/1e3:7.3f} {s['tth']:7.2f} {s['chi']:7.2f} "
                f"{s['I_raw']:11.3e} {s['intensity']:8.4f} {s.get('intensity_phase',0):8.4f}"
            )

project_to_detector

project_to_detector(vol_or_vols, *, pad_px=20, camera=None, exclude_bragg_along=None)

Bin Q-space voxel intensities onto detector pixel coordinates.

Each on-detector voxel is rounded to its nearest integer pixel and its intensity vol["I"] accumulated there, producing a 2-D array directly comparable to a measured photon-counting image (modulo absolute scaling). No detector physics (noise, efficiency, point-spread function) is modelled.

When multiple volumes are supplied (e.g. the list returned by :func:qspace_per_layer) their intensities are summed onto the same pixel grid so the result contains contributions from all layers at once.

Parameters:
  • vol_or_vols –

    A single vol dict from :func:qspace_around_spot, or a list of such dicts (e.g. from :func:qspace_per_layer).

  • pad_px –

    Extra margin (pixels) around the bounding box. Only used when camera is None.

  • camera –

    :class:~nrxrdct.laue.camera.Camera instance. When given, allocates a full (Nv, Nh) detector array; otherwise returns a cropped patch whose bounding box is the union of all volumes.

  • exclude_bragg_along –

    float or None. When set, voxels with |along| < exclude_bragg_along (Å⁻¹) are excluded from the projection. Use this to suppress the kinematical Bragg peak, which is orders of magnitude brighter than superlattice satellites in the kinematical approximation (no extinction) and would otherwise dominate the colour scale. A value of roughly half the smallest satellite spacing (π/Λ) keeps the satellite peaks while removing the central Bragg spike.

Returns:
  • –

    tuple (image, x0, y0) where image is a float64 ndarray of

  • –

    shape (Ny, Nx), and (x0, y0) is the pixel coordinate of the

  • –

    patch's top-left corner in the full detector frame (both 0 when

  • –

    camera is given). Extract the matching patch from a measured image

  • –

    with meas[y0:y0+Ny, x0:x0+Nx].

Source code in src/nrxrdct/laue/simulation.py
def project_to_detector(vol_or_vols, *, pad_px=20, camera=None,
                        exclude_bragg_along=None):
    """
    Bin Q-space voxel intensities onto detector pixel coordinates.

    Each on-detector voxel is rounded to its nearest integer pixel and its
    intensity ``vol["I"]`` accumulated there, producing a 2-D array directly
    comparable to a measured photon-counting image (modulo absolute scaling).
    No detector physics (noise, efficiency, point-spread function) is modelled.

    When multiple volumes are supplied (e.g. the list returned by
    :func:`qspace_per_layer`) their intensities are summed onto the same
    pixel grid so the result contains contributions from all layers at once.

    Args:
        vol_or_vols: A single vol dict from :func:`qspace_around_spot`, or a
            list of such dicts (e.g. from :func:`qspace_per_layer`).
        pad_px: Extra margin (pixels) around the bounding box.  Only used when
            *camera* is ``None``.
        camera: :class:`~nrxrdct.laue.camera.Camera` instance.  When given,
            allocates a full ``(Nv, Nh)`` detector array; otherwise returns a
            cropped patch whose bounding box is the union of all volumes.
        exclude_bragg_along: float or None.  When set, voxels with
            ``|along| < exclude_bragg_along`` (Å⁻¹) are excluded from the
            projection.  Use this to suppress the kinematical Bragg peak,
            which is orders of magnitude brighter than superlattice satellites
            in the kinematical approximation (no extinction) and would
            otherwise dominate the colour scale.  A value of roughly half the
            smallest satellite spacing (``π/Λ``) keeps the satellite peaks
            while removing the central Bragg spike.

    Returns:
        tuple ``(image, x0, y0)`` where *image* is a ``float64`` ndarray of
        shape ``(Ny, Nx)``, and ``(x0, y0)`` is the pixel coordinate of the
        patch's top-left corner in the full detector frame (both 0 when
        *camera* is given).  Extract the matching patch from a measured image
        with ``meas[y0:y0+Ny, x0:x0+Nx]``.
    """
    if isinstance(vol_or_vols, dict):
        vols_list = [vol_or_vols]
    else:
        vols_list = list(vol_or_vols)

    # Validate and gather pixel/intensity arrays from every volume
    all_px, all_py, all_I = [], [], []
    for vol in vols_list:
        pix = vol["pix"]
        on_det = vol["on_detector"]
        if pix is None or on_det is None:
            raise ValueError(
                "vol does not contain pixel coordinates — rerun "
                "qspace_around_spot with a camera= argument."
            )
        on_det = on_det.copy()
        if exclude_bragg_along is not None:
            # Build a per-voxel mask in the (n_along, n_lat, n_lat) grid.
            # vol["along"] has shape (n_along,); broadcast over lateral dims.
            along_3d = vol["along"][:, None, None] * np.ones_like(vol["I"])
            on_det &= np.abs(along_3d) >= float(exclude_bragg_along)
        pix_x = pix[..., 0][on_det]
        pix_y = pix[..., 1][on_det]
        all_px.append(np.round(pix_x).astype(int))
        all_py.append(np.round(pix_y).astype(int))
        all_I.append(vol["I"][on_det])

    px_i = np.concatenate(all_px)
    py_i = np.concatenate(all_py)
    I_on = np.concatenate(all_I)

    if camera is not None:
        Nh, Nv = int(camera.Nh), int(camera.Nv)
        valid = (px_i >= 0) & (px_i < Nh) & (py_i >= 0) & (py_i < Nv)
        det = np.zeros((Nv, Nh), dtype=float)
        np.add.at(det, (py_i[valid], px_i[valid]), I_on[valid])
        return det, 0, 0

    if len(px_i) == 0:
        return np.zeros((1, 1), dtype=float), 0, 0

    x0 = max(int(px_i.min()) - pad_px, 0)
    y0 = max(int(py_i.min()) - pad_px, 0)
    x1 = int(px_i.max()) + pad_px + 1
    y1 = int(py_i.max()) + pad_px + 1

    det = np.zeros((y1 - y0, x1 - x0), dtype=float)
    np.add.at(det, (py_i - y0, px_i - x0), I_on)
    return det, x0, y0

qspace_around_spot

qspace_around_spot(stack, hkl, layer=None, *, n_along=301, n_lateral=7, extent_along=None, extent_lateral=None, max_satellites=6, pin_satellites=True, spot_only=False, camera=None, E_min_eV=E_MIN_eV, E_max_eV=E_MAX_eV, source='bending_magnet', source_kwargs=None, kb_params=BM32_KB, ki_hat=None, structure_model='coherent', darwin=False, correct_depth=False, energy_ref_eV=None, verbose=True)

Reconstruct the 3-D reciprocal-space intensity distribution around one Bragg spot of a LayeredCrystal stack, and (optionally) the detector pixel/energy each voxel maps to.

This generalises the discrete thickness-fringe/satellite construction used internally by :func:simulate_laue_stack (which only evaluates a handful of points at G0 + m * q_fringe * n_hat) into a continuous 3-D grid, so the full rod shape and any off-axis behaviour can be inspected directly.

Grid geometry

The grid is built in a local orthonormal frame centred on G0 = layer.U @ layer.crystal.Q(*hkl):

  • one axis along layer.n_hat (the stack growth direction) — sampled finely, since finite-thickness fringes and superlattice satellites are only a function of Q · n_hat in this kinematical model;
  • two axes transverse to n_hat (arbitrary orthonormal in-plane directions) — sampled coarsely, since the structure factor of this model has no lateral interference structure and only varies smoothly there.

Physical intensity per voxel

For every voxel Q = G0 + Δ, the elastic (Laue) condition is solved for the unique photon energy that would excite it:

\[ E(Q) = hc \,\big/\, \lambda(Q), \qquad \lambda(Q) = -\frac{4\pi\,(\hat k_i \cdot Q)}{|Q|^2} \]

Voxels with \hat k_i \cdot Q \geq 0 or E(Q) outside [E_min_eV, E_max_eV] are marked unreachable (I2 = 0, E = NaN). For reachable voxels the diffracted direction kf_hat follows directly, and the structure factor is evaluated there — the plain kinematical stack sum (stack.structure_factor / stack.average_structure_factor, per structure_model) by default, or the Darwin (dynamical, extinction-saturated) amplitude when darwin=True — giving the same F2 · LP · S(E) intensity convention used throughout this module either way. Only the intensity depends on this choice; voxel positions are exact geometry regardless (see darwin below).

Detector intersection

If camera is given, every voxel's kf_hat is projected onto the detector (camera.project_batch), so the returned pix / on_detector arrays show exactly which pixel (if any) each point of the reconstructed volume lands on — this is how a satellite/fringe feature in Q-space connects to a supplementary spot seen on the detector image.

stack : LayeredCrystal The layered structure. hkl : (int, int, int) Miller indices of the reference reflection, expressed in layer.crystal's lattice. layer : Layer, str, or None, optional Which layer's (crystal, U, n_hat) defines G0 and the rod axis. A str is looked up by .label against stack.all_layers. Default None uses stack.layers[0] (the first film/repeating layer) — pass explicitly for buffer/substrate reflections or multi-layer stacks with more than one distinct film. n_along, n_lateral : int, optional Grid points along the rod axis / each transverse axis. n_lateral is used for both transverse axes; pass 1 to collapse the grid to a pure 1-D rod. extent_along, extent_lateral : float or None, optional Half-width of the grid (Å⁻¹) along the rod axis / transverse axes. None auto-scales from the fringe period (see Note). max_satellites : int, optional Only used to size the default extent_along: spans ±(max_satellites + 0.5) * 2π/period so the same satellite orders simulate_laue_stack would report are covered. pin_satellites : bool, optional When True (default), the exact superlattice-satellite positions (multiples of 2π/Λ along the rod) are inserted into the along grid in addition to the regular linspace points, ensuring they are never missed due to grid coarseness. spot_only : bool, optional When True, collapse the grid to a sparse set of discrete spots: sets n_along=1 and n_lateral=1 and forces pin_satellites=True. The resulting along array contains only the Bragg peak (along=0) and the pinned satellite positions — no continuum sampling. This is useful for a clean spot-by-spot comparison against the measured detector image via :func:plot_detector_projection, without the continuous rod background. Default False (full dense 3-D grid). camera : Camera or None, optional Detector geometry. When None (default), only the Q-space volume is computed — no pixel/energy intersection. E_min_eV, E_max_eV : float, optional White-beam energy window (eV). source, source_kwargs, kb_params : Synchrotron spectrum model, forwarded to :func:_make_spectrum_fn (same meaning as in :func:simulate_laue_stack). ki_hat : array-like (3,) or None, optional Incident beam direction (LT frame). Default KI_HAT = [1,0,0]. structure_model : {'coherent', 'average'}, optional 'coherent' (default) evaluates the full layer-by-layer coherent stack structure factor — physically accurate fringe/satellite intensities. 'average' uses the composition-weighted average structure factor — faster, satellite positions are identical but intensities are not. Applies to both the kinematical (darwin=False) and Darwin (darwin=True) amplitude, exactly as in simulate_laue_stack / simulate_laue_darwin. darwin : bool, optional False (default) evaluates the plain kinematical structure factor (Layer.structure_factor_batch / average_structure_factor_batch — no extinction). True evaluates the Darwin (dynamical, extinction-saturated) amplitude instead (_darwin_amp_batch — the same physics as :func:simulate_laue_darwin), which can differ substantially from the kinematical result for strongly-diffracting/thick layers: extinction saturation is nonlinear in |F|, so two reflections that are only modestly different kinematically can end up in very different saturation regimes and diverge sharply. Only the intensity is affected — voxel positions (which pixel/energy each one maps to) are exact geometry either way, independent of this flag. Slower than darwin=False (still batched by energy bin, but with several extra layer-by-layer terms per bin). correct_depth : bool, optional Apply the parallax correction for layer's centre depth below the sample surface (see Camera.project's source_depth_mm). Only affects pix when camera is given. Default False. energy_ref_eV : float or None, optional Only used when darwin=False. Reference photon energy (eV) used to evaluate the unit-cell structure factor for every voxel at once (via Layer.structure_factor_batch → StructureFactorForQ), instead of each voxel's own energy. None (default) uses the median energy of the reachable voxels. This is the one approximation in an otherwise-exact computation: it only affects the smooth f'(E)/f''(E) anomalous-dispersion terms, which barely change across a typical local energy window — pass an explicit value if your window straddles an absorption edge and you want to pin it to one side. When darwin=True, each voxel's own energy is used instead (internally binned by _STRUCTURE_FACTOR_ENERGY_BINS, same as simulate_laue_darwin); this parameter has no effect. verbose : bool, optional Print a short summary (reachable/on-detector voxel counts, energy range) after the grid is evaluated.

Returns: dict with keys:

`'hkl'`, `'layer'` : the resolved inputs (`layer` as its label).
`'G0'` : ndarray (3,) — nominal reflection Q vector (lab frame, Å⁻¹).
`'axes'` : dict `{'n_hat', 't1', 't2'}` — orthonormal grid basis
    (lab frame unit vectors).
`'along'`, `'lateral1'`, `'lateral2'` : ndarray, 1-D coordinate
    arrays (Å⁻¹ offset from `G0` along each axis).
`'Q'` : ndarray, shape `(n_along, n_lateral, n_lateral, 3)` —
    lab-frame Q at every voxel.
`'F2'` : ndarray, shape `(n_along, n_lateral, n_lateral)` —
    `|F_stack(Q)|²`, zero where unreachable.
`'I'` : ndarray, same shape — `F2 · LP_Laue(2θ, E) · S(E)`, where
    `LP_Laue = P(2θ) · λ²/sin(2θ)` is the correct Laue peak-intensity
    Lorentz factor (un-normalised counts, per voxel).
`'E'` : ndarray, same shape — photon energy (eV), `NaN` where
    unreachable.
`'reachable'` : ndarray of bool, same shape — satisfies the elastic
    condition within `[E_min_eV, E_max_eV]`.
`'pix'` : ndarray, shape `(n_along, n_lateral, n_lateral, 2)`, or
    `None` if `camera` was not given.  `(xcam, ycam)`, `NaN` where
    off-detector or unreachable.
`'on_detector'` : ndarray of bool, same shape as `I`, or `None`.

Note: * The default extent_along uses stack.bilayer_thickness when stack.n_rep > 1, else layer.thickness — the same period simulate_laue_stack uses for its satellite spacing. If that period is degenerate (≤ 0), it falls back to 0.01 * |G0|. * The default extent_lateral is 0.05 * extent_along: this model has no transverse interference structure, so the transverse extent only needs to be large enough to make the array genuinely 3-D (e.g. for later isosurface/slice visualisation) — it is not a physical resolution limit. * With darwin=False (default), the structure factor is evaluated for the whole grid in one vectorised batch per layer (Layer.structure_factor_batch), not per voxel — see energy_ref_eV above for the one approximation this introduces. Runtime therefore scales with len(stack.all_layers) (typically a handful of xrayutilities calls total), not with the number of voxels. With darwin=True, the same batching applies but with several extra layer-by-layer terms per energy bin (extinction-saturated N_eff, per-layer absorption) — slower, though still far from per-voxel.

Example:

vol = qspace_around_spot(stack, (0, 0, 2), camera=cam) lit_up = vol['on_detector'] & (vol['I'] > 0) vol['pix'][lit_up] # every detector pixel this rod reaches

Source code in src/nrxrdct/laue/simulation.py
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
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
def qspace_around_spot(
    stack,
    hkl,
    layer=None,
    *,
    n_along=301,
    n_lateral=7,
    extent_along=None,
    extent_lateral=None,
    max_satellites=6,
    pin_satellites=True,
    spot_only=False,
    camera=None,
    E_min_eV=E_MIN_eV,
    E_max_eV=E_MAX_eV,
    source="bending_magnet",
    source_kwargs=None,
    kb_params=BM32_KB,
    ki_hat=None,
    structure_model="coherent",
    darwin=False,
    correct_depth=False,
    energy_ref_eV=None,
    verbose=True,
):
    """
    Reconstruct the 3-D reciprocal-space intensity distribution around one
    Bragg spot of a `LayeredCrystal` stack, and (optionally) the detector
    pixel/energy each voxel maps to.

    This generalises the discrete thickness-fringe/satellite construction
    used internally by :func:`simulate_laue_stack` (which only evaluates a
    handful of points at `G0 + m * q_fringe * n_hat`) into a continuous 3-D
    grid, so the full rod shape and any off-axis behaviour can be inspected
    directly.

    **Grid geometry**

    The grid is built in a local orthonormal frame centred on
    `G0 = layer.U @ layer.crystal.Q(*hkl)`:

    - one axis along `layer.n_hat` (the stack growth direction) — sampled
      finely, since finite-thickness fringes and superlattice satellites are
      *only* a function of `Q · n_hat` in this kinematical model;
    - two axes transverse to `n_hat` (arbitrary orthonormal in-plane
      directions) — sampled coarsely, since the structure factor of this
      model has no lateral interference structure and only varies smoothly
      there.

    **Physical intensity per voxel**

    For every voxel `Q = G0 + Δ`, the elastic (Laue) condition is solved
    for the unique photon energy that would excite it:

    $$
    E(Q) = hc \\,\\big/\\, \\lambda(Q), \\qquad
    \\lambda(Q) = -\\frac{4\\pi\\,(\\hat k_i \\cdot Q)}{|Q|^2}
    $$

    Voxels with `\\hat k_i \\cdot Q \\geq 0` or `E(Q)` outside
    `[E_min_eV, E_max_eV]` are marked unreachable (`I2 = 0`, `E = NaN`).
    For reachable voxels the diffracted direction `kf_hat` follows directly,
    and the structure factor is evaluated there — the plain kinematical
    stack sum (`stack.structure_factor` / `stack.average_structure_factor`,
    per `structure_model`) by default, or the Darwin (dynamical,
    extinction-saturated) amplitude when `darwin=True` — giving the same
    `F2 · LP · S(E)` intensity convention used throughout this module
    either way.  Only the intensity depends on this choice; voxel
    *positions* are exact geometry regardless (see `darwin` below).

    **Detector intersection**

    If `camera` is given, every voxel's `kf_hat` is projected onto the
    detector (`camera.project_batch`), so the returned `pix` / `on_detector`
    arrays show exactly which pixel (if any) each point of the reconstructed
    volume lands on — this is how a satellite/fringe feature in Q-space
    connects to a supplementary spot seen on the detector image.

    Args:
    stack : LayeredCrystal
        The layered structure.
    hkl : (int, int, int)
        Miller indices of the reference reflection, expressed in
        `layer.crystal`'s lattice.
    layer : Layer, str, or None, optional
        Which layer's `(crystal, U, n_hat)` defines `G0` and the rod axis.
        A `str` is looked up by `.label` against `stack.all_layers`.
        Default `None` uses `stack.layers[0]` (the first film/repeating
        layer) — pass explicitly for buffer/substrate reflections or
        multi-layer stacks with more than one distinct film.
    n_along, n_lateral : int, optional
        Grid points along the rod axis / each transverse axis.
        `n_lateral` is used for both transverse axes; pass `1` to collapse
        the grid to a pure 1-D rod.
    extent_along, extent_lateral : float or None, optional
        Half-width of the grid (Å⁻¹) along the rod axis / transverse axes.
        `None` auto-scales from the fringe period (see Note).
    max_satellites : int, optional
        Only used to size the default `extent_along`: spans
        `±(max_satellites + 0.5) * 2π/period` so the same satellite orders
        `simulate_laue_stack` would report are covered.
    pin_satellites : bool, optional
        When ``True`` (default), the exact superlattice-satellite positions
        (multiples of ``2π/Λ`` along the rod) are inserted into the
        ``along`` grid in addition to the regular linspace points, ensuring
        they are never missed due to grid coarseness.
    spot_only : bool, optional
        When ``True``, collapse the grid to a sparse set of discrete spots:
        sets ``n_along=1`` and ``n_lateral=1`` and forces
        ``pin_satellites=True``.  The resulting ``along`` array contains
        only the Bragg peak (``along=0``) and the pinned satellite
        positions — no continuum sampling.  This is useful for a clean
        spot-by-spot comparison against the measured detector image via
        :func:`plot_detector_projection`, without the continuous rod
        background.  Default ``False`` (full dense 3-D grid).
    camera : Camera or None, optional
        Detector geometry.  When `None` (default), only the Q-space volume
        is computed — no pixel/energy intersection.
    E_min_eV, E_max_eV : float, optional
        White-beam energy window (eV).
    source, source_kwargs, kb_params :
        Synchrotron spectrum model, forwarded to :func:`_make_spectrum_fn`
        (same meaning as in :func:`simulate_laue_stack`).
    ki_hat : array-like (3,) or None, optional
        Incident beam direction (LT frame).  Default `KI_HAT` = `[1,0,0]`.
    structure_model : {'coherent', 'average'}, optional
        `'coherent'` (default) evaluates the full layer-by-layer coherent
        stack structure factor — physically accurate fringe/satellite
        intensities.  `'average'` uses the composition-weighted average
        structure factor — faster, satellite *positions* are identical but
        intensities are not.  Applies to **both** the kinematical
        (`darwin=False`) and Darwin (`darwin=True`) amplitude, exactly as
        in `simulate_laue_stack` / `simulate_laue_darwin`.
    darwin : bool, optional
        `False` (default) evaluates the plain kinematical structure factor
        (`Layer.structure_factor_batch` / `average_structure_factor_batch`
        — no extinction). `True` evaluates the Darwin (dynamical,
        extinction-saturated) amplitude instead
        (`_darwin_amp_batch` — the same physics as
        :func:`simulate_laue_darwin`), which can differ substantially from
        the kinematical result for strongly-diffracting/thick layers:
        extinction saturation is nonlinear in `|F|`, so two reflections that
        are only modestly different kinematically can end up in very
        different saturation regimes and diverge sharply. Only the
        intensity is affected — voxel *positions* (which pixel/energy each
        one maps to) are exact geometry either way, independent of this
        flag.  Slower than `darwin=False` (still batched by energy bin, but
        with several extra layer-by-layer terms per bin).
    correct_depth : bool, optional
        Apply the parallax correction for `layer`'s centre depth below the
        sample surface (see `Camera.project`'s `source_depth_mm`).
        Only affects `pix` when `camera` is given.  Default `False`.
    energy_ref_eV : float or None, optional
        **Only used when `darwin=False`.** Reference photon energy (eV)
        used to evaluate the unit-cell structure factor for **every**
        voxel at once (via `Layer.structure_factor_batch` →
        `StructureFactorForQ`), instead of each voxel's own energy.
        `None` (default) uses the median energy of the reachable voxels.
        This is the one approximation in an otherwise-exact computation: it
        only affects the smooth `f'(E)`/`f''(E)` anomalous-dispersion
        terms, which barely change across a typical local energy window —
        pass an explicit value if your window straddles an absorption edge
        and you want to pin it to one side.  When `darwin=True`, each
        voxel's own energy is used instead (internally binned by
        `_STRUCTURE_FACTOR_ENERGY_BINS`, same as `simulate_laue_darwin`);
        this parameter has no effect.
    verbose : bool, optional
        Print a short summary (reachable/on-detector voxel counts, energy
        range) after the grid is evaluated.

    Returns:
    dict with keys:

        `'hkl'`, `'layer'` : the resolved inputs (`layer` as its label).
        `'G0'` : ndarray (3,) — nominal reflection Q vector (lab frame, Å⁻¹).
        `'axes'` : dict `{'n_hat', 't1', 't2'}` — orthonormal grid basis
            (lab frame unit vectors).
        `'along'`, `'lateral1'`, `'lateral2'` : ndarray, 1-D coordinate
            arrays (Å⁻¹ offset from `G0` along each axis).
        `'Q'` : ndarray, shape `(n_along, n_lateral, n_lateral, 3)` —
            lab-frame Q at every voxel.
        `'F2'` : ndarray, shape `(n_along, n_lateral, n_lateral)` —
            `|F_stack(Q)|²`, zero where unreachable.
        `'I'` : ndarray, same shape — `F2 · LP_Laue(2θ, E) · S(E)`, where
            `LP_Laue = P(2θ) · λ²/sin(2θ)` is the correct Laue peak-intensity
            Lorentz factor (un-normalised counts, per voxel).
        `'E'` : ndarray, same shape — photon energy (eV), `NaN` where
            unreachable.
        `'reachable'` : ndarray of bool, same shape — satisfies the elastic
            condition within `[E_min_eV, E_max_eV]`.
        `'pix'` : ndarray, shape `(n_along, n_lateral, n_lateral, 2)`, or
            `None` if `camera` was not given.  `(xcam, ycam)`, `NaN` where
            off-detector or unreachable.
        `'on_detector'` : ndarray of bool, same shape as `I`, or `None`.

    Note:
    * The default `extent_along` uses `stack.bilayer_thickness` when
      `stack.n_rep > 1`, else `layer.thickness` — the same period
      `simulate_laue_stack` uses for its satellite spacing.  If that
      period is degenerate (≤ 0), it falls back to `0.01 * |G0|`.
    * The default `extent_lateral` is `0.05 * extent_along`: this model has
      no transverse interference structure, so the transverse extent only
      needs to be large enough to make the array genuinely 3-D (e.g. for
      later isosurface/slice visualisation) — it is not a physical
      resolution limit.
    * With `darwin=False` (default), the structure factor is evaluated for
      the whole grid in one vectorised batch per layer
      (`Layer.structure_factor_batch`), not per voxel — see `energy_ref_eV`
      above for the one approximation this introduces. Runtime therefore
      scales with `len(stack.all_layers)` (typically a handful of
      xrayutilities calls total), not with the number of voxels.
      With `darwin=True`, the same batching applies but with several extra
      layer-by-layer terms per energy bin (extinction-saturated `N_eff`,
      per-layer absorption) — slower, though still far from per-voxel.

    Example:
    >>> vol = qspace_around_spot(stack, (0, 0, 2), camera=cam)
    >>> lit_up = vol['on_detector'] & (vol['I'] > 0)
    >>> vol['pix'][lit_up]              # every detector pixel this rod reaches
"""
    if type(stack).__name__ != "LayeredCrystal":
        raise TypeError(f"stack must be a LayeredCrystal, got {type(stack).__name__}")
    if structure_model not in ("coherent", "average"):
        raise ValueError(f"structure_model must be 'coherent' or 'average', got {structure_model!r}")

    # Collect superlattice periods BEFORE flattening — combine_stacks() unrolls
    # every repeating block into individual buffer layers, destroying n_rep info.
    stack._update_offsets()
    _sat_periods = [
        blk._period for blk in getattr(stack, "_blocks", [])
        if blk.n_rep >= 2 and blk._period > 1e-6
    ]

    stack = _flatten_if_multiblock(stack)
    stack._update_offsets()

    # ── resolve layer ────────────────────────────────────────────────────────
    if layer is None:
        if not stack.layers:
            raise ValueError("stack has no repeating/film layers; pass `layer` explicitly")
        layer = stack.layers[0]
    elif isinstance(layer, str):
        match = next((l for l in stack.all_layers if l.label == layer), None)
        if match is None:
            available = [l.label for l in stack.all_layers]
            raise ValueError(f"no layer labeled {layer!r}; available labels: {available}")
        layer = match

    h, k, l = (int(x) for x in hkl)
    G0 = layer.U @ layer.crystal.Q(h, k, l)
    n_hat = np.asarray(layer.n_hat, dtype=float)
    n_hat = n_hat / np.linalg.norm(n_hat)

    # ── transverse basis (arbitrary orthonormal pair ⟂ n_hat) ────────────────
    tmp = np.array([1.0, 0.0, 0.0]) if abs(n_hat[0]) < 0.9 else np.array([0.0, 1.0, 0.0])
    e_t1 = tmp - n_hat * np.dot(tmp, n_hat)
    e_t1 /= np.linalg.norm(e_t1)
    e_t2 = np.cross(n_hat, e_t1)

    # ── default extents ───────────────────────────────────────────────────────
    if extent_along is None:
        t_period = stack.bilayer_thickness if stack.n_rep > 1 else layer.thickness
        q_fringe = (2.0 * np.pi / t_period) if t_period > 1e-6 else 0.01 * float(np.linalg.norm(G0))
        extent_along = (max_satellites + 0.5) * q_fringe
    if extent_lateral is None:
        extent_lateral = 0.05 * extent_along

    # ── spot_only: collapse grid to Bragg + satellite positions only ──────────
    # When True, skip the dense uniform rod sampling and evaluate the structure
    # factor only at along=0 (Bragg peak) plus the pinned satellite positions.
    # This is equivalent to n_along=1, n_lateral=1 with pin_satellites forced
    # on — much faster and gives clean discrete spots for direct comparison
    # with measured peak positions/intensities.
    if spot_only:
        n_along = 1
        n_lateral = 1
        pin_satellites = True

    along_vals = np.linspace(-extent_along, extent_along, n_along)

    # ── pin along_vals to exact satellite positions ───────────────────────────
    # The geometric-series factor Σ exp(i·m·Qn·Λ) peaks where Qn·Λ = 2π·m.
    # In the `along` parameterisation Qn = G0·n̂ + along, so the satellite
    # positions are along_m = 2π·m/Λ − G0·n̂.  For thick stacks (large n_rep)
    # these peaks are far narrower than any reasonable uniform grid step, so
    # without pinning the grid skips over them entirely.
    # NOTE: _sat_periods was captured before _flatten_if_multiblock() because
    # combine_stacks() unrolls repeating blocks into flat buffer layers.
    _pinned_sat_along = []  # collect for verbose reporting
    if pin_satellites and _sat_periods:
        Gn = float(G0 @ stack.n_hat)
        for Lambda in _sat_periods:
            m_center = int(round(Gn * Lambda / (2.0 * np.pi)))
            sat_pts = []
            for m in range(m_center - max_satellites - 1,
                           m_center + max_satellites + 2):
                a = 2.0 * np.pi * m / Lambda - Gn
                if -extent_along <= a <= extent_along:
                    sat_pts.append(a)
            if sat_pts:
                along_vals = np.unique(np.concatenate(
                    [along_vals, np.array(sat_pts)]
                ))
                _pinned_sat_along.extend(sat_pts)
    elif pin_satellites and not _sat_periods and verbose:
        print(
            f"  qspace_around_spot: pin_satellites=True but no blocks with "
            f"n_rep≥2 found in stack — check stack.blocks"
        )

    t1_vals = np.linspace(-extent_lateral, extent_lateral, n_lateral) if n_lateral > 1 else np.array([0.0])
    t2_vals = np.linspace(-extent_lateral, extent_lateral, n_lateral) if n_lateral > 1 else np.array([0.0])

    AA, T1, T2 = np.meshgrid(along_vals, t1_vals, t2_vals, indexing="ij")
    shape = AA.shape
    Q_grid = (
        G0[None, None, None, :]
        + AA[..., None] * n_hat
        + T1[..., None] * e_t1
        + T2[..., None] * e_t2
    )
    Q_flat = Q_grid.reshape(-1, 3)
    n_vox = len(Q_flat)

    # ── elastic (Laue) condition per voxel, vectorised ────────────────────────
    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki = ki / np.linalg.norm(ki)
    lam_lo, lam_hi = en2lam(E_max_eV), en2lam(E_min_eV)

    kdG = Q_flat @ ki
    Gm2 = np.einsum("ij,ij->i", Q_flat, Q_flat)
    backward = kdG < 0

    lam_flat = np.full(n_vox, np.nan)
    lam_flat[backward] = -4.0 * np.pi * kdG[backward] / Gm2[backward]
    reachable_flat = backward & (lam_flat >= lam_lo) & (lam_flat <= lam_hi)
    idx = np.where(reachable_flat)[0]

    E_flat = np.full(n_vox, np.nan)
    kf_flat = np.full((n_vox, 3), np.nan)
    if len(idx):
        E_flat[idx] = HC / lam_flat[idx]
        km = 2.0 * np.pi / lam_flat[idx]
        kf = ki[None, :] * km[:, None] + Q_flat[idx]
        kf /= np.linalg.norm(kf, axis=1, keepdims=True)
        kf_flat[idx] = kf

    # ── structure factor + LP + spectrum, vectorised over all reachable voxels ─
    # The elastic-condition geometry (tth, kf_hat) stays exact and per-voxel
    # in both branches below; only the structure-factor amplitude itself
    # differs (kinematical vs Darwin — see `darwin`).
    spectrum = _make_spectrum_fn(source, source_kwargs or {}, kb_params)
    F2_flat = np.zeros(n_vox)
    I_flat = np.zeros(n_vox)

    if len(idx):
        tth_arr = np.degrees(np.arccos(np.clip(kf_flat[idx, 0], -1.0, 1.0)))
        chi_arr = np.degrees(np.arctan2(kf_flat[idx, 1], kf_flat[idx, 2] + 1e-17))
        LP_arr = _lorentz_pol_vec(tth_arr, E_flat[idx], chi_arr)
        sw_arr = spectrum(E_flat[idx])

        if darwin:
            # Each voxel's own energy is used (binned internally by
            # _darwin_amp_batch, same as simulate_laue_darwin) — the box is
            # small enough that this is usually just 1-2 bins in practice.
            F_arr, _, _ = _darwin_amp_batch(
                stack, ki, structure_model,
                Q_flat[idx], E_flat[idx], lam_flat[idx], tth_arr,
                kf_hat_arr=kf_flat[idx], n_bins=_STRUCTURE_FACTOR_ENERGY_BINS,
            )
        else:
            # F_uc(Q, E) is evaluated at one shared reference energy (see
            # `energy_ref_eV`), which collapses this from N scalar
            # xrayutilities calls to len(stack.all_layers) batched ones.
            E_ref = (
                float(energy_ref_eV) if energy_ref_eV is not None
                else float(np.median(E_flat[idx]))
            )
            batch_fn = (
                stack.average_structure_factor_batch
                if structure_model == "average"
                else stack.structure_factor_batch
            )
            F_arr = batch_fn(Q_flat[idx], E_ref, kf_hat_arr=kf_flat[idx])

        F2_arr = np.abs(F_arr) ** 2

        keep = (LP_arr > 0) & (sw_arr > 0)
        keep_idx = idx[keep]
        F2_flat[keep_idx] = F2_arr[keep]
        I_flat[keep_idx] = F2_arr[keep] * LP_arr[keep] * sw_arr[keep]

    # ── detector intersection ─────────────────────────────────────────────────
    pix_flat = None
    on_det_flat = None
    if camera is not None:
        depth_mm = _layer_depths_mm(stack).get(id(layer), 0.0) if correct_depth else 0.0
        pix_flat = np.full((n_vox, 2), np.nan)
        on_det_flat = np.zeros(n_vox, dtype=bool)
        if len(idx):
            pix_idx, on_det_idx = camera.project_batch(kf_flat[idx], source_depth_mm=depth_mm)
            pix_flat[idx] = pix_idx
            on_det_flat[idx] = on_det_idx

    if verbose:
        n_on_det = int(on_det_flat.sum()) if on_det_flat is not None else None
        e_reach = E_flat[idx]
        e_range = f"{e_reach.min():.0f}–{e_reach.max():.0f} eV" if len(idx) else "—"
        sat_info = (
            f"  pinned_sats={len(_pinned_sat_along)}" if _pinned_sat_along else
            f"  pinned_sats=0(no blocks w/ n_rep≥2)" if (pin_satellites and not _sat_periods) else ""
        )
        print(
            f"  qspace_around_spot: hkl={hkl}  layer='{layer.label}'  "
            f"grid={shape}  reachable={len(idx)}/{n_vox}  E∈[{e_range}]"
            + (f"  on_detector={n_on_det}" if n_on_det is not None else "")
            + sat_info
        )
        # Report where the G0 point and pinned satellites land on the detector
        if camera is not None and on_det_flat is not None:
            # Find the voxel closest to along=0, lateral=(0,0) — the main Bragg point
            mid_along = int(np.argmin(np.abs(along_vals)))
            mid_t1 = len(t1_vals) // 2
            mid_t2 = len(t2_vals) // 2
            bragg_flat_idx = (mid_along * len(t1_vals) + mid_t1) * len(t2_vals) + mid_t2
            if on_det_flat[bragg_flat_idx]:
                bpx = pix_flat[bragg_flat_idx]
                print(f"    G0 pixel: x={bpx[0]:.1f}, y={bpx[1]:.1f}  "
                      f"(along={along_vals[mid_along]:.4f} Å⁻¹)")
            else:
                print(f"    G0 (along≈0) is NOT on detector")
            # Report reachable + on-detector status for each pinned satellite
            if _pinned_sat_along:
                print(f"    Satellite positions (along Å⁻¹) → pixel:")
                for a_sat in sorted(_pinned_sat_along):
                    # find the grid index closest to this satellite
                    j_sat = int(np.argmin(np.abs(along_vals - a_sat)))
                    flat_sat = (j_sat * len(t1_vals) + mid_t1) * len(t2_vals) + mid_t2
                    reach = bool(reachable_flat[flat_sat])
                    on_d = bool(on_det_flat[flat_sat])
                    I_sat = float(I_flat[flat_sat])
                    if reach and on_d:
                        spx = pix_flat[flat_sat]
                        print(f"      along={a_sat:+.4f}  REACH ON-DET  "
                              f"x={spx[0]:.1f} y={spx[1]:.1f}  I={I_sat:.3e}")
                    elif reach:
                        print(f"      along={a_sat:+.4f}  REACH off-det  I={I_sat:.3e}")
                    else:
                        E_sat = float(E_flat[flat_sat]) if not np.isnan(E_flat[flat_sat]) else float("nan")
                        print(f"      along={a_sat:+.4f}  unreachable  E={E_sat:.0f} eV")

    return {
        "hkl": (h, k, l),
        "layer": layer.label,
        "G0": G0,
        "axes": {"n_hat": n_hat, "t1": e_t1, "t2": e_t2},
        "along": along_vals,
        "lateral1": t1_vals,
        "lateral2": t2_vals,
        "Q": Q_grid,
        "F2": F2_flat.reshape(shape),
        "I": I_flat.reshape(shape),
        "E": E_flat.reshape(shape),
        "reachable": reachable_flat.reshape(shape),
        "pix": pix_flat.reshape(*shape, 2) if pix_flat is not None else None,
        "on_detector": on_det_flat.reshape(shape) if on_det_flat is not None else None,
    }

qspace_multi_hkl

qspace_multi_hkl(stack, hkl_list, layer=None, *, n_along=301, n_lateral=7, extent_along=None, extent_lateral=None, max_satellites=6, pin_satellites=True, spot_only=False, camera=None, E_min_eV=E_MIN_eV, E_max_eV=E_MAX_eV, source='bending_magnet', source_kwargs=None, kb_params=BM32_KB, ki_hat=None, structure_model='coherent', darwin=False, correct_depth=False, energy_ref_eV=None, verbose=False)

Run :func:qspace_around_spot for every (HKL, layer) combination and return the results as a flat list of vol dicts.

When layer is None (default) every unique layer in the stack is used, so the returned list has len(hkl_list) × n_unique_layers entries — enough to project all reflections from all layers onto the detector in one call. Pass a single layer label/object or an explicit list to restrict which layers are simulated.

Parameters:
  • stack –

    :class:~nrxrdct.laue.layers.LayeredCrystal stack.

  • hkl_list –

    Iterable of (h, k, l) tuples.

  • layer –

    Which layer(s) to use as the grid centre.

    • None — all unique layers in stack.all_layers (deduplicated by label, same rule as :func:qspace_per_layer).
    • A single :class:~nrxrdct.laue.layers.Layer object or label string — that layer only, for every HKL.
    • A list of Layer objects / label strings — those layers only.
  • spot_only (bool, default: False ) –

    Forwarded to :func:qspace_around_spot. When True, each volume contains only the Bragg peak and pinned satellite positions (no continuum grid) — useful for a clean multi-reflection spot overlay on the measured detector image.

  • –

    func:qspace_around_spot.

Returns:
  • –

    list[dict] — flat list of vol dicts ordered as

  • –

    [(hkl0, lyr0), (hkl0, lyr1), ..., (hkl1, lyr0), ...].

Source code in src/nrxrdct/laue/simulation.py
def qspace_multi_hkl(
    stack,
    hkl_list,
    layer=None,
    *,
    n_along=301,
    n_lateral=7,
    extent_along=None,
    extent_lateral=None,
    max_satellites=6,
    pin_satellites=True,
    spot_only=False,
    camera=None,
    E_min_eV=E_MIN_eV,
    E_max_eV=E_MAX_eV,
    source="bending_magnet",
    source_kwargs=None,
    kb_params=BM32_KB,
    ki_hat=None,
    structure_model="coherent",
    darwin=False,
    correct_depth=False,
    energy_ref_eV=None,
    verbose=False,
):
    """
    Run :func:`qspace_around_spot` for every (HKL, layer) combination and
    return the results as a flat list of vol dicts.

    When *layer* is ``None`` (default) every unique layer in the stack is used,
    so the returned list has ``len(hkl_list) × n_unique_layers`` entries —
    enough to project all reflections from all layers onto the detector in one
    call.  Pass a single layer label/object or an explicit list to restrict
    which layers are simulated.

    Args:
        stack: :class:`~nrxrdct.laue.layers.LayeredCrystal` stack.
        hkl_list: Iterable of ``(h, k, l)`` tuples.
        layer: Which layer(s) to use as the grid centre.

            * ``None`` — all unique layers in ``stack.all_layers``
              (deduplicated by label, same rule as :func:`qspace_per_layer`).
            * A single :class:`~nrxrdct.laue.layers.Layer` object or label
              string — that layer only, for every HKL.
            * A list of Layer objects / label strings — those layers only.

        spot_only (bool): Forwarded to :func:`qspace_around_spot`.  When
            ``True``, each volume contains only the Bragg peak and pinned
            satellite positions (no continuum grid) — useful for a clean
            multi-reflection spot overlay on the measured detector image.
        All remaining keyword arguments are forwarded to
        :func:`qspace_around_spot`.

    Returns:
        ``list[dict]`` — flat list of vol dicts ordered as
        ``[(hkl0, lyr0), (hkl0, lyr1), ..., (hkl1, lyr0), ...]``.
    """
    # ── resolve layers list ───────────────────────────────────────────────────
    if layer is None:
        seen: set[str] = set()
        layers_to_use = []
        for lyr in stack.all_layers:
            if lyr.label not in seen:
                seen.add(lyr.label)
                layers_to_use.append(lyr)
    elif isinstance(layer, (list, tuple)):
        layers_to_use = list(layer)
    else:
        layers_to_use = [layer]

    hkl_list = list(hkl_list)
    n_total = len(hkl_list) * len(layers_to_use)
    vols = []
    for hkl in hkl_list:
        for lyr in layers_to_use:
            vol = qspace_around_spot(
                stack, hkl, layer=lyr,
                n_along=n_along, n_lateral=n_lateral,
                extent_along=extent_along, extent_lateral=extent_lateral,
                max_satellites=max_satellites, pin_satellites=pin_satellites,
                spot_only=spot_only,
                camera=camera, E_min_eV=E_min_eV, E_max_eV=E_max_eV,
                source=source, source_kwargs=source_kwargs,
                kb_params=kb_params, ki_hat=ki_hat,
                structure_model=structure_model,
                darwin=darwin,
                correct_depth=correct_depth,
                energy_ref_eV=energy_ref_eV,
                verbose=verbose,
            )
            vols.append(vol)
    if verbose:
        print(f"  Done — {len(vols)} vols computed.")
    return vols

qspace_per_layer

qspace_per_layer(stack, hkl, layers=None, *, n_along=301, n_lateral=7, extent_along=None, extent_lateral=None, max_satellites=6, pin_satellites=True, spot_only=False, camera=None, E_min_eV=E_MIN_eV, E_max_eV=E_MAX_eV, source='bending_magnet', source_kwargs=None, kb_params=BM32_KB, ki_hat=None, structure_model='coherent', darwin=False, correct_depth=False, energy_ref_eV=None, verbose=False)

Run :func:qspace_around_spot once per layer in the stack, using each layer's own G0 and n_hat as the grid centre, but always evaluating the full coherent structure factor of the entire stack at every Q point.

Because different layers may have slightly different lattice parameters, their individual Bragg peaks sit at slightly different absolute Q · n̂ positions. By running the simulation for each layer separately you can see all peaks on a common absolute-Qn axis and directly compare them against the measured image — revealing whether any apparent shift between simulation and measurement is caused by inter-layer interference, lattice mismatch, or a calibration offset.

Parameters:
  • stack –

    :class:~nrxrdct.laue.layers.LayeredCrystal stack.

  • hkl –

    Miller indices (h, k, l) of the reflection.

  • layers –

    List of :class:~nrxrdct.laue.layers.Layer objects (or layer labels as strings) to simulate. None (default) uses stack.all_layers — every buffer and repeating layer.

  • spot_only (bool, default: False ) –

    Forwarded to :func:qspace_around_spot. When True, each volume contains only the Bragg peak and pinned satellite positions (no continuum grid). Useful for a clean layer-by-layer spot comparison against the measured image.

  • –

    func:qspace_around_spot.

Returns:
  • –

    list[dict] — one vol dict per layer, in the same order as

  • –

    layers (or stack.all_layers), each with the same structure as

  • –

    the return value of :func:qspace_around_spot.

Example:

vols = qspace_per_layer(stack, (0, 0, 2), camera=cam) plot_qspace_summary(vol_main, camera=cam, image=img, ... per_layer_vols=vols)

Source code in src/nrxrdct/laue/simulation.py
def qspace_per_layer(
    stack,
    hkl,
    layers=None,
    *,
    n_along=301,
    n_lateral=7,
    extent_along=None,
    extent_lateral=None,
    max_satellites=6,
    pin_satellites=True,
    spot_only=False,
    camera=None,
    E_min_eV=E_MIN_eV,
    E_max_eV=E_MAX_eV,
    source="bending_magnet",
    source_kwargs=None,
    kb_params=BM32_KB,
    ki_hat=None,
    structure_model="coherent",
    darwin=False,
    correct_depth=False,
    energy_ref_eV=None,
    verbose=False,
):
    """
    Run :func:`qspace_around_spot` once per layer in the stack, using each
    layer's own G0 and n_hat as the grid centre, but always evaluating the
    **full coherent** structure factor of the entire stack at every Q point.

    Because different layers may have slightly different lattice parameters,
    their individual Bragg peaks sit at slightly different absolute
    ``Q · n̂`` positions.  By running the simulation for each layer
    separately you can see all peaks on a common absolute-Qn axis and
    directly compare them against the measured image — revealing whether
    any apparent shift between simulation and measurement is caused by
    inter-layer interference, lattice mismatch, or a calibration offset.

    Args:
        stack: :class:`~nrxrdct.laue.layers.LayeredCrystal` stack.
        hkl: Miller indices ``(h, k, l)`` of the reflection.
        layers: List of :class:`~nrxrdct.laue.layers.Layer` objects (or layer
            labels as strings) to simulate.  ``None`` (default) uses
            ``stack.all_layers`` — every buffer and repeating layer.
        spot_only (bool): Forwarded to :func:`qspace_around_spot`.  When
            ``True``, each volume contains only the Bragg peak and pinned
            satellite positions (no continuum grid).  Useful for a clean
            layer-by-layer spot comparison against the measured image.
        All remaining keyword arguments are forwarded unchanged to
        :func:`qspace_around_spot`.

    Returns:
        ``list[dict]`` — one vol dict per layer, in the same order as
        ``layers`` (or ``stack.all_layers``), each with the same structure as
        the return value of :func:`qspace_around_spot`.

    Example:
    >>> vols = qspace_per_layer(stack, (0, 0, 2), camera=cam)
    >>> plot_qspace_summary(vol_main, camera=cam, image=img,
    ...                     per_layer_vols=vols)
    """
    if type(stack).__name__ != "LayeredCrystal":
        raise TypeError(f"stack must be a LayeredCrystal, got {type(stack).__name__}")

    if layers is None:
        # Deduplicate by label: stack.layers concatenates every block's layers,
        # so a multi-block stack (e.g. lower_cladding / MQW / upper_cladding)
        # can contain the same material type in multiple blocks.  Keeping the
        # first occurrence per label avoids identical duplicate simulations.
        seen_labels: set[str] = set()
        layers = []
        for lyr in stack.all_layers:
            if lyr.label not in seen_labels:
                seen_labels.add(lyr.label)
                layers.append(lyr)
    else:
        resolved = []
        for lyr in layers:
            if isinstance(lyr, str):
                match = next((l for l in stack.all_layers if l.label == lyr), None)
                if match is None:
                    raise ValueError(f"no layer labeled {lyr!r}")
                resolved.append(match)
            else:
                resolved.append(lyr)
        layers = resolved

    vols = []
    for layer in layers:
        v = qspace_around_spot(
            stack, hkl, layer=layer,
            n_along=n_along, n_lateral=n_lateral,
            extent_along=extent_along, extent_lateral=extent_lateral,
            max_satellites=max_satellites, pin_satellites=pin_satellites,
            spot_only=spot_only,
            camera=camera, E_min_eV=E_min_eV, E_max_eV=E_max_eV,
            source=source, source_kwargs=source_kwargs,
            kb_params=kb_params, ki_hat=ki_hat,
            structure_model=structure_model,
            darwin=darwin,
            correct_depth=correct_depth,
            energy_ref_eV=energy_ref_eV,
            verbose=verbose,
        )
        vols.append(v)
    return vols

rod_positions

rod_positions(stack, hkl, layer=None, *, along, camera, ki_hat=None)

Exact pixel/energy position of a reflection's rod at an array of along (ΔQ, Å⁻¹) offsets from G0 = layer.U @ layer.crystal.Q(*hkl) along layer.n_hat -- the same per-point elastic-condition solve rod_tangency uses for pix0 and its satellite orders, vectorised over along instead of evaluated at one or a few discrete points.

rod_tangency's own streak_dir_px is only the local (linear) approximation to this at along=0 -- since the pixel↔Q map is nonlinear, the true rod generally curves away from that straight line as |along| grows. Use this function (not pix0 + along*streak_dir_px) whenever a plot or fit needs the rod's actual trajectory over a non-negligible range, e.g. to draw a faithful streak overlay or to extract an intensity profile whose sample points and x-axis both stay exact far from along=0 -- see plot_rod_tangency's show_profile.

Parameters:
  • stack, hkl, layer, camera, ki_hat –

    Same meaning as in :func:rod_tangency.

  • along –

    array-like (N,) ΔQ offsets (Å⁻¹) from G0 along layer.n_hat, positive and negative freely mixed (not required to be sorted or symmetric).

Returns: dict with keys:

`'along'` : the input array, as float64.
`'pix'` : ndarray (N, 2) — `(xcam, ycam)`; `NaN` where that `along`
    does not satisfy the elastic (backward) condition.
`'E'` : ndarray (N,) — energy (eV); `NaN` where unreachable.
`'on_detector'` : ndarray (N,) bool — whether `pix` lands on
    `camera`'s active area (`False`, not just unreachable, also
    where the elastic condition itself fails).
Source code in src/nrxrdct/laue/simulation.py
def rod_positions(stack, hkl, layer=None, *, along, camera, ki_hat=None):
    """
    Exact pixel/energy position of a reflection's rod at an array of `along`
    (ΔQ, Å⁻¹) offsets from `G0 = layer.U @ layer.crystal.Q(*hkl)` along
    `layer.n_hat` -- the same per-point elastic-condition solve
    `rod_tangency` uses for `pix0` and its satellite orders, vectorised over
    `along` instead of evaluated at one or a few discrete points.

    `rod_tangency`'s own `streak_dir_px` is only the *local* (linear)
    approximation to this at `along=0` -- since the pixel↔Q map is
    nonlinear, the true rod generally curves away from that straight line as
    `|along|` grows. Use this function (not `pix0 + along*streak_dir_px`)
    whenever a plot or fit needs the rod's actual trajectory over a
    non-negligible range, e.g. to draw a faithful streak overlay or to
    extract an intensity profile whose sample points and x-axis both stay
    exact far from `along=0` -- see `plot_rod_tangency`'s `show_profile`.

    Args:
        stack, hkl, layer, camera, ki_hat: Same meaning as in
            :func:`rod_tangency`.
        along : array-like (N,)
            ΔQ offsets (Å⁻¹) from `G0` along `layer.n_hat`, positive and
            negative freely mixed (not required to be sorted or symmetric).

    Returns:
    dict with keys:

        `'along'` : the input array, as float64.
        `'pix'` : ndarray (N, 2) — `(xcam, ycam)`; `NaN` where that `along`
            does not satisfy the elastic (backward) condition.
        `'E'` : ndarray (N,) — energy (eV); `NaN` where unreachable.
        `'on_detector'` : ndarray (N,) bool — whether `pix` lands on
            `camera`'s active area (`False`, not just unreachable, also
            where the elastic condition itself fails).
    """
    if type(stack).__name__ != "LayeredCrystal":
        raise TypeError(f"stack must be a LayeredCrystal, got {type(stack).__name__}")
    if camera is None:
        raise ValueError("camera is required")

    if layer is None:
        if not stack.layers:
            raise ValueError("stack has no repeating/film layers; pass `layer` explicitly")
        layer = stack.layers[0]
    elif isinstance(layer, str):
        match = next((ly for ly in stack.all_layers if ly.label == layer), None)
        if match is None:
            available = [ly.label for ly in stack.all_layers]
            raise ValueError(f"no layer labeled {layer!r}; available labels: {available}")
        layer = match

    h, k, l = (int(x) for x in hkl)
    G0 = layer.U @ layer.crystal.Q(h, k, l)
    n_hat = np.asarray(layer.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)

    along = np.asarray(along, dtype=float)
    Q = G0[None, :] + along[:, None] * n_hat[None, :]  # (N, 3)

    kdG = Q @ ki
    Gm2 = np.einsum("ij,ij->i", Q, Q)
    valid = (kdG < 0) & (Gm2 > 1e-30)

    E = np.full(along.shape, np.nan)
    pix = np.full((len(along), 2), np.nan)
    on_det = np.zeros(along.shape, dtype=bool)

    if np.any(valid):
        lam = -4.0 * np.pi * kdG[valid] / Gm2[valid]
        E[valid] = HC / lam
        km = 2.0 * np.pi / lam
        kf = ki[None, :] * km[:, None] + Q[valid]
        kf /= np.linalg.norm(kf, axis=1, keepdims=True)
        p, od = camera.project_batch(kf)
        pix[valid] = p
        on_det[valid] = od

    return {"along": along, "pix": pix, "E": E, "on_detector": on_det}

rod_satellite_along_positions

rod_satellite_along_positions(stack, layer, G0, n_hat, max_satellites)

Q-space positions of the satellite/fringe comb along a rod's own n_hat axis — pure Q-space geometry, no elastic-condition/camera evaluation, so it works without a Camera. Same anchoring convention :func:rod_tangency uses for its own 'satellites']['along'] values (see that function's docstring for the full physical reasoning): superlattice principal maxima anchored to the nearest true comb tooth when layer belongs to a repeating block with n_rep > 1; an isolated finite layer's own thickness-fringe maxima at half-integer positions otherwise.

Used by :func:~nrxrdct.laue.laue_plotting.plot_simulated_rod_qspace to mark satellite positions on a fixed-energy simulated map, where there is no Camera/pixel information to drive rod_tangency itself.

Parameters:
  • stack –

    LayeredCrystal Already flattened (see _flatten_if_multiblock) — same requirement as rod_tangency's own internal handling.

  • layer –

    Layer The resolved layer object (not a label/None) whose block membership determines the comb anchoring.

  • G0 –

    ndarray (3,) Nominal reflection Q vector (lab frame, Å⁻¹).

  • n_hat –

    ndarray (3,) Rod axis (unit vector, lab frame).

  • max_satellites –

    int Orders m = -max_satellites, ..., max_satellites to compute.

Returns:
  • –

    dict {m: along} — along (Å⁻¹) is the exact ΔQ from G0 along

  • –

    n_hat for order m.

Source code in src/nrxrdct/laue/simulation.py
def rod_satellite_along_positions(stack, layer, G0, n_hat, max_satellites):
    """
    Q-space positions of the satellite/fringe comb along a rod's own
    `n_hat` axis — pure Q-space geometry, no elastic-condition/camera
    evaluation, so it works without a `Camera`. Same anchoring convention
    :func:`rod_tangency` uses for its own `'satellites']['along']` values
    (see that function's docstring for the full physical reasoning):
    superlattice principal maxima anchored to the nearest true comb tooth
    when `layer` belongs to a repeating block with `n_rep > 1`; an isolated
    finite layer's own thickness-fringe maxima at half-integer positions
    otherwise.

    Used by :func:`~nrxrdct.laue.laue_plotting.plot_simulated_rod_qspace`
    to mark satellite positions on a fixed-energy simulated map, where
    there is no `Camera`/pixel information to drive `rod_tangency` itself.

    Args:
        stack : LayeredCrystal
            Already flattened (see `_flatten_if_multiblock`) — same
            requirement as `rod_tangency`'s own internal handling.
        layer : Layer
            The resolved layer object (not a label/`None`) whose block
            membership determines the comb anchoring.
        G0 : ndarray (3,)
            Nominal reflection Q vector (lab frame, Å⁻¹).
        n_hat : ndarray (3,)
            Rod axis (unit vector, lab frame).
        max_satellites : int
            Orders `m = -max_satellites, ..., max_satellites` to compute.

    Returns:
        dict `{m: along}` — `along` (Å⁻¹) is the exact ΔQ from `G0` along
        `n_hat` for order `m`.
    """
    stack._update_offsets()
    owning_block = None
    if layer not in stack.buffer_layers:
        owning_block = next((blk for blk in stack._blocks if layer in blk.layers), None)
    is_superlattice = owning_block is not None and owning_block.n_rep > 1 and owning_block._period > 1e-6

    if is_superlattice:
        period = float(owning_block._period)
        Gn = float(G0 @ n_hat)
        ell0 = round(Gn * period / (2.0 * np.pi))

        def _along(m):
            return 2.0 * np.pi * (ell0 + m) / period - Gn
    else:
        period = float(layer.thickness) if getattr(layer, "thickness", 0.0) > 1e-6 else 0.01 * float(np.linalg.norm(G0))
        q_fringe = 2.0 * np.pi / period

        def _along(m):
            return 0.0 if m == 0 else (m + 0.5 if m > 0 else m - 0.5) * q_fringe

    return {m: _along(m) for m in range(-max_satellites, max_satellites + 1)}

rod_tangency

rod_tangency(stack, hkl, layer=None, camera=None, *, ki_hat=None, d_along=0.0001, max_satellites=0)

Local pixel-space direction a reflection's superlattice rod traces out on the detector — the geometric root cause of the elongated satellite streaks discussed at length around :func:simulate_spot_image (a rod that maps to a large pixel displacement per unit Qn produces a long, thin streak; one that barely moves the pixel produces a compact spot). Pure geometry, no simulation — a fast screening check across candidate hkl before committing to :func:qspace_around_spot / :func:simulate_spot_image.

This must match qspace_around_spot's own construction, not a fixed-energy pixel gradient. The rod is the set of points Q(t) = G0 + t·n_hat; at each t the elastic condition is solved fresh for its own (E(t), kf_hat(t)) — energy and pixel co-vary along the rod, they are not independent. (An earlier version of this function computed ∂Qn/∂pixel at fixed energy instead — the iso-Qn contour for a beam that can't change energy — which is a different, unrelated direction; it was wrong and gave angles that didn't match the actual simulated rod.) This function instead takes two small steps ±d_along along n_hat, solves the exact elastic condition at each (same formula as qspace_around_spot), projects both to pixels via camera.project_batch, and reports the resulting direction — i.e. a two-point finite-difference estimate of d(pixel)/d(along) evaluated at t=0.

Parameters:
  • stack –

    LayeredCrystal

  • hkl –

    (int, int, int) Miller indices of the reflection (in layer.crystal's frame).

  • layer –

    Layer, str, or None, optional Which layer's (crystal, U, n_hat) to use. None (default) uses stack.layers[0], matching qspace_around_spot.

  • camera –

    Camera Detector geometry — required (there is no meaningful pixel gradient without one).

  • ki_hat –

    array-like (3,) or None, optional Incident beam direction (LT frame). Default KI_HAT.

  • d_along –

    float, optional Finite-difference step (Å⁻¹) along n_hat. Small relative to a typical satellite fringe spacing (2π/Λ, usually 0.01-0.1 Å⁻¹) so the estimate is local; the default 1e-4 is safely small for that range without hitting floating-point noise.

  • max_satellites –

    int, optional 0 (default) — only pix0/E0 (the m=0 main peak) are computed. Set to N > 0 to also solve the exact elastic condition at each order's bright position for m = -N, ..., N and project it to a pixel — see 'satellites' below. Two different physical cases share this labelling:

    • layer belongs to a repeating block with n_rep > 1 (Λ = that block's period) — the superlattice geometric factor S_rep has true principal maxima on the absolute comb Qn = 2π·ell/Λ (integer ell), which has nothing to do with hkl — G0 only lands on a comb tooth if it happens to be exactly commensurate with Λ, which is generally false (e.g. for a strained sublattice, or whenever Λ isn't an integer multiple of this hkl's own d-spacing). Order m is therefore probed at G0 + [2π·(ell0+m)/Λ − Gn]·n_hat, where ell0 = round(Gn·Λ/2π) is the comb tooth nearest G0 and Gn = G0·n_hat — the same anchoring qspace_around_spot's pin_satellites already uses. Note this means satellites[0] is not guaranteed to equal pix0/E0 in this case — it is the nearest true comb peak, which is generally offset from the exact hkl position by a fixed fraction of 2π/Λ.
    • layer is not part of a repeating block (Λ = layer.thickness) — a single finite layer's own thickness-interference function is instead exactly zero at those same integer positions; the observable bright fringes sit near the half-integer positions (|m|+½) in between (see the Thin-Film Satellites theory page). Order m is probed at G0 + (m ± 0.5)·(2π/Λ)·n_hat, the same convention simulate_laue_stack uses for its own candidate spots, so the marked positions line up with what an actual simulated exposure would show. See 'is_superlattice' below to tell which case applied.

Returns: dict with keys:

`'hkl'`, `'layer'` : the resolved inputs.
`'pix0'` : `(x, y)` — the reflection's nominal pixel.
`'E0'` : float — nominal energy (eV).
`'streak_dir_px'` : ndarray (2,) — unit vector in `(xcam, ycam)`,
    the streak's elongation direction (`d(pixel)/d(along)`,
    normalised).
`'perp_dir_px'` : ndarray (2,) — unit vector perpendicular to it
    (a display convenience — the streak's *width* is governed by
    the off-rod structure-factor/transverse decay, not derived
    here).
`'dpix_dalong'` : float (px / Å⁻¹) — magnitude of `d(pixel)/d(along)`.
    Large values mean a given accessible `Qn` range (bounded by the
    fringe-order envelope decay — see `simulate_spot_image`'s
    `I_satellites`) maps to a long streak in pixels; small values
    mean the rod is compact on the detector even over many orders.
    Multiply by an expected `Qn` range to estimate streak length in
    pixels; compare across candidate `hkl` rather than reading it
    in isolation.
`'on_detector'` : bool — whether `pix0` actually lands on `camera`.
`'period'` : float or None — the `Λ` (Å) used for the satellite
    comb, or `None` if `max_satellites=0`.
`'is_superlattice'` : bool — whether `layer` belongs to a repeating
    block with `n_rep > 1` (`period` = block period, comb anchored
    to its nearest true tooth) rather than being treated as an
    isolated finite layer (`period` = `layer.thickness`, half-integer
    probing, `m=0` always exactly `along=0`). Always computed,
    independent of `max_satellites`.
`'satellites'` : dict `{m: {'pix', 'E', 'on_detector', 'along'}}`
    for `m = -max_satellites, ..., max_satellites`. `'along'` is the
    exact ΔQ (Å⁻¹, along `n_hat` from `G0`) order `m` was solved at —
    **not** necessarily `m·(2π/period)`, see `max_satellites` above.
    `m=0` duplicates `pix0`/`E0` when `is_superlattice=False`, but
    generally does *not* when `is_superlattice=True` (see above).
    `'pix'`/`'E'` are `None` where the probed position doesn't
    satisfy the elastic condition. Empty when `max_satellites=0`.

Example:

info = rod_tangency(stack, (1, 0, 5), layer='GaN buffer', camera=cam) print(info['streak_dir_px']) # e.g. [0.71, 0.70] -> ~45° from horizontal

Source code in src/nrxrdct/laue/simulation.py
def rod_tangency(stack, hkl, layer=None, camera=None, *, ki_hat=None, d_along=1e-4, max_satellites=0):
    """
    Local pixel-space direction a reflection's superlattice rod traces out
    on the detector — the geometric root cause of the elongated satellite
    streaks discussed at length around :func:`simulate_spot_image` (a rod
    that maps to a large pixel displacement per unit `Qn` produces a long,
    thin streak; one that barely moves the pixel produces a compact spot).
    Pure geometry, no simulation — a fast screening check across candidate
    `hkl` before committing to :func:`qspace_around_spot` /
    :func:`simulate_spot_image`.

    **This must match `qspace_around_spot`'s own construction, not a
    fixed-energy pixel gradient.** The rod is the set of points
    `Q(t) = G0 + t·n_hat`; at *each* `t` the elastic condition is solved
    fresh for its own `(E(t), kf_hat(t))` — energy and pixel co-vary along
    the rod, they are not independent.  (An earlier version of this
    function computed `∂Qn/∂pixel` at *fixed* energy instead — the iso-`Qn`
    contour for a beam that can't change energy — which is a different,
    unrelated direction; it was wrong and gave angles that didn't match the
    actual simulated rod.)  This function instead takes two small steps
    `±d_along` along `n_hat`, solves the exact elastic condition at each
    (same formula as `qspace_around_spot`), projects both to pixels via
    `camera.project_batch`, and reports the resulting direction — i.e. a
    two-point finite-difference estimate of `d(pixel)/d(along)` evaluated
    at `t=0`.

    Args:
        stack : LayeredCrystal
        hkl : (int, int, int)
            Miller indices of the reflection (in `layer.crystal`'s frame).
        layer : Layer, str, or None, optional
            Which layer's `(crystal, U, n_hat)` to use.  `None` (default)
            uses `stack.layers[0]`, matching `qspace_around_spot`.
        camera : Camera
            Detector geometry — required (there is no meaningful pixel
            gradient without one).
        ki_hat : array-like (3,) or None, optional
            Incident beam direction (LT frame).  Default `KI_HAT`.
        d_along : float, optional
            Finite-difference step (Å⁻¹) along `n_hat`.  Small relative to
            a typical satellite fringe spacing (`2π/Λ`, usually
            `0.01`-`0.1` Å⁻¹) so the estimate is local; the default
            `1e-4` is safely small for that range without hitting
            floating-point noise.
        max_satellites : int, optional
            `0` (default) — only `pix0`/`E0` (the `m=0` main peak) are
            computed.  Set to `N > 0` to also solve the exact elastic
            condition at each order's *bright* position for `m = -N, ..., N`
            and project it to a pixel — see `'satellites'` below.  Two
            different physical cases share this labelling:

            * **`layer` belongs to a repeating block with `n_rep > 1`**
              (`Λ` = that block's period) — the superlattice geometric
              factor `S_rep` has true principal maxima on the *absolute*
              comb `Qn = 2π·ell/Λ` (integer `ell`), which has nothing to do
              with `hkl` — `G0` only lands on a comb tooth if it happens to
              be exactly commensurate with `Λ`, which is generally false
              (e.g. for a strained sublattice, or whenever `Λ` isn't an
              integer multiple of this `hkl`'s own d-spacing). Order `m` is
              therefore probed at `G0 + [2π·(ell0+m)/Λ − Gn]·n_hat`, where
              `ell0 = round(Gn·Λ/2π)` is the comb tooth nearest `G0` and
              `Gn = G0·n_hat` — the same anchoring
              `qspace_around_spot`'s `pin_satellites` already uses. Note
              this means `satellites[0]` is **not** guaranteed to equal
              `pix0`/`E0` in this case — it is the nearest *true* comb peak,
              which is generally offset from the exact `hkl` position by a
              fixed fraction of `2π/Λ`.
            * **`layer` is not part of a repeating block** (`Λ` =
              `layer.thickness`) — a single finite layer's own
              thickness-interference function is instead exactly *zero* at
              those same integer positions; the observable bright fringes
              sit near the half-integer positions `(|m|+½)` in between (see
              the Thin-Film Satellites theory page). Order `m` is probed at
              `G0 + (m ± 0.5)·(2π/Λ)·n_hat`, the same convention
              `simulate_laue_stack` uses for its own candidate spots, so the
              marked positions line up with what an actual simulated
              exposure would show. See `'is_superlattice'` below to tell
              which case applied.

    Returns:
    dict with keys:

        `'hkl'`, `'layer'` : the resolved inputs.
        `'pix0'` : `(x, y)` — the reflection's nominal pixel.
        `'E0'` : float — nominal energy (eV).
        `'streak_dir_px'` : ndarray (2,) — unit vector in `(xcam, ycam)`,
            the streak's elongation direction (`d(pixel)/d(along)`,
            normalised).
        `'perp_dir_px'` : ndarray (2,) — unit vector perpendicular to it
            (a display convenience — the streak's *width* is governed by
            the off-rod structure-factor/transverse decay, not derived
            here).
        `'dpix_dalong'` : float (px / Å⁻¹) — magnitude of `d(pixel)/d(along)`.
            Large values mean a given accessible `Qn` range (bounded by the
            fringe-order envelope decay — see `simulate_spot_image`'s
            `I_satellites`) maps to a long streak in pixels; small values
            mean the rod is compact on the detector even over many orders.
            Multiply by an expected `Qn` range to estimate streak length in
            pixels; compare across candidate `hkl` rather than reading it
            in isolation.
        `'on_detector'` : bool — whether `pix0` actually lands on `camera`.
        `'period'` : float or None — the `Λ` (Å) used for the satellite
            comb, or `None` if `max_satellites=0`.
        `'is_superlattice'` : bool — whether `layer` belongs to a repeating
            block with `n_rep > 1` (`period` = block period, comb anchored
            to its nearest true tooth) rather than being treated as an
            isolated finite layer (`period` = `layer.thickness`, half-integer
            probing, `m=0` always exactly `along=0`). Always computed,
            independent of `max_satellites`.
        `'satellites'` : dict `{m: {'pix', 'E', 'on_detector', 'along'}}`
            for `m = -max_satellites, ..., max_satellites`. `'along'` is the
            exact ΔQ (Å⁻¹, along `n_hat` from `G0`) order `m` was solved at —
            **not** necessarily `m·(2π/period)`, see `max_satellites` above.
            `m=0` duplicates `pix0`/`E0` when `is_superlattice=False`, but
            generally does *not* when `is_superlattice=True` (see above).
            `'pix'`/`'E'` are `None` where the probed position doesn't
            satisfy the elastic condition. Empty when `max_satellites=0`.

    Example:
    >>> info = rod_tangency(stack, (1, 0, 5), layer='GaN buffer', camera=cam)
    >>> print(info['streak_dir_px'])   # e.g. [0.71, 0.70] -> ~45° from horizontal
    """
    if type(stack).__name__ != "LayeredCrystal":
        raise TypeError(f"stack must be a LayeredCrystal, got {type(stack).__name__}")
    if camera is None:
        raise ValueError("camera is required")

    if layer is None:
        if not stack.layers:
            raise ValueError("stack has no repeating/film layers; pass `layer` explicitly")
        layer = stack.layers[0]
    elif isinstance(layer, str):
        match = next((ly for ly in stack.all_layers if ly.label == layer), None)
        if match is None:
            available = [ly.label for ly in stack.all_layers]
            raise ValueError(f"no layer labeled {layer!r}; available labels: {available}")
        layer = match

    h, k, l = (int(x) for x in hkl)
    G0 = layer.U @ layer.crystal.Q(h, k, l)
    n_hat = np.asarray(layer.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 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])

    res0 = _solve(G0)
    if res0 is None:
        raise ValueError(f"hkl={(h, k, l)} does not satisfy the elastic (backward) condition for this ki_hat")
    E0, pix0, on_det0 = res0

    res_plus = _solve(G0 + d_along * n_hat)
    res_minus = _solve(G0 - d_along * n_hat)
    if res_plus is not None and res_minus is not None:
        d_pix = (res_plus[1] - res_minus[1]) / (2.0 * d_along)
    elif res_plus is not None:
        d_pix = (res_plus[1] - pix0) / d_along
    elif res_minus is not None:
        d_pix = (pix0 - res_minus[1]) / d_along
    else:
        d_pix = np.zeros(2)

    jac_mag = float(np.linalg.norm(d_pix))
    if jac_mag > 1e-9:
        streak_dir = d_pix / jac_mag
    else:
        streak_dir = np.array([1.0, 0.0])
    perp_dir = np.array([-streak_dir[1], streak_dir[0]])

    stack._update_offsets()
    owning_block = None
    if layer not in stack.buffer_layers:
        owning_block = next((blk for blk in stack._blocks if layer in blk.layers), None)
    is_superlattice = owning_block is not None and owning_block.n_rep > 1 and owning_block._period > 1e-6

    period = None
    satellites = {}
    if max_satellites > 0:
        if is_superlattice:
            period = float(owning_block._period)

            # S_rep's true principal maxima sit on an *absolute* Q-space
            # comb, Qn = 2*pi*ell/period for integer ell -- this comb has
            # nothing to do with any particular hkl, so G0 (this layer's own
            # reciprocal-lattice point for the requested hkl) only happens to
            # coincide with a comb tooth if it is exactly commensurate with
            # `period`, which is not generally true (e.g. G0 for a strained
            # sublattice, or simply period not being an integer multiple of
            # this hkl's own d-spacing). Anchor order 0 at the *nearest* true
            # comb tooth instead of naively at G0, same reasoning
            # qspace_around_spot's pin_satellites already relies on
            # (`m_center = round(Gn*Lambda/2pi)`) -- otherwise every labelled
            # order is offset from the real peaks by the same fixed
            # fractional-period phase error, which can land arbitrarily close
            # to the valleys between them (observed: +0.41 of a period for a
            # worked InGaN/GaN example).
            Gn = float(G0 @ n_hat)
            ell0 = round(Gn * period / (2.0 * np.pi))

            def _along(m):
                return 2.0 * np.pi * (ell0 + m) / period - Gn
        elif getattr(layer, "thickness", 0.0) > 1e-6:
            period = float(layer.thickness)
            q_fringe = 2.0 * np.pi / period

            # A single (non-repeating) layer's own thickness-interference
            # function is exactly *zero* at integer m*(2π/t) around its own
            # G0 -- no commensurability ambiguity here, since G0 is that
            # layer's own exact reciprocal-lattice point by construction, so
            # m=0 is unambiguously along=0. The observable bright fringes
            # sit near the half-integer positions in between, same
            # convention simulate_laue_stack uses for its own candidate
            # spots (see the `frac = m ± 0.5` comment there) -- match it
            # here so the marked positions line up with what an actual
            # simulated spot would show.
            def _along(m):
                return 0.0 if m == 0 else (m + 0.5 if m > 0 else m - 0.5) * q_fringe
        else:
            period = 0.01 * float(np.linalg.norm(G0))
            q_fringe = 2.0 * np.pi / period

            def _along(m):
                return 0.0 if m == 0 else (m + 0.5 if m > 0 else m - 0.5) * q_fringe

        for m in range(-max_satellites, max_satellites + 1):
            along_m = _along(m)
            res_m = _solve(G0 + along_m * n_hat)
            satellites[m] = (
                {"pix": (float(res_m[1][0]), float(res_m[1][1])), "E": res_m[0],
                 "on_detector": res_m[2], "along": along_m}
                if res_m is not None
                else {"pix": None, "E": None, "on_detector": False, "along": along_m}
            )

    return {
        "hkl": (h, k, l),
        "layer": layer.label,
        "pix0": (float(pix0[0]), float(pix0[1])),
        "E0": E0,
        "streak_dir_px": streak_dir,
        "perp_dir_px": perp_dir,
        "dpix_dalong": jac_mag,
        "on_detector": on_det0,
        "period": period,
        "is_superlattice": is_superlattice,
        "satellites": satellites,
    }

rotate_U_about_axis

rotate_U_about_axis(U, angle_deg, axis: str = 'z')

Rotate an orientation matrix by angle_deg about a lab-frame axis.

U : array-like, shape (3, 3) Orientation matrix in the lab frame (G_lab = U @ G_crystal). angle_deg : float Rotation angle in degrees. Positive = right-hand rule about the axis. axis : 'x' | 'y' | 'z' Lab-frame axis to rotate about. 'z' is the surface normal in the standard BM32 / LT geometry; 'x' is along the beam; 'y' is horizontal and perpendicular to the beam.

U_rot : ndarray, shape (3, 3) Rotated orientation matrix: U_rot = R(axis, angle_deg) @ U.

Example: Rotate a GaN (001) orientation by 30° around the surface normal (z)::

U0  = orientation_along_z(GaN, [0, 0, 1], [1, 0, 0])
U30 = rotate_U_about_axis(U0, 30.0, axis='z')

Tilt by 2° around the beam direction (x) to simulate a small miscut::

U_tilt = rotate_U_about_axis(U0, 2.0, axis='x')
Source code in src/nrxrdct/laue/simulation.py
def rotate_U_about_axis(U, angle_deg, axis: str = "z"):
    """
    Rotate an orientation matrix by *angle_deg* about a lab-frame axis.

    Args:
    U : array-like, shape (3, 3)
        Orientation matrix in the lab frame (`G_lab = U @ G_crystal`).
    angle_deg : float
        Rotation angle in degrees.  Positive = right-hand rule about the axis.
    axis : `'x'` | `'y'` | `'z'`
        Lab-frame axis to rotate about.  `'z'` is the surface normal in the
        standard BM32 / LT geometry; `'x'` is along the beam; `'y'` is
        horizontal and perpendicular to the beam.

    Returns:
    U_rot : ndarray, shape (3, 3)
        Rotated orientation matrix: `U_rot = R(axis, angle_deg) @ U`.

    Example:
    Rotate a GaN (001) orientation by 30° around the surface normal (z)::

        U0  = orientation_along_z(GaN, [0, 0, 1], [1, 0, 0])
        U30 = rotate_U_about_axis(U0, 30.0, axis='z')

    Tilt by 2° around the beam direction (x) to simulate a small miscut::

        U_tilt = rotate_U_about_axis(U0, 2.0, axis='x')
"""
    axis = axis.lower().strip()
    if axis not in ("x", "y", "z"):
        raise ValueError(f"axis must be 'x', 'y', or 'z', got {axis!r}")
    R = Rotation.from_euler(axis.upper(), angle_deg, degrees=True).as_matrix()
    return R @ np.asarray(U, dtype=float)

rotate_U_about_crystal_axis

rotate_U_about_crystal_axis(U: ndarray, angle_deg: float, crystal_axis: ndarray) -> np.ndarray

Rotate an orientation matrix by angle_deg about a crystal-frame axis.

The rotation axis is specified in the crystal frame and is first mapped into the lab frame via U before the rotation is applied. This is the natural way to express rotations such as "60° about the c-axis [0001]" or "180° about an in-plane direction [1, 0, 0]".

U : array-like, shape (3, 3) Orientation matrix in the lab frame (G_lab = U @ G_crystal). angle_deg : float Rotation angle in degrees. Positive = right-hand rule about the crystal axis as expressed in the lab frame. crystal_axis : array-like, shape (3,) Rotation axis in the crystal frame (does not need to be a unit vector; it is normalised internally). Examples:

* `[0, 0, 1]` — $c$-axis (for hexagonal / tetragonal crystals)
* `[1, 0, 0]` — $a$-axis
* `[1, 1, 0]` — diagonal in-plane direction

U_rot : ndarray, shape (3, 3) Rotated orientation matrix.

Example: 60° rotation about the GaN \(c\)-axis (rotational domain variant)::

U_domain = rotate_U_about_crystal_axis(U, 60.0, [0, 0, 1])

180° flip about the in-plane \(a\)-axis::

U_flip = rotate_U_about_crystal_axis(U, 180.0, [1, 0, 0])
Source code in src/nrxrdct/laue/simulation.py
def rotate_U_about_crystal_axis(
    U: np.ndarray,
    angle_deg: float,
    crystal_axis: np.ndarray,
) -> np.ndarray:
    """
    Rotate an orientation matrix by *angle_deg* about a crystal-frame axis.

    The rotation axis is specified in the **crystal frame** and is first
    mapped into the lab frame via `U` before the rotation is applied.
    This is the natural way to express rotations such as "60° about the
    c-axis [0001]" or "180° about an in-plane direction [1, 0, 0]".

    Args:
    U : array-like, shape (3, 3)
        Orientation matrix in the lab frame (`G_lab = U @ G_crystal`).
    angle_deg : float
        Rotation angle in degrees.  Positive = right-hand rule about the
        crystal axis as expressed in the lab frame.
    crystal_axis : array-like, shape (3,)
        Rotation axis in the **crystal frame** (does not need to be a unit
        vector; it is normalised internally).  Examples:

        * `[0, 0, 1]` — $c$-axis (for hexagonal / tetragonal crystals)
        * `[1, 0, 0]` — $a$-axis
        * `[1, 1, 0]` — diagonal in-plane direction

    Returns:
    U_rot : ndarray, shape (3, 3)
        Rotated orientation matrix.

    Example:
    60° rotation about the GaN $c$-axis (rotational domain variant)::

        U_domain = rotate_U_about_crystal_axis(U, 60.0, [0, 0, 1])

    180° flip about the in-plane $a$-axis::

        U_flip = rotate_U_about_crystal_axis(U, 180.0, [1, 0, 0])
"""
    U = np.asarray(U, dtype=float)
    axis_cry = np.asarray(crystal_axis, dtype=float)
    axis_cry = axis_cry / np.linalg.norm(axis_cry)
    axis_lab = U @ axis_cry
    axis_lab = axis_lab / np.linalg.norm(axis_lab)
    R = Rotation.from_rotvec(np.radians(angle_deg) * axis_lab).as_matrix()
    return R @ U

simulate_full_detector_image

simulate_full_detector_image(stack, camera, *, bin_px=8, n_energy=101, E_min_eV=E_MIN_eV, E_max_eV=E_MAX_eV, source='bending_magnet', source_kwargs=None, kb_params=BM32_KB, ki_hat=None, structure_model='coherent', darwin=False, exclude_layers=None, sigma_h_mrad=0.0, sigma_v_mrad=0.0, n_div=5, row_start=0, row_end=None, verbose=True)

Forward-simulate an entire detector frame without any hkl enumeration — the pixel-space sibling of :func:simulate_spot_image, generalised from "one already-indexed reflection" to "every pixel".

For every (binned) pixel, the elastic condition makes Q a direct function of energy at that pixel's own kf_hat (from Camera.pixel_to_kf, exact, no reconstruction/anchoring needed here — unlike simulate_spot_image, there is no independently-known "true" Q to anchor against; every pixel's Q(E) is simply computed fresh):

\[ Q(E) = k(E)\,(\hat k_f - \hat k_i), \qquad k(E) = 2\pi E / hc \]

The structure factor is evaluated across the full [E_min_eV, E_max_eV] white-beam window at each pixel and integrated (trapezoidal) to give that pixel's total simulated intensity — no candidate hkl list, no f2_thresh, no satellite-order bookkeeping. Real Bragg peaks and satellite streaks appear automatically wherever Q(pixel, E) happens to pass near a reciprocal-lattice feature for some energy in the window.

Parameters:
  • stack –

    LayeredCrystal The layered structure.

  • camera –

    Camera Detector geometry — required (there is no meaningful "off detector" fallback for a whole-frame simulation).

  • bin_px –

    int, optional Downsampling factor: the image is computed on a grid of camera.Nh // bin_px × camera.Nv // bin_px block centres, not the full native resolution. A full-resolution sweep is usually not worth the cost (see Note) — start coarse (bin_px=8–16) and refine only the region of interest, e.g. with :func:simulate_spot_image once you've spotted something.

  • n_energy –

    int, optional Uniform energy samples per pixel across the entire [E_min_eV, E_max_eV] window. There is no pin_satellites here (nothing to pin without a known reflection) — see Note.

  • E_min_eV, E_max_eV –

    float, optional White-beam energy window (eV).

  • source, source_kwargs, kb_params –

    optional Synchrotron spectrum model, forwarded to _make_spectrum_fn.

  • ki_hat –

    array-like (3,) or None, optional Incident beam direction (LT frame). Default KI_HAT.

  • structure_model –

    {'coherent', 'average'}, optional Forwarded to LayeredCrystal.structure_factor_batch / average_structure_factor_batch (or _darwin_amp_batch when darwin=True) — same meaning as in qspace_around_spot / simulate_spot_image.

  • darwin –

    bool, optional False (default) evaluates the kinematical structure factor; True evaluates the Darwin (dynamical, extinction-saturated) amplitude instead.

  • exclude_layers –

    list[str] or None, optional Buffer-layer labels to drop from the coherent sum entirely — the whole-frame analogue of simulate_spot_image's isolate_layer list form. Use this for a deep growth substrate: its cross-term phase (exp(i·Qn·z0) with z0 up to hundreds of thousands of Å) is numerically unresolvable at any realistic bin_px/n_energy, the same issue documented on simulate_spot_image. None (default) keeps every layer.

  • sigma_h_mrad, sigma_v_mrad, n_div –

    optional Incident-beam angular divergence — same meaning and defaults (0.0, off) as simulate_spot_image.

  • row_start, row_end –

    int, int or None, optional Restrict the computation to a slice ys_full[row_start:row_end] of the binned-row grid (ys_full = arange(bin_px // 2, camera.Nv, bin_px)) — for splitting a full-frame simulation across multiple jobs (one row chunk per SLURM array task), see :func:submit_full_detector_image. Columns (x0) are always computed in full; only rows are chunkable. Defaults (0, None) compute every row, i.e. the whole frame.

  • verbose –

    bool, optional Print progress (one line per row-chunk) and a final summary.

Returns: dict with keys:

`'I'` : ndarray, shape `(n_pix_v, n_pix_h)` — total simulated
    intensity per binned pixel.
`'x0'`, `'y0'` : ndarray, 1-D pixel-centre coordinate arrays
    (native detector pixels) matching `I`'s columns/rows.
`'bin_px'` : the downsampling factor used.

Note: * Cost. (n_pix_h // bin_px) × (n_pix_v // bin_px) × n_energy structure-factor evaluations, batched but still substantial for a full frame — e.g. bin_px=8 on a 2048×2162 detector with n_energy=101 is ≈2.6×10⁷ evaluations. There is no equivalent of pin_satellites (no known reflection to derive an exact peak energy from), so real Bragg peaks narrower than the n_energy step at a given pixel can be aliased away entirely — this function is an overview/screening tool, not a substitute for :func:simulate_spot_image once you know where to look. * Every voxel's position is exact geometry (no anchoring approximation, unlike simulate_spot_image — see the docstring intro above for why none is needed here); only the intra-window energy sampling is approximate. * A deep buffer/substrate layer makes the coherent structure factor an extremely narrow function of Q — see exclude_layers — this is the same numerical reality documented at length on simulate_spot_image, not a separate issue.

Example:

img = simulate_full_detector_image(stack, cam, bin_px=8, exclude_layers=['Sapphire']) plt.imshow(np.log1p(img['I']), extent=[img['x0'][0], img['x0'][-1], img['y0'][-1], img['y0'][0]])

Source code in src/nrxrdct/laue/simulation.py
def simulate_full_detector_image(
    stack,
    camera,
    *,
    bin_px=8,
    n_energy=101,
    E_min_eV=E_MIN_eV,
    E_max_eV=E_MAX_eV,
    source="bending_magnet",
    source_kwargs=None,
    kb_params=BM32_KB,
    ki_hat=None,
    structure_model="coherent",
    darwin=False,
    exclude_layers=None,
    sigma_h_mrad=0.0,
    sigma_v_mrad=0.0,
    n_div=5,
    row_start=0,
    row_end=None,
    verbose=True,
):
    """
    Forward-simulate an entire detector frame **without** any hkl
    enumeration — the pixel-space sibling of :func:`simulate_spot_image`,
    generalised from "one already-indexed reflection" to "every pixel".

    For every (binned) pixel, the elastic condition makes `Q` a direct
    function of energy at that pixel's own `kf_hat` (from
    `Camera.pixel_to_kf`, exact, no reconstruction/anchoring needed here —
    unlike `simulate_spot_image`, there is no independently-known "true" `Q`
    to anchor against; every pixel's `Q(E)` is simply computed fresh):

    $$
    Q(E) = k(E)\\,(\\hat k_f - \\hat k_i), \\qquad k(E) = 2\\pi E / hc
    $$

    The structure factor is evaluated across the full `[E_min_eV,
    E_max_eV]` white-beam window at each pixel and integrated
    (trapezoidal) to give that pixel's total simulated intensity — no
    candidate `hkl` list, no `f2_thresh`, no satellite-order bookkeeping.
    Real Bragg peaks and satellite streaks appear automatically wherever
    `Q(pixel, E)` happens to pass near a reciprocal-lattice feature for
    some energy in the window.

    Args:
        stack : LayeredCrystal
            The layered structure.
        camera : Camera
            Detector geometry — required (there is no meaningful "off
            detector" fallback for a whole-frame simulation).
        bin_px : int, optional
            Downsampling factor: the image is computed on a grid of
            `camera.Nh // bin_px` × `camera.Nv // bin_px` block centres,
            not the full native resolution.  A full-resolution sweep is
            usually not worth the cost (see Note) — start coarse
            (`bin_px=8`–`16`) and refine only the region of interest, e.g.
            with :func:`simulate_spot_image` once you've spotted something.
        n_energy : int, optional
            Uniform energy samples per pixel across the *entire*
            `[E_min_eV, E_max_eV]` window.  There is no `pin_satellites`
            here (nothing to pin without a known reflection) — see Note.
        E_min_eV, E_max_eV : float, optional
            White-beam energy window (eV).
        source, source_kwargs, kb_params : optional
            Synchrotron spectrum model, forwarded to `_make_spectrum_fn`.
        ki_hat : array-like (3,) or None, optional
            Incident beam direction (LT frame).  Default `KI_HAT`.
        structure_model : {'coherent', 'average'}, optional
            Forwarded to `LayeredCrystal.structure_factor_batch` /
            `average_structure_factor_batch` (or `_darwin_amp_batch` when
            `darwin=True`) — same meaning as in `qspace_around_spot` /
            `simulate_spot_image`.
        darwin : bool, optional
            `False` (default) evaluates the kinematical structure factor;
            `True` evaluates the Darwin (dynamical, extinction-saturated)
            amplitude instead.
        exclude_layers : list[str] or None, optional
            Buffer-layer labels to drop from the coherent sum entirely —
            the whole-frame analogue of `simulate_spot_image`'s
            `isolate_layer` list form.  Use this for a deep growth
            substrate: its cross-term phase (`exp(i·Qn·z0)` with `z0` up to
            hundreds of thousands of Å) is numerically unresolvable at any
            realistic `bin_px`/`n_energy`, the same issue documented on
            `simulate_spot_image`.  `None` (default) keeps every layer.
        sigma_h_mrad, sigma_v_mrad, n_div : optional
            Incident-beam angular divergence — same meaning and defaults
            (`0.0`, off) as `simulate_spot_image`.
        row_start, row_end : int, int or None, optional
            Restrict the computation to a slice `ys_full[row_start:row_end]`
            of the binned-row grid (`ys_full = arange(bin_px // 2,
            camera.Nv, bin_px)`) — for splitting a full-frame simulation
            across multiple jobs (one row chunk per SLURM array task), see
            :func:`submit_full_detector_image`. Columns (`x0`) are always
            computed in full; only rows are chunkable. Defaults (`0`,
            `None`) compute every row, i.e. the whole frame.
        verbose : bool, optional
            Print progress (one line per row-chunk) and a final summary.

    Returns:
    dict with keys:

        `'I'` : ndarray, shape `(n_pix_v, n_pix_h)` — total simulated
            intensity per binned pixel.
        `'x0'`, `'y0'` : ndarray, 1-D pixel-centre coordinate arrays
            (native detector pixels) matching `I`'s columns/rows.
        `'bin_px'` : the downsampling factor used.

    Note:
    * **Cost.** `(n_pix_h // bin_px) × (n_pix_v // bin_px) × n_energy`
      structure-factor evaluations, batched but still substantial for a
      full frame — e.g. `bin_px=8` on a 2048×2162 detector with
      `n_energy=101` is ≈2.6×10⁷ evaluations.  There is no equivalent of
      `pin_satellites` (no known reflection to derive an exact peak energy
      from), so real Bragg peaks narrower than the `n_energy` step at a
      given pixel can be aliased away entirely — this function is an
      overview/screening tool, not a substitute for
      :func:`simulate_spot_image` once you know where to look.
    * Every voxel's position is exact geometry (no anchoring
      approximation, unlike `simulate_spot_image` — see the docstring
      intro above for why none is needed here); only the *intra-window*
      energy sampling is approximate.
    * A deep buffer/substrate layer makes the coherent structure factor an
      extremely narrow function of `Q` — see `exclude_layers` — this is
      the same numerical reality documented at length on
      `simulate_spot_image`, not a separate issue.

    Example:
    >>> img = simulate_full_detector_image(stack, cam, bin_px=8, exclude_layers=['Sapphire'])
    >>> plt.imshow(np.log1p(img['I']), extent=[img['x0'][0], img['x0'][-1], img['y0'][-1], img['y0'][0]])
    """
    if type(stack).__name__ != "LayeredCrystal":
        raise TypeError(f"stack must be a LayeredCrystal, got {type(stack).__name__}")
    if structure_model not in ("coherent", "average"):
        raise ValueError(f"structure_model must be 'coherent' or 'average', got {structure_model!r}")

    stack._update_offsets()
    if exclude_layers:
        from .layers import LayeredCrystal as _LayeredCrystal
        from .layers import _RepeatBlock as _RepeatBlockCls
        exclude_labels = set(exclude_layers)
        missing = exclude_labels - {ly.label for ly in stack.buffer_layers}
        if missing:
            raise ValueError(
                f"exclude_layers has labels not found in stack.buffer_layers: {missing}"
            )
        eval_stack = _LayeredCrystal(name="_reduced", stacking_direction=stack.n_hat)
        for ly in stack.buffer_layers:
            if ly.label not in exclude_labels:
                eval_stack.buffer_layers.append(ly)
        for blk in stack._blocks:
            new_blk = _RepeatBlockCls()
            new_blk.layers = list(blk.layers)
            new_blk.n_rep = blk.n_rep
            new_blk._closed = True
            eval_stack._blocks.append(new_blk)
        eval_stack._update_offsets()
    else:
        eval_stack = stack

    xs = np.arange(bin_px // 2, camera.Nh, bin_px, dtype=float)
    ys_full = np.arange(bin_px // 2, camera.Nv, bin_px, dtype=float)
    ys = ys_full[row_start:row_end]
    XX, YY = np.meshgrid(xs, ys)
    shape = XX.shape
    kf_hat = camera.pixel_to_kf(XX.ravel(), YY.ravel())
    n_pix = kf_hat.shape[0]

    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki = ki / np.linalg.norm(ki)
    spectrum = _make_spectrum_fn(source, source_kwargs or {}, kb_params)

    if sigma_h_mrad <= 0.0 and sigma_v_mrad <= 0.0:
        ki_pert_arr = ki[None, :]
        div_weights = np.array([1.0])
    else:
        z_hat = np.array([0.0, 0.0, 1.0])
        cross_zk = np.cross(z_hat, ki)
        e_h = cross_zk / np.linalg.norm(cross_zk) if np.linalg.norm(cross_zk) > 1e-6 else np.array([0.0, 1.0, 0.0])
        e_v = np.cross(ki, e_h)
        e_v /= np.linalg.norm(e_v)
        sigma_h = sigma_h_mrad * 1e-3
        sigma_v = sigma_v_mrad * 1e-3
        dh_vals = np.linspace(-2.5, 2.5, n_div) * sigma_h if sigma_h > 0 else np.zeros(1)
        dv_vals = np.linspace(-2.5, 2.5, n_div) * sigma_v if sigma_v > 0 else np.zeros(1)
        DH, DV = np.meshgrid(dh_vals, dv_vals, indexing="ij")
        DH, DV = DH.reshape(-1), DV.reshape(-1)
        ki_pert_arr = ki[None, :] + DH[:, None] * e_h[None, :] + DV[:, None] * e_v[None, :]
        ki_pert_arr /= np.linalg.norm(ki_pert_arr, axis=1, keepdims=True)
        wh = np.exp(-0.5 * (DH / sigma_h) ** 2) if sigma_h > 0 else np.ones_like(DH)
        wv = np.exp(-0.5 * (DV / sigma_v) ** 2) if sigma_v > 0 else np.ones_like(DV)
        div_weights = wh * wv
        div_weights = div_weights / div_weights.sum()
    n_div_actual = len(div_weights)

    E_samples = np.linspace(E_min_eV, E_max_eV, n_energy)
    n_e = len(E_samples)
    lam_samples = en2lam(E_samples)
    k_samples = 2.0 * np.pi / lam_samples
    E_flat = np.tile(E_samples, n_pix)
    kf_flat = np.repeat(kf_hat, n_e, axis=0)
    tth_flat = np.degrees(np.arccos(np.clip(kf_flat[:, 0], -1.0, 1.0)))
    chi_flat = np.degrees(np.arctan2(kf_flat[:, 1], kf_flat[:, 2] + 1e-17))
    LP_flat = _lorentz_pol_vec(tth_flat, E_flat, chi_flat)
    sw_flat = spectrum(E_flat)

    I_total = np.zeros(n_pix)
    for d in range(n_div_actual):
        ki_d = ki_pert_arr[d]
        diff_d = kf_hat - ki_d[None, :]
        Q_all = k_samples[None, :, None] * diff_d[:, None, :]
        Q_flat = Q_all.reshape(-1, 3)

        if darwin:
            lam_flat = en2lam(E_flat)
            F_arr, _, _ = _darwin_amp_batch(
                eval_stack, ki_d, structure_model, Q_flat, E_flat, lam_flat, tth_flat,
                kf_hat_arr=kf_flat, n_bins=_STRUCTURE_FACTOR_ENERGY_BINS,
            )
        else:
            batch_fn = (
                eval_stack.average_structure_factor_batch
                if structure_model == "average"
                else eval_stack.structure_factor_batch
            )
            F_arr = batch_fn(Q_flat, float(np.median(E_samples)), kf_hat_arr=kf_flat)

        F2_flat = np.abs(F_arr) ** 2
        I_flat = (F2_flat * LP_flat * sw_flat).reshape(n_pix, n_e)
        I_total += div_weights[d] * np.trapz(I_flat, x=E_samples, axis=1)

        if verbose:
            print(f"  simulate_full_detector_image: divergence sample {d + 1}/{n_div_actual} done")

    if verbose:
        print(
            f"  simulate_full_detector_image: grid={shape[1]}x{shape[0]} "
            f"(bin_px={bin_px})  n_energy={n_energy}  rows=[{row_start}:{row_end}]  "
            f"I_max={I_total.max():.3e}"
        )

    return {
        "I": I_total.reshape(shape),
        "x0": xs,
        "y0": ys,
        "bin_px": bin_px,
    }

simulate_laue

simulate_laue(crystal, U, camera, E_min=E_MIN_eV, E_max=E_MAX_eV, source='bending_magnet', source_kwargs=None, f2_thresh=F2_THRESHOLD, kb_params=BM32_KB, sigma_h_mrad=0.0, sigma_v_mrad=0.0, sigma_beam_h_nm=0.0, sigma_beam_v_nm=0.0, n_hat_sample=None, geometry_only=False, allowed_hkl=None, depth_mm=0.0, _pixels_only=False)

Simulate single-crystal white-beam Laue diffraction in reflection geometry.

For every reciprocal-lattice vector G_hkl satisfying the sphere criterion |G_hkl| ≤ G_max = 4π·E_max/12398.4 Å⁻¹ the function:

  1. Rotates G from the crystal frame into the lab frame via the orientation matrix U: G_lab = U @ G_cry.
  2. Applies the Laue condition to find the wavelength (and photon energy) at which this reflection is excited::

    lambda_hkl = -4*pi * (k_i_hat . G_lab) / |G_lab|^2

Reflections whose wavelength falls outside [E_min, E_max] are skipped. 3. Computes the scattered-beam direction kf_hat and projects it onto the detector plane via camera.project(). Reflections that miss the active area are discarded. 4. Evaluates the spot intensity::

   I_raw(hkl) = |F(G, E)|^2  *  LP(2theta)  *  S(E)

where:

  • |F(G, E)|^2 – kinematical structure factor squared (Cromer-Mann f0 plus Henke anomalous corrections f', f'' via xrayutilities). Reflections below f2_thresh are dropped.
  • LP(2theta) – Lorentz-polarisation factor for an unpolarised beam::

       LP = (1 + cos^2(2θ)) / (2 * sin^2(θ) * cos(θ))
    
  • S(E) – synchrotron spectral weight at energy E (bending-magnet, wiggler, or undulator model set by the module-level SOURCE_TYPE).

  • Normalises all surviving I_raw values by the brightest spot so that intensity lies in (0, 1].

crystal : Crystal-like An xrayutilities-compatible crystal object that exposes:

- `crystal.Q(h, k, l)`  → reciprocal-lattice vector in crystal frame
  (Å⁻¹, 2π convention).
- `crystal.StructureFactor(G_cry, en=E)`  → complex structure factor
  at energy `E` (eV).
array-like, shape (3, 3)

Orientation matrix mapping crystal-frame vectors to the LaueTools lab frame (beam along +x). Typically obtained from euler_to_U(phi1, Phi, phi2) or an indexing result.

Camera

Detector geometry object (see camera.py). Must implement camera.project(kf_hat) which returns (col, row) pixel coordinates or None if the ray misses the detector.

float, optional

Low-energy cut-off of the white beam in eV. Default: E_MIN_eV (5 000 eV).

float, optional

High-energy cut-off of the white beam in eV. Default: E_MAX_eV (27 000 eV).

str, optional

Synchrotron source model. See :func:_make_spectrum_fn for the full list ('bending_magnet', 'wiggler', 'undulator', 'flat', 'shadow4', 'tabulated'). Default: 'bending_magnet'.

dict or None, optional

Extra arguments for the chosen source (see :func:_make_spectrum_fn).

dict or None, optional

KB mirror reflectivity correction (see :func:kb_reflectivity). Ignored for 'shadow4' and 'tabulated' sources.

float, optional

Minimum |F|^2 threshold (arbitrary units, same scale as xrayutilities output). Reflections below this value are treated as systematically absent or too weak and discarded before the LP / spectrum weighting step. Default: F2_THRESHOLD (1e-6).

list of dict One dictionary per spot that satisfies all selection criteria, sorted by descending intensity. Each dictionary contains:

==================  ====================================================
Key                 Description
==================  ====================================================
`hkl`             `(h, k, l)` tuple of Miller indices.
`E`               Photon energy at which the reflection is excited (eV).
`lambda`          Corresponding wavelength (Å).
`tth`             Bragg angle `2θ` (degrees), measured from the
                    forward-beam direction `+x`.
`chi`             LaueTools χ angle (degrees):
                    `arctan2(kf_y, kf_z)`.
`az`              Azimuthal angle (degrees):
                    `arctan2(kf_z, kf_y)`.
`pix`             `(col, row)` pixel coordinate on the detector
                    (LaueTools convention: `xcam, ycam`).
`F2`              `|F(G, E)|^2`, structure factor squared **of the
                    first-enumerated reflection at this pixel** (see
                    `n_harmonics` below).
`LP`              Lorentz-polarisation factor (of that same reflection).
`sw`              Synchrotron spectral weight `S(E)` (of that same reflection).
`I_raw`           Un-normalised intensity, **summed over every
                    reflection landing on this pixel**: `Σ F2ₙ·LPₙ·swₙ`.
`intensity`       `I_raw` normalised to `[0, 1]` by the
                    brightest spot in this simulation.
`n_harmonics`     Number of reflections merged onto this pixel
                    (harmonics `hkl`, `2·hkl`, `3·hkl`, ... excited at
                    different energies, or any other accidental
                    overlap). `1` if this pixel has only one contributor.
`harmonic_hkls`   `list[(h,k,l)]`, one entry per contributing reflection.
`harmonic_F2`     `list[float]`, each contributor's own `F2`.
`harmonic_I_raw`  `list[float]`, each contributor's own `F2·LP·sw`;
                    `sum(harmonic_I_raw) == I_raw` always holds.
==================  ====================================================

Returns an **empty list** if no reflection satisfies all criteria.

Note: * The incident beam is fixed along +x in the LaueTools lab frame (KI_HAT = [1, 0, 0]). Do not modify this without updating the camera geometry accordingly. * intensity is a relative quantity within a single call. When comparing patterns from different phases or orientations use I_raw and apply an external weighting (see simulate_mixed_phases). * A detector pixel physically records the sum of every reflection that lands there — most commonly harmonics of one Bragg peak, each excited by a different photon energy in the white beam. These are summed as intensities (Σ F2·LP·sw), never as coherent amplitudes, because different-energy photons don't interfere. See n_harmonics / harmonic_* above to inspect or verify this per spot. * The structure factor is evaluated in energy bins (_STRUCTURE_FACTOR_ENERGY_BINS, default 200) rather than once per candidate — see that constant's definition for the accuracy/speed tradeoff this implies (typically ≲1% error for this function; larger for tightly-spaced satellite-bearing reflections in the layered variants below).

Source code in src/nrxrdct/laue/simulation.py
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
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
def simulate_laue(
    crystal,
    U,
    camera,
    E_min=E_MIN_eV,
    E_max=E_MAX_eV,
    source="bending_magnet",
    source_kwargs=None,
    f2_thresh=F2_THRESHOLD,
    kb_params=BM32_KB,
    sigma_h_mrad=0.0,
    sigma_v_mrad=0.0,
    sigma_beam_h_nm=0.0,
    sigma_beam_v_nm=0.0,
    n_hat_sample=None,
    geometry_only=False,
    allowed_hkl=None,
    depth_mm=0.0,
    _pixels_only=False,
):
    """
    Simulate single-crystal white-beam Laue diffraction in reflection geometry.

    For every reciprocal-lattice vector G_hkl satisfying the sphere criterion
    |G_hkl| ≤ G_max = 4π·E_max/12398.4 Å⁻¹ the function:

    1. Rotates G from the crystal frame into the lab frame via the orientation
       matrix `U`:  `G_lab = U @ G_cry`.
    2. Applies the Laue condition to find the wavelength (and photon energy) at
       which this reflection is excited::

           lambda_hkl = -4*pi * (k_i_hat . G_lab) / |G_lab|^2

       Reflections whose wavelength falls outside `[E_min, E_max]` are
       skipped.
    3. Computes the scattered-beam direction `kf_hat` and projects it onto
       the detector plane via `camera.project()`.  Reflections that miss the
       active area are discarded.
    4. Evaluates the spot intensity::

           I_raw(hkl) = |F(G, E)|^2  *  LP(2theta)  *  S(E)

       where:

       - `|F(G, E)|^2`  – kinematical structure factor squared (Cromer-Mann
         `f0` plus Henke anomalous corrections `f'`, `f''` via
         *xrayutilities*).  Reflections below `f2_thresh` are dropped.
       - `LP(2theta)`   – Lorentz-polarisation factor for an unpolarised
         beam::

               LP = (1 + cos^2(2θ)) / (2 * sin^2(θ) * cos(θ))

       - `S(E)`         – synchrotron spectral weight at energy `E`
         (bending-magnet, wiggler, or undulator model set by the module-level
         `SOURCE_TYPE`).

    5. Normalises all surviving `I_raw` values by the brightest spot so that
       `intensity` lies in `(0, 1]`.

    Args:
    crystal : Crystal-like
        An *xrayutilities*-compatible crystal object that exposes:

        - `crystal.Q(h, k, l)`  → reciprocal-lattice vector in crystal frame
          (Å⁻¹, 2π convention).
        - `crystal.StructureFactor(G_cry, en=E)`  → complex structure factor
          at energy `E` (eV).

    U : array-like, shape (3, 3)
        Orientation matrix mapping crystal-frame vectors to the LaueTools lab
        frame (beam along `+x`).  Typically obtained from
        `euler_to_U(phi1, Phi, phi2)` or an indexing result.

    camera : Camera
        Detector geometry object (see `camera.py`).  Must implement
        `camera.project(kf_hat)` which returns `(col, row)` pixel
        coordinates or `None` if the ray misses the detector.

    E_min : float, optional
        Low-energy cut-off of the white beam in eV.
        Default: `E_MIN_eV` (5 000 eV).

    E_max : float, optional
        High-energy cut-off of the white beam in eV.
        Default: `E_MAX_eV` (27 000 eV).

    source : str, optional
        Synchrotron source model.  See :func:`_make_spectrum_fn` for the full
        list (`'bending_magnet'`, `'wiggler'`, `'undulator'`, `'flat'`,
        `'shadow4'`, `'tabulated'`).  Default: `'bending_magnet'`.

    source_kwargs : dict or None, optional
        Extra arguments for the chosen source (see :func:`_make_spectrum_fn`).

    kb_params : dict or None, optional
        KB mirror reflectivity correction (see :func:`kb_reflectivity`).
        Ignored for `'shadow4'` and `'tabulated'` sources.

    f2_thresh : float, optional
        Minimum `|F|^2` threshold (arbitrary units, same scale as
        *xrayutilities* output).  Reflections below this value are treated as
        systematically absent or too weak and discarded before the LP / spectrum
        weighting step.
        Default: `F2_THRESHOLD` (1e-6).

    Returns:
    list of dict
        One dictionary per spot that satisfies all selection criteria, sorted
        by **descending** `intensity`.  Each dictionary contains:

        ==================  ====================================================
        Key                 Description
        ==================  ====================================================
        `hkl`             `(h, k, l)` tuple of Miller indices.
        `E`               Photon energy at which the reflection is excited (eV).
        `lambda`          Corresponding wavelength (Å).
        `tth`             Bragg angle `2θ` (degrees), measured from the
                            forward-beam direction `+x`.
        `chi`             LaueTools χ angle (degrees):
                            `arctan2(kf_y, kf_z)`.
        `az`              Azimuthal angle (degrees):
                            `arctan2(kf_z, kf_y)`.
        `pix`             `(col, row)` pixel coordinate on the detector
                            (LaueTools convention: `xcam, ycam`).
        `F2`              `|F(G, E)|^2`, structure factor squared **of the
                            first-enumerated reflection at this pixel** (see
                            `n_harmonics` below).
        `LP`              Lorentz-polarisation factor (of that same reflection).
        `sw`              Synchrotron spectral weight `S(E)` (of that same reflection).
        `I_raw`           Un-normalised intensity, **summed over every
                            reflection landing on this pixel**: `Σ F2ₙ·LPₙ·swₙ`.
        `intensity`       `I_raw` normalised to `[0, 1]` by the
                            brightest spot in this simulation.
        `n_harmonics`     Number of reflections merged onto this pixel
                            (harmonics `hkl`, `2·hkl`, `3·hkl`, ... excited at
                            different energies, or any other accidental
                            overlap). `1` if this pixel has only one contributor.
        `harmonic_hkls`   `list[(h,k,l)]`, one entry per contributing reflection.
        `harmonic_F2`     `list[float]`, each contributor's own `F2`.
        `harmonic_I_raw`  `list[float]`, each contributor's own `F2·LP·sw`;
                            `sum(harmonic_I_raw) == I_raw` always holds.
        ==================  ====================================================

        Returns an **empty list** if no reflection satisfies all criteria.

    Note:
    * The incident beam is fixed along `+x` in the LaueTools lab frame
      (`KI_HAT = [1, 0, 0]`).  Do not modify this without updating the
      camera geometry accordingly.
    * `intensity` is a *relative* quantity within a single call.  When
      comparing patterns from different phases or orientations use `I_raw`
      and apply an external weighting (see `simulate_mixed_phases`).
    * A detector pixel physically records the sum of every reflection that
      lands there — most commonly harmonics of one Bragg peak, each excited
      by a different photon energy in the white beam.  These are summed as
      *intensities* (`Σ F2·LP·sw`), never as coherent amplitudes, because
      different-energy photons don't interfere.  See `n_harmonics` /
      `harmonic_*` above to inspect or verify this per spot.
    * The structure factor is evaluated in energy bins
      (`_STRUCTURE_FACTOR_ENERGY_BINS`, default 200) rather than once per
      candidate — see that constant's definition for the accuracy/speed
      tradeoff this implies (typically ≲1% error for this function; larger
      for tightly-spaced satellite-bearing reflections in the layered
      variants below).
"""
    lam_lo = en2lam(E_max)
    lam_hi = en2lam(E_min)
    ki_hat = KI_HAT / np.linalg.norm(KI_HAT)
    source_kwargs = source_kwargs or {}

    _spectrum = _make_spectrum_fn(source, source_kwargs, kb_params)

    # Sphere enumeration: only reflections with |G| ≤ G_max can satisfy
    # the Laue condition within the energy window (back-reflection limit).
    HC_eV_ANG = 12398.4
    G_max = 4.0 * np.pi * E_max / HC_eV_ANG
    G_max_sq = G_max ** 2
    a_star = float(np.linalg.norm(crystal.Q(1, 0, 0)))
    b_star = float(np.linalg.norm(crystal.Q(0, 1, 0)))
    c_star = float(np.linalg.norm(crystal.Q(0, 0, 1)))
    h_lim = int(G_max / a_star) + 1
    k_lim = int(G_max / b_star) + 1
    l_lim = int(G_max / c_star) + 1

    # Build B matrix: Q(h,k,l) = B @ [h,k,l] avoids repeated crystal.Q calls.
    # Deferred to avoid the cost when the hkl_arrays cache is warm.
    def _get_B():
        return np.column_stack([crystal.Q(1, 0, 0), crystal.Q(0, 1, 0), crystal.Q(0, 0, 1)])

    spots = []

    if allowed_hkl is not None:
        # ── VECTORISED PATH (fitting / geometry-only) ─────────────────────────
        # Spectrum and LP are not needed — only pixel positions matter.
        _aid = id(allowed_hkl)
        if _aid in _hkl_arrays_cache:
            _hkl_arr, _G_cry_arr, _cached_crystal = _hkl_arrays_cache[_aid]
            if _cached_crystal is not crystal:
                # Different crystal with same frozenset object — recompute G_cry.
                _G_cry_arr = (_get_B() @ _hkl_arr.T).T
                _hkl_arrays_cache[_aid] = (_hkl_arr, _G_cry_arr, crystal)
        else:
            _B = _get_B()
            _hkl_arr   = np.array(list(allowed_hkl), dtype=np.int32).reshape(-1, 3)  # (M, 3)
            _G_cry_arr = (_B @ _hkl_arr.T).T                          # (M, 3)
            _hkl_arrays_cache[_aid] = (_hkl_arr, _G_cry_arr, crystal)

        G_lab = _G_cry_arr @ U.T                                   # (M, 3)
        kdG   = G_lab @ ki_hat                                     # (M,)
        v1    = kdG < 0
        if np.any(v1):
            G_lab = G_lab[v1];  _hkl_arr = _hkl_arr[v1];  kdG = kdG[v1]
            Gm2   = np.einsum("ij,ij->i", G_lab, G_lab)
            lam   = -4.0 * np.pi * kdG / Gm2
            v2    = (lam >= lam_lo) & (lam <= lam_hi)
            if np.any(v2):
                G_lab = G_lab[v2];  _hkl_arr = _hkl_arr[v2];  lam = lam[v2]
                E_arr = HC / lam
                km    = 2.0 * np.pi / lam
                kf_v  = ki_hat[None, :] * km[:, None] + G_lab     # (M, 3)
                kf_v /= np.linalg.norm(kf_v, axis=1, keepdims=True)
                pix_arr, on_det = camera.project_batch(kf_v, source_depth_mm=depth_mm)
                if np.any(on_det):
                    kf_v    = kf_v[on_det];  _hkl_arr = _hkl_arr[on_det]
                    lam     = lam[on_det];   E_arr    = E_arr[on_det]
                    pix_arr = pix_arr[on_det]
                    if _pixels_only:
                        return pix_arr          # (N, 2) — skip dict construction
                    cos2th  = np.clip(kf_v[:, 0], -1.0, 1.0)
                    tth_arr = np.degrees(np.arccos(cos2th))
                    chi_arr = np.degrees(np.arctan2(kf_v[:, 1], kf_v[:, 2] + 1e-17))
                    az_arr  = np.degrees(np.arctan2(kf_v[:, 2], kf_v[:, 1]))
                    for _i in range(len(lam)):
                        spots.append({
                            "hkl":             (int(_hkl_arr[_i, 0]),
                                                int(_hkl_arr[_i, 1]),
                                                int(_hkl_arr[_i, 2])),
                            "satellite_order": 0,
                            "is_superlattice": False,
                            "E":               float(E_arr[_i]),
                            "lambda":          float(lam[_i]),
                            "tth":             float(tth_arr[_i]),
                            "chi":             float(chi_arr[_i]),
                            "az":              float(az_arr[_i]),
                            "pix":             (float(pix_arr[_i, 0]),
                                                float(pix_arr[_i, 1])),
                            "F2":              1.0,
                            "LP":              1.0,
                            "sw":              1.0,
                            "I_raw":           1.0,
                        })
    else:
        # ── VECTORISED GEOMETRY + PER-SPOT STRUCTURE FACTOR ──────────────────
        # Geometry filters (sphere, kdG, lambda, detector) are applied in bulk
        # with numpy; StructureFactor / LP / spectrum are evaluated only for the
        # small number of on-detector survivors.
        _B = _get_B()
        _H2, _K2, _L2 = np.meshgrid(
            np.arange(-h_lim, h_lim + 1, dtype=np.int32),
            np.arange(-k_lim, k_lim + 1, dtype=np.int32),
            np.arange(-l_lim, l_lim + 1, dtype=np.int32),
            indexing="ij",
        )
        _hkl = np.column_stack([_H2.ravel(), _K2.ravel(), _L2.ravel()])
        _hkl = _hkl[np.any(_hkl != 0, axis=1)]
        G_cry_all = (_B @ _hkl.T).T                                    # (N, 3)

        # Sphere filter (U orthogonal → |G_lab| = |G_cry|)
        G_sq = np.einsum("ij,ij->i", G_cry_all, G_cry_all)
        v0 = G_sq <= G_max_sq
        G_cry_all = G_cry_all[v0];  _hkl = _hkl[v0]

        G_lab_all = G_cry_all @ U.T                                     # (M, 3)

        kdG = G_lab_all @ ki_hat                                        # (M,)
        v1 = kdG < 0
        G_cry_all = G_cry_all[v1];  G_lab_all = G_lab_all[v1]
        _hkl = _hkl[v1];           kdG       = kdG[v1]

        Gm2 = np.einsum("ij,ij->i", G_lab_all, G_lab_all)
        lam = -4.0 * np.pi * kdG / Gm2
        v2 = (lam >= lam_lo) & (lam <= lam_hi)
        G_cry_all = G_cry_all[v2];  G_lab_all = G_lab_all[v2]
        _hkl      = _hkl[v2];      lam       = lam[v2]

        if len(lam) > 0:
            E_arr = HC / lam
            km    = 2.0 * np.pi / lam
            kf_v  = ki_hat[None, :] * km[:, None] + G_lab_all          # (K, 3)
            kf_v /= np.linalg.norm(kf_v, axis=1, keepdims=True)
            pix_arr, on_det = camera.project_batch(kf_v, source_depth_mm=depth_mm)
            if np.any(on_det):
                G_cry_all = G_cry_all[on_det];  _hkl    = _hkl[on_det]
                lam       = lam[on_det];        E_arr   = E_arr[on_det]
                kf_v      = kf_v[on_det];       pix_arr = pix_arr[on_det]
                cos2th  = np.clip(kf_v[:, 0], -1.0, 1.0)
                tth_arr = np.degrees(np.arccos(cos2th))
                chi_arr = np.degrees(np.arctan2(kf_v[:, 1], kf_v[:, 2] + 1e-17))
                az_arr  = np.degrees(np.arctan2(kf_v[:, 2], kf_v[:, 1]))

                LP_arr = _lorentz_pol_vec(tth_arr, E_arr, chi_arr)
                sw_arr = _spectrum(E_arr)
                pre_ok = (LP_arr > 0) & (sw_arr > 0)
                ok_idx = np.where(pre_ok)[0]

                # Structure factor for every survivor, batched by energy bin
                # (one xrayutilities call per bin instead of one per
                # candidate) — see _binned_structure_factor.
                if geometry_only:
                    F2_all = np.ones(len(ok_idx))
                elif len(ok_idx):
                    F_all = _binned_structure_factor(
                        G_cry_all[ok_idx], E_arr[ok_idx],
                        lambda G, E, kf: crystal.StructureFactorForQ(G, en0=E),
                        n_bins=_STRUCTURE_FACTOR_ENERGY_BINS,
                    )
                    F2_all = np.abs(F_all) ** 2
                else:
                    F2_all = np.empty(0)

                # A detector pixel records the sum of every reflection that lands
                # there (most commonly harmonics: hkl, 2·hkl, 3·hkl, ... each at
                # its own energy) — merge coincident candidates instead of
                # letting only the first-enumerated one survive.
                seen_pix = {}
                for _pos, _i in enumerate(ok_idx):
                    F2 = float(F2_all[_pos])
                    if not geometry_only and F2 < f2_thresh:
                        continue
                    h, k, l = int(_hkl[_i, 0]), int(_hkl[_i, 1]), int(_hkl[_i, 2])
                    pix_i = (float(pix_arr[_i, 0]), float(pix_arr[_i, 1]))
                    pix_key = (round(pix_i[0]), round(pix_i[1]))
                    E  = float(E_arr[_i]); LP = float(LP_arr[_i]); sw = float(sw_arr[_i])
                    _merge_or_append_spot(spots, seen_pix, pix_key, {
                        "hkl":             (h, k, l),
                        "satellite_order": 0,
                        "is_superlattice": False,
                        "E":               E,
                        "lambda":          float(lam[_i]),
                        "tth":             float(tth_arr[_i]),
                        "chi":             float(chi_arr[_i]),
                        "az":              float(az_arr[_i]),
                        "pix":             pix_i,
                        "F2":              F2,
                        "LP":              LP,
                        "sw":              sw,
                        "I_raw":           F2 * LP * sw,
                    })

    if spots:
        imax = max(s["I_raw"] for s in spots)
        for s in spots:
            s["intensity"] = s["I_raw"] / imax

    spots = sorted(spots, key=lambda s: s["intensity"], reverse=True)
    beam_divergence_ellipses(
        spots, camera, sigma_h_mrad, sigma_v_mrad,
        sigma_beam_h_nm=sigma_beam_h_nm,
        sigma_beam_v_nm=sigma_beam_v_nm,
        n_hat_sample=n_hat_sample,
    )
    if _pixels_only:
        return np.empty((0, 2), dtype=float)
    return spots

simulate_laue_darwin

simulate_laue_darwin(stack, camera, E_min_eV: float = E_MIN_eV, E_max_eV: float = E_MAX_eV, source: str = 'bending_magnet', source_kwargs: dict | None = None, f2_thresh: float = F2_THRESHOLD, ki_hat=None, kb_params=BM32_KB, max_satellites: int = 5, structure_model: str = 'average', sigma_h_mrad: float = 0.0, sigma_v_mrad: float = 0.0, sigma_beam_h_nm: float = 0.0, sigma_beam_v_nm: float = 0.0, n_hat_sample=None, correct_depth: bool = False, allowed_hkl: frozenset | dict | None = None, verbose: bool = True)

White-beam Laue simulation with Darwin (dynamical diffraction) intensities.

Spot positions are identical to :func:simulate_laue_stack — they come from the same Laue condition and camera geometry. The difference is in how the intensity of each spot is computed.

Kinematical vs Darwin The kinematical model gives

I ∝ |F_uc|² × N²

which diverges for thick perfect-crystal regions (substrate). The Darwin model corrects this with the primary extinction factor:

N_eff = N_ext × tanh(N / N_ext)

N_ext = V_uc sin θ / (rₑ λ |F_uc|) / d    [extinction length, unit cells]

so that thin layers remain kinematical (N_eff ≈ N) while thick regions saturate at N_ext.

For a multilayer stack the amplitudes from all layers are summed coherently (same phase relationship as the kinematical model), so superlattice satellites and fringe patterns are preserved:

F_total(G) = F_buffer(G) + exp(i Qₙ z_buf) · F_unit(G) · S_rep(Qₙ Λ)

F_layer_i(G) = F_uc_i × N_eff_i × exp(i Qₙ z_i)

Absorption limiting (Beer-Lambert) is applied on top of extinction: the effective cell count is min(N_eff_darwin, N_eff_absorption).

Alloys Any xu.materials.Crystal-compatible object can be used as the layer crystal, including alloys created with xrayutilities (e.g. xu.materials.HexagonalAlloy, VCA compositions, etc.). The composition enters through the structure factor F_uc and the unit-cell volume V_uc.

stack : LayeredCrystal Same input as :func:simulate_laue_stack. camera : Camera E_min_eV, E_max_eV : float source : str See :func:simulate_laue_stack and :func:_make_spectrum_fn for the full list ('bending_magnet', 'wiggler', 'undulator', 'flat', 'shadow4', 'tabulated'). source_kwargs : dict, optional f2_thresh : float Minimum Darwin-corrected |F_total|² to keep a spot. ki_hat : array-like (3,) or None kb_params : dict or None max_satellites : int, optional Number of satellite / fringe orders to probe on each side of every Bragg peak (default 5). Probes orders ±1 … ±max_satellites. Set to 0 to skip satellite calculation entirely. structure_model : {'coherent', 'average'}, optional See :func:simulate_laue_stack for full description. In 'average' mode G vectors are enumerated from buffer layers only, intra-period exp(i Qₙ z_rel) phases are dropped, and S_rep is kept — producing a single average Bragg peak with satellites, as seen in a monochromatic scan. Darwin-corrected N_eff values are still computed and reported in the returned 'N_eff' key. allowed_hkl : frozenset or dict or None, optional Pre-computed set of allowed reflections from :func:precompute_allowed_hkl. When supplied, systematically absent reflections are filtered before any geometry computation, avoiding :func:_darwin_amp calls for forbidden hkl. Accepts:

* ``frozenset`` — shared across all phases (useful when all layers
  have the same crystal type).
* ``dict`` mapping ``id(crystal)`` → ``frozenset`` — per-crystal
  sets, as returned by the internal cache.

Default ``None``: all (h, k, l) in the sphere pass to the Laue
condition check, relying on the structure factor threshold to reject
forbidden reflections.

correct_depth : bool, optional When True, each layer's spots are projected from the beam-path depth of that layer's centre rather than from the sample surface (depth = 0). The depth is taken from :func:_layer_depths_mm and divided by cos(angle between ki and surface normal) to convert from normal-direction depth to along-beam displacement, which is then passed as source_depth_mm to camera.project().

This corrects the **depth-parallax** shift: in reflection geometry
a spot originating at depth *z* exits from a laterally displaced
surface point, causing substrate spots to appear at a different
detector position than surface or film spots.  Default ``False``
(all spots projected from the surface, matching the behaviour of
:func:`simulate_laue_stack`).

sigma_h_mrad, sigma_v_mrad : float, optional Horizontal / vertical beam divergence 1σ (mrad). See :func:beam_divergence_ellipses. Typical BM32/ESRF: 2–3 / 0.2–0.5. sigma_beam_h_nm, sigma_beam_v_nm : float, optional Beam footprint size 1σ at the sample (nm). Requires n_hat_sample to activate footprint broadening. n_hat_sample : array-like (3,), optional Sample surface normal in the LT frame (for footprint broadening). verbose : bool

spots : list[dict] Same keys as :func:simulate_laue_stack — including the coincident-reflection accumulation (n_harmonics, harmonic_hkls, harmonic_F2, harmonic_I_raw) — plus:

``'N_eff'``          list of Darwin N_eff per layer (buffer layers
                     then block layers), for **this spot's own**
                     contributing reflection — not summed across
                     `harmonic_hkls`
``'N_ext'``          list of extinction lengths (unit cells) per layer,
                     same per-spot scope as `N_eff`
``'F2_darwin'``      ``|F_total_darwin|²`` (same value as `F2`)
``'source_depth_mm'``  beam-path depth used for projection (mm);
                     0.0 when ``correct_depth=False``

Note: As with :func:simulate_laue_stack, a multi-block stack is transparently flattened via :func:~nrxrdct.laue.layers.combine_stacks before simulation.

Performance The Darwin amplitude (F_uc per layer, plus the extinction-saturated N_eff and, when kf_hat-dependent absorption applies, μ(E)) is evaluated in energy bins (_STRUCTURE_FACTOR_ENERGY_BINS, default 200) across every surviving candidate at once, rather than one full per-candidate Darwin calculation each — this is the difference between a satellite-heavy stack finishing in ~20 s versus not finishing in any practical time (it did not complete within 180 s before this change on the same benchmark stack). Worst-case F2 error at the default 200 bins is ~5% vs. the exact per-candidate-energy value; see _STRUCTURE_FACTOR_ENERGY_BINS's definition for the full benchmark and the accuracy/speed tradeoff of changing it.

Source code in src/nrxrdct/laue/simulation.py
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
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
def simulate_laue_darwin(
    stack,
    camera,
    E_min_eV: float = E_MIN_eV,
    E_max_eV: float = E_MAX_eV,
    source: str = "bending_magnet",
    source_kwargs: dict | None = None,
    f2_thresh: float = F2_THRESHOLD,
    ki_hat=None,
    kb_params=BM32_KB,
    max_satellites: int = 5,
    structure_model: str = "average",
    sigma_h_mrad: float = 0.0,
    sigma_v_mrad: float = 0.0,
    sigma_beam_h_nm: float = 0.0,
    sigma_beam_v_nm: float = 0.0,
    n_hat_sample=None,
    correct_depth: bool = False,
    allowed_hkl: "frozenset | dict | None" = None,
    verbose: bool = True,
):
    """
    White-beam Laue simulation with Darwin (dynamical diffraction) intensities.

    Spot **positions** are identical to :func:`simulate_laue_stack` — they
    come from the same Laue condition and camera geometry.  The difference is
    in how the **intensity** of each spot is computed.

    **Kinematical vs Darwin**
    The kinematical model gives

        I ∝ |F_uc|² × N²

    which diverges for thick perfect-crystal regions (substrate).  The Darwin
    model corrects this with the *primary extinction* factor:

        N_eff = N_ext × tanh(N / N_ext)

        N_ext = V_uc sin θ / (rₑ λ |F_uc|) / d    [extinction length, unit cells]

    so that thin layers remain kinematical (N_eff ≈ N) while thick regions
    saturate at N_ext.

    For a multilayer stack the amplitudes from all layers are summed
    **coherently** (same phase relationship as the kinematical model), so
    superlattice satellites and fringe patterns are preserved:

        F_total(G) = F_buffer(G) + exp(i Qₙ z_buf) · F_unit(G) · S_rep(Qₙ Λ)

        F_layer_i(G) = F_uc_i × N_eff_i × exp(i Qₙ z_i)

    Absorption limiting (Beer-Lambert) is applied on top of extinction:
    the effective cell count is `min(N_eff_darwin, N_eff_absorption)`.

    **Alloys**
    Any `xu.materials.Crystal`-compatible object can be used as the layer
    crystal, including alloys created with xrayutilities (e.g.
    `xu.materials.HexagonalAlloy`, VCA compositions, etc.).  The
    composition enters through the structure factor `F_uc` and the unit-cell
    volume `V_uc`.

    Args:
    stack : LayeredCrystal
        Same input as :func:`simulate_laue_stack`.
    camera : Camera
    E_min_eV, E_max_eV : float
    source : str
        See :func:`simulate_laue_stack` and :func:`_make_spectrum_fn` for the
        full list (`'bending_magnet'`, `'wiggler'`, `'undulator'`,
        `'flat'`, `'shadow4'`, `'tabulated'`).
    source_kwargs : dict, optional
    f2_thresh : float
        Minimum Darwin-corrected |F_total|² to keep a spot.
    ki_hat : array-like (3,) or None
    kb_params : dict or None
    max_satellites : int, optional
        Number of satellite / fringe orders to probe on each side of every
        Bragg peak (default 5).  Probes orders ±1 … ±max_satellites.
        Set to 0 to skip satellite calculation entirely.
    structure_model : {'coherent', 'average'}, optional
        See :func:`simulate_laue_stack` for full description.  In
        `'average'` mode G vectors are enumerated from buffer layers only,
        intra-period `exp(i Qₙ z_rel)` phases are dropped, and `S_rep`
        is kept — producing a single average Bragg peak with satellites, as
        seen in a monochromatic scan.  Darwin-corrected `N_eff` values are
        still computed and reported in the returned `'N_eff'` key.
    allowed_hkl : frozenset or dict or None, optional
        Pre-computed set of allowed reflections from
        :func:`precompute_allowed_hkl`.  When supplied, systematically absent
        reflections are filtered **before** any geometry computation, avoiding
        :func:`_darwin_amp` calls for forbidden hkl.  Accepts:

        * ``frozenset`` — shared across all phases (useful when all layers
          have the same crystal type).
        * ``dict`` mapping ``id(crystal)`` → ``frozenset`` — per-crystal
          sets, as returned by the internal cache.

        Default ``None``: all (h, k, l) in the sphere pass to the Laue
        condition check, relying on the structure factor threshold to reject
        forbidden reflections.
    correct_depth : bool, optional
        When ``True``, each layer's spots are projected from the beam-path
        depth of that layer's centre rather than from the sample surface
        (depth = 0).  The depth is taken from :func:`_layer_depths_mm` and
        divided by ``cos(angle between ki and surface normal)`` to convert
        from normal-direction depth to along-beam displacement, which is
        then passed as ``source_depth_mm`` to ``camera.project()``.

        This corrects the **depth-parallax** shift: in reflection geometry
        a spot originating at depth *z* exits from a laterally displaced
        surface point, causing substrate spots to appear at a different
        detector position than surface or film spots.  Default ``False``
        (all spots projected from the surface, matching the behaviour of
        :func:`simulate_laue_stack`).
    sigma_h_mrad, sigma_v_mrad : float, optional
        Horizontal / vertical beam divergence 1σ (mrad).  See
        :func:`beam_divergence_ellipses`.  Typical BM32/ESRF: 2–3 / 0.2–0.5.
    sigma_beam_h_nm, sigma_beam_v_nm : float, optional
        Beam footprint size 1σ at the sample (nm).  Requires
        ``n_hat_sample`` to activate footprint broadening.
    n_hat_sample : array-like (3,), optional
        Sample surface normal in the LT frame (for footprint broadening).
    verbose : bool

    Returns:
    spots : list[dict]
        Same keys as :func:`simulate_laue_stack` — including the
        coincident-reflection accumulation (`n_harmonics`, `harmonic_hkls`,
        `harmonic_F2`, `harmonic_I_raw`) — plus:

        ``'N_eff'``          list of Darwin N_eff per layer (buffer layers
                             then block layers), for **this spot's own**
                             contributing reflection — not summed across
                             `harmonic_hkls`
        ``'N_ext'``          list of extinction lengths (unit cells) per layer,
                             same per-spot scope as `N_eff`
        ``'F2_darwin'``      ``|F_total_darwin|²`` (same value as `F2`)
        ``'source_depth_mm'``  beam-path depth used for projection (mm);
                             0.0 when ``correct_depth=False``

    Note:
    As with :func:`simulate_laue_stack`, a multi-block `stack` is
    transparently flattened via
    :func:`~nrxrdct.laue.layers.combine_stacks` before simulation.

    **Performance**
    The Darwin amplitude (`F_uc` per layer, plus the extinction-saturated
    `N_eff` and, when `kf_hat`-dependent absorption applies, `μ(E)`) is
    evaluated in energy bins (`_STRUCTURE_FACTOR_ENERGY_BINS`, default 200)
    across every surviving candidate at once, rather than one full
    per-candidate Darwin calculation each — this is the difference between
    a satellite-heavy stack finishing in ~20 s versus not finishing in any
    practical time (it did not complete within 180 s before this change on
    the same benchmark stack). Worst-case `F2` error at the default 200
    bins is ~5% vs. the exact per-candidate-energy value; see
    `_STRUCTURE_FACTOR_ENERGY_BINS`'s definition for the full benchmark and
    the accuracy/speed tradeoff of changing it.
"""
    stack = _flatten_if_multiblock(stack)
    stack._update_offsets()
    source_kwargs = source_kwargs or {}
    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki /= np.linalg.norm(ki)

    # ── Depth correction ──────────────────────────────────────────────────────
    _depth_mm_state = [0.0]
    if correct_depth:
        _depths_mm_raw = _layer_depths_mm(stack)
        _n_hat_norm = np.asarray(stack.n_hat, dtype=float)
        _n_hat_norm = _n_hat_norm / np.linalg.norm(_n_hat_norm)
        _cos_inc = abs(float(np.dot(ki, _n_hat_norm)))
        if _cos_inc > 1e-6:
            _depths_mm = {k: v / _cos_inc for k, v in _depths_mm_raw.items()}
        else:
            _depths_mm = _depths_mm_raw
    else:
        _depths_mm = {}

    lam_lo = en2lam(E_max_eV)
    lam_hi = en2lam(E_min_eV)

    _spectrum = _make_spectrum_fn(source, source_kwargs, kb_params)

    # ── Fringe / satellite wavevectors ────────────────────────────────────────
    # Same logic as simulate_laue_stack: probe G_hkl + frac * q_fringe
    # where frac = m ± 0.5  (bright-fringe maxima between dark zeros).
    MAX_FRINGE_THICK_ANG = 20_000.0
    fringe_q_vecs: list = []
    sat_orders = [m for m in range(-max_satellites, max_satellites + 1) if m != 0]

    if max_satellites > 0 and stack.layers:
        seen_t: set = set()
        for lyr in stack.layers:
            t = lyr.thickness
            if t < 1e-6 or t > MAX_FRINGE_THICK_ANG:
                continue
            t_key = round(t, 2)
            if t_key in seen_t:
                continue
            seen_t.add(t_key)
            q_vec = (2.0 * np.pi / t) * np.asarray(stack.n_hat)
            fringe_q_vecs.append((q_vec, f"layer '{lyr.label}' (t={t/10:.1f} nm)"))

        Lambda = stack.bilayer_thickness
        if stack.n_rep > 1 and Lambda > 1e-6:
            t_key = round(Lambda, 2)
            if t_key not in seen_t:
                q_vec = (2.0 * np.pi / Lambda) * np.asarray(stack.n_hat)
                fringe_q_vecs.append((q_vec, f"bilayer Λ={Lambda/10:.1f} nm"))

    if verbose and fringe_q_vecs:
        print("  Fringe / satellite periods to probe:")
        for qv, desc in fringe_q_vecs:
            t_nm = 2.0 * np.pi / np.linalg.norm(qv) / 10.0
            print(f"    {desc}  →  2π/t = {np.linalg.norm(qv):.4f} Å⁻¹  (t = {t_nm:.2f} nm)")

    # Darwin amplitude helper is now the module-level _darwin_amp_batch
    # (shared with qspace_around_spot) — called below via
    # _darwin_amp_batch(stack, ki, structure_model, ...).

    # Pixel → spots-index map — see _merge_or_append_spot for why coincident
    # reflections (harmonics, etc.) are accumulated rather than discarded.
    seen_pix: dict = {}
    spots: list = []

    # ── Deduplicate orientations for enumeration ──────────────────────────────
    # In average mode enumerate from buffer layers plus the first MQW layer.
    # Same reasoning as simulate_laue_stack: a dissimilar substrate (sapphire,
    # SrTiO3 …) has G vectors at completely different positions from the film,
    # so substrate-only enumeration would miss all film reflections.  Adding
    # the first MQW layer guarantees that film G vectors are always probed.
    # Crystal+orientation deduplication below removes any true duplicate.
    if structure_model == "average":
        _enum_pool = stack.buffer_layers + stack.layers[:1]
    else:
        _enum_pool = stack.all_layers

    seen_combos: list = []
    enum_layers: list = []
    for layer in _enum_pool:
        u_key = (layer.crystal.name, tuple(np.round(layer.U, 4).ravel()))
        if u_key not in seen_combos:
            seen_combos.append(u_key)
            enum_layers.append(layer)

    # Buffer layers provide Bragg peaks only — satellites around substrate
    # G vectors combined with film fringe q vectors are physically meaningless.
    _buffer_set = set(id(l) for l in stack.buffer_layers)

    for enum_layer in enum_layers:
        U = enum_layer.U
        crystal = enum_layer.crystal
        label = enum_layer.label

        if correct_depth:
            _depth_mm_state[0] = _depths_mm.get(id(enum_layer), 0.0)

        layer_has_satellites = id(enum_layer) not in _buffer_set and bool(fringe_q_vecs)
        sat_info = f", ±{max_satellites} satellite orders" if layer_has_satellites else ""

        # Sphere enumeration limits for this layer's crystal
        HC_eV_ANG = 12398.4
        G_max = 4.0 * np.pi * E_max_eV / HC_eV_ANG
        G_max_sq = G_max ** 2
        a_star = float(np.linalg.norm(crystal.Q(1, 0, 0)))
        b_star = float(np.linalg.norm(crystal.Q(0, 1, 0)))
        c_star = float(np.linalg.norm(crystal.Q(0, 0, 1)))
        h_lim = int(G_max / a_star) + 1
        k_lim = int(G_max / b_star) + 1
        l_lim = int(G_max / c_star) + 1

        if verbose:
            print(f"  Enumerating {label} (G_max={G_max:.2f} Å⁻¹{sat_info}) ...", end="", flush=True)

        n_added = 0

        # ── Vectorised geometry — mirrors simulate_laue_stack ─────────────────
        # Build B matrix once; Q(h,k,l) = B @ [h,k,l] by linearity.
        _B = np.column_stack([crystal.Q(1, 0, 0), crystal.Q(0, 1, 0),
                              crystal.Q(0, 0, 1)])
        _HS, _KS, _LS = np.meshgrid(
            np.arange(-h_lim, h_lim + 1, dtype=np.int32),
            np.arange(-k_lim, k_lim + 1, dtype=np.int32),
            np.arange(-l_lim, l_lim + 1, dtype=np.int32),
            indexing="ij",
        )
        _hkl_all = np.column_stack([_HS.ravel(), _KS.ravel(), _LS.ravel()])
        _hkl_all = _hkl_all[np.any(_hkl_all != 0, axis=1)]
        _G_cry_all = (_B @ _hkl_all.T).T                    # (N, 3)
        _in_sphere = np.einsum("ij,ij->i", _G_cry_all, _G_cry_all) <= G_max_sq
        _hkl_all = _hkl_all[_in_sphere]

        # allowed_hkl pre-filter: skip systematically absent reflections before
        # the geometry loop so _darwin_amp is never called for forbidden hkl.
        _layer_allowed = (
            allowed_hkl.get(id(crystal)) if isinstance(allowed_hkl, dict)
            else allowed_hkl
        )
        if _layer_allowed is not None and len(_hkl_all):
            _hkl_ok = np.fromiter(
                (tuple(int(x) for x in row) in _layer_allowed
                 for row in _hkl_all),
                dtype=bool, count=len(_hkl_all),
            )
            _hkl_all = _hkl_all[_hkl_ok]

        # G vectors in lab frame
        _G_lab_all = (_B @ _hkl_all.T).T @ U.T              # (M, 3)

        def _batch_darwin(G_lab_batch, hkl_batch, sat_order):
            """Geometry-filter a batch, call _darwin_amp on survivors, append."""
            if len(G_lab_batch) == 0:
                return 0
            kdG = G_lab_batch @ ki
            v1  = kdG < 0
            if not np.any(v1):
                return 0
            G_b   = G_lab_batch[v1];  hkl_b = hkl_batch[v1];  kdG_b = kdG[v1]
            Gm2_b = np.einsum("ij,ij->i", G_b, G_b)
            lam_b = -4.0 * np.pi * kdG_b / Gm2_b
            v2    = (lam_b >= lam_lo) & (lam_b <= lam_hi)
            if not np.any(v2):
                return 0
            G_b   = G_b[v2];   hkl_b = hkl_b[v2];   lam_b = lam_b[v2]
            E_b   = HC / lam_b
            km_b  = 2.0 * np.pi / lam_b
            kf_b  = ki[None, :] * km_b[:, None] + G_b
            kf_b /= np.linalg.norm(kf_b, axis=1, keepdims=True)
            pix_b, on_det_b = camera.project_batch(
                kf_b, source_depth_mm=_depth_mm_state[0])
            if not np.any(on_det_b):
                return 0
            G_b   = G_b[on_det_b];   hkl_b  = hkl_b[on_det_b]
            lam_b = lam_b[on_det_b]; E_b    = E_b[on_det_b]
            kf_b  = kf_b[on_det_b];  pix_b  = pix_b[on_det_b]
            tth_b = np.degrees(np.arccos(np.clip(kf_b[:, 0], -1.0, 1.0)))
            chi_b = np.degrees(np.arctan2(kf_b[:, 1], kf_b[:, 2] + 1e-17))
            az_b  = np.degrees(np.arctan2(kf_b[:, 2], kf_b[:, 1]))
            LP_b  = _lorentz_pol_vec(tth_b, E_b, chi_b)
            sw_b  = _spectrum(E_b)
            pre_ok = (LP_b > 0) & (sw_b > 0)
            pix_round = np.round(pix_b).astype(np.int64)
            eff_thresh = f2_thresh * 1e-4 if sat_order != 0 else f2_thresh
            n_new = 0
            ok_idx_dw = np.where(pre_ok)[0]
            if len(ok_idx_dw):
                F_total_all, n_effs_all, n_exts_all = _darwin_amp_batch(
                    stack, ki, structure_model,
                    G_b[ok_idx_dw], E_b[ok_idx_dw], lam_b[ok_idx_dw], tth_b[ok_idx_dw],
                    kf_hat_arr=kf_b[ok_idx_dw],
                )
                F2_all_dw = np.abs(F_total_all) ** 2
            else:
                F2_all_dw = np.empty(0)
                n_effs_all, n_exts_all = [], []
            for _pos, _si in enumerate(ok_idx_dw):
                pix_key = (int(pix_round[_si, 0]), int(pix_round[_si, 1]))
                F2 = float(F2_all_dw[_pos])
                n_effs, n_exts = n_effs_all[_pos], n_exts_all[_pos]
                if F2 < eff_thresh:
                    continue
                is_new = _merge_or_append_spot(spots, seen_pix, pix_key, {
                    "phase_label":     label,
                    "hkl":             (int(hkl_b[_si, 0]),
                                        int(hkl_b[_si, 1]),
                                        int(hkl_b[_si, 2])),
                    "satellite_order": sat_order,
                    "is_superlattice": sat_order != 0,
                    "G_lab":           G_b[_si].copy(),
                    "E":               float(E_b[_si]),
                    "lambda":          float(lam_b[_si]),
                    "tth":             float(tth_b[_si]),
                    "chi":             float(chi_b[_si]),
                    "az":              float(az_b[_si]),
                    "pix":             (float(pix_b[_si, 0]),
                                        float(pix_b[_si, 1])),
                    "source_depth_mm": _depth_mm_state[0],
                    "F2":              F2,
                    "F2_darwin":       F2,
                    "LP":              float(LP_b[_si]),
                    "sw":              float(sw_b[_si]),
                    "I_raw":           F2 * float(LP_b[_si]) * float(sw_b[_si]),
                    "N_eff":           n_effs,
                    "N_ext":           n_exts,
                })
                if is_new:
                    n_new += 1
            return n_new

        # Main Bragg peaks
        n_added += _batch_darwin(_G_lab_all, _hkl_all, 0)

        # Thickness fringes / superlattice satellites
        if layer_has_satellites:
            for q_fringe_vec, _ in fringe_q_vecs:
                for m in sat_orders:
                    frac = m + 0.5 if m > 0 else m - 0.5
                    _G_sat = _G_lab_all + frac * q_fringe_vec
                    n_added += _batch_darwin(_G_sat, _hkl_all, m)

        if verbose:
            print(f" {n_added} spots")

    if spots:
        imax = max(s["I_raw"] for s in spots)
        for s in spots:
            s["intensity"] = s["I_raw"] / imax

    spots.sort(key=lambda s: s["intensity"], reverse=True)
    beam_divergence_ellipses(
        spots, camera, sigma_h_mrad, sigma_v_mrad, ki_hat=ki,
        sigma_beam_h_nm=sigma_beam_h_nm,
        sigma_beam_v_nm=sigma_beam_v_nm,
        n_hat_sample=n_hat_sample,
    )

    if verbose:
        print(f"  Total spots (Darwin): {len(spots)}")
        if stack.layers and stack.n_rep > 1:
            print(
                f"  Superlattice satellite 2π/Λ = "
                f"{2*np.pi/stack.bilayer_thickness:.5f} Å⁻¹"
            )

    return spots

simulate_laue_multibeam

simulate_laue_multibeam(crystal, U, camera, E_min_eV: float = E_MIN_eV, E_max_eV: float = E_MAX_eV, source: str = 'bending_magnet', source_kwargs: dict | None = None, f2_thresh: float = F2_THRESHOLD, ki_hat=None, kb_params=BM32_KB, delta_E_rel: float = 0.005, umweg_f2_thresh: float | None = None, verbose: bool = True)

White-beam Laue simulation with N-beam (multi-beam) dynamical diffraction.

Extends :func:simulate_laue with Umweganregung (detour excitation): systematically-forbidden reflections that are activated via two-step scattering paths through the crystal.

Physics

In two-beam kinematical theory, a reflection \(\mathbf{G}_t\) with \(|F(\mathbf{G}_t)| = 0\) (systematic absence) produces no spot. When a secondary reflection \(\mathbf{G}_s\) is simultaneously in Bragg condition at the same energy \(E_t\), the beam can take the detour

.. math::

\mathbf{k}_i \xrightarrow{\mathbf{G}_s} \mathbf{k}_{int}
\xrightarrow{\mathbf{G}_r} \mathbf{k}_f

with \(\mathbf{G}_r = \mathbf{G}_t - \mathbf{G}_s\), producing a spot at the position \(\mathbf{G}_t\) would occupy even though \(F(\mathbf{G}_t) = 0\).

The Umweganregung amplitude at \(\mathbf{G}_t\) is

.. math::

A_t = \sum_{\mathbf{G}_s}
      \frac{F(\mathbf{G}_s)\,F(\mathbf{G}_r)}{\xi_s + i\,\delta_s}

where

  • \(\xi_s\) — excitation error of \(\mathbf{G}_s\) at energy \(E_t\) (Å⁻¹, positive when \(\mathbf{G}_s\) is not exactly in Bragg condition)
  • \(\delta_s = r_e \lambda |F(\mathbf{G}_s)| / (\pi V_{uc} \sin\theta_s)\) — Darwin half-width of \(\mathbf{G}_s\) (regularises the resonance when \(\xi_s \to 0\))

Resonance (\(\xi_s \approx 0\), i.e.\ \(E_s \approx E_t\)) gives the strongest contribution; off-resonance paths decay as \(1/\xi_s\).

All spots (kinematical + Umweganregung) are tagged with 'is_umweganregung' and extra diagnostic keys.

crystal : xrayutilities Crystal Single-crystal object (not a LayeredCrystal stack). U : ndarray, shape (3, 3) Orientation matrix in the LaueTools lab frame (beam along +x). camera : Camera Detector geometry. E_min_eV, E_max_eV : float Energy window (eV). source : str Synchrotron source model — same options as :func:simulate_laue. source_kwargs : dict or None f2_thresh : float Minimum \(|F|^2\) threshold for kinematical reflections. ki_hat : array-like (3,) or None Incident beam direction (defaults to :data:KI_HAT). kb_params : dict or None KB mirror reflectivity correction. delta_E_rel : float Relative energy tolerance for simultaneous excitation of a secondary beam \(\mathbf{G}_s\) at the primary energy \(E_t\):

.. math:: |E_s - E_t| / E_t < \text{delta\_E\_rel}

Default 0.005 (0.5 %).  Larger values find more (weaker) paths but
increase runtime and may produce spurious spots.

umweg_f2_thresh : float or None Minimum \(|A_t|^2\) to retain an Umweganregung spot. Defaults to 1e-4 * f2_thresh. verbose : bool

spots : list of dict All standard keys from :func:simulate_laue plus:

``'is_umweganregung'`` : bool
    True for spots produced by Umweganregung (forbidden kinematically).
``'umweg_paths'`` : list of dict
    For Umweganregung spots: one entry per contributing two-step path,
    containing ``'hkl_s'``, ``'hkl_r'``, ``'F_s'``, ``'F_r'``,
    ``'xi_s'``, ``'delta_s'``.  Empty list for kinematical spots.
``'n_umweg_paths'`` : int
    Number of contributing paths (0 for kinematical spots).
``'F2_umweg'`` : float
    $|A_t|^2$ for Umweganregung spots; 0 for kinematical spots.

Note: The coincident-reflection accumulation described in :func:simulate_laue (n_harmonics, harmonic_hkls, harmonic_F2, harmonic_I_raw) applies to the kinematical step only: harmonics of the same Bragg peak landing on the same pixel at different energies are summed there before Umweganregung paths are searched for. A kinematically-strong pixel (already merged, if applicable) always takes priority over a weaker Umweganregung contribution at the same position — the two mechanisms are not combined into one merged entry, since they are already mutually exclusive by construction (kin_pix_set excludes forbidden G_t whose pixel a kinematical spot already occupies).

Source code in src/nrxrdct/laue/simulation.py
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
6533
6534
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
def simulate_laue_multibeam(
    crystal,
    U,
    camera,
    E_min_eV: float = E_MIN_eV,
    E_max_eV: float = E_MAX_eV,
    source: str = "bending_magnet",
    source_kwargs: dict | None = None,
    f2_thresh: float = F2_THRESHOLD,
    ki_hat=None,
    kb_params=BM32_KB,
    delta_E_rel: float = 0.005,
    umweg_f2_thresh: float | None = None,
    verbose: bool = True,
):
    """
    White-beam Laue simulation with N-beam (multi-beam) dynamical diffraction.

    Extends :func:`simulate_laue` with **Umweganregung** (detour excitation):
    systematically-forbidden reflections that are activated via two-step
    scattering paths through the crystal.

    **Physics**

    In two-beam kinematical theory, a reflection $\\mathbf{G}_t$ with
    $|F(\\mathbf{G}_t)| = 0$ (systematic absence) produces no spot.  When a
    secondary reflection $\\mathbf{G}_s$ is simultaneously in Bragg condition
    at the same energy $E_t$, the beam can take the detour

    .. math::

        \\mathbf{k}_i \\xrightarrow{\\mathbf{G}_s} \\mathbf{k}_{int}
        \\xrightarrow{\\mathbf{G}_r} \\mathbf{k}_f

    with $\\mathbf{G}_r = \\mathbf{G}_t - \\mathbf{G}_s$, producing a spot at
    the position $\\mathbf{G}_t$ would occupy even though
    $F(\\mathbf{G}_t) = 0$.

    The Umweganregung amplitude at $\\mathbf{G}_t$ is

    .. math::

        A_t = \\sum_{\\mathbf{G}_s}
              \\frac{F(\\mathbf{G}_s)\\,F(\\mathbf{G}_r)}{\\xi_s + i\\,\\delta_s}

    where

    * $\\xi_s$ — excitation error of $\\mathbf{G}_s$ at energy $E_t$
      (Å⁻¹, positive when $\\mathbf{G}_s$ is not exactly in Bragg condition)
    * $\\delta_s = r_e \\lambda |F(\\mathbf{G}_s)| / (\\pi V_{uc} \\sin\\theta_s)$ —
      Darwin half-width of $\\mathbf{G}_s$ (regularises the resonance when
      $\\xi_s \\to 0$)

    Resonance ($\\xi_s \\approx 0$, i.e.\\ $E_s \\approx E_t$) gives the
    strongest contribution; off-resonance paths decay as $1/\\xi_s$.

    All spots (kinematical + Umweganregung) are tagged with
    ``'is_umweganregung'`` and extra diagnostic keys.

    Args:
    crystal : xrayutilities Crystal
        Single-crystal object (not a LayeredCrystal stack).
    U : ndarray, shape (3, 3)
        Orientation matrix in the LaueTools lab frame (beam along +x).
    camera : Camera
        Detector geometry.
    E_min_eV, E_max_eV : float
        Energy window (eV).
    source : str
        Synchrotron source model — same options as :func:`simulate_laue`.
    source_kwargs : dict or None
    f2_thresh : float
        Minimum $|F|^2$ threshold for **kinematical** reflections.
    ki_hat : array-like (3,) or None
        Incident beam direction (defaults to :data:`KI_HAT`).
    kb_params : dict or None
        KB mirror reflectivity correction.
    delta_E_rel : float
        Relative energy tolerance for simultaneous excitation of a secondary
        beam $\\mathbf{G}_s$ at the primary energy $E_t$:

        .. math:: |E_s - E_t| / E_t < \\text{delta\\_E\\_rel}

        Default 0.005 (0.5 %).  Larger values find more (weaker) paths but
        increase runtime and may produce spurious spots.
    umweg_f2_thresh : float or None
        Minimum $|A_t|^2$ to retain an Umweganregung spot.
        Defaults to ``1e-4 * f2_thresh``.
    verbose : bool

    Returns:
    spots : list of dict
        All standard keys from :func:`simulate_laue` plus:

        ``'is_umweganregung'`` : bool
            True for spots produced by Umweganregung (forbidden kinematically).
        ``'umweg_paths'`` : list of dict
            For Umweganregung spots: one entry per contributing two-step path,
            containing ``'hkl_s'``, ``'hkl_r'``, ``'F_s'``, ``'F_r'``,
            ``'xi_s'``, ``'delta_s'``.  Empty list for kinematical spots.
        ``'n_umweg_paths'`` : int
            Number of contributing paths (0 for kinematical spots).
        ``'F2_umweg'`` : float
            $|A_t|^2$ for Umweganregung spots; 0 for kinematical spots.

    Note:
    The coincident-reflection accumulation described in :func:`simulate_laue`
    (`n_harmonics`, `harmonic_hkls`, `harmonic_F2`, `harmonic_I_raw`) applies
    to the **kinematical** step only: harmonics of the same Bragg peak
    landing on the same pixel at different energies are summed there before
    Umweganregung paths are searched for.  A kinematically-strong pixel
    (already merged, if applicable) always takes priority over a weaker
    Umweganregung contribution at the same position — the two mechanisms are
    not combined into one merged entry, since they are already mutually
    exclusive by construction (`kin_pix_set` excludes forbidden `G_t` whose
    pixel a kinematical spot already occupies).
"""
    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki /= np.linalg.norm(ki)
    U = np.asarray(U, dtype=float)
    source_kwargs = source_kwargs or {}
    if umweg_f2_thresh is None:
        umweg_f2_thresh = 1e-4 * f2_thresh

    _spectrum = _make_spectrum_fn(source, source_kwargs, kb_params)

    lam_lo = en2lam(E_max_eV)
    lam_hi = en2lam(E_min_eV)

    # ── Build reciprocal lattice matrix ───────────────────────────────────────
    B = np.column_stack([crystal.Q(1, 0, 0), crystal.Q(0, 1, 0), crystal.Q(0, 0, 1)])
    V_uc = float(crystal.lattice.UnitCellVolume())

    HC_eV_ANG = 12398.4
    G_max = 4.0 * np.pi * E_max_eV / HC_eV_ANG
    G_max_sq = G_max ** 2

    a_star = float(np.linalg.norm(B[:, 0]))
    b_star = float(np.linalg.norm(B[:, 1]))
    c_star = float(np.linalg.norm(B[:, 2]))
    h_lim = int(G_max / a_star) + 1
    k_lim = int(G_max / b_star) + 1
    l_lim = int(G_max / c_star) + 1

    # ── Enumerate all G in sphere ─────────────────────────────────────────────
    hv = np.arange(-h_lim, h_lim + 1, dtype=np.int32)
    kv = np.arange(-k_lim, k_lim + 1, dtype=np.int32)
    lv = np.arange(-l_lim, l_lim + 1, dtype=np.int32)
    H, K, L = np.meshgrid(hv, kv, lv, indexing="ij")
    hkl_all = np.column_stack([H.ravel(), K.ravel(), L.ravel()])
    hkl_all = hkl_all[np.any(hkl_all != 0, axis=1)]

    G_cry_all = (B @ hkl_all.T).T                                   # (N, 3)
    G_sq_all  = np.einsum("ij,ij->i", G_cry_all, G_cry_all)
    in_sphere = G_sq_all <= G_max_sq
    hkl_all   = hkl_all[in_sphere]
    G_cry_all = G_cry_all[in_sphere]

    G_lab_all = G_cry_all @ U.T                                      # (N, 3)
    kdG_all   = G_lab_all @ ki                                       # (N,)

    # Laue energies for all G (NaN where kdG >= 0, i.e. not in Bragg condition)
    G_sq_lab  = np.einsum("ij,ij->i", G_lab_all, G_lab_all)
    with np.errstate(invalid="ignore", divide="ignore"):
        lam_all = np.where(
            kdG_all < 0,
            -4.0 * np.pi * kdG_all / G_sq_lab,
            np.nan,
        )
    E_laue_all = np.where(np.isfinite(lam_all), HC_eV_ANG / lam_all, np.nan)

    # Index map: (h, k, l) → position in hkl_all (for fast G_r lookup)
    _hkl_index: dict[tuple, int] = {
        (int(hkl_all[i, 0]), int(hkl_all[i, 1]), int(hkl_all[i, 2])): i
        for i in range(len(hkl_all))
    }

    # Pre-compute structure factors for all G in sphere at a reference energy.
    # Per-spot energies can vary ±~5% from midpoint; using one reference is a
    # good approximation for the secondary-beam search (full F(E) is used for
    # the final amplitude calculation below).
    E_ref = 0.5 * (E_min_eV + E_max_eV)
    if verbose:
        print(f"  Computing structure factors for {len(hkl_all)} G vectors ...",
              end="", flush=True)
    F_ref_all = crystal.StructureFactorForQ(G_cry_all, en0=E_ref)   # (N,) complex
    F2_ref_all = np.abs(F_ref_all) ** 2
    if verbose:
        print(" done")

    # ── Step 1: kinematical spots (primary reflections on detector) ───────────
    in_energy = (lam_all >= lam_lo) & (lam_all <= lam_hi)
    kin_mask  = in_energy & (F2_ref_all >= f2_thresh)
    kin_idx   = np.where(kin_mask)[0]

    if verbose:
        print(f"  Kinematical candidates: {kin_mask.sum()}  (energy window + F² cut)")

    # Vectorised geometry (camera projection, LP, spectrum) for every kinematical
    # candidate at once, then structure factor batched by energy bin — one
    # xrayutilities call per bin instead of one scalar call per candidate.
    if len(kin_idx):
        lam_k = lam_all[kin_idx]
        E_k = HC_eV_ANG / lam_k
        G_lab_k = G_lab_all[kin_idx]
        km_k = 2.0 * np.pi / lam_k
        kf_k = ki[None, :] * km_k[:, None] + G_lab_k
        kf_k /= np.linalg.norm(kf_k, axis=1, keepdims=True)
        pix_k, on_det_k = camera.project_batch(kf_k)

        kin_idx_k = kin_idx[on_det_k]
        lam_k = lam_k[on_det_k]; E_k = E_k[on_det_k]; G_lab_k = G_lab_k[on_det_k]
        kf_k = kf_k[on_det_k]; pix_k = pix_k[on_det_k]

        tth_k = np.degrees(np.arccos(np.clip(kf_k[:, 0], -1.0, 1.0)))
        chi_k = np.degrees(np.arctan2(kf_k[:, 1], kf_k[:, 2] + 1e-17))
        az_k  = np.degrees(np.arctan2(kf_k[:, 2], kf_k[:, 1]))
        LP_k  = _lorentz_pol_vec(tth_k, E_k, chi_k)
        sw_k  = _spectrum(E_k)
        ok_k  = np.where((LP_k > 0) & (sw_k > 0))[0]

        if len(ok_k):
            F_k_all = _binned_structure_factor(
                G_cry_all[kin_idx_k[ok_k]], E_k[ok_k],
                lambda G, E, kf: crystal.StructureFactorForQ(G, en0=E),
                n_bins=_STRUCTURE_FACTOR_ENERGY_BINS,
            )
            F2_k_all = np.abs(F_k_all) ** 2
        else:
            F2_k_all = np.empty(0)
    else:
        kin_idx_k = np.empty(0, dtype=int)
        ok_k = np.empty(0, dtype=int)
        F2_k_all = np.empty(0)

    kin_spots: list[dict] = []
    # Pixel → kin_spots-index map — accumulates coincident reflections
    # (harmonics: hkl, 2·hkl, 3·hkl, ... landing on the same pixel at
    # different energies) instead of keeping every one as a separate,
    # unmerged entry.  See _merge_or_append_spot.
    _kin_seen_pix: dict = {}
    for _pos, _oi in enumerate(ok_k):
        F2 = float(F2_k_all[_pos])
        if F2 < f2_thresh:
            continue
        idx = kin_idx_k[_oi]
        hkl = (int(hkl_all[idx, 0]), int(hkl_all[idx, 1]), int(hkl_all[idx, 2]))
        pix = (float(pix_k[_oi, 0]), float(pix_k[_oi, 1]))
        pix_key = (round(pix[0]), round(pix[1]))
        E = float(E_k[_oi]); LP = float(LP_k[_oi]); sw = float(sw_k[_oi])
        _merge_or_append_spot(kin_spots, _kin_seen_pix, pix_key, {
            "hkl":              hkl,
            "is_umweganregung": False,
            "umweg_paths":      [],
            "n_umweg_paths":    0,
            "F2_umweg":         0.0,
            "G_lab":            G_lab_k[_oi].copy(),
            "E":                E,
            "lambda":           float(lam_k[_oi]),
            "tth":              float(tth_k[_oi]),
            "chi":              float(chi_k[_oi]),
            "az":               float(az_k[_oi]),
            "pix":              pix,
            "F2":               F2,
            "LP":               LP,
            "sw":               sw,
            "I_raw":            F2 * LP * sw,
        })

    if verbose:
        print(f"  Kinematical spots on detector: {len(kin_spots)}")

    # Set of pixel positions already claimed by kinematical spots (coarse grid)
    kin_pix_set: set[tuple] = {
        (round(s["pix"][0]), round(s["pix"][1])) for s in kin_spots
    }

    # ── Step 2: Umweganregung — forbidden G_t in energy range ─────────────────
    # Forbidden: |F_t|² < f2_thresh but G_t is in energy window and hits detector
    forbidden_mask = in_energy & (F2_ref_all < f2_thresh)
    forbidden_idx  = np.where(forbidden_mask)[0]

    if verbose:
        print(f"  Forbidden G vectors in energy window: {forbidden_mask.sum()}")
        print(f"  Searching for Umweganregung paths (delta_E_rel={delta_E_rel:.3f}) ...")

    umweg_spots: list[dict] = []
    n_forbidden_on_det = 0

    # Precompute per-G normalised Laue energies for fast tolerance check
    E_laue_finite = np.where(np.isfinite(E_laue_all), E_laue_all, -1.0)

    for idx_t in forbidden_idx:
        lam_t = float(lam_all[idx_t])
        E_t   = HC_eV_ANG / lam_t
        G_lab_t = G_lab_all[idx_t]
        km_t    = 2.0 * np.pi / lam_t
        kf_t    = ki * km_t + G_lab_t
        kf_hat_t = kf_t / np.linalg.norm(kf_t)

        pix_t = camera.project(kf_hat_t)
        if pix_t is None:
            continue
        pix_key_t = (round(pix_t[0]), round(pix_t[1]))
        if pix_key_t in kin_pix_set:
            # Position already occupied by a kinematical spot — skip
            continue

        n_forbidden_on_det += 1

        tth_t = float(np.degrees(np.arccos(np.clip(kf_hat_t[0], -1.0, 1.0))))
        chi_t = float(np.degrees(np.arctan2(kf_hat_t[1], kf_hat_t[2] + 1e-17)))
        LP_t  = lorentz_pol(tth_t, E_t, chi_t)
        if LP_t == 0.0:
            continue
        sw_t = _spectrum(E_t)
        if sw_t <= 0.0:
            continue

        # ── Find secondary beams G_s with E_s ≈ E_t ──────────────────────────
        # Simultaneous excitation condition: |E_s - E_t| / E_t < delta_E_rel
        near_mask = (
            np.isfinite(E_laue_all)
            & (np.abs(E_laue_finite - E_t) / E_t < delta_E_rel)
        )
        near_idx = np.where(near_mask)[0]

        hkl_t = (int(hkl_all[idx_t, 0]),
                 int(hkl_all[idx_t, 1]),
                 int(hkl_all[idx_t, 2]))

        A_total  = 0.0 + 0j
        paths    = []
        # Normalization constant for this G_t: r_e λ / (π V_uc) makes
        # |A_total|² comparable in units to kinematical |F_uc|²
        norm = _R_E_ANG * lam_t / (np.pi * V_uc)

        for idx_s in near_idx:
            hs, ks, ls = int(hkl_all[idx_s, 0]), int(hkl_all[idx_s, 1]), int(hkl_all[idx_s, 2])

            # G_r must be in our sphere enumeration
            hr, kr, lr = hkl_t[0] - hs, hkl_t[1] - ks, hkl_t[2] - ls
            if (hr, kr, lr) == (0, 0, 0):
                continue
            idx_r = _hkl_index.get((hr, kr, lr))
            if idx_r is None:
                continue

            F_s_ref = F_ref_all[idx_s]
            F_r_ref = F_ref_all[idx_r]
            if abs(F_s_ref) < 1e-6 or abs(F_r_ref) < 1e-6:
                continue

            # Evaluate structure factors at exact energy E_t
            F_s = crystal.StructureFactor(G_cry_all[idx_s], en=E_t)
            F_r = crystal.StructureFactor(G_cry_all[idx_r], en=E_t)
            if abs(F_s) < 1e-8 or abs(F_r) < 1e-8:
                continue

            # Excitation error of G_s at energy E_t (Å⁻¹)
            # ξ_s = k_m(E_t) · (k_hat · G_s_lab) + G_s²/2
            xi_s = float(km_t * float(ki @ G_lab_all[idx_s])
                         + 0.5 * float(G_sq_lab[idx_s]))

            # Darwin half-width δ_s = r_e λ |F_s| / (π V_uc sin θ_s)
            # θ_s is the Bragg angle G_s WOULD have at E_t
            cos_tth_s = float(np.clip(
                (ki * km_t + G_lab_all[idx_s]) @ (ki * km_t + G_lab_all[idx_s]),
                0.0, None,
            ))
            # simpler: use tth_t as proxy for the angular factor (same order)
            sin_th_s  = max(abs(np.sin(np.radians(tth_t / 2.0))), 1e-6)
            delta_s   = (_R_E_ANG * lam_t * abs(F_s)
                         / (np.pi * V_uc * sin_th_s))

            denom = xi_s + 1j * delta_s
            A_path = norm * F_s * F_r / denom
            A_total += A_path

            paths.append({
                "hkl_s":   (hs, ks, ls),
                "hkl_r":   (hr, kr, lr),
                "F_s":     complex(F_s),
                "F_r":     complex(F_r),
                "xi_s":    xi_s,
                "delta_s": delta_s,
            })

        if not paths:
            continue

        F2_umweg = abs(A_total) ** 2
        if F2_umweg < umweg_f2_thresh:
            continue

        chi_t = float(np.degrees(np.arctan2(kf_hat_t[1], kf_hat_t[2] + 1e-17)))
        az_t  = float(np.degrees(np.arctan2(kf_hat_t[2], kf_hat_t[1])))

        umweg_spots.append({
            "hkl":              hkl_t,
            "is_umweganregung": True,
            "umweg_paths":      paths,
            "n_umweg_paths":    len(paths),
            "F2_umweg":         F2_umweg,
            "G_lab":            G_lab_t.copy(),
            "E":                E_t,
            "lambda":           lam_t,
            "tth":              tth_t,
            "chi":              chi_t,
            "az":               az_t,
            "pix":              pix_t,
            "F2":               F2_umweg,
            "LP":               LP_t,
            "sw":               sw_t,
            "I_raw":            F2_umweg * LP_t * sw_t,
        })

    if verbose:
        print(f"  Forbidden G on detector (not obscured): {n_forbidden_on_det}")
        print(f"  Umweganregung spots found: {len(umweg_spots)}")

    # ── Merge and normalise ───────────────────────────────────────────────────
    all_spots = kin_spots + umweg_spots
    if all_spots:
        imax = max(s["I_raw"] for s in all_spots)
        for s in all_spots:
            s["intensity"] = s["I_raw"] / imax

    all_spots.sort(key=lambda s: s["I_raw"], reverse=True)

    if verbose:
        print(f"  Total spots (multi-beam): {len(all_spots)}  "
              f"({len(kin_spots)} kinematical + {len(umweg_spots)} Umweganregung)")

    return all_spots

simulate_laue_stack

simulate_laue_stack(stack, camera, E_min_eV=5000, E_max_eV=27000, source='bending_magnet', source_kwargs=None, f2_thresh=None, ki_hat=None, max_satellites=5, kb_params=BM32_KB, structure_model='average', sigma_h_mrad=0.0, sigma_v_mrad=0.0, sigma_beam_h_nm=0.0, sigma_beam_v_nm=0.0, n_hat_sample=None, verbose=True, geometry_only=False, allowed_hkl=None, correct_depth=False)

Compute Laue spots for a LayeredCrystal stack projected onto camera.

For each phase in the stack the reciprocal lattice is enumerated using the sphere criterion |G_hkl| ≤ G_max = 4π·E_max_eV/12398.4 Å⁻¹. Every G_lab that satisfies the Laue condition within the energy window is kept, and the structure factor is evaluated on the full stack at that Q. This ensures coherent superposition of all layers and natural emergence of superlattice satellites.

stack : LayeredCrystal The layered structure (from layers.py). camera : Camera Detector geometry (from camera.py). E_min_eV, E_max_eV : float Energy window (eV). source : str Synchrotron source model. See :func:_make_spectrum_fn for full details. Summary:

* `'bending_magnet'` *(default)* — Kim 1989 analytical formula, fast.
* `'wiggler'` — same formula × N poles.
* `'undulator'` — Gaussian harmonic model.
* `'flat'` — uniform weight, useful for testing.
* `'shadow4'` — full Monte Carlo via Shadow4 + xraylib tracing
  SBM32 → M1 (Ir) → M2 (Ir) → KB (Rh).  Runs once per call; slow
  (~1–2 min for 1 M rays).  Pass `kb_params=None`.
* `'tabulated'` — arbitrary pre-computed spectrum supplied via
  `source_kwargs`.  Pass `kb_params=None`.
dict, optional

Extra arguments for the chosen source:

  • 'bending_magnet' / 'wiggler' : Ec_eV, N_poles
  • 'undulator' : E1_eV, n_harm, sig_rel
  • 'shadow4' : nrays (default 1 000 000), n_energy_bins (default 250)
  • 'tabulated' : energy_eV (array), flux (array)
dict or None, optional

KB mirror reflectivity correction applied by multiplying the source spectrum by :func:kb_reflectivity at each photon energy. The dict is forwarded as keyword arguments. Defaults to :data:BM32_KB (Rh-coated, 2.5 mrad, 2 mirrors, 3 Å roughness — BM32/ESRF). Pass None to disable, and must be None for 'shadow4' and 'tabulated' sources (reflectivity already included)::

spots = simulate_laue_stack(stack, cam)               # BM32_KB default
spots = simulate_laue_stack(stack, cam, kb_params=None)  # no correction

Keys: material, grazing_angle_mrad, n_mirrors, roughness_ang.

f2_thresh : float or None, optional Minimum |F_stack|² for a main Bragg peak to be kept (absolute, in e.u.²). Satellites use a separate, fixed floor (F2_THRESHOLD) regardless of this value — see Note below. None (default) uses the module baseline F2_THRESHOLD (1e-6), i.e. essentially no filtering; rank/filter the returned list by intensity afterwards instead. Because F2_stack is a coherent sum it scales roughly as (N_cells × N_rep)² at each layer's own Bragg peaks (many orders of magnitude between a thin film and a thick substrate in the same stack), so there is no single stack-wide value that reliably separates "real" from "negligible" reflections — pass an explicit value only if you've checked it against your own stack's F2 range, not as a general-purpose noise filter.

Note: satellites are **always** thresholded against the fixed
`F2_THRESHOLD` floor directly, never against `f2_thresh` (or a
fraction of it, as in earlier versions of this function). A
relative rule ("satellite must be ≥ 1e-4 of its parent peak")
breaks down whenever the parent's own `F2` happens to coincide with
a much stronger, unrelated reflection elsewhere in the stack — e.g.
an unstrained film sublayer that is lattice-matched to a much
thicker buffer, which is a common real situation, not an edge case
(this previously caused entire film layers, and every one of their
satellites, to be silently dropped).

ki_hat : array-like (3,), optional Incident beam direction in the LaueTools LT frame (x // beam). Default: [1, 0, 0]. structure_model : {'coherent', 'average'}, optional Controls how the MQW repeating unit structure factor is evaluated and which crystals are used to enumerate candidate G vectors.

* `'coherent'` — full layer-by-layer coherent sum: each layer
  contributes `F_uc_i × N_eff_i × exp(i Qₙ z_rel_i)` within the
  period, multiplied by `S_rep` over `N_rep` periods.  G vectors
  are enumerated from **every** unique crystal in the stack, so
  slightly displaced GaN and InGaN Bragg peaks appear separately.
  Reproduces superlattice satellites and thickness fringes at their
  physically correct relative intensities.
* `'average'` *(default)* — treats the MQW period as a single
  effective material.  G vectors are enumerated **only from the
  buffer layers** (or the first MQW layer if no buffers exist), so
  only one set of Bragg positions is produced — matching what is seen
  in a monochromatic scan.  The structure factor per period is the
  composition-weighted sum `Σ F_uc_i × N_eff_i` (no intra-period
  `exp(i Qₙ z_rel)` phases), then multiplied by `S_rep`.
  Satellite positions and `N_rep`-dependent peak widths are
  identical to the coherent model; intensities reflect the average
  composition rather than the layer-ordering interference.

Note: strained d-spacings (from :meth:`add_pseudomorphic_layer`)
enter through `N_eff = thickness / d_strained` in both modes.
The unit-cell structure factor amplitude `F_uc` uses the bulk
crystal in both cases.

sigma_h_mrad : float, optional Horizontal beam divergence 1σ (mrad). When non-zero, :func:beam_divergence_ellipses is called automatically and every spot receives broadening keys (cov_px, sigma_major_px, …). Typical BM32/ESRF value: 2–3 mrad. Default: 0 (no broadening). sigma_v_mrad : float, optional Vertical beam divergence 1σ (mrad). Typical BM32/ESRF value: 0.2–0.5 mrad. Default: 0. verbose : bool

spots : list of dicts Same format as simulate_laue() — including n_harmonics, harmonic_hkls, harmonic_F2, harmonic_I_raw (see there for what these mean; the same coincident-reflection accumulation applies here, across both main Bragg peaks and satellites) — plus extra keys: 'phase_label' – which phase's hkl triggered this candidate 'F2_stack' – |F_stack|² (full coherent stack; same value as F2)

Note: For a stack with many layers / large N_cells the absolute values of F2_stack can be large (~N² × single-cell value at Bragg peaks). The returned intensity key is always normalised 0–1 within the returned list.

Performance The structure factor is evaluated for every surviving candidate in one vectorised batch per energy bin (_STRUCTURE_FACTOR_ENERGY_BINS, default 200), for both main Bragg peaks and satellites, instead of one stack.structure_factor() call per candidate — this is what makes a satellite-heavy stack (tens of thousands of candidates once harmonics and fringe orders are included) tractable at all. Benchmarked on a ~10k-candidate satellite-heavy superlattice: ~3.5 s at the default 200 bins (worst-case F2 error ~3–4% vs. the exact per-candidate-energy value), versus ~60 s for the exact (one-call-per-candidate) result. Increase/decrease _STRUCTURE_FACTOR_ENERGY_BINS to trade accuracy for speed differently.

Note: If stack has several independently-repeated blocks (see :meth:~nrxrdct.laue.layers.LayeredCrystal.add_layer), it is transparently flattened via :func:~nrxrdct.laue.layers.combine_stacks before simulation -- you can pass a multi-block stack directly, no manual flattening needed.

Source code in src/nrxrdct/laue/simulation.py
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
def simulate_laue_stack(
    stack,
    camera,
    E_min_eV=5_000,
    E_max_eV=27_000,
    source="bending_magnet",
    source_kwargs=None,
    f2_thresh=None,
    ki_hat=None,
    max_satellites=5,
    kb_params=BM32_KB,
    structure_model="average",
    sigma_h_mrad=0.0,
    sigma_v_mrad=0.0,
    sigma_beam_h_nm=0.0,
    sigma_beam_v_nm=0.0,
    n_hat_sample=None,
    verbose=True,
    geometry_only=False,
    allowed_hkl=None,
    correct_depth=False,
):
    """
    Compute Laue spots for a `LayeredCrystal` stack projected onto `camera`.

    For each phase in the stack the reciprocal lattice is enumerated using the
    sphere criterion |G_hkl| ≤ G_max = 4π·E_max_eV/12398.4 Å⁻¹.  Every
    G_lab that satisfies the Laue condition within the energy window is kept,
    and the structure factor is evaluated on the **full stack** at that Q.
    This ensures coherent superposition of all layers and natural emergence of
    superlattice satellites.

    Args:
    stack : LayeredCrystal
        The layered structure (from layers.py).
    camera : Camera
        Detector geometry (from camera.py).
    E_min_eV, E_max_eV : float
        Energy window  (eV).
    source : str
        Synchrotron source model.  See :func:`_make_spectrum_fn` for full
        details.  Summary:

        * `'bending_magnet'` *(default)* — Kim 1989 analytical formula, fast.
        * `'wiggler'` — same formula × N poles.
        * `'undulator'` — Gaussian harmonic model.
        * `'flat'` — uniform weight, useful for testing.
        * `'shadow4'` — full Monte Carlo via Shadow4 + xraylib tracing
          SBM32 → M1 (Ir) → M2 (Ir) → KB (Rh).  Runs once per call; slow
          (~1–2 min for 1 M rays).  Pass `kb_params=None`.
        * `'tabulated'` — arbitrary pre-computed spectrum supplied via
          `source_kwargs`.  Pass `kb_params=None`.

    source_kwargs : dict, optional
        Extra arguments for the chosen source:

        * `'bending_magnet'` / `'wiggler'` : `Ec_eV`, `N_poles`
        * `'undulator'`                       : `E1_eV`, `n_harm`, `sig_rel`
        * `'shadow4'`                         : `nrays` (default 1 000 000),
          `n_energy_bins` (default 250)
        * `'tabulated'`                       : `energy_eV` (array), `flux` (array)

    kb_params : dict or None, optional
        KB mirror reflectivity correction applied by multiplying the source
        spectrum by :func:`kb_reflectivity` at each photon energy.  The dict
        is forwarded as keyword arguments.  Defaults to :data:`BM32_KB`
        (Rh-coated, 2.5 mrad, 2 mirrors, 3 Å roughness — BM32/ESRF).
        Pass `None` to disable, and **must** be `None` for `'shadow4'`
        and `'tabulated'` sources (reflectivity already included)::

            spots = simulate_laue_stack(stack, cam)               # BM32_KB default
            spots = simulate_laue_stack(stack, cam, kb_params=None)  # no correction

        Keys: `material`, `grazing_angle_mrad`, `n_mirrors`,
        `roughness_ang`.
    f2_thresh : float or None, optional
        Minimum |F_stack|² for a **main Bragg peak** to be kept (absolute,
        in e.u.²).  Satellites use a separate, fixed floor (`F2_THRESHOLD`)
        regardless of this value — see Note below.
        `None` (default) uses the module baseline `F2_THRESHOLD` (1e-6),
        i.e. essentially no filtering; rank/filter the returned list by
        `intensity` afterwards instead.  Because `F2_stack` is a coherent
        sum it scales roughly as `(N_cells × N_rep)²` at each layer's own
        Bragg peaks (many orders of magnitude between a thin film and a
        thick substrate in the *same* stack), so there is no single
        stack-wide value that reliably separates "real" from "negligible"
        reflections — pass an explicit value only if you've checked it
        against your own stack's `F2` range, not as a general-purpose
        noise filter.

        Note: satellites are **always** thresholded against the fixed
        `F2_THRESHOLD` floor directly, never against `f2_thresh` (or a
        fraction of it, as in earlier versions of this function). A
        relative rule ("satellite must be ≥ 1e-4 of its parent peak")
        breaks down whenever the parent's own `F2` happens to coincide with
        a much stronger, unrelated reflection elsewhere in the stack — e.g.
        an unstrained film sublayer that is lattice-matched to a much
        thicker buffer, which is a common real situation, not an edge case
        (this previously caused entire film layers, and every one of their
        satellites, to be silently dropped).
    ki_hat : array-like (3,), optional
        Incident beam direction in the LaueTools LT frame (x // beam).
        Default: [1, 0, 0].
    structure_model : {'coherent', 'average'}, optional
        Controls how the MQW repeating unit structure factor is evaluated
        and which crystals are used to enumerate candidate G vectors.

        * `'coherent'` — full layer-by-layer coherent sum: each layer
          contributes `F_uc_i × N_eff_i × exp(i Qₙ z_rel_i)` within the
          period, multiplied by `S_rep` over `N_rep` periods.  G vectors
          are enumerated from **every** unique crystal in the stack, so
          slightly displaced GaN and InGaN Bragg peaks appear separately.
          Reproduces superlattice satellites and thickness fringes at their
          physically correct relative intensities.
        * `'average'` *(default)* — treats the MQW period as a single
          effective material.  G vectors are enumerated **only from the
          buffer layers** (or the first MQW layer if no buffers exist), so
          only one set of Bragg positions is produced — matching what is seen
          in a monochromatic scan.  The structure factor per period is the
          composition-weighted sum `Σ F_uc_i × N_eff_i` (no intra-period
          `exp(i Qₙ z_rel)` phases), then multiplied by `S_rep`.
          Satellite positions and `N_rep`-dependent peak widths are
          identical to the coherent model; intensities reflect the average
          composition rather than the layer-ordering interference.

        Note: strained d-spacings (from :meth:`add_pseudomorphic_layer`)
        enter through `N_eff = thickness / d_strained` in both modes.
        The unit-cell structure factor amplitude `F_uc` uses the bulk
        crystal in both cases.
    sigma_h_mrad : float, optional
        Horizontal beam divergence 1σ (mrad).  When non-zero,
        :func:`beam_divergence_ellipses` is called automatically and every
        spot receives broadening keys (`cov_px`, `sigma_major_px`, …).
        Typical BM32/ESRF value: 2–3 mrad.  Default: 0 (no broadening).
    sigma_v_mrad : float, optional
        Vertical beam divergence 1σ (mrad).
        Typical BM32/ESRF value: 0.2–0.5 mrad.  Default: 0.
    verbose : bool

    Returns:
    spots : list of dicts
        Same format as `simulate_laue()` — including `n_harmonics`,
        `harmonic_hkls`, `harmonic_F2`, `harmonic_I_raw` (see there for what
        these mean; the same coincident-reflection accumulation applies
        here, across both main Bragg peaks and satellites) — plus extra keys:
          `'phase_label'`  – which phase's hkl triggered this candidate
          `'F2_stack'`     – |F_stack|² (full coherent stack; same value as `F2`)

    Note:
    For a stack with many layers / large N_cells the absolute values of
    `F2_stack` can be large (~N² × single-cell value at Bragg peaks).
    The returned `intensity` key is always normalised 0–1 within the
    returned list.

    **Performance**
    The structure factor is evaluated for every surviving candidate in one
    vectorised batch per energy bin (`_STRUCTURE_FACTOR_ENERGY_BINS`,
    default 200), for both main Bragg peaks and satellites, instead of one
    `stack.structure_factor()` call per candidate — this is what makes a
    satellite-heavy stack (tens of thousands of candidates once harmonics
    and fringe orders are included) tractable at all.  Benchmarked on a
    ~10k-candidate satellite-heavy superlattice: ~3.5 s at the default 200
    bins (worst-case `F2` error ~3–4% vs. the exact per-candidate-energy
    value), versus ~60 s for the exact (one-call-per-candidate) result.
    Increase/decrease `_STRUCTURE_FACTOR_ENERGY_BINS` to trade accuracy for
    speed differently.

    Note:
    If `stack` has several independently-repeated blocks (see
    :meth:`~nrxrdct.laue.layers.LayeredCrystal.add_layer`), it is
    transparently flattened via
    :func:`~nrxrdct.laue.layers.combine_stacks` before simulation --
    you can pass a multi-block stack directly, no manual flattening needed.
"""
    stack = _flatten_if_multiblock(stack)
    stack._update_offsets()
    source_kwargs = source_kwargs or {}
    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki /= np.linalg.norm(ki)

    lam_lo = en2lam(E_max_eV)
    lam_hi = en2lam(E_min_eV)

    spectrum = _make_spectrum_fn(source, source_kwargs, kb_params)

    # F2_stack is an absolute (coherent-sum) quantity that can span many
    # orders of magnitude across one stack (~cell-count² at each layer's own
    # Bragg peaks), so — unlike simulate_laue's per-unit-cell F2 — there is
    # no single stack-wide scale that reliably separates "real" from
    # "negligible" here. Rather than guess one (auto-scaling from whichever
    # layer happens to be enumerated first previously caused entire film
    # layers, and every one of their satellites, to be silently dropped
    # whenever they coincided with a much stronger substrate/buffer
    # reflection), default to the same absolute floor used everywhere else
    # in this module and let candidates be filtered/ranked afterwards by
    # `intensity` instead.
    if f2_thresh is None:
        f2_thresh = F2_THRESHOLD

    # ── Fringe / satellite wavevectors ───────────────────────────────────────
    # Thickness fringes and superlattice satellites both sit at
    #     G_hkl + m * q_fringe * n̂    (m = ±1, ±2, ...)
    # where q_fringe = 2π / t  and  t  is a relevant thickness.
    #
    # Two contributions:
    #   1. Each individual finite layer produces fringes at  q = 2π / t_layer.
    #      (This is the dominant effect for n_rep = 1, e.g. a single InGaN QW.)
    #   2. The full bilayer period Λ produces superlattice satellites at
    #      q = 2π / Λ  when n_rep > 1.
    #
    # Layers thicker than MAX_FRINGE_THICK_ANG are skipped: their fringe
    # spacing 2π/t is so small that the corresponding λ falls far outside any
    # realistic white-beam window and they never pass the Laue-condition check.
    MAX_FRINGE_THICK_ANG = 20000.0  # 2 µm — tune if needed

    fringe_q_vecs = []  # list of (q_vector_3d, description)
    sat_orders = [m for m in range(-max_satellites, max_satellites + 1) if m != 0]

    if max_satellites > 0:
        # Per-layer thickness fringes
        seen_t = set()
        for lyr in stack.layers:
            t = lyr.thickness
            if t < 1e-6 or t > MAX_FRINGE_THICK_ANG:
                continue
            t_key = round(t, 2)
            if t_key in seen_t:
                continue
            seen_t.add(t_key)
            q_vec = (2.0 * np.pi / t) * stack.n_hat
            fringe_q_vecs.append((q_vec, f"layer '{lyr.label}' (t={t/10:.1f} nm)"))

        # Superlattice period (only if n_rep > 1 and Λ ≠ any single-layer t)
        Lambda = stack.bilayer_thickness
        if stack.n_rep > 1 and Lambda > 1e-6:
            t_key = round(Lambda, 2)
            if t_key not in seen_t:
                q_vec = (2.0 * np.pi / Lambda) * stack.n_hat
                fringe_q_vecs.append((q_vec, f"bilayer Λ={Lambda/10:.1f} nm"))

    if verbose and fringe_q_vecs:
        print("  Fringe / satellite periods to probe:")
        for qv, desc in fringe_q_vecs:
            t_nm = 2.0 * np.pi / np.linalg.norm(qv) / 10.0
            print(
                f"    {desc}  →  2π/t = {np.linalg.norm(qv):.4f} Å⁻¹  (t = {t_nm:.2f} nm)"
            )

    # Pixel → spots-index map, used to accumulate coincident reflections
    # (harmonics and other accidental overlaps) onto one merged spot instead
    # of discarding all but the first — see _merge_or_append_spot.
    seen_pix = {}  # dict: (round(xcam), round(ycam)) -> index into spots

    # Per-layer allowed hkl set — reassigned in the outer layer loop so the
    # main-Bragg and satellite batches always see the set matching the
    # crystal currently being enumerated.
    _layer_allowed_hkl = None

    # Depth correction: per-layer centre depth (mm), updated as the outer loop
    # advances through the enumeration pool.
    _depth_mm_state = [0.0]
    if correct_depth:
        _depths_mm = _layer_depths_mm(stack)
        # Convert perpendicular depth to depth along the incident beam.
        # depth_along_beam = depth_perp / |cos θ|  where θ is the angle
        # between ki and the surface normal (stack.n_hat).
        _n_hat = np.asarray(stack.n_hat, dtype=float)
        _n_hat = _n_hat / np.linalg.norm(_n_hat)
        _cos_inc = abs(float(np.dot(ki, _n_hat)))
        if _cos_inc > 1e-6:
            _depths_mm = {k: v / _cos_inc for k, v in _depths_mm.items()}

    spots = []

    # In average mode enumerate G vectors from buffer layers plus the first MQW
    # layer.  Adding the first MQW layer ensures that film reflections are always
    # found even when the only buffer layer is a dissimilar substrate (e.g.
    # sapphire): sapphire G vectors are at completely different positions from
    # GaN/InGaN G vectors, so enumerating from the substrate alone would yield
    # zero film spots.  The crystal+orientation deduplication below then
    # removes any duplicate if the GaN buffer and first MQW layer share the
    # same species and U matrix.  InGaN (second MQW layer) is intentionally
    # excluded so only one set of Bragg positions is produced — matching what
    # is seen in a monochromatic scan.
    if structure_model == "average":
        _enum_pool = stack.buffer_layers + stack.layers[:1]
    else:
        _enum_pool = stack.all_layers

    # Deduplicate: if two layers share the exact same crystal AND orientation,
    # enumerate once — the stack F already includes both contributions.
    seen_combos = []  # list of (crystal.name, U_rounded_tuple)

    # Buffer layers (substrate, thick intermediate layers) are non-repeating and
    # have no finite-thickness interference.  Satellites computed as
    # G_substrate + m·q_fringe_film are physically meaningless and are skipped.
    _buffer_set = set(id(l) for l in stack.buffer_layers)

    for layer in _enum_pool:
        crystal = layer.crystal
        U = layer.U
        label = layer.label
        # Update the closure variables so _try_append uses this layer's
        # allowed HKL set and (when requested) its centre depth.
        _layer_allowed_hkl = allowed_hkl.get(id(crystal)) if isinstance(allowed_hkl, dict) else allowed_hkl
        if correct_depth:
            _depth_mm_state[0] = _depths_mm.get(id(layer), 0.0)

        u_key = (crystal.name, tuple(np.round(U, 4).ravel()))
        if u_key in seen_combos:
            if verbose:
                print(
                    f"  Skipping {label} (same crystal+orientation already enumerated)"
                )
            continue
        seen_combos.append(u_key)

        # Satellites are only meaningful around film (repeating-unit) G vectors.
        layer_has_satellites = id(layer) not in _buffer_set and bool(fringe_q_vecs)

        # Sphere enumeration limits for this layer's crystal
        HC_eV_ANG = 12398.4
        G_max = 4.0 * np.pi * E_max_eV / HC_eV_ANG
        G_max_sq = G_max ** 2
        _B = np.column_stack([crystal.Q(1, 0, 0), crystal.Q(0, 1, 0), crystal.Q(0, 0, 1)])
        a_star = float(np.linalg.norm(_B[:, 0]))
        b_star = float(np.linalg.norm(_B[:, 1]))
        c_star = float(np.linalg.norm(_B[:, 2]))
        h_lim = int(G_max / a_star) + 1
        k_lim = int(G_max / b_star) + 1
        l_lim = int(G_max / c_star) + 1

        if verbose:
            n_sat_orders = len(sat_orders) if layer_has_satellites else 0
            sat_info = f", ±{max_satellites} satellite orders" if n_sat_orders else ""
            print(
                f"  Enumerating {label} (G_max={G_max:.2f} Å⁻¹{sat_info}) ...", end="", flush=True
            )

        # Build full bounding-box grid, filter to sphere, rotate to lab — all vectorised.
        _HS, _KS, _LS = np.meshgrid(
            np.arange(-h_lim, h_lim + 1, dtype=np.int32),
            np.arange(-k_lim, k_lim + 1, dtype=np.int32),
            np.arange(-l_lim, l_lim + 1, dtype=np.int32),
            indexing="ij",
        )
        _hkl_s = np.column_stack([_HS.ravel(), _KS.ravel(), _LS.ravel()])
        _hkl_s = _hkl_s[np.any(_hkl_s != 0, axis=1)]
        _G_cry_s = (_B @ _hkl_s.T).T
        _mask_s = np.einsum("ij,ij->i", _G_cry_s, _G_cry_s) <= G_max_sq
        _hkl_s = _hkl_s[_mask_s]
        _G_lab_s = (U @ (_B @ _hkl_s.T)).T  # (M, 3)

        n_added = 0

        # Shared by both the main-Bragg batch below and the satellite batch
        # further down — one closure per layer instead of redefining per call.
        _batch_eval = (
            (lambda G, E, kf: stack.average_structure_factor_batch(G, E, kf_hat_arr=kf))
            if structure_model == "average"
            else (lambda G, E, kf: stack.structure_factor_batch(G, E, kf_hat_arr=kf))
        )

        # Surviving main-Bragg (G_lab, hkl) pairs that need their thickness-
        # fringe/superlattice satellites computed — collected here so all of
        # them (across every Bragg peak in this layer) can go through the
        # elastic-condition + structure-factor pipeline as ONE batch below,
        # instead of one scalar call per candidate satellite.
        survived_G, survived_hkl = [], []

        # ── Vectorised geometry filter for main Bragg peaks ───────────────────
        _G_lab_b = _G_lab_s.copy()
        _hkl_b   = _hkl_s.copy()

        kdG_b = _G_lab_b @ ki
        v1b   = kdG_b < 0
        _G_lab_b = _G_lab_b[v1b];  _hkl_b = _hkl_b[v1b];  kdG_b = kdG_b[v1b]

        if len(kdG_b) > 0:
            Gm2_b = np.einsum("ij,ij->i", _G_lab_b, _G_lab_b)
            lam_b = -4.0 * np.pi * kdG_b / Gm2_b
            v2b   = (lam_b >= lam_lo) & (lam_b <= lam_hi)
            _G_lab_b = _G_lab_b[v2b];  _hkl_b = _hkl_b[v2b];  lam_b = lam_b[v2b]
        else:
            lam_b = np.empty(0)

        if len(lam_b) > 0:
            E_b  = HC_eV_ANG / lam_b
            km_b = 2.0 * np.pi / lam_b
            kf_b = ki[None, :] * km_b[:, None] + _G_lab_b
            kf_b /= np.linalg.norm(kf_b, axis=1, keepdims=True)
            pix_b, on_det_b = camera.project_batch(kf_b, source_depth_mm=_depth_mm_state[0])

            if np.any(on_det_b):
                _G_lab_b = _G_lab_b[on_det_b];  _hkl_b = _hkl_b[on_det_b]
                lam_b    = lam_b[on_det_b];     E_b    = E_b[on_det_b]
                kf_b     = kf_b[on_det_b];      pix_b  = pix_b[on_det_b]

                tth_b = np.degrees(np.arccos(np.clip(kf_b[:, 0], -1.0, 1.0)))
                chi_b = np.degrees(np.arctan2(kf_b[:, 1], kf_b[:, 2] + 1e-17))
                az_b  = np.degrees(np.arctan2(kf_b[:, 2], kf_b[:, 1]))

                # ── Batch LP + spectrum pre-filter ────────────────────────────
                LP_b = _lorentz_pol_vec(tth_b, E_b, chi_b)
                sw_b = spectrum(E_b)
                pre_ok = (LP_b > 0) & (sw_b > 0)

                # Batch allowed-HKL mask (skips structure-factor path entirely)
                if _layer_allowed_hkl is not None and pre_ok.any():
                    ok_idx = np.where(pre_ok)[0]
                    hkl_ok = np.fromiter(
                        (tuple(int(x) for x in _hkl_b[i]) in _layer_allowed_hkl
                         for i in ok_idx),
                        dtype=bool, count=len(ok_idx),
                    )
                    new_ok = np.zeros(len(pre_ok), dtype=bool)
                    new_ok[ok_idx[hkl_ok]] = True
                    pre_ok = new_ok

                pix_round = np.round(pix_b).astype(np.int64)
                ok_idx_all = np.where(pre_ok)[0]

                # Structure factor for every surviving candidate, batched by
                # energy bin (one xrayutilities call per bin per layer instead
                # of one per candidate) — see _binned_structure_factor.
                skip_F2 = _layer_allowed_hkl is not None or geometry_only
                if skip_F2:
                    F2_all = np.ones(len(ok_idx_all))
                elif len(ok_idx_all):
                    F_all = _binned_structure_factor(
                        _G_lab_b[ok_idx_all], E_b[ok_idx_all], _batch_eval,
                        kf_hat_arr=kf_b[ok_idx_all], n_bins=_STRUCTURE_FACTOR_ENERGY_BINS,
                    )
                    F2_all = np.abs(F_all) ** 2
                else:
                    F2_all = np.empty(0)

                for _pos, _si in enumerate(ok_idx_all):
                    F2 = float(F2_all[_pos])
                    if not skip_F2 and F2 < f2_thresh:
                        continue

                    pix_key = (int(pix_round[_si, 0]), int(pix_round[_si, 1]))
                    G_lab = _G_lab_b[_si]
                    h = int(_hkl_b[_si, 0]); k = int(_hkl_b[_si, 1]); l = int(_hkl_b[_si, 2])
                    lp = float(LP_b[_si]);    sw = float(sw_b[_si])
                    E  = float(E_b[_si])
                    is_new = _merge_or_append_spot(spots, seen_pix, pix_key, {
                        "phase_label":     label,
                        "hkl":             (h, k, l),
                        "satellite_order": 0,
                        "is_superlattice": False,
                        "G_lab":           G_lab.copy(),
                        "E":               E,
                        "lambda":          float(lam_b[_si]),
                        "tth":             float(tth_b[_si]),
                        "chi":             float(chi_b[_si]),
                        "az":              float(az_b[_si]),
                        "pix":             (float(pix_b[_si, 0]), float(pix_b[_si, 1])),
                        "F2":              F2,
                        "F2_stack":        F2,
                        "LP":              lp,
                        "sw":              sw,
                        "I_raw":           F2 * lp * sw,
                    })
                    if is_new:
                        n_added += 1

                    if layer_has_satellites:
                        survived_G.append(G_lab)
                        survived_hkl.append((h, k, l))

        # ── Thickness fringes / satellites, batched across every surviving
        # Bragg peak in this layer at once (same pipeline as the main peaks
        # above: vectorised elastic condition → camera → LP/spectrum
        # prefilter → binned structure factor → cheap per-candidate merge).
        if layer_has_satellites and survived_G:
            G_peaks = np.asarray(survived_G, dtype=float)          # (M, 3)
            hkl_peaks = np.asarray(survived_hkl, dtype=np.int32)   # (M, 3)
            M = len(G_peaks)

            cand_G, cand_hkl, cand_sat = [], [], []
            for q_fringe_vec, _ in fringe_q_vecs:
                for m in sat_orders:
                    frac = m + 0.5 if m > 0 else m - 0.5
                    cand_G.append(G_peaks + frac * q_fringe_vec)
                    cand_hkl.append(hkl_peaks)
                    cand_sat.append(np.full(M, m, dtype=np.int32))
            cand_G = np.concatenate(cand_G, axis=0)
            cand_hkl = np.concatenate(cand_hkl, axis=0)
            cand_sat = np.concatenate(cand_sat, axis=0)

            kdG_sat = cand_G @ ki
            v1s = kdG_sat < 0
            cand_G = cand_G[v1s]; cand_hkl = cand_hkl[v1s]; cand_sat = cand_sat[v1s]
            kdG_sat = kdG_sat[v1s]

            lam_sat = np.empty(0)
            if len(cand_G):
                Gm2_sat = np.einsum("ij,ij->i", cand_G, cand_G)
                lam_sat = -4.0 * np.pi * kdG_sat / Gm2_sat
                v2s = (lam_sat >= lam_lo) & (lam_sat <= lam_hi)
                cand_G = cand_G[v2s]; cand_hkl = cand_hkl[v2s]; cand_sat = cand_sat[v2s]
                lam_sat = lam_sat[v2s]

            if len(lam_sat) > 0:
                E_sat = HC_eV_ANG / lam_sat
                km_sat = 2.0 * np.pi / lam_sat
                kf_sat = ki[None, :] * km_sat[:, None] + cand_G
                kf_sat /= np.linalg.norm(kf_sat, axis=1, keepdims=True)
                pix_sat, on_det_sat = camera.project_batch(kf_sat, source_depth_mm=_depth_mm_state[0])

                if np.any(on_det_sat):
                    cand_G = cand_G[on_det_sat];   cand_hkl = cand_hkl[on_det_sat]
                    cand_sat = cand_sat[on_det_sat]; lam_sat = lam_sat[on_det_sat]
                    E_sat = E_sat[on_det_sat];      kf_sat = kf_sat[on_det_sat]
                    pix_sat = pix_sat[on_det_sat]

                    tth_sat = np.degrees(np.arccos(np.clip(kf_sat[:, 0], -1.0, 1.0)))
                    chi_sat = np.degrees(np.arctan2(kf_sat[:, 1], kf_sat[:, 2] + 1e-17))
                    az_sat  = np.degrees(np.arctan2(kf_sat[:, 2], kf_sat[:, 1]))
                    LP_sat  = _lorentz_pol_vec(tth_sat, E_sat, chi_sat)
                    sw_sat  = spectrum(E_sat)
                    pre_ok_sat = (LP_sat > 0) & (sw_sat > 0)

                    if _layer_allowed_hkl is not None and pre_ok_sat.any():
                        ok_idx_s = np.where(pre_ok_sat)[0]
                        hkl_ok_s = np.fromiter(
                            (tuple(int(x) for x in cand_hkl[i]) in _layer_allowed_hkl
                             for i in ok_idx_s),
                            dtype=bool, count=len(ok_idx_s),
                        )
                        new_ok_s = np.zeros(len(pre_ok_sat), dtype=bool)
                        new_ok_s[ok_idx_s[hkl_ok_s]] = True
                        pre_ok_sat = new_ok_s

                    pix_round_sat = np.round(pix_sat).astype(np.int64)
                    ok_idx_sat = np.where(pre_ok_sat)[0]

                    if skip_F2:
                        F2_sat_all = np.ones(len(ok_idx_sat))
                    elif len(ok_idx_sat):
                        F_sat_all = _binned_structure_factor(
                            cand_G[ok_idx_sat], E_sat[ok_idx_sat], _batch_eval,
                            kf_hat_arr=kf_sat[ok_idx_sat], n_bins=_STRUCTURE_FACTOR_ENERGY_BINS,
                        )
                        F2_sat_all = np.abs(F_sat_all) ** 2
                    else:
                        F2_sat_all = np.empty(0)

                    for _pos_s, _si_s in enumerate(ok_idx_sat):
                        sat_order_val = int(cand_sat[_si_s])
                        F2s = float(F2_sat_all[_pos_s])
                        if not skip_F2 and F2s < F2_THRESHOLD:
                            # Satellites are judged against the module's absolute
                            # baseline floor, not any relative/parent-derived
                            # scale: a "1e-4 of the parent peak" rule breaks down
                            # whenever the parent happens to coincide with a much
                            # stronger, unrelated reflection elsewhere in the
                            # stack (its own F2 no longer reflects what a real
                            # satellite of *this* repeating structure should look
                            # like), which is common whenever a film sublayer is
                            # lattice-matched to a much thicker buffer/substrate.
                            continue
                        pix_key_s = (int(pix_round_sat[_si_s, 0]), int(pix_round_sat[_si_s, 1]))
                        lp_s = float(LP_sat[_si_s]); sw_s = float(sw_sat[_si_s])
                        is_new_s = _merge_or_append_spot(spots, seen_pix, pix_key_s, {
                            "phase_label":     label,
                            "hkl":             (int(cand_hkl[_si_s, 0]),
                                                int(cand_hkl[_si_s, 1]),
                                                int(cand_hkl[_si_s, 2])),
                            "satellite_order": sat_order_val,
                            "is_superlattice": sat_order_val != 0,
                            "G_lab":           cand_G[_si_s].copy(),
                            "E":               float(E_sat[_si_s]),
                            "lambda":          float(lam_sat[_si_s]),
                            "tth":             float(tth_sat[_si_s]),
                            "chi":             float(chi_sat[_si_s]),
                            "az":              float(az_sat[_si_s]),
                            "pix":             (float(pix_sat[_si_s, 0]), float(pix_sat[_si_s, 1])),
                            "F2":              F2s,
                            "F2_stack":        F2s,
                            "LP":              lp_s,
                            "sw":              sw_s,
                            "I_raw":           F2s * lp_s * sw_s,
                        })
                        if is_new_s:
                            n_added += 1

        if verbose:
            print(f" {n_added} spots")

    # Normalise
    if spots:
        imax = max(s["I_raw"] for s in spots)
        for s in spots:
            s["intensity"] = s["I_raw"] / imax

    spots.sort(key=lambda s: s["intensity"], reverse=True)
    beam_divergence_ellipses(
        spots, camera, sigma_h_mrad, sigma_v_mrad, ki_hat=ki,
        sigma_beam_h_nm=sigma_beam_h_nm,
        sigma_beam_v_nm=sigma_beam_v_nm,
        n_hat_sample=n_hat_sample,
    )

    if verbose:
        print(f"  Total spots on detector: {len(spots)}")
        print(
            f"  Stack: {stack.name}  "
            f"Λ={stack.bilayer_thickness:.2f} Å  "
            f"N_rep={stack.n_rep}"
        )
        if stack.bilayer_thickness > 1e-6:
            print(
                f"  Superlattice satellite 2π/Λ = "
                f"{2*np.pi/stack.bilayer_thickness:.5f} Å⁻¹"
            )

    return spots

simulate_mixed_phases

simulate_mixed_phases(phases, camera, E_min_eV=5000, E_max_eV=27000, source='bending_magnet', source_kwargs=None, f2_thresh=None, normalise='volume', kb_params=BM32_KB, structure_model='average', sigma_h_mrad=0.0, sigma_v_mrad=0.0, sigma_beam_h_nm=0.0, sigma_beam_v_nm=0.0, n_hat_sample=None, verbose=True, geometry_only=False, allowed_hkl=None)

Simulate a Laue pattern from a multi-phase sample with known volume fractions.

Each phase scatters independently (incoherent between phases — different grains, different orientations). The contribution of each phase is weighted by its volume fraction and unit-cell number density before the spot lists are merged into one.

Intensity weighting The number of unit cells of phase p contributing to diffraction scales as:

N_uc_p  ∝  f_p / V_uc_p

where f_p is the volume fraction and V_uc_p is the unit-cell volume (ų). This is the standard Rietveld weight used in powder diffraction and is correct for any single-crystal Laue measurement of a multi-phase polycrystal.

For a LayeredCrystal phase, V_uc_p is taken as the thickness-weighted harmonic mean of the individual layer unit-cell volumes — i.e. the effective number of unit cells per unit volume of the stack.

The normalise argument controls how the final intensities are scaled: 'volume' (default) — weight by f_p / V_uc_p (physics-correct) 'fraction' — weight by f_p only (ignore V_uc differences) 'equal' — all phases equally weighted regardless of fraction 'none' — no rescaling; I_raw values are kept as-is from each phase's simulation

phases : list of dicts or list of tuples Each entry describes one phase. Accepted formats:

**dict** (recommended)::

    {
      'crystal'         : xu.materials.Crystal  or  LayeredCrystal,
      'U'               : np.ndarray (3×3) orientation matrix,
      'volume_fraction' : float,          # must sum to 1 (normalised)
      'label'           : str,            # optional, default crystal.name
      'f2_thresh'       : float | None,   # optional, overrides global
    }

**tuple** (short form)::

    (crystal_or_stack, U, volume_fraction)
    (crystal_or_stack, U, volume_fraction, label)
Camera

Detector geometry (from laue_white_synchrotron.py).

E_min_eV, E_max_eV : float Energy window (eV), applied to all phases.

str

Synchrotron source model, forwarded to each per-phase simulation. Accepts all options supported by :func:simulate_laue_stack: 'bending_magnet', 'wiggler', 'undulator', 'flat', 'shadow4', or 'tabulated'.

For 'shadow4', the Monte Carlo simulation is run once here and the resulting spectrum is passed to every phase as 'tabulated', so the cost is paid only once regardless of how many phases are in the mix.

dict, optional

Forwarded to the spectrum function. For 'shadow4', accepts nrays and n_energy_bins (see :func:_make_spectrum_fn). For 'tabulated', must contain 'energy_eV' and 'flux'.

dict or None, optional

KB mirror reflectivity correction, forwarded unchanged to each per-phase simulation call. Defaults to :data:BM32_KB. Pass None to disable, and must be None for 'shadow4' and 'tabulated' sources.

float | None

Minimum |F|² threshold (global default, overridable per phase). None = auto-scale per phase.

str

Weighting mode: 'volume', 'fraction', 'equal', 'none'.

structure_model : {'coherent', 'average'}, optional Forwarded to :func:simulate_laue_stack for any LayeredCrystal phase. 'average' (default) enumerates G vectors from buffer layers only and uses the composition-weighted average MQW structure factor, matching the single-peak-plus-satellites appearance of a monochromatic scan. 'coherent' enumerates every crystal separately and preserves full inter-layer interference. Ignored for plain xu.materials.Crystal phases (handled by :func:simulate_laue). verbose : bool

spots : list of dicts Merged, weighted, and renormalised spot list. Each dict has all the standard keys plus:

  `'phase_label'`      – which phase this spot belongs to
  `'volume_fraction'`  – f_p of that phase
  `'phase_weight'`     – the weight applied (f_p / V_uc_p or variant)
  `'intensity'`        – normalised 0–1 over the full mixed pattern
  `'intensity_phase'`  – normalised 0–1 within that phase alone

ValueError If volume fractions do not sum to approximately 1.0 (within ±0.01).

Example:

import xrayutilities as xu from simulate_laue_layered import simulate_mixed_phases from layered_structure_factor import orientation_along_z, or_kurdjumov_sachs

Fe = xu.materials.Fe Cu = xu.materials.Cu U_Fe = orientation_along_z([0,0,1], Fe) U_Cu = U_Fe @ or_kurdjumov_sachs(Fe, Cu).T

phases = [ ... {'crystal': Fe, 'U': U_Fe, 'volume_fraction': 0.6, 'label': 'austenite'}, ... {'crystal': Cu, 'U': U_Cu, 'volume_fraction': 0.4, 'label': 'Cu KS'}, ... ] spots = simulate_mixed_phases(phases, camera) plot_detector_image(spots, camera, colour_by='phase')

Note: Orientation relationship between phases does NOT produce interference fringes here — use LayeredCrystal + simulate_laue_stack for that. This function is for incoherent multi-grain mixtures (e.g. a polycrystal with two phases, or a transformed microstructure).

Source code in src/nrxrdct/laue/simulation.py
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
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
def simulate_mixed_phases(
    phases,
    camera,
    E_min_eV=5_000,
    E_max_eV=27_000,
    source="bending_magnet",
    source_kwargs=None,
    f2_thresh=None,
    normalise="volume",
    kb_params=BM32_KB,
    structure_model="average",
    sigma_h_mrad=0.0,
    sigma_v_mrad=0.0,
    sigma_beam_h_nm=0.0,
    sigma_beam_v_nm=0.0,
    n_hat_sample=None,
    verbose=True,
    geometry_only=False,
    allowed_hkl=None,
):
    """
    Simulate a Laue pattern from a multi-phase sample with known volume
    fractions.

    Each phase scatters **independently** (incoherent between phases —
    different grains, different orientations).  The contribution of each
    phase is weighted by its volume fraction and unit-cell number density
    before the spot lists are merged into one.

    **Intensity weighting**
    The number of unit cells of phase p contributing to diffraction scales as:

        N_uc_p  ∝  f_p / V_uc_p

    where  f_p  is the volume fraction and  V_uc_p  is the unit-cell volume
    (ų).  This is the standard Rietveld weight used in powder diffraction
    and is correct for any single-crystal Laue measurement of a multi-phase
    polycrystal.

    For a `LayeredCrystal` phase, V_uc_p is taken as the thickness-weighted
    harmonic mean of the individual layer unit-cell volumes — i.e. the
    effective number of unit cells per unit volume of the stack.

    The `normalise` argument controls how the final intensities are scaled:
      `'volume'`   (default) — weight by f_p / V_uc_p  (physics-correct)
      `'fraction'` — weight by f_p only (ignore V_uc differences)
      `'equal'`    — all phases equally weighted regardless of fraction
      `'none'`     — no rescaling; I_raw values are kept as-is from each
                       phase's simulation

    Args:
    phases : list of dicts or list of tuples
        Each entry describes one phase.  Accepted formats:

        **dict** (recommended)::

            {
              'crystal'         : xu.materials.Crystal  or  LayeredCrystal,
              'U'               : np.ndarray (3×3) orientation matrix,
              'volume_fraction' : float,          # must sum to 1 (normalised)
              'label'           : str,            # optional, default crystal.name
              'f2_thresh'       : float | None,   # optional, overrides global
            }

        **tuple** (short form)::

            (crystal_or_stack, U, volume_fraction)
            (crystal_or_stack, U, volume_fraction, label)

    camera : Camera
        Detector geometry (from laue_white_synchrotron.py).

    E_min_eV, E_max_eV : float
        Energy window (eV), applied to all phases.

    source : str
        Synchrotron source model, forwarded to each per-phase simulation.
        Accepts all options supported by :func:`simulate_laue_stack`:
        `'bending_magnet'`, `'wiggler'`, `'undulator'`, `'flat'`,
        `'shadow4'`, or `'tabulated'`.

        For `'shadow4'`, the Monte Carlo simulation is run **once** here
        and the resulting spectrum is passed to every phase as
        `'tabulated'`, so the cost is paid only once regardless of how
        many phases are in the mix.

    source_kwargs : dict, optional
        Forwarded to the spectrum function.  For `'shadow4'`, accepts
        `nrays` and `n_energy_bins` (see :func:`_make_spectrum_fn`).
        For `'tabulated'`, must contain `'energy_eV'` and `'flux'`.

    kb_params : dict or None, optional
        KB mirror reflectivity correction, forwarded unchanged to each
        per-phase simulation call.  Defaults to :data:`BM32_KB`.
        Pass `None` to disable, and **must** be `None` for
        `'shadow4'` and `'tabulated'` sources.

    f2_thresh : float | None
        Minimum |F|² threshold (global default, overridable per phase).
        `None` = auto-scale per phase.

    normalise : str
        Weighting mode: `'volume'`, `'fraction'`, `'equal'`, `'none'`.
    structure_model : {'coherent', 'average'}, optional
        Forwarded to :func:`simulate_laue_stack` for any `LayeredCrystal`
        phase.  `'average'` *(default)* enumerates G vectors from buffer
        layers only and uses the composition-weighted average MQW structure
        factor, matching the single-peak-plus-satellites appearance of a
        monochromatic scan.  `'coherent'` enumerates every crystal
        separately and preserves full inter-layer interference.  Ignored for
        plain `xu.materials.Crystal` phases (handled by
        :func:`simulate_laue`).
    verbose : bool

    Returns:
    spots : list of dicts
        Merged, weighted, and renormalised spot list.  Each dict has all the
        standard keys plus:

          `'phase_label'`      – which phase this spot belongs to
          `'volume_fraction'`  – f_p of that phase
          `'phase_weight'`     – the weight applied (f_p / V_uc_p or variant)
          `'intensity'`        – normalised 0–1 over the full mixed pattern
          `'intensity_phase'`  – normalised 0–1 within that phase alone

    Raises:
    ValueError
        If volume fractions do not sum to approximately 1.0 (within ±0.01).

    Example:
    >>> import xrayutilities as xu
    >>> from simulate_laue_layered import simulate_mixed_phases
    >>> from layered_structure_factor import orientation_along_z, or_kurdjumov_sachs
    >>>
    >>> Fe = xu.materials.Fe
    >>> Cu = xu.materials.Cu
    >>> U_Fe = orientation_along_z([0,0,1], Fe)
    >>> U_Cu = U_Fe @ or_kurdjumov_sachs(Fe, Cu).T
    >>>
    >>> phases = [
    ...     {'crystal': Fe, 'U': U_Fe, 'volume_fraction': 0.6, 'label': 'austenite'},
    ...     {'crystal': Cu, 'U': U_Cu, 'volume_fraction': 0.4, 'label': 'Cu KS'},
    ... ]
    >>> spots = simulate_mixed_phases(phases, camera)
    >>> plot_detector_image(spots, camera, colour_by='phase')

    Note:
    Orientation relationship between phases does NOT produce interference
    fringes here — use `LayeredCrystal` + `simulate_laue_stack` for that.
    This function is for incoherent multi-grain mixtures (e.g. a polycrystal
    with two phases, or a transformed microstructure).
"""
    import os
    import sys

    import numpy as np
    import xrayutilities as xu

    from .layers import LayeredCrystal

    source_kwargs = source_kwargs or {}

    # ── Pre-compute spectrum for interpolated sources (pay the cost once) ─────
    # For 'shadow4' the Monte Carlo run takes ~1-2 min; running it once per
    # phase would multiply that cost by the number of phases.  Instead, run it
    # here, then switch source to 'tabulated' so every sub-call gets a free
    # interpolation.  The same logic applies when the caller already passes
    # 'tabulated' — we just pass those arrays through unchanged.
    if source in ("shadow4", "tabulated"):
        _fn = _make_spectrum_fn(source, source_kwargs, kb_params)
        # Evaluate on a dense grid covering the energy window so the per-phase
        # simulate_laue / simulate_laue_stack calls get a fine interpolator.
        _e_grid = np.linspace(E_min_eV, E_max_eV, 500)
        _f_grid = np.array([_fn(e) for e in _e_grid])
        source = "tabulated"
        source_kwargs = {"energy_eV": _e_grid, "flux": _f_grid}
        kb_params = None   # already embedded in _f_grid

    # ── Normalise phase list ──────────────────────────────────────────────────
    parsed = []
    for entry in phases:
        if isinstance(entry, dict):
            p = entry.copy()
        elif isinstance(entry, (list, tuple)):
            p = {}
            p["crystal"] = entry[0]
            p["U"] = entry[1]
            p["volume_fraction"] = float(entry[2])
            if len(entry) >= 4:
                p["label"] = str(entry[3])
        else:
            raise TypeError(f"Each phase must be a dict or tuple, got {type(entry)}")
        parsed.append(p)

    # Default label
    for p in parsed:
        if "label" not in p:
            c = p["crystal"]
            p["label"] = c.name if hasattr(c, "name") else str(c)

    # Check fractions
    total_f = sum(float(p["volume_fraction"]) for p in parsed)
    if abs(total_f - 1.0) > 0.01:
        raise ValueError(
            f"Volume fractions sum to {total_f:.4f}, expected 1.0. "
            "Please normalise them."
        )

    # ── Compute effective unit-cell volume per phase ───────────────────────────
    def eff_vuc(crystal_or_stack):
        """Effective unit-cell volume (ų) for weighting."""
        if type(crystal_or_stack).__name__ == "LayeredCrystal":
            stk = crystal_or_stack
            stk._update_offsets()
            total_t = stk.total_thickness
            if total_t < 1e-10:
                return 1.0
            # Thickness-weighted harmonic mean of layer V_uc values
            # = effective V_uc per unit volume of the stack
            w_sum = 0.0
            for layer in stk.layers:
                frac = layer.thickness / total_t
                w_sum += frac / layer.crystal.lattice.UnitCellVolume()
            return 1.0 / w_sum if w_sum > 1e-30 else 1.0
        else:
            return crystal_or_stack.lattice.UnitCellVolume()

    # # ── Load simulation helpers ────────────────────────────────────────────────
    # mod_src = open(os.path.join(_here, "laue_white_synchrotron.py")).read()
    # ns = {}
    # exec(compile(mod_src.split("\ndef main():")[0], "laue_sim", "exec"), ns)
    # _simulate_laue_single = ns["simulate_laue"]

    # ── Simulate each phase ────────────────────────────────────────────────────
    if verbose:
        print(f"\n  Mixed-phase Laue simulation  ({len(parsed)} phases)")
        print(f"  {'─'*52}")
        print(f"  {'Phase':22s} {'f_vol':>6}  {'V_uc(ų)':>10}  {'weight':>10}")

    phase_results = []
    for p in parsed:
        crystal = p["crystal"]
        U = np.asarray(p["U"], dtype=float)
        f = float(p["volume_fraction"])
        label = p["label"]
        ph_f2 = p.get("f2_thresh", f2_thresh)

        vuc = eff_vuc(crystal)

        # Compute weight
        if normalise == "volume":
            weight = f / vuc
        elif normalise == "fraction":
            weight = f
        elif normalise == "equal":
            weight = 1.0 / len(parsed)
        elif normalise == "none":
            weight = 1.0
        else:
            raise ValueError(f"normalise must be 'volume','fraction','equal','none'")

        if verbose:
            print(f"  {label:22s} {f:6.3f}  {vuc:10.3f}  {weight:10.6f}")

        # Resolve per-phase allowed_hkl: dict keyed by id(crystal) takes priority,
        # then a bare frozenset is used for all phases, then None falls through.
        _phase_allowed = (
            allowed_hkl.get(id(crystal)) if isinstance(allowed_hkl, dict)
            else allowed_hkl
        )

        # Simulate
        if type(crystal).__name__ == "LayeredCrystal":
            spots_p = simulate_laue_stack(
                crystal,
                camera,
                E_min_eV=E_min_eV,
                E_max_eV=E_max_eV,
                source=source,
                source_kwargs=source_kwargs,
                f2_thresh=ph_f2,
                kb_params=kb_params,
                structure_model=structure_model,
                verbose=False,
                geometry_only=geometry_only,
                allowed_hkl=_phase_allowed,
            )
        else:
            spots_p = simulate_laue(
                crystal,
                U,
                camera,
                E_min=E_min_eV,
                E_max=E_max_eV,
                source=source,
                source_kwargs=source_kwargs,
                f2_thresh=(ph_f2 if ph_f2 is not None else F2_THRESHOLD),
                kb_params=kb_params,
                geometry_only=geometry_only,
                allowed_hkl=_phase_allowed,
            )

        if verbose:
            print(f"    → {len(spots_p)} spots on camera")

        # Tag each spot and apply weight to I_raw
        for s in spots_p:
            s["phase_label"] = label
            s["volume_fraction"] = f
            s["phase_weight"] = weight
            s["I_raw_weighted"] = s["I_raw"] * weight

        # Store per-phase normalised intensity (within this phase)
        if spots_p:
            imax_p = max(s["I_raw"] for s in spots_p)
            for s in spots_p:
                s["intensity_phase"] = s["I_raw"] / imax_p if imax_p > 0 else 0.0
        else:
            for s in spots_p:
                s["intensity_phase"] = 0.0

        phase_results.append((label, f, vuc, weight, spots_p))

    # ── Merge and renormalise ──────────────────────────────────────────────────
    all_spots = []
    for _, _, _, _, spots_p in phase_results:
        all_spots.extend(spots_p)

    if all_spots:
        imax = max(s["I_raw_weighted"] for s in all_spots)
        for s in all_spots:
            s["intensity"] = s["I_raw_weighted"] / imax if imax > 0 else 0.0

    all_spots.sort(key=lambda s: s["intensity"], reverse=True)
    beam_divergence_ellipses(
        all_spots, camera, sigma_h_mrad, sigma_v_mrad,
        sigma_beam_h_nm=sigma_beam_h_nm,
        sigma_beam_v_nm=sigma_beam_v_nm,
        n_hat_sample=n_hat_sample,
    )

    if verbose:
        print(f"  {'─'*52}")
        print(f"  Total spots on camera : {len(all_spots)}")
        for label, f, vuc, weight, spots_p in phase_results:
            pct = len(spots_p) / max(len(all_spots), 1) * 100
            print(
                f"    {label:22s}: {len(spots_p):4d} spots  " f"({pct:.0f}% of total)"
            )
        print(f"  normalise = '{normalise}'")

    return all_spots

simulate_qspace_around_spot

simulate_qspace_around_spot(stack, hkl, energy_eV, layer=None, *, n_along=301, n_lateral=7, extent_along=None, extent_lateral=None, max_satellites=6, pin_satellites=True, structure_model='coherent', verbose=True)

Simulated |F_stack(Q)|² on a 3-D grid around one Bragg spot, evaluated at a single fixed photon energy — the fixed-energy counterpart of :func:qspace_around_spot.

qspace_around_spot solves the exact elastic (Ewald-sphere) condition at every voxel, so E varies continuously across the grid and only the subset of voxels that are actually reachable by some white-beam photon carries nonzero intensity — the physically correct picture for a real energy-dispersive Laue exposure. This function instead asks a simpler question: "what does the coherent structure factor of this stack look like across Q-space near G0, if I evaluate it at one chosen energy?" Every voxel gets a value regardless of whether it sits on the Ewald sphere for energy_eV — most of them physically wouldn't, since a single fixed energy only intersects Q-space on a 2-D sphere shell, not a 3-D volume. What's returned is therefore the bare kinematical structure-factor landscape (rod shape, thickness fringes, superlattice satellites) as a function of Q alone, decoupled from any specific diffraction geometry — no Lorentz-polarization factor, no camera, no reachability filtering. Use :func:qspace_around_spot instead when you need the physically-realizable intensity a detector would actually record.

Grid geometry, extent auto-scaling, and satellite pinning are identical to :func:qspace_around_spot (see that function's docstring) — this function reuses the same (n_hat, t1, t2) local frame and along pinning logic, just without the elastic-condition/camera machinery.

Parameters:
  • stack –

    LayeredCrystal

  • hkl –

    (int, int, int) Miller indices of the reference reflection, in layer.crystal's lattice.

  • energy_eV (float) –

    Fixed photon energy (eV) the structure factor is evaluated at for every voxel (via Layer.structure_factor_batch → StructureFactorForQ, same one-batched-call-per-layer path qspace_around_spot uses for its own energy_ref_eV).

  • layer –

    Layer, str, or None, optional Which layer's (crystal, U, n_hat) defines G0 and the rod axis. Same resolution rule as qspace_around_spot (None -> stack.layers[0]).

  • pin_satellites –

    Same meaning as in qspace_around_spot.

  • structure_model ({coherent, average}, default: 'coherent' ) –

    'coherent' (default) evaluates the full layer-by-layer coherent stack structure factor. 'average' uses the composition-weighted average structure factor instead (satellite positions identical, intensities differ) — same choice as qspace_around_spot.

  • verbose (bool, default: True ) –

    Print a short summary (grid shape, energy, |F|² range) after evaluation.

Returns:
  • –

    dict with keys 'hkl', 'layer', 'energy_eV', 'G0', 'axes'

  • –

    ({'n_hat', 't1', 't2'}), 'along', 'lateral1', 'lateral2',

  • –

    'Q' (shape (n_along, n_lateral, n_lateral, 3)), and 'F2'

  • –

    (|F_stack(Q, energy_eV)|², same shape as Q minus the last axis)

  • –

    — the same grid/axis conventions as qspace_around_spot, minus the

  • –

    elastic-condition-only fields ('I', 'E', 'reachable', 'pix',

  • –

    'on_detector').

Example:

vol = simulate_qspace_around_spot(stack, (0, 0, 2), energy_eV=17000) vol['F2'][:, vol['F2'].shape[1] // 2, vol['F2'].shape[2] // 2] # rod profile

Source code in src/nrxrdct/laue/simulation.py
def simulate_qspace_around_spot(
    stack,
    hkl,
    energy_eV,
    layer=None,
    *,
    n_along=301,
    n_lateral=7,
    extent_along=None,
    extent_lateral=None,
    max_satellites=6,
    pin_satellites=True,
    structure_model="coherent",
    verbose=True,
):
    """
    Simulated `|F_stack(Q)|²` on a 3-D grid around one Bragg spot, evaluated
    at a single **fixed** photon energy — the fixed-energy counterpart of
    :func:`qspace_around_spot`.

    `qspace_around_spot` solves the exact elastic (Ewald-sphere) condition
    at every voxel, so `E` varies continuously across the grid and only the
    subset of voxels that are actually reachable by *some* white-beam photon
    carries nonzero intensity — the physically correct picture for a real
    energy-dispersive Laue exposure. This function instead asks a simpler
    question: "what does the coherent structure factor of this stack look
    like across Q-space near `G0`, if I evaluate it at one chosen energy?"
    Every voxel gets a value regardless of whether it sits on the Ewald
    sphere for `energy_eV` — most of them physically wouldn't, since a
    single fixed energy only intersects Q-space on a 2-D sphere shell, not
    a 3-D volume. What's returned is therefore the bare kinematical
    structure-factor landscape (rod shape, thickness fringes, superlattice
    satellites) as a function of Q alone, decoupled from any specific
    diffraction geometry — no Lorentz-polarization factor, no camera, no
    reachability filtering. Use :func:`qspace_around_spot` instead when you
    need the physically-realizable intensity a detector would actually
    record.

    Grid geometry, extent auto-scaling, and satellite pinning are identical
    to :func:`qspace_around_spot` (see that function's docstring) — this
    function reuses the same `(n_hat, t1, t2)` local frame and `along`
    pinning logic, just without the elastic-condition/camera machinery.

    Args:
        stack : LayeredCrystal
        hkl : (int, int, int)
            Miller indices of the reference reflection, in `layer.crystal`'s
            lattice.
        energy_eV (float): Fixed photon energy (eV) the structure factor is evaluated
            at for every voxel (via `Layer.structure_factor_batch` →
            `StructureFactorForQ`, same one-batched-call-per-layer path
            `qspace_around_spot` uses for its own `energy_ref_eV`).
        layer : Layer, str, or None, optional
            Which layer's `(crystal, U, n_hat)` defines `G0` and the rod
            axis. Same resolution rule as `qspace_around_spot` (`None` ->
            `stack.layers[0]`).
        n_along, n_lateral, extent_along, extent_lateral, max_satellites,
        pin_satellites : Same meaning as in `qspace_around_spot`.
        structure_model ({'coherent', 'average'}, optional): `'coherent'` (default) evaluates the full layer-by-layer coherent
            stack structure factor. `'average'` uses the composition-weighted
            average structure factor instead (satellite positions identical,
            intensities differ) — same choice as `qspace_around_spot`.
        verbose (bool, optional): Print a short summary (grid shape, energy, `|F|²` range) after
            evaluation.

    Returns:
        dict with keys `'hkl'`, `'layer'`, `'energy_eV'`, `'G0'`, `'axes'`
        (`{'n_hat', 't1', 't2'}`), `'along'`, `'lateral1'`, `'lateral2'`,
        `'Q'` (shape `(n_along, n_lateral, n_lateral, 3)`), and `'F2'`
        (`|F_stack(Q, energy_eV)|²`, same shape as `Q` minus the last axis)
        — the same grid/axis conventions as `qspace_around_spot`, minus the
        elastic-condition-only fields (`'I'`, `'E'`, `'reachable'`, `'pix'`,
        `'on_detector'`).

    Example:
    >>> vol = simulate_qspace_around_spot(stack, (0, 0, 2), energy_eV=17000)
    >>> vol['F2'][:, vol['F2'].shape[1] // 2, vol['F2'].shape[2] // 2]  # rod profile
    """
    if type(stack).__name__ != "LayeredCrystal":
        raise TypeError(f"stack must be a LayeredCrystal, got {type(stack).__name__}")
    if structure_model not in ("coherent", "average"):
        raise ValueError(f"structure_model must be 'coherent' or 'average', got {structure_model!r}")

    stack._update_offsets()
    _sat_periods = [
        blk._period for blk in getattr(stack, "_blocks", [])
        if blk.n_rep >= 2 and blk._period > 1e-6
    ]
    stack = _flatten_if_multiblock(stack)
    stack._update_offsets()

    if layer is None:
        if not stack.layers:
            raise ValueError("stack has no repeating/film layers; pass `layer` explicitly")
        layer = stack.layers[0]
    elif isinstance(layer, str):
        match = next((l for l in stack.all_layers if l.label == layer), None)
        if match is None:
            available = [l.label for l in stack.all_layers]
            raise ValueError(f"no layer labeled {layer!r}; available labels: {available}")
        layer = match

    h, k, l = (int(x) for x in hkl)
    G0 = layer.U @ layer.crystal.Q(h, k, l)
    n_hat = np.asarray(layer.n_hat, dtype=float)
    n_hat = n_hat / np.linalg.norm(n_hat)

    tmp = np.array([1.0, 0.0, 0.0]) if abs(n_hat[0]) < 0.9 else np.array([0.0, 1.0, 0.0])
    e_t1 = tmp - n_hat * np.dot(tmp, n_hat)
    e_t1 /= np.linalg.norm(e_t1)
    e_t2 = np.cross(n_hat, e_t1)

    if extent_along is None:
        t_period = stack.bilayer_thickness if stack.n_rep > 1 else layer.thickness
        q_fringe = (2.0 * np.pi / t_period) if t_period > 1e-6 else 0.01 * float(np.linalg.norm(G0))
        extent_along = (max_satellites + 0.5) * q_fringe
    if extent_lateral is None:
        extent_lateral = 0.05 * extent_along

    along_vals = np.linspace(-extent_along, extent_along, n_along)

    _pinned_sat_along = []
    if pin_satellites and _sat_periods:
        Gn = float(G0 @ stack.n_hat)
        for Lambda in _sat_periods:
            m_center = int(round(Gn * Lambda / (2.0 * np.pi)))
            sat_pts = []
            for m in range(m_center - max_satellites - 1, m_center + max_satellites + 2):
                a = 2.0 * np.pi * m / Lambda - Gn
                if -extent_along <= a <= extent_along:
                    sat_pts.append(a)
            if sat_pts:
                along_vals = np.unique(np.concatenate([along_vals, np.array(sat_pts)]))
                _pinned_sat_along.extend(sat_pts)
    elif pin_satellites and not _sat_periods and verbose:
        print(
            f"  simulate_qspace_around_spot: pin_satellites=True but no blocks with "
            f"n_rep≥2 found in stack — check stack.blocks"
        )

    t1_vals = np.linspace(-extent_lateral, extent_lateral, n_lateral) if n_lateral > 1 else np.array([0.0])
    t2_vals = np.linspace(-extent_lateral, extent_lateral, n_lateral) if n_lateral > 1 else np.array([0.0])

    AA, T1, T2 = np.meshgrid(along_vals, t1_vals, t2_vals, indexing="ij")
    shape = AA.shape
    Q_grid = (
        G0[None, None, None, :]
        + AA[..., None] * n_hat
        + T1[..., None] * e_t1
        + T2[..., None] * e_t2
    )
    Q_flat = Q_grid.reshape(-1, 3)

    batch_fn = (
        stack.average_structure_factor_batch
        if structure_model == "average"
        else stack.structure_factor_batch
    )
    F_flat = batch_fn(Q_flat, float(energy_eV))
    F2_flat = np.abs(F_flat) ** 2

    if verbose:
        sat_info = (
            f"  pinned_sats={len(_pinned_sat_along)}" if _pinned_sat_along else
            f"  pinned_sats=0(no blocks w/ n_rep≥2)" if (pin_satellites and not _sat_periods) else ""
        )
        print(
            f"  simulate_qspace_around_spot: hkl={hkl}  layer='{layer.label}'  "
            f"grid={shape}  E={float(energy_eV):.1f} eV  "
            f"|F|²∈[{F2_flat.min():.3e}, {F2_flat.max():.3e}]" + sat_info
        )

    return {
        "hkl": (h, k, l),
        "layer": layer.label,
        "energy_eV": float(energy_eV),
        "G0": G0,
        "axes": {"n_hat": n_hat, "t1": e_t1, "t2": e_t2},
        "along": along_vals,
        "lateral1": t1_vals,
        "lateral2": t2_vals,
        "Q": Q_grid,
        "F2": F2_flat.reshape(shape),
    }

simulate_rod_qspace

simulate_rod_qspace(stack, hkl, energy_eV, layer=None, *, camera=None, ki_hat=None, q_par_range=None, q_perp_range=None, n_par=300, n_perp=300, half_size_px=40.0, perp_probe_px=5.0, max_satellites=6, structure_model='coherent', verbose=True)

Simulated |F_stack(Q)|² on a 2-D (q_parallel, q_perp) grid around one Bragg spot, evaluated at a single fixed photon energy — the simulation-side counterpart of :func:~nrxrdct.laue.laue_plotting.warp_rod_to_qspace (which instead resamples a measured detector image at the exact per-voxel elastic-condition energy). Feed the result to nrxrdct.laue.laue_plotting.plot_rod_qspace_warp-style display code, or plot it directly with imshow — the return signature (F2, q_par_ax, q_perp_ax, info) mirrors warp_rod_to_qspace's (warped, q_par_ax, q_perp_ax, info) so the two are drop-in comparable on the same axes.

As in :func:simulate_qspace_around_spot, fixing the energy means most grid points are not physically on the Ewald sphere for energy_eV — this is the bare structure-factor landscape as a function of Q, not a reconstruction of what a real energy-dispersive exposure would record (no Lorentz-polarization factor, no reachability filtering).

Axis convention

q_parallel is measured along layer.n_hat (the stacking direction, = layer_tangency's rod axis), q_perp along one transverse direction. camera given: q_perp is chosen to line up with rod_tangency's own perp_dir_px at the nominal energy — the same axis warp_rod_to_qspace/plot_rod_qspace_warp use — so a simulated map can be directly overlaid on the warped experimental one; the elastic condition is only solved here to calibrate axis directions/auto-range, never to filter or weight the simulated intensity itself. camera=None: q_perp falls back to an arbitrary transverse direction (same convention as qspace_around_spot's t1), and the extent auto-scales from the fringe period the same way simulate_qspace_around_spot does.

Parameters:
  • stack –

    LayeredCrystal

  • hkl –

    (int, int, int) Miller indices of the reference reflection.

  • energy_eV (float) –

    Fixed photon energy (eV) the structure factor is evaluated at.

  • layer –

    Layer, str, or None, optional Which layer's (crystal, U, n_hat) to use. None (default) uses stack.layers[0].

  • camera –

    Camera or None, optional Detector geometry, used only to anchor q_perp/the auto-ranged extents to the same convention warp_rod_to_qspace uses — see above. None skips all of that and uses an arbitrary transverse axis with fringe-period-based auto-ranging.

  • ki_hat –

    array-like (3,) or None, optional Incident beam direction (LT frame). Default KI_HAT. Only used when camera is given (axis calibration).

  • q_par_range, q_perp_range ((float, float) or None) –

    Output range in Å⁻¹, (min, max), centred on G0. None auto-derives from camera's pixel geometry (if given) or the fringe period (if not) — see above.

  • 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 the ranges when camera is given and a range isn't. Unused otherwise.

  • perp_probe_px (float, default: 5.0 ) –

    Pixel step used to bootstrap q_perp's direction when camera is given — same role as in warp_rod_to_qspace.

  • max_satellites (int, default: 6 ) –

    Only used to size the default extent when camera=None — same role as in simulate_qspace_around_spot/qspace_around_spot.

  • structure_model ({coherent, average}, default: 'coherent' ) –

    Same choice as simulate_qspace_around_spot.

  • verbose (bool, default: True ) –

    Print a short summary after evaluation.

Returns:
  • F2( (ndarray, shape(n_perp, n_par)) ) –

    |F_stack(Q, energy_eV)|² at every grid point.

  • q_par_ax( (ndarray, shape(n_par)) ) –

    q_parallel values (Å⁻¹).

  • q_perp_ax( (ndarray, shape(n_perp)) ) –

    q_perp values (Å⁻¹).

  • info( dict ) –

    hkl, layer, energy_eV, G0, n_hat, perp_hat, and (only when camera was given) pix0, dpix_dalong — for axis labelling/titling, matching warp_rod_to_qspace's info keys where they overlap. Also layer_obj (the resolved Layer instance, not just its label) and stack_flat (the already-flattened stack this function evaluated against, i.e. _flatten_if_multiblock(stack)) — together these let a caller (e.g. plot_simulated_rod_qspace) look up this exact layer's owning block (for satellite-comb geometry via rod_satellite_along_positions) without re-flattening the stack itself, which for a genuinely multi-block stack would produce different Layer objects than the ones this call actually used.

Example:

F2, qpar, qperp, info = simulate_rod_qspace(stack, (0, 0, 2), energy_eV=17000, camera=cam) plt.imshow(np.log1p(F2), extent=[qperp[0], qperp[-1], qpar[0], qpar[-1]], origin="lower")

Source code in src/nrxrdct/laue/simulation.py
def simulate_rod_qspace(
    stack,
    hkl,
    energy_eV,
    layer=None,
    *,
    camera=None,
    ki_hat=None,
    q_par_range=None,
    q_perp_range=None,
    n_par=300,
    n_perp=300,
    half_size_px=40.0,
    perp_probe_px=5.0,
    max_satellites=6,
    structure_model="coherent",
    verbose=True,
):
    """
    Simulated `|F_stack(Q)|²` on a 2-D `(q_parallel, q_perp)` grid around one
    Bragg spot, evaluated at a single **fixed** photon energy — the
    simulation-side counterpart of :func:`~nrxrdct.laue.laue_plotting.warp_rod_to_qspace`
    (which instead resamples a *measured* detector image at the exact
    per-voxel elastic-condition energy). Feed the result to
    `nrxrdct.laue.laue_plotting.plot_rod_qspace_warp`-style display code, or
    plot it directly with `imshow` — the return signature
    `(F2, q_par_ax, q_perp_ax, info)` mirrors `warp_rod_to_qspace`'s
    `(warped, q_par_ax, q_perp_ax, info)` so the two are drop-in comparable
    on the same axes.

    As in :func:`simulate_qspace_around_spot`, fixing the energy means most
    grid points are not physically on the Ewald sphere for `energy_eV` —
    this is the bare structure-factor landscape as a function of Q, not a
    reconstruction of what a real energy-dispersive exposure would record
    (no Lorentz-polarization factor, no reachability filtering).

    Axis convention:
        `q_parallel` is measured along `layer.n_hat` (the stacking
        direction, `= layer_tangency`'s rod axis), `q_perp` along one
        transverse direction. **`camera` given:** `q_perp` is chosen to
        line up with `rod_tangency`'s own `perp_dir_px` at the nominal
        energy — the *same* axis `warp_rod_to_qspace`/`plot_rod_qspace_warp`
        use — so a simulated map can be directly overlaid on the warped
        experimental one; the elastic condition is only solved here to
        calibrate axis directions/auto-range, never to filter or weight the
        simulated intensity itself. **`camera=None`:** `q_perp` falls back
        to an arbitrary transverse direction (same convention as
        `qspace_around_spot`'s `t1`), and the extent auto-scales from the
        fringe period the same way `simulate_qspace_around_spot` does.

    Args:
        stack : LayeredCrystal
        hkl : (int, int, int)
            Miller indices of the reference reflection.
        energy_eV (float): Fixed photon energy (eV) the structure factor is evaluated at.
        layer : Layer, str, or None, optional
            Which layer's `(crystal, U, n_hat)` to use. `None` (default)
            uses `stack.layers[0]`.
        camera : Camera or None, optional
            Detector geometry, used only to anchor `q_perp`/the auto-ranged
            extents to the same convention `warp_rod_to_qspace` uses — see
            above. `None` skips all of that and uses an arbitrary transverse
            axis with fringe-period-based auto-ranging.
        ki_hat : array-like (3,) or None, optional
            Incident beam direction (LT frame). Default `KI_HAT`. Only used
            when `camera` is given (axis calibration).
        q_par_range, q_perp_range ((float, float) or None, optional): Output range in Å⁻¹, `(min, max)`, centred on `G0`. `None`
            auto-derives from `camera`'s pixel geometry (if given) or the
            fringe period (if not) — see above.
        n_par, n_perp (int, optional): Output grid size along each axis.
        half_size_px (float, optional): Half-window (pixels) used to auto-derive the ranges when
            `camera` is given and a range isn't. Unused otherwise.
        perp_probe_px (float, optional): Pixel step used to bootstrap `q_perp`'s direction when `camera`
            is given — same role as in `warp_rod_to_qspace`.
        max_satellites (int, optional): Only used to size the default extent when `camera=None` — same
            role as in `simulate_qspace_around_spot`/`qspace_around_spot`.
        structure_model ({'coherent', 'average'}, optional): Same choice as `simulate_qspace_around_spot`.
        verbose (bool, optional): Print a short summary after evaluation.

    Returns:
        F2 (ndarray, shape (n_perp, n_par)): `|F_stack(Q, energy_eV)|²` at every grid point.
        q_par_ax (ndarray, shape (n_par,)): `q_parallel` values (Å⁻¹).
        q_perp_ax (ndarray, shape (n_perp,)): `q_perp` values (Å⁻¹).
        info (dict): `hkl`, `layer`, `energy_eV`, `G0`, `n_hat`, `perp_hat`, and
            (only when `camera` was given) `pix0`, `dpix_dalong` — for axis
            labelling/titling, matching `warp_rod_to_qspace`'s `info` keys
            where they overlap. Also `layer_obj` (the resolved `Layer`
            instance, not just its label) and `stack_flat` (the
            already-flattened `stack` this function evaluated against,
            i.e. `_flatten_if_multiblock(stack)`) — together these let a
            caller (e.g. `plot_simulated_rod_qspace`) look up this exact
            layer's owning block (for satellite-comb geometry via
            `rod_satellite_along_positions`) without re-flattening the
            stack itself, which for a genuinely multi-block stack would
            produce different `Layer` objects than the ones this call
            actually used.

    Example:
    >>> F2, qpar, qperp, info = simulate_rod_qspace(stack, (0, 0, 2), energy_eV=17000, camera=cam)
    >>> plt.imshow(np.log1p(F2), extent=[qperp[0], qperp[-1], qpar[0], qpar[-1]], origin="lower")
    """
    if type(stack).__name__ != "LayeredCrystal":
        raise TypeError(f"stack must be a LayeredCrystal, got {type(stack).__name__}")
    if structure_model not in ("coherent", "average"):
        raise ValueError(f"structure_model must be 'coherent' or 'average', got {structure_model!r}")

    stack._update_offsets()
    stack = _flatten_if_multiblock(stack)
    stack._update_offsets()

    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 = (int(x) for x in 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)

    pix0 = None
    dpix_dalong = None

    if camera is not None:
        info0 = rod_tangency(stack, hkl, layer=ly, 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}")

        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):
            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])

        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
        perp_hat = dQ_perp / np.linalg.norm(dQ_perp)

        d_step = 1e-4
        res_plus = _solve(G0 + d_step * perp_hat)
        res_minus = _solve(G0 - d_step * perp_hat)
        dpix_dperp = (
            float(np.linalg.norm(res_plus[1] - res_minus[1]) / (2.0 * d_step))
            if res_plus is not None and res_minus is not None
            else None
        )

        pix0 = info0["pix0"]
        dpix_dalong = info0["dpix_dalong"]

        if q_par_range is None:
            q_par_half = half_size_px / dpix_dalong
            q_par_range = (-q_par_half, q_par_half)
        if q_perp_range is None:
            if dpix_dperp is None:
                raise ValueError("could not evaluate d(pixel)/d(q_perp) near this reflection; pass q_perp_range explicitly")
            q_perp_half = half_size_px / dpix_dperp
            q_perp_range = (-q_perp_half, q_perp_half)
    else:
        tmp = np.array([1.0, 0.0, 0.0]) if abs(n_hat[0]) < 0.9 else np.array([0.0, 1.0, 0.0])
        perp_hat = tmp - n_hat * np.dot(tmp, n_hat)
        perp_hat /= np.linalg.norm(perp_hat)

        if q_par_range is None or q_perp_range is None:
            t_period = stack.bilayer_thickness if stack.n_rep > 1 else ly.thickness
            q_fringe = (2.0 * np.pi / t_period) if t_period > 1e-6 else 0.01 * float(np.linalg.norm(G0))
            extent_along = (max_satellites + 0.5) * q_fringe
            if q_par_range is None:
                q_par_range = (-extent_along, extent_along)
            if q_perp_range is None:
                extent_perp = 0.05 * extent_along
                q_perp_range = (-extent_perp, extent_perp)

    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)

    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, :]
    )

    batch_fn = (
        stack.average_structure_factor_batch
        if structure_model == "average"
        else stack.structure_factor_batch
    )
    F_flat = batch_fn(Q_flat, float(energy_eV))
    F2 = (np.abs(F_flat) ** 2).reshape(n_perp, n_par)

    info = {
        "hkl": (h, k, l),
        "layer": ly.label,
        "layer_obj": ly,
        "stack_flat": stack,
        "energy_eV": float(energy_eV),
        "G0": G0,
        "n_hat": n_hat,
        "perp_hat": perp_hat,
        "pix0": pix0,
        "dpix_dalong": dpix_dalong,
    }

    if verbose:
        print(
            f"  simulate_rod_qspace: hkl={hkl}  layer='{ly.label}'  E={float(energy_eV):.1f} eV  "
            f"grid=({n_perp},{n_par})  |F|²∈[{F2.min():.3e}, {F2.max():.3e}]"
        )

    return F2, q_par_ax, q_perp_ax, info

simulate_spot_image

simulate_spot_image(stack, spots, hkl, camera, layer=None, *, satellite_order=0, half_size_px=30, n_energy=101, dE_eV=300.0, pin_satellites=True, max_satellite_order=None, max_harmonics=5, E_min_eV=E_MIN_eV, E_max_eV=E_MAX_eV, source='bending_magnet', source_kwargs=None, kb_params=BM32_KB, ki_hat=None, structure_model='coherent', darwin=False, isolate_layer=False, sigma_h_mrad=0.0, sigma_v_mrad=0.0, n_div=5, verbose=True)

Forward-simulate a small detector-image patch around one already-indexed Bragg spot, evaluated per pixel rather than per reflection.

This inverts the usual direction of :func:qspace_around_spot: instead of building a grid in Q-space and asking which pixel/energy each point maps to, it starts from real pixel positions (via Camera.pixel_to_kf, an exact closed-form inverse — no root-finding) and asks what Q a photon of a given energy would need to have arrived there. For a fixed pixel, the elastic condition makes this a direct function of energy:

\[ Q(E) = k(E)\,(\hat k_f - \hat k_i), \qquad k(E) = 2\pi E / hc \]

So each pixel's structure factor is evaluated by sampling a narrow band of energies around the reference reflection's own energy E0 (from spots) — and around every integer multiple n·E0 that still falls in [E_min_eV, E_max_eV], since those are exactly the energies at which the same pixel also receives the n-th harmonic (n·hkl, exactly collinear with hkl in Q-space — see simulate_laue_stack's harmonic handling). Each harmonic's contribution is a Riemann-sum integral over its energy band; the total image is the sum over harmonics. This gives a directly comparable, per-pixel simulated image that automatically includes harmonic buildup, without any hkl-candidate enumeration or f2_thresh bookkeeping.

Parameters:
  • stack –

    LayeredCrystal The layered structure.

  • spots –

    list[dict] Output of any simulate_laue* function — used only to look up the reference reflection's energy and layer (see hkl, layer).

  • hkl –

    (int, int, int) Miller indices of the reference (fundamental, n=1) reflection.

  • camera –

    Camera Detector geometry — required (unlike qspace_around_spot, where it is optional) since pixels are the starting point here.

  • layer –

    Layer, str, or None, optional Which layer's reflection to use when multiple layers share the same hkl (matched against spots[i]['phase_label']). None (default) uses whichever matching spot is brightest.

  • satellite_order –

    int, optional Which spots[i]['satellite_order'] to match — 0 (default) targets the main (m=0) Bragg peak. A reflection commonly exists in spots only as a satellite (e.g. the main peak fell below f2_thresh or off-detector while a satellite didn't, or vice versa) — if you get a "no on-detector spot ... found" error, check the error message's suggested satellite_order values and pass one explicitly to target that entry instead.

  • half_size_px –

    int, optional Pixel window is (2*half_size_px+1) square, centred on the reference spot's own pixel (from spots).

  • n_energy –

    int, optional Energy samples per harmonic band (trapezoidal-integration resolution — see pin_satellites). Default 101.

  • dE_eV –

    float, optional Half-width (eV) of the energy band sampled around each n·E0. Default 300.0. A repeating block's S_rep interference term oscillates with period 2π/Λ in Qn (peaks spaced ~E0·2π / (Λ·|Q|) apart in energy, only 1/n_rep as wide — a few eV to a few tens of eV for a typical MQW). pin_satellites=True guarantees peaks aren't skipped, but a dE_eV narrower than a few periods still under-counts the destructive-interference minima between them and underestimates the true dynamic range — in one test case dynamic range roughly doubled going from a 150 eV to a 500 eV half-width before plateauing. 300.0 is a reasonable general-purpose default, not a precisely-tuned one — widen it further for a thick/many-repeat block, or if the image still looks flatter than expected.

  • pin_satellites –

    bool, optional True (default). A repeating block's S_rep term produces energy-domain fringe peaks spaced by (and only 1/n_rep as wide as) a period set by the block's own thickness — often much finer than any reasonable uniform n_energy grid can resolve, the same problem qspace_around_spot's own pin_satellites solves in Q-space. When True, the exact fringe-peak energies (evaluated at the window's centre pixel, valid over a modest window) are inserted into the energy grid in addition to the uniform samples, for every repeating block still present in eval_stack (i.e. respecting isolate_layer) — so they are never skipped regardless of n_energy/dE_eV. The energy integral then uses trapezoidal integration (not a fixed-step Riemann sum) to handle the resulting non-uniform grid correctly.

  • max_satellite_order –

    int or None, optional None (default) sums every satellite order that falls within dE_eV of each harmonic centre, however many that is — dE_eV wide enough to integrate destructive interference correctly (see dE_eV) can easily span 5+ orders, most of them weak. Set this to cap how many orders (|m - m_center| <= max_satellite_order) actually get summed into I/I_harmonics — e.g. 1 keeps only the main peak and its nearest satellite on each side. This is a different knob from dE_eV: dE_eV controls how finely/widely the kept orders are integrated (for correctness), max_satellite_order controls how many orders are kept in the first place (for a cleaner, less blended-looking image). Only takes effect in the same single-repeating-block case as I_satellites; ignored otherwise.

  • max_harmonics –

    int, optional Upper bound on harmonic order n, independent of the E_max_eV cutoff (whichever is more restrictive wins).

  • E_min_eV, E_max_eV –

    float, optional White-beam energy window (eV).

  • source, source_kwargs, kb_params –

    optional Synchrotron spectrum model, forwarded to _make_spectrum_fn.

  • ki_hat –

    array-like (3,) or None, optional Incident beam direction (LT frame). Default KI_HAT.

  • structure_model –

    {'coherent', 'average'}, optional Forwarded to LayeredCrystal.structure_factor_batch / average_structure_factor_batch (or, when darwin=True, to _darwin_amp_batch) — same meaning as in qspace_around_spot.

  • darwin –

    bool, optional False (default) evaluates the kinematical structure factor. True evaluates the Darwin (dynamical, extinction-saturated) amplitude instead — see qspace_around_spot's darwin for the physics; same tradeoff applies here. Compatible with isolate_layer=True.

  • isolate_layer –

    bool or list[str], optional False (default) evaluates the full multi-layer coherent (or average) stack sum, exactly like qspace_around_spot / simulate_laue_stack.

    • True — builds a minimal stand-in stack containing only the reflecting layer (or, if it belongs to a repeating block, only that block), dropping cross-terms with every other buffer layer or block. The most aggressive option — use when you don't yet know which layer(s) are causing the problem.
    • A list of buffer-layer labels — builds a stand-in stack with exactly those buffer layers excluded, keeping every other buffer layer and every repeating block coherently summed together. This is the practical choice once you've identified the problem layer (usually the deepest one, e.g. a growth substrate): it lets genuinely resolvable cross-terms between layers that are physically close together (e.g. a repeating block and the buffer layer immediately beneath it) still interfere constructively — which is often what actually produces the sharp, bright measured peak — while dropping only the pathologically deep one(s).

    Either form reuses the same Layer object(s) (so absorption_limit/d_spacing/n_cells are preserved exactly) and evaluates structure_model/darwin against the reduced stack instead of the full one. See the Note below — this is the practical fix when a buffer layer sits on a deep buffer/substrate (large absolute z0), where cross-terms with it are numerically unresolvable at pixel/energy sampling anyway. Works with both darwin=False and darwin=True.

  • sigma_h_mrad, sigma_v_mrad –

    float, optional 1σ incident-beam angular divergence (mrad), horizontal/vertical (same convention as beam_divergence_ellipses; typical BM32/ESRF values are 2-3 mrad horizontal, 0.2-0.5 mrad vertical). Both default to 0.0 (a perfectly parallel, point-like incident beam — the same idealisation used throughout this module). With zero divergence, a single reflection's intrinsic Q-response is often far narrower than any realistic pixel/energy sampling can resolve (see the Note below), and looks flat/featureless as a result — that is not a bug, it is what a delta-function beam actually implies. A real measured spot's finite size mostly comes from convolving that intrinsic response with the source's actual divergence (and, to a lesser extent, detector point-spread, not modelled here). Setting these lets the image show that realistic spot size.

  • n_div –

    int, optional Divergence grid resolution per axis (n_div × n_div samples, Gaussian-weighted, spanning ±2.5σ) when divergence is enabled. No effect when sigma_h_mrad == sigma_v_mrad == 0. Cost scales linearly with n_div**2 (an extra outer loop around the existing pixel/energy batch, so still fully vectorised per sample) — 5 is a reasonable default; raise it if the spot shape looks blocky.

  • verbose –

    bool, optional Print the resolved reference spot and per-harmonic summary.

Returns: dict with keys:

`'hkl'`, `'layer'` : the resolved inputs (`layer` as its label).
`'E0'` : float — the reference reflection's energy (eV).
`'ref_pix'` : `(x, y)` — the reference spot's own pixel (from
    `spots`), not necessarily the window centre after edge clipping.
`'x0'`, `'y0'` : ndarray, 1-D pixel coordinate arrays of the window.
`'I'` : ndarray, shape `(len(y0), len(x0))` — total simulated
    intensity per pixel, summed over all harmonics.
`'I_harmonics'` : dict `{n: ndarray}` — same shape, per harmonic
    order `n` (only orders that contributed at least one in-window
    energy sample are included).
`'n_harmonics'` : int — number of harmonic orders included.
`'I_satellites'` : dict `{n: {m: ndarray}}` — same shape, `I_harmonics[n]`
    further split by satellite order `m` (relative to the harmonic's
    own centre order, so `m=0` is the fringe order nearest `n·E0`).
    `sum(I_satellites[n].values()) == I_harmonics[n]` (up to the
    same trapezoidal-integration precision).  Only populated when
    `pin_satellites=True` **and** `eval_stack` has exactly one
    repeating block (see `pin_satellites`) — empty otherwise, since
    a single order index isn't uniquely meaningful across several
    independent periods.  This is the fix for a per-pixel image
    that looks like one flat, uniformly-bright streak: a wide
    `dE_eV` correctly integrates the destructive interference at
    *each* pixel, but also means most pixels in the window end up
    summing over the *same* few dominant orders — `I_satellites`
    lets you see which order actually dominates where, instead of
    one pre-blended total.

Note: * Because this integrates over an energy band (Riemann sum with a finite dE_eV and n_energy), I is on a different physical scale than spots[i]['I_raw'] (a single delta-like evaluation at exactly E) — treat pixel-to-pixel and harmonic-to-harmonic comparisons within this function's output as meaningful, not raw magnitude comparisons against simulate_laue_stack's spot list. * Every voxel's position (which energy band centres at which n) is exact geometry; only the intra-band sampling (dE_eV, n_energy) is an approximation — widen/refine it if a real thickness-fringe feature looks under-resolved. * Both structure_model="coherent" and "average" sum phases exp(i·Qn·z0) across every buffer layer (only the treatment of repeating-block layers differs between the two — see average_structure_factor's docstring). When the reflecting layer sits on a deep buffer/substrate (z0 up to hundreds of thousands of Å — e.g. a growth substrate under a nucleation/buffer layer), that cross-term phase is an extremely narrow function of Q: the true fringe period can be far narrower than one detector pixel or one dE_eV sampling step, in either structure model, so a per-pixel point sample cannot resolve it — the image looks flat/featureless no matter how fine dE_eV/n_energy are. This is not fixable by more sampling; use isolate_layer=True instead, which drops exactly those unresolvable cross-terms and keeps only the reflecting layer's (and, if applicable, its own repeating block's) structure — the practical choice whenever the reflecting layer is buried under another deep buffer layer. * Even a fully isolated single layer's intrinsic Q-response can still look essentially flat at realistic half_size_px/dE_eV — this is not necessarily unresolved fringe structure; with zero beam divergence (sigma_h_mrad == sigma_v_mrad == 0) a Bragg reflection is a true delta function in angle, so there is nothing broader than that to resolve in the first place. If the image is flat even after isolate_layer=True, set sigma_h_mrad/sigma_v_mrad to your source's real divergence before concluding anything is wrong. * A repeating block sitting in eval_stack (i.e. not excluded by isolate_layer) contributes an S_rep interference term that is genuinely periodic in energy at a fixed pixel — real destructive interference, not noise. pin_satellites=True (default) makes sure those peaks are never skipped by inserting their exact energies into the grid, but a dE_eV narrower than a few oscillation periods still underestimates the true peak-to-background contrast, because it only sees part of one rise/fall rather than full periods including their minima — see dE_eV. pin_satellites fixes "missing a peak entirely"; it does not by itself fix "window too narrow to judge contrast" — widen dE_eV for that.

Example:

spots = simulate_laue_stack(stack, cam) img = simulate_spot_image(stack, spots, (0, 0, 4), cam, layer='GaN') plt.imshow(np.log1p(img['I']))

Source code in src/nrxrdct/laue/simulation.py
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
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
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
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
def simulate_spot_image(
    stack,
    spots,
    hkl,
    camera,
    layer=None,
    *,
    satellite_order=0,
    half_size_px=30,
    n_energy=101,
    dE_eV=300.0,
    pin_satellites=True,
    max_satellite_order=None,
    max_harmonics=5,
    E_min_eV=E_MIN_eV,
    E_max_eV=E_MAX_eV,
    source="bending_magnet",
    source_kwargs=None,
    kb_params=BM32_KB,
    ki_hat=None,
    structure_model="coherent",
    darwin=False,
    isolate_layer=False,
    sigma_h_mrad=0.0,
    sigma_v_mrad=0.0,
    n_div=5,
    verbose=True,
):
    """
    Forward-simulate a small detector-image patch around one already-indexed
    Bragg spot, evaluated **per pixel** rather than per reflection.

    This inverts the usual direction of :func:`qspace_around_spot`: instead
    of building a grid in Q-space and asking which pixel/energy each point
    maps to, it starts from real pixel positions (via
    `Camera.pixel_to_kf`, an exact closed-form inverse — no root-finding)
    and asks what `Q` a photon of a given energy would need to have arrived
    there.  For a fixed pixel, the elastic condition makes this a direct
    function of energy:

    $$
    Q(E) = k(E)\\,(\\hat k_f - \\hat k_i), \\qquad k(E) = 2\\pi E / hc
    $$

    So each pixel's structure factor is evaluated by sampling a narrow band
    of energies around the reference reflection's own energy `E0` (from
    `spots`) — and around every integer multiple `n·E0` that still falls in
    `[E_min_eV, E_max_eV]`, since those are exactly the energies at which
    the *same* pixel also receives the `n`-th harmonic (`n·hkl`, exactly
    collinear with `hkl` in Q-space — see `simulate_laue_stack`'s harmonic
    handling).  Each harmonic's contribution is a Riemann-sum integral over
    its energy band; the total image is the sum over harmonics.  This gives
    a directly comparable, per-pixel simulated image that automatically
    includes harmonic buildup, without any hkl-candidate enumeration or
    `f2_thresh` bookkeeping.

    Args:
        stack : LayeredCrystal
            The layered structure.
        spots : list[dict]
            Output of any `simulate_laue*` function — used only to look up
            the reference reflection's energy and layer (see `hkl`,
            `layer`).
        hkl : (int, int, int)
            Miller indices of the reference (fundamental, `n=1`) reflection.
        camera : Camera
            Detector geometry — required (unlike `qspace_around_spot`,
            where it is optional) since pixels are the starting point here.
        layer : Layer, str, or None, optional
            Which layer's reflection to use when multiple layers share the
            same `hkl` (matched against `spots[i]['phase_label']`).
            `None` (default) uses whichever matching spot is brightest.
        satellite_order : int, optional
            Which `spots[i]['satellite_order']` to match — `0` (default)
            targets the main (`m=0`) Bragg peak.  A reflection commonly
            exists in `spots` *only* as a satellite (e.g. the main peak fell
            below `f2_thresh` or off-detector while a satellite didn't, or
            vice versa) — if you get a "no on-detector spot ... found"
            error, check the error message's suggested `satellite_order`
            values and pass one explicitly to target that entry instead.
        half_size_px : int, optional
            Pixel window is `(2*half_size_px+1)` square, centred on the
            reference spot's own pixel (from `spots`).
        n_energy : int, optional
            Energy samples per harmonic band (trapezoidal-integration
            resolution — see `pin_satellites`).  Default `101`.
        dE_eV : float, optional
            Half-width (eV) of the energy band sampled around each `n·E0`.
            Default `300.0`.  A repeating block's `S_rep` interference term
            oscillates with period `2π/Λ` in `Qn` (peaks spaced ~`E0·2π /
            (Λ·|Q|)` apart in energy, only `1/n_rep` as wide — a few eV to
            a few tens of eV for a typical MQW).  `pin_satellites=True`
            guarantees peaks aren't skipped, but a `dE_eV` narrower than a
            few periods still under-counts the destructive-interference
            minima between them and *underestimates* the true dynamic
            range — in one test case dynamic range roughly doubled going
            from a 150 eV to a 500 eV half-width before plateauing.
            `300.0` is a reasonable general-purpose default, not a
            precisely-tuned one — widen it further for a thick/many-repeat
            block, or if the image still looks flatter than expected.
        pin_satellites : bool, optional
            `True` (default).  A repeating block's `S_rep` term produces
            energy-domain fringe peaks spaced by (and only
            `1/n_rep` as wide as) a period set by the block's own
            thickness — often much finer than any reasonable uniform
            `n_energy` grid can resolve, the same problem
            `qspace_around_spot`'s own `pin_satellites` solves in Q-space.
            When `True`, the *exact* fringe-peak energies (evaluated at the
            window's centre pixel, valid over a modest window) are inserted
            into the energy grid in addition to the uniform samples, for
            every repeating block still present in `eval_stack` (i.e.
            respecting `isolate_layer`) — so they are never skipped
            regardless of `n_energy`/`dE_eV`.  The energy integral then
            uses trapezoidal integration (not a fixed-step Riemann sum) to
            handle the resulting non-uniform grid correctly.
        max_satellite_order : int or None, optional
            `None` (default) sums *every* satellite order that falls within
            `dE_eV` of each harmonic centre, however many that is — `dE_eV`
            wide enough to integrate destructive interference correctly
            (see `dE_eV`) can easily span 5+ orders, most of them weak.
            Set this to cap how many orders (`|m - m_center| <=
            max_satellite_order`) actually get summed into `I`/`I_harmonics`
            — e.g. `1` keeps only the main peak and its nearest satellite on
            each side.  This is a *different* knob from `dE_eV`: `dE_eV`
            controls how finely/widely the *kept* orders are integrated
            (for correctness), `max_satellite_order` controls how many
            orders are kept in the first place (for a cleaner, less
            blended-looking image).  Only takes effect in the same
            single-repeating-block case as `I_satellites`; ignored
            otherwise.
        max_harmonics : int, optional
            Upper bound on harmonic order `n`, independent of the
            `E_max_eV` cutoff (whichever is more restrictive wins).
        E_min_eV, E_max_eV : float, optional
            White-beam energy window (eV).
        source, source_kwargs, kb_params : optional
            Synchrotron spectrum model, forwarded to `_make_spectrum_fn`.
        ki_hat : array-like (3,) or None, optional
            Incident beam direction (LT frame).  Default `KI_HAT`.
        structure_model : {'coherent', 'average'}, optional
            Forwarded to `LayeredCrystal.structure_factor_batch` /
            `average_structure_factor_batch` (or, when `darwin=True`, to
            `_darwin_amp_batch`) — same meaning as in `qspace_around_spot`.
        darwin : bool, optional
            `False` (default) evaluates the kinematical structure factor.
            `True` evaluates the Darwin (dynamical, extinction-saturated)
            amplitude instead — see `qspace_around_spot`'s `darwin` for the
            physics; same tradeoff applies here.  Compatible with
            `isolate_layer=True`.
        isolate_layer : bool or list[str], optional
            `False` (default) evaluates the full multi-layer coherent (or
            average) stack sum, exactly like `qspace_around_spot` /
            `simulate_laue_stack`.

            * `True` — builds a minimal stand-in stack containing **only**
              the reflecting layer (or, if it belongs to a repeating block,
              only that block), dropping cross-terms with *every* other
              buffer layer or block.  The most aggressive option — use when
              you don't yet know which layer(s) are causing the problem.
            * A list of buffer-layer labels — builds a stand-in stack with
              exactly those buffer layers **excluded**, keeping every other
              buffer layer and every repeating block coherently summed
              together.  This is the practical choice once you've
              identified the problem layer (usually the deepest one, e.g.
              a growth substrate): it lets genuinely resolvable cross-terms
              between layers that are physically close together (e.g. a
              repeating block and the buffer layer immediately beneath it)
              still interfere constructively — which is often what actually
              produces the sharp, bright measured peak — while dropping
              only the pathologically deep one(s).

            Either form reuses the same `Layer` object(s) (so
            `absorption_limit`/`d_spacing`/`n_cells` are preserved exactly)
            and evaluates `structure_model`/`darwin` against the reduced
            stack instead of the full one.  See the Note below — this is
            the practical fix when a buffer layer sits on a deep
            buffer/substrate (large absolute `z0`), where cross-terms with
            it are numerically unresolvable at pixel/energy sampling
            anyway.  Works with both `darwin=False` and `darwin=True`.
        sigma_h_mrad, sigma_v_mrad : float, optional
            1σ incident-beam angular divergence (mrad), horizontal/vertical
            (same convention as `beam_divergence_ellipses`; typical
            BM32/ESRF values are 2-3 mrad horizontal, 0.2-0.5 mrad
            vertical).  Both default to `0.0` (a perfectly parallel,
            point-like incident beam — the same idealisation used
            throughout this module).  With zero divergence, a single
            reflection's *intrinsic* Q-response is often far narrower than
            any realistic pixel/energy sampling can resolve (see the Note
            below), and looks flat/featureless as a result — that is not a
            bug, it is what a delta-function beam actually implies.  A real
            measured spot's finite size mostly comes from convolving that
            intrinsic response with the source's actual divergence (and,
            to a lesser extent, detector point-spread, not modelled here).
            Setting these lets the image show that realistic spot size.
        n_div : int, optional
            Divergence grid resolution per axis (`n_div × n_div` samples,
            Gaussian-weighted, spanning ±2.5σ) when divergence is enabled.
            No effect when `sigma_h_mrad == sigma_v_mrad == 0`.  Cost scales
            linearly with `n_div**2` (an extra outer loop around the
            existing pixel/energy batch, so still fully vectorised per
            sample) — 5 is a reasonable default; raise it if the spot shape
            looks blocky.
        verbose : bool, optional
            Print the resolved reference spot and per-harmonic summary.

    Returns:
    dict with keys:

        `'hkl'`, `'layer'` : the resolved inputs (`layer` as its label).
        `'E0'` : float — the reference reflection's energy (eV).
        `'ref_pix'` : `(x, y)` — the reference spot's own pixel (from
            `spots`), not necessarily the window centre after edge clipping.
        `'x0'`, `'y0'` : ndarray, 1-D pixel coordinate arrays of the window.
        `'I'` : ndarray, shape `(len(y0), len(x0))` — total simulated
            intensity per pixel, summed over all harmonics.
        `'I_harmonics'` : dict `{n: ndarray}` — same shape, per harmonic
            order `n` (only orders that contributed at least one in-window
            energy sample are included).
        `'n_harmonics'` : int — number of harmonic orders included.
        `'I_satellites'` : dict `{n: {m: ndarray}}` — same shape, `I_harmonics[n]`
            further split by satellite order `m` (relative to the harmonic's
            own centre order, so `m=0` is the fringe order nearest `n·E0`).
            `sum(I_satellites[n].values()) == I_harmonics[n]` (up to the
            same trapezoidal-integration precision).  Only populated when
            `pin_satellites=True` **and** `eval_stack` has exactly one
            repeating block (see `pin_satellites`) — empty otherwise, since
            a single order index isn't uniquely meaningful across several
            independent periods.  This is the fix for a per-pixel image
            that looks like one flat, uniformly-bright streak: a wide
            `dE_eV` correctly integrates the destructive interference at
            *each* pixel, but also means most pixels in the window end up
            summing over the *same* few dominant orders — `I_satellites`
            lets you see which order actually dominates where, instead of
            one pre-blended total.

    Note:
    * Because this integrates over an energy band (Riemann sum with a
      finite `dE_eV` and `n_energy`), `I` is on a different physical scale
      than `spots[i]['I_raw']` (a single delta-like evaluation at exactly
      `E`) — treat pixel-to-pixel and harmonic-to-harmonic comparisons
      *within* this function's output as meaningful, not raw magnitude
      comparisons against `simulate_laue_stack`'s spot list.
    * Every voxel's position (which energy band centres at which `n`) is
      exact geometry; only the intra-band sampling (`dE_eV`, `n_energy`)
      is an approximation — widen/refine it if a real thickness-fringe
      feature looks under-resolved.
    * Both `structure_model="coherent"` and `"average"` sum phases
      `exp(i·Qn·z0)` across every **buffer layer** (only the treatment of
      *repeating-block* layers differs between the two — see
      `average_structure_factor`'s docstring).  When the reflecting layer
      sits on a deep buffer/substrate (`z0` up to hundreds of thousands of
      Å — e.g. a growth substrate under a nucleation/buffer layer), that
      cross-term phase is an extremely narrow function of Q: the true
      fringe period can be **far narrower than one detector pixel or one
      `dE_eV` sampling step**, in either structure model, so a per-pixel
      point sample cannot resolve it — the image looks flat/featureless no
      matter how fine `dE_eV`/`n_energy` are.  This is not fixable by more
      sampling; use `isolate_layer=True` instead, which drops exactly
      those unresolvable cross-terms and keeps only the reflecting layer's
      (and, if applicable, its own repeating block's) structure — the
      practical choice whenever the reflecting layer is buried under
      another deep buffer layer.
    * Even a fully isolated single layer's intrinsic Q-response can still
      look essentially flat at realistic `half_size_px`/`dE_eV` — this is
      *not* necessarily unresolved fringe structure; with zero beam
      divergence (`sigma_h_mrad == sigma_v_mrad == 0`) a Bragg reflection
      is a true delta function in angle, so there is nothing broader than
      that to resolve in the first place.  If the image is flat even after
      `isolate_layer=True`, set `sigma_h_mrad`/`sigma_v_mrad` to your
      source's real divergence before concluding anything is wrong.
    * A repeating block sitting in `eval_stack` (i.e. not excluded by
      `isolate_layer`) contributes an `S_rep` interference term that is
      genuinely periodic in energy at a fixed pixel — real destructive
      interference, not noise.  `pin_satellites=True` (default) makes sure
      those peaks are never skipped by inserting their exact energies into
      the grid, but a `dE_eV` narrower than a few oscillation periods still
      *underestimates* the true peak-to-background contrast, because it
      only sees part of one rise/fall rather than full periods including
      their minima — see `dE_eV`.  `pin_satellites` fixes "missing a peak
      entirely"; it does not by itself fix "window too narrow to judge
      contrast" — widen `dE_eV` for that.

    Example:
    >>> spots = simulate_laue_stack(stack, cam)
    >>> img = simulate_spot_image(stack, spots, (0, 0, 4), cam, layer='GaN')
    >>> plt.imshow(np.log1p(img['I']))
    """
    if type(stack).__name__ != "LayeredCrystal":
        raise TypeError(f"stack must be a LayeredCrystal, got {type(stack).__name__}")
    if structure_model not in ("coherent", "average"):
        raise ValueError(f"structure_model must be 'coherent' or 'average', got {structure_model!r}")
    h, k, l = (int(x) for x in hkl)
    layer_label = layer.label if hasattr(layer, "label") else layer
    candidates = [
        s for s in spots
        if tuple(s["hkl"]) == (h, k, l)
        and s.get("satellite_order", 0) == satellite_order
        and s.get("pix") is not None
        and (layer_label is None or s.get("phase_label") == layer_label)
    ]
    if not candidates:
        # A spot with this hkl/layer often *does* exist in `spots` but at a
        # different satellite_order than requested (e.g. only as a satellite,
        # not the m=0 main peak, or vice versa) — report what's actually
        # there instead of a bare "not found", since that's the most common
        # cause of this error despite the reflection genuinely being present.
        same_hkl_layer = [
            s for s in spots
            if tuple(s["hkl"]) == (h, k, l) and s.get("pix") is not None
            and (layer_label is None or s.get("phase_label") == layer_label)
        ]
        layer_part = f", layer={layer_label!r}" if layer_label is not None else ""
        if same_hkl_layer:
            available = sorted({s.get("satellite_order", 0) for s in same_hkl_layer})
            raise ValueError(
                f"no on-detector spot with hkl={(h, k, l)}{layer_part} at "
                f"satellite_order={satellite_order} found in `spots` — but "
                f"{len(same_hkl_layer)} spot(s) with this hkl/layer exist at "
                f"satellite_order in {available}; pass satellite_order=... "
                f"to target one of those."
            )
        raise ValueError(f"no on-detector spot with hkl={(h, k, l)}{layer_part} found in `spots`")
    s0 = max(candidates, key=lambda s: s.get("intensity", 0.0))
    E0 = float(s0["E"])
    x0_center, y0_center = s0["pix"]
    phase_label = s0["phase_label"]
    resolved_layer = next((ly for ly in stack.all_layers if ly.label == phase_label), None)
    if resolved_layer is None:
        raise ValueError(f"spot's phase_label {phase_label!r} not found in stack.all_layers")

    iso_stack = None
    if isolate_layer:
        stack._update_offsets()
        # A reduced LayeredCrystal reusing the *same* Layer object(s) (so
        # absorption_limit / d_spacing / n_cells are exactly preserved), so
        # some deep-z0 cross-terms never enter the coherent sum.  This lets
        # us reuse structure_factor_batch / average_structure_factor_batch /
        # _darwin_amp_batch completely unchanged, just scoped to a smaller
        # stack, instead of duplicating that physics here.  `_RepeatBlock`
        # instances are always shallow-copied (never shared with `stack`
        # itself), since `_update_offsets()` mutates them in place — sharing
        # would corrupt the original stack's cached offsets.
        from .layers import LayeredCrystal as _LayeredCrystal
        from .layers import _RepeatBlock as _RepeatBlockCls

        def _copy_block(blk):
            new_blk = _RepeatBlockCls()
            new_blk.layers = list(blk.layers)
            new_blk.n_rep = blk.n_rep
            new_blk._closed = True
            return new_blk

        if isolate_layer is True:
            # Isolate to just the reflecting layer (or its own block) —
            # drops cross-terms with *every* other buffer layer/block.
            owning_block = None
            if resolved_layer not in stack.buffer_layers:
                owning_block = next(
                    (blk for blk in stack._blocks if resolved_layer in blk.layers), None
                )
                if owning_block is None:
                    raise ValueError(
                        f"isolate_layer=True: layer {phase_label!r} not found among "
                        "stack.buffer_layers or any repeating block"
                    )
            iso_stack = _LayeredCrystal(name="_isolated", stacking_direction=stack.n_hat)
            if owning_block is None:
                iso_stack.buffer_layers.append(resolved_layer)
            else:
                iso_stack._blocks.append(_copy_block(owning_block))
        else:
            # isolate_layer is an iterable of buffer-layer labels to exclude
            # — keep everything else (all blocks, all other buffer layers)
            # coherently summed, so genuinely resolvable cross-terms (e.g.
            # between a repeating block and the buffer layer immediately
            # beneath it) are preserved; only the excluded (typically
            # pathologically deep) buffer layers are dropped.
            exclude_labels = set(isolate_layer)
            missing = exclude_labels - {ly.label for ly in stack.buffer_layers}
            if missing:
                raise ValueError(
                    f"isolate_layer excludes labels not found in stack.buffer_layers: {missing}"
                )
            iso_stack = _LayeredCrystal(name="_isolated", stacking_direction=stack.n_hat)
            for ly in stack.buffer_layers:
                if ly.label not in exclude_labels:
                    iso_stack.buffer_layers.append(ly)
            for blk in stack._blocks:
                iso_stack._blocks.append(_copy_block(blk))
        iso_stack._update_offsets()

    xs = np.arange(int(round(x0_center)) - half_size_px, int(round(x0_center)) + half_size_px + 1)
    ys = np.arange(int(round(y0_center)) - half_size_px, int(round(y0_center)) + half_size_px + 1)
    xs = xs[(xs >= 0) & (xs < camera.Nh)]
    ys = ys[(ys >= 0) & (ys < camera.Nv)]
    if len(xs) == 0 or len(ys) == 0:
        raise ValueError("pixel window falls entirely off the detector")
    XX, YY = np.meshgrid(xs, ys)
    shape = XX.shape
    kf_hat = camera.pixel_to_kf(XX.ravel().astype(float), YY.ravel().astype(float))

    ki = np.asarray(ki_hat if ki_hat is not None else KI_HAT, dtype=float)
    ki = ki / np.linalg.norm(ki)
    spectrum = _make_spectrum_fn(source, source_kwargs or {}, kb_params)

    # ── anchor Q to the exact reciprocal-lattice point ────────────────────────
    # `camera.pixel_to_kf` reconstructs kf_hat from the *stored* (float, but
    # not infinite-precision) reference pixel, which differs from the true
    # kf_hat0 (the one `simulate_laue_stack` actually used to place this spot)
    # by a tiny angular bias — sub-1e-4 px worth of calibration/round-trip
    # noise.  That is utterly negligible geometrically, but every buried
    # layer's coherent phase is `exp(i * Qn * z0)` with `z0` up to hundreds of
    # thousands of Å (a deep substrate), so `Δ(Qn) * z0` can be many radians —
    # the coherent structure factor is essentially randomised at every pixel,
    # including the reference one, unless Q is anchored to the reflection's
    # exact analytic G0.  We do that anchoring once here and re-apply the same
    # (energy-scaled) correction to every sampled pixel/energy below — a
    # locally constant angular-bias correction, valid over a modest window.
    if s0.get("G_lab") is not None:
        # Trust the *exact* Q that simulate_laue_stack itself used to place
        # this spot — critical for a pseudomorphically strained layer
        # (add_pseudomorphic_layer only corrects the growth-direction
        # d-spacing, not layer.crystal, so layer.U @ layer.crystal.Q(h,k,l)
        # below silently recomputes the *bulk*, unstrained G0 — wrong
        # whenever strain shifts the true reflection position).
        G0_exact = np.asarray(s0["G_lab"], dtype=float)
    else:
        G0_exact = resolved_layer.U @ resolved_layer.crystal.Q(h, k, l)
    kf_hat0 = camera.pixel_to_kf(np.array([x0_center]), np.array([y0_center]))[0]
    k0 = 2.0 * np.pi / float(en2lam(np.array([E0]))[0])
    Q_correction = G0_exact - k0 * (kf_hat0 - ki)

    # ── incident-beam angular divergence grid ─────────────────────────────────
    # `ki` above is the single, perfectly-parallel nominal beam direction used
    # throughout this module.  With zero divergence a Bragg reflection is a
    # true delta function in angle, so a real measured spot's finite size
    # mostly comes from the source's actual divergence — see `sigma_h_mrad`
    # docstring.  Same (e_h, e_v) convention as `beam_divergence_ellipses`.
    if sigma_h_mrad <= 0.0 and sigma_v_mrad <= 0.0:
        ki_pert_arr = ki[None, :]
        div_weights = np.array([1.0])
    else:
        z_hat = np.array([0.0, 0.0, 1.0])
        cross_zk = np.cross(z_hat, ki)
        e_h = cross_zk / np.linalg.norm(cross_zk) if np.linalg.norm(cross_zk) > 1e-6 else np.array([0.0, 1.0, 0.0])
        e_v = np.cross(ki, e_h)
        e_v /= np.linalg.norm(e_v)
        sigma_h = sigma_h_mrad * 1e-3
        sigma_v = sigma_v_mrad * 1e-3
        dh_vals = np.linspace(-2.5, 2.5, n_div) * sigma_h if sigma_h > 0 else np.zeros(1)
        dv_vals = np.linspace(-2.5, 2.5, n_div) * sigma_v if sigma_v > 0 else np.zeros(1)
        DH, DV = np.meshgrid(dh_vals, dv_vals, indexing="ij")
        DH, DV = DH.reshape(-1), DV.reshape(-1)
        ki_pert_arr = ki[None, :] + DH[:, None] * e_h[None, :] + DV[:, None] * e_v[None, :]
        ki_pert_arr /= np.linalg.norm(ki_pert_arr, axis=1, keepdims=True)
        wh = np.exp(-0.5 * (DH / sigma_h) ** 2) if sigma_h > 0 else np.ones_like(DH)
        wv = np.exp(-0.5 * (DV / sigma_v) ** 2) if sigma_v > 0 else np.ones_like(DV)
        div_weights = wh * wv
        div_weights = div_weights / div_weights.sum()
    n_div_actual = len(div_weights)

    n_pix = kf_hat.shape[0]
    n_max = min(max_harmonics, int(np.floor(E_max_eV / E0)))
    if n_max < 1:
        raise ValueError(f"reference energy E0={E0:.0f} eV already exceeds E_max_eV={E_max_eV:.0f}")

    # `isolate_layer` swaps in the minimal `iso_stack` built above (only the
    # reflecting layer / its own block, no cross-terms with other buffer
    # layers or blocks) — everything below is otherwise identical for both
    # cases, kinematical or Darwin.
    eval_stack = iso_stack if isolate_layer else stack
    eval_stack._update_offsets()
    _pin_periods = [
        blk._period for blk in eval_stack._blocks
        if blk.n_rep >= 2 and blk._period > 1e-6
    ]

    def _Qn_center(E_arr):
        """Qn(E) at the window's centre pixel (kf_hat0) — used only to
        locate exact S_rep fringe-peak energies for pinning below."""
        lam_c = en2lam(E_arr)
        k_c = 2.0 * np.pi / lam_c
        Q_c = k_c[:, None] * (kf_hat0 - ki)[None, :] + (E_arr / E0)[:, None] * Q_correction[None, :]
        return Q_c @ stack.n_hat

    I_total = np.zeros(n_pix)
    I_harmonics = {}
    I_satellites = {}
    for n in range(1, n_max + 1):
        E_center = n * E0
        if E_center > E_max_eV:
            break
        E_samples = np.linspace(E_center - dE_eV, E_center + dE_eV, n_energy)

        # `pinned_with_m` keeps (E_pin, m) so the energy axis can also be
        # segmented per satellite order below — only when there is exactly
        # one relevant repeating block, since a single "m" isn't uniquely
        # meaningful across several independent periods.
        pinned_with_m = []
        m_center_single = None
        if pin_satellites and _pin_periods:
            Qn_c = float(_Qn_center(np.array([E_center]))[0])
            Qn_slope = float(_Qn_center(np.array([E_center + 1.0]))[0]) - Qn_c  # per eV
            pinned = []
            if abs(Qn_slope) > 1e-14:
                for Lambda in _pin_periods:
                    q_fringe = 2.0 * np.pi / Lambda
                    m_center = round(Qn_c / q_fringe)
                    if len(_pin_periods) == 1:
                        m_center_single = m_center
                    m_span = int(np.ceil(abs(dE_eV * Qn_slope) / q_fringe)) + 2
                    for m in range(m_center - m_span, m_center + m_span + 1):
                        E_pin = E_center + (m * q_fringe - Qn_c) / Qn_slope
                        if E_center - dE_eV <= E_pin <= E_center + dE_eV:
                            pinned.append(E_pin)
                            if len(_pin_periods) == 1:
                                pinned_with_m.append((E_pin, m))
            if pinned:
                E_samples = np.concatenate([E_samples, np.array(pinned)])

        E_samples = np.unique(E_samples)
        E_samples = E_samples[(E_samples >= E_min_eV) & (E_samples <= E_max_eV)]
        if len(E_samples) == 0:
            continue
        n_e = len(E_samples)

        # `pinned_with_m` was built against the *window* bounds
        # (E_center +/- dE_eV) above, before E_samples was clipped to the
        # *global* [E_min_eV, E_max_eV] range — re-clip here so every pin
        # used to build _order_segments below actually survives into
        # E_samples. Otherwise, for a reflection whose window straddles
        # E_min_eV/E_max_eV, a dropped edge pin leaves mid_E (and hence
        # boundary_idx via searchsorted) pointing past the end of the
        # array, and np.arange(start, end + 1) below silently walks one
        # index out of bounds.
        if pinned_with_m:
            pinned_with_m = [
                (e, m) for e, m in pinned_with_m if E_min_eV <= e <= E_max_eV
            ]

        # Segment the energy axis at the midpoints between consecutive
        # pinned satellite orders, so each order's own contribution to the
        # energy integral can be reported separately — the fix for a wide
        # dE_eV blending every order into one flat-looking total (see
        # `I_satellites`/pin_satellites docstring).  Consecutive segments
        # share their boundary *sample* (not just an energy range) — trapz
        # over [a..b] plus trapz over [b..c] only equals trapz over [a..c]
        # when point `b` is included in both pieces; splitting on an energy
        # range with no sample exactly at the midpoint silently drops the
        # sliver of area straddling it.
        _order_segments = None
        if pinned_with_m and m_center_single is not None:
            _sorted_pins = sorted(pinned_with_m)
            pin_E = np.array([e for e, _ in _sorted_pins])
            pin_m = np.array([m for _, m in _sorted_pins])
            mid_E = 0.5 * (pin_E[:-1] + pin_E[1:])
            boundary_idx = np.clip(
                np.searchsorted(E_samples, mid_E), 0, len(E_samples) - 1
            )
            starts = np.concatenate([[0], boundary_idx])
            ends = np.concatenate([boundary_idx, [len(E_samples) - 1]])
            _order_segments = []
            for m, start, end in zip(pin_m, starts, ends):
                if end - start >= 1:
                    idx = np.arange(start, end + 1)
                    _order_segments.append((int(m - m_center_single), idx))

        # `max_satellite_order` — drop samples belonging to far orders
        # *before* the (expensive) structure-factor evaluation below, both
        # to keep the total less blended and to save compute.  Re-indexes
        # `_order_segments` against the filtered E_samples.
        if max_satellite_order is not None and _order_segments:
            keep_mask = np.zeros(len(E_samples), dtype=bool)
            for rel_m, idx in _order_segments:
                if abs(rel_m) <= max_satellite_order:
                    keep_mask[idx] = True
            if keep_mask.any() and not keep_mask.all():
                keep_idx = np.where(keep_mask)[0]
                remap = -np.ones(len(E_samples), dtype=int)
                remap[keep_idx] = np.arange(len(keep_idx))
                E_samples = E_samples[keep_idx]
                _order_segments = [
                    (rel_m, remap[idx]) for rel_m, idx in _order_segments
                    if abs(rel_m) <= max_satellite_order
                ]
                n_e = len(E_samples)

        lam_samples = en2lam(E_samples)
        k_samples = 2.0 * np.pi / lam_samples
        E_flat = np.tile(E_samples, n_pix)
        kf_flat = np.repeat(kf_hat, n_e, axis=0)

        # tth/chi/LP/spectrum depend only on kf_hat (fixed by pixel) and
        # energy — identical across divergence samples, so computed once.
        tth_flat = np.degrees(np.arccos(np.clip(kf_flat[:, 0], -1.0, 1.0)))
        chi_flat = np.degrees(np.arctan2(kf_flat[:, 1], kf_flat[:, 2] + 1e-17))
        LP_flat = _lorentz_pol_vec(tth_flat, E_flat, chi_flat)
        sw_flat = spectrum(E_flat)

        I_n = np.zeros(n_pix)
        for d in range(n_div_actual):
            ki_d = ki_pert_arr[d]
            diff_d = kf_hat - ki_d[None, :]  # (n_pix, 3)
            Q_all = k_samples[None, :, None] * diff_d[:, None, :]  # (n_pix, n_e, 3)
            # energy-scaled anchor correction — see note above `Q_correction`
            Q_all = Q_all + (E_samples / E0)[None, :, None] * Q_correction[None, None, :]
            Q_flat = Q_all.reshape(-1, 3)

            if darwin:
                lam_flat = en2lam(E_flat)
                F_arr, _, _ = _darwin_amp_batch(
                    eval_stack, ki_d, structure_model, Q_flat, E_flat, lam_flat, tth_flat,
                    kf_hat_arr=kf_flat, n_bins=_STRUCTURE_FACTOR_ENERGY_BINS,
                )
            else:
                batch_fn = (
                    eval_stack.average_structure_factor_batch
                    if structure_model == "average"
                    else eval_stack.structure_factor_batch
                )
                F_arr = batch_fn(Q_flat, float(E_center), kf_hat_arr=kf_flat)

            F2_flat = np.abs(F_arr) ** 2
            I_flat = (F2_flat * LP_flat * sw_flat).reshape(n_pix, n_e)
            # Trapezoidal, not a fixed-step Riemann sum — E_samples is
            # generally non-uniform once pin_satellites has inserted exact
            # fringe-peak energies alongside the uniform grid.
            I_n += div_weights[d] * (
                np.trapz(I_flat, x=E_samples, axis=1) if n_e > 1
                else I_flat[:, 0] * 2.0 * dE_eV
            )

            if _order_segments:
                harm_sat = I_satellites.setdefault(n, {})
                for rel_m, seg_idx in _order_segments:
                    contrib = np.trapz(I_flat[:, seg_idx], x=E_samples[seg_idx], axis=1)
                    if rel_m not in harm_sat:
                        harm_sat[rel_m] = np.zeros(n_pix)
                    harm_sat[rel_m] += div_weights[d] * contrib

        I_harmonics[n] = I_n.reshape(shape)
        I_total += I_n

        if verbose:
            print(f"    n={n}  E_center={E_center:.0f} eV  "
                  f"{n_e}/{n_energy} samples in window  "
                  f"{n_div_actual} divergence sample(s)  "
                  f"peak I={I_n.max():.3e}")

    if verbose:
        print(
            f"  simulate_spot_image: hkl={(h, k, l)}  layer={phase_label!r}  "
            f"E0={E0:.0f} eV  window={shape[1]}x{shape[0]} px  "
            f"harmonics=1..{len(I_harmonics)}"
        )

    return {
        "hkl": (h, k, l),
        "layer": phase_label,
        "E0": E0,
        "ref_pix": (float(x0_center), float(y0_center)),
        "x0": xs.astype(float),
        "y0": ys.astype(float),
        "I": I_total.reshape(shape),
        "I_harmonics": I_harmonics,
        "n_harmonics": len(I_harmonics),
        "I_satellites": {
            n: {m: arr.reshape(shape) for m, arr in sat.items()}
            for n, sat in I_satellites.items()
        },
    }

spectrum_bm

spectrum_bm(E_eV, Ec_eV=E_CRIT_eV, N=1)

Bending magnet / wiggler on-axis spectral flux (Kim 1989).

Source code in src/nrxrdct/laue/simulation.py
def spectrum_bm(E_eV, Ec_eV=E_CRIT_eV, N=1):
    """Bending magnet / wiggler on-axis spectral flux (Kim 1989)."""
    y = E_eV / Ec_eV
    if y <= 1e-7:
        return 0.0
    return float(2 * N * y**2 * kv(2 / 3, y / 2) ** 2)

spectrum_undulator

spectrum_undulator(E_eV, E1_eV=E_FUNDAMENTAL_eV, n_harm=N_HARMONICS, sig_rel=HARMONIC_WIDTH)

Planar undulator: sum of odd Gaussian harmonics.

Source code in src/nrxrdct/laue/simulation.py
def spectrum_undulator(
    E_eV, E1_eV=E_FUNDAMENTAL_eV, n_harm=N_HARMONICS, sig_rel=HARMONIC_WIDTH
):
    """Planar undulator: sum of odd Gaussian harmonics."""
    s = 0.0
    for n in range(1, 2 * n_harm, 2):
        En = n * E1_eV
        s += (1.0 / n) * np.exp(-0.5 * ((E_eV - En) / (En * sig_rel)) ** 2)
    return float(s)

spot_LP_and_SE

spot_LP_and_SE(spots, hkl, chi_deg=None, verbose=True)

Look up a reflection by Miller index and report its LP(2θ) and S(E).

Searches each spot's primary 'hkl' first; if not found there, also checks 'harmonic_hkls' (reflections merged onto the same detector pixel by :func:_merge_or_append_spot) and rescales the pixel's stored energy by the harmonic order, since E_n = n * E_1 for hkl' = n*hkl.

Parameters

spots : list of dict Output of :func:simulate_laue. hkl : (int, int, int) Miller indices to look up. chi_deg : float, optional Override azimuthal angle passed to :func:lorentz_pol; defaults to the spot's own 'chi'. verbose : bool Print a summary line if True (default).

Returns

dict with keys 'hkl', 'E', 'tth', 'chi', 'LP', 'S' — or None if hkl is not present in spots.

Source code in src/nrxrdct/laue/simulation.py
def spot_LP_and_SE(spots, hkl, chi_deg=None, verbose=True):
    """Look up a reflection by Miller index and report its LP(2θ) and S(E).

    Searches each spot's primary `'hkl'` first; if not found there, also
    checks `'harmonic_hkls'` (reflections merged onto the same detector
    pixel by :func:`_merge_or_append_spot`) and rescales the pixel's stored
    energy by the harmonic order, since E_n = n * E_1 for hkl' = n*hkl.

    Parameters
    ----------
    spots : list of dict
        Output of :func:`simulate_laue`.
    hkl : (int, int, int)
        Miller indices to look up.
    chi_deg : float, optional
        Override azimuthal angle passed to :func:`lorentz_pol`; defaults to
        the spot's own `'chi'`.
    verbose : bool
        Print a summary line if True (default).

    Returns
    -------
    dict with keys `'hkl'`, `'E'`, `'tth'`, `'chi'`, `'LP'`, `'S'` — or
    `None` if `hkl` is not present in `spots`.
    """
    hkl = tuple(int(x) for x in hkl)
    for s in spots:
        if s["hkl"] == hkl:
            E, tth, chi = s["E"], s["tth"], s["chi"]
        elif hkl in s.get("harmonic_hkls", []):
            order = s["harmonic_orders"][s["harmonic_hkls"].index(hkl)]
            if order is None:
                continue
            E, tth, chi = order * s["E"], s["tth"], s["chi"]
        else:
            continue

        chi_used = chi_deg if chi_deg is not None else chi
        LP = lorentz_pol(tth, energy_eV=E, chi_deg=chi_used)
        S = synchrotron_spectrum(E)

        result = {"hkl": hkl, "E": E, "tth": tth, "chi": chi, "LP": LP, "S": S}
        if verbose:
            print(
                f"hkl={hkl}  E={E:.1f} eV  2θ={tth:.3f}°  chi={chi:.3f}°  "
                f"LP(2θ)={LP:.5g}   S(E)={S:.5g}"
            )
        return result

    if verbose:
        print(f"hkl={hkl} not found in spots.")
    return None

strain_broadening

strain_broadening(spots, crystal, U, camera, eps_voigt_std=0.001, eps_cov=None, eps_step=1e-05)

Estimate the pixel-space broadening of each Laue spot due to strain.

Given a strain distribution characterised by a covariance matrix Σ_ε (6×6 in Voigt space), the pixel-space covariance of a spot is:

$$ \Sigma_{\text{pix}} = J \, \Sigma_{\varepsilon} \, J^{\top} $$ where J (2×6) is the strain Jacobian from :func:strain_spot_jacobian. The broadening is reported as the RMS pixel spread (square root of the largest eigenvalue of Σ_pix) and the full 2×2 pixel covariance, from which the ellipse axes and orientation can be extracted.

spots : list of dict Output of :func:simulate_laue. crystal : xu.materials.Crystal Same crystal used to produce spots. U : ndarray, shape (3, 3) Rotation-only orientation matrix (from :func:decompose_matstarlab). camera : Camera Same camera used to produce spots. eps_voigt_std : float or array-like, shape (6,), optional Standard deviation of each Voigt strain component [σ₁₁, σ₂₂, σ₃₃, σ₂₃, σ₁₃, σ₁₂]. If scalar, the same std is applied to all six components. Ignored when eps_cov is provided. Default: 1e-3 (typical elastic strain). eps_cov : array-like, shape (6, 6), optional Full 6×6 covariance matrix of the strain distribution (Voigt basis). When provided, overrides eps_voigt_std. eps_step : float, optional Finite-difference step for the Jacobian computation.

list of dict Copy of spots with three new keys added to each entry:

`'sigma_strain_pix'` : float
    RMS broadening (pixels) = √(largest eigenvalue of Σ_pix).
    This is the semi-major axis of the broadening ellipse.
`'sigma_strain_minor'` : float
    Semi-minor axis of the broadening ellipse (pixels).
`'cov_pix'` : ndarray, shape (2, 2)
    Full pixel-space covariance matrix.  Its eigenvectors give the
    orientations of the broadening ellipse on the detector.

Note: * The broadening is relative to the spot centre; it does not include the intrinsic diffraction spot width (set by sigma_pix in :meth:Camera.render). * To render spots with strain broadening included, pass sigma_pix=sigma_strain_pix to :meth:Camera.render, or add it in quadrature: sigma_total = sqrt(sigma_instrument² + sigma_strain²). * The Jacobian approach is linear (first-order); it is accurate for strain spreads ≪ 1 and fails if strain is so large that spots migrate by more than ~10 px.

Source code in src/nrxrdct/laue/simulation.py
def strain_broadening(
    spots, crystal, U, camera, eps_voigt_std=1e-3, eps_cov=None, eps_step=1e-5
):
    """
    Estimate the pixel-space broadening of each Laue spot due to strain.

    Given a strain distribution characterised by a covariance matrix Σ_ε
    (6×6 in Voigt space), the pixel-space covariance of a spot is:

    $$
    \\Sigma_{\\text{pix}} = J \\, \\Sigma_{\\varepsilon} \\, J^{\\top}
    $$
    where J (2×6) is the strain Jacobian from :func:`strain_spot_jacobian`.
    The broadening is reported as the RMS pixel spread (square root of the
    largest eigenvalue of Σ_pix) and the full 2×2 pixel covariance, from
    which the ellipse axes and orientation can be extracted.

    Args:
    spots : list of dict
        Output of :func:`simulate_laue`.
    crystal : xu.materials.Crystal
        Same crystal used to produce `spots`.
    U : ndarray, shape (3, 3)
        Rotation-only orientation matrix (from :func:`decompose_matstarlab`).
    camera : Camera
        Same camera used to produce `spots`.
    eps_voigt_std : float or array-like, shape (6,), optional
        Standard deviation of each Voigt strain component
        [σ₁₁, σ₂₂, σ₃₃, σ₂₃, σ₁₃, σ₁₂].
        If scalar, the same std is applied to all six components.
        Ignored when `eps_cov` is provided.
        Default: 1e-3 (typical elastic strain).
    eps_cov : array-like, shape (6, 6), optional
        Full 6×6 covariance matrix of the strain distribution (Voigt basis).
        When provided, overrides `eps_voigt_std`.
    eps_step : float, optional
        Finite-difference step for the Jacobian computation.

    Returns:
    list of dict
        Copy of `spots` with three new keys added to each entry:

        `'sigma_strain_pix'` : float
            RMS broadening (pixels) = √(largest eigenvalue of Σ_pix).
            This is the semi-major axis of the broadening ellipse.
        `'sigma_strain_minor'` : float
            Semi-minor axis of the broadening ellipse (pixels).
        `'cov_pix'` : ndarray, shape (2, 2)
            Full pixel-space covariance matrix.  Its eigenvectors give the
            orientations of the broadening ellipse on the detector.

    Note:
    * The broadening is relative to the spot centre; it does **not** include
      the intrinsic diffraction spot width (set by `sigma_pix` in
      :meth:`Camera.render`).
    * To render spots with strain broadening included, pass
      `sigma_pix=sigma_strain_pix` to :meth:`Camera.render`, or add it in
      quadrature: `sigma_total = sqrt(sigma_instrument² + sigma_strain²)`.
    * The Jacobian approach is linear (first-order); it is accurate for
      strain spreads ≪ 1 and fails if strain is so large that spots migrate
      by more than ~10 px.
"""
    if eps_cov is not None:
        Sigma_eps = np.asarray(eps_cov, dtype=float)
    else:
        std = np.broadcast_to(np.asarray(eps_voigt_std, dtype=float), (6,))
        Sigma_eps = np.diag(std**2)

    jacobians = strain_spot_jacobian(spots, crystal, U, camera, eps_step=eps_step)

    result = []
    for s in spots:
        s = dict(s)
        J = jacobians.get(s["hkl"])
        if J is not None and np.any(J != 0):
            cov_pix = J @ Sigma_eps @ J.T  # (2,2)
            eigvals = np.linalg.eigvalsh(cov_pix)
            eigvals = np.maximum(eigvals, 0.0)  # numerical guard
            s["sigma_strain_pix"] = float(np.sqrt(eigvals.max()))
            s["sigma_strain_minor"] = float(np.sqrt(eigvals.min()))
            s["cov_pix"] = cov_pix
        else:
            s["sigma_strain_pix"] = 0.0
            s["sigma_strain_minor"] = 0.0
            s["cov_pix"] = np.zeros((2, 2))
        result.append(s)

    return result

strain_spot_jacobian

strain_spot_jacobian(spots, crystal, U, camera, eps_step=1e-05)

Compute the 2×6 Jacobian ∂(xcam, ycam)/∂ε_voigt for each Laue spot.

For each reflection (hkl) in spots, a small strain increment is applied to each of the six independent tensor strain components (Voigt order: ε₁₁, ε₂₂, ε₃₃, ε₂₃, ε₁₃, ε₁₂) and the resulting shift in pixel coordinates is measured via finite differences.

Physics note — in white-beam Laue the incident wavelength adjusts freely to satisfy the Laue condition. A pure hydrostatic strain rescales |G| but not its direction, so it does not shift the spot. Only the deviatoric part of the strain (which rotates G) moves spots. The Jacobian captures this automatically.

spots : list of dict Output of :func:simulate_laue (must contain 'hkl' and 'pix'). crystal : xu.materials.Crystal Same crystal used to produce spots. U : ndarray, shape (3, 3) Orientation matrix used to produce spots (LT frame). Pass the rotation-only U from :func:decompose_matstarlab, not the full deformation gradient F, so that strain perturbations are applied on top of a clean orientation. camera : Camera Same camera used to produce spots. eps_step : float, optional Finite-difference step size for each strain component (dimensionless). Default 1e-5 is safe for typical elastic strains ~10⁻³.

jacobians : dict {(h,k,l): ndarray shape (2, 6)} Maps each hkl tuple to its 2×6 Jacobian matrix J where::

    [δxcam, δycam] ≈ J @ δε_voigt

Spots for which the perturbed beam misses the detector for one or
more components will have those columns set to zero.
Source code in src/nrxrdct/laue/simulation.py
def strain_spot_jacobian(spots, crystal, U, camera, eps_step=1e-5):
    """
    Compute the 2×6 Jacobian ∂(xcam, ycam)/∂ε_voigt for each Laue spot.

    For each reflection (hkl) in `spots`, a small strain increment is applied
    to each of the six independent tensor strain components (Voigt order:
    ε₁₁, ε₂₂, ε₃₃, ε₂₃, ε₁₃, ε₁₂) and the resulting shift in pixel
    coordinates is measured via finite differences.

    **Physics note** — in white-beam Laue the incident wavelength adjusts
    freely to satisfy the Laue condition.  A pure hydrostatic strain rescales
    |G| but not its direction, so it does **not** shift the spot.  Only the
    *deviatoric* part of the strain (which rotates G) moves spots.  The
    Jacobian captures this automatically.

    Args:
    spots : list of dict
        Output of :func:`simulate_laue` (must contain `'hkl'` and `'pix'`).
    crystal : xu.materials.Crystal
        Same crystal used to produce `spots`.
    U : ndarray, shape (3, 3)
        Orientation matrix used to produce `spots` (LT frame).
        Pass the **rotation-only** U from :func:`decompose_matstarlab`,
        not the full deformation gradient F, so that strain perturbations
        are applied on top of a clean orientation.
    camera : Camera
        Same camera used to produce `spots`.
    eps_step : float, optional
        Finite-difference step size for each strain component (dimensionless).
        Default 1e-5 is safe for typical elastic strains ~10⁻³.

    Returns:
    jacobians : dict  {(h,k,l): ndarray shape (2, 6)}
        Maps each hkl tuple to its 2×6 Jacobian matrix J where::

            [δxcam, δycam] ≈ J @ δε_voigt

        Spots for which the perturbed beam misses the detector for one or
        more components will have those columns set to zero.
"""
    ki_hat = KI_HAT / np.linalg.norm(KI_HAT)
    U = np.asarray(U, dtype=float)
    jacobians = {}

    for s in spots:
        if s.get("pix") is None:
            continue
        h, k, l = s["hkl"]
        G_cry = crystal.Q(h, k, l)
        pix0 = np.array(s["pix"], dtype=float)
        J = np.zeros((2, 6))

        for vi, (i, j) in enumerate(_VOIGT_IJ):
            # Symmetric strain perturbation tensor
            deps = np.zeros((3, 3))
            deps[i, j] += eps_step
            if i != j:
                deps[j, i] += eps_step  # symmetrise off-diagonal

            # Perturbed G in lab frame: G' = U @ (I + δε) @ G_cry
            G_lab_p = U @ (np.eye(3) + deps) @ G_cry

            # Re-apply Laue condition for perturbed G
            Gm2 = float(G_lab_p @ G_lab_p)
            kdG = float(ki_hat @ G_lab_p)
            if kdG >= 0 or Gm2 < 1e-30:
                continue
            lam_p = -4.0 * np.pi * kdG / Gm2
            km_p = 2.0 * np.pi / lam_p
            kf_p = ki_hat * km_p + G_lab_p
            kf_hat_p = kf_p / np.linalg.norm(kf_p)

            pix_p = camera.project(kf_hat_p)
            if pix_p is None:
                continue

            J[:, vi] = (np.array(pix_p) - pix0) / eps_step

        jacobians[(h, k, l)] = J

    return jacobians

submit_full_detector_image

submit_full_detector_image(base_dir, stack, camera, n_jobs=20, *, bin_px=8, n_energy=101, E_min_eV=E_MIN_eV, E_max_eV=E_MAX_eV, source='bending_magnet', source_kwargs=None, kb_params=BM32_KB, ki_hat=None, structure_model='coherent', darwin=False, exclude_layers=None, sigma_h_mrad=0.0, sigma_v_mrad=0.0, n_div=5, partition='all', time='04:00:00', mem='32G', cpus_per_task=1, python_bin='python', extra_sbatch=None)

Submit :func:simulate_full_detector_image to SLURM, split across n_jobs independent array jobs by detector row (row_start/row_end on the binned-row grid — see that function). Every pixel's Q(E) is independent of every other pixel, so this is embarrassingly parallel; splitting also caps the peak memory of the big (n_pixels * n_energy,) intermediate arrays each job has to hold, which a single unchunked call at high bin_px/n_energy can blow past easily.

Each job writes its own row-chunk to base_dir/chunks/chunk_XXXX.npz (no shared/concurrent file — safe with any number of simultaneously running jobs). Call :func:collect_full_detector_image once every job has finished to stitch the chunks into one HDF5 file.

Parameters:
  • base_dir (str) –

    Root processing directory. chunks/, slurm_logs/, and job_meta/ are created inside it.

  • stack (LayeredCrystal) –

    The layered structure — pickled once to job_meta/stack.pkl and shared by every worker.

  • camera (Camera) –

    Detector geometry.

  • n_jobs (int, default: 20 ) –

    Number of SLURM array jobs (row chunks). Default 20.

  • sigma_h_mrad, sigma_v_mrad, n_div –

    Forwarded verbatim to simulate_full_detector_image on every worker — same meaning/defaults as there.

  • partition, time, mem, cpus_per_task, python_bin, extra_sbatch –

    Standard SLURM parameters, same convention as GrainMap.submit_segmentation etc. python_bin should be an absolute interpreter path if you're not relying on conda activate inside the job (unreliable in non-interactive batch shells).

Returns:
  • –

    list of str: SLURM job IDs, one per row chunk.

Source code in src/nrxrdct/laue/simulation.py
def submit_full_detector_image(
    base_dir,
    stack,
    camera,
    n_jobs=20,
    *,
    bin_px=8,
    n_energy=101,
    E_min_eV=E_MIN_eV,
    E_max_eV=E_MAX_eV,
    source="bending_magnet",
    source_kwargs=None,
    kb_params=BM32_KB,
    ki_hat=None,
    structure_model="coherent",
    darwin=False,
    exclude_layers=None,
    sigma_h_mrad=0.0,
    sigma_v_mrad=0.0,
    n_div=5,
    partition="all",
    time="04:00:00",
    mem="32G",
    cpus_per_task=1,
    python_bin="python",
    extra_sbatch=None,
):
    """
    Submit :func:`simulate_full_detector_image` to SLURM, split across
    `n_jobs` independent array jobs by detector row (`row_start`/`row_end`
    on the binned-row grid — see that function). Every pixel's `Q(E)` is
    independent of every other pixel, so this is embarrassingly parallel;
    splitting also caps the peak memory of the big `(n_pixels * n_energy,)`
    intermediate arrays each job has to hold, which a single unchunked call
    at high `bin_px`/`n_energy` can blow past easily.

    Each job writes its own row-chunk to `base_dir/chunks/chunk_XXXX.npz`
    (no shared/concurrent file — safe with any number of simultaneously
    running jobs). Call :func:`collect_full_detector_image` once every job
    has finished to stitch the chunks into one HDF5 file.

    Args:
        base_dir (str): Root processing directory. `chunks/`, `slurm_logs/`,
            and `job_meta/` are created inside it.
        stack (LayeredCrystal): The layered structure — pickled once to
            `job_meta/stack.pkl` and shared by every worker.
        camera (Camera): Detector geometry.
        n_jobs (int): Number of SLURM array jobs (row chunks). Default `20`.
        bin_px, n_energy, E_min_eV, E_max_eV, source, source_kwargs,
        kb_params, ki_hat, structure_model, darwin, exclude_layers,
        sigma_h_mrad, sigma_v_mrad, n_div:
            Forwarded verbatim to `simulate_full_detector_image` on every
            worker — same meaning/defaults as there.
        partition, time, mem, cpus_per_task, python_bin, extra_sbatch:
            Standard SLURM parameters, same convention as
            `GrainMap.submit_segmentation` etc. `python_bin` should be an
            absolute interpreter path if you're not relying on `conda
            activate` inside the job (unreliable in non-interactive batch
            shells).

    Returns:
        list of str: SLURM job IDs, one per row chunk.
    """
    mem = str(mem)
    if mem[-1].upper() not in ("K", "M", "G", "T"):
        raise ValueError(
            f"mem={mem!r} has no unit suffix. SLURM's --mem defaults to "
            f"MEGABYTES when none is given, so mem=64 requests 64 MB (not "
            f"64 GB) and the job will likely be OOM-killed. Pass a string "
            f"with an explicit unit, e.g. mem='64G'."
        )

    dirs = {
        "chunks": os.path.join(base_dir, "chunks"),
        "slurm_logs": os.path.join(base_dir, "slurm_logs"),
        "job_meta": os.path.join(base_dir, "job_meta"),
    }
    for d in dirs.values():
        os.makedirs(d, exist_ok=True)

    stack_pkl = os.path.join(dirs["job_meta"], "stack.pkl")
    with open(stack_pkl, "wb") as fh:
        pickle.dump(stack, fh)

    n_rows_total = len(np.arange(bin_px // 2, camera.Nv, bin_px))
    if n_rows_total == 0:
        raise ValueError("camera.Nv too small for the given bin_px — no rows to simulate.")
    n_jobs = min(n_jobs, n_rows_total)
    row_chunks = [
        (int(c[0]), int(c[-1]) + 1)
        for c in np.array_split(np.arange(n_rows_total), n_jobs)
        if len(c) > 0
    ]

    meta = dict(
        stack_pkl=stack_pkl,
        camera=_camera_to_dict(camera),
        chunks_dir=dirs["chunks"],
        n_rows_total=n_rows_total,
        bin_px=bin_px,
        n_energy=n_energy,
        E_min_eV=E_min_eV,
        E_max_eV=E_max_eV,
        source=source,
        source_kwargs=source_kwargs,
        kb_params=kb_params,
        ki_hat=None if ki_hat is None else list(np.asarray(ki_hat, dtype=float)),
        structure_model=structure_model,
        darwin=darwin,
        exclude_layers=exclude_layers,
        sigma_h_mrad=sigma_h_mrad,
        sigma_v_mrad=sigma_v_mrad,
        n_div=n_div,
    )
    meta_path = os.path.join(dirs["job_meta"], "full_detector_image_meta.json")
    with open(meta_path, "w") as fh:
        json.dump(meta, fh, indent=2)

    job_ids = []
    for i, (row_start, row_end) in enumerate(row_chunks):
        wrap_cmd = (
            f"{python_bin} -m nrxrdct.laue.workers.slurm_full_detector_image_worker "
            f"--meta-json {meta_path} --chunk-index {i} "
            f"--row-start {row_start} --row-end {row_end}"
        )
        sbatch_args = [
            "sbatch",
            f"--job-name=fdi_{i:04d}",
            f"--partition={partition}",
            f"--time={time}",
            f"--mem={mem}",
            f"--cpus-per-task={cpus_per_task}",
            f"--output={os.path.join(dirs['slurm_logs'], f'fdi_{i:04d}_%j.out')}",
            f"--error={os.path.join(dirs['slurm_logs'], f'fdi_{i:04d}_%j.err')}",
        ]
        if extra_sbatch:
            for k, v in extra_sbatch.items():
                sbatch_args.append(f"--{k}={v}")
        sbatch_args += ["--wrap", wrap_cmd]

        result = subprocess.run(sbatch_args, capture_output=True, text=True)
        if result.returncode != 0:
            raise RuntimeError(f"sbatch failed for chunk {i}:\n{result.stderr}")
        job_ids.append(result.stdout.strip().split()[-1])

    print(
        f"submit_full_detector_image: {len(job_ids)} jobs, "
        f"{n_rows_total} rows total -> {dirs['chunks']}"
    )
    return job_ids

symmetry_equivalent_axes

symmetry_equivalent_axes(axis: ndarray, symmetry: str = 'cubic', *, atol: float = 1e-06) -> np.ndarray

Unique crystal-frame directions equivalent to axis under the point group.

Applies every proper rotation of the crystal's point group to axis and deduplicates the results, treating a direction and its negation as the same axis (a 180° rotation about v is identical to a 180° rotation about -v). Useful for enumerating twin-law variants: a {112}<111> BCC/B2 twin, for example, can occur about any of the 4 crystallographically equivalent <111> directions, and testing only [1, 1, 1] would miss the other 3.

Parameters:
  • axis ((3,) array-like) –

    A representative crystal-frame direction (e.g. [1, 1, 1]). Need not be a unit vector.

  • symmetry (str, default: 'cubic' ) –

    Crystal point-group symmetry — same options as :func:disorientation ('cubic', 'hexagonal', 'tetragonal', 'orthorhombic').

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

    Absolute tolerance used to deduplicate equivalent directions. Default 1e-6.

Returns:
  • axes( (M, 3) ndarray ) –

    Unique unit-vector directions, one row per symmetry-equivalent variant of axis.

Example::

# the 4 <111>-type axes for the BCC/B2 {112}<111> twin law
axes = symmetry_equivalent_axes([1, 1, 1], symmetry='cubic')
Source code in src/nrxrdct/laue/simulation.py
def symmetry_equivalent_axes(
    axis: "np.ndarray",
    symmetry: str = "cubic",
    *,
    atol: float = 1e-6,
) -> "np.ndarray":
    """
    Unique crystal-frame directions equivalent to *axis* under the point group.

    Applies every proper rotation of the crystal's point group to *axis* and
    deduplicates the results, treating a direction and its negation as the
    same axis (a 180° rotation about `v` is identical to a 180° rotation
    about `-v`).  Useful for enumerating twin-law variants: a {112}<111>
    BCC/B2 twin, for example, can occur about any of the 4 crystallographically
    equivalent <111> directions, and testing only `[1, 1, 1]` would miss the
    other 3.

    Args:
        axis ((3,) array-like): A representative crystal-frame direction
            (e.g. `[1, 1, 1]`).  Need not be a unit vector.
        symmetry (str): Crystal point-group symmetry — same options as
            :func:`disorientation` (`'cubic'`, `'hexagonal'`, `'tetragonal'`,
            `'orthorhombic'`).
        atol (float): Absolute tolerance used to deduplicate equivalent
            directions.  Default `1e-6`.

    Returns:
        axes ((M, 3) ndarray): Unique unit-vector directions, one row per
            symmetry-equivalent variant of *axis*.

    Example::

        # the 4 <111>-type axes for the BCC/B2 {112}<111> twin law
        axes = symmetry_equivalent_axes([1, 1, 1], symmetry='cubic')
    """
    ops = _symmetry_ops_np(symmetry)                     # (N, 3, 3)
    axis = np.asarray(axis, dtype=float)
    axis = axis / np.linalg.norm(axis)

    equiv = ops @ axis                                   # (N, 3)
    # Canonicalise sign so v and -v collapse to the same row: flip so the
    # first component with |component| > atol is positive.
    for i, v in enumerate(equiv):
        j = int(np.argmax(np.abs(v) > atol))
        if v[j] < 0:
            equiv[i] = -v

    unique: list = []
    for v in equiv:
        if not any(np.allclose(v, u, atol=atol) for u in unique):
            unique.append(v)
    return np.array(unique)