Pymatgen - Python Materials Genomics
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 the Materials Project
database. Supports 100+ file formats from various computational codes.
When to Use This Skill
Use 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 (band gaps, DOS, band structures)
- Generating surfaces/slabs or studying interfaces
- Accessing the Materials Project database programmatically
- Setting up high-throughput computational workflows
- Working with VASP, Gaussian, Quantum ESPRESSO, or other codes
Quick Start
uv pip install pymatgen # core
uv pip install pymatgen mp-api # + Materials Project API access
uv pip install pymatgen[analysis] # extended analysis tools
uv pip install pymatgen[vis] # visualization tools
from pymatgen.core import Structure, Lattice
struct = Structure.from_file("POSCAR") # auto format detection
struct.to(filename="structure.cif") # write any format
print(struct.composition.reduced_formula)
print(struct.get_space_group_info())
print(f"{struct.density:.2f} g/cm³")
export MP_API_KEY="your_api_key_here" # for Materials Project access
Core Capabilities (routing)
Each capability has a copy-paste code block in references/core_examples.md and deeper
module docs in the references listed below.
- Structure creation & manipulation — from files, from scratch (lattice params or
space group), transformations (supercell, substitution, primitive). →
core_classes.md
- File-format conversion —
from_file()/to() plus scripts/structure_converter.py
for single/batch. → io_formats.md
- Structure analysis & symmetry —
SpacegroupAnalyzer, CrystalNN, plus
scripts/structure_analyzer.py. → analysis_modules.md
- Phase diagrams & thermodynamics —
PhaseDiagram, energy-above-hull, decomposition,
plus scripts/phase_diagram_generator.py. → analysis_modules.md, transformations_workflows.md
- Electronic structure — band structures and DOS from
Vasprun, band gaps,
metallicity. → analysis_modules.md, io_formats.md
- Surfaces & interfaces —
SlabGenerator, WulffShape, AdsorbateSiteFinder.
→ analysis_modules.md, transformations_workflows.md
- Materials Project access —
MPRester search and retrieval with property filters.
→ materials_project_api.md
- Computational workflow setup — VASP input sets (
MPRelaxSet, MPStaticSet,
MPNonSCFSet), Gaussian, Quantum ESPRESSO. → io_formats.md, transformations_workflows.md
- Advanced analysis — XRD patterns, elastic tensors, magnetic ordering.
→
analysis_modules.md
Multi-step worked examples (high-throughput generation, band-structure pipeline, surface
energy): references/common_workflows_code.md.
Bundled Resources
Scripts (scripts/)
structure_converter.py: convert between structure file formats (batch + auto
detection). Usage: python scripts/structure_converter.py POSCAR structure.cif
structure_analyzer.py: symmetry, coordination, lattice parameters, distance
matrix. Usage: python scripts/structure_analyzer.py structure.cif --symmetry --neighbors
phase_diagram_generator.py: phase diagrams from Materials Project, stability
analysis. Usage: python scripts/phase_diagram_generator.py Li-Fe-O --analyze "LiFeO2"
All scripts include detailed help, e.g. python scripts/structure_converter.py --help
References (references/)
core_examples.md: copy-paste code for all nine core capabilities
common_workflows_code.md: multi-step worked workflow code
core_classes.md: Element, Structure, Lattice, Molecule, Composition classes
io_formats.md: file-format support and code integration (VASP, Gaussian, etc.)
analysis_modules.md: phase diagrams, surfaces, electronic structure, symmetry
materials_project_api.md: complete Materials Project API guide
transformations_workflows.md: transformations framework and 10 common workflows
Best Practices
Structures: use auto format detection; prefer IStructure when immutable; reduce to
primitive cell with SpacegroupAnalyzer; validate for overlapping atoms / bad bond
lengths. File I/O: prefer from_file()/to(); specify format when detection fails;
use as_dict()/from_dict() for version-safe storage. MP API: always use the context
manager; batch queries; cache results; filter by property. Workflows: prefer input
sets over manual INCAR; verify convergence; track transformations for provenance.
Performance: use primitive cells; bound neighbor-search cutoffs; parallelize where
possible.
Units and Conventions
Lengths in Å, energies in eV, angles in degrees, magnetic moments in μB, time in fs.
Convert with pymatgen.core.units.
Integration
Integrates with ASE, Phonopy, BoltzTraP, Atomate/Fireworks, AiiDA, Zeo++, and OpenBabel.
Troubleshooting
- Import errors:
uv pip install pymatgen[analysis,vis]
- API key not found:
export MP_API_KEY="your_key_here"
- Structure read failures: try explicit format, e.g.
Structure.from_file("file.txt", fmt="cif")
- Symmetry analysis fails: increase tolerance, e.g.
SpacegroupAnalyzer(struct, symprec=0.1)
Additional Resources
Docs: https://pymatgen.org/ · Materials Project: https://materialsproject.org/ ·
GitHub: https://github.com/materialsproject/pymatgen · Forum: https://matsci.org/ ·
Example notebooks: https://matgenb.materialsvirtuallab.org/
Version Notes
Designed for pymatgen 2024.x and later. For the Materials Project API, use the mp-api
package (separate from legacy pymatgen.ext.matproj). Requirements: Python ≥ 3.10,
pymatgen ≥ 2023.x, mp-api (for Materials Project access).
1---2name: alterlab-pymatgen3description: Analyzes and manipulates materials with the pymatgen toolkit — crystal structures and molecules, phase diagrams and thermodynamic stability, electronic structure (band structures, DOS), surfaces and interfaces, and Materials Project database access. Use when working with crystal structures in materials science, converting between structure formats (CIF, POSCAR, XYZ), analyzing symmetry or space groups, computing phase diagrams, querying the Materials Project API, or handling VASP, Gaussian, or Quantum ESPRESSO output. Part of the AlterLab Academic Skills suite.4license: MIT5---67# Pymatgen - Python Materials Genomics89## Overview1011Pymatgen is a comprehensive Python library for materials analysis that powers the12Materials Project. Create, analyze, and manipulate crystal structures and molecules;13compute phase diagrams and thermodynamic properties; analyze electronic structure (band14structures, DOS); generate surfaces and interfaces; and access the Materials Project15database. Supports 100+ file formats from various computational codes.1617## When to Use This Skill1819Use when:20- Working with crystal structures or molecular systems in materials science21- Converting between structure file formats (CIF, POSCAR, XYZ, etc.)22- Analyzing symmetry, space groups, or coordination environments23- Computing phase diagrams or assessing thermodynamic stability24- Analyzing electronic structure (band gaps, DOS, band structures)25- Generating surfaces/slabs or studying interfaces26- Accessing the Materials Project database programmatically27- Setting up high-throughput computational workflows28- Working with VASP, Gaussian, Quantum ESPRESSO, or other codes2930## Quick Start3132```bash33uv pip install pymatgen # core34uv pip install pymatgen mp-api # + Materials Project API access35uv pip install pymatgen[analysis] # extended analysis tools36uv pip install pymatgen[vis] # visualization tools37```3839```python40from pymatgen.core import Structure, Lattice4142struct = Structure.from_file("POSCAR") # auto format detection43struct.to(filename="structure.cif") # write any format44print(struct.composition.reduced_formula)45print(struct.get_space_group_info())46print(f"{struct.density:.2f} g/cm³")47```4849```bash50export MP_API_KEY="your_api_key_here" # for Materials Project access51```5253## Core Capabilities (routing)5455Each capability has a copy-paste code block in `references/core_examples.md` and deeper56module docs in the references listed below.57581. **Structure creation & manipulation** — from files, from scratch (lattice params or59 space group), transformations (supercell, substitution, primitive). → `core_classes.md`602. **File-format conversion** — `from_file()`/`to()` plus `scripts/structure_converter.py`61 for single/batch. → `io_formats.md`623. **Structure analysis & symmetry** — `SpacegroupAnalyzer`, `CrystalNN`, plus63 `scripts/structure_analyzer.py`. → `analysis_modules.md`644. **Phase diagrams & thermodynamics** — `PhaseDiagram`, energy-above-hull, decomposition,65 plus `scripts/phase_diagram_generator.py`. → `analysis_modules.md`, `transformations_workflows.md`665. **Electronic structure** — band structures and DOS from `Vasprun`, band gaps,67 metallicity. → `analysis_modules.md`, `io_formats.md`686. **Surfaces & interfaces** — `SlabGenerator`, `WulffShape`, `AdsorbateSiteFinder`.69 → `analysis_modules.md`, `transformations_workflows.md`707. **Materials Project access** — `MPRester` search and retrieval with property filters.71 → `materials_project_api.md`728. **Computational workflow setup** — VASP input sets (`MPRelaxSet`, `MPStaticSet`,73 `MPNonSCFSet`), Gaussian, Quantum ESPRESSO. → `io_formats.md`, `transformations_workflows.md`749. **Advanced analysis** — XRD patterns, elastic tensors, magnetic ordering.75 → `analysis_modules.md`7677Multi-step worked examples (high-throughput generation, band-structure pipeline, surface78energy): `references/common_workflows_code.md`.7980## Bundled Resources8182### Scripts (`scripts/`)8384- **`structure_converter.py`**: convert between structure file formats (batch + auto85 detection). Usage: `python scripts/structure_converter.py POSCAR structure.cif`86- **`structure_analyzer.py`**: symmetry, coordination, lattice parameters, distance87 matrix. Usage: `python scripts/structure_analyzer.py structure.cif --symmetry --neighbors`88- **`phase_diagram_generator.py`**: phase diagrams from Materials Project, stability89 analysis. Usage: `python scripts/phase_diagram_generator.py Li-Fe-O --analyze "LiFeO2"`9091All scripts include detailed help, e.g. `python scripts/structure_converter.py --help`9293### References (`references/`)9495- **`core_examples.md`**: copy-paste code for all nine core capabilities96- **`common_workflows_code.md`**: multi-step worked workflow code97- **`core_classes.md`**: Element, Structure, Lattice, Molecule, Composition classes98- **`io_formats.md`**: file-format support and code integration (VASP, Gaussian, etc.)99- **`analysis_modules.md`**: phase diagrams, surfaces, electronic structure, symmetry100- **`materials_project_api.md`**: complete Materials Project API guide101- **`transformations_workflows.md`**: transformations framework and 10 common workflows102103## Best Practices104105**Structures**: use auto format detection; prefer `IStructure` when immutable; reduce to106primitive cell with `SpacegroupAnalyzer`; validate for overlapping atoms / bad bond107lengths. **File I/O**: prefer `from_file()`/`to()`; specify format when detection fails;108use `as_dict()`/`from_dict()` for version-safe storage. **MP API**: always use the context109manager; batch queries; cache results; filter by property. **Workflows**: prefer input110sets over manual INCAR; verify convergence; track transformations for provenance.111**Performance**: use primitive cells; bound neighbor-search cutoffs; parallelize where112possible.113114## Units and Conventions115116Lengths in Å, energies in eV, angles in degrees, magnetic moments in μB, time in fs.117Convert with `pymatgen.core.units`.118119## Integration120121Integrates with ASE, Phonopy, BoltzTraP, Atomate/Fireworks, AiiDA, Zeo++, and OpenBabel.122123## Troubleshooting124125- **Import errors**: `uv pip install pymatgen[analysis,vis]`126- **API key not found**: `export MP_API_KEY="your_key_here"`127- **Structure read failures**: try explicit format, e.g. `Structure.from_file("file.txt", fmt="cif")`128- **Symmetry analysis fails**: increase tolerance, e.g. `SpacegroupAnalyzer(struct, symprec=0.1)`129130## Additional Resources131132Docs: https://pymatgen.org/ · Materials Project: https://materialsproject.org/ ·133GitHub: https://github.com/materialsproject/pymatgen · Forum: https://matsci.org/ ·134Example notebooks: https://matgenb.materialsvirtuallab.org/135136## Version Notes137138Designed for pymatgen 2024.x and later. For the Materials Project API, use the `mp-api`139package (separate from legacy `pymatgen.ext.matproj`). Requirements: Python ≥ 3.10,140pymatgen ≥ 2023.x, mp-api (for Materials Project access).