Communitygithub.com

pymatgen

使用最新的 pymatgen API 分析、验证、转换和变换材料结构及计算材料数据,包括局部相图、对称性敏感度、电子结构 I/O 以及显式边界的 Materials Project 查询。

pymatgen 是什么?

pymatgen 是一个强大的材料分析库,专门用于处理成分、分子、周期结构、计算条目、对称性、相图、电子结构以及电子结构代码文件。此技能基于 pymatgen 2026.5.4 和 pymatgen-core 2026.7.16,强调显式的来源追溯和方法参数依赖。它支持本地安全的文件解析(如 CIF)、对称性分析、格式转换、变换记录、局部相图生成、VASP 和 Q-Chem 的 I/O,以及通过 mp-api 0.46.4 进行 Materials Project 查询。所有操作默认离线,查询需显式执行,并遵循严格的数据验证和来源清单要求。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/pymatgen

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

pymatgen 是做什么的?

使用 pymatgen 进行显式、来源可追溯的工作,涉及成分、分子、周期性结构、计算条目、对称性、相图、电子结构以及电子结构代码文件。将每次解析、转换、对称性分配、变换和数据库结果都视为依赖于方法和参数。

MIT 前言许可证涵盖此技能。pymatgen 和 pymatgen-core 是 MIT 许可;mp-api 声明为 BSD-3-Clause-LBNL。Materials Project 数据通常采用 CC BY 4.0,而贡献的数据仍归贡献者所有。在重新分发之前,请检查具体的工件和数据条款。

已验证的快照(2026-07-23)

  • pymatgen==2026.5.4 是最新的稳定封装版本(2026-05-04)。包元数据要求 Python 3.11+,并直接要求 pymatgen-core>=2026.4.16。
  • pymatgen-core==2026.7.16 是最新的稳定核心版本(2026-07-16)。它现在包含核心对象、对称性/晶格操作以及 I/O 层,全部位于现有的 pymatgen.* 命名空间下。
  • mp-api==0.46.4 是最新的稳定 Materials Project 客户端(2026-06-15),需要 Python 3.11+,并依赖于 pymatgen>2024.2.20。
  • 当前的 API 站点基于 2026.7.16 核心文档构建。锁定这两个发行版可防止 pymatgen==2026.5.4 静默解析到不同的未来核心版本。
  • Pymatgen 使用基于日期的版本。PyPI 用点分隔日期;不要从数字推断语义版本兼容性。

创建项目锁以确保可重现性:

uv init --python 3.11
uv add "pymatgen==2026.5.4" "pymatgen-core==2026.7.16" "mp-api==0.46.4"
uv lock
uv sync --frozen

对于一次性的审查环境:

uv venv --python 3.11 .venv-pymatgen
uv pip install --python .venv-pymatgen/bin/python \
  "pymatgen==2026.5.4" "pymatgen-core==2026.7.16" "mp-api==0.46.4"

直接固定版本并不会冻结所有传递的 wheel。请保留 uv.lock、平台、Python 版本、包版本和工件哈希值。

必需的工作流程

  1. 声明对象是非周期性的 Molecule 还是周期性的 Structure;记录晶格和周期性边界条件。
  2. 声明单位。Pymatgen 通常使用 Å、度、eV、eV/atom、amu 和 g/cm³,但每个 API 的文档合同具有权威性。
  3. 声明坐标模式。除非设置 coords_are_cartesian=True,否则 Structure 坐标是分数坐标;Molecule 坐标是笛卡尔坐标。
  4. 检查每个解析器警告。对于 CIF,保留占用率、位点合并、化学计量和修正警告;不要静默接受修复。
  5. 报告无序/部分占用和氧化态装饰。永远不要隐式猜测氧化态。
  6. 在对称性、邻近、变换、转换或热力学分析之前运行验证。
  7. 扫描对称性容差,并在每次分配时以 Å 为单位报告 symprec,以度为单位报告 angle_tolerance。
  8. 将变换视为新的工件。保留输入、参数、软件版本、警告以及父/子校验和。
  9. 在转换之前,识别表示损失。仅写入新路径,并通过往返检查科学相关的属性。
  10. 仅从兼容的总能量和修正方案构建相图。计算得到的 hull 取决于提供的条目集。
  11. 默认关闭所有数据库访问。在显式执行步骤之前,披露端点、过滤器、字段、结果限制、缓存行为、输出、许可证和引用。
  12. 保留工件清单。永远不要使用 pickle 或加载不受信任的通用对象图;使用经过模式验证的 JSON 和显式构造函数。

核心对象

使用公共便捷导入:

from pymatgen.core import Composition, Element, Lattice, Molecule, Structure

composition = Composition("LiFePO4", strict=True)
iron = Element("Fe")

lattice = Lattice.cubic(5.64)  # Å
structure = Structure(
    lattice,
    ["Na", "Cl"],
    [[0, 0, 0], [0.5, 0.5, 0.5]],
    coords_are_cartesian=False,
    validate_proximity=True,
)

molecule = Molecule(
    ["O", "H", "H"],
    [[0.0, 0.0, 0.0], [0.758, 0.0, 0.504], [-0.758, 0.0, 0.504]],
    charge=0,
    spin_multiplicity=1,
)

Structure 和 Molecule 是可变的;当修改会损害来源追溯时,请使用 IStructure/IMolecule 或显式副本。请参阅核心类。

安全的本地结构导入

优先使用附带的验证器,它会捕获 CIF 和 Python 警告,并报告单位、占用率、无序、氧化态、周期性、坐标模式和最小距离:

python scripts/composition_structure_validator.py composition "Fe2O3"
python scripts/composition_structure_validator.py structure structure.cif
python scripts/structure_analyzer.py structure.cif --symmetry

对于直接的 CIF 工作,使用当前的解析器方法并检查两个警告通道:

import warnings
from pymatgen.io.cif import CifParser

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    parser = CifParser("input.cif", check_cif=True)
    structures = parser.parse_structures(
        primitive=False,
        check_occu=True,
        on_error="raise",
    )

parser_messages = list(parser.warnings)
python_messages = [str(item.message) for item in caught]

不要在特权进程中解析不受信任的文件。一个关键的恶意 CIF 代码执行漏洞影响了直到 2024.2.8 的 pymatgen,并在 2024.2.20 中修复;固定的版本较新,但解析器仍然处理攻击者控制的内容。使用隔离和 CPU/RAM/磁盘/时间限制。

对称性

空间群分配取决于容差和结构质量:

from pymatgen.symmetry.analyzer import SpacegroupAnalyzer

analyzer = SpacegroupAnalyzer(
    structure,
    symprec=0.01,          # Å
    angle_tolerance=5.0,   # 度
)
symbol = analyzer.get_space_group_symbol()
number = analyzer.get_space_group_number()

Materials Project 流水线通常使用 symprec=0.1 Å,而 pymatgen 文档记录的默认值是 0.01 Å;这些可能产生不同的分配。生成敏感度报告,而不是更改容差直到出现首选答案:

python scripts/symmetry_sensitivity_report.py structure.cif \
  --symprec 0.001,0.01,0.1 --angle-tolerance 1,5

请参阅分析模块。

转换和解析器/写入器 I/O

提前计划;计划程序不会打开文件或导入 pymatgen:

python scripts/io_conversion_plan.py \
  --input input.cif --input-format cif \
  --output POSCAR.new --output-format poscar \
  --periodic --coordinate-mode direct

然后通过显式声明损失转换到新路径:

python scripts/structure_converter.py input.cif POSCAR.new \
  --output-format poscar --coordinate-mode direct --allow-lossy \
  --acknowledge-parser-warnings

CIF、POSCAR、XYZ 和 JSON 不保留相同的语义。每次转换后检查晶格、周期性、坐标模式、物种排序、选择性动力学、位点属性、氧化态、标签和无序。请参阅I/O 格式。

变换和来源追溯

变换副本并保留历史:

from pymatgen.alchemy.materials import TransformedStructure
from pymatgen.transformations.standard_transformations import (
    SubstitutionTransformation,
    SupercellTransformation,
)

tracked = TransformedStructure(structure.copy(), [])
tracked.append_transformation(SupercellTransformation([2, 2, 2]))
tracked.append_transformation(SubstitutionTransformation({"Na": "K"}))
derived = tracked.final_structure
history = tracked.history

一对多的排序、掺杂、切片和磁性变换可能会组合爆炸或调用可选的可执行文件。限制候选、位点、超胞大小、运行时间和输出数量。请参阅变换和工作流。

局部相图

附带的生成器是离线的,只接受具有每个条目总 eV 和来源追溯的严格 JSON 模式:

{
  "schema_version": "1.0",
  "energy_unit": "eV",
  "energy_basis": "total_per_entry",
  "provenance": {
    "source": "经审查的本地计算",
    "method": "一个兼容的能量/修正方案"
  },
  "entries": [
    {
      "entry_id": "local-Li",
      "composition": "Li",
      "energy_eV": -1.0,
      "provenance": {"source": "计算清单 sha256:..."}
    }
  ]
}
python scripts/phase_diagram_generator.py entries.json --analyze Li2O

元素端点和所有竞争相必须存在。不要混合来自不同泛函、赝势、磁态或修正约定的原始能量。计算的 on-hull 状态并非实验稳定性。

能带结构、DOS、VASP 以及 Q-Chem

仅解析所需的数据:

from pymatgen.io.vasp import Vasprun

run = Vasprun(
    "vasprun.xml",
    parse_dos=True,
    parse_eigen=True,
    parse_projected_eigen=False,
    parse_potcar_file=False,
)
band_structure = run.get_band_structure(line_mode=True)
band_gap = band_structure.get_band_gap()
complete_dos = run.complete_dos

投影本征值可能需要极大量的内存。在解释带隙或 DOS 之前,验证收敛性、k 路径、自旋/SOC 设置、费米能级约定、涂抹和投影基组。解析成功不等于计算收敛。

当前的 Q-Chem 接口是 pymatgen.io.qchem.inputs.QCInput 和 pymatgen.io.qchem.outputs.QCOutput:

from pymatgen.io.qchem.inputs import QCInput

job = QCInput(
    molecule,
    rem={"job_type": "sp", "method": "wb97x-v", "basis": "def2-svpd"},
)
text = str(job)

Pymatgen 写入输入并解析输出;它不授予 VASP 或 Q-Chem 许可证,也不建立方法有效性。POTCAR 文件是 VASP 许可的,不由 pymatgen 分发。永远不要重新分发它们或扫描无关目录。可选工具如 enumlib、Bader、packmol、ffmpeg 和 Zeo++ 是原生/外部可执行文件:在单独显式调用之前,审查来源、许可证、argv、工作目录和资源限制。

Materials Project:先规划再连接网络

仅使用:

from mp_api.client import MPRester

客户端在构造时读取 MP_API_KEY。仅通过用户的 shell 或密钥管理器提供该命名环境变量。不要接受密钥作为 CLI 参数、遍历 .env 文件、转储环境变量或输出未经编辑的异常数据。

默认进行空运行规划:

python scripts/mp_query.py \
  --chemsys Li-Fe-O \
  --energy-above-hull 0 0.05 \
  --fields formula_pretty,energy_above_hull,band_gap,origins \
  --limit 25

只有 --execute 允许一次有边界的摘要查询,并要求一个新的输出:

python scripts/mp_query.py \
  --material-id mp-149 \
  --fields formula_pretty,structure,origins,last_updated \
  --limit 1 --output mp-149.json --execute

CLI 设置 num_chunks=1,要求显式字段和过滤器,限制结果,不实现隐式结果缓存,并且从不覆盖输出。MPRester 初始化也会执行兼容性/心跳元数据请求;计划会披露这些请求,禁用平台详情用户代理和本地数据库版本通知日志,并记录返回的数据库版本。摘要工作流不请求完整数据集缓存下载。mp-api 0.46.4 根据其自身配置的策略重试 HTTP 429/502/504,并尊重 Retry-After;不要发明数字服务配额或添加无界重试循环。

Materials Project 核心值是计算得出的、依赖于方法的数据——而不是实验事实。PBE 通常高估晶格参数并系统性低估带隙;聚合值可能随数据库版本而变化。保留检索时间、查询、字段、材料/任务来源、可用的数据库版本、客户端版本、CC BY 归属以及规范的特定属性引用。请参阅Materials Project API。

附带的 CLI

所有 CLI 都有无依赖的 --help、惰性科学导入、有边界的 JSON 以及无隐式网络:

  • scripts/composition_structure_validator.py — 严格的成分/结构检查;可选的氧化态猜测是显式且有边界的。
  • scripts/structure_analyzer.py — 有边界的晶格、位点、对称性、距离和可选的 CrystalNN 报告。
  • scripts/symmetry_sensitivity_report.py — 容差网格空间群。
  • scripts/io_conversion_plan.py — 无依赖的表示损失计划。
  • scripts/structure_converter.py — 单文件转换到新路径。
  • scripts/phase_diagram_generator.py — 严格的本地计算条目 hull。
  • scripts/mp_query.py — 空运行 MP 查询计划和选择性加入的有边界客户端。
  • scripts/artifact_manifest.py — 校验和、版本、来源和来源追溯。

使用:

python scripts/artifact_manifest.py \
  --artifact input.cif --artifact analysis.json \
  --workflow "local symmetry sensitivity" --output manifest.json

参考

来源(已验证 2026-07-23)


MIT 许可证文本的可选副本请参见LICENSE文件。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相关技能