科研 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.
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) — seepymatgen-materialsfor 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
| Symptom | Likely cause | Fix |
|---|---|---|
| Nothing matches any candidate | Wrong wavelength assumed (Cu vs. Mo vs. Co Kα), or 2θ range/offset miscalibrated | Confirm instrument wavelength and zero-point calibration before comparing |
| Everything "matches" with huge tolerance | tol_deg set too loose | Tighten 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 entirely | Preferred orientation (texture) in the real sample suppressing/enhancing certain reflections, or simulation ignoring the correct space group/site occupancies | Compare peak positions (most robust) before trusting intensity ratios; note texture as a caveat, do not force-fit |
| Peak positions systematically shifted by a constant offset | Sample-height/displacement error on the instrument, not a real lattice difference | Check 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
XRDCalculatorassume 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
- ASE原子模拟环境Builds and analyzes atomic structures with ASE: geometry optimization, NEB transition states, and MD trajectories. Use for setting up or analyzing atomistic simulations.
- 电池材料计算工作流Guides DFT/pymatgen workflows for battery materials: voltage profiles, phase stability, and ion migration barriers. Use for cathode, anode, or electrolyte computation.
- 催化剂设计指导Advises on catalyst composition, structure, and synthesis strategy using a traceable methodology base. Use when designing or optimizing a catalyst for a given reaction.
- 催化文献检索整理Searches arXiv, OpenAlex, and journal sites for catalysis literature and outputs a structured matrix. Use for catalysis literature reviews on a reaction or material system.
- ChEMBL生物活性数据查询Queries the ChEMBL API for bioactivity data: target lookup, IC50/Ki retrieval, and SAR tables. Use to build bioactivity datasets for a protein target.
- 量子化学计算工作流Guides quantum chemistry workflows with ORCA and xTB: geometry optimization, thermochemistry, and transition-state search. Use for first-principles energy calculations.
- 分子描述符与指纹计算Computes versioned 2D descriptors, Morgan/MACCS fingerprints, and dataset quality profiles with fixed RDKit. Use to generate reproducible features or audit data quality.
- 腐蚀电化学分析Guides corrosion analysis: electrode potentials, polarization curves, impedance, and Pourbaix diagrams. Use for electrochemical stability or corrosion-kinetics reasoning.
- 化学反应数据整理Curates structured single-step reactions against an ORD schema and RDKit, preserving originals. Use to clean reaction SMILES or tables and flag duplicates or mass-balance issues.
- RDKit简化分子处理Wraps RDKit with sensible defaults for SMILES parsing, standardization, descriptors, and conformers. Use for standard drug-discovery tasks; use rdkit for advanced control.
- 红外拉曼光谱分析Processes IR and Raman spectra with baseline correction, peak picking, and functional-group assignment. Use to interpret vibrational spectra against reference data.
- 质谱相似性比对Computes spectral similarity scores and identifies unknown compounds from mass-spectral libraries. Use for metabolite identification; use pyopenms for full proteomics pipelines.
- 分子动力学轨迹分析Analyzes MD trajectories from GROMACS, AMBER, LAMMPS, or NAMD with MDAnalysis: RMSD, RMSF, and contact maps. Use when analyzing existing trajectory files.
- 药物化学分子过滤Applies drug-likeness rules and structural alert catalogs (PAINS, NIBR) to compound libraries. Use for triaging compound libraries early in drug discovery.
- 分子数据集构建与清洗Guides molecular ML dataset building: source selection, deduplication, unit harmonization, and leakage-aware splits. Use before training molecular property models.
- 分子特征化方法Guides molecular featurization strategy for ML: parsing, fingerprints, and descriptor selection. Use when designing a featurization pipeline before model training.
- 分子机器学习特征化Converts molecules into ML-ready features using 100+ pretrained and hand-crafted featurizers. Use for QSAR modeling or virtual-screening feature generation at scale.
- 核磁共振谱图分析Processes raw NMR FID data through Fourier transform and phase correction, then picks peaks with nmrglue. Use for processing and interpreting 1D/2D NMR spectra.
- 化学文件格式转换Converts chemical file formats and generates 3D coordinates and conformers with OpenBabel and RDKit. Use when interconverting structure formats or generating 3D structures.
- pymatgen晶体材料分析Manipulates crystal structures and queries the Materials Project API for band gaps and formation energies. Use for computational materials science on crystal structures.
- 蛋白质组质谱分析Processes proteomics and metabolomics MS data via OpenMS bindings: feature detection and peptide ID. Use for LC-MS/MS pipelines; use matchms for simpler spectral comparison.
- PySCF量子化学计算Runs ab initio and DFT calculations with PySCF: HF/DFT energies, optimization, and MP2/CCSD(T). Use for first-principles molecular energy and property calculations.
- RDKit化学信息学Provides fine-grained RDKit control: I/O, descriptors, fingerprints, substructure search, and reactions. Use for advanced workflows; use datamol for a simpler interface.
- 化学物质身份解析Resolves chemical names, SMILES, InChI, or registry IDs into auditable records, preserving ambiguity. Use to confirm a chemical’s identity before standardization.
常见问题
粉末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 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。