科研 Skill
红外拉曼光谱分析
ir-raman-spectroscopy-analysis
Processes IR and Raman spectra with baseline correction, peak picking, and functional-group assignment. Use to interpret vibrational spectra against reference data.
SKILL.md
IR and Raman Spectroscopy Analysis
Purpose
Interpret infrared (IR) and Raman vibrational spectra: load raw spectral data,
remove baseline drift, pick peaks, assign candidate functional groups from
wavenumber correlation tables, and compare an experimental spectrum against a
reference (literature or database) spectrum. This closes a real gap in the
chemistry skill set, which otherwise covers NMR (nmr-analysis) and mass
spectrometry (matchms, pyopenms) but has no vibrational-spectroscopy
workflow.
When to Use This Skill
- Assigning functional groups from an unknown compound's IR or Raman spectrum (e.g., confirming a carbonyl, O-H, N-H, or aromatic C=C stretch).
- Comparing a measured spectrum to a reference spectrum to check product identity or purity (e.g., "does this match starting material or product?").
- Quantifying peak positions, widths, and relative intensities for a series of related compounds (e.g., substituent effects on a carbonyl stretch).
- Pre-processing noisy, sloped, or fluorescence-contaminated Raman spectra before any downstream peak analysis.
When Not to Use This Skill
- For NMR spectra — use
nmr-analysis. - For mass spectra / metabolite identification — use
matchmsorpyopenms. - As the sole evidence for structure determination — IR/Raman narrows down
functional groups and confirms expected bands; it rarely proves a full
structure on its own and should be combined with NMR, MS, and (for crystals)
powder-xrd-phase-analysis. - For definitive library matching against a large curated spectral database —
no free, comprehensive, programmatically queryable IR/Raman database is
bundled here (see Limitations); this skill supports heuristic correlation
and manual reference comparison, not automated compound ID from a spectral
library the way
matchmsdoes for mass spectra.
Prerequisites
- Python with
numpy,scipy,pandas, andmatplotlib(pip install numpy scipy pandas matplotlib). - A raw spectrum file: two columns of wavenumber (cm⁻¹) and intensity/absorbance,
as CSV/TSV, or a JCAMP-DX (
.jdx/.dx) file exported by most FTIR/Raman instrument software. For JCAMP-DX, usejcamp(pip install jcamp) to parse. - Basic familiarity with which spectral region is relevant to the question (fingerprint region 400–1500 cm⁻¹ is compound-specific and hard to assign by rule; functional-group region 1500–4000 cm⁻¹ is much more reliable for rule-based assignment — see Core Workflow).
Core Workflow
Step 1 — Load the spectrum
import numpy as np
import pandas as pd
def load_spectrum_csv(path, wn_col=0, intensity_col=1):
df = pd.read_csv(path)
wn = df.iloc[:, wn_col].to_numpy(dtype=float)
intensity = df.iloc[:, intensity_col].to_numpy(dtype=float)
# Ensure ascending wavenumber order for downstream processing
order = np.argsort(wn)
return wn[order], intensity[order]
# For JCAMP-DX files:
# import jcamp
# data = jcamp.jcamp_readfile("spectrum.jdx")
# wn, intensity = np.asarray(data["x"]), np.asarray(data["y"])
wn, intensity = load_spectrum_csv("sample_ir.csv")
print(f"Loaded {len(wn)} points, range {wn.min():.0f}-{wn.max():.0f} cm-1")
Step 2 — Baseline correction (asymmetric least squares)
Raman spectra in particular often ride on a broad fluorescence background. Asymmetric least squares (ALS) smoothing is a standard, simple baseline estimator:
from scipy import sparse
from scipy.sparse.linalg import spsolve
def als_baseline(y, lam=1e5, p=0.01, n_iter=10):
"""Eilers & Boelens (2005) asymmetric least squares baseline."""
L = len(y)
D = sparse.diags([1, -2, 1], [0, -1, -2], shape=(L, L - 2))
D = lam * D.dot(D.transpose())
w = np.ones(L)
W = sparse.spdiags(w, 0, L, L)
z = y.copy()
for _ in range(n_iter):
W.setdiag(w)
Z = W + D
z = spsolve(Z, w * y)
w = p * (y > z) + (1 - p) * (y < z)
return z
baseline = als_baseline(intensity, lam=1e5, p=0.01)
corrected = intensity - baseline
Tune lam (smoothness, larger = smoother baseline) and p (asymmetry) for the
specific instrument/sample; defaults above are reasonable starting points for
broad fluorescence backgrounds, not a universal setting.
Step 3 — Peak picking
from scipy.signal import find_peaks
def pick_peaks(wn, intensity, prominence=0.02, distance=5):
peaks_idx, props = find_peaks(intensity, prominence=prominence, distance=distance)
peaks = pd.DataFrame({
"wavenumber_cm-1": wn[peaks_idx],
"intensity": intensity[peaks_idx],
"prominence": props["prominences"],
}).sort_values("wavenumber_cm-1", ascending=False).reset_index(drop=True)
return peaks
peaks = pick_peaks(wn, corrected)
print(peaks.head(10))
Normalize intensity (e.g., divide by max) before setting prominence so the
threshold is comparable across spectra collected at different gains.
Step 4 — Functional-group assignment from a correlation table
# Minimal illustrative correlation table (cm-1 ranges). Extend/replace with a
# curated table for the compound classes relevant to the task; this is a
# teaching-grade subset, not exhaustive.
IR_CORRELATION_TABLE = [
(3200, 3550, "O-H stretch (alcohol/phenol, broad) or N-H stretch (amine/amide)"),
(3300, 3300, "Terminal alkyne C-H stretch (sharp)"),
(2500, 3000, "O-H stretch, carboxylic acid (very broad)"),
(2850, 2970, "sp3 C-H stretch"),
(2100, 2260, "C#C or C#N stretch"),
(1650, 1750, "C=O stretch (ketone/aldehyde/ester/acid; exact position is diagnostic)"),
(1580, 1650, "C=C stretch (alkene) or N-H bend (amide II region overlap)"),
(1450, 1600, "Aromatic C=C ring stretches"),
(1000, 1300, "C-O, C-N stretches (fingerprint region, less diagnostic alone)"),
]
def assign_bands(peaks, table=IR_CORRELATION_TABLE):
assignments = []
for _, row in peaks.iterrows():
wn_val = row["wavenumber_cm-1"]
matches = [label for lo, hi, label in table if lo <= wn_val <= hi]
assignments.append("; ".join(matches) if matches else "unassigned (check fingerprint region)")
peaks = peaks.copy()
peaks["candidate_assignment"] = assignments
return peaks
assigned = assign_bands(peaks)
print(assigned.to_string(index=False))
Step 5 — Compare to a reference spectrum
from scipy.interpolate import interp1d
def spectral_similarity(wn_a, int_a, wn_b, int_b, grid=None):
"""Cosine similarity after resampling both spectra onto a common grid."""
if grid is None:
lo = max(wn_a.min(), wn_b.min())
hi = min(wn_a.max(), wn_b.max())
grid = np.linspace(lo, hi, 2000)
fa = interp1d(wn_a, int_a, bounds_error=False, fill_value=0.0)
fb = interp1d(wn_b, int_b, bounds_error=False, fill_value=0.0)
a, b = fa(grid), fb(grid)
a, b = a / (np.linalg.norm(a) + 1e-12), b / (np.linalg.norm(b) + 1e-12)
return float(np.dot(a, b))
sim = spectral_similarity(wn, corrected, ref_wn, ref_intensity)
print(f"Cosine similarity to reference: {sim:.3f}")
Advanced Usage
Distinguishing IR from Raman band activity
Centrosymmetric molecules obey the mutual exclusion rule: IR-active and Raman-active modes are largely complementary (a mode active in one is typically silent in the other). When both IR and Raman spectra are available for the same compound, a band present in one but absent in the other is expected for symmetric structures and should not be treated as an inconsistency.
Reference spectra sources
No programmatic, free, comprehensive IR/Raman spectral database is bundled with this skill. For reference spectra, use:
- NIST Chemistry WebBook (webbook.nist.gov) — many compounds have digitized
IR spectra (public, searchable by name/CAS/formula; no bulk API, manual or
WebFetch-based lookup of individual compound pages). - SDBS (Spectral Database for Organic Compounds, AIST, Japan, sdbs.db.aist.go.jp) — IR, Raman, NMR, MS spectra for many organic compounds; also manual/per-compound lookup, not a bulk API.
- Vendor or literature SI spectra, digitized by hand if no machine-readable source exists — note the provenance explicitly when doing this.
Batch processing a series of spectra
import glob
records = []
for path in glob.glob("spectra/*.csv"):
wn_i, int_i = load_spectrum_csv(path)
base = als_baseline(int_i)
pk = pick_peaks(wn_i, int_i - base)
records.append({"file": path, "n_peaks": len(pk),
"top_peak_cm-1": pk.iloc[0]["wavenumber_cm-1"] if len(pk) else None})
pd.DataFrame(records).to_csv("ir_batch_summary.csv", index=False)
Common Failure Modes
| Symptom | Likely cause | Fix |
|---|---|---|
| Baseline correction removes real broad peaks (e.g., O-H) | lam/p too aggressive for a genuinely broad feature | Increase lam, reduce p, or fit the baseline only outside the region of interest |
| Dozens of spurious peaks picked | No smoothing before peak picking, or prominence too low | Apply a Savitzky-Golay filter (scipy.signal.savgol_filter) first; raise prominence/distance |
| Fingerprint-region bands "assigned" with high confidence | Correlation table misapplied outside its valid (functional-group) region | Treat 400–1500 cm⁻¹ assignments as low-confidence; confirm with a reference spectrum instead of the table alone |
| Raman spectrum dominated by a sloping background | Fluorescence from sample or substrate | ALS or polynomial baseline correction (Step 2); consider longer excitation wavelength or SERS substrate if fluorescence persists experimentally |
Limitations
- The bundled correlation table is illustrative and intentionally small; it is not a substitute for a full group-frequency reference (e.g., Socrates' Infrared and Raman Characteristic Group Frequencies). Extend it with a curated table for the compound classes relevant to the task, and always caveat fingerprint-region (400–1500 cm⁻¹) assignments as low-confidence.
- No bundled spectral database exists for automated library search the way
matchmsprovides for mass spectra; reference comparison here means fetching one or a few reference spectra manually (e.g., from NIST WebBook or SDBS) and comparing by eye or cosine similarity, not searching millions of library entries. - Peak positions and relative intensities depend on instrument resolution, sample preparation (KBr pellet vs. ATR vs. solution-phase), and calibration; comparing spectra collected under different conditions without accounting for this can produce misleading similarity scores.
- IR/Raman alone cannot usually determine a full structure or stereochemistry;
treat it as corroborating evidence alongside NMR (
nmr-analysis), mass spectrometry (matchms/pyopenms), and, for solids, diffraction (powder-xrd-phase-analysis).
Quality Checks Before Reporting an Assignment
- State whether the spectrum is IR or Raman, and the measurement geometry (ATR, transmission, dispersive/FT-Raman) if known — band positions and relative intensities differ between these.
- Report peak positions to the resolution of the instrument (typically ±1–4 cm⁻¹ for FTIR), not spuriously precise digits from interpolation.
- Flag every assignment made from the fingerprint region as tentative.
- Note the source and provenance of any reference spectrum used for comparison.
- Cross-check at least one key assignment against an independent method (NMR, MS, or known synthesis route) before stating a conclusion with confidence.
示例提示词
帮我处理这条红外光谱数据,做基线校正并标注官能团归属。
所属插件
安装该插件会一并获得同领域的 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.
- 质谱相似性比对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.
- 粉末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.
- 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.
常见问题
红外拉曼光谱分析能做什么?
Processes IR and Raman spectra with baseline correction, peak picking, and functional-group assignment. Use to interpret vibrational spectra against reference data。
如何安装红外拉曼光谱分析?
在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「红外拉曼光谱分析」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。
红外拉曼光谱分析需要哪些权限?
该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。
红外拉曼光谱分析经过官方审核吗?
是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。