科研 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.

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

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 matchms or pyopenms.
  • 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 matchms does for mass spectra.

Prerequisites

  • Python with numpy, scipy, pandas, and matplotlib (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, use jcamp (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

SymptomLikely causeFix
Baseline correction removes real broad peaks (e.g., O-H)lam/p too aggressive for a genuinely broad featureIncrease lam, reduce p, or fit the baseline only outside the region of interest
Dozens of spurious peaks pickedNo smoothing before peak picking, or prominence too lowApply a Savitzky-Golay filter (scipy.signal.savgol_filter) first; raise prominence/distance
Fingerprint-region bands "assigned" with high confidenceCorrelation table misapplied outside its valid (functional-group) regionTreat 400–1500 cm⁻¹ assignments as low-confidence; confirm with a reference spectrum instead of the table alone
Raman spectrum dominated by a sloping backgroundFluorescence from sample or substrateALS 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 matchms provides 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

常见问题

红外拉曼光谱分析能做什么?

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 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。