Communitygithub.com

pymatgen

使用最新的 pymatgen API 分析、驗證、轉換與變換材料結構及計算材料數據,包括局部相圖、對稱性分析、電子結構 I/O 以及明確界限的 Materials Project 查詢。

pymatgen 是什麼?

此技能專為需要以顯式且可追溯方式處理材料數據的 AI 代理與開發人員設計。核心功能圍繞 pymatgen 函式庫,涵蓋組成、分子、週期性結構、計算條目、對稱性、相圖、電子結構,以及電子結構程式碼(如 VASP、Q-Chem)的檔案 I/O。技能強調資料來源的明確記錄,要求每一步操作(如解析、轉換、對稱性分配)都記錄方法與參數,以確保可重複性。支援的平台包括 Claude Code、Cursor 與 Codex 等可執行 Python 腳本的環境。主要用途有:安全地讀取 CIF 等結構檔案(附帶警告檢查)、進行空間群對稱性分析(含容忍度敏感性掃描)、執行結構轉換(如超晶胞、取代)並保留轉換歷史、根據相容總能計算局部相圖、解析能帶結構與態密度,以及透過 mp-api 客戶端進行有計畫且受限制的 Materials Project 資料庫查詢。技能提供了捆綁的 CLI 腳本(如驗證器、轉換器、對稱性報告、相圖產生器),這些腳本設計為無隱含網路請求且僅在顯式執行時才進行科學計算。整體工作流程強制使用專案鎖定檔案以確保環境一致性,並要求對所有資料的人工製品進行清單記錄。

相容平台~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 明確且保留來源地處理組成、分子、週期性結構、計算條目、對稱性、相圖、電子結構與電子結構程式碼檔案。將每一次的解析、轉換、對稱性指定、轉換與資料庫結果視為依賴方法與參數的結果。

此技能的 frontmatter 採用 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. 說明座標模式。Structure 的座標除非設定了 coords_are_cartesian=True,否則為分數座標;Molecule 的座標為笛卡爾座標。
  4. 檢查每個解析器警告。對於 CIF,請保留佔有率、位點合併、化學計量與修正警告;請勿默默接受修正。
  5. 報告無序/部分佔有率與氧化態標記。切勿隱式猜測氧化態。
  6. 在進行對稱性、鄰近、轉換、變換或熱力學分析之前,先執行驗證。
  7. 掃描對稱性容忍度,並在每次指定時報告以 Å 為單位的 symprec 與以度為單位的 angle_tolerance。
  8. 將轉換視為新的產物。保留輸入、參數、軟體版本、警告以及父/子項目的校驗和。
  9. 在轉換之前,識別表示法損失。僅寫入新路徑,並對科學相關屬性進行往返檢查。
  10. 僅從相容的總能與修正方案建構相圖。計算出的 Hull 取決於所提供的條目集合。
  11. 預設關閉所有資料庫存取。在顯式執行步驟之前,公開端點、過濾器、欄位、結果限制、快取行為、輸出、授權與引用。
  12. 保留產物清單。切勿使用 pickle 或載入未受信任的通用物件圖;請使用經過 schema 驗證的 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:

{
  "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

必須提供元素端點與所有競爭相。請勿混合來自不同泛函、贗勢、磁態或修正慣例的原始能量。計算出的在 Hull 上方狀態並非實驗穩定性。

能帶結構、態密度、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

投影特徵值可能需要極大的記憶體。在解釋能隙或態密度之前,請驗證收斂性、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)

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.

相關技能