layers

nrxrdct.laue.layers

layered_structure_factor.py

Model a stack of crystalline layers with known orientation relationships (OR) and compute the total kinematical structure factor \(F(\mathbf{Q})\) and intensity \(|F(\mathbf{Q})|^2\).

Physics

In the kinematical (Born) approximation the total scattered amplitude is the coherent sum of contributions from every unit cell in the stack:

\[ A(\mathbf{Q}) = \sum_l F_l(\mathbf{Q}^\text{cry}_l) \cdot \sum_{n=0}^{N_l-1} \exp(i\,\mathbf{Q}\cdot\mathbf{R}_{l,n}) \]

where

  • \(\mathbf{Q}\) — scattering vector in the lab frame (Å⁻¹)
  • \(\mathbf{Q}^\text{cry}_l = U_l^T\,\mathbf{Q}\) — \(\mathbf{Q}\) expressed in the crystal frame of layer \(l\)
  • \(F_l(\mathbf{Q}^\text{cry})\) — unit-cell structure factor of layer \(l\), computed by xrayutilities with energy-dependent Cromer–Mann + Henke anomalous scattering factors
  • \(\mathbf{R}_{l,n} = z_{0,l}\,\hat{z} + n\,c_l\,\hat{z}\) — position of the \(n\)-th unit cell of layer \(l\) (1-D stacking along \(\hat{z}\))
  • \(z_{0,l}\) — cumulative thickness of all layers below layer \(l\)

The geometric sum \(\sum_n \exp(in\varphi)\) is evaluated analytically:

\[ \frac{1 - \exp(iN\varphi)}{1 - \exp(i\varphi)} \quad \text{if } \varphi \bmod 2\pi \neq 0, \qquad N \text{ otherwise.} \]

For a superlattice with \(N_\text{rep}\) bilayer repetitions an additional geometric factor is applied over the full bilayer period \(\Lambda\).

Orientation relationship

The orientation \(U\) of each layer maps crystal-frame vectors to the lab frame:

\[ \mathbf{G}_\text{lab} = U\,\mathbf{G}_\text{crystal} \]

orientation_along_z builds \(U\) from a real-space zone axis [uvw]; orientation_along_plane builds it from a Miller plane (hkl) instead -- required for any growth surface whose normal is not parallel to the same-index real-space direction, which is always true away from cubic crystals and hexagonal c-axis growth (in particular, hexagonal m-plane and a-plane growth). See that function's docstring and the "Non-c-axis / m-plane stacking" section of the layered-structures user guide for the underlying geometry.

The OR between two phases A and B is specified by two direction pairs (primary and secondary), defining a rotation \(R_\text{OR}\) such that \(U_B = R_\text{OR}\,U_A\).

Common ORs implemented as helpers:

  • or_nishiyama_wassermann (NW) — FCC/BCC
  • or_kurdjumov_sachs (KS) — FCC/BCC
  • or_baker_nutting (BN) — BCC/rock-salt (e.g. Fe/MgO)
  • or_from_directions — generic two-direction specification

Usage

from layered_structure_factor import LayeredCrystal, or_kurdjumov_sachs
import xrayutilities as xu
import numpy as np

Fe = xu.materials.Fe
Cu = xu.materials.Cu

# Orient Fe with [001] along the stacking direction (lab z)
U_Fe = orientation_along_z([0, 0, 1], Fe)

# Derive Cu orientation via Kurdjumov-Sachs OR
U_Cu = or_kurdjumov_sachs(Fe, Cu) @ U_Fe

# Build the stack: 20 Fe unit cells / 20 Cu unit cells, 5 repetitions
stack = LayeredCrystal()
stack.add_layer(Fe, U_Fe, thickness=57.4, label='Fe')   # ~20 cells × 2.87 Å
stack.add_layer(Cu, U_Cu, thickness=72.6, label='Cu')   # ~20 cells × 3.63 Å
stack.set_repetitions(5)

# Compute |F(Q)|² along a scan
qz = np.linspace(1.0, 6.0, 4000)
Q_scan = np.column_stack([np.zeros_like(qz),
                          np.zeros_like(qz), qz])   # along lab z
intensity = stack.intensity(Q_scan, energy_eV=17000)

# Or single Q-point
Q = np.array([0., 0., 3.09])
F  = stack.structure_factor(Q, energy_eV=17000)
print(f'|F(Q)| = {abs(F):.4f} e.u.')

Layer

One crystalline layer in the stack.

Parameters:
  • crystal (Crystal) –
  • U ((3,3) orientation matrix) –

    G_lab = U @ G_crystal

  • thickness (float) –

    physical thickness of the layer in Å

  • n_hat (array - like(3), default: None ) –

    Unit vector in the lab frame that defines the stacking / growth direction (= sample-surface normal). Defaults to [0, 0, 1] (lab Z), which is correct when U was obtained from orientation_along_z. When U comes from a Laue indexation result, pass the growth-direction vector explicitly: n_hat = U @ growth_dir_crystal / np.linalg.norm(...).

  • d_spacing (float, default: None ) –

    Repeat distance along the stacking direction (Å). If None, found automatically via shortest_lattice_vector(U.T @ n_hat, crystal) -- the length of the shortest real lattice translation parallel to the stacking direction (not simply an interplanar spacing d_hkl: for m-plane hexagonal growth in particular these differ by a factor of 2, see that function's docstring). Raises ValueError if no such lattice vector is found within its default search range, in which case pass d_spacing explicitly.

  • label (str, default: None ) –

    name for this layer

  • absorption_limit (bool, default: False ) –

    When True, the effective thickness used in the structure-factor sum is capped at the absorption length 1/μ (energy-dependent). Set automatically for buffer/substrate layers by :meth:LayeredCrystal.add_buffer_layer. Default False.

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

    Manual override for the linear absorption coefficient μ (Å⁻¹) at any energy. When set, :meth:_linear_mu returns this value directly and skips the automatic xrayutilities / StructureFactor lookup. Useful for alloy materials (InGaN, AlGaN) built from CIF files where the automatic lookup may fail or return zero. Set to 0.0 to disable absorption for this layer entirely. Default None (use automatic lookup).

Source code in src/nrxrdct/laue/layers.py
 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
class Layer:
    """
    One crystalline layer in the stack.

    Args:
        crystal (xu.materials.Crystal):
        U ((3,3) orientation matrix): G_lab = U @ G_crystal
        thickness (float): physical thickness of the layer in Å
        n_hat (array-like (3,), optional): Unit vector in the **lab frame** that defines the stacking / growth
            direction (= sample-surface normal).  Defaults to `[0, 0, 1]`
            (lab Z), which is correct when `U` was obtained from
            `orientation_along_z`.  When `U` comes from a Laue indexation
            result, pass the growth-direction vector explicitly:
            `n_hat = U @ growth_dir_crystal / np.linalg.norm(...)`.

        The growth direction always coincides with the sample-surface normal
        (the plane given as `growth_crystal` is parallel to the sample
        surface).  The angle between the incident beam (LT-frame x-axis,
        `[1,0,0]`) and this vector is therefore fixed by the sample
        mounting and is used to correct the Beer-Lambert absorption depth
        when `absorption_limit=True`.
        d_spacing (float, optional): Repeat distance along the stacking direction (Å).
            If `None`, found automatically via
            `shortest_lattice_vector(U.T @ n_hat, crystal)` -- the length of
            the shortest real lattice translation parallel to the stacking
            direction (not simply an interplanar spacing `d_hkl`: for m-plane
            hexagonal growth in particular these differ by a factor of 2,
            see that function's docstring). Raises `ValueError` if no such
            lattice vector is found within its default search range, in
            which case pass `d_spacing` explicitly.
        label (str, optional): name for this layer
        absorption_limit (bool, optional): When ``True``, the effective
            thickness used in the structure-factor sum is capped at the
            absorption length ``1/μ`` (energy-dependent).  Set automatically
            for buffer/substrate layers by
            :meth:`LayeredCrystal.add_buffer_layer`.  Default ``False``.
        mu_Ang (float or None, optional): Manual override for the linear
            absorption coefficient μ (Å⁻¹) at any energy.  When set,
            :meth:`_linear_mu` returns this value directly and skips the
            automatic xrayutilities / ``StructureFactor`` lookup.  Useful
            for alloy materials (InGaN, AlGaN) built from CIF files where
            the automatic lookup may fail or return zero.  Set to ``0.0``
            to disable absorption for this layer entirely.  Default ``None``
            (use automatic lookup).
"""

    def __init__(
        self,
        crystal,
        U,
        thickness,
        n_hat=None,
        d_spacing=None,
        label=None,
        absorption_limit=False,
        mu_Ang=None,
    ):
        self.crystal = crystal
        self.U = np.asarray(U, dtype=float)
        self.label = label or crystal.name
        # When True, structure_factor uses an energy-dependent effective thickness
        # min(real thickness, 1/μ) to model Beer-Lambert absorption depth.
        # Set automatically for buffer layers by LayeredCrystal.add_buffer_layer.
        self.absorption_limit = bool(absorption_limit)
        # Optional manual override for the linear absorption coefficient (Å⁻¹).
        # When set, _linear_mu() returns this value directly without any
        # xrayutilities lookup — useful for alloy materials (InGaN, AlGaN) where
        # the automatic lookup may fail.  Set to 0.0 to disable absorption for
        # this layer.  Example: layer.mu_Ang = 3.5e-5
        self.mu_Ang = float(mu_Ang) if mu_Ang is not None else None

        if n_hat is None:
            self.n_hat = np.array([0.0, 0.0, 1.0])
        else:
            nh = np.asarray(n_hat, dtype=float)
            self.n_hat = nh / np.linalg.norm(nh)

        if d_spacing is not None:
            self.d = float(d_spacing)
        else:
            # Find the real-space repeat along the stacking direction n_hat:
            # the geometric sum uses phase φ = (Q · n_hat) · d, so d must be
            # the length of the *shortest actual lattice translation* parallel
            # to n_hat -- only then does each step reproduce an identical
            # atomic arrangement, so the same F_uc legitimately applies to
            # every step (see shortest_lattice_vector's docstring for why a
            # single-primitive-vector projection is not enough in general,
            # e.g. for a hexagonal m-plane normal, which is parallel to
            # 2*a1+a2 rather than any individual a_i).
            n_hat_crystal = self.U.T @ self.n_hat
            T, length = shortest_lattice_vector(n_hat_crystal, crystal)
            if T is None:
                raise ValueError(
                    f"Layer {self.label!r}: no real lattice vector of "
                    f"{crystal.name} within ±8 primitive-cell steps is "
                    f"parallel to the stacking direction n_hat={self.n_hat}. "
                    f"This growth direction may be crystallographically "
                    f"irrational for this lattice (e.g. a semipolar plane), "
                    f"or need a larger search range -- pass d_spacing "
                    f"explicitly (e.g. from d_spacing_hkl, if a single "
                    f"interplanar spacing is physically the right repeat "
                    f"here), or call shortest_lattice_vector(n_hat_crystal, "
                    f"crystal, max_index=...) yourself with a larger range."
                )
            self.d = length

        self._thickness = float(thickness)
        self.n_cells = max(1, round(self._thickness / self.d))

    @property
    def thickness(self):
        """
        Total layer thickness in Å -- exactly the value passed to the
        constructor.

        All geometric bookkeeping (block/buffer z-offsets, period lengths,
        `total_thickness`, absorption-depth placement) uses this exact
        value.  It generally differs slightly from `n_cells * d`, since
        the requested thickness need not be an integer multiple of the
        unit-cell repeat `d`: the *coherent structure-factor sum* still
        runs over the nearest integer number of cells (`n_cells`), but
        every position/period calculation is anchored to the thickness you
        asked for, not to its lattice-quantised approximation.
"""
        return self._thickness

    def _linear_mu(self, energy_eV: float) -> float:
        """
        Linear absorption coefficient μ (Å⁻¹) for this material at *energy_eV*.

        Lookup order:
        1. ``self.mu_Ang`` — direct user override (set on the Layer instance).
        2. ``crystal.delta_beta(energy_eV)`` — works for named xrayutilities
           materials (e.g. Si, Al2O3).
        3. ``Im(F(Q=0)) / V_uc`` via ``crystal.StructureFactor`` — works for
           any crystal whose constituent elements have Henke f'' tables, which
           covers all standard III-nitrides and oxides built from CIF files.

        Returns 0.0 only when all three paths fail.

        Memoised to the nearest eV: paths 2-3 each hit xrayutilities'
        (h5py-backed) atomic database, and μ(E) is smooth on an eV scale, so
        callers that sweep many close-by candidate energies (e.g. one Bragg
        peak's harmonic series) don't re-pay that lookup for each one.
"""
        _HC_ANG = 12398.419843

        # 1. Manual override
        if self.mu_Ang is not None:
            return float(self.mu_Ang)

        cache = self.__dict__.setdefault("_mu_cache", {})
        key = round(float(energy_eV))
        cached = cache.get(key)
        if cached is not None:
            return cached
        mu = self._linear_mu_uncached(energy_eV)
        cache[key] = mu
        return mu

    def _linear_mu_uncached(self, energy_eV: float) -> float:
        _HC_ANG = 12398.419843

        # 2. xrayutilities delta_beta (named materials)
        try:
            if hasattr(self.crystal, "delta_beta"):
                _, beta = self.crystal.delta_beta(energy_eV)
            else:
                elem = getattr(xu.materials.elements, self.crystal.name, None)
                if elem is None or not getattr(elem, "density", 0):
                    raise ValueError("no element")
                mat = xu.materials.Amorphous(self.crystal.name, elem.density)
                _, beta = mat.delta_beta(energy_eV)
            if beta > 0:
                lam_ang = _HC_ANG / energy_eV
                return float(4.0 * np.pi * beta / lam_ang)
        except Exception:
            pass

        # 3. Im(F(Q=0)) / V_uc — works for any crystal with Henke f'' data.
        # Physical basis:  mu = 2 r_e lambda Im(F_uc(0)) / V_uc
        # where F_uc(0) = Σ_i (Z_i + f'_i + i f''_i) sums over all atoms in
        # the unit cell and V_uc is the unit cell volume in ų.
        try:
            F0 = complex(self.crystal.StructureFactor([0.0, 0.0, 0.0],
                                                      en=energy_eV))
            if F0.imag > 0:
                lat = self.crystal.lattice
                ca = np.cos(np.radians(float(lat.alpha)))
                cb = np.cos(np.radians(float(lat.beta)))
                cg = np.cos(np.radians(float(lat.gamma)))
                V = (float(lat.a) * float(lat.b) * float(lat.c)
                     * np.sqrt(max(0.0,
                                   1.0 - ca**2 - cb**2 - cg**2
                                   + 2.0*ca*cb*cg)))
                if V > 0:
                    r_e = 2.8179403e-5       # Å
                    lam_ang = _HC_ANG / energy_eV
                    mu = 2.0 * r_e * lam_ang * F0.imag / V
                    if mu > 0:
                        return float(mu)
        except Exception:
            pass

        return 0.0

    def _effective_n_cells(self, energy_eV: float, kf_hat=None) -> int:
        """
        Effective number of unit cells after Beer-Lambert absorption limiting.

        With only the incident beam considered (`kf_hat=None`):

            n_eff = cos_in / (μ · d)

            cos_in = |n̂ · x̂| = |n_hat[0]|

        When the diffracted-beam direction `kf_hat` is supplied, the
        **two-beam** formula accounts for both the incident and exit paths
        through the layer:

            n_eff = cos_in · cos_out / (μ · d · (cos_in + cos_out))

            cos_out = |n̂ · k̂_f|

        This is equivalent to using an effective linear attenuation

            μ_eff = μ · (1/cos_in + 1/cos_out)

        which is the standard symmetric absorption correction used in
        surface-diffraction and thin-film rocking-curve analysis.

        Returns `self.n_cells` unchanged if the material lookup fails or if
        the absorption depth exceeds the real layer thickness.
"""
        mu = self._linear_mu(energy_eV)
        if mu <= 0:
            # Absorption lookup failed (e.g. custom CIF crystal, older xrayutilities).
            # Fall back to a conservative 1e-3 Å⁻¹ rather than returning raw n_cells:
            # for thick substrates raw n_cells would be ~10⁶ and would dominate the
            # stack structure factor, setting auto-scaled thresholds far too high.
            mu = 1e-3  # Å⁻¹ — conservative hard-X-ray value; keeps n_eff physically sane

        cos_in = max(abs(float(self.n_hat[0])), 1e-3)

        if kf_hat is not None:
            kf = np.asarray(kf_hat, dtype=float)
            cos_out = max(abs(float(np.dot(self.n_hat, kf))), 1e-3)
            n_eff = int(min(self.n_cells,
                           cos_in * cos_out / (mu * self.d * (cos_in + cos_out))))
        else:
            n_eff = int(min(self.n_cells, cos_in / (mu * self.d)))

        return max(n_eff, 1)

    def structure_factor(self, Q_lab, energy_eV, z0=0.0, kf_hat=None):
        """
        Kinematical structure factor of this layer at scattering vector Q_lab.

        F_layer(Q) = F_uc(Q_crystal) · Σ_{n=0}^{N-1} exp(i (Q·n̂)(z0 + n·d))

        The phase uses the projection of Q onto the stacking direction `n_hat`
        (not Q_z), so the result is correct for any sample orientation.

        Args:
            Q_lab (array-like (3,)): scattering vector in lab frame  (Å⁻¹)
            energy_eV: float             photon energy  (eV)
            z0 (float): cumulative offset along n_hat (Å)

        Returns:
            F (complex): kinematical structure factor (electron units)
"""
        Q = np.asarray(Q_lab, dtype=float)

        # Q in crystal frame
        Q_cry = self.U.T @ Q

        # Unit-cell structure factor (Cromer-Mann + anomalous)
        F_uc = self.crystal.StructureFactor(Q_cry, en=energy_eV)
        if not (np.isfinite(F_uc.real) and np.isfinite(F_uc.imag)):
            return 0.0 + 0j  # Q outside Cromer-Mann range

        # Projection of Q onto the stacking direction
        Qn = float(np.dot(Q, self.n_hat))
        phi = Qn * self.d

        # Effective cell count: limited by absorption depth for buffer layers.
        # kf_hat enables the two-beam (incident + exit) correction.
        n_eff = (
            self._effective_n_cells(energy_eV, kf_hat=kf_hat)
            if self.absorption_limit
            else self.n_cells
        )

        phi_mod = phi % (2.0 * np.pi)
        if abs(phi_mod) < 1e-10 or abs(phi_mod - 2 * np.pi) < 1e-10:
            geo_sum = n_eff + 0j
        else:
            geo_sum = (1.0 - np.exp(1j * n_eff * phi)) / (1.0 - np.exp(1j * phi))

        phase_z0 = np.exp(1j * Qn * z0)
        return F_uc * phase_z0 * geo_sum

    # ── Vectorised (batch-Q) counterparts ─────────────────────────────────────
    # Same physics as structure_factor/_effective_n_cells above, evaluated for
    # many Q (and, optionally, many kf_hat) at once against a **single**
    # reference energy — the one approximation relative to the scalar path,
    # justified because f'(E)/f''(E) anomalous dispersion is smooth away from
    # absorption edges.  Everything else (Q-dependence, geometry, absorption
    # depth) is exact.  Used by :func:`~nrxrdct.laue.simulation.qspace_around_spot`
    # to replace thousands of scalar xrayutilities calls with one per layer.

    def _structure_factor_uc_batch(self, Q_lab_arr, energy_eV):
        """Vectorised unit-cell structure factor `F_uc(Q)` at one energy."""
        Q_cry_arr = Q_lab_arr @ self.U  # == (self.U.T @ Q) per row
        F_uc = np.asarray(
            self.crystal.StructureFactorForQ(Q_cry_arr, en0=energy_eV), dtype=complex
        )
        bad = ~(np.isfinite(F_uc.real) & np.isfinite(F_uc.imag))
        if np.any(bad):
            F_uc = np.where(bad, 0.0 + 0j, F_uc)
        return F_uc

    def _effective_n_cells_batch(self, energy_eV, kf_hat_arr=None, n_points=None):
        """Vectorised :meth:`_effective_n_cells`."""
        mu = self._linear_mu(energy_eV)
        if mu <= 0:
            mu = 1e-3
        cos_in = max(abs(float(self.n_hat[0])), 1e-3)
        if kf_hat_arr is not None:
            cos_out = np.maximum(np.abs(kf_hat_arr @ self.n_hat), 1e-3)
            n_eff = cos_in * cos_out / (mu * self.d * (cos_in + cos_out))
        else:
            n_eff = np.full(n_points, cos_in / (mu * self.d))
        n_eff = np.minimum(float(self.n_cells), n_eff)
        n_eff = np.maximum(n_eff.astype(int), 1)
        return n_eff.astype(float)

    def structure_factor_batch(self, Q_lab_arr, energy_eV, z0=0.0, kf_hat_arr=None):
        """
        Vectorised :meth:`structure_factor` for many `Q_lab` (and, optionally,
        many `kf_hat`) at once, evaluated against a single reference energy.

        Args:
            Q_lab_arr (ndarray, shape (N, 3)): Scattering vectors in the lab frame (Å⁻¹).
            energy_eV (float): Reference photon energy (eV) — see the class-level note above.
            z0 (float): Cumulative offset along `n_hat` (Å), same for every row.
            kf_hat_arr (ndarray, shape (N, 3) or None): Per-voxel diffracted-beam unit vectors for the two-beam
                absorption correction; `None` uses the one-beam correction.

        Returns:
            ndarray, shape (N,), complex.
"""
        Q_lab_arr = np.asarray(Q_lab_arr, dtype=float)
        n = len(Q_lab_arr)
        F_uc = self._structure_factor_uc_batch(Q_lab_arr, energy_eV)
        Qn = Q_lab_arr @ self.n_hat
        phi = Qn * self.d
        n_eff = (
            self._effective_n_cells_batch(energy_eV, kf_hat_arr=kf_hat_arr, n_points=n)
            if self.absorption_limit
            else np.full(n, float(self.n_cells))
        )
        geo_sum = _geometric_sum_batch(n_eff, phi)
        phase_z0 = np.exp(1j * Qn * z0)
        return F_uc * phase_z0 * geo_sum

    def __repr__(self):
        return (
            f"Layer('{self.label}', {self.thickness:.2f} Å"
            f" ({self.n_cells} cells × {self.d:.4f} Å))"
        )

thickness property

thickness

Total layer thickness in Å -- exactly the value passed to the constructor.

All geometric bookkeeping (block/buffer z-offsets, period lengths, total_thickness, absorption-depth placement) uses this exact value. It generally differs slightly from n_cells * d, since the requested thickness need not be an integer multiple of the unit-cell repeat d: the coherent structure-factor sum still runs over the nearest integer number of cells (n_cells), but every position/period calculation is anchored to the thickness you asked for, not to its lattice-quantised approximation.

structure_factor

structure_factor(Q_lab, energy_eV, z0=0.0, kf_hat=None)

Kinematical structure factor of this layer at scattering vector Q_lab.

F_layer(Q) = F_uc(Q_crystal) · Σ_{n=0}^{N-1} exp(i (Q·n̂)(z0 + n·d))

The phase uses the projection of Q onto the stacking direction n_hat (not Q_z), so the result is correct for any sample orientation.

Parameters:
  • Q_lab (array - like(3)) –

    scattering vector in lab frame (Å⁻¹)

  • energy_eV –

    float photon energy (eV)

  • z0 (float, default: 0.0 ) –

    cumulative offset along n_hat (Å)

Returns:
  • F( complex ) –

    kinematical structure factor (electron units)

Source code in src/nrxrdct/laue/layers.py
    def structure_factor(self, Q_lab, energy_eV, z0=0.0, kf_hat=None):
        """
        Kinematical structure factor of this layer at scattering vector Q_lab.

        F_layer(Q) = F_uc(Q_crystal) · Σ_{n=0}^{N-1} exp(i (Q·n̂)(z0 + n·d))

        The phase uses the projection of Q onto the stacking direction `n_hat`
        (not Q_z), so the result is correct for any sample orientation.

        Args:
            Q_lab (array-like (3,)): scattering vector in lab frame  (Å⁻¹)
            energy_eV: float             photon energy  (eV)
            z0 (float): cumulative offset along n_hat (Å)

        Returns:
            F (complex): kinematical structure factor (electron units)
"""
        Q = np.asarray(Q_lab, dtype=float)

        # Q in crystal frame
        Q_cry = self.U.T @ Q

        # Unit-cell structure factor (Cromer-Mann + anomalous)
        F_uc = self.crystal.StructureFactor(Q_cry, en=energy_eV)
        if not (np.isfinite(F_uc.real) and np.isfinite(F_uc.imag)):
            return 0.0 + 0j  # Q outside Cromer-Mann range

        # Projection of Q onto the stacking direction
        Qn = float(np.dot(Q, self.n_hat))
        phi = Qn * self.d

        # Effective cell count: limited by absorption depth for buffer layers.
        # kf_hat enables the two-beam (incident + exit) correction.
        n_eff = (
            self._effective_n_cells(energy_eV, kf_hat=kf_hat)
            if self.absorption_limit
            else self.n_cells
        )

        phi_mod = phi % (2.0 * np.pi)
        if abs(phi_mod) < 1e-10 or abs(phi_mod - 2 * np.pi) < 1e-10:
            geo_sum = n_eff + 0j
        else:
            geo_sum = (1.0 - np.exp(1j * n_eff * phi)) / (1.0 - np.exp(1j * phi))

        phase_z0 = np.exp(1j * Qn * z0)
        return F_uc * phase_z0 * geo_sum

structure_factor_batch

structure_factor_batch(Q_lab_arr, energy_eV, z0=0.0, kf_hat_arr=None)

Vectorised :meth:structure_factor for many Q_lab (and, optionally, many kf_hat) at once, evaluated against a single reference energy.

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

    Scattering vectors in the lab frame (Å⁻¹).

  • energy_eV (float) –

    Reference photon energy (eV) — see the class-level note above.

  • z0 (float, default: 0.0 ) –

    Cumulative offset along n_hat (Å), same for every row.

  • kf_hat_arr ((ndarray, shape(N, 3) or None), default: None ) –

    Per-voxel diffracted-beam unit vectors for the two-beam absorption correction; None uses the one-beam correction.

Returns:
  • –

    ndarray, shape (N,), complex.

Source code in src/nrxrdct/laue/layers.py
    def structure_factor_batch(self, Q_lab_arr, energy_eV, z0=0.0, kf_hat_arr=None):
        """
        Vectorised :meth:`structure_factor` for many `Q_lab` (and, optionally,
        many `kf_hat`) at once, evaluated against a single reference energy.

        Args:
            Q_lab_arr (ndarray, shape (N, 3)): Scattering vectors in the lab frame (Å⁻¹).
            energy_eV (float): Reference photon energy (eV) — see the class-level note above.
            z0 (float): Cumulative offset along `n_hat` (Å), same for every row.
            kf_hat_arr (ndarray, shape (N, 3) or None): Per-voxel diffracted-beam unit vectors for the two-beam
                absorption correction; `None` uses the one-beam correction.

        Returns:
            ndarray, shape (N,), complex.
"""
        Q_lab_arr = np.asarray(Q_lab_arr, dtype=float)
        n = len(Q_lab_arr)
        F_uc = self._structure_factor_uc_batch(Q_lab_arr, energy_eV)
        Qn = Q_lab_arr @ self.n_hat
        phi = Qn * self.d
        n_eff = (
            self._effective_n_cells_batch(energy_eV, kf_hat_arr=kf_hat_arr, n_points=n)
            if self.absorption_limit
            else np.full(n, float(self.n_cells))
        )
        geo_sum = _geometric_sum_batch(n_eff, phi)
        phase_z0 = np.exp(1j * Qn * z0)
        return F_uc * phase_z0 * geo_sum

LayeredCrystal

A stack of crystalline layers with specified orientations, optionally repeated as a superlattice.

The stacking direction is a lab-frame unit vector n_hat (default [0, 0, 1], i.e. lab Z). All phase calculations use the projection Q · n_hat rather than Q_z, so the structure factor is correct regardless of how the sample sits on the diffractometer.

Parameters:
  • name (str, default: 'layered_crystal' ) –
  • stacking_direction (array - like(3), default: None ) –

    Unit vector in the lab frame defining the growth / stacking direction (sample-surface normal).

Source code in src/nrxrdct/laue/layers.py
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
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
class LayeredCrystal:
    """
    A stack of crystalline layers with specified orientations,
    optionally repeated as a superlattice.

    The stacking direction is a lab-frame unit vector `n_hat` (default
    `[0, 0, 1]`, i.e. lab Z).  All phase calculations use the projection
    `Q · n_hat` rather than `Q_z`, so the structure factor is correct
    regardless of how the sample sits on the diffractometer.

    Args:
        name (str, optional):
        stacking_direction (array-like (3,), optional): Unit vector in the **lab frame** defining the growth / stacking
            direction (sample-surface normal).

        - When all `U` matrices come from `orientation_along_z`, the
          stacking direction is lab Z and the default `[0, 0, 1]` is correct.
        - When `U` comes from a Laue indexation result, pass the actual
          growth direction:  `stacking_direction = U @ growth_dir_crystal`
          (e.g. `U @ [0, 0, 1]` for GaN grown along its c-axis).

        **Example — using orientation_along_z (default n_hat = Z)**
        >>> stack = LayeredCrystal(name='Fe/Cu KS superlattice')
        >>> stack.add_layer(Fe, U_Fe, thickness=57.4, label='Fe')
        >>> stack.add_layer(Cu, U_Cu, thickness=72.6, label='Cu')
        >>> stack.set_repetitions(10)

        **Example — using a U matrix from Laue indexation (GaN grown along c)**
        >>> n_hat = U_GaN @ np.array([0., 0., 1.])   # growth dir in lab frame
        >>> stack = LayeredCrystal(name='GaN/InGaN', stacking_direction=n_hat)
        >>> stack.add_layer(GaN,   U_GaN,   thickness=51800.0, label='GaN')    # ~1000 cells
        >>> stack.add_layer(InGaN, U_InGaN, thickness=259.0,   label='InGaN')  # ~50 cells

"""

    def __init__(self, name="layered_crystal", stacking_direction=None):
        self.name = name
        self.buffer_layers = []   # non-repeating layers (substrate, buffer) — bottom of stack
        self._blocks = []         # repeating blocks (bottom to top), each a _RepeatBlock
        self._buffer_z_offsets = []
        self._buffer_thickness = 0.0

        if stacking_direction is None:
            self.n_hat = np.array([0.0, 0.0, 1.0])
        else:
            nh = np.asarray(stacking_direction, dtype=float)
            self.n_hat = nh / np.linalg.norm(nh)

    # ── Building the stack ────────────────────────────────────────────────────

    def add_buffer_layer(self, crystal, U, thickness, d_spacing=None, label=None):
        """
        Append a **non-repeating** layer at the bottom of the stack (substrate
        side), below every repeating block.

        Buffer layers are always added in order from deepest to shallowest:
        the first call places the layer closest to the substrate, subsequent
        calls place layers closer to the surface.

        Args:
            crystal (xu.materials.Crystal):
            U ((3,3) orientation matrix): G_lab = U @ G_crystal
            thickness (float): physical thickness of the layer in Å
            d_spacing (float, optional): stacking repeat distance (Å)
            label (str, optional):
"""
        layer = Layer(
            crystal,
            U,
            thickness,
            n_hat=self.n_hat,
            d_spacing=d_spacing,
            label=label,
            absorption_limit=True,
        )
        self.buffer_layers.append(layer)
        self._update_offsets()
        return self

    def add_layer(self, crystal, U, thickness, d_spacing=None, label=None):
        """
        Append a layer to the **currently open repeating block**.

        Layers are stacked in the order they are added; the first call
        (after the stack was created, or after the previous block was
        closed by :meth:`set_repetitions`) starts a *new* block and places
        this layer at its bottom; further calls add layers on top of it,
        within the same block.

        To build **several independently-repeated blocks stacked on top of
        each other** (e.g. one unit repeated 5×, then a different unit
        repeated 8×), call :meth:`set_repetitions` right after finishing
        each block -- that both sets its repeat count and closes it, so the
        next `add_layer` call starts a fresh block::

            stack.add_layer(A, U_A, tA, label='A')
            stack.add_layer(B, U_B, tB, label='B')
            stack.set_repetitions(5)     # block 1 = (A, B) × 5

            stack.add_layer(C, U_C, tC, label='C')
            stack.set_repetitions(8)     # block 2 = (C,) × 8

            stack.add_layer(D, U_D, tD, label='D')  # block 3 = (D,) × 1 (cap)

        Blocks are stacked bottom to top in the order they were closed (or,
        for the last, still-open block, in the order its layers were added).
        If you never call `set_repetitions` at all, every `add_layer` call
        keeps extending a single block -- the original single-repeating-unit
        behaviour is preserved exactly.

        Args:
            crystal (xu.materials.Crystal):
            U ((3,3) orientation matrix):
            thickness (float): physical thickness of the layer in Å
            d_spacing (float, optional): stacking repeat distance (Å)
            label (str, optional):
"""
        layer = Layer(
            crystal, U, thickness, n_hat=self.n_hat, d_spacing=d_spacing, label=label
        )
        if not self._blocks or self._blocks[-1]._closed:
            self._blocks.append(_RepeatBlock())
        self._blocks[-1].layers.append(layer)
        self._update_offsets()
        return self

    def add_pseudomorphic_layer(
        self,
        crystal,
        U,
        thickness,
        a_substrate,
        C13: float,
        C33: float,
        growth_dir=(0, 0, 1),
        label=None,
    ):
        """
        Append a pseudomorphically strained layer to the repeating unit.

        The out-of-plane repeat distance is computed from the biaxial strain
        state imposed by the in-plane lattice constraint:

        $$
        d = d_{\\text{bulk}}\\left(1 - \\frac{2C_{13}}{C_{33}}\\,
        \\varepsilon_\\parallel\\right)
        \\qquad
        \\varepsilon_\\parallel =
        \\frac{a_{\\text{sub}} - a_{\\text{film}}}{a_{\\text{film}}}
        $$
        Equivalent to calling :func:`pseudomorphic_d_spacing` then
        :meth:`add_layer` with the computed `d_spacing`.

        Args:
            crystal (xu.materials.Crystal): Bulk (relaxed) film crystal.
            U ((3,3) ndarray): Orientation matrix for this layer.
            thickness (float): Physical thickness of the layer in Å.
            a_substrate (float): or  xu.materials.Crystal
                In-plane lattice parameter of the template (Å), or a Crystal
                whose `.lattice.a` is used.
            C13, C33 (float): Elastic stiffness constants (GPa).

            * Hexagonal c-axis growth → $C_{13}$, $C_{33}$
            * Cubic [001] growth      → $C_{12}$, $C_{11}$
            growth_dir (array-like (3,), optional): Growth direction in the **film's crystal frame**.
                Default: `(0, 0, 1)` (c-axis).
            label (str, optional):

        Returns:
            self  (for method chaining)

        Note:
        The strain values are printed on addition so you can verify the
        mismatch.
"""
        d_strained, eps_par, eps_perp = pseudomorphic_d_spacing(
            crystal, a_substrate, C13, C33, growth_dir
        )
        lbl = label or crystal.name
        print(
            f"  {lbl}: ε_∥ = {eps_par:+.4f}  ε_⊥ = {eps_perp:+.4f}"
            f"  d_bulk → {d_strained / (1 + eps_perp):.4f} Å"
            f"  d_strained = {d_strained:.4f} Å"
        )
        return self.add_layer(crystal, U, thickness, d_spacing=d_strained, label=lbl)

    def add_pseudomorphic_layer_nonpolar(
        self,
        crystal,
        U,
        thickness,
        a_substrate,
        c_substrate,
        C11: float,
        C12: float,
        C13: float,
        growth_hkl=(1, 0, 0),
        label=None,
    ):
        """
        Append a pseudomorphically strained layer grown on a **non-polar**
        hexagonal surface (m-plane `{1,0,-1,0}` or a-plane `{1,1,-2,0}`) to
        the repeating unit.

        Equivalent to calling :func:`pseudomorphic_d_spacing_nonpolar` then
        :meth:`add_layer` with the computed `d_spacing` -- see that
        function's docstring for the full derivation and for why
        :meth:`add_pseudomorphic_layer` (the `c`-axis version) cannot be
        reused here: non-polar growth strains **two** elastically
        inequivalent in-plane directions (`c` itself, and the remaining
        in-plane `a`-type direction) differently, so it needs both
        substrate lattice parameters and three stiffness constants
        (`C11`, `C12`, `C13`), not one parameter and two constants
        (`C13`, `C33`).

        Args:
            crystal (xu.materials.Crystal): Bulk (relaxed) film crystal.
            U ((3,3) ndarray): Orientation matrix for this layer -- from :func:`orientation_along_plane`
                (or a fitted Laue orientation), **not** `orientation_along_z`.
            thickness (float): Physical thickness of the layer in Å.
            a_substrate, c_substrate (float): or  xu.materials.Crystal
                In-plane `a`- and `c`-parameters of the template (Å), or
                Crystals whose `.lattice.a` / `.lattice.c` are used.
            C11, C12, C13 (float): Elastic stiffness constants (GPa).
            growth_hkl (array-like (3,), optional): Miller **plane** indices of the growth surface (default `(1,0,0)`).
                Must match whichever specific `{1,0,-1,0}`-family member is
                physically correct for *this* `U` -- there are 6
                symmetry-equivalent choices around the hexagonal cross-section,
                and nothing here can infer which one your crystal/orientation
                actually uses; check against known geometry as needed (e.g.
                comparing against a known substrate-contact facet) before
                trusting a default.
            label (str, optional):

        Returns:
            self  (for method chaining)

        Note:
        The strain values are printed on addition so you can verify the
        mismatch.
"""
        d_strained, eps_a, eps_c, eps_perp = pseudomorphic_d_spacing_nonpolar(
            crystal, a_substrate, c_substrate, C11, C12, C13, growth_hkl
        )
        lbl = label or crystal.name
        print(
            f"  {lbl}: ε_a = {eps_a:+.4f}  ε_c = {eps_c:+.4f}  ε_⊥ = {eps_perp:+.4f}"
            f"  d_bulk → {d_strained / (1 + eps_perp):.4f} Å"
            f"  d_strained = {d_strained:.4f} Å"
        )
        return self.add_layer(crystal, U, thickness, d_spacing=d_strained, label=lbl)

    def set_repetitions(self, n):
        """
        Set the repeat count of the **currently open block** (the layers
        added since the previous `set_repetitions` call, or since the stack
        was created) and close it.

        The next :meth:`add_layer` call starts a brand-new block, so
        calling `add_layer(...)` a few times then `set_repetitions(N)`,
        repeated as many times as needed, is how you build a sequence of
        independently-repeated blocks -- see :meth:`add_layer`.
"""
        if not self._blocks:
            raise ValueError(
                "set_repetitions() has nothing to act on -- call add_layer(...) "
                "at least once first to define the block to repeat."
            )
        self._blocks[-1].n_rep = int(n)
        self._blocks[-1]._closed = True
        return self

    def set_U(self, U) -> "LayeredCrystal":
        """
        Replace the orientation matrix of layers in the stack.

        Two calling forms:

        **Global** — apply one `U` to every layer::

            stack.set_U(U)

        **Per-material** — supply a dict mapping crystal name to `U`; only
        layers whose `crystal.name` matches a key are updated::

            stack.set_U({'GaN': U_GaN, 'InGaN': U_InGaN})

        Layers whose material is not listed in the dict are left unchanged.
        Useful for modelling domain variants or orientation relationships
        between different materials in the same stack without rebuilding it.

        Args:
            U (array-like (3, 3) or dict[str, array-like (3, 3)]): A single orientation matrix applied to all layers, or a mapping
                `{crystal_name: U_matrix}`.

        Returns:
            self  (for method chaining)
"""
        if isinstance(U, dict):
            U_map = {name: np.asarray(mat, dtype=float) for name, mat in U.items()}
            for layer in self.buffer_layers + self.layers:
                if layer.crystal.name in U_map:
                    layer.U = U_map[layer.crystal.name].copy()
        else:
            U_mat = np.asarray(U, dtype=float)
            for layer in self.buffer_layers + self.layers:
                layer.U = U_mat.copy()
        return self

    def _resolve_layers(self, layers):
        """Normalise the `layers` argument shared by :meth:`rotate` and
        friends into a list of `Layer` objects: `None` -> every layer in
        `self.all_layers`; a single `Layer` or label `str`; or a list mixing
        either. Raises `ValueError` naming the available labels on a bad
        match, same convention as :func:`~nrxrdct.laue.simulation.rod_tangency`.
"""
        if layers is None:
            return list(self.all_layers)
        items = layers if isinstance(layers, (list, tuple)) else [layers]
        resolved = []
        for item in items:
            if isinstance(item, str):
                match = next((ly for ly in self.all_layers if ly.label == item), None)
                if match is None:
                    available = [ly.label for ly in self.all_layers]
                    raise ValueError(f"no layer labeled {item!r}; available labels: {available}")
                resolved.append(match)
            else:
                resolved.append(item)
        return resolved

    def rotate(self, angle_deg, axis, frame: str = "lab", layers=None, inplace: bool = True) -> "LayeredCrystal":
        """
        Rotate one or more layers' orientation matrices by `angle_deg` about
        `axis`, in either the lab frame or each layer's own crystal frame.

        The two frames compose differently and answer different questions:

        - **`frame='lab'`** (default) -- `axis` is a direction in the **lab
          frame** (e.g. vertical `[0,0,1]`, the beam `[1,0,0]`, or any other
          measured lab-frame direction such as a wire's own long axis).
          Applied as `U_new = R(axis) @ U` -- physically, rotating the
          sample itself on the diffractometer about a fixed external axis.
          Same convention as
          :func:`~nrxrdct.laue.simulation.rotate_U_about_axis`, generalised
          from `'x'/'y'/'z'` to an arbitrary vector.
        - **`frame='crystal'`** -- `axis` is a direction in **each selected
          layer's own crystal frame** (e.g. `c = [0,0,1]`; for a Miller
          *plane* normal rather than a real-space direction, convert first
          with :func:`plane_normal_cartesian`). Applied as
          `U_new = U @ R(axis)` -- physically, twisting the lattice about
          its own crystallographic axis, independent of the layer's
          absolute orientation. Because this composes on the right, applying
          it to several layers with *different* `U` (e.g. an independently
          fitted core and shell) twists each one about *its own* `c`, not
          about a shared lab direction.

        A common diagnostic use: probing whether a small residual
        misorientation between an independently refined core and shell is
        consistent with a genuine c-axis twisting moment (rather than a
        fitting artifact) -- e.g. nudging just the shell by a fraction of a
        degree about its own `c` and re-comparing against the measured
        pattern, without disturbing the original stack::

            trial = stack.rotate(0.05, [0, 0, 1], frame='crystal',
                                  layers='InGaN QW', inplace=False)
            # stack is untouched; compare trial's simulated pattern instead.

        Args:
            angle_deg (float): Rotation angle in degrees (right-hand rule about `axis`).
            axis (array-like (3,)): Rotation axis. Interpreted per `frame`; need not be
                pre-normalised.
            frame (`'lab'` or `'crystal'`, optional): Which frame `axis` is expressed in. Default `'lab'`.
            layers (Layer, str, list, or None, optional): Which layer(s) to rotate. `None` (default) rotates every
                layer in `self.all_layers`. A single `Layer` object or label
                string, or a list of either, restricts to those layers.
            inplace (bool, optional): `True` (default) mutates this stack's layers directly and returns
                `self` -- matches every other stack-building method
                (`add_layer`, `set_U`, ...). `False` leaves this stack
                completely untouched and applies the rotation to a
                :meth:`copy` instead, returning that copy -- use this to try
                a rotation without losing the original.

        Returns:
            LayeredCrystal: `self` if `inplace=True` (the default); otherwise a new, independently
            mutable copy with the rotation applied.
"""
        if frame not in ("lab", "crystal"):
            raise ValueError(f"frame must be 'lab' or 'crystal', got {frame!r}")

        ax = np.asarray(axis, dtype=float)
        ax_norm = np.linalg.norm(ax)
        if ax_norm < 1e-12:
            raise ValueError(f"axis must be nonzero, got {axis}")
        ax = ax / ax_norm

        R = Rotation.from_rotvec(np.radians(float(angle_deg)) * ax).as_matrix()

        target = self if inplace else self.copy()
        for layer in target._resolve_layers(layers):
            layer.U = (R @ layer.U) if frame == "lab" else (layer.U @ R)
        return target

    def copy(self) -> "LayeredCrystal":
        """
        Return an independent deep copy of this stack -- every layer's
        material, orientation, thickness, and the block/buffer structure are
        duplicated, so mutating the copy (e.g. via :meth:`rotate`, `set_U`,
        or reassigning `layer.U` directly) never affects the original, and
        vice versa.

        Implemented as a `dill` round-trip (the same mechanism as
        :meth:`save`/:meth:`load`) rather than `copy.deepcopy`, since it is
        already proven to correctly duplicate the `xu.materials.Crystal` /
        `Alloy` objects each layer holds.

        Returns:
            LayeredCrystal: a new instance, `==` in content but `is not` this stack (nor is any of
            its layers `is` a layer of this stack).
"""
        return dill.loads(dill.dumps(self))

    def _update_offsets(self):
        """Recompute cumulative z-offsets for buffer layers and every repeating block."""
        # Buffer layers: z = 0 at deepest point, increasing toward surface
        self._buffer_z_offsets = []
        z = 0.0
        for layer in self.buffer_layers:
            self._buffer_z_offsets.append(z)
            z += layer.thickness
        self._buffer_thickness = z

        # Repeating blocks, stacked in sequence above the buffer (bottom to top)
        z_start = self._buffer_thickness
        for blk in self._blocks:
            blk._z_offsets = []
            zl = 0.0
            for layer in blk.layers:
                blk._z_offsets.append(zl)
                zl += layer.thickness
            blk._period = zl
            blk._z_start = z_start
            z_start += zl * blk.n_rep

    # ── Backward-compatible single-block accessors ───────────────────────────
    # Most stacks have exactly one repeating block; `.layers` / `.n_rep` /
    # `._z_offsets` / `._bilayer_thickness` keep working exactly as before for
    # them.  Stacks with several independently-repeated blocks should use
    # `.blocks` instead -- accessing these on a multi-block stack raises a
    # clear error rather than silently guessing which block you meant.

    def _require_single_block(self, attr):
        if len(self._blocks) > 1:
            raise AttributeError(
                f"This LayeredCrystal has {len(self._blocks)} independently-"
                f"repeated blocks; `.{attr}` is only defined for a single "
                f"repeating block.  Use `.blocks` (each with `.layers` and "
                f"`.n_rep`) instead, or a block-aware method "
                f"(structure_factor, describe, plot_layer_scheme, ...)."
            )

    @property
    def blocks(self):
        """Repeating blocks, bottom to top.  Each has `.layers` (list[Layer])
        and `.n_rep` (int).  Built by alternating :meth:`add_layer` calls
        with :meth:`set_repetitions`."""
        return list(self._blocks)

    @property
    def layers(self):
        """
        All layers belonging to repeating blocks, flattened bottom to top.

        For the common case of a single repeating block this is exactly
        that block's layer list.  For a multi-block stack this concatenates
        every block's layers (without unrolling `n_rep`) -- enough for
        callers that just need "some/all layers regardless of block", but
        not for period/offset math (use `.blocks` for that).
"""
        out = []
        for blk in self._blocks:
            out.extend(blk.layers)
        return out

    @property
    def n_rep(self):
        """Repeat count of the (single) repeating block."""
        self._require_single_block("n_rep")
        return self._blocks[0].n_rep if self._blocks else 1

    @property
    def _z_offsets(self):
        self._require_single_block("_z_offsets")
        return self._blocks[0]._z_offsets if self._blocks else []

    @property
    def _bilayer_thickness(self):
        self._require_single_block("_bilayer_thickness")
        return self._blocks[0]._period if self._blocks else 0.0

    @property
    def buffer_thickness(self):
        """Total thickness of all non-repeating buffer layers (Å)."""
        self._update_offsets()
        return self._buffer_thickness

    @property
    def bilayer_thickness(self):
        """Thickness of the (single) repeating unit (Å)."""
        self._update_offsets()
        return self._bilayer_thickness

    @property
    def total_thickness(self):
        """Total stack thickness: buffer + Σ_blocks (n_rep × block period)  (Å)."""
        self._update_offsets()
        total = self._buffer_thickness
        for blk in self._blocks:
            total += blk._period * blk.n_rep
        return total

    @property
    def all_layers(self):
        """All distinct Layer objects: buffer layers, then every repeating
        block's layers in order (each listed once, not unrolled by `n_rep`)."""
        return self.buffer_layers + self.layers

    def print_reflections(self, spots, layer=None, *, satellite_order=None,
                           min_intensity=0.0, max_rows=200):
        """
        Print the reflections actually present in a `spots` list for one
        layer (or every layer), grouped and sorted by intensity.

        Meant as a quick answer to "does hkl=... exist in my spots list for
        this layer?" before calling something like
        :func:`~nrxrdct.laue.simulation.simulate_spot_image`, which raises a
        `ValueError` naming exactly this hkl/layer/satellite_order
        combination when it can't find a match — this prints the full
        picture up front instead of discovering it one failed call at a
        time.

        Args:
            spots (list[dict]): Output of any `simulate_laue*` function.
            layer (Layer, str, or None, optional): Which layer to list. `None` (default) lists every layer in
                `self.all_layers` in turn.
            satellite_order (int or None, optional): `None` (default) shows every satellite order; pass an int
                (e.g. `0` for main peaks only) to filter to just that order.
            min_intensity (float, optional): Only show spots with `spots[i]['intensity']` (normalised 0-1) at or
                above this value.  Default `0.0` (show everything).
            max_rows (int, optional): Truncate the printed table per layer after this many rows
                (still sorted by intensity first, so the brightest survive).

        Returns:
            None — prints only.
        """
        if layer is not None:
            labels = [layer.label if hasattr(layer, "label") else layer]
        else:
            labels = [ly.label for ly in self.all_layers]

        for label in labels:
            rows = [
                s for s in spots
                if s.get("phase_label") == label
                and (satellite_order is None or s.get("satellite_order", 0) == satellite_order)
                and s.get("intensity", 1.0) >= min_intensity
            ]
            if not rows:
                print(f"Layer {label!r}: no matching spots in `spots`")
                continue
            rows = sorted(rows, key=lambda s: -s.get("intensity", 0.0))
            print(f"Layer {label!r}: {len(rows)} spot(s)")
            print(f"  {'hkl':<18}{'order':>7}{'E (eV)':>11}{'intensity':>11}  pix")
            for r in rows[:max_rows]:
                hkl_str = str(tuple(int(x) for x in r["hkl"]))
                order = r.get("satellite_order", 0)
                E = r.get("E", float("nan"))
                inten = r.get("intensity", float("nan"))
                pix = r.get("pix")
                pix_str = f"({pix[0]:.1f}, {pix[1]:.1f})" if pix is not None else "None"
                print(f"  {hkl_str:<18}{order:>7}{E:>11.1f}{inten:>11.4f}  {pix_str}")
            if len(rows) > max_rows:
                print(f"  ... ({len(rows) - max_rows} more not shown; increase max_rows)")

    # ── Structure factor ──────────────────────────────────────────────────────

    def structure_factor(self, Q_lab, energy_eV, kf_hat=None):
        """
        Total kinematical structure factor of the stack at Q_lab.

        The stack is divided into two sections:

        1. **Buffer layers** (non-repeating, at the bottom):

               F_buf(Q) = Σ_j  T_above_j · F_layer_j(Q, z0_j)

           where `T_above_j` is the amplitude attenuation from all layers
           above layer *j* (both the MQW block and the shallower buffer layers).

        2. **Repeating unit** (MQW / bilayer, sitting on top of the buffer):

               F_MQW(Q) = exp(i·Qₙ·z_buf) · F_unit(Q) · S_rep(Q)

           where `z_buf` is the total buffer thickness,
           `F_unit` is the single-bilayer structure factor, and

               S_rep(Q) = Σ_{m=0}^{N_rep-1} exp(i·m·Qₙ·Λ)

           is the superlattice geometric factor.

        The total structure factor is `F_buf + F_MQW`.

        Args:
            Q_lab (array-like (3,)): scattering vector in lab frame  (Å⁻¹)
            energy_eV: float             photon energy  (eV)
            kf_hat (array-like (3,) or None): Unit vector of the diffracted beam in the lab frame.  When
                provided, the **exit-path** absorption through each overlying layer
                is included via the two-beam transmission factor

                T = exp(−μ · t · (1/cos_in + 1/cos_out))

            where `cos_in = |n̂ · x̂|` and `cos_out = |n̂ · k̂_f|`.
            If `None`, only the incident-path (one-beam) correction already
            embedded in each buffer layer's `_effective_n_cells` is applied.

        Returns:
            F (complex): total structure factor (electron units)
"""
        self._update_offsets()
        Q = np.asarray(Q_lab, dtype=float)
        Qn = float(np.dot(Q, self.n_hat))

        # ── Overlying-layer transmission helper ───────────────────────────────
        def _T_slab(lyr, thickness):
            """Amplitude transmission exp(-μ·t·(1/cos_in + 1/cos_out))."""
            if kf_hat is None:
                return 1.0
            mu = lyr._linear_mu(energy_eV)
            if mu <= 0:
                return 1.0
            kf = np.asarray(kf_hat, dtype=float)
            cos_in  = max(abs(float(self.n_hat[0])), 1e-3)
            cos_out = max(abs(float(np.dot(self.n_hat, kf))), 1e-3)
            return float(np.exp(-mu * thickness * (1.0 / cos_in + 1.0 / cos_out)))

        # Transmission through each repeating block, taken as a whole (all
        # n_rep periods of it) -- this is how much a block above attenuates
        # everything sitting below it.
        T_block = []
        for blk in self._blocks:
            T = 1.0
            for lyr in blk.layers:
                T *= _T_slab(lyr, lyr.thickness * blk.n_rep)
            T_block.append(T)

        # T_above_block[i] = transmission through every block strictly above
        # block i (i.e. blocks[i+1:], since blocks are stored bottom to top).
        n_blk = len(self._blocks)
        T_above_block = [1.0] * n_blk
        T_run = 1.0
        for i in range(n_blk - 1, -1, -1):
            T_above_block[i] = T_run
            T_run *= T_block[i]
        T_above_all_blocks = T_run   # transmission through the ENTIRE repeating section

        # ── Buffer layers (non-repeating, deepest) ────────────────────────────
        F_total = 0.0 + 0j
        for i, (layer, z0) in enumerate(zip(self.buffer_layers, self._buffer_z_offsets)):
            # Attenuation from: every repeating block above + shallower buffer layers
            T_above = T_above_all_blocks
            for j in range(i + 1, len(self.buffer_layers)):
                T_above *= _T_slab(self.buffer_layers[j],
                                   self.buffer_layers[j].thickness)
            F_total += T_above * layer.structure_factor(Q, energy_eV, z0=z0,
                                                        kf_hat=kf_hat)

        # ── Repeating blocks (bottom to top) ──────────────────────────────────
        for i, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            F_unit = 0.0 + 0j
            for layer, z0 in zip(blk.layers, blk._z_offsets):
                F_unit += layer.structure_factor(Q, energy_eV, z0=z0,
                                                 kf_hat=kf_hat)

            # Phase to shift this block to its z position in the stack
            phase_start = np.exp(1j * Qn * blk._z_start)

            # Geometric sum over this block's own n_rep repetitions
            Lambda = blk._period
            phi_rep = Qn * Lambda
            phi_mod = phi_rep % (2.0 * np.pi)
            if abs(phi_mod) < 1e-10 or abs(phi_mod - 2 * np.pi) < 1e-10:
                S_rep = blk.n_rep + 0j
            else:
                S_rep = (1.0 - np.exp(1j * blk.n_rep * phi_rep)) / (
                    1.0 - np.exp(1j * phi_rep)
                )

            F_total += T_above_block[i] * phase_start * F_unit * S_rep

        return F_total

    def structure_factor_batch(self, Q_lab_arr, energy_eV, kf_hat_arr=None):
        """
        Vectorised :meth:`structure_factor` for many `Q_lab` (and,
        optionally, many `kf_hat`) at once.

        Identical physics to the scalar method, with one approximation: the
        unit-cell structure factor `F_uc(Q, E)` is evaluated at a **single**
        reference energy for the whole batch (via `Layer.structure_factor_batch`
        → `xu.materials.Crystal.StructureFactorForQ`) instead of each row's own
        energy. This only affects the smooth `f'(E)`/`f''(E)` anomalous-dispersion
        terms — safe away from absorption edges — and is what makes the batch
        path fast: it turns `len(all_layers) × N` scalar xrayutilities calls into
        `len(all_layers)` vectorised ones. Everything else (Q-dependence,
        geometry, per-voxel absorption via `kf_hat_arr`) is exact and
        per-row.

        Args:
            Q_lab_arr (ndarray, shape (N, 3)): Scattering vectors in the lab frame (Å⁻¹).
            energy_eV (float): Reference photon energy (eV) for the `F_uc` evaluation —
                e.g. the median energy of the batch.
            kf_hat_arr (ndarray, shape (N, 3) or None): Per-row diffracted-beam unit vectors for the two-beam
                absorption correction; `None` uses the one-beam correction
                (same convention as :meth:`structure_factor`).

        Returns:
            ndarray, shape (N,), complex — total stack structure factor per row.
"""
        self._update_offsets()
        Q_lab_arr = np.asarray(Q_lab_arr, dtype=float)
        n = len(Q_lab_arr)
        Qn = Q_lab_arr @ self.n_hat

        def _T_slab_batch(lyr, thickness):
            if kf_hat_arr is None:
                return np.ones(n)
            mu = lyr._linear_mu(energy_eV)
            if mu <= 0:
                return np.ones(n)
            cos_in = max(abs(float(self.n_hat[0])), 1e-3)
            cos_out = np.maximum(np.abs(kf_hat_arr @ self.n_hat), 1e-3)
            return np.exp(-mu * thickness * (1.0 / cos_in + 1.0 / cos_out))

        T_block = []
        for blk in self._blocks:
            T = np.ones(n)
            for lyr in blk.layers:
                T = T * _T_slab_batch(lyr, lyr.thickness * blk.n_rep)
            T_block.append(T)

        n_blk = len(self._blocks)
        T_above_block = [np.ones(n) for _ in range(n_blk)]
        T_run = np.ones(n)
        for i in range(n_blk - 1, -1, -1):
            T_above_block[i] = T_run
            T_run = T_run * T_block[i]
        T_above_all_blocks = T_run

        F_total = np.zeros(n, dtype=complex)
        for i, (layer, z0) in enumerate(zip(self.buffer_layers, self._buffer_z_offsets)):
            T_above = T_above_all_blocks.copy()
            for j in range(i + 1, len(self.buffer_layers)):
                T_above = T_above * _T_slab_batch(
                    self.buffer_layers[j], self.buffer_layers[j].thickness
                )
            F_total += T_above * layer.structure_factor_batch(
                Q_lab_arr, energy_eV, z0=z0, kf_hat_arr=kf_hat_arr
            )

        for i, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            F_unit = np.zeros(n, dtype=complex)
            for layer, z0 in zip(blk.layers, blk._z_offsets):
                F_unit += layer.structure_factor_batch(
                    Q_lab_arr, energy_eV, z0=z0, kf_hat_arr=kf_hat_arr
                )

            phase_start = np.exp(1j * Qn * blk._z_start)
            Lambda = blk._period
            phi_rep = Qn * Lambda
            S_rep = _geometric_sum_batch(blk.n_rep, phi_rep)

            F_total += T_above_block[i] * phase_start * F_unit * S_rep

        return F_total

    def average_structure_factor(self, Q_lab, energy_eV, kf_hat=None):
        """
        Structure factor of the thickness-weighted average unit cell at Q_lab.

        Instead of summing layer amplitudes with their relative depth phases
        (the coherent model), this method sums `F_uc_i × N_eff_i` over all
        layers **without** the inter-layer phase factors
        `exp(i Q_n z_{0,i})`.  The result is the *structural envelope* of
        the diffraction pattern: the intensity it predicts at any Q is the
        maximum each satellite could reach if all unit cells happened to
        scatter perfectly in phase.

        This approximation is useful to:

        * predict which satellite positions carry significant scattering power
          based on the average composition, before running the slower coherent
          simulation;
        * compare the coherent fringe pattern against its envelope to isolate
          which features arise from constructive interference vs. from the unit
          cell structure factor.

        All absorption corrections (Beer-Lambert two-beam depth limit,
        overlying-layer attenuation) are applied identically to
        :meth:`structure_factor`.

        Args:
            Q_lab (array-like (3,)): Scattering vector in the lab frame (Å⁻¹).
            energy_eV (float): Photon energy (eV).
            kf_hat (array-like (3,) or None): Diffracted beam unit vector for the two-beam absorption correction.

        Returns:
            F (complex): (electron units)
"""
        self._update_offsets()
        Q = np.asarray(Q_lab, dtype=float)
        Qn = float(np.dot(Q, self.n_hat))

        # ── Overlying-layer transmission (identical to structure_factor) ──────
        def _T_slab(lyr, thickness):
            if kf_hat is None:
                return 1.0
            mu = lyr._linear_mu(energy_eV)
            if mu <= 0:
                return 1.0
            kf = np.asarray(kf_hat, dtype=float)
            cos_in  = max(abs(float(self.n_hat[0])), 1e-3)
            cos_out = max(abs(float(np.dot(self.n_hat, kf))), 1e-3)
            return float(np.exp(-mu * thickness * (1.0 / cos_in + 1.0 / cos_out)))

        T_block = []
        for blk in self._blocks:
            T = 1.0
            for lyr in blk.layers:
                T *= _T_slab(lyr, lyr.thickness * blk.n_rep)
            T_block.append(T)

        n_blk = len(self._blocks)
        T_above_block = [1.0] * n_blk
        T_run = 1.0
        for i in range(n_blk - 1, -1, -1):
            T_above_block[i] = T_run
            T_run *= T_block[i]
        T_above_all_blocks = T_run

        # ── Buffer layers — coherent sum with depth phase offsets ─────────────
        # Buffer layers are not part of any periodic block; their positions
        # are fixed and their phase offsets must be kept even in average mode.
        F_total = 0.0 + 0j
        for i, (layer, z0) in enumerate(
                zip(self.buffer_layers, self._buffer_z_offsets)):
            T_above = T_above_all_blocks
            for j in range(i + 1, len(self.buffer_layers)):
                T_above *= _T_slab(self.buffer_layers[j],
                                   self.buffer_layers[j].thickness)
            Q_cry = layer.U.T @ Q
            F_uc = layer.crystal.StructureFactor(Q_cry, en=energy_eV)
            if not (np.isfinite(F_uc.real) and np.isfinite(F_uc.imag)):
                continue
            n_eff = (layer._effective_n_cells(energy_eV, kf_hat=kf_hat)
                     if layer.absorption_limit else layer.n_cells)
            F_total += T_above * F_uc * n_eff * np.exp(1j * Qn * z0)

        # ── Repeating blocks — average over each period, keep S_rep ──────────
        # Sum F_uc_i × N_cells_i over one block period WITHOUT intra-period
        # phase factors (z_rel).  The inter-period interference is still
        # captured by the geometric series S_rep, so satellite peaks appear at
        # the correct positions with N_rep²-enhanced intensities.
        for i, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            F_unit = 0.0 + 0j
            for layer in blk.layers:
                Q_cry = layer.U.T @ Q
                F_uc = layer.crystal.StructureFactor(Q_cry, en=energy_eV)
                if not (np.isfinite(F_uc.real) and np.isfinite(F_uc.imag)):
                    continue
                F_unit += F_uc * layer.n_cells

            Lambda  = blk._period
            phi_rep = Qn * Lambda
            phi_mod = phi_rep % (2.0 * np.pi)
            if abs(phi_mod) < 1e-10 or abs(phi_mod - 2.0 * np.pi) < 1e-10:
                S_rep = float(blk.n_rep) + 0j
            else:
                S_rep = ((1.0 - np.exp(1j * blk.n_rep * phi_rep))
                         / (1.0 - np.exp(1j * phi_rep)))
            F_total += (T_above_block[i] * np.exp(1j * Qn * blk._z_start)
                        * F_unit * S_rep)

        return F_total

    def average_structure_factor_batch(self, Q_lab_arr, energy_eV, kf_hat_arr=None):
        """
        Vectorised :meth:`average_structure_factor` for many `Q_lab` (and,
        optionally, many `kf_hat`) at once, evaluated against a single
        reference energy — see :meth:`structure_factor_batch` for the
        approximation this implies (exact in Q, approximate in the smooth
        `f'(E)`/`f''(E)` dispersion terms only).

        Args:
            Q_lab_arr (ndarray, shape (N, 3)): Scattering vectors in the lab frame (Å⁻¹).
            energy_eV (float): Reference photon energy (eV).
            kf_hat_arr (ndarray, shape (N, 3) or None): Per-row diffracted-beam unit vectors for the two-beam
                absorption correction; `None` uses the one-beam correction.

        Returns:
            ndarray, shape (N,), complex.
"""
        self._update_offsets()
        Q_lab_arr = np.asarray(Q_lab_arr, dtype=float)
        n = len(Q_lab_arr)
        Qn = Q_lab_arr @ self.n_hat

        def _T_slab_batch(lyr, thickness):
            if kf_hat_arr is None:
                return np.ones(n)
            mu = lyr._linear_mu(energy_eV)
            if mu <= 0:
                return np.ones(n)
            cos_in = max(abs(float(self.n_hat[0])), 1e-3)
            cos_out = np.maximum(np.abs(kf_hat_arr @ self.n_hat), 1e-3)
            return np.exp(-mu * thickness * (1.0 / cos_in + 1.0 / cos_out))

        T_block = []
        for blk in self._blocks:
            T = np.ones(n)
            for lyr in blk.layers:
                T = T * _T_slab_batch(lyr, lyr.thickness * blk.n_rep)
            T_block.append(T)

        n_blk = len(self._blocks)
        T_above_block = [np.ones(n) for _ in range(n_blk)]
        T_run = np.ones(n)
        for i in range(n_blk - 1, -1, -1):
            T_above_block[i] = T_run
            T_run = T_run * T_block[i]
        T_above_all_blocks = T_run

        # ── Buffer layers — coherent sum with depth phase offsets (branches on
        #    absorption_limit, matching the scalar method) ─────────────────────
        F_total = np.zeros(n, dtype=complex)
        for i, (layer, z0) in enumerate(zip(self.buffer_layers, self._buffer_z_offsets)):
            T_above = T_above_all_blocks.copy()
            for j in range(i + 1, len(self.buffer_layers)):
                T_above = T_above * _T_slab_batch(
                    self.buffer_layers[j], self.buffer_layers[j].thickness
                )
            F_uc = layer._structure_factor_uc_batch(Q_lab_arr, energy_eV)
            n_eff = (
                layer._effective_n_cells_batch(energy_eV, kf_hat_arr=kf_hat_arr, n_points=n)
                if layer.absorption_limit
                else np.full(n, float(layer.n_cells))
            )
            F_total += T_above * F_uc * n_eff * np.exp(1j * Qn * z0)

        # ── Repeating blocks — average over each period (no absorption_limit
        #    branch on the block layers, matching the scalar method) ──────────
        for i, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            F_unit = np.zeros(n, dtype=complex)
            for layer in blk.layers:
                F_uc = layer._structure_factor_uc_batch(Q_lab_arr, energy_eV)
                F_unit += F_uc * float(layer.n_cells)

            Lambda = blk._period
            phi_rep = Qn * Lambda
            S_rep = _geometric_sum_batch(blk.n_rep, phi_rep)
            F_total += (T_above_block[i] * np.exp(1j * Qn * blk._z_start)
                        * F_unit * S_rep)

        return F_total

    def intensity(self, Q_arr, energy_eV):
        """
        Compute |F(Q)|² for an array of Q-points.

        Args:
            Q_arr (array-like, shape (N, 3)): scattering vectors in lab frame
            energy_eV: float                      photon energy (eV)

        Returns:
            I (ndarray, shape (N,)): |F(Q)|² in (electron units)²
"""
        Q_arr = np.asarray(Q_arr, dtype=float)
        return np.array([abs(self.structure_factor(Q, energy_eV)) ** 2 for Q in Q_arr])

    # ── Per-layer and per-Q analysis ─────────────────────────────────────────

    def layer_contributions(self, Q_lab, energy_eV):
        """
        Return the individual structure factor contribution of each layer.

        Buffer layers are included at their absolute z positions.  Layers of
        every repeating block are included for the *first* repetition of
        their own block only (z0 relative to that block's start position),
        without the superlattice factor.

        Args:
            Q_lab (array-like (3,)):
            energy_eV: float

        Returns:
            dict  { label (complex F_layer }):
"""
        self._update_offsets()
        Q = np.asarray(Q_lab, dtype=float)
        result = {}
        for layer, z0 in zip(self.buffer_layers, self._buffer_z_offsets):
            F = layer.structure_factor(Q, energy_eV, z0=z0)
            result[layer.label] = result.get(layer.label, 0j) + F
        for blk in self._blocks:
            for layer, z0 in zip(blk.layers, blk._z_offsets):
                F = layer.structure_factor(Q, energy_eV, z0=blk._z_start + z0)
                result[layer.label] = result.get(layer.label, 0j) + F
        return result

    # ── Description ──────────────────────────────────────────────────────────

    def describe(self):
        """Print a summary of the stack."""
        self._update_offsets()
        nh = self.n_hat
        W = 56

        def _layer_row(i, layer, z0_abs):
            lat = layer.crystal.lattice
            print(
                f"    [{i}] {layer.label:22s} "
                f"{layer.n_cells:5d} cells × {layer.d:.4f} Å"
                f" = {layer.thickness:9.3f} Å   z = {z0_abs:.1f} Å"
            )
            print(
                f"         SG {lat.space_group}  "
                f"a={lat.a:.4f}  b={lat.b:.4f}  c={lat.c:.4f} Å"
            )

        beam_angle_deg = np.degrees(np.arccos(np.clip(abs(float(nh[0])), 0.0, 1.0)))
        print(f"\n  LayeredCrystal: '{self.name}'")
        print(f"  {'─'*W}")
        print(f"  Stacking / surface normal (lab): [{nh[0]:+.4f}, {nh[1]:+.4f}, {nh[2]:+.4f}]"
              f"   beam angle = {beam_angle_deg:.1f}°")

        # Buffer layers
        if self.buffer_layers:
            print(
                f"\n  Buffer layers  (non-repeating, {len(self.buffer_layers)} layer"
                f"{'s' if len(self.buffer_layers) != 1 else ''}):"
            )
            for i, (layer, z0) in enumerate(
                zip(self.buffer_layers, self._buffer_z_offsets)
            ):
                _layer_row(i, layer, z0)
        else:
            print(f"\n  Buffer layers: none")

        # Repeating blocks
        if self._blocks:
            for bi, blk in enumerate(self._blocks):
                if not blk.layers:
                    continue
                print(
                    f"\n  Repeating block [{bi}]  (× {blk.n_rep},"
                    f" starts at z = {blk._z_start:.1f} Å):"
                )
                for i, (layer, z0) in enumerate(zip(blk.layers, blk._z_offsets)):
                    _layer_row(i, layer, blk._z_start + z0)
                Lambda = blk._period
                print(f"    Block period  Λ = {Lambda:.4f} Å")
                if Lambda > 1e-6:
                    print(f"    Satellite spacing 2π/Λ = {2*np.pi/Lambda:.5f} Å⁻¹")
        else:
            print(f"\n  Repeating blocks: none")

        print(
            f"\n  Total thickness = {self.total_thickness:.2f} Å"
            f"  = {self.total_thickness/10:.2f} nm"
        )
        print(f"  {'─'*W}")

    def save(self, path: str) -> None:
        """
        Save this stack to *path* via `dill`, so it can be reloaded later
        instead of rebuilt from scratch -- resuming a session where you left
        off, or handing a hand-tuned/fitted stack to
        :class:`~nrxrdct.laue.layered_map.LayeredMap` as the starting-point
        orientation for a per-pixel map (`LayeredMap(stack=..., ...)`)
        without re-running the notebook cells that built it.

        Round-trips everything: every layer's material (`xu.materials.Crystal`
        / `Alloy`), orientation `U`, thickness, resolved `d`-spacing, `n_hat`,
        label, and absorption settings, plus the block/repetition structure
        and buffer layers -- the exact same mechanism already used internally
        by `LayeredMap` to ship a stack to local worker processes (see
        `layered_map._serialize_stack`), just to a permanent path instead of
        a temp file.

        Args:
            path (str): Destination file path (any extension; `.pkl` by convention).

        Example:
        >>> stack.save('gan_mplane_stack.pkl')
        >>> # ...later, or in a different session...
        >>> stack = LayeredCrystal.load('gan_mplane_stack.pkl')
        >>> lmap = LayeredMap(ny=21, nx=21, stack=stack, h5_path='scan.h5')
"""
        with open(path, "wb") as fh:
            dill.dump(self, fh)
        print(f"LayeredCrystal '{self.name}' saved -> {path!r}", flush=True)

    @classmethod
    def load(cls, path: str) -> "LayeredCrystal":
        """
        Load a stack previously saved with :meth:`save`.

        Args:
            path (str): Path to a file written by :meth:`save`.

        Returns:
            LayeredCrystal: the restored stack, with every layer's material, orientation,
            thickness, and block structure intact.
"""
        with open(path, "rb") as fh:
            stack = dill.load(fh)
        if not isinstance(stack, cls):
            raise TypeError(
                f"{path!r} does not contain a LayeredCrystal "
                f"(got {type(stack).__name__})"
            )
        return stack

    def plot_lattice_parameter(
        self,
        param: str = "c",
        unit: str = "A",
        ax=None,
        figsize=(8, 4),
    ):
        """
        Plot a lattice parameter profile through the stack depth.

        Draws a step function showing how *param* (`'a'`, `'b'`, or
        `'c'`) varies with depth, with buffer layers at the bottom and the
        surface at the top.  Every repeating block is unrolled across all of
        its own `n_rep` repetitions, in stack order.

        Args:
            param (`'a'` | `'b'` | `'c'`): Which lattice parameter to plot.
            unit (`'A'` | `'nm'`): Display unit for the depth axis (Å or nm).
            ax (matplotlib.axes.Axes, optional): Draw into an existing axes; a new figure is created if `None`.
            figsize ((float, float)):

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

        if param not in ("a", "b", "c"):
            raise ValueError(f"param must be 'a', 'b', or 'c', got {param!r}")
        if unit not in ("A", "nm"):
            raise ValueError(f"unit must be 'A' or 'nm', got {unit!r}")

        self._update_offsets()
        scale = 0.1 if unit == "nm" else 1.0
        unit_label = "nm" if unit == "nm" else "Å"

        # Build full layer sequence with absolute z offsets (bottom = 0)
        # Each entry: (z_start, z_end, layer)
        segments = []
        z = 0.0
        for layer in self.buffer_layers:
            segments.append((z, z + layer.thickness, layer))
            z += layer.thickness
        for blk in self._blocks:
            for _ in range(blk.n_rep):
                for layer in blk.layers:
                    segments.append((z, z + layer.thickness, layer))
                    z += layer.thickness

        # Collect unique phase labels for the legend
        seen_labels = {}
        colors_cycle = plt.get_cmap("tab10")
        color_idx = 0

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

        for z0, z1, layer in segments:
            val = getattr(layer.crystal.lattice, param)
            y0 = z0 * scale
            y1 = z1 * scale
            lbl = layer.label

            if lbl not in seen_labels:
                seen_labels[lbl] = colors_cycle(color_idx / 9)
                color_idx = (color_idx + 1) % 10
            col = seen_labels[lbl]

            # Horizontal bar: lattice parameter value across the layer depth range
            ax.hlines(val, y0, y1, colors=col, linewidths=2.5)
            # Vertical connectors between adjacent layers
            ax.vlines(y0, val, val, colors=col, linewidths=1.0, linestyles="dotted")

        # Draw vertical connectors between adjacent steps
        for i in range(1, len(segments)):
            _, _, layer_prev = segments[i - 1]
            z_curr, _, layer_curr  = segments[i]
            val_prev = getattr(layer_prev.crystal.lattice, param)
            val_curr = getattr(layer_curr.crystal.lattice, param)
            z_joint = z_curr * scale
            ax.vlines(z_joint, min(val_prev, val_curr), max(val_prev, val_curr),
                      colors="#555555", linewidths=0.8, linestyles="--")

        # Legend
        handles = [
            mpatches.Patch(color=col, label=lbl)
            for lbl, col in seen_labels.items()
        ]
        ax.legend(handles=handles, fontsize=8, loc="best",
                  framealpha=0.4, facecolor="#1a1f2e", edgecolor="#3a3f4e",
                  labelcolor="#ccccee")

        ax.set_xlabel(f"depth  ({unit_label})", fontsize=9)
        ax.set_ylabel(f"lattice parameter {param}  (Å)", fontsize=9)
        ax.set_title(
            f"{self.name}  —  lattice parameter {param} profile",
            fontsize=10,
        )
        ax.set_xlim(0, self.total_thickness * scale)

        if standalone:
            fig.tight_layout()

        return fig, ax

    def plot_strain_profile(
        self,
        param: str = "c",
        reference=None,
        unit: str = "A",
        ax=None,
        figsize=(8, 4),
    ):
        """
        Plot the strain profile of a lattice parameter through the stack depth.

        Strain is defined as

        $$
        \\varepsilon = \\frac{p_{\\text{layer}} - p_{\\text{ref}}}{p_{\\text{ref}}}
        $$
        where *p* is the chosen lattice parameter (`'a'`, `'b'`, or
        `'c'`).

        Args:
            param (`'a'` | `'b'` | `'c'`): Lattice parameter to use.
            reference (float, xu.materials.Crystal, or None): Reference value for zero strain.

            * **float** — use this value directly (Å).
            * **Crystal** — use `crystal.lattice.<param>`.
            * **None** *(default)* — use the lattice parameter of the first
              buffer layer; if there are no buffer layers, use the first
              repeating layer.
            unit (`'A'` | `'nm'`): Display unit for the depth axis.
            ax (matplotlib.axes.Axes, optional):
            figsize ((float, float)):

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

        if param not in ("a", "b", "c"):
            raise ValueError(f"param must be 'a', 'b', or 'c', got {param!r}")
        if unit not in ("A", "nm"):
            raise ValueError(f"unit must be 'A' or 'nm', got {unit!r}")

        self._update_offsets()
        scale = 0.1 if unit == "nm" else 1.0
        unit_label = "nm" if unit == "nm" else "Å"

        # Resolve reference value
        if reference is None:
            ref_layer = (self.buffer_layers or self.layers)[0]
            p_ref = getattr(ref_layer.crystal.lattice, param)
        elif isinstance(reference, (int, float)):
            p_ref = float(reference)
        else:
            # Assume xu.materials.Crystal-like object
            p_ref = float(getattr(reference.lattice, param))

        # Build full layer sequence (same logic as plot_lattice_parameter)
        segments = []
        z = 0.0
        for layer in self.buffer_layers:
            segments.append((z, z + layer.thickness, layer))
            z += layer.thickness
        for blk in self._blocks:
            for _ in range(blk.n_rep):
                for layer in blk.layers:
                    segments.append((z, z + layer.thickness, layer))
                    z += layer.thickness

        seen_labels = {}
        colors_cycle = plt.get_cmap("tab10")
        color_idx = 0

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

        for z0, z1, layer in segments:
            p_val = getattr(layer.crystal.lattice, param)
            strain = (p_val - p_ref) / p_ref
            y0 = z0 * scale
            y1 = z1 * scale
            lbl = layer.label

            if lbl not in seen_labels:
                seen_labels[lbl] = colors_cycle(color_idx / 9)
                color_idx = (color_idx + 1) % 10
            col = seen_labels[lbl]

            ax.hlines(strain, y0, y1, colors=col, linewidths=2.5)

        # Vertical connectors between adjacent steps
        for i in range(1, len(segments)):
            _, _, layer_prev = segments[i - 1]
            z_curr, _, layer_curr = segments[i]
            s_prev = (getattr(layer_prev.crystal.lattice, param) - p_ref) / p_ref
            s_curr = (getattr(layer_curr.crystal.lattice, param) - p_ref) / p_ref
            ax.vlines(z_curr * scale, min(s_prev, s_curr), max(s_prev, s_curr),
                      colors="#555555", linewidths=0.8, linestyles="--")

        # Zero-strain reference line
        ax.axhline(0.0, color="#888888", linewidth=0.8, linestyle=":")

        handles = [
            mpatches.Patch(color=col, label=lbl)
            for lbl, col in seen_labels.items()
        ]
        ax.legend(handles=handles, fontsize=8, loc="best",
                  framealpha=0.4, facecolor="#1a1f2e", edgecolor="#3a3f4e",
                  labelcolor="#ccccee")

        ref_str = f"{p_ref:.4f} Å"
        ax.set_xlabel(f"depth  ({unit_label})", fontsize=9)
        ax.set_ylabel(f"ε_{param}  =  (p − p_ref) / p_ref", fontsize=9)
        ax.set_title(
            f"{self.name}  —  strain profile  [{param},  ref = {ref_str}]",
            fontsize=10,
        )
        ax.set_xlim(0, self.total_thickness * scale)

        if standalone:
            fig.tight_layout()

        return fig, ax

all_layers property

all_layers

All distinct Layer objects: buffer layers, then every repeating block's layers in order (each listed once, not unrolled by n_rep).

bilayer_thickness property

bilayer_thickness

Thickness of the (single) repeating unit (Å).

blocks property

blocks

Repeating blocks, bottom to top. Each has .layers (list[Layer]) and .n_rep (int). Built by alternating :meth:add_layer calls with :meth:set_repetitions.

buffer_thickness property

buffer_thickness

Total thickness of all non-repeating buffer layers (Å).

layers property

layers

All layers belonging to repeating blocks, flattened bottom to top.

For the common case of a single repeating block this is exactly that block's layer list. For a multi-block stack this concatenates every block's layers (without unrolling n_rep) -- enough for callers that just need "some/all layers regardless of block", but not for period/offset math (use .blocks for that).

n_rep property

n_rep

Repeat count of the (single) repeating block.

total_thickness property

total_thickness

Total stack thickness: buffer + Σ_blocks (n_rep × block period) (Å).

add_buffer_layer

add_buffer_layer(crystal, U, thickness, d_spacing=None, label=None)

Append a non-repeating layer at the bottom of the stack (substrate side), below every repeating block.

Buffer layers are always added in order from deepest to shallowest: the first call places the layer closest to the substrate, subsequent calls place layers closer to the surface.

Parameters:
  • crystal (Crystal) –
  • U ((3,3) orientation matrix) –

    G_lab = U @ G_crystal

  • thickness (float) –

    physical thickness of the layer in Å

  • d_spacing (float, default: None ) –

    stacking repeat distance (Å)

  • label (str, default: None ) –
Source code in src/nrxrdct/laue/layers.py
    def add_buffer_layer(self, crystal, U, thickness, d_spacing=None, label=None):
        """
        Append a **non-repeating** layer at the bottom of the stack (substrate
        side), below every repeating block.

        Buffer layers are always added in order from deepest to shallowest:
        the first call places the layer closest to the substrate, subsequent
        calls place layers closer to the surface.

        Args:
            crystal (xu.materials.Crystal):
            U ((3,3) orientation matrix): G_lab = U @ G_crystal
            thickness (float): physical thickness of the layer in Å
            d_spacing (float, optional): stacking repeat distance (Å)
            label (str, optional):
"""
        layer = Layer(
            crystal,
            U,
            thickness,
            n_hat=self.n_hat,
            d_spacing=d_spacing,
            label=label,
            absorption_limit=True,
        )
        self.buffer_layers.append(layer)
        self._update_offsets()
        return self

add_layer

add_layer(crystal, U, thickness, d_spacing=None, label=None)

Append a layer to the currently open repeating block.

Layers are stacked in the order they are added; the first call (after the stack was created, or after the previous block was closed by :meth:set_repetitions) starts a new block and places this layer at its bottom; further calls add layers on top of it, within the same block.

To build several independently-repeated blocks stacked on top of each other (e.g. one unit repeated 5×, then a different unit repeated 8×), call :meth:set_repetitions right after finishing each block -- that both sets its repeat count and closes it, so the next add_layer call starts a fresh block::

stack.add_layer(A, U_A, tA, label='A')
stack.add_layer(B, U_B, tB, label='B')
stack.set_repetitions(5)     # block 1 = (A, B) × 5

stack.add_layer(C, U_C, tC, label='C')
stack.set_repetitions(8)     # block 2 = (C,) × 8

stack.add_layer(D, U_D, tD, label='D')  # block 3 = (D,) × 1 (cap)

Blocks are stacked bottom to top in the order they were closed (or, for the last, still-open block, in the order its layers were added). If you never call set_repetitions at all, every add_layer call keeps extending a single block -- the original single-repeating-unit behaviour is preserved exactly.

Parameters:
  • crystal (Crystal) –
  • U ((3,3) orientation matrix) –
  • thickness (float) –

    physical thickness of the layer in Å

  • d_spacing (float, default: None ) –

    stacking repeat distance (Å)

  • label (str, default: None ) –
Source code in src/nrxrdct/laue/layers.py
    def add_layer(self, crystal, U, thickness, d_spacing=None, label=None):
        """
        Append a layer to the **currently open repeating block**.

        Layers are stacked in the order they are added; the first call
        (after the stack was created, or after the previous block was
        closed by :meth:`set_repetitions`) starts a *new* block and places
        this layer at its bottom; further calls add layers on top of it,
        within the same block.

        To build **several independently-repeated blocks stacked on top of
        each other** (e.g. one unit repeated 5×, then a different unit
        repeated 8×), call :meth:`set_repetitions` right after finishing
        each block -- that both sets its repeat count and closes it, so the
        next `add_layer` call starts a fresh block::

            stack.add_layer(A, U_A, tA, label='A')
            stack.add_layer(B, U_B, tB, label='B')
            stack.set_repetitions(5)     # block 1 = (A, B) × 5

            stack.add_layer(C, U_C, tC, label='C')
            stack.set_repetitions(8)     # block 2 = (C,) × 8

            stack.add_layer(D, U_D, tD, label='D')  # block 3 = (D,) × 1 (cap)

        Blocks are stacked bottom to top in the order they were closed (or,
        for the last, still-open block, in the order its layers were added).
        If you never call `set_repetitions` at all, every `add_layer` call
        keeps extending a single block -- the original single-repeating-unit
        behaviour is preserved exactly.

        Args:
            crystal (xu.materials.Crystal):
            U ((3,3) orientation matrix):
            thickness (float): physical thickness of the layer in Å
            d_spacing (float, optional): stacking repeat distance (Å)
            label (str, optional):
"""
        layer = Layer(
            crystal, U, thickness, n_hat=self.n_hat, d_spacing=d_spacing, label=label
        )
        if not self._blocks or self._blocks[-1]._closed:
            self._blocks.append(_RepeatBlock())
        self._blocks[-1].layers.append(layer)
        self._update_offsets()
        return self

add_pseudomorphic_layer

add_pseudomorphic_layer(crystal, U, thickness, a_substrate, C13: float, C33: float, growth_dir=(0, 0, 1), label=None)

Append a pseudomorphically strained layer to the repeating unit.

The out-of-plane repeat distance is computed from the biaxial strain state imposed by the in-plane lattice constraint:

$$ d = d_{\text{bulk}}\left(1 - \frac{2C_{13}}{C_{33}}\, \varepsilon_\parallel\right) \qquad \varepsilon_\parallel = \frac{a_{\text{sub}} - a_{\text{film}}}{a_{\text{film}}} $$ Equivalent to calling :func:pseudomorphic_d_spacing then :meth:add_layer with the computed d_spacing.

Parameters:
  • crystal (Crystal) –

    Bulk (relaxed) film crystal.

  • U ((3,3) ndarray) –

    Orientation matrix for this layer.

  • thickness (float) –

    Physical thickness of the layer in Å.

  • a_substrate (float) –

    or xu.materials.Crystal In-plane lattice parameter of the template (Å), or a Crystal whose .lattice.a is used.

  • C13, C33 (float) –

    Elastic stiffness constants (GPa).

  • growth_dir (array - like(3), default: (0, 0, 1) ) –

    Growth direction in the film's crystal frame. Default: (0, 0, 1) (c-axis).

  • label (str, default: None ) –
Returns:
  • –

    self (for method chaining)

Note: The strain values are printed on addition so you can verify the mismatch.

Source code in src/nrxrdct/laue/layers.py
    def add_pseudomorphic_layer(
        self,
        crystal,
        U,
        thickness,
        a_substrate,
        C13: float,
        C33: float,
        growth_dir=(0, 0, 1),
        label=None,
    ):
        """
        Append a pseudomorphically strained layer to the repeating unit.

        The out-of-plane repeat distance is computed from the biaxial strain
        state imposed by the in-plane lattice constraint:

        $$
        d = d_{\\text{bulk}}\\left(1 - \\frac{2C_{13}}{C_{33}}\\,
        \\varepsilon_\\parallel\\right)
        \\qquad
        \\varepsilon_\\parallel =
        \\frac{a_{\\text{sub}} - a_{\\text{film}}}{a_{\\text{film}}}
        $$
        Equivalent to calling :func:`pseudomorphic_d_spacing` then
        :meth:`add_layer` with the computed `d_spacing`.

        Args:
            crystal (xu.materials.Crystal): Bulk (relaxed) film crystal.
            U ((3,3) ndarray): Orientation matrix for this layer.
            thickness (float): Physical thickness of the layer in Å.
            a_substrate (float): or  xu.materials.Crystal
                In-plane lattice parameter of the template (Å), or a Crystal
                whose `.lattice.a` is used.
            C13, C33 (float): Elastic stiffness constants (GPa).

            * Hexagonal c-axis growth → $C_{13}$, $C_{33}$
            * Cubic [001] growth      → $C_{12}$, $C_{11}$
            growth_dir (array-like (3,), optional): Growth direction in the **film's crystal frame**.
                Default: `(0, 0, 1)` (c-axis).
            label (str, optional):

        Returns:
            self  (for method chaining)

        Note:
        The strain values are printed on addition so you can verify the
        mismatch.
"""
        d_strained, eps_par, eps_perp = pseudomorphic_d_spacing(
            crystal, a_substrate, C13, C33, growth_dir
        )
        lbl = label or crystal.name
        print(
            f"  {lbl}: ε_∥ = {eps_par:+.4f}  ε_⊥ = {eps_perp:+.4f}"
            f"  d_bulk → {d_strained / (1 + eps_perp):.4f} Å"
            f"  d_strained = {d_strained:.4f} Å"
        )
        return self.add_layer(crystal, U, thickness, d_spacing=d_strained, label=lbl)

add_pseudomorphic_layer_nonpolar

add_pseudomorphic_layer_nonpolar(crystal, U, thickness, a_substrate, c_substrate, C11: float, C12: float, C13: float, growth_hkl=(1, 0, 0), label=None)

Append a pseudomorphically strained layer grown on a non-polar hexagonal surface (m-plane {1,0,-1,0} or a-plane {1,1,-2,0}) to the repeating unit.

Equivalent to calling :func:pseudomorphic_d_spacing_nonpolar then :meth:add_layer with the computed d_spacing -- see that function's docstring for the full derivation and for why :meth:add_pseudomorphic_layer (the c-axis version) cannot be reused here: non-polar growth strains two elastically inequivalent in-plane directions (c itself, and the remaining in-plane a-type direction) differently, so it needs both substrate lattice parameters and three stiffness constants (C11, C12, C13), not one parameter and two constants (C13, C33).

Parameters:
  • crystal (Crystal) –

    Bulk (relaxed) film crystal.

  • U ((3,3) ndarray) –

    Orientation matrix for this layer -- from :func:orientation_along_plane (or a fitted Laue orientation), not orientation_along_z.

  • thickness (float) –

    Physical thickness of the layer in Å.

  • a_substrate, c_substrate (float) –

    or xu.materials.Crystal In-plane a- and c-parameters of the template (Å), or Crystals whose .lattice.a / .lattice.c are used.

  • C11, C12, C13 (float) –

    Elastic stiffness constants (GPa).

  • growth_hkl (array - like(3), default: (1, 0, 0) ) –

    Miller plane indices of the growth surface (default (1,0,0)). Must match whichever specific {1,0,-1,0}-family member is physically correct for this U -- there are 6 symmetry-equivalent choices around the hexagonal cross-section, and nothing here can infer which one your crystal/orientation actually uses; check against known geometry as needed (e.g. comparing against a known substrate-contact facet) before trusting a default.

  • label (str, default: None ) –
Returns:
  • –

    self (for method chaining)

Note: The strain values are printed on addition so you can verify the mismatch.

Source code in src/nrxrdct/laue/layers.py
    def add_pseudomorphic_layer_nonpolar(
        self,
        crystal,
        U,
        thickness,
        a_substrate,
        c_substrate,
        C11: float,
        C12: float,
        C13: float,
        growth_hkl=(1, 0, 0),
        label=None,
    ):
        """
        Append a pseudomorphically strained layer grown on a **non-polar**
        hexagonal surface (m-plane `{1,0,-1,0}` or a-plane `{1,1,-2,0}`) to
        the repeating unit.

        Equivalent to calling :func:`pseudomorphic_d_spacing_nonpolar` then
        :meth:`add_layer` with the computed `d_spacing` -- see that
        function's docstring for the full derivation and for why
        :meth:`add_pseudomorphic_layer` (the `c`-axis version) cannot be
        reused here: non-polar growth strains **two** elastically
        inequivalent in-plane directions (`c` itself, and the remaining
        in-plane `a`-type direction) differently, so it needs both
        substrate lattice parameters and three stiffness constants
        (`C11`, `C12`, `C13`), not one parameter and two constants
        (`C13`, `C33`).

        Args:
            crystal (xu.materials.Crystal): Bulk (relaxed) film crystal.
            U ((3,3) ndarray): Orientation matrix for this layer -- from :func:`orientation_along_plane`
                (or a fitted Laue orientation), **not** `orientation_along_z`.
            thickness (float): Physical thickness of the layer in Å.
            a_substrate, c_substrate (float): or  xu.materials.Crystal
                In-plane `a`- and `c`-parameters of the template (Å), or
                Crystals whose `.lattice.a` / `.lattice.c` are used.
            C11, C12, C13 (float): Elastic stiffness constants (GPa).
            growth_hkl (array-like (3,), optional): Miller **plane** indices of the growth surface (default `(1,0,0)`).
                Must match whichever specific `{1,0,-1,0}`-family member is
                physically correct for *this* `U` -- there are 6
                symmetry-equivalent choices around the hexagonal cross-section,
                and nothing here can infer which one your crystal/orientation
                actually uses; check against known geometry as needed (e.g.
                comparing against a known substrate-contact facet) before
                trusting a default.
            label (str, optional):

        Returns:
            self  (for method chaining)

        Note:
        The strain values are printed on addition so you can verify the
        mismatch.
"""
        d_strained, eps_a, eps_c, eps_perp = pseudomorphic_d_spacing_nonpolar(
            crystal, a_substrate, c_substrate, C11, C12, C13, growth_hkl
        )
        lbl = label or crystal.name
        print(
            f"  {lbl}: ε_a = {eps_a:+.4f}  ε_c = {eps_c:+.4f}  ε_⊥ = {eps_perp:+.4f}"
            f"  d_bulk → {d_strained / (1 + eps_perp):.4f} Å"
            f"  d_strained = {d_strained:.4f} Å"
        )
        return self.add_layer(crystal, U, thickness, d_spacing=d_strained, label=lbl)

average_structure_factor

average_structure_factor(Q_lab, energy_eV, kf_hat=None)

Structure factor of the thickness-weighted average unit cell at Q_lab.

Instead of summing layer amplitudes with their relative depth phases (the coherent model), this method sums F_uc_i × N_eff_i over all layers without the inter-layer phase factors exp(i Q_n z_{0,i}). The result is the structural envelope of the diffraction pattern: the intensity it predicts at any Q is the maximum each satellite could reach if all unit cells happened to scatter perfectly in phase.

This approximation is useful to:

  • predict which satellite positions carry significant scattering power based on the average composition, before running the slower coherent simulation;
  • compare the coherent fringe pattern against its envelope to isolate which features arise from constructive interference vs. from the unit cell structure factor.

All absorption corrections (Beer-Lambert two-beam depth limit, overlying-layer attenuation) are applied identically to :meth:structure_factor.

Parameters:
  • Q_lab (array - like(3)) –

    Scattering vector in the lab frame (Å⁻¹).

  • energy_eV (float) –

    Photon energy (eV).

  • kf_hat (array - like(3) or None, default: None ) –

    Diffracted beam unit vector for the two-beam absorption correction.

Returns:
  • F( complex ) –

    (electron units)

Source code in src/nrxrdct/laue/layers.py
    def average_structure_factor(self, Q_lab, energy_eV, kf_hat=None):
        """
        Structure factor of the thickness-weighted average unit cell at Q_lab.

        Instead of summing layer amplitudes with their relative depth phases
        (the coherent model), this method sums `F_uc_i × N_eff_i` over all
        layers **without** the inter-layer phase factors
        `exp(i Q_n z_{0,i})`.  The result is the *structural envelope* of
        the diffraction pattern: the intensity it predicts at any Q is the
        maximum each satellite could reach if all unit cells happened to
        scatter perfectly in phase.

        This approximation is useful to:

        * predict which satellite positions carry significant scattering power
          based on the average composition, before running the slower coherent
          simulation;
        * compare the coherent fringe pattern against its envelope to isolate
          which features arise from constructive interference vs. from the unit
          cell structure factor.

        All absorption corrections (Beer-Lambert two-beam depth limit,
        overlying-layer attenuation) are applied identically to
        :meth:`structure_factor`.

        Args:
            Q_lab (array-like (3,)): Scattering vector in the lab frame (Å⁻¹).
            energy_eV (float): Photon energy (eV).
            kf_hat (array-like (3,) or None): Diffracted beam unit vector for the two-beam absorption correction.

        Returns:
            F (complex): (electron units)
"""
        self._update_offsets()
        Q = np.asarray(Q_lab, dtype=float)
        Qn = float(np.dot(Q, self.n_hat))

        # ── Overlying-layer transmission (identical to structure_factor) ──────
        def _T_slab(lyr, thickness):
            if kf_hat is None:
                return 1.0
            mu = lyr._linear_mu(energy_eV)
            if mu <= 0:
                return 1.0
            kf = np.asarray(kf_hat, dtype=float)
            cos_in  = max(abs(float(self.n_hat[0])), 1e-3)
            cos_out = max(abs(float(np.dot(self.n_hat, kf))), 1e-3)
            return float(np.exp(-mu * thickness * (1.0 / cos_in + 1.0 / cos_out)))

        T_block = []
        for blk in self._blocks:
            T = 1.0
            for lyr in blk.layers:
                T *= _T_slab(lyr, lyr.thickness * blk.n_rep)
            T_block.append(T)

        n_blk = len(self._blocks)
        T_above_block = [1.0] * n_blk
        T_run = 1.0
        for i in range(n_blk - 1, -1, -1):
            T_above_block[i] = T_run
            T_run *= T_block[i]
        T_above_all_blocks = T_run

        # ── Buffer layers — coherent sum with depth phase offsets ─────────────
        # Buffer layers are not part of any periodic block; their positions
        # are fixed and their phase offsets must be kept even in average mode.
        F_total = 0.0 + 0j
        for i, (layer, z0) in enumerate(
                zip(self.buffer_layers, self._buffer_z_offsets)):
            T_above = T_above_all_blocks
            for j in range(i + 1, len(self.buffer_layers)):
                T_above *= _T_slab(self.buffer_layers[j],
                                   self.buffer_layers[j].thickness)
            Q_cry = layer.U.T @ Q
            F_uc = layer.crystal.StructureFactor(Q_cry, en=energy_eV)
            if not (np.isfinite(F_uc.real) and np.isfinite(F_uc.imag)):
                continue
            n_eff = (layer._effective_n_cells(energy_eV, kf_hat=kf_hat)
                     if layer.absorption_limit else layer.n_cells)
            F_total += T_above * F_uc * n_eff * np.exp(1j * Qn * z0)

        # ── Repeating blocks — average over each period, keep S_rep ──────────
        # Sum F_uc_i × N_cells_i over one block period WITHOUT intra-period
        # phase factors (z_rel).  The inter-period interference is still
        # captured by the geometric series S_rep, so satellite peaks appear at
        # the correct positions with N_rep²-enhanced intensities.
        for i, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            F_unit = 0.0 + 0j
            for layer in blk.layers:
                Q_cry = layer.U.T @ Q
                F_uc = layer.crystal.StructureFactor(Q_cry, en=energy_eV)
                if not (np.isfinite(F_uc.real) and np.isfinite(F_uc.imag)):
                    continue
                F_unit += F_uc * layer.n_cells

            Lambda  = blk._period
            phi_rep = Qn * Lambda
            phi_mod = phi_rep % (2.0 * np.pi)
            if abs(phi_mod) < 1e-10 or abs(phi_mod - 2.0 * np.pi) < 1e-10:
                S_rep = float(blk.n_rep) + 0j
            else:
                S_rep = ((1.0 - np.exp(1j * blk.n_rep * phi_rep))
                         / (1.0 - np.exp(1j * phi_rep)))
            F_total += (T_above_block[i] * np.exp(1j * Qn * blk._z_start)
                        * F_unit * S_rep)

        return F_total

average_structure_factor_batch

average_structure_factor_batch(Q_lab_arr, energy_eV, kf_hat_arr=None)

Vectorised :meth:average_structure_factor for many Q_lab (and, optionally, many kf_hat) at once, evaluated against a single reference energy — see :meth:structure_factor_batch for the approximation this implies (exact in Q, approximate in the smooth f'(E)/f''(E) dispersion terms only).

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

    Scattering vectors in the lab frame (Å⁻¹).

  • energy_eV (float) –

    Reference photon energy (eV).

  • kf_hat_arr ((ndarray, shape(N, 3) or None), default: None ) –

    Per-row diffracted-beam unit vectors for the two-beam absorption correction; None uses the one-beam correction.

Returns:
  • –

    ndarray, shape (N,), complex.

Source code in src/nrxrdct/laue/layers.py
    def average_structure_factor_batch(self, Q_lab_arr, energy_eV, kf_hat_arr=None):
        """
        Vectorised :meth:`average_structure_factor` for many `Q_lab` (and,
        optionally, many `kf_hat`) at once, evaluated against a single
        reference energy — see :meth:`structure_factor_batch` for the
        approximation this implies (exact in Q, approximate in the smooth
        `f'(E)`/`f''(E)` dispersion terms only).

        Args:
            Q_lab_arr (ndarray, shape (N, 3)): Scattering vectors in the lab frame (Å⁻¹).
            energy_eV (float): Reference photon energy (eV).
            kf_hat_arr (ndarray, shape (N, 3) or None): Per-row diffracted-beam unit vectors for the two-beam
                absorption correction; `None` uses the one-beam correction.

        Returns:
            ndarray, shape (N,), complex.
"""
        self._update_offsets()
        Q_lab_arr = np.asarray(Q_lab_arr, dtype=float)
        n = len(Q_lab_arr)
        Qn = Q_lab_arr @ self.n_hat

        def _T_slab_batch(lyr, thickness):
            if kf_hat_arr is None:
                return np.ones(n)
            mu = lyr._linear_mu(energy_eV)
            if mu <= 0:
                return np.ones(n)
            cos_in = max(abs(float(self.n_hat[0])), 1e-3)
            cos_out = np.maximum(np.abs(kf_hat_arr @ self.n_hat), 1e-3)
            return np.exp(-mu * thickness * (1.0 / cos_in + 1.0 / cos_out))

        T_block = []
        for blk in self._blocks:
            T = np.ones(n)
            for lyr in blk.layers:
                T = T * _T_slab_batch(lyr, lyr.thickness * blk.n_rep)
            T_block.append(T)

        n_blk = len(self._blocks)
        T_above_block = [np.ones(n) for _ in range(n_blk)]
        T_run = np.ones(n)
        for i in range(n_blk - 1, -1, -1):
            T_above_block[i] = T_run
            T_run = T_run * T_block[i]
        T_above_all_blocks = T_run

        # ── Buffer layers — coherent sum with depth phase offsets (branches on
        #    absorption_limit, matching the scalar method) ─────────────────────
        F_total = np.zeros(n, dtype=complex)
        for i, (layer, z0) in enumerate(zip(self.buffer_layers, self._buffer_z_offsets)):
            T_above = T_above_all_blocks.copy()
            for j in range(i + 1, len(self.buffer_layers)):
                T_above = T_above * _T_slab_batch(
                    self.buffer_layers[j], self.buffer_layers[j].thickness
                )
            F_uc = layer._structure_factor_uc_batch(Q_lab_arr, energy_eV)
            n_eff = (
                layer._effective_n_cells_batch(energy_eV, kf_hat_arr=kf_hat_arr, n_points=n)
                if layer.absorption_limit
                else np.full(n, float(layer.n_cells))
            )
            F_total += T_above * F_uc * n_eff * np.exp(1j * Qn * z0)

        # ── Repeating blocks — average over each period (no absorption_limit
        #    branch on the block layers, matching the scalar method) ──────────
        for i, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            F_unit = np.zeros(n, dtype=complex)
            for layer in blk.layers:
                F_uc = layer._structure_factor_uc_batch(Q_lab_arr, energy_eV)
                F_unit += F_uc * float(layer.n_cells)

            Lambda = blk._period
            phi_rep = Qn * Lambda
            S_rep = _geometric_sum_batch(blk.n_rep, phi_rep)
            F_total += (T_above_block[i] * np.exp(1j * Qn * blk._z_start)
                        * F_unit * S_rep)

        return F_total

copy

copy() -> LayeredCrystal

Return an independent deep copy of this stack -- every layer's material, orientation, thickness, and the block/buffer structure are duplicated, so mutating the copy (e.g. via :meth:rotate, set_U, or reassigning layer.U directly) never affects the original, and vice versa.

Implemented as a dill round-trip (the same mechanism as :meth:save/:meth:load) rather than copy.deepcopy, since it is already proven to correctly duplicate the xu.materials.Crystal / Alloy objects each layer holds.

Returns:
  • LayeredCrystal( LayeredCrystal ) –

    a new instance, == in content but is not this stack (nor is any of

  • LayeredCrystal –

    its layers is a layer of this stack).

Source code in src/nrxrdct/laue/layers.py
    def copy(self) -> "LayeredCrystal":
        """
        Return an independent deep copy of this stack -- every layer's
        material, orientation, thickness, and the block/buffer structure are
        duplicated, so mutating the copy (e.g. via :meth:`rotate`, `set_U`,
        or reassigning `layer.U` directly) never affects the original, and
        vice versa.

        Implemented as a `dill` round-trip (the same mechanism as
        :meth:`save`/:meth:`load`) rather than `copy.deepcopy`, since it is
        already proven to correctly duplicate the `xu.materials.Crystal` /
        `Alloy` objects each layer holds.

        Returns:
            LayeredCrystal: a new instance, `==` in content but `is not` this stack (nor is any of
            its layers `is` a layer of this stack).
"""
        return dill.loads(dill.dumps(self))

describe

describe()

Print a summary of the stack.

Source code in src/nrxrdct/laue/layers.py
def describe(self):
    """Print a summary of the stack."""
    self._update_offsets()
    nh = self.n_hat
    W = 56

    def _layer_row(i, layer, z0_abs):
        lat = layer.crystal.lattice
        print(
            f"    [{i}] {layer.label:22s} "
            f"{layer.n_cells:5d} cells × {layer.d:.4f} Å"
            f" = {layer.thickness:9.3f} Å   z = {z0_abs:.1f} Å"
        )
        print(
            f"         SG {lat.space_group}  "
            f"a={lat.a:.4f}  b={lat.b:.4f}  c={lat.c:.4f} Å"
        )

    beam_angle_deg = np.degrees(np.arccos(np.clip(abs(float(nh[0])), 0.0, 1.0)))
    print(f"\n  LayeredCrystal: '{self.name}'")
    print(f"  {'─'*W}")
    print(f"  Stacking / surface normal (lab): [{nh[0]:+.4f}, {nh[1]:+.4f}, {nh[2]:+.4f}]"
          f"   beam angle = {beam_angle_deg:.1f}°")

    # Buffer layers
    if self.buffer_layers:
        print(
            f"\n  Buffer layers  (non-repeating, {len(self.buffer_layers)} layer"
            f"{'s' if len(self.buffer_layers) != 1 else ''}):"
        )
        for i, (layer, z0) in enumerate(
            zip(self.buffer_layers, self._buffer_z_offsets)
        ):
            _layer_row(i, layer, z0)
    else:
        print(f"\n  Buffer layers: none")

    # Repeating blocks
    if self._blocks:
        for bi, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            print(
                f"\n  Repeating block [{bi}]  (× {blk.n_rep},"
                f" starts at z = {blk._z_start:.1f} Å):"
            )
            for i, (layer, z0) in enumerate(zip(blk.layers, blk._z_offsets)):
                _layer_row(i, layer, blk._z_start + z0)
            Lambda = blk._period
            print(f"    Block period  Λ = {Lambda:.4f} Å")
            if Lambda > 1e-6:
                print(f"    Satellite spacing 2π/Λ = {2*np.pi/Lambda:.5f} Å⁻¹")
    else:
        print(f"\n  Repeating blocks: none")

    print(
        f"\n  Total thickness = {self.total_thickness:.2f} Å"
        f"  = {self.total_thickness/10:.2f} nm"
    )
    print(f"  {'─'*W}")

intensity

intensity(Q_arr, energy_eV)

Compute |F(Q)|² for an array of Q-points.

Parameters:
  • Q_arr ((array - like, shape(N, 3))) –

    scattering vectors in lab frame

  • energy_eV –

    float photon energy (eV)

Returns:
  • I( (ndarray, shape(N)) ) –

    |F(Q)|² in (electron units)²

Source code in src/nrxrdct/laue/layers.py
    def intensity(self, Q_arr, energy_eV):
        """
        Compute |F(Q)|² for an array of Q-points.

        Args:
            Q_arr (array-like, shape (N, 3)): scattering vectors in lab frame
            energy_eV: float                      photon energy (eV)

        Returns:
            I (ndarray, shape (N,)): |F(Q)|² in (electron units)²
"""
        Q_arr = np.asarray(Q_arr, dtype=float)
        return np.array([abs(self.structure_factor(Q, energy_eV)) ** 2 for Q in Q_arr])

layer_contributions

layer_contributions(Q_lab, energy_eV)

Return the individual structure factor contribution of each layer.

Buffer layers are included at their absolute z positions. Layers of every repeating block are included for the first repetition of their own block only (z0 relative to that block's start position), without the superlattice factor.

Parameters:
  • Q_lab (array - like(3)) –
  • energy_eV –

    float

Returns:
  • –

    dict { label (complex F_layer }):

Source code in src/nrxrdct/laue/layers.py
    def layer_contributions(self, Q_lab, energy_eV):
        """
        Return the individual structure factor contribution of each layer.

        Buffer layers are included at their absolute z positions.  Layers of
        every repeating block are included for the *first* repetition of
        their own block only (z0 relative to that block's start position),
        without the superlattice factor.

        Args:
            Q_lab (array-like (3,)):
            energy_eV: float

        Returns:
            dict  { label (complex F_layer }):
"""
        self._update_offsets()
        Q = np.asarray(Q_lab, dtype=float)
        result = {}
        for layer, z0 in zip(self.buffer_layers, self._buffer_z_offsets):
            F = layer.structure_factor(Q, energy_eV, z0=z0)
            result[layer.label] = result.get(layer.label, 0j) + F
        for blk in self._blocks:
            for layer, z0 in zip(blk.layers, blk._z_offsets):
                F = layer.structure_factor(Q, energy_eV, z0=blk._z_start + z0)
                result[layer.label] = result.get(layer.label, 0j) + F
        return result

load classmethod

load(path: str) -> LayeredCrystal

Load a stack previously saved with :meth:save.

Parameters:
  • path (str) –

    Path to a file written by :meth:save.

Returns:
  • LayeredCrystal( LayeredCrystal ) –

    the restored stack, with every layer's material, orientation,

  • LayeredCrystal –

    thickness, and block structure intact.

Source code in src/nrxrdct/laue/layers.py
    @classmethod
    def load(cls, path: str) -> "LayeredCrystal":
        """
        Load a stack previously saved with :meth:`save`.

        Args:
            path (str): Path to a file written by :meth:`save`.

        Returns:
            LayeredCrystal: the restored stack, with every layer's material, orientation,
            thickness, and block structure intact.
"""
        with open(path, "rb") as fh:
            stack = dill.load(fh)
        if not isinstance(stack, cls):
            raise TypeError(
                f"{path!r} does not contain a LayeredCrystal "
                f"(got {type(stack).__name__})"
            )
        return stack

plot_lattice_parameter

plot_lattice_parameter(param: str = 'c', unit: str = 'A', ax=None, figsize=(8, 4))

Plot a lattice parameter profile through the stack depth.

Draws a step function showing how param ('a', 'b', or 'c') varies with depth, with buffer layers at the bottom and the surface at the top. Every repeating block is unrolled across all of its own n_rep repetitions, in stack order.

Parameters:
  • param (`'a'` | `'b'` | `'c'`, default: 'c' ) –

    Which lattice parameter to plot.

  • unit (`'A'` | `'nm'`, default: 'A' ) –

    Display unit for the depth axis (Å or nm).

  • ax (Axes, default: None ) –

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

  • figsize ((float, float), default: (8, 4) ) –
Returns:
  • –

    fig, ax

Source code in src/nrxrdct/laue/layers.py
    def plot_lattice_parameter(
        self,
        param: str = "c",
        unit: str = "A",
        ax=None,
        figsize=(8, 4),
    ):
        """
        Plot a lattice parameter profile through the stack depth.

        Draws a step function showing how *param* (`'a'`, `'b'`, or
        `'c'`) varies with depth, with buffer layers at the bottom and the
        surface at the top.  Every repeating block is unrolled across all of
        its own `n_rep` repetitions, in stack order.

        Args:
            param (`'a'` | `'b'` | `'c'`): Which lattice parameter to plot.
            unit (`'A'` | `'nm'`): Display unit for the depth axis (Å or nm).
            ax (matplotlib.axes.Axes, optional): Draw into an existing axes; a new figure is created if `None`.
            figsize ((float, float)):

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

        if param not in ("a", "b", "c"):
            raise ValueError(f"param must be 'a', 'b', or 'c', got {param!r}")
        if unit not in ("A", "nm"):
            raise ValueError(f"unit must be 'A' or 'nm', got {unit!r}")

        self._update_offsets()
        scale = 0.1 if unit == "nm" else 1.0
        unit_label = "nm" if unit == "nm" else "Å"

        # Build full layer sequence with absolute z offsets (bottom = 0)
        # Each entry: (z_start, z_end, layer)
        segments = []
        z = 0.0
        for layer in self.buffer_layers:
            segments.append((z, z + layer.thickness, layer))
            z += layer.thickness
        for blk in self._blocks:
            for _ in range(blk.n_rep):
                for layer in blk.layers:
                    segments.append((z, z + layer.thickness, layer))
                    z += layer.thickness

        # Collect unique phase labels for the legend
        seen_labels = {}
        colors_cycle = plt.get_cmap("tab10")
        color_idx = 0

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

        for z0, z1, layer in segments:
            val = getattr(layer.crystal.lattice, param)
            y0 = z0 * scale
            y1 = z1 * scale
            lbl = layer.label

            if lbl not in seen_labels:
                seen_labels[lbl] = colors_cycle(color_idx / 9)
                color_idx = (color_idx + 1) % 10
            col = seen_labels[lbl]

            # Horizontal bar: lattice parameter value across the layer depth range
            ax.hlines(val, y0, y1, colors=col, linewidths=2.5)
            # Vertical connectors between adjacent layers
            ax.vlines(y0, val, val, colors=col, linewidths=1.0, linestyles="dotted")

        # Draw vertical connectors between adjacent steps
        for i in range(1, len(segments)):
            _, _, layer_prev = segments[i - 1]
            z_curr, _, layer_curr  = segments[i]
            val_prev = getattr(layer_prev.crystal.lattice, param)
            val_curr = getattr(layer_curr.crystal.lattice, param)
            z_joint = z_curr * scale
            ax.vlines(z_joint, min(val_prev, val_curr), max(val_prev, val_curr),
                      colors="#555555", linewidths=0.8, linestyles="--")

        # Legend
        handles = [
            mpatches.Patch(color=col, label=lbl)
            for lbl, col in seen_labels.items()
        ]
        ax.legend(handles=handles, fontsize=8, loc="best",
                  framealpha=0.4, facecolor="#1a1f2e", edgecolor="#3a3f4e",
                  labelcolor="#ccccee")

        ax.set_xlabel(f"depth  ({unit_label})", fontsize=9)
        ax.set_ylabel(f"lattice parameter {param}  (Å)", fontsize=9)
        ax.set_title(
            f"{self.name}  —  lattice parameter {param} profile",
            fontsize=10,
        )
        ax.set_xlim(0, self.total_thickness * scale)

        if standalone:
            fig.tight_layout()

        return fig, ax

plot_strain_profile

plot_strain_profile(param: str = 'c', reference=None, unit: str = 'A', ax=None, figsize=(8, 4))

Plot the strain profile of a lattice parameter through the stack depth.

Strain is defined as

$$ \varepsilon = \frac{p_{\text{layer}} - p_{\text{ref}}}{p_{\text{ref}}} $$ where p is the chosen lattice parameter ('a', 'b', or 'c').

Parameters:
  • param (`'a'` | `'b'` | `'c'`, default: 'c' ) –

    Lattice parameter to use.

  • reference (float, xu.materials.Crystal, or None, default: None ) –

    Reference value for zero strain.

  • unit (`'A'` | `'nm'`, default: 'A' ) –

    Display unit for the depth axis.

  • ax (Axes, default: None ) –
  • figsize ((float, float), default: (8, 4) ) –
Returns:
  • –

    fig, ax

Source code in src/nrxrdct/laue/layers.py
    def plot_strain_profile(
        self,
        param: str = "c",
        reference=None,
        unit: str = "A",
        ax=None,
        figsize=(8, 4),
    ):
        """
        Plot the strain profile of a lattice parameter through the stack depth.

        Strain is defined as

        $$
        \\varepsilon = \\frac{p_{\\text{layer}} - p_{\\text{ref}}}{p_{\\text{ref}}}
        $$
        where *p* is the chosen lattice parameter (`'a'`, `'b'`, or
        `'c'`).

        Args:
            param (`'a'` | `'b'` | `'c'`): Lattice parameter to use.
            reference (float, xu.materials.Crystal, or None): Reference value for zero strain.

            * **float** — use this value directly (Å).
            * **Crystal** — use `crystal.lattice.<param>`.
            * **None** *(default)* — use the lattice parameter of the first
              buffer layer; if there are no buffer layers, use the first
              repeating layer.
            unit (`'A'` | `'nm'`): Display unit for the depth axis.
            ax (matplotlib.axes.Axes, optional):
            figsize ((float, float)):

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

        if param not in ("a", "b", "c"):
            raise ValueError(f"param must be 'a', 'b', or 'c', got {param!r}")
        if unit not in ("A", "nm"):
            raise ValueError(f"unit must be 'A' or 'nm', got {unit!r}")

        self._update_offsets()
        scale = 0.1 if unit == "nm" else 1.0
        unit_label = "nm" if unit == "nm" else "Å"

        # Resolve reference value
        if reference is None:
            ref_layer = (self.buffer_layers or self.layers)[0]
            p_ref = getattr(ref_layer.crystal.lattice, param)
        elif isinstance(reference, (int, float)):
            p_ref = float(reference)
        else:
            # Assume xu.materials.Crystal-like object
            p_ref = float(getattr(reference.lattice, param))

        # Build full layer sequence (same logic as plot_lattice_parameter)
        segments = []
        z = 0.0
        for layer in self.buffer_layers:
            segments.append((z, z + layer.thickness, layer))
            z += layer.thickness
        for blk in self._blocks:
            for _ in range(blk.n_rep):
                for layer in blk.layers:
                    segments.append((z, z + layer.thickness, layer))
                    z += layer.thickness

        seen_labels = {}
        colors_cycle = plt.get_cmap("tab10")
        color_idx = 0

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

        for z0, z1, layer in segments:
            p_val = getattr(layer.crystal.lattice, param)
            strain = (p_val - p_ref) / p_ref
            y0 = z0 * scale
            y1 = z1 * scale
            lbl = layer.label

            if lbl not in seen_labels:
                seen_labels[lbl] = colors_cycle(color_idx / 9)
                color_idx = (color_idx + 1) % 10
            col = seen_labels[lbl]

            ax.hlines(strain, y0, y1, colors=col, linewidths=2.5)

        # Vertical connectors between adjacent steps
        for i in range(1, len(segments)):
            _, _, layer_prev = segments[i - 1]
            z_curr, _, layer_curr = segments[i]
            s_prev = (getattr(layer_prev.crystal.lattice, param) - p_ref) / p_ref
            s_curr = (getattr(layer_curr.crystal.lattice, param) - p_ref) / p_ref
            ax.vlines(z_curr * scale, min(s_prev, s_curr), max(s_prev, s_curr),
                      colors="#555555", linewidths=0.8, linestyles="--")

        # Zero-strain reference line
        ax.axhline(0.0, color="#888888", linewidth=0.8, linestyle=":")

        handles = [
            mpatches.Patch(color=col, label=lbl)
            for lbl, col in seen_labels.items()
        ]
        ax.legend(handles=handles, fontsize=8, loc="best",
                  framealpha=0.4, facecolor="#1a1f2e", edgecolor="#3a3f4e",
                  labelcolor="#ccccee")

        ref_str = f"{p_ref:.4f} Å"
        ax.set_xlabel(f"depth  ({unit_label})", fontsize=9)
        ax.set_ylabel(f"ε_{param}  =  (p − p_ref) / p_ref", fontsize=9)
        ax.set_title(
            f"{self.name}  —  strain profile  [{param},  ref = {ref_str}]",
            fontsize=10,
        )
        ax.set_xlim(0, self.total_thickness * scale)

        if standalone:
            fig.tight_layout()

        return fig, ax

print_reflections

print_reflections(spots, layer=None, *, satellite_order=None, min_intensity=0.0, max_rows=200)

Print the reflections actually present in a spots list for one layer (or every layer), grouped and sorted by intensity.

Meant as a quick answer to "does hkl=... exist in my spots list for this layer?" before calling something like :func:~nrxrdct.laue.simulation.simulate_spot_image, which raises a ValueError naming exactly this hkl/layer/satellite_order combination when it can't find a match — this prints the full picture up front instead of discovering it one failed call at a time.

Parameters:
  • spots (list[dict]) –

    Output of any simulate_laue* function.

  • layer (Layer, str, or None, default: None ) –

    Which layer to list. None (default) lists every layer in self.all_layers in turn.

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

    None (default) shows every satellite order; pass an int (e.g. 0 for main peaks only) to filter to just that order.

  • min_intensity (float, default: 0.0 ) –

    Only show spots with spots[i]['intensity'] (normalised 0-1) at or above this value. Default 0.0 (show everything).

  • max_rows (int, default: 200 ) –

    Truncate the printed table per layer after this many rows (still sorted by intensity first, so the brightest survive).

Returns:
  • –

    None — prints only.

Source code in src/nrxrdct/laue/layers.py
def print_reflections(self, spots, layer=None, *, satellite_order=None,
                       min_intensity=0.0, max_rows=200):
    """
    Print the reflections actually present in a `spots` list for one
    layer (or every layer), grouped and sorted by intensity.

    Meant as a quick answer to "does hkl=... exist in my spots list for
    this layer?" before calling something like
    :func:`~nrxrdct.laue.simulation.simulate_spot_image`, which raises a
    `ValueError` naming exactly this hkl/layer/satellite_order
    combination when it can't find a match — this prints the full
    picture up front instead of discovering it one failed call at a
    time.

    Args:
        spots (list[dict]): Output of any `simulate_laue*` function.
        layer (Layer, str, or None, optional): Which layer to list. `None` (default) lists every layer in
            `self.all_layers` in turn.
        satellite_order (int or None, optional): `None` (default) shows every satellite order; pass an int
            (e.g. `0` for main peaks only) to filter to just that order.
        min_intensity (float, optional): Only show spots with `spots[i]['intensity']` (normalised 0-1) at or
            above this value.  Default `0.0` (show everything).
        max_rows (int, optional): Truncate the printed table per layer after this many rows
            (still sorted by intensity first, so the brightest survive).

    Returns:
        None — prints only.
    """
    if layer is not None:
        labels = [layer.label if hasattr(layer, "label") else layer]
    else:
        labels = [ly.label for ly in self.all_layers]

    for label in labels:
        rows = [
            s for s in spots
            if s.get("phase_label") == label
            and (satellite_order is None or s.get("satellite_order", 0) == satellite_order)
            and s.get("intensity", 1.0) >= min_intensity
        ]
        if not rows:
            print(f"Layer {label!r}: no matching spots in `spots`")
            continue
        rows = sorted(rows, key=lambda s: -s.get("intensity", 0.0))
        print(f"Layer {label!r}: {len(rows)} spot(s)")
        print(f"  {'hkl':<18}{'order':>7}{'E (eV)':>11}{'intensity':>11}  pix")
        for r in rows[:max_rows]:
            hkl_str = str(tuple(int(x) for x in r["hkl"]))
            order = r.get("satellite_order", 0)
            E = r.get("E", float("nan"))
            inten = r.get("intensity", float("nan"))
            pix = r.get("pix")
            pix_str = f"({pix[0]:.1f}, {pix[1]:.1f})" if pix is not None else "None"
            print(f"  {hkl_str:<18}{order:>7}{E:>11.1f}{inten:>11.4f}  {pix_str}")
        if len(rows) > max_rows:
            print(f"  ... ({len(rows) - max_rows} more not shown; increase max_rows)")

rotate

rotate(angle_deg, axis, frame: str = 'lab', layers=None, inplace: bool = True) -> LayeredCrystal

Rotate one or more layers' orientation matrices by angle_deg about axis, in either the lab frame or each layer's own crystal frame.

The two frames compose differently and answer different questions:

  • frame='lab' (default) -- axis is a direction in the lab frame (e.g. vertical [0,0,1], the beam [1,0,0], or any other measured lab-frame direction such as a wire's own long axis). Applied as U_new = R(axis) @ U -- physically, rotating the sample itself on the diffractometer about a fixed external axis. Same convention as :func:~nrxrdct.laue.simulation.rotate_U_about_axis, generalised from 'x'/'y'/'z' to an arbitrary vector.
  • frame='crystal' -- axis is a direction in each selected layer's own crystal frame (e.g. c = [0,0,1]; for a Miller plane normal rather than a real-space direction, convert first with :func:plane_normal_cartesian). Applied as U_new = U @ R(axis) -- physically, twisting the lattice about its own crystallographic axis, independent of the layer's absolute orientation. Because this composes on the right, applying it to several layers with different U (e.g. an independently fitted core and shell) twists each one about its own c, not about a shared lab direction.

A common diagnostic use: probing whether a small residual misorientation between an independently refined core and shell is consistent with a genuine c-axis twisting moment (rather than a fitting artifact) -- e.g. nudging just the shell by a fraction of a degree about its own c and re-comparing against the measured pattern, without disturbing the original stack::

trial = stack.rotate(0.05, [0, 0, 1], frame='crystal',
                      layers='InGaN QW', inplace=False)
# stack is untouched; compare trial's simulated pattern instead.
Parameters:
  • angle_deg (float) –

    Rotation angle in degrees (right-hand rule about axis).

  • axis (array - like(3)) –

    Rotation axis. Interpreted per frame; need not be pre-normalised.

  • frame (`'lab'` or `'crystal'`, default: 'lab' ) –

    Which frame axis is expressed in. Default 'lab'.

  • layers (Layer, str, list, or None, default: None ) –

    Which layer(s) to rotate. None (default) rotates every layer in self.all_layers. A single Layer object or label string, or a list of either, restricts to those layers.

  • inplace (bool, default: True ) –

    True (default) mutates this stack's layers directly and returns self -- matches every other stack-building method (add_layer, set_U, ...). False leaves this stack completely untouched and applies the rotation to a :meth:copy instead, returning that copy -- use this to try a rotation without losing the original.

Returns:
  • LayeredCrystal( LayeredCrystal ) –

    self if inplace=True (the default); otherwise a new, independently

  • LayeredCrystal –

    mutable copy with the rotation applied.

Source code in src/nrxrdct/laue/layers.py
    def rotate(self, angle_deg, axis, frame: str = "lab", layers=None, inplace: bool = True) -> "LayeredCrystal":
        """
        Rotate one or more layers' orientation matrices by `angle_deg` about
        `axis`, in either the lab frame or each layer's own crystal frame.

        The two frames compose differently and answer different questions:

        - **`frame='lab'`** (default) -- `axis` is a direction in the **lab
          frame** (e.g. vertical `[0,0,1]`, the beam `[1,0,0]`, or any other
          measured lab-frame direction such as a wire's own long axis).
          Applied as `U_new = R(axis) @ U` -- physically, rotating the
          sample itself on the diffractometer about a fixed external axis.
          Same convention as
          :func:`~nrxrdct.laue.simulation.rotate_U_about_axis`, generalised
          from `'x'/'y'/'z'` to an arbitrary vector.
        - **`frame='crystal'`** -- `axis` is a direction in **each selected
          layer's own crystal frame** (e.g. `c = [0,0,1]`; for a Miller
          *plane* normal rather than a real-space direction, convert first
          with :func:`plane_normal_cartesian`). Applied as
          `U_new = U @ R(axis)` -- physically, twisting the lattice about
          its own crystallographic axis, independent of the layer's
          absolute orientation. Because this composes on the right, applying
          it to several layers with *different* `U` (e.g. an independently
          fitted core and shell) twists each one about *its own* `c`, not
          about a shared lab direction.

        A common diagnostic use: probing whether a small residual
        misorientation between an independently refined core and shell is
        consistent with a genuine c-axis twisting moment (rather than a
        fitting artifact) -- e.g. nudging just the shell by a fraction of a
        degree about its own `c` and re-comparing against the measured
        pattern, without disturbing the original stack::

            trial = stack.rotate(0.05, [0, 0, 1], frame='crystal',
                                  layers='InGaN QW', inplace=False)
            # stack is untouched; compare trial's simulated pattern instead.

        Args:
            angle_deg (float): Rotation angle in degrees (right-hand rule about `axis`).
            axis (array-like (3,)): Rotation axis. Interpreted per `frame`; need not be
                pre-normalised.
            frame (`'lab'` or `'crystal'`, optional): Which frame `axis` is expressed in. Default `'lab'`.
            layers (Layer, str, list, or None, optional): Which layer(s) to rotate. `None` (default) rotates every
                layer in `self.all_layers`. A single `Layer` object or label
                string, or a list of either, restricts to those layers.
            inplace (bool, optional): `True` (default) mutates this stack's layers directly and returns
                `self` -- matches every other stack-building method
                (`add_layer`, `set_U`, ...). `False` leaves this stack
                completely untouched and applies the rotation to a
                :meth:`copy` instead, returning that copy -- use this to try
                a rotation without losing the original.

        Returns:
            LayeredCrystal: `self` if `inplace=True` (the default); otherwise a new, independently
            mutable copy with the rotation applied.
"""
        if frame not in ("lab", "crystal"):
            raise ValueError(f"frame must be 'lab' or 'crystal', got {frame!r}")

        ax = np.asarray(axis, dtype=float)
        ax_norm = np.linalg.norm(ax)
        if ax_norm < 1e-12:
            raise ValueError(f"axis must be nonzero, got {axis}")
        ax = ax / ax_norm

        R = Rotation.from_rotvec(np.radians(float(angle_deg)) * ax).as_matrix()

        target = self if inplace else self.copy()
        for layer in target._resolve_layers(layers):
            layer.U = (R @ layer.U) if frame == "lab" else (layer.U @ R)
        return target

save

save(path: str) -> None

Save this stack to path via dill, so it can be reloaded later instead of rebuilt from scratch -- resuming a session where you left off, or handing a hand-tuned/fitted stack to :class:~nrxrdct.laue.layered_map.LayeredMap as the starting-point orientation for a per-pixel map (LayeredMap(stack=..., ...)) without re-running the notebook cells that built it.

Round-trips everything: every layer's material (xu.materials.Crystal / Alloy), orientation U, thickness, resolved d-spacing, n_hat, label, and absorption settings, plus the block/repetition structure and buffer layers -- the exact same mechanism already used internally by LayeredMap to ship a stack to local worker processes (see layered_map._serialize_stack), just to a permanent path instead of a temp file.

Parameters:
  • path (str) –

    Destination file path (any extension; .pkl by convention).

Example:

stack.save('gan_mplane_stack.pkl')

...later, or in a different session...

stack = LayeredCrystal.load('gan_mplane_stack.pkl') lmap = LayeredMap(ny=21, nx=21, stack=stack, h5_path='scan.h5')

Source code in src/nrxrdct/laue/layers.py
    def save(self, path: str) -> None:
        """
        Save this stack to *path* via `dill`, so it can be reloaded later
        instead of rebuilt from scratch -- resuming a session where you left
        off, or handing a hand-tuned/fitted stack to
        :class:`~nrxrdct.laue.layered_map.LayeredMap` as the starting-point
        orientation for a per-pixel map (`LayeredMap(stack=..., ...)`)
        without re-running the notebook cells that built it.

        Round-trips everything: every layer's material (`xu.materials.Crystal`
        / `Alloy`), orientation `U`, thickness, resolved `d`-spacing, `n_hat`,
        label, and absorption settings, plus the block/repetition structure
        and buffer layers -- the exact same mechanism already used internally
        by `LayeredMap` to ship a stack to local worker processes (see
        `layered_map._serialize_stack`), just to a permanent path instead of
        a temp file.

        Args:
            path (str): Destination file path (any extension; `.pkl` by convention).

        Example:
        >>> stack.save('gan_mplane_stack.pkl')
        >>> # ...later, or in a different session...
        >>> stack = LayeredCrystal.load('gan_mplane_stack.pkl')
        >>> lmap = LayeredMap(ny=21, nx=21, stack=stack, h5_path='scan.h5')
"""
        with open(path, "wb") as fh:
            dill.dump(self, fh)
        print(f"LayeredCrystal '{self.name}' saved -> {path!r}", flush=True)

set_U

set_U(U) -> LayeredCrystal

Replace the orientation matrix of layers in the stack.

Two calling forms:

Global — apply one U to every layer::

stack.set_U(U)

Per-material — supply a dict mapping crystal name to U; only layers whose crystal.name matches a key are updated::

stack.set_U({'GaN': U_GaN, 'InGaN': U_InGaN})

Layers whose material is not listed in the dict are left unchanged. Useful for modelling domain variants or orientation relationships between different materials in the same stack without rebuilding it.

Parameters:
  • U (array - like(3, 3) or dict[str, array - like(3, 3)]) –

    A single orientation matrix applied to all layers, or a mapping {crystal_name: U_matrix}.

Returns:
Source code in src/nrxrdct/laue/layers.py
    def set_U(self, U) -> "LayeredCrystal":
        """
        Replace the orientation matrix of layers in the stack.

        Two calling forms:

        **Global** — apply one `U` to every layer::

            stack.set_U(U)

        **Per-material** — supply a dict mapping crystal name to `U`; only
        layers whose `crystal.name` matches a key are updated::

            stack.set_U({'GaN': U_GaN, 'InGaN': U_InGaN})

        Layers whose material is not listed in the dict are left unchanged.
        Useful for modelling domain variants or orientation relationships
        between different materials in the same stack without rebuilding it.

        Args:
            U (array-like (3, 3) or dict[str, array-like (3, 3)]): A single orientation matrix applied to all layers, or a mapping
                `{crystal_name: U_matrix}`.

        Returns:
            self  (for method chaining)
"""
        if isinstance(U, dict):
            U_map = {name: np.asarray(mat, dtype=float) for name, mat in U.items()}
            for layer in self.buffer_layers + self.layers:
                if layer.crystal.name in U_map:
                    layer.U = U_map[layer.crystal.name].copy()
        else:
            U_mat = np.asarray(U, dtype=float)
            for layer in self.buffer_layers + self.layers:
                layer.U = U_mat.copy()
        return self

set_repetitions

set_repetitions(n)

Set the repeat count of the currently open block (the layers added since the previous set_repetitions call, or since the stack was created) and close it.

The next :meth:add_layer call starts a brand-new block, so calling add_layer(...) a few times then set_repetitions(N), repeated as many times as needed, is how you build a sequence of independently-repeated blocks -- see :meth:add_layer.

Source code in src/nrxrdct/laue/layers.py
    def set_repetitions(self, n):
        """
        Set the repeat count of the **currently open block** (the layers
        added since the previous `set_repetitions` call, or since the stack
        was created) and close it.

        The next :meth:`add_layer` call starts a brand-new block, so
        calling `add_layer(...)` a few times then `set_repetitions(N)`,
        repeated as many times as needed, is how you build a sequence of
        independently-repeated blocks -- see :meth:`add_layer`.
"""
        if not self._blocks:
            raise ValueError(
                "set_repetitions() has nothing to act on -- call add_layer(...) "
                "at least once first to define the block to repeat."
            )
        self._blocks[-1].n_rep = int(n)
        self._blocks[-1]._closed = True
        return self

structure_factor

structure_factor(Q_lab, energy_eV, kf_hat=None)

Total kinematical structure factor of the stack at Q_lab.

The stack is divided into two sections:

  1. Buffer layers (non-repeating, at the bottom):

    F_buf(Q) = Σ_j T_above_j · F_layer_j(Q, z0_j)

where T_above_j is the amplitude attenuation from all layers above layer j (both the MQW block and the shallower buffer layers).

  1. Repeating unit (MQW / bilayer, sitting on top of the buffer):

    F_MQW(Q) = exp(i·Qₙ·z_buf) · F_unit(Q) · S_rep(Q)

where z_buf is the total buffer thickness, F_unit is the single-bilayer structure factor, and

   S_rep(Q) = Σ_{m=0}^{N_rep-1} exp(i·m·Qₙ·Λ)

is the superlattice geometric factor.

The total structure factor is F_buf + F_MQW.

Parameters:
  • Q_lab (array - like(3)) –

    scattering vector in lab frame (Å⁻¹)

  • energy_eV –

    float photon energy (eV)

  • kf_hat (array - like(3) or None, default: None ) –

    Unit vector of the diffracted beam in the lab frame. When provided, the exit-path absorption through each overlying layer is included via the two-beam transmission factor

    T = exp(−μ · t · (1/cos_in + 1/cos_out))

Returns:
  • F( complex ) –

    total structure factor (electron units)

Source code in src/nrxrdct/laue/layers.py
    def structure_factor(self, Q_lab, energy_eV, kf_hat=None):
        """
        Total kinematical structure factor of the stack at Q_lab.

        The stack is divided into two sections:

        1. **Buffer layers** (non-repeating, at the bottom):

               F_buf(Q) = Σ_j  T_above_j · F_layer_j(Q, z0_j)

           where `T_above_j` is the amplitude attenuation from all layers
           above layer *j* (both the MQW block and the shallower buffer layers).

        2. **Repeating unit** (MQW / bilayer, sitting on top of the buffer):

               F_MQW(Q) = exp(i·Qₙ·z_buf) · F_unit(Q) · S_rep(Q)

           where `z_buf` is the total buffer thickness,
           `F_unit` is the single-bilayer structure factor, and

               S_rep(Q) = Σ_{m=0}^{N_rep-1} exp(i·m·Qₙ·Λ)

           is the superlattice geometric factor.

        The total structure factor is `F_buf + F_MQW`.

        Args:
            Q_lab (array-like (3,)): scattering vector in lab frame  (Å⁻¹)
            energy_eV: float             photon energy  (eV)
            kf_hat (array-like (3,) or None): Unit vector of the diffracted beam in the lab frame.  When
                provided, the **exit-path** absorption through each overlying layer
                is included via the two-beam transmission factor

                T = exp(−μ · t · (1/cos_in + 1/cos_out))

            where `cos_in = |n̂ · x̂|` and `cos_out = |n̂ · k̂_f|`.
            If `None`, only the incident-path (one-beam) correction already
            embedded in each buffer layer's `_effective_n_cells` is applied.

        Returns:
            F (complex): total structure factor (electron units)
"""
        self._update_offsets()
        Q = np.asarray(Q_lab, dtype=float)
        Qn = float(np.dot(Q, self.n_hat))

        # ── Overlying-layer transmission helper ───────────────────────────────
        def _T_slab(lyr, thickness):
            """Amplitude transmission exp(-μ·t·(1/cos_in + 1/cos_out))."""
            if kf_hat is None:
                return 1.0
            mu = lyr._linear_mu(energy_eV)
            if mu <= 0:
                return 1.0
            kf = np.asarray(kf_hat, dtype=float)
            cos_in  = max(abs(float(self.n_hat[0])), 1e-3)
            cos_out = max(abs(float(np.dot(self.n_hat, kf))), 1e-3)
            return float(np.exp(-mu * thickness * (1.0 / cos_in + 1.0 / cos_out)))

        # Transmission through each repeating block, taken as a whole (all
        # n_rep periods of it) -- this is how much a block above attenuates
        # everything sitting below it.
        T_block = []
        for blk in self._blocks:
            T = 1.0
            for lyr in blk.layers:
                T *= _T_slab(lyr, lyr.thickness * blk.n_rep)
            T_block.append(T)

        # T_above_block[i] = transmission through every block strictly above
        # block i (i.e. blocks[i+1:], since blocks are stored bottom to top).
        n_blk = len(self._blocks)
        T_above_block = [1.0] * n_blk
        T_run = 1.0
        for i in range(n_blk - 1, -1, -1):
            T_above_block[i] = T_run
            T_run *= T_block[i]
        T_above_all_blocks = T_run   # transmission through the ENTIRE repeating section

        # ── Buffer layers (non-repeating, deepest) ────────────────────────────
        F_total = 0.0 + 0j
        for i, (layer, z0) in enumerate(zip(self.buffer_layers, self._buffer_z_offsets)):
            # Attenuation from: every repeating block above + shallower buffer layers
            T_above = T_above_all_blocks
            for j in range(i + 1, len(self.buffer_layers)):
                T_above *= _T_slab(self.buffer_layers[j],
                                   self.buffer_layers[j].thickness)
            F_total += T_above * layer.structure_factor(Q, energy_eV, z0=z0,
                                                        kf_hat=kf_hat)

        # ── Repeating blocks (bottom to top) ──────────────────────────────────
        for i, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            F_unit = 0.0 + 0j
            for layer, z0 in zip(blk.layers, blk._z_offsets):
                F_unit += layer.structure_factor(Q, energy_eV, z0=z0,
                                                 kf_hat=kf_hat)

            # Phase to shift this block to its z position in the stack
            phase_start = np.exp(1j * Qn * blk._z_start)

            # Geometric sum over this block's own n_rep repetitions
            Lambda = blk._period
            phi_rep = Qn * Lambda
            phi_mod = phi_rep % (2.0 * np.pi)
            if abs(phi_mod) < 1e-10 or abs(phi_mod - 2 * np.pi) < 1e-10:
                S_rep = blk.n_rep + 0j
            else:
                S_rep = (1.0 - np.exp(1j * blk.n_rep * phi_rep)) / (
                    1.0 - np.exp(1j * phi_rep)
                )

            F_total += T_above_block[i] * phase_start * F_unit * S_rep

        return F_total

structure_factor_batch

structure_factor_batch(Q_lab_arr, energy_eV, kf_hat_arr=None)

Vectorised :meth:structure_factor for many Q_lab (and, optionally, many kf_hat) at once.

Identical physics to the scalar method, with one approximation: the unit-cell structure factor F_uc(Q, E) is evaluated at a single reference energy for the whole batch (via Layer.structure_factor_batch → xu.materials.Crystal.StructureFactorForQ) instead of each row's own energy. This only affects the smooth f'(E)/f''(E) anomalous-dispersion terms — safe away from absorption edges — and is what makes the batch path fast: it turns len(all_layers) × N scalar xrayutilities calls into len(all_layers) vectorised ones. Everything else (Q-dependence, geometry, per-voxel absorption via kf_hat_arr) is exact and per-row.

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

    Scattering vectors in the lab frame (Å⁻¹).

  • energy_eV (float) –

    Reference photon energy (eV) for the F_uc evaluation — e.g. the median energy of the batch.

  • kf_hat_arr ((ndarray, shape(N, 3) or None), default: None ) –

    Per-row diffracted-beam unit vectors for the two-beam absorption correction; None uses the one-beam correction (same convention as :meth:structure_factor).

Returns:
  • –

    ndarray, shape (N,), complex — total stack structure factor per row.

Source code in src/nrxrdct/laue/layers.py
    def structure_factor_batch(self, Q_lab_arr, energy_eV, kf_hat_arr=None):
        """
        Vectorised :meth:`structure_factor` for many `Q_lab` (and,
        optionally, many `kf_hat`) at once.

        Identical physics to the scalar method, with one approximation: the
        unit-cell structure factor `F_uc(Q, E)` is evaluated at a **single**
        reference energy for the whole batch (via `Layer.structure_factor_batch`
        → `xu.materials.Crystal.StructureFactorForQ`) instead of each row's own
        energy. This only affects the smooth `f'(E)`/`f''(E)` anomalous-dispersion
        terms — safe away from absorption edges — and is what makes the batch
        path fast: it turns `len(all_layers) × N` scalar xrayutilities calls into
        `len(all_layers)` vectorised ones. Everything else (Q-dependence,
        geometry, per-voxel absorption via `kf_hat_arr`) is exact and
        per-row.

        Args:
            Q_lab_arr (ndarray, shape (N, 3)): Scattering vectors in the lab frame (Å⁻¹).
            energy_eV (float): Reference photon energy (eV) for the `F_uc` evaluation —
                e.g. the median energy of the batch.
            kf_hat_arr (ndarray, shape (N, 3) or None): Per-row diffracted-beam unit vectors for the two-beam
                absorption correction; `None` uses the one-beam correction
                (same convention as :meth:`structure_factor`).

        Returns:
            ndarray, shape (N,), complex — total stack structure factor per row.
"""
        self._update_offsets()
        Q_lab_arr = np.asarray(Q_lab_arr, dtype=float)
        n = len(Q_lab_arr)
        Qn = Q_lab_arr @ self.n_hat

        def _T_slab_batch(lyr, thickness):
            if kf_hat_arr is None:
                return np.ones(n)
            mu = lyr._linear_mu(energy_eV)
            if mu <= 0:
                return np.ones(n)
            cos_in = max(abs(float(self.n_hat[0])), 1e-3)
            cos_out = np.maximum(np.abs(kf_hat_arr @ self.n_hat), 1e-3)
            return np.exp(-mu * thickness * (1.0 / cos_in + 1.0 / cos_out))

        T_block = []
        for blk in self._blocks:
            T = np.ones(n)
            for lyr in blk.layers:
                T = T * _T_slab_batch(lyr, lyr.thickness * blk.n_rep)
            T_block.append(T)

        n_blk = len(self._blocks)
        T_above_block = [np.ones(n) for _ in range(n_blk)]
        T_run = np.ones(n)
        for i in range(n_blk - 1, -1, -1):
            T_above_block[i] = T_run
            T_run = T_run * T_block[i]
        T_above_all_blocks = T_run

        F_total = np.zeros(n, dtype=complex)
        for i, (layer, z0) in enumerate(zip(self.buffer_layers, self._buffer_z_offsets)):
            T_above = T_above_all_blocks.copy()
            for j in range(i + 1, len(self.buffer_layers)):
                T_above = T_above * _T_slab_batch(
                    self.buffer_layers[j], self.buffer_layers[j].thickness
                )
            F_total += T_above * layer.structure_factor_batch(
                Q_lab_arr, energy_eV, z0=z0, kf_hat_arr=kf_hat_arr
            )

        for i, blk in enumerate(self._blocks):
            if not blk.layers:
                continue
            F_unit = np.zeros(n, dtype=complex)
            for layer, z0 in zip(blk.layers, blk._z_offsets):
                F_unit += layer.structure_factor_batch(
                    Q_lab_arr, energy_eV, z0=z0, kf_hat_arr=kf_hat_arr
                )

            phase_start = np.exp(1j * Qn * blk._z_start)
            Lambda = blk._period
            phi_rep = Qn * Lambda
            S_rep = _geometric_sum_batch(blk.n_rep, phi_rep)

            F_total += T_above_block[i] * phase_start * F_unit * S_rep

        return F_total

combine_stacks

combine_stacks(stacks, name='combined')

Merge an ordered sequence of LayeredCrystal objects (bottom to top) into one flat LayeredCrystal with every repeating block unrolled (so the result has no blocks of its own, only a single implicit non-repeating one).

Each sub-stack's buffer layers are transferred in order as buffer layers of the combined stack. Each of the sub-stack's repeating blocks (whether it has one or several -- see :meth:LayeredCrystal.add_layer) is unrolled across its own n_rep as individual flat layers, preserving crystal, orientation matrix, physical thickness, and d-spacing. The result has a single coherent structure factor that sums over the entire multi-section sequence with the correct inter-layer phase relationships.

This is also the way to make a multi-block stack usable with single-block-only consumers (e.g. :func:~nrxrdct.laue.simulate_laue_stack): flatten it first with combine_stacks([my_multi_block_stack]).

Parameters:
  • stacks –

    iterable of LayeredCrystal, or dict[str, LayeredCrystal] Sub-stacks in physical order, bottom (substrate side) first. If a dict is passed its values are used in insertion order.

  • name –

    str, optional Name for the returned combined stack.

Returns:
  • combined –

    LayeredCrystal with every layer unrolled into one block.

Example

stacks = build_ebl_qw_stacks() # returns dict full = combine_stacks(stacks, name="full LED stack") spots = simulate_laue_stack(full, cam, structure_model='coherent')

Source code in src/nrxrdct/laue/layers.py
def combine_stacks(stacks, name="combined"):
    """
    Merge an ordered sequence of LayeredCrystal objects (bottom to top) into
    one flat LayeredCrystal with every repeating block unrolled (so the
    result has no blocks of its own, only a single implicit non-repeating
    one).

    Each sub-stack's buffer layers are transferred in order as buffer layers
    of the combined stack.  Each of the sub-stack's repeating blocks
    (whether it has one or several -- see :meth:`LayeredCrystal.add_layer`)
    is unrolled across its own `n_rep` as individual flat layers, preserving
    crystal, orientation matrix, physical thickness, and d-spacing.  The
    result has a single coherent structure factor that sums over the entire
    multi-section sequence with the correct inter-layer phase relationships.

    This is also the way to make a multi-block stack usable with
    single-block-only consumers (e.g. :func:`~nrxrdct.laue.simulate_laue_stack`):
    flatten it first with `combine_stacks([my_multi_block_stack])`.

    Args:
        stacks : iterable of LayeredCrystal, or dict[str, LayeredCrystal]
            Sub-stacks in physical order, bottom (substrate side) first.
            If a dict is passed its values are used in insertion order.
        name : str, optional
            Name for the returned combined stack.

    Returns:
        combined : LayeredCrystal with every layer unrolled into one block.

    Example:
        >>> stacks = build_ebl_qw_stacks()               # returns dict
        >>> full = combine_stacks(stacks, name="full LED stack")
        >>> spots = simulate_laue_stack(full, cam, structure_model='coherent')
    """
    if isinstance(stacks, dict):
        stacks = list(stacks.values())
    else:
        stacks = list(stacks)
    if not stacks:
        raise ValueError("stacks must be non-empty")

    n_hat = stacks[0].n_hat.copy()
    combined = LayeredCrystal(name=name, stacking_direction=n_hat)

    for stack in stacks:
        stack._update_offsets()
        for lyr in stack.buffer_layers:
            combined.add_buffer_layer(
                lyr.crystal, lyr.U.copy(), lyr.thickness,
                d_spacing=lyr.d, label=lyr.label,
            )
        for blk in stack.blocks:
            for _ in range(blk.n_rep):
                for lyr in blk.layers:
                    combined.add_layer(
                        lyr.crystal, lyr.U.copy(), lyr.thickness,
                        d_spacing=lyr.d, label=lyr.label,
                    )

    return combined

crystal_to_cartesian

crystal_to_cartesian(uvw, crystal)

Convert Miller direction [uvw] to a Cartesian vector using the crystal's reciprocal lattice (for directions, use the direct metric).

For a general crystal with lattice parameters a, b, c, α, β, γ the direct metric tensor G is used: x_cart = A · [uvw] where A is the lattice matrix.

Parameters:
  • uvw ((array - like, shape(3))) –

    Miller direction indices

  • crystal (Crystal) –
Returns:
  • cart( (ndarray, shape(3)) ) –

    Cartesian vector (Å)

Source code in src/nrxrdct/laue/layers.py
def crystal_to_cartesian(uvw, crystal):
    """
    Convert Miller direction [uvw] to a Cartesian vector using the crystal's
    reciprocal lattice (for directions, use the direct metric).

    For a general crystal with lattice parameters a, b, c, α, β, γ the direct
    metric tensor G is used:  x_cart = A · [uvw]  where A is the lattice matrix.

    Args:
        uvw (array-like, shape (3,)): Miller direction indices
        crystal (xu.materials.Crystal):

    Returns:
        cart (ndarray, shape (3,)): Cartesian vector (Å)
"""
    lat = crystal.lattice
    # Build direct lattice matrix A (columns = a1, a2, a3 vectors)
    A = lat._ai  # shape (3,3), rows are a1, a2, a3
    return A.T @ np.array(uvw, dtype=float)

d_spacing_hkl

d_spacing_hkl(crystal, h, k, l)

Interplanar spacing of the (hkl) family for crystal.

Uses the reciprocal lattice directly, so it is valid for any crystal system (cubic, hexagonal, orthorhombic, triclinic, …):

$$ d_{hkl} = \frac{2\pi}{|\mathbf{G}{hkl}|} \qquad \mathbf{G}{hkl} = h\,\mathbf{b}_1 + k\,\mathbf{b}_2 + l\,\mathbf{b}_3 $$ where \(\mathbf{b}_i\) are the reciprocal-lattice basis vectors in the xrayutilities convention (\(\mathbf{b}_i \cdot \mathbf{a}_j = 2\pi\,\delta_{ij}\)).

Parameters:
  • crystal (Crystal) –
  • h, k, l (int or float) –

    Miller indices.

Returns:
  • –

    float d-spacing in Å.

Example:

import xrayutilities as xu GaN = xu.materials.GaN d_spacing_hkl(GaN, 0, 0, 2) # GaN 002 reflection 2.593...

Source code in src/nrxrdct/laue/layers.py
def d_spacing_hkl(crystal, h, k, l):
    """
    Interplanar spacing of the `(hkl)` family for *crystal*.

    Uses the reciprocal lattice directly, so it is valid for any crystal
    system (cubic, hexagonal, orthorhombic, triclinic, …):

    $$
    d_{hkl} = \\frac{2\\pi}{|\\mathbf{G}_{hkl}|}
    \\qquad
    \\mathbf{G}_{hkl} = h\\,\\mathbf{b}_1 + k\\,\\mathbf{b}_2 + l\\,\\mathbf{b}_3
    $$
    where $\\mathbf{b}_i$ are the reciprocal-lattice basis vectors in
    the xrayutilities convention ($\\mathbf{b}_i \\cdot \\mathbf{a}_j =
    2\\pi\\,\\delta_{ij}$).

    Args:
        crystal (xu.materials.Crystal):
        h, k, l (int or float): Miller indices.

    Returns:
        float
            d-spacing in Å.

    Example:
    >>> import xrayutilities as xu
    >>> GaN = xu.materials.GaN
    >>> d_spacing_hkl(GaN, 0, 0, 2)   # GaN 002 reflection
    2.593...
"""
    b1, b2, b3 = crystal.lattice._bi   # reciprocal vectors, Å⁻¹ (2π convention)
    G = h * np.asarray(b1) + k * np.asarray(b2) + l * np.asarray(b3)
    return float(2 * np.pi / np.linalg.norm(G))

nitride_elastic_constants

nitride_elastic_constants(material: str, x: float = 0.0, end_material: str = 'GaN')

Elastic stiffness constants for a binary or ternary III-nitride (GPa).

For ternary alloys the constants are linearly interpolated between the two binary end-members (Vegard's law approximation).

Parameters:
  • material (`'GaN'` | `'InN'` | `'AlN'`) –

    First end-member (or the only material when x=0).

  • x (float, default: 0.0 ) –

    Alloy fraction of material in the ternary (default 0). Example: for In₀.₂Ga₀.₈N pass material='InN', x=0.2, end_material='GaN'.

  • end_material (`'GaN'` | `'InN'` | `'AlN'`, default: 'GaN' ) –

    Second end-member (default 'GaN').

Returns:
  • –

    dict with keys 'C11', 'C12', 'C13', 'C33', 'C44'

  • –

    (all in GPa).

Example:

c = nitride_elastic_constants('GaN') c = nitride_elastic_constants('InN', x=0.20, end_material='GaN') d, eps_par, eps_perp = pseudomorphic_d_spacing( ... InGaN, GaN.lattice.a, C13=c['C13'], C33=c['C33'])

Source code in src/nrxrdct/laue/layers.py
def nitride_elastic_constants(material: str, x: float = 0.0, end_material: str = "GaN"):
    """
    Elastic stiffness constants for a binary or ternary III-nitride (GPa).

    For ternary alloys the constants are linearly interpolated between the
    two binary end-members (Vegard's law approximation).

    Args:
        material (`'GaN'` | `'InN'` | `'AlN'`): First end-member (or the only material when `x=0`).
        x (float, optional): Alloy fraction of `material` in the ternary (default 0).
            Example: for In₀.₂Ga₀.₈N pass
            `material='InN', x=0.2, end_material='GaN'`.
        end_material (`'GaN'` | `'InN'` | `'AlN'`, optional): Second end-member (default `'GaN'`).

    Returns:
        dict with keys `'C11'`, `'C12'`, `'C13'`, `'C33'`, `'C44'`
        (all in GPa).

    Example:
    >>> c = nitride_elastic_constants('GaN')
    >>> c = nitride_elastic_constants('InN', x=0.20, end_material='GaN')
    >>> d, eps_par, eps_perp = pseudomorphic_d_spacing(
    ...     InGaN, GaN.lattice.a, C13=c['C13'], C33=c['C33'])
"""
    for m in (material, end_material):
        if m not in _NITRIDE_ELASTIC:
            raise ValueError(
                f"Unknown nitride {m!r}.  Available: {list(_NITRIDE_ELASTIC)}"
            )
    keys = ("C11", "C12", "C13", "C33", "C44")
    v1 = _NITRIDE_ELASTIC[material]
    v2 = _NITRIDE_ELASTIC[end_material]
    return {k: x * a + (1.0 - x) * b for k, a, b in zip(keys, v1, v2)}

or_baker_nutting

or_baker_nutting(crystal_bcc, crystal_rocksalt)

Baker-Nutting (BN) OR between BCC metal and rock-salt oxide (e.g. Fe / MgO, Fe / FeO): {100}_BCC ∥ {100}_RS <110>_BCC ∥ <010>_RS

Returns R_OR (BCC->rock-salt). Use: U_RS = U_BCC @ R_OR.T

Source code in src/nrxrdct/laue/layers.py
def or_baker_nutting(crystal_bcc, crystal_rocksalt):
    """
    Baker-Nutting (BN) OR between BCC metal and rock-salt oxide
    (e.g. Fe / MgO, Fe / FeO):
        {100}_BCC ∥ {100}_RS
        <110>_BCC ∥ <010>_RS

    Returns R_OR (BCC->rock-salt). Use: U_RS = U_BCC @ R_OR.T
"""
    return or_from_directions(
        crystal_bcc, [1, 0, 0], [1, 1, 0], crystal_rocksalt, [1, 0, 0], [0, 1, 0]
    )  # [010]_RS perpendicular to primary

or_from_directions

or_from_directions(crystal_A, dir1_A, dir2_A, crystal_B, dir1_B, dir2_B)

Compute the orientation relationship rotation R_OR such that crystal direction dir1_A in phase A is parallel to dir1_B in B, and dir2_A is as close as possible to dir2_B.

Usage

R_OR = or_from_directions(Fe, [1,1,1], [1,-1,0], Cu, [1,1,0], [1,-1,-2]) U_Cu = R_OR @ U_Fe

Parameters:
  • crystal_A, crystal_B (Crystal) –
  • dir1_A, dir2_A (Miller direction in phase A) –

    [u,v,w]

  • dir1_B, dir2_B (Miller direction in phase B) –

    [u,v,w]

Returns:
  • R_OR( (ndarray, shape(3, 3)) ) –

    rotation matrix

Source code in src/nrxrdct/laue/layers.py
def or_from_directions(crystal_A, dir1_A, dir2_A, crystal_B, dir1_B, dir2_B):
    """
    Compute the orientation relationship rotation  R_OR  such that
    crystal direction `dir1_A` in phase A is parallel to `dir1_B` in B,
    and `dir2_A` is as close as possible to `dir2_B`.

    Usage:
        R_OR = or_from_directions(Fe, [1,1,1], [1,-1,0],
                                  Cu, [1,1,0], [1,-1,-2])
        U_Cu = R_OR @ U_Fe

    Args:
        crystal_A, crystal_B (xu.materials.Crystal):
        dir1_A, dir2_A (Miller direction in phase A): [u,v,w]
        dir1_B, dir2_B (Miller direction in phase B): [u,v,w]

    Returns:
        R_OR (ndarray, shape (3,3)): rotation matrix
"""
    v1A = crystal_to_cartesian(dir1_A, crystal_A)
    v2A = crystal_to_cartesian(dir2_A, crystal_A)
    v1B = crystal_to_cartesian(dir1_B, crystal_B)
    v2B = crystal_to_cartesian(dir2_B, crystal_B)
    return _or_from_two_pairs(v1A, v2A, v1B, v2B)

or_kurdjumov_sachs

or_kurdjumov_sachs(crystal_bcc, crystal_fcc)

Kurdjumov-Sachs (KS) OR between BCC and FCC phases: {110}_BCC ∥ {111}_FCC <111>_BCC ∥ <110>_FCC

Returns R_OR (rotation from BCC crystal frame to FCC crystal frame). To derive U_FCC from U_BCC use: U_FCC = U_BCC @ R_OR.T

Source code in src/nrxrdct/laue/layers.py
def or_kurdjumov_sachs(crystal_bcc, crystal_fcc):
    """
    Kurdjumov-Sachs (KS) OR between BCC and FCC phases:
        {110}_BCC ∥ {111}_FCC
        <111>_BCC ∥ <110>_FCC

    Returns R_OR  (rotation from BCC crystal frame to FCC crystal frame).
    To derive U_FCC from U_BCC use:   U_FCC = U_BCC @ R_OR.T
"""
    return or_from_directions(
        crystal_bcc, [1, 1, 1], [1, -1, 0], crystal_fcc, [1, 1, 0], [1, -1, -2]
    )

or_nishiyama_wassermann

or_nishiyama_wassermann(crystal_bcc, crystal_fcc)

Nishiyama-Wassermann (NW) OR between BCC and FCC phases: {110}_BCC ∥ {111}_FCC <100>_BCC ∥ <011>_FCC

Returns R_OR (rotation from BCC crystal frame to FCC crystal frame). To derive U_FCC from U_BCC use: U_FCC = U_BCC @ R_OR.T

Source code in src/nrxrdct/laue/layers.py
def or_nishiyama_wassermann(crystal_bcc, crystal_fcc):
    """
    Nishiyama-Wassermann (NW) OR between BCC and FCC phases:
        {110}_BCC ∥ {111}_FCC
        <100>_BCC ∥ <011>_FCC

    Returns R_OR  (rotation from BCC crystal frame to FCC crystal frame).
    To derive U_FCC from U_BCC use:   U_FCC = U_BCC @ R_OR.T
"""
    return or_from_directions(
        crystal_bcc, [1, 1, 0], [0, 0, 1], crystal_fcc, [1, 1, 1], [0, 1, -1]
    )

or_pitsch

or_pitsch(crystal_bcc, crystal_fcc)
Pitsch OR between BCC and FCC

{100}_BCC ∥ {110}_FCC <011>_BCC ∥ <111>_FCC

Returns R_OR (rotation from BCC crystal frame to FCC crystal frame). To derive U_FCC from U_BCC use: U_FCC = U_BCC @ R_OR.T

Source code in src/nrxrdct/laue/layers.py
def or_pitsch(crystal_bcc, crystal_fcc):
    """
    Pitsch OR between BCC and FCC:
        {100}_BCC ∥ {110}_FCC
        <011>_BCC ∥ <111>_FCC

    Returns R_OR  (rotation from BCC crystal frame to FCC crystal frame).
    To derive U_FCC from U_BCC use:   U_FCC = U_BCC @ R_OR.T
"""
    return or_from_directions(
        crystal_bcc, [0, 1, 1], [1, 0, 0], crystal_fcc, [1, 1, 1], [1, 0, -1]
    )

orientation_along_plane

orientation_along_plane(hkl, crystal, up_crystal=None)

Build a 3×3 orientation matrix U that places the normal of the (hkl) lattice-plane family — the physically correct growth/stacking-direction convention for epitaxial films, since the sample surface is parallel to those planes — along the lab +z axis.

Unlike :func:orientation_along_z, which aligns a real-space direction [uvw], this aligns the reciprocal vector \(\mathbf{G}_{hkl}\) (via :func:plane_normal_cartesian). The two functions agree for cubic crystals and for hexagonal c-axis ((0001)) growth, but differ for any other hexagonal growth plane — most notably the non-polar m-plane {1,0,-1,0} and a-plane {1,1,-2,0} orientations used for polarization-optimised III-nitride devices, where the plane normal is a 30°-rotated real-space direction relative to the same-index [uvw].

Use this whenever the stacking/growth surface is specified as a Miller plane rather than a zone axis — in particular, always for non-c-axis hexagonal stacking. Pass the resulting U (or U @ [0, 0, 1], its own growth direction in the crystal frame) as stacking_direction / n_hat when building a :class:LayeredCrystal.

Parameters:
  • hkl ((array - like, shape(3))) –

    Miller indices (h, k, l) of the plane parallel to the growth surface (e.g. (1, 0, 0) for the hexagonal m-plane, using the 3-index convention — drop the redundant i = -(h+k) index of the 4-index Miller-Bravais (h k i l) notation).

  • crystal (Crystal) –
  • up_crystal (array - like, default: None ) –

    secondary alignment direction (a real-space [uvw]), rotated about z to align as closely as possible with lab +x — e.g. pass the in-plane c-axis [0, 0, 1] for m-plane GaN to fix the azimuthal reference.

Returns:
  • U( (ndarray, shape(3, 3)) ) –

    orientation matrix (G_lab = U @ G_crystal)

Example:

m-plane GaN: (10-10) surface, c-axis in-plane along lab x

U_GaN_mplane = orientation_along_plane([1, 0, 0], GaN, up_crystal=[0, 0, 1]) n_hat = U_GaN_mplane @ np.array([1.0, 0.0, 0.0]) # growth dir, crystal frame ∥ lab z

Source code in src/nrxrdct/laue/layers.py
def orientation_along_plane(hkl, crystal, up_crystal=None):
    """
    Build a 3×3 orientation matrix U that places the **normal of the `(hkl)`
    lattice-plane family** — the physically correct growth/stacking-direction
    convention for epitaxial films, since the sample surface is parallel to
    those planes — along the lab +z axis.

    Unlike :func:`orientation_along_z`, which aligns a real-space **direction**
    `[uvw]`, this aligns the **reciprocal** vector $\\mathbf{G}_{hkl}$ (via
    :func:`plane_normal_cartesian`). The two functions agree for cubic
    crystals and for hexagonal `c`-axis (`(0001)`) growth, but differ for any
    other hexagonal growth plane — most notably the non-polar **m-plane**
    `{1,0,-1,0}` and **a-plane** `{1,1,-2,0}` orientations used for
    polarization-optimised III-nitride devices, where the plane normal is a
    30°-rotated real-space direction relative to the same-index `[uvw]`.

    Use this whenever the stacking/growth surface is specified as a Miller
    plane rather than a zone axis — in particular, always for non-`c`-axis
    hexagonal stacking. Pass the resulting `U` (or `U @ [0, 0, 1]`, its own
    growth direction in the crystal frame) as `stacking_direction` /
    `n_hat` when building a :class:`LayeredCrystal`.

    Args:
        hkl (array-like, shape (3,)): Miller indices `(h, k, l)` of the plane parallel to the
            growth surface (e.g. `(1, 0, 0)` for the hexagonal m-plane, using
            the 3-index convention — drop the redundant `i = -(h+k)` index of
            the 4-index Miller-Bravais `(h k i l)` notation).
        crystal (xu.materials.Crystal):
        up_crystal (array-like, optional): secondary alignment direction (a real-space `[uvw]`), rotated
            about z to align as closely as possible with lab +x — e.g. pass
            the in-plane `c`-axis `[0, 0, 1]` for m-plane GaN to fix the
            azimuthal reference.

    Returns:
        U (ndarray, shape (3,3)): orientation matrix  (G_lab = U @ G_crystal)

    Example:
    >>> # m-plane GaN: (10-10) surface, c-axis in-plane along lab x
    >>> U_GaN_mplane = orientation_along_plane([1, 0, 0], GaN, up_crystal=[0, 0, 1])
    >>> n_hat = U_GaN_mplane @ np.array([1.0, 0.0, 0.0])  # growth dir, crystal frame ∥ lab z
"""
    G = plane_normal_cartesian(hkl, crystal)
    return _orient_axis_to_z(G, crystal, up_crystal)

orientation_along_z

orientation_along_z(zone_axis_crystal, crystal, up_crystal=None)

Build a 3×3 orientation matrix U that places the crystal direction zone_axis_crystal (real-space [uvw]) along the lab +z axis (stacking direction).

Optionally align up_crystal as close as possible to lab +x.

Warning

zone_axis_crystal is a real-space direction, not a plane normal. For cubic crystals and for c-axis hexagonal growth ([0001]) the two coincide, but for any other non-orthogonal-lattice growth plane (e.g. hexagonal m-plane or a-plane) they do not — use :func:orientation_along_plane instead when the growth surface is specified by Miller plane indices (hkl).

Parameters:
  • zone_axis_crystal (array - like) –

    Miller direction [uvw] in the crystal frame

  • crystal (Crystal) –
  • up_crystal (array - like, default: None ) –

    secondary alignment direction

Returns:
  • U( (ndarray, shape(3, 3)) ) –

    orientation matrix (G_lab = U @ G_crystal)

Source code in src/nrxrdct/laue/layers.py
def orientation_along_z(zone_axis_crystal, crystal, up_crystal=None):
    """
    Build a 3×3 orientation matrix U that places the crystal **direction**
    `zone_axis_crystal` (real-space `[uvw]`) along the lab +z axis (stacking
    direction).

    Optionally align `up_crystal` as close as possible to lab +x.

    !!! warning
        `zone_axis_crystal` is a real-space direction, not a plane normal.
        For cubic crystals and for `c`-axis hexagonal growth (`[0001]`) the
        two coincide, but for any other non-orthogonal-lattice growth plane
        (e.g. hexagonal m-plane or a-plane) they do **not** — use
        :func:`orientation_along_plane` instead when the growth surface is
        specified by Miller plane indices `(hkl)`.

    Args:
        zone_axis_crystal (array-like): Miller direction [uvw] in the crystal frame
        crystal (xu.materials.Crystal):
        up_crystal (array-like, optional): secondary alignment direction

    Returns:
        U (ndarray, shape (3,3)): orientation matrix  (G_lab = U @ G_crystal)
"""
    b = crystal_to_cartesian(zone_axis_crystal, crystal)
    return _orient_axis_to_z(b, crystal, up_crystal)

plane_normal_cartesian

plane_normal_cartesian(hkl, crystal)

Cartesian direction of the reciprocal-lattice vector \(\mathbf{G}_{hkl}\) — i.e. the normal to the (hkl) lattice-plane family — as opposed to :func:crystal_to_cartesian, which converts a real-space direction [uvw].

These two are only parallel for the same index triple in an orthogonal (e.g. cubic) system. In a non-orthogonal system (hexagonal, monoclinic, triclinic) they generally differ: for example in a hexagonal lattice the real-space direction [1,0,0] (an a-axis) is not normal to the (1,0,0)-type prism ("m") plane — the m-plane normal is instead parallel to the real-space <11-20>-type ("a") direction, a 30° rotation away in the basal plane. Use this function (via :func:orientation_along_plane) whenever the growth/stacking direction is specified as a Miller plane (hkl) rather than a zone axis [uvw] — in particular for any non-c-axis hexagonal growth such as m-plane or a-plane GaN.

Parameters:
  • hkl ((array - like, shape(3))) –

    Miller indices (h, k, l) of the plane family.

  • crystal (Crystal) –
Returns:
  • G( (ndarray, shape(3)) ) –

    Un-normalised Cartesian reciprocal vector (Å⁻¹); caller normalises if only the direction is needed.

Source code in src/nrxrdct/laue/layers.py
def plane_normal_cartesian(hkl, crystal):
    """
    Cartesian direction of the reciprocal-lattice vector $\\mathbf{G}_{hkl}$ —
    i.e. the **normal to the `(hkl)` lattice-plane family** — as opposed to
    :func:`crystal_to_cartesian`, which converts a *real-space* direction
    `[uvw]`.

    These two are only parallel for the same index triple in an orthogonal
    (e.g. cubic) system.  In a non-orthogonal system (hexagonal, monoclinic,
    triclinic) they generally differ: for example in a hexagonal lattice the
    real-space direction `[1,0,0]` (an a-axis) is **not** normal to the
    `(1,0,0)`-type prism ("m") plane — the m-plane normal is instead parallel
    to the real-space `<11-20>`-type ("a") direction, a 30° rotation away in
    the basal plane. Use this function (via :func:`orientation_along_plane`)
    whenever the growth/stacking direction is specified as a Miller **plane**
    `(hkl)` rather than a zone axis `[uvw]` — in particular for any non-`c`-axis
    hexagonal growth such as m-plane or a-plane GaN.

    Args:
        hkl (array-like, shape (3,)): Miller indices `(h, k, l)` of the plane family.
        crystal (xu.materials.Crystal):

    Returns:
        G (ndarray, shape (3,)): Un-normalised Cartesian reciprocal vector (Å⁻¹); caller
            normalises if only the direction is needed.
"""
    b1, b2, b3 = crystal.lattice._bi  # reciprocal vectors, Å⁻¹ (2π convention)
    h, k, l = (float(x) for x in hkl)
    return h * np.asarray(b1) + k * np.asarray(b2) + l * np.asarray(b3)

pseudomorphic_d_spacing

pseudomorphic_d_spacing(crystal_film, a_substrate, C13: float, C33: float, growth_dir=(0, 0, 1)) -> float

Out-of-plane repeat distance for a pseudomorphic (coherently strained) film.

Assuming biaxial in-plane stress with a free surface perpendicular to the growth direction, the out-of-plane strain is:

$$ \varepsilon_\perp = -\frac{2C_{13}}{C_{33}}\,\varepsilon_\parallel \qquad \varepsilon_\parallel = \frac{a_{\text{sub}} - a_{\text{film}}}{a_{\text{film}}} $$ The strained repeat along growth_dir is then \(d = d_{\text{bulk}}(1 + \varepsilon_\perp)\).

This formula is exact for hexagonal c-axis growth and for cubic [001] growth (substitute \(C_{12}/C_{11}\) for \(C_{13}/C_{33}\)).

Warning

Not valid for non-c-axis hexagonal or off-axis cubic growth. For semipolar / non-polar orientations (e.g. GaN grown along [2,-2,0], [1,1,-2,3], etc.) the in-plane strain is anisotropic and the correct out-of-plane response requires rotating the full elastic stiffness tensor into the growth frame. Calling this function with a non-c-axis growth_dir for a hexagonal crystal will raise ValueError.

Parameters:
  • crystal_film (Crystal) –

    Bulk (relaxed) film crystal.

  • a_substrate (float) –

    or xu.materials.Crystal In-plane lattice parameter of the template / substrate (Å). If a Crystal is passed its .lattice.a is used.

  • C13, C33 (float) –

    Elastic stiffness constants in any consistent units (GPa or Pa).

  • growth_dir (array - like(3), default: (0, 0, 1) ) –

    Miller direction of the stacking / growth axis in the film's crystal frame (default: (0, 0, 1)). For hexagonal crystals only (0, 0, 1) (c-axis) is supported.

Returns:
  • d_strained( float ) –

    Strained repeat along growth_dir (Å). Pass directly as d_spacing to :meth:LayeredCrystal.add_layer.

  • eps_par( float ) –

    In-plane strain \(\varepsilon_\parallel\) (positive = tensile).

  • eps_perp( float ) –

    Out-of-plane strain \(\varepsilon_\perp\).

Example: GaN/InGaN LED — pseudomorphic InGaN well on GaN buffer::

d_InGaN, eps_par, eps_perp = pseudomorphic_d_spacing(
    InGaN, GaN.lattice.a, C13=92.0, C33=224.0)
stack.add_layer(InGaN, U_InGaN, thickness=n_InGaN * d_InGaN,
                d_spacing=d_InGaN, label="InGaN (strained)")
Source code in src/nrxrdct/laue/layers.py
def pseudomorphic_d_spacing(
    crystal_film,
    a_substrate,
    C13: float,
    C33: float,
    growth_dir=(0, 0, 1),
) -> float:
    """
    Out-of-plane repeat distance for a pseudomorphic (coherently strained) film.

    Assuming biaxial in-plane stress with a free surface perpendicular to the
    growth direction, the out-of-plane strain is:

    $$
    \\varepsilon_\\perp = -\\frac{2C_{13}}{C_{33}}\\,\\varepsilon_\\parallel
    \\qquad
    \\varepsilon_\\parallel = \\frac{a_{\\text{sub}} - a_{\\text{film}}}{a_{\\text{film}}}
    $$
    The strained repeat along `growth_dir` is then
    $d = d_{\\text{bulk}}(1 + \\varepsilon_\\perp)$.

    This formula is exact for hexagonal **c-axis** growth and for cubic
    **[001]** growth (substitute $C_{12}/C_{11}$ for
    $C_{13}/C_{33}$).

    !!! warning
        **Not valid for non-c-axis hexagonal or off-axis cubic growth.**
        For semipolar / non-polar orientations (e.g. GaN grown along
        [2,-2,0], [1,1,-2,3], etc.) the in-plane strain is anisotropic and
        the correct out-of-plane response requires rotating the full
        elastic stiffness tensor into the growth frame.  Calling this
        function with a non-c-axis `growth_dir` for a hexagonal crystal
        will raise `ValueError`.

    Args:
        crystal_film (xu.materials.Crystal): Bulk (relaxed) film crystal.
        a_substrate (float): or  xu.materials.Crystal
            In-plane lattice parameter of the template / substrate (Å).
            If a Crystal is passed its `.lattice.a` is used.
        C13, C33 (float): Elastic stiffness constants in any consistent units (GPa or Pa).

        * Hexagonal c-axis growth  → $C_{13}$, $C_{33}$
        * Cubic [001] growth       → $C_{12}$, $C_{11}$
        growth_dir (array-like (3,), optional): Miller direction of the stacking / growth axis in the **film's crystal
            frame** (default: `(0, 0, 1)`).
            For hexagonal crystals only `(0, 0, 1)` (c-axis) is supported.

    Returns:
        d_strained (float): Strained repeat along `growth_dir` (Å).  Pass directly as
            `d_spacing` to :meth:`LayeredCrystal.add_layer`.
        eps_par (float): In-plane strain $\\varepsilon_\\parallel$ (positive = tensile).
        eps_perp (float): Out-of-plane strain $\\varepsilon_\\perp$.

    Example:
    GaN/InGaN LED — pseudomorphic InGaN well on GaN buffer::

        d_InGaN, eps_par, eps_perp = pseudomorphic_d_spacing(
            InGaN, GaN.lattice.a, C13=92.0, C33=224.0)
        stack.add_layer(InGaN, U_InGaN, thickness=n_InGaN * d_InGaN,
                        d_spacing=d_InGaN, label="InGaN (strained)")
"""
    # Resolve substrate in-plane parameter
    if hasattr(a_substrate, "lattice"):
        a_sub = float(a_substrate.lattice.a)
    else:
        a_sub = float(a_substrate)

    lat = crystal_film.lattice
    A = lat._ai  # rows are direct lattice vectors in Cartesian (Å)

    growth_dir = np.asarray(growth_dir, dtype=float)

    # Guard: for hexagonal lattices (a == b, γ == 120°) only c-axis growth is
    # supported.  Non-c-axis hexagonal growth requires a rotated compliance
    # tensor calculation that this scalar formula cannot provide.
    _is_hexagonal = (
        abs(lat.a - lat.b) < 1e-4
        and abs(lat.alpha - 90.0) < 0.5
        and abs(lat.beta - 90.0) < 0.5
        and abs(lat.gamma - 120.0) < 0.5
    )
    if _is_hexagonal:
        g_norm = growth_dir / np.linalg.norm(growth_dir)
        c_axis = np.array([0.0, 0.0, 1.0])
        if abs(abs(float(np.dot(g_norm, c_axis))) - 1.0) > 1e-3:
            raise ValueError(
                f"pseudomorphic_d_spacing: growth_dir={growth_dir.tolist()} is not "
                f"the c-axis for a hexagonal crystal.  For non-c-axis hexagonal "
                f"orientations (semipolar / non-polar) the scalar biaxial formula "
                f"ε_⊥ = -2(C₁₃/C₃₃)·ε_∥ is not valid.  Provide d_spacing manually "
                f"from a full elastic-tensor calculation."
            )

    g_cart = A.T @ growth_dir
    g_cart /= np.linalg.norm(g_cart)

    # Bulk repeat along growth direction
    projs_along_g = []
    projs_inplane = []
    for vec in A:
        along = abs(float(np.dot(vec, g_cart)))
        if along > 1e-6:
            projs_along_g.append(along)
        inplane_vec = vec - np.dot(vec, g_cart) * g_cart
        inplane_len = float(np.linalg.norm(inplane_vec))
        if inplane_len > 1e-6:
            projs_inplane.append(inplane_len)

    d_bulk = min(projs_along_g) if projs_along_g else float(lat.c)
    a_film = min(projs_inplane) if projs_inplane else float(lat.a)

    eps_par = (a_sub - a_film) / a_film
    eps_perp = -2.0 * (C13 / C33) * eps_par
    d_strained = d_bulk * (1.0 + eps_perp)

    return float(d_strained), float(eps_par), float(eps_perp)

pseudomorphic_d_spacing_nonpolar

pseudomorphic_d_spacing_nonpolar(crystal_film, a_substrate, c_substrate, C11: float, C12: float, C13: float, growth_hkl=(1, 0, 0))

Out-of-plane (growth-normal) repeat distance for a pseudomorphic film grown on a non-polar hexagonal surface -- the m-plane {1,0,-1,0} or a-plane {1,1,-2,0} family (more generally, any prism-plane growth direction, i.e. any direction perpendicular to c).

Why pseudomorphic_d_spacing cannot be reused here. That function's scalar formula \(\varepsilon_\perp = -2(C_{13}/C_{33})\varepsilon_\parallel\) relies on hexagonal elastic stiffness being transversely isotropic about c: for c-axis growth both in-plane directions are elastically identical a-type directions, so a single mismatch strain \(\varepsilon_\parallel\) (and a single ratio \(C_{13}/C_{33}\)) suffices. Non-polar growth breaks that symmetry: its two in-plane directions are not equivalent -- one is c itself (elastic constants \(C_{13}\), \(C_{33}\)), the other is the remaining in-plane a-type direction (elastic constants \(C_{11}\), \(C_{12}\), \(C_{13}\)) -- so the mismatch strain along each is generally different, and each pulls on the free surface with a different coefficient. Calling pseudomorphic_d_spacing with a non-c-axis growth_dir for a hexagonal crystal raises ValueError for exactly this reason; leaving growth_dir at its default (0,0,1) instead silently computes a c-axis strain answer that has nothing to do with the actual (non-polar) growth direction -- neither is usable, hence this separate function.

Derivation. Because hexagonal elastic stiffness is transversely isotropic about c, any direction in the basal plane is elastically equivalent to any other -- so the growth normal (an a-type direction) and the in-plane a-type direction retained in the surface share the same \((C_{11}, C_{12})\) pair, with \(C_{13}\) coupling each to c. Writing Hooke's law in this local frame with the free-surface condition \(\sigma_{\perp} = 0\):

\[ \boxed{ \varepsilon_\perp = -\frac{C_{12}\,\varepsilon_a + C_{13}\,\varepsilon_c}{C_{11}} } \qquad \varepsilon_a = \frac{a_\text{sub} - a_\text{film}}{a_\text{film}}, \qquad \varepsilon_c = \frac{c_\text{sub} - c_\text{film}}{c_\text{film}} \]

Unlike the c-axis case, both substrate lattice parameters enter (the surface contains both the a- and c-type in-plane directions), and no stiffness-tensor rotation is needed -- transverse isotropy makes this formula valid for any basal-plane-normal growth direction, not just the specific growth_hkl passed.

The bulk (unstrained) repeat d_bulk along the growth normal is found via :func:shortest_lattice_vector -- not d_spacing_hkl -- since for a non-orthogonal lattice the shortest lattice-vector repeat along a prism-plane normal is generally a multiple of the bare interplanar spacing (for GaN m-plane, exactly 2×; see that function's docstring).

Parameters:
  • crystal_film (Crystal) –

    Bulk (relaxed) film crystal.

  • a_substrate (float) –

    or xu.materials.Crystal In-plane a-parameter of the template (Å), or a Crystal whose .lattice.a is used.

  • c_substrate (float) –

    or xu.materials.Crystal In-plane c-parameter of the template (Å), or a Crystal whose .lattice.c is used. Required because, unlike c-axis growth, the c-direction lies in a non-polar growth surface and is therefore also lattice-matched to the substrate.

  • C11, C12, C13 (float) –

    Elastic stiffness constants (GPa or Pa, any consistent unit).

  • growth_hkl (array - like(3), default: (1, 0, 0) ) –

    Miller plane indices of the growth surface (default (1,0,0), the hexagonal m-plane in the 3-index convention). Must be perpendicular to c (any prism-plane family); passing a direction with a nonzero c-component raises ValueError, since that would be a genuinely semipolar direction requiring a full stiffness-tensor rotation this function does not perform. Aligned via :func:plane_normal_cartesian, so this is the reciprocal plane normal, not a real-space [uvw] direction -- use whichever specific family member (e.g. (1,0,0) vs (0,1,0)) matches your own indexed/measured orientation convention, as with :func:orientation_along_plane.

Returns:
  • d_strained( float ) –

    Strained repeat along growth_hkl's normal (Å). Pass directly as d_spacing to :meth:LayeredCrystal.add_layer.

  • eps_a( float ) –

    In-plane strain along the a-type direction (positive = tensile).

  • eps_c( float ) –

    In-plane strain along c (positive = tensile).

  • eps_perp( float ) –

    Out-of-plane (growth-normal) strain.

Example:

d, eps_a, eps_c, eps_perp = pseudomorphic_d_spacing_nonpolar( ... InGaN, a_substrate=GaN.lattice.a, c_substrate=GaN.lattice.c, ... C11=c['C11'], C12=c['C12'], C13=c['C13'], growth_hkl=(0, 1, 0))

Source code in src/nrxrdct/laue/layers.py
def pseudomorphic_d_spacing_nonpolar(
    crystal_film,
    a_substrate,
    c_substrate,
    C11: float,
    C12: float,
    C13: float,
    growth_hkl=(1, 0, 0),
):
    """
    Out-of-plane (growth-normal) repeat distance for a pseudomorphic film
    grown on a **non-polar hexagonal** surface -- the m-plane `{1,0,-1,0}`
    or a-plane `{1,1,-2,0}` family (more generally, any prism-plane growth
    direction, i.e. any direction perpendicular to `c`).

    **Why `pseudomorphic_d_spacing` cannot be reused here.** That function's
    scalar formula $\\varepsilon_\\perp = -2(C_{13}/C_{33})\\varepsilon_\\parallel$
    relies on hexagonal elastic stiffness being *transversely isotropic*
    about `c`: for `c`-axis growth both in-plane directions are elastically
    identical `a`-type directions, so a single mismatch strain
    $\\varepsilon_\\parallel$ (and a single ratio $C_{13}/C_{33}$) suffices.
    Non-polar growth breaks that symmetry: its two in-plane directions are
    **not** equivalent -- one is `c` itself (elastic constants $C_{13}$,
    $C_{33}$), the other is the remaining in-plane `a`-type direction
    (elastic constants $C_{11}$, $C_{12}$, $C_{13}$) -- so the mismatch
    strain along each is generally different, and each pulls on the free
    surface with a different coefficient. Calling `pseudomorphic_d_spacing`
    with a non-`c`-axis `growth_dir` for a hexagonal crystal raises
    `ValueError` for exactly this reason; leaving `growth_dir` at its default
    `(0,0,1)` instead silently computes a *c*-axis strain answer that has
    nothing to do with the actual (non-polar) growth direction -- neither is
    usable, hence this separate function.

    **Derivation.** Because hexagonal elastic stiffness is transversely
    isotropic about `c`, *any* direction in the basal plane is elastically
    equivalent to any other -- so the growth normal (an `a`-type direction)
    and the in-plane `a`-type direction retained in the surface share the
    same $(C_{11}, C_{12})$ pair, with $C_{13}$ coupling each to `c`.
    Writing Hooke's law in this local frame with the free-surface condition
    $\\sigma_{\\perp} = 0$:

    $$
    \\boxed{
    \\varepsilon_\\perp = -\\frac{C_{12}\\,\\varepsilon_a + C_{13}\\,\\varepsilon_c}{C_{11}}
    }
    \\qquad
    \\varepsilon_a = \\frac{a_\\text{sub} - a_\\text{film}}{a_\\text{film}},
    \\qquad
    \\varepsilon_c = \\frac{c_\\text{sub} - c_\\text{film}}{c_\\text{film}}
    $$

    Unlike the `c`-axis case, **both** substrate lattice parameters enter
    (the surface contains both the `a`- and `c`-type in-plane directions),
    and no stiffness-tensor rotation is needed -- transverse isotropy makes
    this formula valid for *any* basal-plane-normal growth direction, not
    just the specific `growth_hkl` passed.

    The bulk (unstrained) repeat `d_bulk` along the growth normal is found
    via :func:`shortest_lattice_vector` -- **not** `d_spacing_hkl` -- since
    for a non-orthogonal lattice the shortest lattice-vector repeat along a
    prism-plane normal is generally a multiple of the bare interplanar
    spacing (for GaN m-plane, exactly 2×; see that function's docstring).

    Args:
        crystal_film (xu.materials.Crystal): Bulk (relaxed) film crystal.
        a_substrate (float): or  xu.materials.Crystal
            In-plane `a`-parameter of the template (Å), or a Crystal whose
            `.lattice.a` is used.
        c_substrate (float): or  xu.materials.Crystal
            In-plane `c`-parameter of the template (Å), or a Crystal whose
            `.lattice.c` is used. Required because, unlike `c`-axis growth,
            the `c`-direction lies *in* a non-polar growth surface and is
            therefore also lattice-matched to the substrate.
        C11, C12, C13 (float): Elastic stiffness constants (GPa or Pa, any consistent unit).
        growth_hkl (array-like (3,), optional): Miller **plane** indices of the growth surface (default `(1,0,0)`,
            the hexagonal m-plane in the 3-index convention). Must be
            perpendicular to `c` (any prism-plane family); passing a
            direction with a nonzero `c`-component raises `ValueError`, since
            that would be a genuinely semipolar direction requiring a full
            stiffness-tensor rotation this function does not perform.
            Aligned via :func:`plane_normal_cartesian`, so this is the
            reciprocal plane normal, not a real-space `[uvw]` direction --
            use whichever specific family member (e.g. `(1,0,0)` vs
            `(0,1,0)`) matches your own indexed/measured orientation
            convention, as with :func:`orientation_along_plane`.

    Returns:
        d_strained (float): Strained repeat along `growth_hkl`'s normal (Å). Pass directly as
            `d_spacing` to :meth:`LayeredCrystal.add_layer`.
        eps_a (float): In-plane strain along the `a`-type direction (positive = tensile).
        eps_c (float): In-plane strain along `c` (positive = tensile).
        eps_perp (float): Out-of-plane (growth-normal) strain.

    Example:
    >>> d, eps_a, eps_c, eps_perp = pseudomorphic_d_spacing_nonpolar(
    ...     InGaN, a_substrate=GaN.lattice.a, c_substrate=GaN.lattice.c,
    ...     C11=c['C11'], C12=c['C12'], C13=c['C13'], growth_hkl=(0, 1, 0))
"""
    if hasattr(a_substrate, "lattice"):
        a_sub = float(a_substrate.lattice.a)
    else:
        a_sub = float(a_substrate)
    if hasattr(c_substrate, "lattice"):
        c_sub = float(c_substrate.lattice.c)
    else:
        c_sub = float(c_substrate)

    a_film = float(crystal_film.lattice.a)
    c_film = float(crystal_film.lattice.c)

    g_cart = plane_normal_cartesian(growth_hkl, crystal_film)
    g_hat = g_cart / np.linalg.norm(g_cart)

    c_axis = np.array([0.0, 0.0, 1.0])
    if abs(float(np.dot(g_hat, c_axis))) > 1e-3:
        raise ValueError(
            f"pseudomorphic_d_spacing_nonpolar: growth_hkl={tuple(growth_hkl)} is "
            f"not perpendicular to c -- this function only covers basal-plane-"
            f"normal (prism-plane, e.g. m-plane/a-plane) growth, where transverse "
            f"isotropy makes the strain response independent of azimuth. A "
            f"genuinely semipolar direction (nonzero c-component) needs a full "
            f"stiffness-tensor rotation, which this function does not perform."
        )

    T, d_bulk = shortest_lattice_vector(g_hat, crystal_film)
    if T is None:
        raise ValueError(
            f"pseudomorphic_d_spacing_nonpolar: no real lattice vector of "
            f"{crystal_film.name} within shortest_lattice_vector's default "
            f"search range is parallel to growth_hkl={tuple(growth_hkl)}'s "
            f"normal -- pass a lower-index growth_hkl, or call "
            f"shortest_lattice_vector yourself with a larger max_index."
        )

    eps_a = (a_sub - a_film) / a_film
    eps_c = (c_sub - c_film) / c_film
    eps_perp = -(C12 * eps_a + C13 * eps_c) / C11
    d_strained = d_bulk * (1.0 + eps_perp)

    return float(d_strained), float(eps_a), float(eps_c), float(eps_perp)

shortest_lattice_vector

shortest_lattice_vector(direction, crystal, max_index=8, tol=1e-06)

Shortest real-space Bravais lattice vector exactly parallel to direction, found by an exhaustive search over small integer combinations of the crystal's primitive direct-lattice vectors.

Why this is needed (and why a per-axis projection is not enough). :meth:Layer's coherent structure-factor sum treats the whole stack as N identical copies of the same unit-cell structure factor F_uc(Q_cry), translated by a scalar step d along the stacking direction n_hat. That 1-D geometric-series model is only exact when n_hat is parallel to an actual lattice translation T: only then does stepping by d = |T| regenerate an identical atomic arrangement each time, so the same F_uc legitimately applies to every step.

For an orthogonal lattice (cubic, tetragonal, orthorhombic) or for hexagonal c-axis growth, that translation happens to be one of the primitive vectors themselves (a1, a2, or a3), which is why simply projecting each one onto n_hat and keeping the shortest — the original heuristic used here — worked. It is not true in general: for a hexagonal m-plane normal ({1,0,-1,0}), for instance, the shortest lattice vector parallel to it is 2·a1 + a2 (length a√3), a combination of primitives that the old per-vector heuristic could never find — and its length is twice the bare interplanar spacing d_spacing_hkl of that plane family (wurtzite has 2 formula units per cell, so consecutive (10-10) planes are not identical; only every second one is). Using the bare d_hkl there would silently impose a spurious extra periodicity — half the true repeat — corrupting the satellite spacing and systematic absences. Searching combinations, not just single vectors, is what makes this general.

Not every direction has such a lattice vector within reach: n_hat may be genuinely incommensurate with the lattice (e.g. many semipolar planes, where the real/reciprocal correspondence depends on a/c and need not close on a short integer vector). This function returns (None, None) in that case rather than guessing — the caller (:class:Layer) turns that into a ValueError asking for an explicit d_spacing.

Parameters:
  • direction ((array - like, shape(3))) –

    Target direction, in the same Cartesian frame as the crystal's direct lattice (i.e. the crystal frame — pass U.T @ n_hat_lab when starting from a lab-frame stacking direction). Need not be normalised.

  • crystal (Crystal) –
  • max_index (int, default: 8 ) –

    Search integer coefficients p, q, r in [-max_index, max_index] for T = p*a1 + q*a2 + r*a3. Default 8 comfortably covers m-/a-plane hexagonal growth (needs |p|,|q| ≤ 2) and all low-index cubic directions; raise it only for deliberately high-index growth planes.

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

    Relative tolerance on |cos(angle)| = 1 used to accept a candidate T as parallel to direction. Default 1e-6.

Returns:
  • T( ndarray, shape (3,), or None ) –

    Shortest matching lattice vector (Å), or None if none was found within max_index.

  • length( float or None ) –

    |T| (Å), or None if no match was found. This is the physically correct stacking repeat d to use for add_layer(..., d_spacing=length).

Example:

m-plane GaN: shortest lattice vector along the (10-10) normal

U = orientation_along_plane([1, 0, 0], GaN) n_hat_crystal = U.T @ (U @ np.array([1.0, 0.0, 0.0])) # = [1,0,0] here T, d = shortest_lattice_vector(n_hat_crystal, GaN) d, d_spacing_hkl(GaN, 1, 0, 0) # d == 2x the bare (10-10) spacing (5.527..., 2.763...)

Source code in src/nrxrdct/laue/layers.py
def shortest_lattice_vector(direction, crystal, max_index=8, tol=1e-6):
    """
    Shortest real-space Bravais lattice vector exactly parallel to `direction`,
    found by an exhaustive search over small integer combinations of the
    crystal's primitive direct-lattice vectors.

    **Why this is needed (and why a per-axis projection is not enough).**
    :meth:`Layer`'s coherent structure-factor sum treats the whole stack as
    `N` identical copies of the *same* unit-cell structure factor
    `F_uc(Q_cry)`, translated by a scalar step `d` along the stacking
    direction `n_hat`. That 1-D geometric-series model is only exact when
    `n_hat` is parallel to an actual lattice translation `T`: only then does
    stepping by `d = |T|` regenerate an *identical* atomic arrangement each
    time, so the same `F_uc` legitimately applies to every step.

    For an orthogonal lattice (cubic, tetragonal, orthorhombic) or for
    hexagonal `c`-axis growth, that translation happens to be one of the
    primitive vectors themselves (`a1`, `a2`, or `a3`), which is why simply
    projecting each one onto `n_hat` and keeping the shortest — the original
    heuristic used here — worked. It is **not** true in general: for a
    hexagonal **m-plane** normal (`{1,0,-1,0}`), for instance, the shortest
    lattice vector parallel to it is `2·a1 + a2` (length `a√3`), a *combination*
    of primitives that the old per-vector heuristic could never find — and its
    length is twice the bare interplanar spacing `d_spacing_hkl` of that plane
    family (wurtzite has 2 formula units per cell, so consecutive `(10-10)`
    planes are not identical; only every *second* one is). Using the bare
    `d_hkl` there would silently impose a spurious extra periodicity — half
    the true repeat — corrupting the satellite spacing and systematic
    absences. Searching combinations, not just single vectors, is what makes
    this general.

    Not every direction has such a lattice vector within reach: `n_hat` may be
    genuinely incommensurate with the lattice (e.g. many semipolar planes,
    where the real/reciprocal correspondence depends on `a/c` and need not
    close on a short integer vector). This function returns `(None, None)` in
    that case rather than guessing — the caller (:class:`Layer`) turns that
    into a `ValueError` asking for an explicit `d_spacing`.

    Args:
        direction (array-like, shape (3,)): Target direction, in the **same Cartesian frame** as the crystal's
            direct lattice (i.e. the crystal frame — pass `U.T @ n_hat_lab`
            when starting from a lab-frame stacking direction). Need not be
            normalised.
        crystal (xu.materials.Crystal):
        max_index (int, optional): Search integer coefficients `p, q, r` in `[-max_index, max_index]`
            for `T = p*a1 + q*a2 + r*a3`. Default `8` comfortably covers m-/a-plane
            hexagonal growth (needs `|p|,|q| ≤ 2`) and all low-index cubic
            directions; raise it only for deliberately high-index growth
            planes.
        tol (float, optional): Relative tolerance on `|cos(angle)| = 1` used to accept a
            candidate `T` as parallel to `direction`. Default `1e-6`.

    Returns:
        T (ndarray, shape (3,), or None): Shortest matching lattice vector (Å), or `None` if none was found
            within `max_index`.
        length (float or None): `|T|` (Å), or `None` if no match was found. This is the physically
            correct stacking repeat `d` to use for `add_layer(..., d_spacing=length)`.

    Example:
    >>> # m-plane GaN: shortest lattice vector along the (10-10) normal
    >>> U = orientation_along_plane([1, 0, 0], GaN)
    >>> n_hat_crystal = U.T @ (U @ np.array([1.0, 0.0, 0.0]))  # = [1,0,0] here
    >>> T, d = shortest_lattice_vector(n_hat_crystal, GaN)
    >>> d, d_spacing_hkl(GaN, 1, 0, 0)   # d == 2x the bare (10-10) spacing
    (5.527..., 2.763...)
"""
    lat = crystal.lattice
    A = np.asarray(lat._ai, dtype=float)  # rows: a1, a2, a3
    d_hat = np.asarray(direction, dtype=float)
    d_hat = d_hat / np.linalg.norm(d_hat)

    best_T = None
    best_len = np.inf
    idx = range(-int(max_index), int(max_index) + 1)
    for p in idx:
        for q in idx:
            for r in idx:
                if p == 0 and q == 0 and r == 0:
                    continue
                T = p * A[0] + q * A[1] + r * A[2]
                length = float(np.linalg.norm(T))
                if length < 1e-8 or length >= best_len:
                    continue
                cos_ang = abs(float(np.dot(T, d_hat))) / length
                if abs(cos_ang - 1.0) < tol:
                    best_T = T
                    best_len = length
    if best_T is None:
        return None, None
    return best_T, best_len