camera

nrxrdct.laue.camera

CalibrationResult dataclass

Returned by :meth:Camera.fit_calibration.

Source code in src/nrxrdct/laue/camera.py
@dataclass
class CalibrationResult:
    """Returned by :meth:`Camera.fit_calibration`."""

    camera: "Camera"
    U: np.ndarray
    rms_px: float
    n_matched: int
    n_obs: int
    n_sim: int
    fit_params: tuple
    success: bool
    message: str

    def __repr__(self):
        return (
            f"CalibrationResult(rms={self.rms_px:.2f} px, "
            f"matched={self.n_matched}/{self.n_obs} obs / {self.n_sim} sim, "
            f"success={self.success})"
        )

    def plot(
        self,
        crystal,
        peaklist: np.ndarray,
        image: np.ndarray | None = None,
        max_match_px: float = 20.0,
        space: str = "detector",
        E_min_eV: float = 5_000.0,
        E_max_eV: float = 27_000.0,
        source: str = "bending_magnet",
        source_kwargs: dict | None = None,
        f2_thresh: float = 0.0,
        top_n_sim: int | None = None,
        figsize: tuple = (14, 5),
    ):
        """
        Plot the calibration result: observed vs simulated spot positions.

        Args:
            crystal (Crystal): calibration standard used during fitting.
            peaklist ((N, ≥2) array): peak list from
                :func:`~nrxrdct.laue.segmentation.convert_spotsfile2peaklist`.
                Columns 0 and 1 are used as (xcam, ycam) pixel positions.
            image ((Nv, Nh) array or None): optional detector image
                (`'detector'` space only; ignored for `'angular'`).
            max_match_px (float): pixel-space match radius for spot pairing.
            space (`'detector'` or `'angular'`): coordinate frame for
                the main panel.  `'angular'` plots 2θ (x) vs χ (y) in
                degrees.  Matching is always done in detector (pixel)
                space; the histogram shows pixel distances in detector
                mode and Euclidean (2θ, χ) distances in angular mode.
            f2_thresh (float): minimum |F|² to include a reflection (0 = all).
            top_n_sim (int or None): restrict to the N brightest simulated spots.
            figsize ((w, h)): figure size in inches.

        Returns:
            fig, (ax_det, ax_info, ax_hist)
"""
        import matplotlib.colors as mcolors
        import matplotlib.gridspec as gridspec
        import matplotlib.pyplot as plt

        from .simulation import simulate_laue
        from .fitting import _match_spots

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

        _BG   = "#080c14"
        _BG2  = "#0d1220"
        _FG   = "#ccccee"
        _GRAY = "#4a5070"
        _OBS  = "#ffffff"
        _SIM  = "#ff6b35"

        cam    = self.camera
        obs_xy = np.asarray(peaklist, dtype=float)[:, :2]
        src_kw = source_kwargs or {}

        # ── simulate with the fitted camera + U ──────────────────────────────
        spots = simulate_laue(
            crystal, self.U, cam,
            E_min=E_min_eV, E_max=E_max_eV,
            source=source, source_kwargs=src_kw,
            f2_thresh=f2_thresh,
        )

        # Collect on-detector spots keeping pixel, angular, and intensity aligned
        _on_det = [
            (s["pix"], s.get("tth", np.nan), s.get("chi", np.nan), s.get("I_raw", 1.0))
            for s in spots if s.get("pix") is not None
        ]
        if top_n_sim is not None and len(_on_det) > top_n_sim:
            _on_det.sort(key=lambda t: -t[3])
            _on_det = _on_det[:top_n_sim]

        if _on_det:
            sim_xy  = np.array([t[0] for t in _on_det], dtype=float)
            tth_sim = np.array([t[1] for t in _on_det], dtype=float)
            chi_sim = np.array([t[2] for t in _on_det], dtype=float)
        else:
            sim_xy  = np.empty((0, 2), dtype=float)
            tth_sim = np.empty(0, dtype=float)
            chi_sim = np.empty(0, dtype=float)

        # ── match in detector (pixel) space ───────────────────────────────────
        row_ind, col_ind, dist_px = _match_spots(obs_xy, sim_xy, max_match_px)
        ok_mask   = dist_px < max_match_px
        n_matched = int(ok_mask.sum())
        rate      = n_matched / max(len(obs_xy), 1)

        # ── angular coords for observed spots ─────────────────────────────────
        uf_obs  = cam.pixel_to_kf(obs_xy[:, 0], obs_xy[:, 1])
        tth_obs = np.degrees(np.arccos(np.clip(uf_obs[:, 0], -1.0, 1.0)))
        chi_obs = np.degrees(np.arctan2(uf_obs[:, 1], uf_obs[:, 2] + 1e-17))

        # ── distances for histogram ───────────────────────────────────────────
        if space == "detector":
            dists_ok  = dist_px[ok_mask]
            dist_unit = "px"
        else:
            ang_dists = np.sqrt(
                (tth_obs[row_ind] - tth_sim[col_ind]) ** 2
                + (chi_obs[row_ind] - chi_sim[col_ind]) ** 2
            )
            dists_ok  = ang_dists[ok_mask]
            dist_unit = "°"

        mean_d = float(np.mean(dists_ok))               if n_matched > 0 else float("nan")
        rms_d  = float(np.sqrt(np.mean(dists_ok ** 2))) if n_matched > 0 else float("nan")
        mean_s = f"{mean_d:.3f} {dist_unit}" if np.isfinite(mean_d) else "—"
        rms_s  = f"{rms_d:.3f} {dist_unit}"  if np.isfinite(rms_d)  else "—"

        # ── figure layout ─────────────────────────────────────────────────────
        with plt.ioff():
            fig = plt.figure(figsize=figsize, facecolor=_BG)

        gs = gridspec.GridSpec(
            1, 2, figure=fig,
            left=0.06, right=0.98, bottom=0.08, top=0.93,
            wspace=0.06, width_ratios=[2.5, 1.0],
        )
        gs_r = gridspec.GridSpecFromSubplotSpec(
            2, 1, subplot_spec=gs[1], hspace=0.45, height_ratios=[1, 1],
        )
        ax_det  = fig.add_subplot(gs[0])
        ax_info = fig.add_subplot(gs_r[0])
        ax_hist = fig.add_subplot(gs_r[1])

        for ax in (ax_det, ax_info, ax_hist):
            ax.set_facecolor(_BG2)
            ax.tick_params(colors=_GRAY, labelsize=7)
            for sp in ax.spines.values():
                sp.set_edgecolor(_GRAY)

        # ── choose display coordinates ────────────────────────────────────────
        if space == "detector":
            obs_plot = obs_xy
            sim_plot = sim_xy
            ax_det.set_xlim(0, cam.Nh)
            ax_det.set_ylim(cam.Nv, 0)
            ax_det.set_aspect("equal")
            ax_det.set_xlabel("xcam  (px)", color=_FG, fontsize=8)
            ax_det.set_ylabel("ycam  (px)", color=_FG, fontsize=8)
            if image is not None:
                img = np.asarray(image, dtype=float)
                vmax = np.percentile(img[img > 0], 99) if img.max() > 0 else 1.0
                ax_det.imshow(
                    np.log1p(img / vmax * 1000),
                    origin="upper", extent=[0, cam.Nh, cam.Nv, 0],
                    cmap="inferno", aspect="auto", alpha=0.55, zorder=0,
                )
            else:
                ax_det.add_patch(plt.Rectangle(
                    (0, 0), cam.Nh, cam.Nv,
                    linewidth=0.8, edgecolor=_GRAY, facecolor="none", zorder=0,
                ))
        else:
            obs_plot = np.column_stack([tth_obs, chi_obs])
            sim_plot = (np.column_stack([tth_sim, chi_sim])
                        if len(tth_sim) else np.empty((0, 2)))
            ax_det.set_aspect("auto")
            ax_det.set_xlabel("2θ  (°)", color=_FG, fontsize=8)
            ax_det.set_ylabel("χ  (°)", color=_FG, fontsize=8)
            ax_det.grid(True, ls=":", lw=0.35, color="#181e2e", zorder=0)

        ax_det.set_title(
            f"Calibration result   ○ observed   ◆ fitted   — matched   "
            f"mean={mean_s}   rms={rms_s}",
            color=_FG, fontsize=9, pad=6,
        )
        ax_det.scatter(
            obs_plot[:, 0], obs_plot[:, 1],
            s=45, c="none", edgecolors=_OBS, linewidths=0.9,
            zorder=4, label=f"observed ({len(obs_xy)})",
        )
        if len(sim_plot):
            ax_det.scatter(
                sim_plot[:, 0], sim_plot[:, 1],
                s=28, c=_SIM, marker="D", linewidths=0,
                zorder=5, label=f"simulated ({len(sim_xy)})",
            )

        # Lines coloured green→red by pixel distance (calibration quality)
        cmap_match = plt.get_cmap("RdYlGn_r")
        cnorm = mcolors.Normalize(vmin=0, vmax=max_match_px)
        for r, c, d, ok in zip(row_ind, col_ind, dist_px, ok_mask):
            if ok:
                ax_det.plot(
                    [obs_plot[r, 0], sim_plot[c, 0]],
                    [obs_plot[r, 1], sim_plot[c, 1]],
                    color=cmap_match(cnorm(d)), lw=0.8, alpha=0.7, zorder=3,
                )
        ax_det.legend(loc="upper right", fontsize=7,
                      facecolor=_BG2, edgecolor=_GRAY, labelcolor=_FG)

        # ── info panel ────────────────────────────────────────────────────────
        ax_info.set_axis_off()
        status = "OK" if self.success else "FAILED"
        ax_info.text(
            0.06, 0.97,
            f"Fit  [{status}]\n"
            f"{'─' * 22}\n"
            f"  matched : {n_matched} / {len(obs_xy)}\n"
            f"  rate    : {rate:.0%}\n"
            f"  mean    : {mean_s}\n"
            f"  rms     : {rms_s}\n"
            f"\n"
            f"Camera\n"
            f"{'─' * 22}\n"
            f"  dd   ={cam.dd:9.4f} mm\n"
            f"  xcen ={cam.xcen:9.2f} px\n"
            f"  ycen ={cam.ycen:9.2f} px\n"
            f"  xbet ={cam.xbet:9.4f} °\n"
            f"  xgam ={cam.xgam:9.4f} °\n",
            transform=ax_info.transAxes,
            color=_FG, fontsize=8, va="top", family="monospace",
            linespacing=1.5,
        )

        # ── histogram panel ───────────────────────────────────────────────────
        ax_hist.set_xlabel(f"distance  ({dist_unit})", color=_FG, fontsize=8)
        ax_hist.set_ylabel("count", color=_FG, fontsize=8)
        ax_hist.set_title("Match distances", color=_FG, fontsize=9, pad=4)

        if n_matched > 0:
            bins = np.linspace(0, dists_ok.max() * 1.05, min(30, n_matched + 1))
            ax_hist.hist(dists_ok, bins=bins, color=_SIM, alpha=0.85,
                         edgecolor=_BG, linewidth=0.4)
            ax_hist.axvline(mean_d, color="#44dd66", lw=1.4, ls="--",
                            label=f"mean {mean_s}")
            ax_hist.axvline(rms_d, color="#ffcc44", lw=1.4, ls=":",
                            label=f"rms  {rms_s}")
            ax_hist.legend(fontsize=7, facecolor=_BG2, edgecolor=_GRAY,
                           labelcolor=_FG)

        plt.show()
        return fig, (ax_det, ax_info, ax_hist)

plot

plot(crystal, peaklist: ndarray, image: ndarray | None = None, max_match_px: float = 20.0, space: str = 'detector', E_min_eV: float = 5000.0, E_max_eV: float = 27000.0, source: str = 'bending_magnet', source_kwargs: dict | None = None, f2_thresh: float = 0.0, top_n_sim: int | None = None, figsize: tuple = (14, 5))

Plot the calibration result: observed vs simulated spot positions.

Parameters:
  • crystal (Crystal) –

    calibration standard used during fitting.

  • peaklist ((N, ≥2) array) –

    peak list from :func:~nrxrdct.laue.segmentation.convert_spotsfile2peaklist. Columns 0 and 1 are used as (xcam, ycam) pixel positions.

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

    optional detector image ('detector' space only; ignored for 'angular').

  • max_match_px (float, default: 20.0 ) –

    pixel-space match radius for spot pairing.

  • space (`'detector'` or `'angular'`, default: 'detector' ) –

    coordinate frame for the main panel. 'angular' plots 2θ (x) vs χ (y) in degrees. Matching is always done in detector (pixel) space; the histogram shows pixel distances in detector mode and Euclidean (2θ, χ) distances in angular mode.

  • f2_thresh (float, default: 0.0 ) –

    minimum |F|² to include a reflection (0 = all).

  • top_n_sim (int or None, default: None ) –

    restrict to the N brightest simulated spots.

  • figsize ((w, h), default: (14, 5) ) –

    figure size in inches.

Returns:
  • –

    fig, (ax_det, ax_info, ax_hist)

Source code in src/nrxrdct/laue/camera.py
    def plot(
        self,
        crystal,
        peaklist: np.ndarray,
        image: np.ndarray | None = None,
        max_match_px: float = 20.0,
        space: str = "detector",
        E_min_eV: float = 5_000.0,
        E_max_eV: float = 27_000.0,
        source: str = "bending_magnet",
        source_kwargs: dict | None = None,
        f2_thresh: float = 0.0,
        top_n_sim: int | None = None,
        figsize: tuple = (14, 5),
    ):
        """
        Plot the calibration result: observed vs simulated spot positions.

        Args:
            crystal (Crystal): calibration standard used during fitting.
            peaklist ((N, ≥2) array): peak list from
                :func:`~nrxrdct.laue.segmentation.convert_spotsfile2peaklist`.
                Columns 0 and 1 are used as (xcam, ycam) pixel positions.
            image ((Nv, Nh) array or None): optional detector image
                (`'detector'` space only; ignored for `'angular'`).
            max_match_px (float): pixel-space match radius for spot pairing.
            space (`'detector'` or `'angular'`): coordinate frame for
                the main panel.  `'angular'` plots 2θ (x) vs χ (y) in
                degrees.  Matching is always done in detector (pixel)
                space; the histogram shows pixel distances in detector
                mode and Euclidean (2θ, χ) distances in angular mode.
            f2_thresh (float): minimum |F|² to include a reflection (0 = all).
            top_n_sim (int or None): restrict to the N brightest simulated spots.
            figsize ((w, h)): figure size in inches.

        Returns:
            fig, (ax_det, ax_info, ax_hist)
"""
        import matplotlib.colors as mcolors
        import matplotlib.gridspec as gridspec
        import matplotlib.pyplot as plt

        from .simulation import simulate_laue
        from .fitting import _match_spots

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

        _BG   = "#080c14"
        _BG2  = "#0d1220"
        _FG   = "#ccccee"
        _GRAY = "#4a5070"
        _OBS  = "#ffffff"
        _SIM  = "#ff6b35"

        cam    = self.camera
        obs_xy = np.asarray(peaklist, dtype=float)[:, :2]
        src_kw = source_kwargs or {}

        # ── simulate with the fitted camera + U ──────────────────────────────
        spots = simulate_laue(
            crystal, self.U, cam,
            E_min=E_min_eV, E_max=E_max_eV,
            source=source, source_kwargs=src_kw,
            f2_thresh=f2_thresh,
        )

        # Collect on-detector spots keeping pixel, angular, and intensity aligned
        _on_det = [
            (s["pix"], s.get("tth", np.nan), s.get("chi", np.nan), s.get("I_raw", 1.0))
            for s in spots if s.get("pix") is not None
        ]
        if top_n_sim is not None and len(_on_det) > top_n_sim:
            _on_det.sort(key=lambda t: -t[3])
            _on_det = _on_det[:top_n_sim]

        if _on_det:
            sim_xy  = np.array([t[0] for t in _on_det], dtype=float)
            tth_sim = np.array([t[1] for t in _on_det], dtype=float)
            chi_sim = np.array([t[2] for t in _on_det], dtype=float)
        else:
            sim_xy  = np.empty((0, 2), dtype=float)
            tth_sim = np.empty(0, dtype=float)
            chi_sim = np.empty(0, dtype=float)

        # ── match in detector (pixel) space ───────────────────────────────────
        row_ind, col_ind, dist_px = _match_spots(obs_xy, sim_xy, max_match_px)
        ok_mask   = dist_px < max_match_px
        n_matched = int(ok_mask.sum())
        rate      = n_matched / max(len(obs_xy), 1)

        # ── angular coords for observed spots ─────────────────────────────────
        uf_obs  = cam.pixel_to_kf(obs_xy[:, 0], obs_xy[:, 1])
        tth_obs = np.degrees(np.arccos(np.clip(uf_obs[:, 0], -1.0, 1.0)))
        chi_obs = np.degrees(np.arctan2(uf_obs[:, 1], uf_obs[:, 2] + 1e-17))

        # ── distances for histogram ───────────────────────────────────────────
        if space == "detector":
            dists_ok  = dist_px[ok_mask]
            dist_unit = "px"
        else:
            ang_dists = np.sqrt(
                (tth_obs[row_ind] - tth_sim[col_ind]) ** 2
                + (chi_obs[row_ind] - chi_sim[col_ind]) ** 2
            )
            dists_ok  = ang_dists[ok_mask]
            dist_unit = "°"

        mean_d = float(np.mean(dists_ok))               if n_matched > 0 else float("nan")
        rms_d  = float(np.sqrt(np.mean(dists_ok ** 2))) if n_matched > 0 else float("nan")
        mean_s = f"{mean_d:.3f} {dist_unit}" if np.isfinite(mean_d) else "—"
        rms_s  = f"{rms_d:.3f} {dist_unit}"  if np.isfinite(rms_d)  else "—"

        # ── figure layout ─────────────────────────────────────────────────────
        with plt.ioff():
            fig = plt.figure(figsize=figsize, facecolor=_BG)

        gs = gridspec.GridSpec(
            1, 2, figure=fig,
            left=0.06, right=0.98, bottom=0.08, top=0.93,
            wspace=0.06, width_ratios=[2.5, 1.0],
        )
        gs_r = gridspec.GridSpecFromSubplotSpec(
            2, 1, subplot_spec=gs[1], hspace=0.45, height_ratios=[1, 1],
        )
        ax_det  = fig.add_subplot(gs[0])
        ax_info = fig.add_subplot(gs_r[0])
        ax_hist = fig.add_subplot(gs_r[1])

        for ax in (ax_det, ax_info, ax_hist):
            ax.set_facecolor(_BG2)
            ax.tick_params(colors=_GRAY, labelsize=7)
            for sp in ax.spines.values():
                sp.set_edgecolor(_GRAY)

        # ── choose display coordinates ────────────────────────────────────────
        if space == "detector":
            obs_plot = obs_xy
            sim_plot = sim_xy
            ax_det.set_xlim(0, cam.Nh)
            ax_det.set_ylim(cam.Nv, 0)
            ax_det.set_aspect("equal")
            ax_det.set_xlabel("xcam  (px)", color=_FG, fontsize=8)
            ax_det.set_ylabel("ycam  (px)", color=_FG, fontsize=8)
            if image is not None:
                img = np.asarray(image, dtype=float)
                vmax = np.percentile(img[img > 0], 99) if img.max() > 0 else 1.0
                ax_det.imshow(
                    np.log1p(img / vmax * 1000),
                    origin="upper", extent=[0, cam.Nh, cam.Nv, 0],
                    cmap="inferno", aspect="auto", alpha=0.55, zorder=0,
                )
            else:
                ax_det.add_patch(plt.Rectangle(
                    (0, 0), cam.Nh, cam.Nv,
                    linewidth=0.8, edgecolor=_GRAY, facecolor="none", zorder=0,
                ))
        else:
            obs_plot = np.column_stack([tth_obs, chi_obs])
            sim_plot = (np.column_stack([tth_sim, chi_sim])
                        if len(tth_sim) else np.empty((0, 2)))
            ax_det.set_aspect("auto")
            ax_det.set_xlabel("2θ  (°)", color=_FG, fontsize=8)
            ax_det.set_ylabel("χ  (°)", color=_FG, fontsize=8)
            ax_det.grid(True, ls=":", lw=0.35, color="#181e2e", zorder=0)

        ax_det.set_title(
            f"Calibration result   ○ observed   ◆ fitted   — matched   "
            f"mean={mean_s}   rms={rms_s}",
            color=_FG, fontsize=9, pad=6,
        )
        ax_det.scatter(
            obs_plot[:, 0], obs_plot[:, 1],
            s=45, c="none", edgecolors=_OBS, linewidths=0.9,
            zorder=4, label=f"observed ({len(obs_xy)})",
        )
        if len(sim_plot):
            ax_det.scatter(
                sim_plot[:, 0], sim_plot[:, 1],
                s=28, c=_SIM, marker="D", linewidths=0,
                zorder=5, label=f"simulated ({len(sim_xy)})",
            )

        # Lines coloured green→red by pixel distance (calibration quality)
        cmap_match = plt.get_cmap("RdYlGn_r")
        cnorm = mcolors.Normalize(vmin=0, vmax=max_match_px)
        for r, c, d, ok in zip(row_ind, col_ind, dist_px, ok_mask):
            if ok:
                ax_det.plot(
                    [obs_plot[r, 0], sim_plot[c, 0]],
                    [obs_plot[r, 1], sim_plot[c, 1]],
                    color=cmap_match(cnorm(d)), lw=0.8, alpha=0.7, zorder=3,
                )
        ax_det.legend(loc="upper right", fontsize=7,
                      facecolor=_BG2, edgecolor=_GRAY, labelcolor=_FG)

        # ── info panel ────────────────────────────────────────────────────────
        ax_info.set_axis_off()
        status = "OK" if self.success else "FAILED"
        ax_info.text(
            0.06, 0.97,
            f"Fit  [{status}]\n"
            f"{'─' * 22}\n"
            f"  matched : {n_matched} / {len(obs_xy)}\n"
            f"  rate    : {rate:.0%}\n"
            f"  mean    : {mean_s}\n"
            f"  rms     : {rms_s}\n"
            f"\n"
            f"Camera\n"
            f"{'─' * 22}\n"
            f"  dd   ={cam.dd:9.4f} mm\n"
            f"  xcen ={cam.xcen:9.2f} px\n"
            f"  ycen ={cam.ycen:9.2f} px\n"
            f"  xbet ={cam.xbet:9.4f} °\n"
            f"  xgam ={cam.xgam:9.4f} °\n",
            transform=ax_info.transAxes,
            color=_FG, fontsize=8, va="top", family="monospace",
            linespacing=1.5,
        )

        # ── histogram panel ───────────────────────────────────────────────────
        ax_hist.set_xlabel(f"distance  ({dist_unit})", color=_FG, fontsize=8)
        ax_hist.set_ylabel("count", color=_FG, fontsize=8)
        ax_hist.set_title("Match distances", color=_FG, fontsize=9, pad=4)

        if n_matched > 0:
            bins = np.linspace(0, dists_ok.max() * 1.05, min(30, n_matched + 1))
            ax_hist.hist(dists_ok, bins=bins, color=_SIM, alpha=0.85,
                         edgecolor=_BG, linewidth=0.4)
            ax_hist.axvline(mean_d, color="#44dd66", lw=1.4, ls="--",
                            label=f"mean {mean_s}")
            ax_hist.axvline(rms_d, color="#ffcc44", lw=1.4, ls=":",
                            label=f"rms  {rms_s}")
            ax_hist.legend(fontsize=7, facecolor=_BG2, edgecolor=_GRAY,
                           labelcolor=_FG)

        plt.show()
        return fig, (ax_det, ax_info, ax_hist)

Camera

Pixelated area detector fully compatible with LaueTools calibration files.

Public frame convention (LT frame) All public methods (kf_to_pixel, pixel_to_kf, project) use the canonical LaueTools LT frame:

x  : along incident beam  (ki direction)
z  : vertical up
y  : horizontal (= z ^ x, towards the wall)

Internally the camera geometry is computed in the LT2 frame (y // beam), which is what LaueGeometry.py uses. The LT ↔ LT2 conversion is handled transparently inside each method:

LT → LT2 :  x_LT2 = −y_LT,   y_LT2 =  x_LT,  z_LT2 = z_LT
LT2 → LT :  x_LT  =  y_LT2,  y_LT  = −x_LT2, z_LT  = z_LT2

Calibration parameters (CCDCalibParameters = [dd, xcen, ycen, xbet, xgam]) dd : distance sample → detector reference point O (mm) xcen : pixel X of point O (normal-incidence / beam-footprint pixel) ycen : pixel Y of point O xbet : angle (°) between the vector IO and the vertical z axis xbet ≈ 0 → camera directly above sample (Z>0 geometry, 2θ ~ 90°) xbet ≈ 90 → transmission forward camera xgam : in-plane rotation (°) of the CCD pixel axes around the IO direction

geometry label used by LaueTools

'Z>0' top/side reflection (most common, xbet small) 'X>0' transmission (forward) 'X<0' back-reflection

Pixel convention (identical to LaueTools) (xcam=0, ycam=0) : top-left corner of the array xcam increases to the right (columns) ycam increases downward (rows) (xcen, ycen) : sub-pixel reference point where the detector normal intersects the pixel array.

The IO vector and detector normal (in LT2 frame) For Z>0 geometry: beta = pi/2 - xbet * pi/180 IO = dd * [0, cos(beta), sin(beta)] = dd * [0, sin(xbet), cos(xbet)] normal = IO / |IO|

The two key public functions

kf_to_pixel : uflab (N×3, LT) → (xcam, ycam) [LaueTools: calc_xycam] pixel_to_kf : (xcam, ycam) → uflab (N×3, LT) [LaueTools: calc_uflab]

Source code in src/nrxrdct/laue/camera.py
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
class Camera:
    """
    Pixelated area detector fully compatible with LaueTools calibration files.

    **Public frame convention (LT frame)**
    All public methods (kf_to_pixel, pixel_to_kf, project) use the canonical
    LaueTools LT frame:

        x  : along incident beam  (ki direction)
        z  : vertical up
        y  : horizontal (= z ^ x, towards the wall)

    Internally the camera geometry is computed in the LT2 frame (y // beam),
    which is what LaueGeometry.py uses.  The LT ↔ LT2 conversion is handled
    transparently inside each method:

        LT → LT2 :  x_LT2 = −y_LT,   y_LT2 =  x_LT,  z_LT2 = z_LT
        LT2 → LT :  x_LT  =  y_LT2,  y_LT  = −x_LT2, z_LT  = z_LT2

    **Calibration parameters  (CCDCalibParameters = [dd, xcen, ycen, xbet, xgam])**
    dd   : distance sample → detector reference point O  (mm)
    xcen : pixel X of point O  (normal-incidence / beam-footprint pixel)
    ycen : pixel Y of point O
    xbet : angle (°) between the vector IO and the vertical z axis
             xbet ≈ 0  →  camera directly above sample  (Z>0 geometry, 2θ ~ 90°)
             xbet ≈ 90 →  transmission forward camera
    xgam : in-plane rotation (°) of the CCD pixel axes around the IO direction

    kf_direction : geometry label used by LaueTools
        'Z>0'  top/side reflection  (most common, xbet small)
        'X>0'  transmission (forward)
        'X<0'  back-reflection

    **Pixel convention  (identical to LaueTools)**
    (xcam=0, ycam=0) : top-left corner of the array
    xcam increases to the right (columns)
    ycam increases downward    (rows)
    (xcen, ycen) : sub-pixel reference point where the detector normal
                   intersects the pixel array.

    **The IO vector and detector normal  (in LT2 frame)**
    For Z>0 geometry:
        beta  = pi/2 - xbet * pi/180
        IO    = dd * [0,  cos(beta),  sin(beta)]
              = dd * [0,  sin(xbet),  cos(xbet)]
        normal = IO / |IO|

    The two key public functions:
        kf_to_pixel  : uflab (N×3, LT)  →  (xcam, ycam)   [LaueTools: calc_xycam]
        pixel_to_kf  : (xcam, ycam)     →  uflab (N×3, LT) [LaueTools: calc_uflab]
"""

    def __init__(
        self,
        dd=DD,
        xcen=XCEN,
        ycen=YCEN,
        xbet=XBET,
        xgam=XGAM,
        pixelsize=PIXEL_SIZE_MM,
        n_pix_h=N_PIX_H,
        n_pix_v=N_PIX_V,
        kf_direction=KF_DIRECTION,
    ):

        self.dd = float(dd)
        self.xcen = float(xcen)
        self.ycen = float(ycen)
        self.xbet = float(xbet)
        self.xgam = float(xgam)
        self.pixel_mm = float(pixelsize)
        self.Nh = int(n_pix_h)
        self.Nv = int(n_pix_v)
        self.kf_direction = kf_direction

        self._build_geometry()

    # ── internal geometry ──────────────────────────────────────────────────────

    def _build_geometry(self):
        DEG = np.pi / 180.0
        xbet = self.xbet
        xgam = self.xgam
        dd = self.dd

        if self.kf_direction in ("Z>0", "Y>0", "Y<0"):
            # Top / side reflection geometry (default)
            # beta = pi/2 - xbet*DEG  (angle between IO and y axis)
            self._cosbeta = np.cos(np.pi / 2 - xbet * DEG)  # = sin(xbet)
            self._sinbeta = np.sin(np.pi / 2 - xbet * DEG)  # = cos(xbet)
            # IO vector: points from sample I to detector reference point O
            self.IOlab = dd * np.array([0.0, self._cosbeta, self._sinbeta])

        elif self.kf_direction == "X>0":
            # Transmission geometry
            self._cosbeta = np.cos(-xbet * DEG)
            self._sinbeta = np.sin(-xbet * DEG)
            self.IOlab = dd * np.array([0.0, self._cosbeta, self._sinbeta])

        elif self.kf_direction == "X<0":
            # Back-reflection geometry
            self._cosbeta = np.cos(-xbet * DEG)
            self._sinbeta = np.sin(-xbet * DEG)
            self.IOlab = dd * np.array([0.0, -self._cosbeta, self._sinbeta])

        else:
            raise ValueError(f"Unknown kf_direction: {self.kf_direction!r}")

        # Detector unit normal
        self.normal = self.IOlab / np.linalg.norm(self.IOlab)
        # Precompute gam rotation coefficients (used in both directions)
        self._cosgam = np.cos(-xgam * DEG)
        self._singam = np.sin(-xgam * DEG)
        # Physical size
        self.size_h_mm = self.Nh * self.pixel_mm
        self.size_v_mm = self.Nv * self.pixel_mm

    # ── forward projection: kf unit vector → pixel ────────────────────────────

    def kf_to_pixel(self, uflab_arr):
        """
        Map scattered unit vectors to pixel coordinates.
        Implements LaueTools calc_xycam() for Z>0 geometry.

        Args:
            uflab_arr ((N, 3) array of unit scattered vectors in LT frame (x // beam)):

        Returns:
            xcam, ycam ((N,) arrays of pixel coordinates (float, sub-pixel precision)): Returns NaN for beams that miss the detector or go backward.
"""
        # Convert LT -> LT2:  x_LT2 = -y_LT,  y_LT2 = x_LT,  z_LT2 = z_LT
        uf_lt = np.atleast_2d(np.array(uflab_arr, dtype=float))
        norms = np.linalg.norm(uf_lt, axis=1, keepdims=True)
        uf_lt = uf_lt / norms
        uf = np.column_stack([-uf_lt[:, 1], uf_lt[:, 0], uf_lt[:, 2]])

        scal = uf @ self.normal  # cos(angle between kf and detector normal)
        valid = scal > 1e-8
        normeIM = np.where(valid, self.dd / scal, np.nan)

        IMlab = uf * normeIM[:, None]
        OMlab = IMlab - self.IOlab

        xca0 = OMlab[:, 0]
        if abs(self._sinbeta) > 1e-8:
            yca0 = OMlab[:, 1] / self._sinbeta
        else:
            yca0 = -OMlab[:, 2] / self._cosbeta

        xcam1 = self._cosgam * xca0 + self._singam * yca0
        ycam1 = -self._singam * xca0 + self._cosgam * yca0

        xcam = self.xcen + xcam1 / self.pixel_mm
        ycam = self.ycen + ycam1 / self.pixel_mm

        xcam[~valid] = np.nan
        ycam[~valid] = np.nan
        return xcam, ycam

    # ── inverse projection: pixel → kf unit vector ────────────────────────────

    def pixel_to_kf(self, xcam_arr, ycam_arr):
        """
        Map pixel coordinates to scattered unit vectors.
        Implements LaueTools calc_uflab() for Z>0 geometry.

        Args:
            xcam_arr, ycam_arr (array-like of pixel coordinates):

        Returns:
            uflab ((N, 3) unit scattered vectors in LT frame): (x // ki)
"""
        xcam1 = (np.asarray(xcam_arr, float) - self.xcen) * self.pixel_mm
        ycam1 = (np.asarray(ycam_arr, float) - self.ycen) * self.pixel_mm

        xca0 = self._cosgam * xcam1 - self._singam * ycam1
        yca0 = self._singam * xcam1 + self._cosgam * ycam1

        xO, yO, zO = self.IOlab
        xM = xO + xca0
        yM = yO + yca0 * self._sinbeta
        zM = zO - yca0 * self._cosbeta

        nIM = np.sqrt(xM**2 + yM**2 + zM**2)
        # Geometry is in LT2 frame (y // beam); convert to LT frame (x // beam):
        # x_LT = y_LT2,  y_LT = -x_LT2,  z_LT = z_LT2
        uflab_lt2 = np.array([xM, yM, zM]).T / nIM[:, None]
        uflab = np.column_stack([uflab_lt2[:, 1], -uflab_lt2[:, 0], uflab_lt2[:, 2]])
        return uflab

    # ── single-spot projection for simulation ────────────────────────────────

    def project(self, kf_hat, source_depth_mm: float = 0.0):
        """
        Project one scattered beam direction (in LT frame, x // beam) onto
        the detector.  Returns (xcam, ycam) in pixels, or None if beam misses.

        Args:
            kf_hat: Unit scattered-beam vector in the LT frame.
            source_depth_mm: Depth of the scattering centre below the surface
                along the incident beam direction (mm).  Non-zero for layers
                buried beneath the sample surface — corrects the parallax
                shift that occurs when the scattering point is not at the
                nominal sample position.  Default ``0.0`` (surface).
"""
        # Convert LT -> LT2 for camera geometry
        kf_lt = np.array(kf_hat, dtype=float)
        kf_lt = kf_lt / np.linalg.norm(kf_lt)
        kf = np.array([-kf_lt[1], kf_lt[0], kf_lt[2]])  # LT2 frame
        scal = float(np.dot(kf, self.normal))
        if scal < 1e-8:
            return None
        # Depth correction: source displaced to (0, depth_mm, 0) in LT2 frame
        # (beam is along y in LT2).  normeIM = (dd − s·n̂) / scal.
        s_dot_n  = source_depth_mm * float(self.normal[1])
        normeIM  = (self.dd - s_dot_n) / scal
        IM = np.array([0.0, source_depth_mm, 0.0]) + kf * normeIM
        OM = IM - self.IOlab
        xca0 = OM[0]
        yca0 = (
            OM[1] / self._sinbeta
            if abs(self._sinbeta) > 1e-8
            else -OM[2] / self._cosbeta
        )
        xcam1 = self._cosgam * xca0 + self._singam * yca0
        ycam1 = -self._singam * xca0 + self._cosgam * yca0
        xcam = self.xcen + xcam1 / self.pixel_mm
        ycam = self.ycen + ycam1 / self.pixel_mm
        if 0 <= xcam < self.Nh and 0 <= ycam < self.Nv:
            return float(xcam), float(ycam)
        return None

    def project_batch(self, kf_hat_arr, source_depth_mm: float = 0.0):
        """
        Vectorised :meth:`project` for N directions at once.

        Args:
            kf_hat_arr (ndarray, shape (N, 3)): Unit vectors in the LT frame (x // beam).  Need not be
                pre-normalised — they are normalised internally.
            source_depth_mm (float): Depth of the scattering centre below the
                surface along the beam direction (mm).  See :meth:`project`.

        Returns:
            pix (ndarray, shape (N, 2)): Pixel coordinates (xcam, ycam).  Rows for rays that miss the
                detector contain NaN.
            on_det (ndarray, shape (N,), dtype bool):
"""
        kf_lt = kf_hat_arr / np.linalg.norm(kf_hat_arr, axis=1, keepdims=True)
        kf = np.column_stack([-kf_lt[:, 1], kf_lt[:, 0], kf_lt[:, 2]])
        scal = kf @ self.normal
        hit = scal > 1e-8
        safe_scal = np.where(hit, scal, 1.0)
        # Depth correction: source at (0, depth_mm, 0) in LT2; dd_eff = dd − d·n̂[1]
        s_dot_n = source_depth_mm * self.normal[1]
        normeIM = (self.dd - s_dot_n) / safe_scal
        IM = np.array([0.0, source_depth_mm, 0.0]) + kf * normeIM[:, None]
        OM = IM - self.IOlab[None, :]
        xca0 = OM[:, 0]
        yca0 = (
            OM[:, 1] / self._sinbeta
            if abs(self._sinbeta) > 1e-8
            else -OM[:, 2] / self._cosbeta
        )
        xcam1 = self._cosgam * xca0 + self._singam * yca0
        ycam1 = -self._singam * xca0 + self._cosgam * yca0
        xcam = self.xcen + xcam1 / self.pixel_mm
        ycam = self.ycen + ycam1 / self.pixel_mm
        on_det = hit & (xcam >= 0) & (xcam < self.Nh) & (ycam >= 0) & (ycam < self.Nv)
        pix = np.empty((len(kf_hat_arr), 2), dtype=float)
        pix[:, 0] = xcam
        pix[:, 1] = ycam
        pix[~on_det] = np.nan
        return pix, on_det

    # ── 2theta / chi from pixel ───────────────────────────────────────────────

    def pixel_to_2theta_chi(self, xcam, ycam):
        """
        Compute 2theta and chi (degrees) from pixel position.

        Uses pixel_to_kf to obtain the scattered unit vector in the LT frame
        (x // beam), then:

            2theta = arccos(uf_x)
            chi    = arctan2(uf_y, uf_z)
"""
        uf_lt = self.pixel_to_kf([xcam], [ycam])[0]
        tth = np.degrees(np.arccos(np.clip(uf_lt[0], -1, 1)))
        chi = np.degrees(np.arctan2(uf_lt[1], uf_lt[2] + 1e-17))
        return tth, chi

    # ── 2theta grid on detector ───────────────────────────────────────────────

    def tth_grid(self, step=None):
        """
        Return a 2theta map over the whole detector (shape Nv x Nh).
        Useful for contour overlays on detector images.
"""
        if step is None:
            step = max(1, self.Nh // 40)
        cs = np.arange(0, self.Nh, step)
        rs = np.arange(0, self.Nv, step)
        CC, RR = np.meshgrid(cs, rs)
        uf = self.pixel_to_kf(CC.ravel(), RR.ravel())
        TTH = np.degrees(np.arccos(np.clip(uf[:, 0], -1, 1))).reshape(CC.shape)
        return CC, RR, TTH

    # ── describe ──────────────────────────────────────────────────────────────

    def describe(self):
        tth_cen, chi_cen = self.pixel_to_2theta_chi(self.xcen, self.ycen)
        corners = [
            (0, 0),
            (self.Nh - 1, 0),
            (0, self.Nv - 1),
            (self.Nh - 1, self.Nv - 1),
        ]
        tths = [self.pixel_to_2theta_chi(c, r)[0] for c, r in corners]
        print(
            f"  Camera ({self.kf_direction}) : {self.Nh} x {self.Nv} px  "
            f"pixel={self.pixel_mm*1e3:.1f} um"
        )
        print(f"  Physical size : {self.size_h_mm:.1f} x {self.size_v_mm:.1f} mm²")
        print(f"  LaueTools calibration:")
        print(f"    dd={self.dd:.3f} mm   xcen={self.xcen:.2f}   ycen={self.ycen:.2f}")
        print(f"    xbet={self.xbet:.3f} deg   xgam={self.xgam:.3f} deg")
        print(
            f"  2theta at (xcen,ycen) : {tth_cen:.4f} deg  "
            f"(= 90 - xbet = {90-self.xbet:.4f} deg)"
        )
        print(f"  chi   at (xcen,ycen) : {chi_cen:.4f} deg")
        print(
            f"  Angular coverage (corners): "
            f"2theta = {min(tths):.1f} - {max(tths):.1f} deg"
        )
        # direct beam position
        ki_hat = np.array([1.0, 0.0, 0.0])
        db = self.project(ki_hat)
        if db:
            print(
                f"  Direct beam footprint: xcam={db[0]:.1f}  ycam={db[1]:.1f}  "
                f"(pixel; should match xcen,ycen for xbet~0)"
            )
        else:
            print("  Direct beam does not hit this detector")

    # ── load from LaueTools calibration dict or list ──────────────────────────

    @classmethod
    def from_lauetools(cls, calib, pixelsize=None, framedim=None, kf_direction="Z>0"):
        """
        Build a Camera from a LaueTools calibration.

        Args:
            calib (list or array): [dd, xcen, ycen, xbet, xgam]
                (= CCDCalibParameters in LaueTools)
            pixelsize (float, mm): (= xpixelsize in LaueTools dict)
            framedim ((Nh, Nv)): (= framedim in LaueTools dict)
            kf_direction (str): (= kf_direction in LaueTools dict)
"""
        dd, xcen, ycen, xbet, xgam = calib[:5]
        px = pixelsize if pixelsize is not None else PIXEL_SIZE_MM
        Nh, Nv = framedim if framedim is not None else (N_PIX_H, N_PIX_V)
        return cls(
            dd=dd,
            xcen=xcen,
            ycen=ycen,
            xbet=xbet,
            xgam=xgam,
            pixelsize=px,
            n_pix_h=int(Nh),
            n_pix_v=int(Nv),
            kf_direction=kf_direction,
        )

    # ── synthetic image ────────────────────────────────────────────────────────

    def add_poisson_noise(
        self,
        image: "np.ndarray",
        peak_counts: float = 1000.0,
        noise_floor: float = 0.0,
        rng: "np.random.Generator | int | None" = None,
    ) -> "np.ndarray":
        """
        Simulate Poissonian photon-counting statistics on a detector image.

        The image is treated as a map of *relative* intensities.  It is
        scaled so that the brightest pixel has `peak_counts` expected
        photons, then `noise_floor` is added to every pixel, and finally
        every pixel is sampled independently from a Poisson distribution:

        $$
        \\lambda_i = I_i \\cdot \\frac{\\text{peak\\_counts}}{\\max(I)}
                   + \\text{noise\\_floor}
        \\qquad
        n_i \\sim \\operatorname{Poisson}(\\lambda_i)
        $$

        This reproduces the correct counting statistics: the noise standard
        deviation at pixel *i* is $\\sqrt{\\lambda_i}$, so bright spots
        have more absolute noise but better signal-to-noise than dim pixels.
        The `noise_floor` term ensures that even empty pixels receive
        Poisson-distributed background counts (dark current, diffuse scatter),
        matching real photon-counting detector behaviour.

        !!! note
            Pass a **linear** (non-log-scaled) image so that relative
            intensities are preserved.  Use
            `camera.render(spots, log_scale=False)` before calling this
            method, then optionally apply log-scaling to the returned noisy
            image for display.

        Args:
            image (numpy.ndarray, shape (Nv, Nh)): Linear intensity image from :meth:`render` (`log_scale=False`).
                All values must be ≥ 0.
            peak_counts (float): Expected photon count at the brightest pixel.  Controls the
                overall exposure level and therefore the noise level:
                SNR ∝ √peak_counts.
            noise_floor (float): Expected background counts added to every pixel before Poisson
                sampling.  Models dark current and diffuse scattered background.
                Default 0 (no background — purely signal-dependent noise).
            rng (numpy.random.Generator or int or None): Random-number source.  Pass an integer seed for reproducibility,
                or `None` (default) to use a fresh default RNG.

        Returns:
            noisy (numpy.ndarray, shape (Nv, Nh), dtype float32): Poisson-sampled photon-count image.

        Example:
        >>> img_linear = camera.render(spots, log_scale=False)
        >>> img_noisy  = camera.add_poisson_noise(img_linear, peak_counts=500, noise_floor=2.0)
        >>> img_display = np.log1p(img_noisy / img_noisy.max() * 1000)
"""
        img = np.asarray(image, dtype=np.float64)
        img_max = img.max()
        if img_max > 0:
            lam = img * (float(peak_counts) / img_max) + float(noise_floor)
        else:
            lam = np.full_like(img, float(noise_floor))

        if isinstance(rng, np.random.Generator):
            gen = rng
        elif rng is None:
            gen = np.random.default_rng()
        else:
            gen = np.random.default_rng(int(rng))

        noisy = gen.poisson(np.maximum(lam, 0)).astype(np.float32)
        return noisy

    def render(self, spots, sigma_pix=SPOT_SIGMA_PIX, log_scale=False, normalize=False, upsample=4):
        """
        Render a synthetic detector image (float32, shape Nv x Nh).

        Each spot's raw intensity (`I_raw`) is deposited at its nearest pixel
        on an *upsampled* grid (`upsample` sub-pixels per detector pixel),
        which recovers sub-pixel spot placement; the assembled upsampled
        image is then blurred once with an isotropic Gaussian and binned
        back down to the native detector resolution.  By default the image
        is returned in raw intensity units with no scaling applied.

        Args:
            spots (list of dicts): Spot list from any `simulate_laue*` function.
                Required keys: `'pix'` (xcam, ycam), `'I_raw'`.
                The key `'tth'` (degrees) is required when *sigma_pix* is a
                callable or a broadening result dict.
            sigma_pix (float | callable | dict): Controls the Gaussian σ (pixels)
                used for the single whole-image blur:

            * **float** *(default)*  — fixed width, used directly.
            * **callable** `f(tth_deg) → float` or `f(tth_deg, chi_deg) → float`
              — evaluated per spot as a function of 2θ (and, if the callable
              accepts a second positional argument, χ — auto-detected via
              its signature; requires the `'chi'` key on each spot), then
              averaged across all spots to obtain the single σ used for the
              whole-image blur.  Pass the `'model'` callable returned by
              :func:`~nrxrdct.laue.estimate_instrument_broadening`.
            * **dict** — the full result dict from
              :func:`~nrxrdct.laue.estimate_instrument_broadening`; the
              `'model'` key is extracted automatically and handled as above.

            log_scale (bool): Apply `log1p` compression before returning (default `False`).
            normalize (bool): Divide by the image maximum after all other processing
                (default `False`).
            upsample (int): Sub-pixel refinement factor (default `4`).  Spot
                positions are binned onto a grid `upsample` times finer than
                the detector before blurring, then the result is summed back
                down to native resolution.  `1` disables the sub-pixel
                refinement (spots snap to the nearest native pixel).
"""
        # Resolve broadening model
        if isinstance(sigma_pix, dict):
            _model = sigma_pix["model"]
            _fixed_sigma = None
        elif callable(sigma_pix):
            _model = sigma_pix
            _fixed_sigma = None
        else:
            _model = None
            _fixed_sigma = float(sigma_pix)

        _model_uses_chi = False
        if _model is not None:
            try:
                _model_uses_chi = len(inspect.signature(_model).parameters) >= 2
            except (TypeError, ValueError):
                _model_uses_chi = False

        upsample = int(upsample)
        if upsample < 1:
            raise ValueError("upsample must be >= 1")
        Nv_up, Nh_up = self.Nv * upsample, self.Nh * upsample

        img_up = np.zeros((Nv_up, Nh_up), dtype=np.float64)
        sigmas = []
        rows, cols, weights = [], [], []
        for s in spots:
            if s.get("pix") is None:
                continue

            if _model is not None:
                sigma = _model(s["tth"], s["chi"]) if _model_uses_chi else _model(s["tth"])
            else:
                sigma = _fixed_sigma
            if not (sigma > 0):
                continue

            c, r = s["pix"]  # xcam, ycam
            I_raw = s["I_raw"]
            if not (np.isfinite(c) and np.isfinite(r) and np.isfinite(I_raw)):
                continue

            ci, ri = int(round(c * upsample)), int(round(r * upsample))
            if not (0 <= ci < Nh_up and 0 <= ri < Nv_up):
                continue

            sigmas.append(sigma)
            rows.append(ri)
            cols.append(ci)
            weights.append(I_raw)

        if rows:
            np.add.at(img_up, (rows, cols), weights)
            sigma_avg = float(np.mean(sigmas))
            if sigma_avg > 0:
                img_up = np.clip(_fft_gauss_convolve(img_up, sigma_avg * upsample), 0.0, None)

        img = img_up.reshape(self.Nv, upsample, self.Nh, upsample).sum(axis=(1, 3))
        img = np.nan_to_num(img, nan=0.0, posinf=0.0, neginf=0.0)

        if log_scale:
            img = np.log1p(img)
        if normalize and img.max() > 0:
            img = img / img.max()
        return img.astype(np.float32)

    # ── .det file IO ──────────────────────────────────────────────────────────

    def to_det(self, path) -> None:
        """
        Write a LaueTools-compatible `.det` calibration file.

        Format (4 data lines, preceded by a comment header)::

            # LaueTools camera calibration
            # dd xcen ycen xbet xgam   pixelsize   Nh Nv   kf_direction
            # Written: <ISO date>
            dd xcen ycen xbet xgam
            pixelsize
            Nh Nv
            kf_direction
"""
        import datetime
        from pathlib import Path

        header = (
            "# LaueTools camera calibration\n"
            "# dd(mm)  xcen(px)  ycen(px)  xbet(deg)  xgam(deg)"
            "   pixelsize(mm)   Nh Nv   kf_direction\n"
            f"# Written: {datetime.date.today().isoformat()}\n"
        )
        data = (
            f"{self.dd:.6g} {self.xcen:.6g} {self.ycen:.6g} "
            f"{self.xbet:.6g} {self.xgam:.6g}\n"
            f"{self.pixel_mm:.6g}\n"
            f"{self.Nh} {self.Nv}\n"
            f"{self.kf_direction}\n"
        )
        Path(path).write_text(header + data)

    @classmethod
    def from_det(cls, path, pixelsize=None, framedim=None, kf_direction=None):
        """
        Read a LaueTools-compatible `.det` calibration file.

        Args:
            path (path-like): Path to the `.det` file.
            pixelsize (float or None): Override the pixel size (mm) read from the file.
            framedim ((Nh, Nv) or None): Override the frame dimensions read from the file.
            kf_direction (str or None): Override the kf_direction read from the file.
"""
        from pathlib import Path

        lines = [
            ln.strip()
            for ln in Path(path).read_text().splitlines()
            if ln.strip() and not ln.strip().startswith("#")
        ]
        dd, xcen, ycen, xbet, xgam = map(float, lines[0].split())
        px = float(lines[1]) if pixelsize is None else float(pixelsize)
        if framedim is None:
            Nh, Nv = map(int, lines[2].split())
        else:
            Nh, Nv = int(framedim[0]), int(framedim[1])
        kfd = lines[3] if kf_direction is None else kf_direction
        return cls(
            dd=dd, xcen=xcen, ycen=ycen, xbet=xbet, xgam=xgam,
            pixelsize=px, n_pix_h=Nh, n_pix_v=Nv, kf_direction=kfd,
        )

    # ── calibration fitting ───────────────────────────────────────────────────

    def fit_calibration(
        self,
        crystal,
        U,
        obs_xy,
        *,
        fit_params=("dd", "xcen", "ycen", "xbet", "xgam"),
        fit_U=False,
        E_min=5_000.0,
        E_max=27_000.0,
        source="bending_magnet",
        source_kwargs=None,
        f2_thresh=1e-6,
        max_match_px=20.0,
        top_n_sim=None,
        bounds=None,
        dd_range=None,
        cen_range_px=None,
        angle_range_deg=None,
        U_range_deg=None,
        method=None,
        options=None,
    ):
        """
        Fit camera calibration parameters to an observed Laue pattern.

        The cost function is the mean squared nearest-neighbour distance from
        each observed spot to the closest simulated spot, capped at
        `max_match_px`.  This soft matching gives a smooth landscape suitable
        for derivative-free optimisation.

        When bounds are specified the optimizer switches to L-BFGS-B (which
        enforces them natively); otherwise Nelder-Mead is used.

        Args:
            crystal (Crystal): Crystal structure of the calibration standard.
            U ((3, 3) array): Initial orientation matrix.  Updated in the result if `fit_U=True`.
            obs_xy ((N, 2) array): Observed spot pixel positions `[[xcam, ycam], ...]`.
            fit_params (sequence of str): Camera parameters to optimise.  Any subset of
                `{"dd", "xcen", "ycen", "xbet", "xgam"}`.
            fit_U (bool): If `True`, also refine the orientation matrix via three small-angle
                Euler rotations around lab x, y, z (degrees).
            E_min, E_max (float): Energy range (eV) for the Laue simulation.
            source (str): Source model passed to `simulate_laue`.
            source_kwargs (dict or None): Extra kwargs for the spectrum function.
            f2_thresh (float): Structure-factor threshold for HKL precomputation.
            max_match_px (float or list of float): Cap distance (pixels) used in the cost function and for
                reporting the final match rate.  Pass a list to run staged
                refinement: the optimizer restarts from the previous result
                at each successively tighter cap, e.g. `[30, 10, 3]`.
            top_n_sim (int or None): Restrict cost evaluation to the brightest *N* simulated spots.
            bounds (dict or None): Explicit parameter bounds as `{param_name: (lo, hi)}`.  Values
                are absolute (not relative).  Keys are the same as `fit_params`
                plus `"U_rx"`, `"U_ry"`, `"U_rz"` for orientation angles.
                Takes priority over the convenience range parameters below.
            dd_range (float or None): Maximum allowed deviation of `dd` from its starting value (mm).
                E.g. `dd_range=5.0` → bounds `(dd0 - 5, dd0 + 5)`.
            cen_range_px (float or None): Maximum allowed deviation of `xcen` / `ycen` from their
                starting values (pixels).
            angle_range_deg (float or None): Maximum allowed deviation of `xbet` / `xgam` from their
                starting values (degrees).
            U_range_deg (float or None): Maximum allowed rotation of the orientation angles `U_rx`,
                `U_ry`, `U_rz` from zero (degrees).  Only relevant when
                `fit_U=True`.
            method (str or None): Scipy optimisation method.  Defaults to `"L-BFGS-B"` when any
                bounds are active, `"Nelder-Mead"` otherwise.
            options (dict or None): Options forwarded to `scipy.optimize.minimize`, overriding
                defaults.

        Returns:
            CalibrationResult
"""
        from scipy.optimize import minimize
        from scipy.spatial import cKDTree
        from .simulation import simulate_laue, precompute_allowed_hkl

        obs_xy = np.asarray(obs_xy, dtype=float)
        if obs_xy.ndim != 2 or obs_xy.shape[1] != 2:
            raise ValueError("obs_xy must be shape (N, 2)")
        n_obs = len(obs_xy)
        U0 = np.asarray(U, dtype=float).copy()
        src_kw = source_kwargs or {}

        _valid = {"dd", "xcen", "ycen", "xbet", "xgam"}
        for p in fit_params:
            if p not in _valid:
                raise ValueError(f"Unknown fit_param {p!r}; must be one of {_valid}")
        fit_params = list(fit_params)

        if isinstance(max_match_px, (int, float)):
            _stages = [float(max_match_px)]
        else:
            _stages = [float(v) for v in max_match_px]
        _cur_mmp = _stages[0]

        E_ref = 0.5 * (E_min + E_max)
        allowed_hkl = precompute_allowed_hkl(crystal, E_max_eV=E_max, E_ref_eV=E_ref, f2_thresh=f2_thresh)

        _all_names = fit_params + (["U_rx", "U_ry", "U_rz"] if fit_U else [])
        _cam_init = {
            "dd": self.dd, "xcen": self.xcen, "ycen": self.ycen,
            "xbet": self.xbet, "xgam": self.xgam,
        }
        x0 = np.array(
            [_cam_init[p] for p in fit_params] + ([0.0, 0.0, 0.0] if fit_U else []),
            dtype=float,
        )

        def _build_cam(x):
            kw = dict(
                dd=self.dd, xcen=self.xcen, ycen=self.ycen,
                xbet=self.xbet, xgam=self.xgam,
                pixelsize=self.pixel_mm, n_pix_h=self.Nh, n_pix_v=self.Nv,
                kf_direction=self.kf_direction,
            )
            for i, p in enumerate(fit_params):
                kw[p] = float(x[i])
            return Camera(**kw)

        def _build_U(x):
            if not fit_U:
                return U0
            from scipy.spatial.transform import Rotation
            rx, ry, rz = x[len(fit_params):]
            dU = Rotation.from_euler("xyz", [rx, ry, rz], degrees=True).as_matrix()
            return U0 @ dU

        def _cost(x):
            try:
                cam = _build_cam(x)
                U_cur = _build_U(x)
                spots = simulate_laue(
                    crystal, U_cur, cam,
                    E_min=E_min, E_max=E_max,
                    source=source, source_kwargs=src_kw,
                    f2_thresh=f2_thresh,
                    allowed_hkl=allowed_hkl,
                )
            except Exception:
                return float(_cur_mmp ** 2)

            sim_xy = np.array(
                [s["pix"] for s in spots if s.get("pix") is not None]
            )
            if len(sim_xy) == 0:
                return float(_cur_mmp ** 2)

            if top_n_sim is not None and len(sim_xy) > top_n_sim:
                I_vals = np.array(
                    [s["I_raw"] for s in spots if s.get("pix") is not None]
                )
                idx = np.argsort(I_vals)[::-1][:top_n_sim]
                sim_xy = sim_xy[idx]

            tree = cKDTree(sim_xy)
            dists, _ = tree.query(obs_xy, k=1)
            return float(np.mean(np.minimum(dists, _cur_mmp) ** 2))

        # ── build bounds ─────────────────────────────────────────────────────
        # Start from the explicit bounds dict, then fill missing entries from
        # the convenience range parameters.
        _bounds_dict: dict = dict(bounds) if bounds else {}

        _range_defaults = {
            "dd":   dd_range,
            "xcen": cen_range_px,
            "ycen": cen_range_px,
            "xbet": angle_range_deg,
            "xgam": angle_range_deg,
            "U_rx": U_range_deg,
            "U_ry": U_range_deg,
            "U_rz": U_range_deg,
        }
        for pname in _all_names:
            if pname not in _bounds_dict and _range_defaults.get(pname) is not None:
                r = float(_range_defaults[pname])
                centre = _cam_init.get(pname, 0.0)   # orientation deltas start at 0
                _bounds_dict[pname] = (centre - r, centre + r)

        # Ordered bounds list matching x0 / _all_names
        scipy_bounds = (
            [_bounds_dict[p] for p in _all_names]
            if _bounds_dict else None
        )

        # ── choose method ────────────────────────────────────────────────────
        if method is not None:
            _method = method
        elif scipy_bounds is not None:
            _method = "L-BFGS-B"
        else:
            _method = "Nelder-Mead"

        # ── build options (rebuilt each stage so simplex tracks x0) ─────────
        _steps = {
            "dd": 2.0, "xcen": 50.0, "ycen": 50.0, "xbet": 0.5, "xgam": 0.5,
            "U_rx": 2.0, "U_ry": 2.0, "U_rz": 2.0,
        }

        def _build_opts(x0_cur):
            if _method == "Nelder-Mead":
                n_p = len(x0_cur)
                init_simplex = np.tile(x0_cur, (n_p + 1, 1))
                for i, pname in enumerate(_all_names):
                    step = _steps.get(pname, 1.0)
                    if scipy_bounds:
                        lo, hi = scipy_bounds[i]
                        step = min(step, (hi - lo) * 0.25)
                    init_simplex[i + 1, i] += step
                return {
                    "maxiter": 5000, "xatol": 0.05, "fatol": 1e-4,
                    "initial_simplex": init_simplex,
                }
            return {"maxiter": 5000, "ftol": 1e-6, "gtol": 1e-6}

        # ── staged optimisation ───────────────────────────────────────────────
        result = None
        for _cur_mmp in _stages:
            _opts = _build_opts(x0)
            if options:
                _opts.update(options)
            result = minimize(
                _cost, x0,
                method=_method,
                bounds=scipy_bounds,
                options=_opts,
            )
            x0 = result.x

        cam_final = _build_cam(result.x)
        U_final = _build_U(result.x)

        # Final match statistics with the converged parameters
        spots_final = simulate_laue(
            crystal, U_final, cam_final,
            E_min=E_min, E_max=E_max,
            source=source, source_kwargs=src_kw,
            f2_thresh=f2_thresh,
            allowed_hkl=allowed_hkl,
        )
        sim_xy_f = np.array(
            [s["pix"] for s in spots_final if s.get("pix") is not None]
        )

        n_matched, rms_px = 0, float("nan")
        if len(sim_xy_f) > 0 and n_obs > 0:
            tree = cKDTree(sim_xy_f)
            dists, _ = tree.query(obs_xy, k=1)
            ok = dists < _stages[-1]
            n_matched = int(ok.sum())
            if n_matched > 0:
                rms_px = float(np.sqrt((dists[ok] ** 2).mean()))

        return CalibrationResult(
            camera=cam_final,
            U=U_final,
            rms_px=rms_px,
            n_matched=n_matched,
            n_obs=n_obs,
            n_sim=len(sim_xy_f),
            fit_params=tuple(_all_names),
            success=bool(result.success),
            message=result.message,
        )

    def fit_calibration_staged(
        self,
        crystal,
        U,
        obs_xy,
        *,
        # ── Phase A — stabilise geometry ─────────────────────────────────────
        phaseA_params=("dd", "xcen", "ycen", "xbet", "xgam"),
        phaseA_fit_U=False,
        phaseA_dd_range=5.0,
        phaseA_cen_range_px=100.0,
        phaseA_angle_range_deg=1.0,
        phaseA_U_range_deg=0.5,
        phaseA_options=None,
        # ── Phase B — refine orientation ─────────────────────────────────────
        phaseB_params=(),
        phaseB_fit_U=True,
        phaseB_U_range_deg=10.0,
        phaseB_options=None,
        # ── Phase C — global refinement ──────────────────────────────────────
        phaseC_params=("dd", "xcen", "ycen", "xbet", "xgam"),
        phaseC_fit_U=True,
        phaseC_dd_range=2.0,
        phaseC_cen_range_px=30.0,
        phaseC_angle_range_deg=0.5,
        phaseC_U_range_deg=3.0,
        phaseC_options=None,
        # ── shared ───────────────────────────────────────────────────────────
        E_min=5_000.0,
        E_max=27_000.0,
        source="bending_magnet",
        source_kwargs=None,
        f2_thresh=1e-6,
        max_match_px=20.0,
        top_n_sim=None,
        verbose=False,
    ) -> "CalibrationResult":
        """
        Three-phase staged calibration that alternates between geometry and
        orientation refinement for improved convergence.

        **Phase A — stabilise geometry**
            Refine camera geometry parameters with U fixed (or nearly fixed).
            Large initial bounds allow coarse corrections from the starting
            estimate; tight U bounds prevent orientation drift from corrupting
            the geometry.

        **Phase B — refine orientation**
            Fix the geometry from Phase A and refine the orientation matrix U.
            Geometry is now good enough that the spot pattern can guide U
            without the two coupled parameters fighting each other.

        **Phase C — global refinement**
            Refine geometry and U simultaneously, starting from the Phase B
            solution with tighter bounds.  Resolves the remaining correlation
            between small geometry shifts and orientation corrections.

        Args:
            crystal (Crystal): Calibration standard.
            U ((3, 3) array): Initial orientation matrix.
            obs_xy ((N, 2) array): Observed spot pixel positions.

            phaseA_params (sequence of str): Camera parameters to optimise in Phase A.
                Default: all five geometry parameters.
            phaseA_fit_U (bool): Allow a small orientation correction in Phase A.  Default False.
            phaseA_dd_range (float): Phase A bound on `dd` (mm, ± from starting value).
            phaseA_cen_range_px (float): Phase A bound on `xcen` / `ycen` (pixels).
            phaseA_angle_range_deg (float): Phase A bound on `xbet` / `xgam` (degrees).
            phaseA_U_range_deg (float): Phase A bound on orientation angles (degrees), only used when
                `phaseA_fit_U=True`.
            phaseA_options (dict or None): Extra options for the Phase A optimizer.

            phaseB_params (sequence of str): Camera parameters to optimise in Phase B.  Default: none
                (geometry frozen).
            phaseB_fit_U (bool): Refine U in Phase B.  Default True.
            phaseB_U_range_deg (float): Phase B bound on orientation angles (degrees).
            phaseB_options (dict or None): Extra options for the Phase B optimizer.

            phaseC_params (sequence of str): Camera parameters to optimise in Phase C.  Default: all five.
            phaseC_fit_U (bool): Refine U in Phase C.  Default True.
            phaseC_dd_range (float): Phase C bound on `dd` (mm).
            phaseC_cen_range_px (float): Phase C bound on `xcen` / `ycen` (pixels).
            phaseC_angle_range_deg (float): Phase C bound on `xbet` / `xgam` (degrees).
            phaseC_U_range_deg (float): Phase C bound on orientation angles (degrees).
            phaseC_options (dict or None): Extra options for the Phase C optimizer.

            E_min, E_max (float): Energy range (eV) shared by all phases.  The allowed-HKL
                sphere cutoff is derived automatically from `E_max`.
            source, source_kwargs, f2_thresh, max_match_px, top_n_sim
                Forwarded unchanged to each :meth:`fit_calibration` call.
            verbose (bool): Print a one-line summary after each phase.

        Returns:
            CalibrationResult
                Result of Phase C (the final global refinement).  Intermediate
                results are available via `verbose=True` output.
"""
        _shared = dict(
            E_min=E_min, E_max=E_max,
            source=source, source_kwargs=source_kwargs,
            f2_thresh=f2_thresh,
            max_match_px=max_match_px, top_n_sim=top_n_sim,
        )

        # ── Phase A ───────────────────────────────────────────────────────────
        res_A = self.fit_calibration(
            crystal, U, obs_xy,
            fit_params=phaseA_params,
            fit_U=phaseA_fit_U,
            dd_range=phaseA_dd_range,
            cen_range_px=phaseA_cen_range_px,
            angle_range_deg=phaseA_angle_range_deg,
            U_range_deg=phaseA_U_range_deg if phaseA_fit_U else None,
            options=phaseA_options,
            **_shared,
        )
        if verbose:
            print(f"Phase A (geometry):     {res_A}")

        # ── Phase B ───────────────────────────────────────────────────────────
        res_B = res_A.camera.fit_calibration(
            crystal, res_A.U, obs_xy,
            fit_params=phaseB_params,
            fit_U=phaseB_fit_U,
            U_range_deg=phaseB_U_range_deg if phaseB_fit_U else None,
            options=phaseB_options,
            **_shared,
        )
        if verbose:
            print(f"Phase B (orientation):  {res_B}")

        # ── Phase C ───────────────────────────────────────────────────────────
        res_C = res_B.camera.fit_calibration(
            crystal, res_B.U, obs_xy,
            fit_params=phaseC_params,
            fit_U=phaseC_fit_U,
            dd_range=phaseC_dd_range,
            cen_range_px=phaseC_cen_range_px,
            angle_range_deg=phaseC_angle_range_deg,
            U_range_deg=phaseC_U_range_deg if phaseC_fit_U else None,
            options=phaseC_options,
            **_shared,
        )
        if verbose:
            print(f"Phase C (global):       {res_C}")

        return res_C

add_poisson_noise

add_poisson_noise(image: ndarray, peak_counts: float = 1000.0, noise_floor: float = 0.0, rng: Generator | int | None = None) -> np.ndarray

Simulate Poissonian photon-counting statistics on a detector image.

The image is treated as a map of relative intensities. It is scaled so that the brightest pixel has peak_counts expected photons, then noise_floor is added to every pixel, and finally every pixel is sampled independently from a Poisson distribution:

\[ \lambda_i = I_i \cdot \frac{\text{peak\_counts}}{\max(I)} + \text{noise\_floor} \qquad n_i \sim \operatorname{Poisson}(\lambda_i) \]

This reproduces the correct counting statistics: the noise standard deviation at pixel i is \(\sqrt{\lambda_i}\), so bright spots have more absolute noise but better signal-to-noise than dim pixels. The noise_floor term ensures that even empty pixels receive Poisson-distributed background counts (dark current, diffuse scatter), matching real photon-counting detector behaviour.

Note

Pass a linear (non-log-scaled) image so that relative intensities are preserved. Use camera.render(spots, log_scale=False) before calling this method, then optionally apply log-scaling to the returned noisy image for display.

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

    Linear intensity image from :meth:render (log_scale=False). All values must be ≥ 0.

  • peak_counts (float, default: 1000.0 ) –

    Expected photon count at the brightest pixel. Controls the overall exposure level and therefore the noise level: SNR ∝ √peak_counts.

  • noise_floor (float, default: 0.0 ) –

    Expected background counts added to every pixel before Poisson sampling. Models dark current and diffuse scattered background. Default 0 (no background — purely signal-dependent noise).

  • rng (Generator or int or None, default: None ) –

    Random-number source. Pass an integer seed for reproducibility, or None (default) to use a fresh default RNG.

Returns:
  • noisy( numpy.ndarray, shape (Nv, Nh), dtype float32 ) –

    Poisson-sampled photon-count image.

Example:

img_linear = camera.render(spots, log_scale=False) img_noisy = camera.add_poisson_noise(img_linear, peak_counts=500, noise_floor=2.0) img_display = np.log1p(img_noisy / img_noisy.max() * 1000)

Source code in src/nrxrdct/laue/camera.py
    def add_poisson_noise(
        self,
        image: "np.ndarray",
        peak_counts: float = 1000.0,
        noise_floor: float = 0.0,
        rng: "np.random.Generator | int | None" = None,
    ) -> "np.ndarray":
        """
        Simulate Poissonian photon-counting statistics on a detector image.

        The image is treated as a map of *relative* intensities.  It is
        scaled so that the brightest pixel has `peak_counts` expected
        photons, then `noise_floor` is added to every pixel, and finally
        every pixel is sampled independently from a Poisson distribution:

        $$
        \\lambda_i = I_i \\cdot \\frac{\\text{peak\\_counts}}{\\max(I)}
                   + \\text{noise\\_floor}
        \\qquad
        n_i \\sim \\operatorname{Poisson}(\\lambda_i)
        $$

        This reproduces the correct counting statistics: the noise standard
        deviation at pixel *i* is $\\sqrt{\\lambda_i}$, so bright spots
        have more absolute noise but better signal-to-noise than dim pixels.
        The `noise_floor` term ensures that even empty pixels receive
        Poisson-distributed background counts (dark current, diffuse scatter),
        matching real photon-counting detector behaviour.

        !!! note
            Pass a **linear** (non-log-scaled) image so that relative
            intensities are preserved.  Use
            `camera.render(spots, log_scale=False)` before calling this
            method, then optionally apply log-scaling to the returned noisy
            image for display.

        Args:
            image (numpy.ndarray, shape (Nv, Nh)): Linear intensity image from :meth:`render` (`log_scale=False`).
                All values must be ≥ 0.
            peak_counts (float): Expected photon count at the brightest pixel.  Controls the
                overall exposure level and therefore the noise level:
                SNR ∝ √peak_counts.
            noise_floor (float): Expected background counts added to every pixel before Poisson
                sampling.  Models dark current and diffuse scattered background.
                Default 0 (no background — purely signal-dependent noise).
            rng (numpy.random.Generator or int or None): Random-number source.  Pass an integer seed for reproducibility,
                or `None` (default) to use a fresh default RNG.

        Returns:
            noisy (numpy.ndarray, shape (Nv, Nh), dtype float32): Poisson-sampled photon-count image.

        Example:
        >>> img_linear = camera.render(spots, log_scale=False)
        >>> img_noisy  = camera.add_poisson_noise(img_linear, peak_counts=500, noise_floor=2.0)
        >>> img_display = np.log1p(img_noisy / img_noisy.max() * 1000)
"""
        img = np.asarray(image, dtype=np.float64)
        img_max = img.max()
        if img_max > 0:
            lam = img * (float(peak_counts) / img_max) + float(noise_floor)
        else:
            lam = np.full_like(img, float(noise_floor))

        if isinstance(rng, np.random.Generator):
            gen = rng
        elif rng is None:
            gen = np.random.default_rng()
        else:
            gen = np.random.default_rng(int(rng))

        noisy = gen.poisson(np.maximum(lam, 0)).astype(np.float32)
        return noisy

fit_calibration

fit_calibration(crystal, U, obs_xy, *, fit_params=('dd', 'xcen', 'ycen', 'xbet', 'xgam'), fit_U=False, E_min=5000.0, E_max=27000.0, source='bending_magnet', source_kwargs=None, f2_thresh=1e-06, max_match_px=20.0, top_n_sim=None, bounds=None, dd_range=None, cen_range_px=None, angle_range_deg=None, U_range_deg=None, method=None, options=None)

Fit camera calibration parameters to an observed Laue pattern.

The cost function is the mean squared nearest-neighbour distance from each observed spot to the closest simulated spot, capped at max_match_px. This soft matching gives a smooth landscape suitable for derivative-free optimisation.

When bounds are specified the optimizer switches to L-BFGS-B (which enforces them natively); otherwise Nelder-Mead is used.

Parameters:
  • crystal (Crystal) –

    Crystal structure of the calibration standard.

  • U ((3, 3) array) –

    Initial orientation matrix. Updated in the result if fit_U=True.

  • obs_xy ((N, 2) array) –

    Observed spot pixel positions [[xcam, ycam], ...].

  • fit_params (sequence of str, default: ('dd', 'xcen', 'ycen', 'xbet', 'xgam') ) –

    Camera parameters to optimise. Any subset of {"dd", "xcen", "ycen", "xbet", "xgam"}.

  • fit_U (bool, default: False ) –

    If True, also refine the orientation matrix via three small-angle Euler rotations around lab x, y, z (degrees).

  • E_min, E_max (float) –

    Energy range (eV) for the Laue simulation.

  • source (str, default: 'bending_magnet' ) –

    Source model passed to simulate_laue.

  • source_kwargs (dict or None, default: None ) –

    Extra kwargs for the spectrum function.

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

    Structure-factor threshold for HKL precomputation.

  • max_match_px (float or list of float, default: 20.0 ) –

    Cap distance (pixels) used in the cost function and for reporting the final match rate. Pass a list to run staged refinement: the optimizer restarts from the previous result at each successively tighter cap, e.g. [30, 10, 3].

  • top_n_sim (int or None, default: None ) –

    Restrict cost evaluation to the brightest N simulated spots.

  • bounds (dict or None, default: None ) –

    Explicit parameter bounds as {param_name: (lo, hi)}. Values are absolute (not relative). Keys are the same as fit_params plus "U_rx", "U_ry", "U_rz" for orientation angles. Takes priority over the convenience range parameters below.

  • dd_range (float or None, default: None ) –

    Maximum allowed deviation of dd from its starting value (mm). E.g. dd_range=5.0 → bounds (dd0 - 5, dd0 + 5).

  • cen_range_px (float or None, default: None ) –

    Maximum allowed deviation of xcen / ycen from their starting values (pixels).

  • angle_range_deg (float or None, default: None ) –

    Maximum allowed deviation of xbet / xgam from their starting values (degrees).

  • U_range_deg (float or None, default: None ) –

    Maximum allowed rotation of the orientation angles U_rx, U_ry, U_rz from zero (degrees). Only relevant when fit_U=True.

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

    Scipy optimisation method. Defaults to "L-BFGS-B" when any bounds are active, "Nelder-Mead" otherwise.

  • options (dict or None, default: None ) –

    Options forwarded to scipy.optimize.minimize, overriding defaults.

Returns:
  • –

    CalibrationResult

Source code in src/nrxrdct/laue/camera.py
    def fit_calibration(
        self,
        crystal,
        U,
        obs_xy,
        *,
        fit_params=("dd", "xcen", "ycen", "xbet", "xgam"),
        fit_U=False,
        E_min=5_000.0,
        E_max=27_000.0,
        source="bending_magnet",
        source_kwargs=None,
        f2_thresh=1e-6,
        max_match_px=20.0,
        top_n_sim=None,
        bounds=None,
        dd_range=None,
        cen_range_px=None,
        angle_range_deg=None,
        U_range_deg=None,
        method=None,
        options=None,
    ):
        """
        Fit camera calibration parameters to an observed Laue pattern.

        The cost function is the mean squared nearest-neighbour distance from
        each observed spot to the closest simulated spot, capped at
        `max_match_px`.  This soft matching gives a smooth landscape suitable
        for derivative-free optimisation.

        When bounds are specified the optimizer switches to L-BFGS-B (which
        enforces them natively); otherwise Nelder-Mead is used.

        Args:
            crystal (Crystal): Crystal structure of the calibration standard.
            U ((3, 3) array): Initial orientation matrix.  Updated in the result if `fit_U=True`.
            obs_xy ((N, 2) array): Observed spot pixel positions `[[xcam, ycam], ...]`.
            fit_params (sequence of str): Camera parameters to optimise.  Any subset of
                `{"dd", "xcen", "ycen", "xbet", "xgam"}`.
            fit_U (bool): If `True`, also refine the orientation matrix via three small-angle
                Euler rotations around lab x, y, z (degrees).
            E_min, E_max (float): Energy range (eV) for the Laue simulation.
            source (str): Source model passed to `simulate_laue`.
            source_kwargs (dict or None): Extra kwargs for the spectrum function.
            f2_thresh (float): Structure-factor threshold for HKL precomputation.
            max_match_px (float or list of float): Cap distance (pixels) used in the cost function and for
                reporting the final match rate.  Pass a list to run staged
                refinement: the optimizer restarts from the previous result
                at each successively tighter cap, e.g. `[30, 10, 3]`.
            top_n_sim (int or None): Restrict cost evaluation to the brightest *N* simulated spots.
            bounds (dict or None): Explicit parameter bounds as `{param_name: (lo, hi)}`.  Values
                are absolute (not relative).  Keys are the same as `fit_params`
                plus `"U_rx"`, `"U_ry"`, `"U_rz"` for orientation angles.
                Takes priority over the convenience range parameters below.
            dd_range (float or None): Maximum allowed deviation of `dd` from its starting value (mm).
                E.g. `dd_range=5.0` → bounds `(dd0 - 5, dd0 + 5)`.
            cen_range_px (float or None): Maximum allowed deviation of `xcen` / `ycen` from their
                starting values (pixels).
            angle_range_deg (float or None): Maximum allowed deviation of `xbet` / `xgam` from their
                starting values (degrees).
            U_range_deg (float or None): Maximum allowed rotation of the orientation angles `U_rx`,
                `U_ry`, `U_rz` from zero (degrees).  Only relevant when
                `fit_U=True`.
            method (str or None): Scipy optimisation method.  Defaults to `"L-BFGS-B"` when any
                bounds are active, `"Nelder-Mead"` otherwise.
            options (dict or None): Options forwarded to `scipy.optimize.minimize`, overriding
                defaults.

        Returns:
            CalibrationResult
"""
        from scipy.optimize import minimize
        from scipy.spatial import cKDTree
        from .simulation import simulate_laue, precompute_allowed_hkl

        obs_xy = np.asarray(obs_xy, dtype=float)
        if obs_xy.ndim != 2 or obs_xy.shape[1] != 2:
            raise ValueError("obs_xy must be shape (N, 2)")
        n_obs = len(obs_xy)
        U0 = np.asarray(U, dtype=float).copy()
        src_kw = source_kwargs or {}

        _valid = {"dd", "xcen", "ycen", "xbet", "xgam"}
        for p in fit_params:
            if p not in _valid:
                raise ValueError(f"Unknown fit_param {p!r}; must be one of {_valid}")
        fit_params = list(fit_params)

        if isinstance(max_match_px, (int, float)):
            _stages = [float(max_match_px)]
        else:
            _stages = [float(v) for v in max_match_px]
        _cur_mmp = _stages[0]

        E_ref = 0.5 * (E_min + E_max)
        allowed_hkl = precompute_allowed_hkl(crystal, E_max_eV=E_max, E_ref_eV=E_ref, f2_thresh=f2_thresh)

        _all_names = fit_params + (["U_rx", "U_ry", "U_rz"] if fit_U else [])
        _cam_init = {
            "dd": self.dd, "xcen": self.xcen, "ycen": self.ycen,
            "xbet": self.xbet, "xgam": self.xgam,
        }
        x0 = np.array(
            [_cam_init[p] for p in fit_params] + ([0.0, 0.0, 0.0] if fit_U else []),
            dtype=float,
        )

        def _build_cam(x):
            kw = dict(
                dd=self.dd, xcen=self.xcen, ycen=self.ycen,
                xbet=self.xbet, xgam=self.xgam,
                pixelsize=self.pixel_mm, n_pix_h=self.Nh, n_pix_v=self.Nv,
                kf_direction=self.kf_direction,
            )
            for i, p in enumerate(fit_params):
                kw[p] = float(x[i])
            return Camera(**kw)

        def _build_U(x):
            if not fit_U:
                return U0
            from scipy.spatial.transform import Rotation
            rx, ry, rz = x[len(fit_params):]
            dU = Rotation.from_euler("xyz", [rx, ry, rz], degrees=True).as_matrix()
            return U0 @ dU

        def _cost(x):
            try:
                cam = _build_cam(x)
                U_cur = _build_U(x)
                spots = simulate_laue(
                    crystal, U_cur, cam,
                    E_min=E_min, E_max=E_max,
                    source=source, source_kwargs=src_kw,
                    f2_thresh=f2_thresh,
                    allowed_hkl=allowed_hkl,
                )
            except Exception:
                return float(_cur_mmp ** 2)

            sim_xy = np.array(
                [s["pix"] for s in spots if s.get("pix") is not None]
            )
            if len(sim_xy) == 0:
                return float(_cur_mmp ** 2)

            if top_n_sim is not None and len(sim_xy) > top_n_sim:
                I_vals = np.array(
                    [s["I_raw"] for s in spots if s.get("pix") is not None]
                )
                idx = np.argsort(I_vals)[::-1][:top_n_sim]
                sim_xy = sim_xy[idx]

            tree = cKDTree(sim_xy)
            dists, _ = tree.query(obs_xy, k=1)
            return float(np.mean(np.minimum(dists, _cur_mmp) ** 2))

        # ── build bounds ─────────────────────────────────────────────────────
        # Start from the explicit bounds dict, then fill missing entries from
        # the convenience range parameters.
        _bounds_dict: dict = dict(bounds) if bounds else {}

        _range_defaults = {
            "dd":   dd_range,
            "xcen": cen_range_px,
            "ycen": cen_range_px,
            "xbet": angle_range_deg,
            "xgam": angle_range_deg,
            "U_rx": U_range_deg,
            "U_ry": U_range_deg,
            "U_rz": U_range_deg,
        }
        for pname in _all_names:
            if pname not in _bounds_dict and _range_defaults.get(pname) is not None:
                r = float(_range_defaults[pname])
                centre = _cam_init.get(pname, 0.0)   # orientation deltas start at 0
                _bounds_dict[pname] = (centre - r, centre + r)

        # Ordered bounds list matching x0 / _all_names
        scipy_bounds = (
            [_bounds_dict[p] for p in _all_names]
            if _bounds_dict else None
        )

        # ── choose method ────────────────────────────────────────────────────
        if method is not None:
            _method = method
        elif scipy_bounds is not None:
            _method = "L-BFGS-B"
        else:
            _method = "Nelder-Mead"

        # ── build options (rebuilt each stage so simplex tracks x0) ─────────
        _steps = {
            "dd": 2.0, "xcen": 50.0, "ycen": 50.0, "xbet": 0.5, "xgam": 0.5,
            "U_rx": 2.0, "U_ry": 2.0, "U_rz": 2.0,
        }

        def _build_opts(x0_cur):
            if _method == "Nelder-Mead":
                n_p = len(x0_cur)
                init_simplex = np.tile(x0_cur, (n_p + 1, 1))
                for i, pname in enumerate(_all_names):
                    step = _steps.get(pname, 1.0)
                    if scipy_bounds:
                        lo, hi = scipy_bounds[i]
                        step = min(step, (hi - lo) * 0.25)
                    init_simplex[i + 1, i] += step
                return {
                    "maxiter": 5000, "xatol": 0.05, "fatol": 1e-4,
                    "initial_simplex": init_simplex,
                }
            return {"maxiter": 5000, "ftol": 1e-6, "gtol": 1e-6}

        # ── staged optimisation ───────────────────────────────────────────────
        result = None
        for _cur_mmp in _stages:
            _opts = _build_opts(x0)
            if options:
                _opts.update(options)
            result = minimize(
                _cost, x0,
                method=_method,
                bounds=scipy_bounds,
                options=_opts,
            )
            x0 = result.x

        cam_final = _build_cam(result.x)
        U_final = _build_U(result.x)

        # Final match statistics with the converged parameters
        spots_final = simulate_laue(
            crystal, U_final, cam_final,
            E_min=E_min, E_max=E_max,
            source=source, source_kwargs=src_kw,
            f2_thresh=f2_thresh,
            allowed_hkl=allowed_hkl,
        )
        sim_xy_f = np.array(
            [s["pix"] for s in spots_final if s.get("pix") is not None]
        )

        n_matched, rms_px = 0, float("nan")
        if len(sim_xy_f) > 0 and n_obs > 0:
            tree = cKDTree(sim_xy_f)
            dists, _ = tree.query(obs_xy, k=1)
            ok = dists < _stages[-1]
            n_matched = int(ok.sum())
            if n_matched > 0:
                rms_px = float(np.sqrt((dists[ok] ** 2).mean()))

        return CalibrationResult(
            camera=cam_final,
            U=U_final,
            rms_px=rms_px,
            n_matched=n_matched,
            n_obs=n_obs,
            n_sim=len(sim_xy_f),
            fit_params=tuple(_all_names),
            success=bool(result.success),
            message=result.message,
        )

fit_calibration_staged

fit_calibration_staged(crystal, U, obs_xy, *, phaseA_params=('dd', 'xcen', 'ycen', 'xbet', 'xgam'), phaseA_fit_U=False, phaseA_dd_range=5.0, phaseA_cen_range_px=100.0, phaseA_angle_range_deg=1.0, phaseA_U_range_deg=0.5, phaseA_options=None, phaseB_params=(), phaseB_fit_U=True, phaseB_U_range_deg=10.0, phaseB_options=None, phaseC_params=('dd', 'xcen', 'ycen', 'xbet', 'xgam'), phaseC_fit_U=True, phaseC_dd_range=2.0, phaseC_cen_range_px=30.0, phaseC_angle_range_deg=0.5, phaseC_U_range_deg=3.0, phaseC_options=None, E_min=5000.0, E_max=27000.0, source='bending_magnet', source_kwargs=None, f2_thresh=1e-06, max_match_px=20.0, top_n_sim=None, verbose=False) -> CalibrationResult

Three-phase staged calibration that alternates between geometry and orientation refinement for improved convergence.

Phase A — stabilise geometry Refine camera geometry parameters with U fixed (or nearly fixed). Large initial bounds allow coarse corrections from the starting estimate; tight U bounds prevent orientation drift from corrupting the geometry.

Phase B — refine orientation Fix the geometry from Phase A and refine the orientation matrix U. Geometry is now good enough that the spot pattern can guide U without the two coupled parameters fighting each other.

Phase C — global refinement Refine geometry and U simultaneously, starting from the Phase B solution with tighter bounds. Resolves the remaining correlation between small geometry shifts and orientation corrections.

Parameters:
  • crystal (Crystal) –

    Calibration standard.

  • U ((3, 3) array) –

    Initial orientation matrix.

  • obs_xy ((N, 2) array) –

    Observed spot pixel positions.

  • phaseA_params (sequence of str, default: ('dd', 'xcen', 'ycen', 'xbet', 'xgam') ) –

    Camera parameters to optimise in Phase A. Default: all five geometry parameters.

  • phaseA_fit_U (bool, default: False ) –

    Allow a small orientation correction in Phase A. Default False.

  • phaseA_dd_range (float, default: 5.0 ) –

    Phase A bound on dd (mm, ± from starting value).

  • phaseA_cen_range_px (float, default: 100.0 ) –

    Phase A bound on xcen / ycen (pixels).

  • phaseA_angle_range_deg (float, default: 1.0 ) –

    Phase A bound on xbet / xgam (degrees).

  • phaseA_U_range_deg (float, default: 0.5 ) –

    Phase A bound on orientation angles (degrees), only used when phaseA_fit_U=True.

  • phaseA_options (dict or None, default: None ) –

    Extra options for the Phase A optimizer.

  • phaseB_params (sequence of str, default: () ) –

    Camera parameters to optimise in Phase B. Default: none (geometry frozen).

  • phaseB_fit_U (bool, default: True ) –

    Refine U in Phase B. Default True.

  • phaseB_U_range_deg (float, default: 10.0 ) –

    Phase B bound on orientation angles (degrees).

  • phaseB_options (dict or None, default: None ) –

    Extra options for the Phase B optimizer.

  • phaseC_params (sequence of str, default: ('dd', 'xcen', 'ycen', 'xbet', 'xgam') ) –

    Camera parameters to optimise in Phase C. Default: all five.

  • phaseC_fit_U (bool, default: True ) –

    Refine U in Phase C. Default True.

  • phaseC_dd_range (float, default: 2.0 ) –

    Phase C bound on dd (mm).

  • phaseC_cen_range_px (float, default: 30.0 ) –

    Phase C bound on xcen / ycen (pixels).

  • phaseC_angle_range_deg (float, default: 0.5 ) –

    Phase C bound on xbet / xgam (degrees).

  • phaseC_U_range_deg (float, default: 3.0 ) –

    Phase C bound on orientation angles (degrees).

  • phaseC_options (dict or None, default: None ) –

    Extra options for the Phase C optimizer.

  • E_min, E_max (float) –

    Energy range (eV) shared by all phases. The allowed-HKL sphere cutoff is derived automatically from E_max.

  • verbose (bool, default: False ) –

    Print a one-line summary after each phase.

Returns:
  • CalibrationResult –

    CalibrationResult Result of Phase C (the final global refinement). Intermediate results are available via verbose=True output.

Source code in src/nrxrdct/laue/camera.py
    def fit_calibration_staged(
        self,
        crystal,
        U,
        obs_xy,
        *,
        # ── Phase A — stabilise geometry ─────────────────────────────────────
        phaseA_params=("dd", "xcen", "ycen", "xbet", "xgam"),
        phaseA_fit_U=False,
        phaseA_dd_range=5.0,
        phaseA_cen_range_px=100.0,
        phaseA_angle_range_deg=1.0,
        phaseA_U_range_deg=0.5,
        phaseA_options=None,
        # ── Phase B — refine orientation ─────────────────────────────────────
        phaseB_params=(),
        phaseB_fit_U=True,
        phaseB_U_range_deg=10.0,
        phaseB_options=None,
        # ── Phase C — global refinement ──────────────────────────────────────
        phaseC_params=("dd", "xcen", "ycen", "xbet", "xgam"),
        phaseC_fit_U=True,
        phaseC_dd_range=2.0,
        phaseC_cen_range_px=30.0,
        phaseC_angle_range_deg=0.5,
        phaseC_U_range_deg=3.0,
        phaseC_options=None,
        # ── shared ───────────────────────────────────────────────────────────
        E_min=5_000.0,
        E_max=27_000.0,
        source="bending_magnet",
        source_kwargs=None,
        f2_thresh=1e-6,
        max_match_px=20.0,
        top_n_sim=None,
        verbose=False,
    ) -> "CalibrationResult":
        """
        Three-phase staged calibration that alternates between geometry and
        orientation refinement for improved convergence.

        **Phase A — stabilise geometry**
            Refine camera geometry parameters with U fixed (or nearly fixed).
            Large initial bounds allow coarse corrections from the starting
            estimate; tight U bounds prevent orientation drift from corrupting
            the geometry.

        **Phase B — refine orientation**
            Fix the geometry from Phase A and refine the orientation matrix U.
            Geometry is now good enough that the spot pattern can guide U
            without the two coupled parameters fighting each other.

        **Phase C — global refinement**
            Refine geometry and U simultaneously, starting from the Phase B
            solution with tighter bounds.  Resolves the remaining correlation
            between small geometry shifts and orientation corrections.

        Args:
            crystal (Crystal): Calibration standard.
            U ((3, 3) array): Initial orientation matrix.
            obs_xy ((N, 2) array): Observed spot pixel positions.

            phaseA_params (sequence of str): Camera parameters to optimise in Phase A.
                Default: all five geometry parameters.
            phaseA_fit_U (bool): Allow a small orientation correction in Phase A.  Default False.
            phaseA_dd_range (float): Phase A bound on `dd` (mm, ± from starting value).
            phaseA_cen_range_px (float): Phase A bound on `xcen` / `ycen` (pixels).
            phaseA_angle_range_deg (float): Phase A bound on `xbet` / `xgam` (degrees).
            phaseA_U_range_deg (float): Phase A bound on orientation angles (degrees), only used when
                `phaseA_fit_U=True`.
            phaseA_options (dict or None): Extra options for the Phase A optimizer.

            phaseB_params (sequence of str): Camera parameters to optimise in Phase B.  Default: none
                (geometry frozen).
            phaseB_fit_U (bool): Refine U in Phase B.  Default True.
            phaseB_U_range_deg (float): Phase B bound on orientation angles (degrees).
            phaseB_options (dict or None): Extra options for the Phase B optimizer.

            phaseC_params (sequence of str): Camera parameters to optimise in Phase C.  Default: all five.
            phaseC_fit_U (bool): Refine U in Phase C.  Default True.
            phaseC_dd_range (float): Phase C bound on `dd` (mm).
            phaseC_cen_range_px (float): Phase C bound on `xcen` / `ycen` (pixels).
            phaseC_angle_range_deg (float): Phase C bound on `xbet` / `xgam` (degrees).
            phaseC_U_range_deg (float): Phase C bound on orientation angles (degrees).
            phaseC_options (dict or None): Extra options for the Phase C optimizer.

            E_min, E_max (float): Energy range (eV) shared by all phases.  The allowed-HKL
                sphere cutoff is derived automatically from `E_max`.
            source, source_kwargs, f2_thresh, max_match_px, top_n_sim
                Forwarded unchanged to each :meth:`fit_calibration` call.
            verbose (bool): Print a one-line summary after each phase.

        Returns:
            CalibrationResult
                Result of Phase C (the final global refinement).  Intermediate
                results are available via `verbose=True` output.
"""
        _shared = dict(
            E_min=E_min, E_max=E_max,
            source=source, source_kwargs=source_kwargs,
            f2_thresh=f2_thresh,
            max_match_px=max_match_px, top_n_sim=top_n_sim,
        )

        # ── Phase A ───────────────────────────────────────────────────────────
        res_A = self.fit_calibration(
            crystal, U, obs_xy,
            fit_params=phaseA_params,
            fit_U=phaseA_fit_U,
            dd_range=phaseA_dd_range,
            cen_range_px=phaseA_cen_range_px,
            angle_range_deg=phaseA_angle_range_deg,
            U_range_deg=phaseA_U_range_deg if phaseA_fit_U else None,
            options=phaseA_options,
            **_shared,
        )
        if verbose:
            print(f"Phase A (geometry):     {res_A}")

        # ── Phase B ───────────────────────────────────────────────────────────
        res_B = res_A.camera.fit_calibration(
            crystal, res_A.U, obs_xy,
            fit_params=phaseB_params,
            fit_U=phaseB_fit_U,
            U_range_deg=phaseB_U_range_deg if phaseB_fit_U else None,
            options=phaseB_options,
            **_shared,
        )
        if verbose:
            print(f"Phase B (orientation):  {res_B}")

        # ── Phase C ───────────────────────────────────────────────────────────
        res_C = res_B.camera.fit_calibration(
            crystal, res_B.U, obs_xy,
            fit_params=phaseC_params,
            fit_U=phaseC_fit_U,
            dd_range=phaseC_dd_range,
            cen_range_px=phaseC_cen_range_px,
            angle_range_deg=phaseC_angle_range_deg,
            U_range_deg=phaseC_U_range_deg if phaseC_fit_U else None,
            options=phaseC_options,
            **_shared,
        )
        if verbose:
            print(f"Phase C (global):       {res_C}")

        return res_C

from_det classmethod

from_det(path, pixelsize=None, framedim=None, kf_direction=None)

Read a LaueTools-compatible .det calibration file.

Parameters:
  • path (path - like) –

    Path to the .det file.

  • pixelsize (float or None, default: None ) –

    Override the pixel size (mm) read from the file.

  • framedim ((Nh, Nv) or None, default: None ) –

    Override the frame dimensions read from the file.

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

    Override the kf_direction read from the file.

Source code in src/nrxrdct/laue/camera.py
    @classmethod
    def from_det(cls, path, pixelsize=None, framedim=None, kf_direction=None):
        """
        Read a LaueTools-compatible `.det` calibration file.

        Args:
            path (path-like): Path to the `.det` file.
            pixelsize (float or None): Override the pixel size (mm) read from the file.
            framedim ((Nh, Nv) or None): Override the frame dimensions read from the file.
            kf_direction (str or None): Override the kf_direction read from the file.
"""
        from pathlib import Path

        lines = [
            ln.strip()
            for ln in Path(path).read_text().splitlines()
            if ln.strip() and not ln.strip().startswith("#")
        ]
        dd, xcen, ycen, xbet, xgam = map(float, lines[0].split())
        px = float(lines[1]) if pixelsize is None else float(pixelsize)
        if framedim is None:
            Nh, Nv = map(int, lines[2].split())
        else:
            Nh, Nv = int(framedim[0]), int(framedim[1])
        kfd = lines[3] if kf_direction is None else kf_direction
        return cls(
            dd=dd, xcen=xcen, ycen=ycen, xbet=xbet, xgam=xgam,
            pixelsize=px, n_pix_h=Nh, n_pix_v=Nv, kf_direction=kfd,
        )

from_lauetools classmethod

from_lauetools(calib, pixelsize=None, framedim=None, kf_direction='Z>0')

Build a Camera from a LaueTools calibration.

Parameters:
  • calib (list or array) –

    [dd, xcen, ycen, xbet, xgam] (= CCDCalibParameters in LaueTools)

  • pixelsize ((float, mm), default: None ) –

    (= xpixelsize in LaueTools dict)

  • framedim ((Nh, Nv), default: None ) –

    (= framedim in LaueTools dict)

  • kf_direction (str, default: 'Z>0' ) –

    (= kf_direction in LaueTools dict)

Source code in src/nrxrdct/laue/camera.py
    @classmethod
    def from_lauetools(cls, calib, pixelsize=None, framedim=None, kf_direction="Z>0"):
        """
        Build a Camera from a LaueTools calibration.

        Args:
            calib (list or array): [dd, xcen, ycen, xbet, xgam]
                (= CCDCalibParameters in LaueTools)
            pixelsize (float, mm): (= xpixelsize in LaueTools dict)
            framedim ((Nh, Nv)): (= framedim in LaueTools dict)
            kf_direction (str): (= kf_direction in LaueTools dict)
"""
        dd, xcen, ycen, xbet, xgam = calib[:5]
        px = pixelsize if pixelsize is not None else PIXEL_SIZE_MM
        Nh, Nv = framedim if framedim is not None else (N_PIX_H, N_PIX_V)
        return cls(
            dd=dd,
            xcen=xcen,
            ycen=ycen,
            xbet=xbet,
            xgam=xgam,
            pixelsize=px,
            n_pix_h=int(Nh),
            n_pix_v=int(Nv),
            kf_direction=kf_direction,
        )

kf_to_pixel

kf_to_pixel(uflab_arr)

Map scattered unit vectors to pixel coordinates. Implements LaueTools calc_xycam() for Z>0 geometry.

Parameters:
  • uflab_arr ((N, 3) array of unit scattered vectors in LT frame (x // beam)) –
Returns:
  • –

    xcam, ycam ((N,) arrays of pixel coordinates (float, sub-pixel precision)): Returns NaN for beams that miss the detector or go backward.

Source code in src/nrxrdct/laue/camera.py
    def kf_to_pixel(self, uflab_arr):
        """
        Map scattered unit vectors to pixel coordinates.
        Implements LaueTools calc_xycam() for Z>0 geometry.

        Args:
            uflab_arr ((N, 3) array of unit scattered vectors in LT frame (x // beam)):

        Returns:
            xcam, ycam ((N,) arrays of pixel coordinates (float, sub-pixel precision)): Returns NaN for beams that miss the detector or go backward.
"""
        # Convert LT -> LT2:  x_LT2 = -y_LT,  y_LT2 = x_LT,  z_LT2 = z_LT
        uf_lt = np.atleast_2d(np.array(uflab_arr, dtype=float))
        norms = np.linalg.norm(uf_lt, axis=1, keepdims=True)
        uf_lt = uf_lt / norms
        uf = np.column_stack([-uf_lt[:, 1], uf_lt[:, 0], uf_lt[:, 2]])

        scal = uf @ self.normal  # cos(angle between kf and detector normal)
        valid = scal > 1e-8
        normeIM = np.where(valid, self.dd / scal, np.nan)

        IMlab = uf * normeIM[:, None]
        OMlab = IMlab - self.IOlab

        xca0 = OMlab[:, 0]
        if abs(self._sinbeta) > 1e-8:
            yca0 = OMlab[:, 1] / self._sinbeta
        else:
            yca0 = -OMlab[:, 2] / self._cosbeta

        xcam1 = self._cosgam * xca0 + self._singam * yca0
        ycam1 = -self._singam * xca0 + self._cosgam * yca0

        xcam = self.xcen + xcam1 / self.pixel_mm
        ycam = self.ycen + ycam1 / self.pixel_mm

        xcam[~valid] = np.nan
        ycam[~valid] = np.nan
        return xcam, ycam

pixel_to_2theta_chi

pixel_to_2theta_chi(xcam, ycam)

Compute 2theta and chi (degrees) from pixel position.

Uses pixel_to_kf to obtain the scattered unit vector in the LT frame (x // beam), then:

2theta = arccos(uf_x)
chi    = arctan2(uf_y, uf_z)
Source code in src/nrxrdct/laue/camera.py
    def pixel_to_2theta_chi(self, xcam, ycam):
        """
        Compute 2theta and chi (degrees) from pixel position.

        Uses pixel_to_kf to obtain the scattered unit vector in the LT frame
        (x // beam), then:

            2theta = arccos(uf_x)
            chi    = arctan2(uf_y, uf_z)
"""
        uf_lt = self.pixel_to_kf([xcam], [ycam])[0]
        tth = np.degrees(np.arccos(np.clip(uf_lt[0], -1, 1)))
        chi = np.degrees(np.arctan2(uf_lt[1], uf_lt[2] + 1e-17))
        return tth, chi

pixel_to_kf

pixel_to_kf(xcam_arr, ycam_arr)

Map pixel coordinates to scattered unit vectors. Implements LaueTools calc_uflab() for Z>0 geometry.

Parameters:
  • xcam_arr, ycam_arr (array-like of pixel coordinates) –
Returns:
  • uflab( (N, 3) unit scattered vectors in LT frame ) –

    (x // ki)

Source code in src/nrxrdct/laue/camera.py
    def pixel_to_kf(self, xcam_arr, ycam_arr):
        """
        Map pixel coordinates to scattered unit vectors.
        Implements LaueTools calc_uflab() for Z>0 geometry.

        Args:
            xcam_arr, ycam_arr (array-like of pixel coordinates):

        Returns:
            uflab ((N, 3) unit scattered vectors in LT frame): (x // ki)
"""
        xcam1 = (np.asarray(xcam_arr, float) - self.xcen) * self.pixel_mm
        ycam1 = (np.asarray(ycam_arr, float) - self.ycen) * self.pixel_mm

        xca0 = self._cosgam * xcam1 - self._singam * ycam1
        yca0 = self._singam * xcam1 + self._cosgam * ycam1

        xO, yO, zO = self.IOlab
        xM = xO + xca0
        yM = yO + yca0 * self._sinbeta
        zM = zO - yca0 * self._cosbeta

        nIM = np.sqrt(xM**2 + yM**2 + zM**2)
        # Geometry is in LT2 frame (y // beam); convert to LT frame (x // beam):
        # x_LT = y_LT2,  y_LT = -x_LT2,  z_LT = z_LT2
        uflab_lt2 = np.array([xM, yM, zM]).T / nIM[:, None]
        uflab = np.column_stack([uflab_lt2[:, 1], -uflab_lt2[:, 0], uflab_lt2[:, 2]])
        return uflab

project

project(kf_hat, source_depth_mm: float = 0.0)

Project one scattered beam direction (in LT frame, x // beam) onto the detector. Returns (xcam, ycam) in pixels, or None if beam misses.

Parameters:
  • kf_hat –

    Unit scattered-beam vector in the LT frame.

  • source_depth_mm (float, default: 0.0 ) –

    Depth of the scattering centre below the surface along the incident beam direction (mm). Non-zero for layers buried beneath the sample surface — corrects the parallax shift that occurs when the scattering point is not at the nominal sample position. Default 0.0 (surface).

Source code in src/nrxrdct/laue/camera.py
    def project(self, kf_hat, source_depth_mm: float = 0.0):
        """
        Project one scattered beam direction (in LT frame, x // beam) onto
        the detector.  Returns (xcam, ycam) in pixels, or None if beam misses.

        Args:
            kf_hat: Unit scattered-beam vector in the LT frame.
            source_depth_mm: Depth of the scattering centre below the surface
                along the incident beam direction (mm).  Non-zero for layers
                buried beneath the sample surface — corrects the parallax
                shift that occurs when the scattering point is not at the
                nominal sample position.  Default ``0.0`` (surface).
"""
        # Convert LT -> LT2 for camera geometry
        kf_lt = np.array(kf_hat, dtype=float)
        kf_lt = kf_lt / np.linalg.norm(kf_lt)
        kf = np.array([-kf_lt[1], kf_lt[0], kf_lt[2]])  # LT2 frame
        scal = float(np.dot(kf, self.normal))
        if scal < 1e-8:
            return None
        # Depth correction: source displaced to (0, depth_mm, 0) in LT2 frame
        # (beam is along y in LT2).  normeIM = (dd − s·n̂) / scal.
        s_dot_n  = source_depth_mm * float(self.normal[1])
        normeIM  = (self.dd - s_dot_n) / scal
        IM = np.array([0.0, source_depth_mm, 0.0]) + kf * normeIM
        OM = IM - self.IOlab
        xca0 = OM[0]
        yca0 = (
            OM[1] / self._sinbeta
            if abs(self._sinbeta) > 1e-8
            else -OM[2] / self._cosbeta
        )
        xcam1 = self._cosgam * xca0 + self._singam * yca0
        ycam1 = -self._singam * xca0 + self._cosgam * yca0
        xcam = self.xcen + xcam1 / self.pixel_mm
        ycam = self.ycen + ycam1 / self.pixel_mm
        if 0 <= xcam < self.Nh and 0 <= ycam < self.Nv:
            return float(xcam), float(ycam)
        return None

project_batch

project_batch(kf_hat_arr, source_depth_mm: float = 0.0)

Vectorised :meth:project for N directions at once.

Parameters:
  • kf_hat_arr ((ndarray, shape(N, 3))) –

    Unit vectors in the LT frame (x // beam). Need not be pre-normalised — they are normalised internally.

  • source_depth_mm (float, default: 0.0 ) –

    Depth of the scattering centre below the surface along the beam direction (mm). See :meth:project.

Returns:
  • pix( (ndarray, shape(N, 2)) ) –

    Pixel coordinates (xcam, ycam). Rows for rays that miss the detector contain NaN.

  • on_det( ndarray, shape (N,), dtype bool ) –
Source code in src/nrxrdct/laue/camera.py
    def project_batch(self, kf_hat_arr, source_depth_mm: float = 0.0):
        """
        Vectorised :meth:`project` for N directions at once.

        Args:
            kf_hat_arr (ndarray, shape (N, 3)): Unit vectors in the LT frame (x // beam).  Need not be
                pre-normalised — they are normalised internally.
            source_depth_mm (float): Depth of the scattering centre below the
                surface along the beam direction (mm).  See :meth:`project`.

        Returns:
            pix (ndarray, shape (N, 2)): Pixel coordinates (xcam, ycam).  Rows for rays that miss the
                detector contain NaN.
            on_det (ndarray, shape (N,), dtype bool):
"""
        kf_lt = kf_hat_arr / np.linalg.norm(kf_hat_arr, axis=1, keepdims=True)
        kf = np.column_stack([-kf_lt[:, 1], kf_lt[:, 0], kf_lt[:, 2]])
        scal = kf @ self.normal
        hit = scal > 1e-8
        safe_scal = np.where(hit, scal, 1.0)
        # Depth correction: source at (0, depth_mm, 0) in LT2; dd_eff = dd − d·n̂[1]
        s_dot_n = source_depth_mm * self.normal[1]
        normeIM = (self.dd - s_dot_n) / safe_scal
        IM = np.array([0.0, source_depth_mm, 0.0]) + kf * normeIM[:, None]
        OM = IM - self.IOlab[None, :]
        xca0 = OM[:, 0]
        yca0 = (
            OM[:, 1] / self._sinbeta
            if abs(self._sinbeta) > 1e-8
            else -OM[:, 2] / self._cosbeta
        )
        xcam1 = self._cosgam * xca0 + self._singam * yca0
        ycam1 = -self._singam * xca0 + self._cosgam * yca0
        xcam = self.xcen + xcam1 / self.pixel_mm
        ycam = self.ycen + ycam1 / self.pixel_mm
        on_det = hit & (xcam >= 0) & (xcam < self.Nh) & (ycam >= 0) & (ycam < self.Nv)
        pix = np.empty((len(kf_hat_arr), 2), dtype=float)
        pix[:, 0] = xcam
        pix[:, 1] = ycam
        pix[~on_det] = np.nan
        return pix, on_det

render

render(spots, sigma_pix=SPOT_SIGMA_PIX, log_scale=False, normalize=False, upsample=4)

Render a synthetic detector image (float32, shape Nv x Nh).

Each spot's raw intensity (I_raw) is deposited at its nearest pixel on an upsampled grid (upsample sub-pixels per detector pixel), which recovers sub-pixel spot placement; the assembled upsampled image is then blurred once with an isotropic Gaussian and binned back down to the native detector resolution. By default the image is returned in raw intensity units with no scaling applied.

Parameters:
  • spots (list of dicts) –

    Spot list from any simulate_laue* function. Required keys: 'pix' (xcam, ycam), 'I_raw'. The key 'tth' (degrees) is required when sigma_pix is a callable or a broadening result dict.

  • sigma_pix (float | callable | dict, default: SPOT_SIGMA_PIX ) –

    Controls the Gaussian σ (pixels) used for the single whole-image blur:

  • log_scale (bool, default: False ) –

    Apply log1p compression before returning (default False).

  • normalize (bool, default: False ) –

    Divide by the image maximum after all other processing (default False).

  • upsample (int, default: 4 ) –

    Sub-pixel refinement factor (default 4). Spot positions are binned onto a grid upsample times finer than the detector before blurring, then the result is summed back down to native resolution. 1 disables the sub-pixel refinement (spots snap to the nearest native pixel).

Source code in src/nrxrdct/laue/camera.py
    def render(self, spots, sigma_pix=SPOT_SIGMA_PIX, log_scale=False, normalize=False, upsample=4):
        """
        Render a synthetic detector image (float32, shape Nv x Nh).

        Each spot's raw intensity (`I_raw`) is deposited at its nearest pixel
        on an *upsampled* grid (`upsample` sub-pixels per detector pixel),
        which recovers sub-pixel spot placement; the assembled upsampled
        image is then blurred once with an isotropic Gaussian and binned
        back down to the native detector resolution.  By default the image
        is returned in raw intensity units with no scaling applied.

        Args:
            spots (list of dicts): Spot list from any `simulate_laue*` function.
                Required keys: `'pix'` (xcam, ycam), `'I_raw'`.
                The key `'tth'` (degrees) is required when *sigma_pix* is a
                callable or a broadening result dict.
            sigma_pix (float | callable | dict): Controls the Gaussian σ (pixels)
                used for the single whole-image blur:

            * **float** *(default)*  — fixed width, used directly.
            * **callable** `f(tth_deg) → float` or `f(tth_deg, chi_deg) → float`
              — evaluated per spot as a function of 2θ (and, if the callable
              accepts a second positional argument, χ — auto-detected via
              its signature; requires the `'chi'` key on each spot), then
              averaged across all spots to obtain the single σ used for the
              whole-image blur.  Pass the `'model'` callable returned by
              :func:`~nrxrdct.laue.estimate_instrument_broadening`.
            * **dict** — the full result dict from
              :func:`~nrxrdct.laue.estimate_instrument_broadening`; the
              `'model'` key is extracted automatically and handled as above.

            log_scale (bool): Apply `log1p` compression before returning (default `False`).
            normalize (bool): Divide by the image maximum after all other processing
                (default `False`).
            upsample (int): Sub-pixel refinement factor (default `4`).  Spot
                positions are binned onto a grid `upsample` times finer than
                the detector before blurring, then the result is summed back
                down to native resolution.  `1` disables the sub-pixel
                refinement (spots snap to the nearest native pixel).
"""
        # Resolve broadening model
        if isinstance(sigma_pix, dict):
            _model = sigma_pix["model"]
            _fixed_sigma = None
        elif callable(sigma_pix):
            _model = sigma_pix
            _fixed_sigma = None
        else:
            _model = None
            _fixed_sigma = float(sigma_pix)

        _model_uses_chi = False
        if _model is not None:
            try:
                _model_uses_chi = len(inspect.signature(_model).parameters) >= 2
            except (TypeError, ValueError):
                _model_uses_chi = False

        upsample = int(upsample)
        if upsample < 1:
            raise ValueError("upsample must be >= 1")
        Nv_up, Nh_up = self.Nv * upsample, self.Nh * upsample

        img_up = np.zeros((Nv_up, Nh_up), dtype=np.float64)
        sigmas = []
        rows, cols, weights = [], [], []
        for s in spots:
            if s.get("pix") is None:
                continue

            if _model is not None:
                sigma = _model(s["tth"], s["chi"]) if _model_uses_chi else _model(s["tth"])
            else:
                sigma = _fixed_sigma
            if not (sigma > 0):
                continue

            c, r = s["pix"]  # xcam, ycam
            I_raw = s["I_raw"]
            if not (np.isfinite(c) and np.isfinite(r) and np.isfinite(I_raw)):
                continue

            ci, ri = int(round(c * upsample)), int(round(r * upsample))
            if not (0 <= ci < Nh_up and 0 <= ri < Nv_up):
                continue

            sigmas.append(sigma)
            rows.append(ri)
            cols.append(ci)
            weights.append(I_raw)

        if rows:
            np.add.at(img_up, (rows, cols), weights)
            sigma_avg = float(np.mean(sigmas))
            if sigma_avg > 0:
                img_up = np.clip(_fft_gauss_convolve(img_up, sigma_avg * upsample), 0.0, None)

        img = img_up.reshape(self.Nv, upsample, self.Nh, upsample).sum(axis=(1, 3))
        img = np.nan_to_num(img, nan=0.0, posinf=0.0, neginf=0.0)

        if log_scale:
            img = np.log1p(img)
        if normalize and img.max() > 0:
            img = img / img.max()
        return img.astype(np.float32)

to_det

to_det(path) -> None

Write a LaueTools-compatible .det calibration file.

Format (4 data lines, preceded by a comment header)::

# LaueTools camera calibration
# dd xcen ycen xbet xgam   pixelsize   Nh Nv   kf_direction
# Written: <ISO date>
dd xcen ycen xbet xgam
pixelsize
Nh Nv
kf_direction
Source code in src/nrxrdct/laue/camera.py
    def to_det(self, path) -> None:
        """
        Write a LaueTools-compatible `.det` calibration file.

        Format (4 data lines, preceded by a comment header)::

            # LaueTools camera calibration
            # dd xcen ycen xbet xgam   pixelsize   Nh Nv   kf_direction
            # Written: <ISO date>
            dd xcen ycen xbet xgam
            pixelsize
            Nh Nv
            kf_direction
"""
        import datetime
        from pathlib import Path

        header = (
            "# LaueTools camera calibration\n"
            "# dd(mm)  xcen(px)  ycen(px)  xbet(deg)  xgam(deg)"
            "   pixelsize(mm)   Nh Nv   kf_direction\n"
            f"# Written: {datetime.date.today().isoformat()}\n"
        )
        data = (
            f"{self.dd:.6g} {self.xcen:.6g} {self.ycen:.6g} "
            f"{self.xbet:.6g} {self.xgam:.6g}\n"
            f"{self.pixel_mm:.6g}\n"
            f"{self.Nh} {self.Nv}\n"
            f"{self.kf_direction}\n"
        )
        Path(path).write_text(header + data)

tth_grid

tth_grid(step=None)

Return a 2theta map over the whole detector (shape Nv x Nh). Useful for contour overlays on detector images.

Source code in src/nrxrdct/laue/camera.py
    def tth_grid(self, step=None):
        """
        Return a 2theta map over the whole detector (shape Nv x Nh).
        Useful for contour overlays on detector images.
"""
        if step is None:
            step = max(1, self.Nh // 40)
        cs = np.arange(0, self.Nh, step)
        rs = np.arange(0, self.Nv, step)
        CC, RR = np.meshgrid(cs, rs)
        uf = self.pixel_to_kf(CC.ravel(), RR.ravel())
        TTH = np.degrees(np.arccos(np.clip(uf[:, 0], -1, 1))).reshape(CC.shape)
        return CC, RR, TTH