科研 Skill

粉末XRD物相分析

powder-xrd-phase-analysis

Simulates powder XRD patterns from candidate structures and matches them to an experimental pattern. Use for phase ID; use dedicated software for full Rietveld refinement.

发布者 Codar安全审核通过v0.1.0更新于 2026-11-18

SKILL.md

Powder XRD Phase Analysis

Purpose

Identify which crystalline phase(s) are present in an experimental powder X-ray diffraction (XRD) pattern by simulating theoretical patterns from candidate structures and comparing peak positions/intensities, estimate lattice parameters from matched peaks, and flag multi-phase mixtures. This fills a gap in the plugin: pymatgen-materials covers computed structure symmetry and the Materials Project database, but nothing here previously analyzed an experimental diffraction pattern.

When to Use This Skill

  • Confirming a synthesized material matches the intended crystal structure (e.g., "is this powder the target perovskite phase, or a known impurity?").
  • Identifying an unknown crystalline phase by comparing its pattern against simulated patterns for candidate structures pulled from the Materials Project or Crystallography Open Database (COD).
  • Estimating approximate lattice parameters from peak positions (Bragg's law) for quick structure-family discrimination (cubic vs. tetragonal vs. hexagonal, etc.) before committing to full refinement.
  • Detecting multi-phase samples (impurity peaks that do not match the primary candidate structure).

When Not to Use This Skill

  • For quantitative Rietveld refinement (full-pattern fitting of atomic positions, thermal factors, phase fractions with statistical uncertainty) — use dedicated software such as GSAS-II or FullProf (see Limitations); this skill's pymatgen-based matching is a fast qualitative/semi-quantitative screen, not a refinement engine.
  • For single-crystal XRD structure solution — single-crystal indexing and structure solution use different software (e.g., SHELX, Olex2) and are out of scope here.
  • For small-molecule structure determination from solution-phase data — this skill is for solid-state/crystalline powders.

Prerequisites

  • pymatgen (pip install pymatgen) for pattern simulation (pymatgen.analysis.diffraction.xrd.XRDCalculator) and structure I/O.
  • Candidate reference structures as CIF files, or a free Materials Project API key (materialsproject.org) to pull them programmatically via mp-api (pip install mp-api) — see pymatgen-materials for API-key setup details; do not duplicate that setup here beyond referencing it.
  • An experimental pattern as two columns (2θ in degrees, intensity), exported from the diffractometer software as CSV/TXT/XY, and the X-ray wavelength used (commonly Cu Kα, λ ≈ 1.5406 Å, but confirm from the instrument — a wrong wavelength assumption invalidates every downstream comparison).

Core Workflow

Step 1 — Simulate a reference pattern from a candidate structure

from pymatgen.core import Structure
from pymatgen.analysis.diffraction.xrd import XRDCalculator

structure = Structure.from_file("candidate_phase.cif")

calc = XRDCalculator(wavelength="CuKa")  # or a numeric wavelength in Angstrom
pattern = calc.get_pattern(structure, two_theta_range=(10, 80))

for two_theta, intensity, hkls, d in zip(
    pattern.x, pattern.y, pattern.hkls, pattern.d_hkls
):
    if intensity > 5:  # skip negligible reflections
        hkl_str = ", ".join(f"{h['hkl']}" for h in hkls)
        print(f"2theta={two_theta:6.2f}  I={intensity:6.1f}  d={d:.3f} A  hkl={hkl_str}")

Step 2 — Load the experimental pattern

import numpy as np
import pandas as pd

def load_experimental_xrd(path):
    df = pd.read_csv(path)
    two_theta = df.iloc[:, 0].to_numpy(dtype=float)
    intensity = df.iloc[:, 1].to_numpy(dtype=float)
    intensity = intensity / intensity.max() * 100.0  # normalize to 100
    return two_theta, intensity

exp_2theta, exp_intensity = load_experimental_xrd("experimental_pattern.csv")

Step 3 — Pick experimental peaks and match against the simulated pattern

from scipy.signal import find_peaks

def pick_xrd_peaks(two_theta, intensity, prominence=2.0, distance=5):
    idx, props = find_peaks(intensity, prominence=prominence, distance=distance)
    return pd.DataFrame({
        "two_theta": two_theta[idx],
        "intensity": intensity[idx],
    }).sort_values("intensity", ascending=False).reset_index(drop=True)

exp_peaks = pick_xrd_peaks(exp_2theta, exp_intensity)

def match_peaks(exp_peaks_df, sim_two_theta, sim_intensity, tol_deg=0.2):
    matches, unmatched = [], []
    for _, row in exp_peaks_df.iterrows():
        diffs = np.abs(np.asarray(sim_two_theta) - row["two_theta"])
        j = int(np.argmin(diffs))
        if diffs[j] <= tol_deg:
            matches.append({"exp_2theta": row["two_theta"], "sim_2theta": sim_two_theta[j],
                             "delta": diffs[j], "exp_intensity": row["intensity"]})
        else:
            unmatched.append(row["two_theta"])
    return pd.DataFrame(matches), unmatched

matched, unmatched_peaks = match_peaks(exp_peaks, pattern.x, pattern.y)
match_fraction = len(matched) / max(len(exp_peaks), 1)
print(f"{len(matched)}/{len(exp_peaks)} experimental peaks matched "
      f"({match_fraction:.0%}); unmatched 2theta: {unmatched_peaks}")

A high match_fraction (most strong experimental peaks accounted for within tolerance, e.g., ≥0.2–0.3° 2θ for typical lab diffractometer resolution) is evidence for — not proof of — the candidate phase. unmatched_peaks are candidate impurity-phase or secondary-phase reflections.

Step 4 — Screen multiple candidate phases

candidates = {
    "target_phase": "target_phase.cif",
    "known_impurity_A": "impurity_a.cif",
    "known_impurity_B": "impurity_b.cif",
}

results = {}
for name, cif in candidates.items():
    struct = Structure.from_file(cif)
    pat = calc.get_pattern(struct, two_theta_range=(10, 80))
    matched_i, _ = match_peaks(exp_peaks, pat.x, pat.y)
    results[name] = len(matched_i) / max(len(exp_peaks), 1)

for name, frac in sorted(results.items(), key=lambda kv: -kv[1]):
    print(f"{name}: {frac:.0%} of experimental peaks matched")

Step 5 — Rough lattice-parameter estimate from matched peaks (cubic case)

import numpy as np

def cubic_lattice_param_from_peak(two_theta_deg, hkl, wavelength_A=1.5406):
    """Estimate cubic lattice parameter a from one indexed peak via Bragg's law."""
    theta = np.radians(two_theta_deg / 2.0)
    d = wavelength_A / (2 * np.sin(theta))
    h, k, l = hkl
    a = d * np.sqrt(h**2 + k**2 + l**2)
    return a

# Example: (111) reflection observed at 2theta = 28.4 deg
a_est = cubic_lattice_param_from_peak(28.4, (1, 1, 1))
print(f"Estimated cubic lattice parameter a = {a_est:.4f} A")

This is only valid once the reflection has been correctly indexed (hkl known) and the crystal system is confirmed cubic; for lower-symmetry systems the corresponding d-spacing formula needs more than one peak and standard indexing software (see Limitations).

Advanced Usage

Pulling candidate structures from the Materials Project

from mp_api.client import MPRester
import os

api_key = os.getenv("MP_API_KEY")
with MPRester(api_key) as mpr:
    docs = mpr.summary.search(formula="TiO2", fields=["material_id", "structure", "symmetry"])

for d in docs[:5]:
    print(d.material_id, d.symmetry.crystal_system, d.symmetry.symbol)
    # d.structure can be passed directly to XRDCalculator.get_pattern()

Use this to screen several known polymorphs (e.g., anatase vs. rutile vs. brookite TiO2) against one experimental pattern without hand-sourcing CIFs for each.

Quantitative phase fraction (reference intensity ratio, approximate)

A rough two-phase weight-fraction estimate can be made from the ratio of a strong, non-overlapping peak's integrated intensity between phases if the Reference Intensity Ratio (RIR) for each phase is known from the literature or a corundum-standard measurement. This is an approximation; treat results as semi-quantitative (uncertainties of order tens of percent) and prefer a full Rietveld refinement for any result that needs to be defended quantitatively.

Common Failure Modes

SymptomLikely causeFix
Nothing matches any candidateWrong wavelength assumed (Cu vs. Mo vs. Co Kα), or 2θ range/offset miscalibratedConfirm instrument wavelength and zero-point calibration before comparing
Everything "matches" with huge tolerancetol_deg set too looseTighten to instrument resolution (~0.05–0.2° for most lab diffractometers); check match quality degrades sensibly as tolerance shrinks
Simulated pattern has reflections experimental data lacks entirelyPreferred orientation (texture) in the real sample suppressing/enhancing certain reflections, or simulation ignoring the correct space group/site occupanciesCompare peak positions (most robust) before trusting intensity ratios; note texture as a caveat, do not force-fit
Peak positions systematically shifted by a constant offsetSample-height/displacement error on the instrument, not a real lattice differenceCheck for a constant 2θ offset across all peaks before concluding lattice parameters differ

Limitations

  • This skill performs peak-position matching and simulated-pattern comparison, not full Rietveld refinement. It cannot refine atomic positions, thermal (Debye-Waller) factors, preferred orientation corrections, or report statistically rigorous phase-fraction uncertainties. For any of that, export the experimental pattern to GSAS-II (free, gsas-ii.readthedocs.io) or FullProf (free for academic use) and run a proper Rietveld fit.
  • Simulated intensities from XRDCalculator assume an ideal powder (random crystallite orientation, kinematic diffraction, no preferred orientation, no instrumental broadening model); real samples routinely deviate from this, especially platy or needle-like crystallites.
  • Peak matching by nearest-2θ is sensitive to instrument calibration (zero-point offset, sample-height displacement) — always check for and correct a systematic offset before concluding a phase does not match.
  • A high match fraction supports a phase assignment but is not definitive proof; always consider at least one plausible alternative phase (polymorphs, common impurities for the synthesis route) as in Step 4, and corroborate with an independent method (elemental analysis, spectroscopy, or SEM/EDS) for any conclusion that matters.

Quality Checks Before Reporting a Phase Identification

  • Confirm and state the X-ray wavelength and 2θ range used for both experimental and simulated data.
  • Check for and correct a constant 2θ offset (instrument calibration) before comparing peak positions.
  • Report match fraction and list unmatched peaks explicitly — do not silently drop them.
  • Screen at least one plausible alternative/impurity phase, not only the expected target phase.
  • State clearly that lattice-parameter estimates from one or two peaks are approximate and that quantitative phase fractions require Rietveld refinement in dedicated software.

示例提示词

用模拟衍射图谱比对这份实验粉末XRD数据,帮我判断物相。

所属插件

化学面向化学研究:化学信息学、量子化学、分子模拟、反应检索与路线评审、谱学与质谱、催化剂检索与设计、电化学。

安装该插件会一并获得同领域的 32 个 Skill / MCP。

同插件的其他科研 Skill

常见问题

粉末XRD物相分析能做什么?

Simulates powder XRD patterns from candidate structures and matches them to an experimental pattern. Use for phase ID; use dedicated software for full Rietveld refinement。

如何安装粉末XRD物相分析?

在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「粉末XRD物相分析」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。

粉末XRD物相分析需要哪些权限?

该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。

粉末XRD物相分析经过官方审核吗?

是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。