powder

simulation

nrxrdct.powder.simulation

calculate_xrd_baseline

calculate_xrd_baseline(y: ndarray, x: ndarray | None = None, method: str = 'iasls', **kwargs) -> tuple[np.ndarray, dict]

Calculate the baseline of an X-ray diffraction (XRD) intensity curve.

Parameters:
  • y (ndarray) –

    1D array of intensity values from the XRD measurement.

  • x (ndarray, default: None ) –

    1D array of 2θ (or q) values corresponding to y. If None, integer indices [0, 1, ..., len(y)-1] are used.

  • method (str, default: 'iasls' ) –

    Baseline algorithm to use. Recommended options for XRD: "iasls" – Iterative asymmetric least squares (default), good general-purpose choice; "aspls" – Adaptive smoothness penalized least squares, better when peaks are dense or asymmetric; "snip" – Statistics-sensitive Non-linear Iterative Peak-clipping, fast and parameter-light; "arpls" – Asymmetrically reweighted penalized least squares; "mor" – Morphological baseline (very fast).

  • **kwargs –

    Extra keyword arguments forwarded to the chosen pybaselines method. Useful tuning parameters: iasls → lam=1e6, lam_1=1e-4, p=1e-2; aspls → lam=1e5, diff_order=2; snip → max_half_window=40, decreasing=True, smooth_half_window=3; arpls → lam=1e5, threshold=0.001.

Returns:
  • baseline( ndarray ) –

    Estimated baseline array, same shape as y.

  • params( dict ) –

    Dictionary returned by pybaselines containing diagnostic info (e.g. weights, residuals, number of iterations).

Example

import numpy as np two_theta = np.linspace(10, 80, 1000) intensity = np.random.default_rng(0).normal(500, 10, 1000) baseline, info = calculate_xrd_baseline(intensity, two_theta) corrected = intensity - baseline

Source code in src/nrxrdct/powder/simulation.py
def calculate_xrd_baseline(
    y: np.ndarray, x: np.ndarray | None = None, method: str = "iasls", **kwargs
) -> tuple[np.ndarray, dict]:
    """
    Calculate the baseline of an X-ray diffraction (XRD) intensity curve.

    Args:
        y (np.ndarray): 1D array of intensity values from the XRD measurement.
        x (np.ndarray, optional): 1D array of 2θ (or q) values corresponding to `y`.
            If None, integer indices [0, 1, ..., len(y)-1] are used.
        method (str): Baseline algorithm to use. Recommended options for XRD:
            "iasls" – Iterative asymmetric least squares (default), good general-purpose
            choice; "aspls" – Adaptive smoothness penalized least squares, better when
            peaks are dense or asymmetric; "snip" – Statistics-sensitive Non-linear
            Iterative Peak-clipping, fast and parameter-light; "arpls" – Asymmetrically
            reweighted penalized least squares; "mor" – Morphological baseline (very fast).
        **kwargs: Extra keyword arguments forwarded to the chosen pybaselines method.
            Useful tuning parameters: iasls → lam=1e6, lam_1=1e-4, p=1e-2;
            aspls → lam=1e5, diff_order=2; snip → max_half_window=40,
            decreasing=True, smooth_half_window=3; arpls → lam=1e5, threshold=0.001.

    Returns:
        baseline (np.ndarray): Estimated baseline array, same shape as `y`.
        params (dict): Dictionary returned by pybaselines containing diagnostic info
            (e.g. weights, residuals, number of iterations).

    Example:
        >>> import numpy as np
        >>> two_theta = np.linspace(10, 80, 1000)
        >>> intensity  = np.random.default_rng(0).normal(500, 10, 1000)
        >>> baseline, info = calculate_xrd_baseline(intensity, two_theta)
        >>> corrected = intensity - baseline
    """
    y = np.asarray(y, dtype=float)

    if x is None:
        x = np.arange(len(y), dtype=float)
    else:
        x = np.asarray(x, dtype=float)

    if y.ndim != 1 or x.ndim != 1:
        raise ValueError("Both `y` and `x` must be 1-dimensional arrays.")
    if len(y) != len(x):
        raise ValueError("`y` and `x` must have the same length.")

    fitter = Baseline(x_data=x)

    # Default parameters tuned for typical XRD data
    defaults = {
        "iasls": {"lam": 1e6, "lam_1": 1e-4, "p": 1e-2},
        "aspls": {"lam": 1e5, "diff_order": 2},
        "snip": {"max_half_window": 40, "decreasing": True, "smooth_half_window": 3},
        "arpls": {"lam": 1e5},
        "mor": {},
    }

    if method not in defaults:
        raise ValueError(
            f"Unknown method '{method}'. Choose from: {list(defaults.keys())}"
        )

    # Merge defaults with any user-supplied kwargs (user wins)
    params = {**defaults[method], **kwargs}

    algo = getattr(fitter, method)
    baseline, info = algo(y, **params)

    return baseline, info

get_powder_xrd_peaks

get_powder_xrd_peaks(cif_files, names: list[str] = None, energy_keV: float = 100.0, tth_min: float = None, tth_max: float = None) -> dict[str, pd.DataFrame]

Return peak positions and hkl families for one or more CIF files.

Parameters:
  • cif_files (path or list) –

    Path(s) to CIF file(s).

  • names (list of str, default: None ) –

    Phase names to use as dict keys, one per CIF file. If None or shorter than cif_files, the name embedded in the CIF is used for any entry without a supplied name.

  • energy_keV (float, default: 100.0 ) –

    X-ray energy in keV (default 100 keV).

  • tth_min (float, default: None ) –

    Minimum 2theta in degrees (auto if None).

  • tth_max (float, default: None ) –

    Maximum 2theta in degrees (auto if None).

Returns:
  • dict( dict[str, DataFrame] ) –

    Mapping of phase_name to DataFrame with columns h, k, l, hkl, tth, d_hkl, r (structure factor |F|²).

Source code in src/nrxrdct/powder/simulation.py
def get_powder_xrd_peaks(
    cif_files,
    names: list[str] = None,
    energy_keV: float = 100.0,
    tth_min: float = None,
    tth_max: float = None,
) -> dict[str, pd.DataFrame]:
    """
    Return peak positions and hkl families for one or more CIF files.

    Args:
        cif_files (path or list): Path(s) to CIF file(s).
        names (list of str, optional): Phase names to use as dict keys, one per
            CIF file.  If None or shorter than cif_files, the name embedded in
            the CIF is used for any entry without a supplied name.
        energy_keV (float): X-ray energy in keV (default 100 keV).
        tth_min (float, optional): Minimum 2theta in degrees (auto if None).
        tth_max (float, optional): Maximum 2theta in degrees (auto if None).

    Returns:
        dict: Mapping of phase_name to DataFrame with columns
            h, k, l, hkl, tth, d_hkl, r (structure factor |F|²).
    """
    if not isinstance(cif_files, list):
        cif_files = [cif_files]

    if names is None:
        names = []

    wavelength = xu.en2lam(energy_keV * 1000)  # Å

    if tth_min is None:
        tth_min = 2 * np.degrees(np.arcsin(wavelength / (2 * 10.0)))
    if tth_max is None:
        tth_max = 2 * np.degrees(np.arcsin(wavelength / (2 * 0.5)))

    results = {}

    for i, cif in enumerate(cif_files):
        mat = xu.materials.Crystal.fromCIF(cif)
        phase_name = names[i] if i < len(names) else mat.name.replace(" ", "_")

        pd_obj = xu.simpack.PowderDiffraction(mat, en=energy_keV * 1000)

        rows = []
        for hkl, data in pd_obj.data.items():
            # only keep active (non-extinct) reflections
            if not data["active"]:
                continue

            tth_peak = data["ang"] * 2  # ang is theta in degrees; tth in degrees
            # d from Bragg's law: d = lambda / (2 * sin(theta))
            d = wavelength / (2 * np.sin(np.radians(data["ang"])))

            if tth_min <= tth_peak <= tth_max:
                h, k, l = hkl
                rows.append(
                    {
                        "h": h,
                        "k": k,
                        "l": l,
                        "hkl": f"({h} {k} {l})",
                        "tth": round(float(tth_peak), 4),
                        "d_hkl": round(float(d), 4),
                        "r": float(data["r"]),  # |F|² structure factor
                    }
                )

        df = pd.DataFrame(rows).sort_values("r", ascending=False).reset_index(drop=True)
        results[phase_name] = df

    _print_peaks_table(results)
    return results

simulate_powder_xrd_monophase

simulate_powder_xrd_monophase(tth, cif_files, do_plot=True, energy_keV: float = 100.0, crystallite_size: float = 1e-07, do_save: bool = True) -> np.ndarray

Simulate a powder XRD pattern for one or more phases using xrayutilities.

Parameters:
  • tth (ndarray) –

    2θ array in degrees at which to evaluate the pattern.

  • cif_files (str or list) –

    Path(s) to CIF file(s); each phase is simulated independently.

  • do_plot (bool, default: True ) –

    If True, produce a matplotlib figure for each phase (default True).

  • energy_keV (float, default: 100.0 ) –

    X-ray energy in keV (default 100 keV).

  • crystallite_size (float, default: 1e-07 ) –

    Gaussian crystallite size in metres used for peak broadening (default 100 nm).

  • do_save (bool, default: True ) –

    If True, save each pattern to <phase_name>_simulated.xy (default True).

Returns:
  • ndarray –

    np.ndarray: Simulated intensity array for the last phase in cif_files, evaluated at tth.

Source code in src/nrxrdct/powder/simulation.py
def simulate_powder_xrd_monophase(
    tth,
    cif_files,
    do_plot=True,
    energy_keV: float = 100.0,
    crystallite_size: float = 100e-9,
    do_save: bool = True,
) -> np.ndarray:
    """
    Simulate a powder XRD pattern for one or more phases using xrayutilities.

    Args:
        tth (np.ndarray): 2θ array in degrees at which to evaluate the pattern.
        cif_files (str or list): Path(s) to CIF file(s); each phase is simulated
            independently.
        do_plot (bool, optional): If ``True``, produce a matplotlib figure for each
            phase (default ``True``).
        energy_keV (float, optional): X-ray energy in keV (default 100 keV).
        crystallite_size (float, optional): Gaussian crystallite size in metres used
            for peak broadening (default 100 nm).
        do_save (bool, optional): If ``True``, save each pattern to
            ``<phase_name>_simulated.xy`` (default ``True``).

    Returns:
        np.ndarray: Simulated intensity array for the *last* phase in *cif_files*,
            evaluated at *tth*.
    """
    if not isinstance(cif_files, list):
        cif_files = [cif_files]

    for cif in cif_files:
        mat = xu.materials.Crystal.fromCIF(cif)
        pwdr = xu.simpack.Powder(mat, 1, crystallite_size_gauss=crystallite_size)
        model = xu.simpack.PowderModel(pwdr, I0=100, en=energy_keV * 1000)
        intensity = model.simulate(tth)
        model.close()

        phase_name = mat.name.replace(" ", "_")
        if do_save:
            save_xy_file(tth, intensity, None, Path(f"{phase_name}_simulated.xy"))
        if do_plot:
            plt.figure()
            plt.plot(tth, intensity)
            plt.xlabel(r"2$\theta$ [degree]")
            plt.ylabel(r"Intensity")
            plt.title(f"{phase_name} simulated powder")

    return intensity

structures

nrxrdct.powder.structures

nrxrdct.powder.structures

Build xrayutilities Crystal objects for multi-element solid-solution alloys.

Lattice parameters are estimated via Vegard's law: the molar-fraction-weighted average of per-element CN-12 equivalent metallic radii is converted to the lattice parameter of the target structure.

Metallic radii are derived from crystallographic data when available, using a uniform volume-to-radius formula:

r_CN12 = (3 · V_atom · φ_FCC / (4π))^(1/3)

where V_atom is the volume per atom in the element's own crystal and φ_FCC = π/(3√2) ≈ 0.7405 is the FCC packing fraction. This converts any structure's atomic volume to the CN-12 equivalent radius used in Vegard's-law calculations.

Data sources (in priority order): 1. xrayutilities — crystallographic lattice parameters (exact) 2. xraylib — elemental density + atomic weight (< 1 % error)

elem_radius

elem_radius(symbol: str) -> float

Return the CN-12 equivalent metallic radius (Å) for an element symbol.

Tries xrayutilities' crystallographic data first, falls back to xraylib density data.

Parameters:
  • symbol (str) –

    Element symbol, e.g. "Fe".

Returns:
  • float( float ) –

    CN-12 metallic radius in Å.

Raises:
  • ValueError –

    If no radius data is available for the element.

Source code in src/nrxrdct/powder/structures.py
def elem_radius(symbol: str) -> float:
    """
    Return the CN-12 equivalent metallic radius (Å) for an element symbol.

    Tries xrayutilities' crystallographic data first, falls back to
    xraylib density data.

    Args:
        symbol (str): Element symbol, e.g. ``"Fe"``.

    Returns:
        float: CN-12 metallic radius in Å.

    Raises:
        ValueError: If no radius data is available for the element.
    """
    r = _xu_radius(symbol)
    if r is not None:
        return r
    r = _xrl_radius(symbol)
    if r is not None:
        return r
    raise ValueError(
        f"No radius data found for '{symbol}'. "
        "Supply the lattice parameter `a` (and `c` for HCP) directly."
    )

list_structures

list_structures() -> list[str]

Return the supported structure types for :func:make_alloy_crystal.

Source code in src/nrxrdct/powder/structures.py
def list_structures() -> list[str]:
    """Return the supported structure types for :func:`make_alloy_crystal`."""
    return sorted(_TARGET)

make_alloy_crystal

make_alloy_crystal(elements: Sequence[str], fractions: Sequence[float] | None = None, *, structure: str = 'BCC', name: str | None = None, a: float | None = None, c: float | None = None, b_factor: float = 0.0) -> xu.materials.Crystal

Build an xrayutilities Crystal for a multi-element solid-solution alloy.

Lattice parameters are estimated via Vegard's law unless overridden. Each element is placed on the same Wyckoff site with occupancy equal to its molar fraction. When fractions is not supplied every element gets equal occupancy (1/N).

Parameters:
  • elements (list of str) –

    Element symbols, e.g. ["Fe", "Ni", "Cr"].

  • fractions (list of float, default: None ) –

    Molar fractions for each element, same order as elements. Must be positive and are normalised automatically. Defaults to 1/N (equal occupancies).

  • structure (str, default: 'BCC' ) –

    Target crystal structure — one of "BCC", "FCC", "HCP", "SC" (default "BCC").

  • name (str, default: None ) –

    Name of the Crystal object. Defaults to the concatenated element symbols + _<structure>, e.g. "FeNiCr_BCC".

  • a (float, default: None ) –

    Lattice parameter a in Å. Overrides the Vegard's-law estimate.

  • c (float, default: None ) –

    Lattice parameter c in Å (HCP only). When omitted the ideal c/a ratio (√(8/3) ≈ 1.633) is used.

  • b_factor (float, default: 0.0 ) –

    Isotropic Debye–Waller B-factor applied to all sites (default 0.0).

Returns:
  • Crystal –

    xu.materials.Crystal: Crystal object ready for use with :func:~nrxrdct.powder.simulate_powder_xrd_monophase or xrayutilities' PowderModel.

Raises:
  • ValueError –

    If structure is not recognised, elements is empty, fractions length differs from elements, or a required metallic radius is unavailable and a was not supplied.

Example

Equiatomic CrMnFeCoNi Cantor alloy (FCC)

crystal = make_alloy_crystal( ... ["Cr", "Mn", "Fe", "Co", "Ni"], structure="FCC" ... ) print(f"a = {crystal.a:.4f} A")

Fe60Cr20Ni20 (wt% approximate) BCC steel, explicit a

crystal = make_alloy_crystal( ... ["Fe", "Cr", "Ni"], fractions=[0.60, 0.20, 0.20], ... structure="BCC", a=2.874 ... )

Ti-6Al-4V HCP phase (approximate)

crystal = make_alloy_crystal( ... ["Ti", "Al", "V"], fractions=[0.90, 0.06, 0.04], ... structure="HCP", ... )

Source code in src/nrxrdct/powder/structures.py
def make_alloy_crystal(
    elements: Sequence[str],
    fractions: Sequence[float] | None = None,
    *,
    structure: str = "BCC",
    name: str | None = None,
    a: float | None = None,
    c: float | None = None,
    b_factor: float = 0.0,
) -> xu.materials.Crystal:
    """
    Build an xrayutilities Crystal for a multi-element solid-solution alloy.

    Lattice parameters are estimated via Vegard's law unless overridden.
    Each element is placed on the same Wyckoff site with occupancy equal to
    its molar fraction.  When *fractions* is not supplied every element gets
    equal occupancy (1/N).

    Args:
        elements (list of str): Element symbols, e.g. ``["Fe", "Ni", "Cr"]``.
        fractions (list of float, optional): Molar fractions for each element,
            same order as *elements*.  Must be positive and are normalised
            automatically.  Defaults to ``1/N`` (equal occupancies).
        structure (str): Target crystal structure — one of ``"BCC"``,
            ``"FCC"``, ``"HCP"``, ``"SC"`` (default ``"BCC"``).
        name (str, optional): Name of the Crystal object.  Defaults to the
            concatenated element symbols + ``_<structure>``,
            e.g. ``"FeNiCr_BCC"``.
        a (float, optional): Lattice parameter *a* in Å.  Overrides the
            Vegard's-law estimate.
        c (float, optional): Lattice parameter *c* in Å (HCP only).  When
            omitted the ideal *c/a* ratio (√(8/3) ≈ 1.633) is used.
        b_factor (float): Isotropic Debye–Waller *B*-factor applied to all
            sites (default 0.0).

    Returns:
        xu.materials.Crystal: Crystal object ready for use with
            :func:`~nrxrdct.powder.simulate_powder_xrd_monophase` or
            xrayutilities' ``PowderModel``.

    Raises:
        ValueError: If *structure* is not recognised, *elements* is empty,
            *fractions* length differs from *elements*, or a required metallic
            radius is unavailable and *a* was not supplied.

    Example:
        >>> # Equiatomic CrMnFeCoNi Cantor alloy (FCC)
        >>> crystal = make_alloy_crystal(
        ...     ["Cr", "Mn", "Fe", "Co", "Ni"], structure="FCC"
        ... )
        >>> print(f"a = {crystal.a:.4f} A")

        >>> # Fe60Cr20Ni20 (wt% approximate) BCC steel, explicit a
        >>> crystal = make_alloy_crystal(
        ...     ["Fe", "Cr", "Ni"], fractions=[0.60, 0.20, 0.20],
        ...     structure="BCC", a=2.874
        ... )

        >>> # Ti-6Al-4V HCP phase (approximate)
        >>> crystal = make_alloy_crystal(
        ...     ["Ti", "Al", "V"], fractions=[0.90, 0.06, 0.04],
        ...     structure="HCP",
        ... )
    """
    structure = structure.upper()
    if structure not in _TARGET:
        raise ValueError(
            f"Unknown structure '{structure}'. "
            f"Choose from: {sorted(_TARGET)}."
        )

    elements = list(elements)
    if not elements:
        raise ValueError("`elements` must not be empty.")
    N = len(elements)

    # ── Normalise fractions ────────────────────────────────────────────────────
    if fractions is None:
        fracs = np.ones(N) / N
    else:
        fracs = np.asarray(fractions, dtype=float)
        if len(fracs) != N:
            raise ValueError(
                f"`fractions` length ({len(fracs)}) must match "
                f"`elements` length ({N})."
            )
        if np.any(fracs < 0):
            raise ValueError("`fractions` must be non-negative.")
        total = fracs.sum()
        if total <= 0:
            raise ValueError("`fractions` must sum to a positive value.")
        if not np.isclose(total, 1.0, atol=1e-6):
            warnings.warn(
                f"fractions sum to {total:.6g}; normalising to 1.",
                stacklevel=2,
            )
            fracs = fracs / total

    # ── Vegard's-law lattice parameters ───────────────────────────────────────
    sp = _TARGET[structure]

    if a is None:
        radii = np.array([elem_radius(sym) for sym in elements])
        r_avg = float(fracs @ radii)
        a = _r_to_a(r_avg, structure)

    if sp["hex"] and c is None:
        c = sp["ideal_ca"] * a

    # ── Auto-name ─────────────────────────────────────────────────────────────
    if name is None:
        name = "".join(elements) + f"_{structure}"

    # ── Build SGLattice ───────────────────────────────────────────────────────
    wyck  = sp["wyck"]
    sgnum = sp["sgnum"]

    lat_kwargs = dict(
        atoms=elements,
        pos=[wyck] * N,
        occ=fracs.tolist(),
        b=[b_factor] * N,
    )

    if sp["hex"]:
        lat = xu.materials.SGLattice(sgnum, a, c, **lat_kwargs)
    else:
        lat = xu.materials.SGLattice(sgnum, a, **lat_kwargs)

    return xu.materials.Crystal(name, lat)