pymatgen
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePymatgen - Python Materials Genomics
Pymatgen - Python材料基因组学工具库
Overview
概述
Pymatgen is a comprehensive Python library for materials analysis that powers the Materials Project. Create, analyze, and manipulate crystal structures and molecules, compute phase diagrams and thermodynamic properties, analyze electronic structure (band structures, DOS), generate surfaces and interfaces, and access Materials Project's database of computed materials. Supports 100+ file formats from various computational codes.
Pymatgen是一款功能全面的Python材料分析库,为Materials Project提供技术支持。可用于创建、分析和操作晶体结构与分子结构,计算相图和热力学性质,分析电子结构(能带结构、态密度),生成表面和界面结构,以及访问Materials Project的计算材料数据库。支持100余种来自各类计算代码的文件格式。
When to Use This Skill
适用场景
This skill should be used when:
- Working with crystal structures or molecular systems in materials science
- Converting between structure file formats (CIF, POSCAR, XYZ, etc.)
- Analyzing symmetry, space groups, or coordination environments
- Computing phase diagrams or assessing thermodynamic stability
- Analyzing electronic structure data (band gaps, DOS, band structures)
- Generating surfaces, slabs, or studying interfaces
- Accessing the Materials Project database programmatically
- Setting up high-throughput computational workflows
- Analyzing diffusion, magnetism, or mechanical properties
- Working with VASP, Gaussian, Quantum ESPRESSO, or other computational codes
在以下场景中可使用本工具:
- 在材料科学领域处理晶体结构或分子系统
- 在不同结构文件格式间进行转换(CIF、POSCAR、XYZ等)
- 分析对称性、空间群或配位环境
- 计算相图或评估热力学稳定性
- 分析电子结构数据(带隙、态密度、能带结构)
- 生成表面、板层结构或研究界面
- 通过编程方式访问Materials Project数据库
- 搭建高通量计算工作流
- 分析扩散、磁性或力学性质
- 使用VASP、Gaussian、Quantum ESPRESSO或其他计算代码开展工作
Quick Start Guide
快速入门指南
Installation
安装
bash
undefinedbash
undefinedCore pymatgen
核心pymatgen库
uv pip install pymatgen
uv pip install pymatgen
With Materials Project API access
包含Materials Project API访问权限
uv pip install pymatgen mp-api
uv pip install pymatgen mp-api
Optional dependencies for extended functionality
扩展功能的可选依赖
uv pip install pymatgen[analysis] # Additional analysis tools
uv pip install pymatgen[vis] # Visualization tools
undefineduv pip install pymatgen[analysis] # 额外分析工具
uv pip install pymatgen[vis] # 可视化工具
undefinedBasic Structure Operations
基础结构操作
python
from pymatgen.core import Structure, Latticepython
from pymatgen.core import Structure, LatticeRead structure from file (automatic format detection)
从文件读取结构(自动检测格式)
struct = Structure.from_file("POSCAR")
struct = Structure.from_file("POSCAR")
Create structure from scratch
从零开始创建结构
lattice = Lattice.cubic(3.84)
struct = Structure(lattice, ["Si", "Si"], [[0,0,0], [0.25,0.25,0.25]])
lattice = Lattice.cubic(3.84)
struct = Structure(lattice, ["Si", "Si"], [[0,0,0], [0.25,0.25,0.25]])
Write to different format
写入为其他格式
struct.to(filename="structure.cif")
struct.to(filename="structure.cif")
Basic properties
基础属性查看
print(f"Formula: {struct.composition.reduced_formula}")
print(f"Space group: {struct.get_space_group_info()}")
print(f"Density: {struct.density:.2f} g/cm³")
undefinedprint(f"化学式: {struct.composition.reduced_formula}")
print(f"空间群: {struct.get_space_group_info()}")
print(f"密度: {struct.density:.2f} g/cm³")
undefinedMaterials Project Integration
Materials Project集成
bash
undefinedbash
undefinedSet up API key
设置API密钥
export MP_API_KEY="your_api_key_here"
```python
from mp_api.client import MPRester
with MPRester() as mpr:
# Get structure by material ID
struct = mpr.get_structure_by_material_id("mp-149")
# Search for materials
materials = mpr.materials.summary.search(
formula="Fe2O3",
energy_above_hull=(0, 0.05)
)export MP_API_KEY="your_api_key_here"
```python
from mp_api.client import MPRester
with MPRester() as mpr:
# 通过材料ID获取结构
struct = mpr.get_structure_by_material_id("mp-149")
# 搜索材料
materials = mpr.materials.summary.search(
formula="Fe2O3",
energy_above_hull=(0, 0.05)
)Core Capabilities
核心功能
1. Structure Creation and Manipulation
1. 结构创建与操作
Create structures using various methods and perform transformations.
From files:
python
undefined通过多种方式创建结构并执行转换操作。
从文件导入:
python
undefinedAutomatic format detection
自动检测格式
struct = Structure.from_file("structure.cif")
struct = Structure.from_file("POSCAR")
mol = Molecule.from_file("molecule.xyz")
**From scratch:**
```python
from pymatgen.core import Structure, Latticestruct = Structure.from_file("structure.cif")
struct = Structure.from_file("POSCAR")
mol = Molecule.from_file("molecule.xyz")
**从零创建:**
```python
from pymatgen.core import Structure, LatticeUsing lattice parameters
使用晶格参数
lattice = Lattice.from_parameters(a=3.84, b=3.84, c=3.84,
alpha=120, beta=90, gamma=60)
coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
struct = Structure(lattice, ["Si", "Si"], coords)
lattice = Lattice.from_parameters(a=3.84, b=3.84, c=3.84,
alpha=120, beta=90, gamma=60)
coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
struct = Structure(lattice, ["Si", "Si"], coords)
From space group
从空间群创建
struct = Structure.from_spacegroup(
"Fm-3m",
Lattice.cubic(3.5),
["Si"],
[[0, 0, 0]]
)
**Transformations:**
```python
from pymatgen.transformations.standard_transformations import (
SupercellTransformation,
SubstitutionTransformation,
PrimitiveCellTransformation
)struct = Structure.from_spacegroup(
"Fm-3m",
Lattice.cubic(3.5),
["Si"],
[[0, 0, 0]]
)
**结构转换:**
```python
from pymatgen.transformations.standard_transformations import (
SupercellTransformation,
SubstitutionTransformation,
PrimitiveCellTransformation
)Create supercell
创建超胞
trans = SupercellTransformation([[2,0,0],[0,2,0],[0,0,2]])
supercell = trans.apply_transformation(struct)
trans = SupercellTransformation([[2,0,0],[0,2,0],[0,0,2]])
supercell = trans.apply_transformation(struct)
Substitute elements
元素替换
trans = SubstitutionTransformation({"Fe": "Mn"})
new_struct = trans.apply_transformation(struct)
trans = SubstitutionTransformation({"Fe": "Mn"})
new_struct = trans.apply_transformation(struct)
Get primitive cell
获取原胞
trans = PrimitiveCellTransformation()
primitive = trans.apply_transformation(struct)
**Reference:** See `references/core_classes.md` for comprehensive documentation of Structure, Lattice, Molecule, and related classes.trans = PrimitiveCellTransformation()
primitive = trans.apply_transformation(struct)
**参考文档:** 详见`references/core_classes.md`,其中包含Structure、Lattice、Molecule及相关类的完整文档。2. File Format Conversion
2. 文件格式转换
Convert between 100+ file formats with automatic format detection.
Using convenience methods:
python
undefined支持100余种文件格式间的转换,具备自动格式检测功能。
使用便捷方法:
python
undefinedRead any format
读取任意格式
struct = Structure.from_file("input_file")
struct = Structure.from_file("input_file")
Write to any format
写入为任意格式
struct.to(filename="output.cif")
struct.to(filename="POSCAR")
struct.to(filename="output.xyz")
**Using the conversion script:**
```bashstruct.to(filename="output.cif")
struct.to(filename="POSCAR")
struct.to(filename="output.xyz")
**使用转换脚本:**
```bashSingle file conversion
单个文件转换
python scripts/structure_converter.py POSCAR structure.cif
python scripts/structure_converter.py POSCAR structure.cif
Batch conversion
批量转换
python scripts/structure_converter.py *.cif --output-dir ./poscar_files --format poscar
**Reference:** See `references/io_formats.md` for detailed documentation of all supported formats and code integrations.python scripts/structure_converter.py *.cif --output-dir ./poscar_files --format poscar
**参考文档:** 详见`references/io_formats.md`,其中包含所有支持格式及代码集成的详细说明。3. Structure Analysis and Symmetry
3. 结构分析与对称性
Analyze structures for symmetry, coordination, and other properties.
Symmetry analysis:
python
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
sga = SpacegroupAnalyzer(struct)分析结构的对称性、配位环境及其他属性。
对称性分析:
python
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
sga = SpacegroupAnalyzer(struct)Get space group information
获取空间群信息
print(f"Space group: {sga.get_space_group_symbol()}")
print(f"Number: {sga.get_space_group_number()}")
print(f"Crystal system: {sga.get_crystal_system()}")
print(f"空间群: {sga.get_space_group_symbol()}")
print(f"空间群编号: {sga.get_space_group_number()}")
print(f"晶系: {sga.get_crystal_system()}")
Get conventional/primitive cells
获取常规胞/原胞
conventional = sga.get_conventional_standard_structure()
primitive = sga.get_primitive_standard_structure()
**Coordination environment:**
```python
from pymatgen.analysis.local_env import CrystalNN
cnn = CrystalNN()
neighbors = cnn.get_nn_info(struct, n=0) # Neighbors of site 0
print(f"Coordination number: {len(neighbors)}")
for neighbor in neighbors:
site = struct[neighbor['site_index']]
print(f" {site.species_string} at {neighbor['weight']:.3f} Å")Using the analysis script:
bash
undefinedconventional = sga.get_conventional_standard_structure()
primitive = sga.get_primitive_standard_structure()
**配位环境分析:**
```python
from pymatgen.analysis.local_env import CrystalNN
cnn = CrystalNN()
neighbors = cnn.get_nn_info(struct, n=0) # 位点0的邻近原子
print(f"配位数: {len(neighbors)}")
for neighbor in neighbors:
site = struct[neighbor['site_index']]
print(f" {site.species_string},距离: {neighbor['weight']:.3f} Å")使用分析脚本:
bash
undefinedComprehensive analysis
全面分析
python scripts/structure_analyzer.py POSCAR --symmetry --neighbors
python scripts/structure_analyzer.py POSCAR --symmetry --neighbors
Export results
导出结果
python scripts/structure_analyzer.py structure.cif --symmetry --export json
**Reference:** See `references/analysis_modules.md` for detailed documentation of all analysis capabilities.python scripts/structure_analyzer.py structure.cif --symmetry --export json
**参考文档:** 详见`references/analysis_modules.md`,其中包含所有分析功能的详细说明。4. Phase Diagrams and Thermodynamics
4. 相图与热力学
Construct phase diagrams and analyze thermodynamic stability.
Phase diagram construction:
python
from mp_api.client import MPRester
from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter构建相图并分析热力学稳定性。
相图构建:
python
from mp_api.client import MPRester
from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotterGet entries from Materials Project
从Materials Project获取条目
with MPRester() as mpr:
entries = mpr.get_entries_in_chemsys("Li-Fe-O")
with MPRester() as mpr:
entries = mpr.get_entries_in_chemsys("Li-Fe-O")
Build phase diagram
构建相图
pd = PhaseDiagram(entries)
pd = PhaseDiagram(entries)
Check stability
稳定性检查
from pymatgen.core import Composition
comp = Composition("LiFeO2")
from pymatgen.core import Composition
comp = Composition("LiFeO2")
Find entry for composition
查找对应组分的条目
for entry in entries:
if entry.composition.reduced_formula == comp.reduced_formula:
e_above_hull = pd.get_e_above_hull(entry)
print(f"Energy above hull: {e_above_hull:.4f} eV/atom")
if e_above_hull > 0.001:
# Get decomposition
decomp = pd.get_decomposition(comp)
print("Decomposes to:", decomp)for entry in entries:
if entry.composition.reduced_formula == comp.reduced_formula:
e_above_hull = pd.get_e_above_hull(entry)
print(f"凸包上方能量: {e_above_hull:.4f} eV/原子")
if e_above_hull > 0.001:
# 获取分解产物
decomp = pd.get_decomposition(comp)
print("分解产物:", decomp)Plot
绘图
plotter = PDPlotter(pd)
plotter.show()
**Using the phase diagram script:**
```bashplotter = PDPlotter(pd)
plotter.show()
**使用相图脚本:**
```bashGenerate phase diagram
生成相图
python scripts/phase_diagram_generator.py Li-Fe-O --output li_fe_o.png
python scripts/phase_diagram_generator.py Li-Fe-O --output li_fe_o.png
Analyze specific composition
分析特定组分
python scripts/phase_diagram_generator.py Li-Fe-O --analyze "LiFeO2" --show
**Reference:** See `references/analysis_modules.md` (Phase Diagrams section) and `references/transformations_workflows.md` (Workflow 2) for detailed examples.python scripts/phase_diagram_generator.py Li-Fe-O --analyze "LiFeO2" --show
**参考文档:** 详见`references/analysis_modules.md`(相图章节)和`references/transformations_workflows.md`(工作流2)中的详细示例。5. Electronic Structure Analysis
5. 电子结构分析
Analyze band structures, density of states, and electronic properties.
Band structure:
python
from pymatgen.io.vasp import Vasprun
from pymatgen.electronic_structure.plotter import BSPlotter分析能带结构、态密度及其他电子性质。
能带结构分析:
python
from pymatgen.io.vasp import Vasprun
from pymatgen.electronic_structure.plotter import BSPlotterRead from VASP calculation
从VASP计算结果读取
vasprun = Vasprun("vasprun.xml")
bs = vasprun.get_band_structure()
vasprun = Vasprun("vasprun.xml")
bs = vasprun.get_band_structure()
Analyze
分析带隙
band_gap = bs.get_band_gap()
print(f"Band gap: {band_gap['energy']:.3f} eV")
print(f"Direct: {band_gap['direct']}")
print(f"Is metal: {bs.is_metal()}")
band_gap = bs.get_band_gap()
print(f"带隙: {band_gap['energy']:.3f} eV")
print(f"直接带隙: {band_gap['direct']}")
print(f"金属性: {bs.is_metal()}")
Plot
绘图
plotter = BSPlotter(bs)
plotter.save_plot("band_structure.png")
**Density of states:**
```python
from pymatgen.electronic_structure.plotter import DosPlotter
dos = vasprun.complete_dosplotter = BSPlotter(bs)
plotter.save_plot("band_structure.png")
**态密度分析:**
```python
from pymatgen.electronic_structure.plotter import DosPlotter
dos = vasprun.complete_dosGet element-projected DOS
获取元素投影态密度
element_dos = dos.get_element_dos()
for element, element_dos_obj in element_dos.items():
print(f"{element}: {element_dos_obj.get_gap():.3f} eV")
element_dos = dos.get_element_dos()
for element, element_dos_obj in element_dos.items():
print(f"{element}: 带隙 {element_dos_obj.get_gap():.3f} eV")
Plot
绘图
plotter = DosPlotter()
plotter.add_dos("Total DOS", dos)
plotter.show()
**Reference:** See `references/analysis_modules.md` (Electronic Structure section) and `references/io_formats.md` (VASP section).plotter = DosPlotter()
plotter.add_dos("总态密度", dos)
plotter.show()
**参考文档:** 详见`references/analysis_modules.md`(电子结构章节)和`references/io_formats.md`(VASP章节)。6. Surface and Interface Analysis
6. 表面与界面分析
Generate slabs, analyze surfaces, and study interfaces.
Slab generation:
python
from pymatgen.core.surface import SlabGenerator生成板层结构、分析表面特性并研究界面。
板层结构生成:
python
from pymatgen.core.surface import SlabGeneratorGenerate slabs for specific Miller index
生成特定米勒指数的板层结构
slabgen = SlabGenerator(
struct,
miller_index=(1, 1, 1),
min_slab_size=10.0, # Å
min_vacuum_size=10.0, # Å
center_slab=True
)
slabs = slabgen.get_slabs()
slabgen = SlabGenerator(
struct,
miller_index=(1, 1, 1),
min_slab_size=10.0, # 埃(Å)
min_vacuum_size=10.0, # 埃(Å)
center_slab=True
)
slabs = slabgen.get_slabs()
Write slabs
导出板层结构
for i, slab in enumerate(slabs):
slab.to(filename=f"slab_{i}.cif")
**Wulff shape construction:**
```python
from pymatgen.analysis.wulff import WulffShapefor i, slab in enumerate(slabs):
slab.to(filename=f"slab_{i}.cif")
**Wulff形状构建:**
```python
from pymatgen.analysis.wulff import WulffShapeDefine surface energies
定义表面能
surface_energies = {
(1, 0, 0): 1.0,
(1, 1, 0): 1.1,
(1, 1, 1): 0.9,
}
wulff = WulffShape(struct.lattice, surface_energies)
print(f"Surface area: {wulff.surface_area:.2f} Ų")
print(f"Volume: {wulff.volume:.2f} ų")
wulff.show()
**Adsorption site finding:**
```python
from pymatgen.analysis.adsorption import AdsorbateSiteFinder
from pymatgen.core import Molecule
asf = AdsorbateSiteFinder(slab)surface_energies = {
(1, 0, 0): 1.0,
(1, 1, 0): 1.1,
(1, 1, 1): 0.9,
}
wulff = WulffShape(struct.lattice, surface_energies)
print(f"表面积: {wulff.surface_area:.2f} Ų")
print(f"体积: {wulff.volume:.2f} ų")
wulff.show()
**吸附位点查找:**
```python
from pymatgen.analysis.adsorption import AdsorbateSiteFinder
from pymatgen.core import Molecule
asf = AdsorbateSiteFinder(slab)Find sites
查找吸附位点
ads_sites = asf.find_adsorption_sites()
print(f"On-top sites: {len(ads_sites['ontop'])}")
print(f"Bridge sites: {len(ads_sites['bridge'])}")
print(f"Hollow sites: {len(ads_sites['hollow'])}")
ads_sites = asf.find_adsorption_sites()
print(f"顶位吸附位点数量: {len(ads_sites['ontop'])}")
print(f"桥位吸附位点数量: {len(ads_sites['bridge'])}")
print(f"空位吸附位点数量: {len(ads_sites['hollow'])}")
Add adsorbate
添加吸附质
adsorbate = Molecule("O", [[0, 0, 0]])
ads_struct = asf.add_adsorbate(adsorbate, ads_sites["ontop"][0])
**Reference:** See `references/analysis_modules.md` (Surface and Interface section) and `references/transformations_workflows.md` (Workflows 3 and 9).adsorbate = Molecule("O", [[0, 0, 0]])
ads_struct = asf.add_adsorbate(adsorbate, ads_sites["ontop"][0])
**参考文档:** 详见`references/analysis_modules.md`(表面与界面章节)和`references/transformations_workflows.md`(工作流3和9)。7. Materials Project Database Access
7. Materials Project数据库访问
Programmatically access the Materials Project database.
Setup:
- Get API key from https://next-gen.materialsproject.org/
- Set environment variable:
export MP_API_KEY="your_key_here"
Search and retrieve:
python
from mp_api.client import MPRester
with MPRester() as mpr:
# Search by formula
materials = mpr.materials.summary.search(formula="Fe2O3")
# Search by chemical system
materials = mpr.materials.summary.search(chemsys="Li-Fe-O")
# Filter by properties
materials = mpr.materials.summary.search(
chemsys="Li-Fe-O",
energy_above_hull=(0, 0.05), # Stable/metastable
band_gap=(1.0, 3.0) # Semiconducting
)
# Get structure
struct = mpr.get_structure_by_material_id("mp-149")
# Get band structure
bs = mpr.get_bandstructure_by_material_id("mp-149")
# Get entries for phase diagram
entries = mpr.get_entries_in_chemsys("Li-Fe-O")Reference: See for comprehensive API documentation and examples.
references/materials_project_api.md通过编程方式访问Materials Project数据库。
配置步骤:
- 从https://next-gen.materialsproject.org/获取API密钥
- 设置环境变量:
export MP_API_KEY="your_key_here"
搜索与检索:
python
from mp_api.client import MPRester
with MPRester() as mpr:
# 按化学式搜索
materials = mpr.materials.summary.search(formula="Fe2O3")
# 按化学体系搜索
materials = mpr.materials.summary.search(chemsys="Li-Fe-O")
# 按属性筛选
materials = mpr.materials.summary.search(
chemsys="Li-Fe-O",
energy_above_hull=(0, 0.05), # 稳定/亚稳定
band_gap=(1.0, 3.0) # 半导体
)
# 获取结构
struct = mpr.get_structure_by_material_id("mp-149")
# 获取能带结构
bs = mpr.get_bandstructure_by_material_id("mp-149")
# 获取相图条目
entries = mpr.get_entries_in_chemsys("Li-Fe-O")参考文档: 详见,其中包含完整的API文档与示例。
references/materials_project_api.md8. Computational Workflow Setup
8. 计算工作流搭建
Set up calculations for various electronic structure codes.
VASP input generation:
python
from pymatgen.io.vasp.sets import MPRelaxSet, MPStaticSet, MPNonSCFSet为各类电子结构代码搭建计算任务。
VASP输入文件生成:
python
from pymatgen.io.vasp.sets import MPRelaxSet, MPStaticSet, MPNonSCFSetRelaxation
弛豫计算
relax = MPRelaxSet(struct)
relax.write_input("./relax_calc")
relax = MPRelaxSet(struct)
relax.write_input("./relax_calc")
Static calculation
静态计算
static = MPStaticSet(struct)
static.write_input("./static_calc")
static = MPStaticSet(struct)
static.write_input("./static_calc")
Band structure (non-self-consistent)
能带结构(非自洽)计算
nscf = MPNonSCFSet(struct, mode="line")
nscf.write_input("./bandstructure_calc")
nscf = MPNonSCFSet(struct, mode="line")
nscf.write_input("./bandstructure_calc")
Custom parameters
自定义参数
custom = MPRelaxSet(struct, user_incar_settings={"ENCUT": 600})
custom.write_input("./custom_calc")
**Other codes:**
```pythoncustom = MPRelaxSet(struct, user_incar_settings={"ENCUT": 600})
custom.write_input("./custom_calc")
**其他代码支持:**
```pythonGaussian
Gaussian
from pymatgen.io.gaussian import GaussianInput
gin = GaussianInput(
mol,
functional="B3LYP",
basis_set="6-31G(d)",
route_parameters={"Opt": None}
)
gin.write_file("input.gjf")
from pymatgen.io.gaussian import GaussianInput
gin = GaussianInput(
mol,
functional="B3LYP",
basis_set="6-31G(d)",
route_parameters={"Opt": None}
)
gin.write_file("input.gjf")
Quantum ESPRESSO
Quantum ESPRESSO
from pymatgen.io.pwscf import PWInput
pwin = PWInput(struct, control={"calculation": "scf"})
pwin.write_file("pw.in")
**Reference:** See `references/io_formats.md` (Electronic Structure Code I/O section) and `references/transformations_workflows.md` for workflow examples.from pymatgen.io.pwscf import PWInput
pwin = PWInput(struct, control={"calculation": "scf"})
pwin.write_file("pw.in")
**参考文档:** 详见`references/io_formats.md`(电子结构代码输入输出章节)和`references/transformations_workflows.md`中的工作流示例。9. Advanced Analysis
9. 高级分析
Diffraction patterns:
python
from pymatgen.analysis.diffraction.xrd import XRDCalculator
xrd = XRDCalculator()
pattern = xrd.get_pattern(struct)衍射图谱:
python
from pymatgen.analysis.diffraction.xrd import XRDCalculator
xrd = XRDCalculator()
pattern = xrd.get_pattern(struct)Get peaks
获取衍射峰
for peak in pattern.hkls:
print(f"2θ = {peak['2theta']:.2f}°, hkl = {peak['hkl']}")
pattern.plot()
**Elastic properties:**
```python
from pymatgen.analysis.elasticity import ElasticTensorfor peak in pattern.hkls:
print(f"2θ = {peak['2theta']:.2f}°, 晶面指数 = {peak['hkl']}")
pattern.plot()
**弹性性质:**
```python
from pymatgen.analysis.elasticity import ElasticTensorFrom elastic tensor matrix
从弹性张量矩阵创建
elastic_tensor = ElasticTensor.from_voigt(matrix)
print(f"Bulk modulus: {elastic_tensor.k_voigt:.1f} GPa")
print(f"Shear modulus: {elastic_tensor.g_voigt:.1f} GPa")
print(f"Young's modulus: {elastic_tensor.y_mod:.1f} GPa")
**Magnetic ordering:**
```python
from pymatgen.transformations.advanced_transformations import MagOrderingTransformationelastic_tensor = ElasticTensor.from_voigt(matrix)
print(f"体积模量: {elastic_tensor.k_voigt:.1f} GPa")
print(f"剪切模量: {elastic_tensor.g_voigt:.1f} GPa")
print(f"杨氏模量: {elastic_tensor.y_mod:.1f} GPa")
**磁有序性:**
```python
from pymatgen.transformations.advanced_transformations import MagOrderingTransformationEnumerate magnetic orderings
枚举磁有序结构
trans = MagOrderingTransformation({"Fe": 5.0})
mag_structs = trans.apply_transformation(struct, return_ranked_list=True)
trans = MagOrderingTransformation({"Fe": 5.0})
mag_structs = trans.apply_transformation(struct, return_ranked_list=True)
Get lowest energy magnetic structure
获取最低能量的磁有序结构
lowest_energy_struct = mag_structs[0]['structure']
**Reference:** See `references/analysis_modules.md` for comprehensive analysis module documentation.lowest_energy_struct = mag_structs[0]['structure']
**参考文档:** 详见`references/analysis_modules.md`,其中包含所有分析模块的完整文档。Bundled Resources
配套资源
Scripts (scripts/
)
scripts/脚本(scripts/
)
scripts/Executable Python scripts for common tasks:
-
: Convert between structure file formats
structure_converter.py- Supports batch conversion and automatic format detection
- Usage:
python scripts/structure_converter.py POSCAR structure.cif
-
: Comprehensive structure analysis
structure_analyzer.py- Symmetry, coordination, lattice parameters, distance matrix
- Usage:
python scripts/structure_analyzer.py structure.cif --symmetry --neighbors
-
: Generate phase diagrams from Materials Project
phase_diagram_generator.py- Stability analysis and thermodynamic properties
- Usage:
python scripts/phase_diagram_generator.py Li-Fe-O --analyze "LiFeO2"
All scripts include detailed help:
python scripts/script_name.py --help用于常见任务的可执行Python脚本:
-
: 结构文件格式转换
structure_converter.py- 支持批量转换与自动格式检测
- 使用方式:
python scripts/structure_converter.py POSCAR structure.cif
-
: 全面结构分析
structure_analyzer.py- 支持对称性、配位环境、晶格参数、距离矩阵分析
- 使用方式:
python scripts/structure_analyzer.py structure.cif --symmetry --neighbors
-
: 从Materials Project生成相图
phase_diagram_generator.py- 支持稳定性分析与热力学性质计算
- 使用方式:
python scripts/phase_diagram_generator.py Li-Fe-O --analyze "LiFeO2"
所有脚本均包含详细帮助信息:
python scripts/script_name.py --helpReferences (references/
)
references/参考文档(references/
)
references/Comprehensive documentation loaded into context as needed:
- : Element, Structure, Lattice, Molecule, Composition classes
core_classes.md - : File format support and code integration (VASP, Gaussian, etc.)
io_formats.md - : Phase diagrams, surfaces, electronic structure, symmetry
analysis_modules.md - : Complete Materials Project API guide
materials_project_api.md - : Transformations framework and common workflows
transformations_workflows.md
Load references when detailed information is needed about specific modules or workflows.
根据需要加载的完整文档:
- : Element、Structure、Lattice、Molecule、Composition类的文档
core_classes.md - : 文件格式支持与代码集成(VASP、Gaussian等)
io_formats.md - : 相图、表面、电子结构、对称性分析模块文档
analysis_modules.md - : 完整的Materials Project API指南
materials_project_api.md - : 转换框架与常见工作流
transformations_workflows.md
当需要了解特定模块或工作流的详细信息时,可加载对应参考文档。
Common Workflows
常见工作流
High-Throughput Structure Generation
高通量结构生成
python
from pymatgen.transformations.standard_transformations import SubstitutionTransformation
from pymatgen.io.vasp.sets import MPRelaxSetpython
from pymatgen.transformations.standard_transformations import SubstitutionTransformation
from pymatgen.io.vasp.sets import MPRelaxSetGenerate doped structures
生成掺杂结构
base_struct = Structure.from_file("POSCAR")
dopants = ["Mn", "Co", "Ni", "Cu"]
for dopant in dopants:
trans = SubstitutionTransformation({"Fe": dopant})
doped_struct = trans.apply_transformation(base_struct)
# Generate VASP inputs
vasp_input = MPRelaxSet(doped_struct)
vasp_input.write_input(f"./calcs/Fe_{dopant}")undefinedbase_struct = Structure.from_file("POSCAR")
dopants = ["Mn", "Co", "Ni", "Cu"]
for dopant in dopants:
trans = SubstitutionTransformation({"Fe": dopant})
doped_struct = trans.apply_transformation(base_struct)
# 生成VASP输入文件
vasp_input = MPRelaxSet(doped_struct)
vasp_input.write_input(f"./calcs/Fe_{dopant}")undefinedBand Structure Calculation Workflow
能带结构计算工作流
python
undefinedpython
undefined1. Relaxation
1. 弛豫计算
relax = MPRelaxSet(struct)
relax.write_input("./1_relax")
relax = MPRelaxSet(struct)
relax.write_input("./1_relax")
2. Static (after relaxation)
2. 静态计算(弛豫完成后)
relaxed = Structure.from_file("1_relax/CONTCAR")
static = MPStaticSet(relaxed)
static.write_input("./2_static")
relaxed = Structure.from_file("1_relax/CONTCAR")
static = MPStaticSet(relaxed)
static.write_input("./2_static")
3. Band structure (non-self-consistent)
3. 能带结构(非自洽)计算
nscf = MPNonSCFSet(relaxed, mode="line")
nscf.write_input("./3_bandstructure")
nscf = MPNonSCFSet(relaxed, mode="line")
nscf.write_input("./3_bandstructure")
4. Analysis
4. 结果分析
from pymatgen.io.vasp import Vasprun
vasprun = Vasprun("3_bandstructure/vasprun.xml")
bs = vasprun.get_band_structure()
bs.get_band_gap()
undefinedfrom pymatgen.io.vasp import Vasprun
vasprun = Vasprun("3_bandstructure/vasprun.xml")
bs = vasprun.get_band_structure()
bs.get_band_gap()
undefinedSurface Energy Calculation
表面能计算
python
undefinedpython
undefined1. Get bulk energy
1. 获取块体材料的原子能量
bulk_vasprun = Vasprun("bulk/vasprun.xml")
bulk_E_per_atom = bulk_vasprun.final_energy / len(bulk)
bulk_vasprun = Vasprun("bulk/vasprun.xml")
bulk_E_per_atom = bulk_vasprun.final_energy / len(bulk)
2. Generate and calculate slabs
2. 生成并计算板层结构
slabgen = SlabGenerator(bulk, (1,1,1), 10, 15)
slab = slabgen.get_slabs()[0]
MPRelaxSet(slab).write_input("./slab_calc")
slabgen = SlabGenerator(bulk, (1,1,1), 10, 15)
slab = slabgen.get_slabs()[0]
MPRelaxSet(slab).write_input("./slab_calc")
3. Calculate surface energy (after calculation)
3. 计算表面能(计算完成后)
slab_vasprun = Vasprun("slab_calc/vasprun.xml")
E_surf = (slab_vasprun.final_energy - len(slab) * bulk_E_per_atom) / (2 * slab.surface_area)
E_surf *= 16.021766 # Convert eV/Ų to J/m²
**More workflows:** See `references/transformations_workflows.md` for 10 detailed workflow examples.slab_vasprun = Vasprun("slab_calc/vasprun.xml")
E_surf = (slab_vasprun.final_energy - len(slab) * bulk_E_per_atom) / (2 * slab.surface_area)
E_surf *= 16.021766 # 转换单位:从eV/Ų到J/m²
**更多工作流:** 详见`references/transformations_workflows.md`,其中包含10个详细的工作流示例。Best Practices
最佳实践
Structure Handling
结构处理
- Use automatic format detection: handles most formats
Structure.from_file() - Prefer immutable structures: Use when structure shouldn't change
IStructure - Check symmetry: Use to reduce to primitive cell
SpacegroupAnalyzer - Validate structures: Check for overlapping atoms or unreasonable bond lengths
- 使用自动格式检测:可处理大多数格式
Structure.from_file() - 优先使用不可变结构:当结构无需修改时,使用
IStructure - 检查对称性:使用将结构简化为原胞
SpacegroupAnalyzer - 验证结构合理性:检查是否存在原子重叠或不合理的键长
File I/O
文件输入输出
- Use convenience methods: and
from_file()are preferredto() - Specify formats explicitly: When automatic detection fails
- Handle exceptions: Wrap file I/O in try-except blocks
- Use serialization: /
as_dict()for version-safe storagefrom_dict()
- 使用便捷方法:优先使用和
from_file()方法to() - 显式指定格式:当自动检测失败时,手动指定格式
- 异常处理:将文件输入输出代码包裹在try-except块中
- 使用序列化:使用/
as_dict()实现版本安全的存储from_dict()
Materials Project API
Materials Project API使用
- Use context manager: Always use
with MPRester() as mpr: - Batch queries: Request multiple items at once
- Cache results: Save frequently used data locally
- Filter effectively: Use property filters to reduce data transfer
- 使用上下文管理器:始终使用的方式
with MPRester() as mpr: - 批量查询:一次性请求多个数据项
- 缓存结果:将频繁使用的数据保存到本地
- 有效筛选:使用属性筛选减少数据传输量
Computational Workflows
计算工作流
- Use input sets: Prefer ,
MPRelaxSetover manual INCARMPStaticSet - Check convergence: Always verify calculations converged
- Track transformations: Use for provenance
TransformedStructure - Organize calculations: Use clear directory structures
- 使用输入集:优先使用、
MPRelaxSet而非手动编写INCAR文件MPStaticSet - 检查收敛性:始终验证计算是否收敛
- 跟踪转换过程:使用记录溯源信息
TransformedStructure - 规范目录结构:使用清晰的目录组织计算任务
Performance
性能优化
- Reduce symmetry: Use primitive cells when possible
- Limit neighbor searches: Specify reasonable cutoff radii
- Use appropriate methods: Different analysis tools have different speed/accuracy tradeoffs
- Parallelize when possible: Many operations can be parallelized
- 降低对称性:尽可能使用原胞
- 限制邻近原子搜索范围:指定合理的截断半径
- 选择合适的方法:不同分析工具在速度与精度上存在权衡
- 并行化处理:许多操作可并行执行以提升效率
Units and Conventions
单位与约定
Pymatgen uses atomic units throughout:
- Lengths: Angstroms (Å)
- Energies: Electronvolts (eV)
- Angles: Degrees (°)
- Magnetic moments: Bohr magnetons (μB)
- Time: Femtoseconds (fs)
Convert units using when needed.
pymatgen.core.unitsPymatgen全程使用原子单位:
- 长度:埃(Å)
- 能量:电子伏特(eV)
- 角度:度(°)
- 磁矩:玻尔磁子(μB)
- 时间:飞秒(fs)
如需转换单位,可使用模块。
pymatgen.core.unitsIntegration with Other Tools
与其他工具的集成
Pymatgen integrates seamlessly with:
- ASE (Atomic Simulation Environment)
- Phonopy (phonon calculations)
- BoltzTraP (transport properties)
- Atomate/Fireworks (workflow management)
- AiiDA (provenance tracking)
- Zeo++ (pore analysis)
- OpenBabel (molecule conversion)
Pymatgen可与以下工具无缝集成:
- ASE(原子模拟环境)
- Phonopy(声子计算)
- BoltzTraP(输运性质计算)
- Atomate/Fireworks(工作流管理)
- AiiDA(溯源跟踪)
- Zeo++(孔隙分析)
- OpenBabel(分子转换)
Troubleshooting
故障排查
Import errors: Install missing dependencies
bash
uv pip install pymatgen[analysis,vis]API key not found: Set MP_API_KEY environment variable
bash
export MP_API_KEY="your_key_here"Structure read failures: Check file format and syntax
python
undefined导入错误:安装缺失的依赖
bash
uv pip install pymatgen[analysis,vis]API密钥未找到:设置MP_API_KEY环境变量
bash
export MP_API_KEY="your_key_here"结构读取失败:检查文件格式与语法
python
undefinedTry explicit format specification
尝试显式指定格式
struct = Structure.from_file("file.txt", fmt="cif")
**Symmetry analysis fails**: Structure may have numerical precision issues
```pythonstruct = Structure.from_file("file.txt", fmt="cif")
**对称性分析失败**:结构可能存在数值精度问题
```pythonIncrease tolerance
提高容差
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
sga = SpacegroupAnalyzer(struct, symprec=0.1)
undefinedfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer
sga = SpacegroupAnalyzer(struct, symprec=0.1)
undefinedAdditional Resources
额外资源
- Documentation: https://pymatgen.org/
- Materials Project: https://materialsproject.org/
- GitHub: https://github.com/materialsproject/pymatgen
- Forum: https://matsci.org/
- Example notebooks: https://matgenb.materialsvirtuallab.org/
- 官方文档:https://pymatgen.org/
- Materials Project官网:https://materialsproject.org/
- GitHub仓库:https://github.com/materialsproject/pymatgen
- 论坛:https://matsci.org/
- 示例笔记本:https://matgenb.materialsvirtuallab.org/
Version Notes
版本说明
This skill is designed for pymatgen 2024.x and later. For the Materials Project API, use the package (separate from legacy ).
mp-apipymatgen.ext.matprojRequirements:
- Python 3.10 or higher
- pymatgen >= 2023.x
- mp-api (for Materials Project access)
本工具适用于pymatgen 2024.x及更高版本。对于Materials Project API,请使用包(区别于旧版的)。
mp-apipymatgen.ext.matproj系统要求:
- Python 3.10或更高版本
- pymatgen >= 2023.x
- mp-api(用于访问Materials Project)