Ultimate Pymatgen
Enterprise-grade skill for materials, science, toolkit, crystal. Includes structured workflows, validation checks, and reusable patterns for scientific.
Ultimate Pymatgen
Analyze crystal structures, compute phase diagrams, and perform materials property predictions using Pymatgen (Python Materials Genomics). This skill covers structure creation and manipulation, thermodynamic analysis, electronic structure processing, and integration with the Materials Project database.
When to Use This Skill
Choose Ultimate Pymatgen when you need to:
- Create, manipulate, and analyze crystal structures programmatically
- Compute phase diagrams and thermodynamic stability of materials
- Parse and visualize electronic structure data (band structures, DOS)
- Query the Materials Project database for materials properties
Consider alternatives when:
- You need molecular dynamics simulations (use ASE or LAMMPS)
- You need DFT calculation setup specifically (use ASE with VASP/QE interfaces)
- You need machine learning interatomic potentials (use MACE or NequIP)
Quick Start
pip install pymatgen mp-api
from pymatgen.core import Structure, Lattice # Create a crystal structure (FCC Copper) lattice = Lattice.cubic(3.61) # Angstroms structure = Structure( lattice, ["Cu"], [[0, 0, 0]] ) print(f"Formula: {structure.composition.reduced_formula}") print(f"Space group: {structure.get_space_group_info()}") print(f"Volume: {structure.volume:.2f} ų") print(f"Density: {structure.density:.2f} g/cm³") # Query Materials Project from mp_api.client import MPRester with MPRester("YOUR_API_KEY") as mpr: docs = mpr.summary.search( formula="LiFePO4", fields=["material_id", "formula_pretty", "energy_above_hull", "band_gap", "symmetry"] ) for doc in docs[:3]: print(f"{doc.material_id}: {doc.formula_pretty}, " f"E_hull={doc.energy_above_hull:.3f} eV/atom, " f"Band gap={doc.band_gap:.2f} eV")
Core Concepts
Key Classes
| Class | Purpose | Example Use |
|---|---|---|
Structure | 3D periodic crystal structure | Crystal analysis |
Molecule | Non-periodic molecular structure | Gas-phase molecules |
Lattice | Unit cell definition | Cell parameters |
Composition | Chemical composition | Stoichiometry analysis |
Element/Species | Atomic properties | Electronegativity, radius |
PhaseDiagram | Thermodynamic stability | Stability analysis |
BandStructure | Electronic band structure | Band gap analysis |
Phase Diagram Analysis
from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter from mp_api.client import MPRester def compute_phase_diagram(elements, api_key): """Compute and analyze a phase diagram from Materials Project data.""" with MPRester(api_key) as mpr: entries = mpr.get_entries_in_chemsys(elements) pd = PhaseDiagram(entries) # Stable phases print("Stable phases:") for entry in pd.stable_entries: print(f" {entry.composition.reduced_formula}: " f"{pd.get_form_energy_per_atom(entry):.3f} eV/atom") # Check stability of a specific composition from pymatgen.core import Composition comp = Composition("Li2O") energy_hull = pd.get_hull_energy_per_atom(comp) print(f"\n{comp}: hull energy = {energy_hull:.3f} eV/atom") # Plot plotter = PDPlotter(pd) plotter.get_plot().savefig("phase_diagram.png", dpi=200) return pd pd = compute_phase_diagram(["Li", "Fe", "O"], "YOUR_API_KEY")
Structure Manipulation
from pymatgen.core import Structure, Lattice from pymatgen.transformations.standard_transformations import ( SupercellTransformation, SubstitutionTransformation ) # Load structure from file structure = Structure.from_file("POSCAR") # Create supercell supercell_transform = SupercellTransformation([[2,0,0],[0,2,0],[0,0,2]]) supercell = supercell_transform.apply_transformation(structure) print(f"Supercell: {supercell.num_sites} atoms") # Substitute atoms (doping) sub_transform = SubstitutionTransformation({"Fe": {"Fe": 0.75, "Co": 0.25}}) doped = sub_transform.apply_transformation(structure) print(f"Doped formula: {doped.composition.reduced_formula}") # Find symmetry from pymatgen.symmetry.analyzer import SpacegroupAnalyzer sga = SpacegroupAnalyzer(structure) print(f"Space group: {sga.get_space_group_symbol()}") print(f"Crystal system: {sga.get_crystal_system()}") conventional = sga.get_conventional_standard_structure()
Configuration
| Parameter | Description | Default |
|---|---|---|
mp_api_key | Materials Project API key | Required for MP queries |
symprec | Symmetry precision tolerance (Å) | 0.1 |
angle_tolerance | Angle tolerance for symmetry (°) | 5.0 |
oxidation_states | Default oxidation state assignment | Auto-detected |
structure_format | File format for I/O | "cif" |
energy_units | Energy units for thermodynamics | "eV/atom" |
Best Practices
-
Set symmetry precision appropriately — Use
symprec=0.1for experimental structures (which have slight distortions) andsymprec=0.01for DFT-relaxed structures (which are more precise). Too-tight tolerance misses symmetry; too-loose creates false symmetry. -
Always check the convex hull distance — A material's energy above the convex hull indicates thermodynamic stability. Materials with
energy_above_hull > 0.1 eV/atomare unlikely to be synthesizable. Use phase diagrams to assess stability before proposing new materials. -
Use the
MPRestercontext manager — Always usewith MPRester(key) as mpr:to properly manage API connections. This ensures sessions are closed correctly and avoids connection leaks that can cause rate limiting. -
Validate structures after manipulation — After creating supercells, substitutions, or defects, check that the structure is physically reasonable: no overlapping atoms (
structure.is_valid()), reasonable bond lengths, and correct total charge. Invalid structures cause DFT calculations to crash. -
Cache Materials Project queries — API queries are rate-limited and slow for large datasets. Save query results to local JSON or pickle files for iterative analysis rather than re-querying the database each time your analysis script runs.
Common Issues
"No API key provided" error — Set your Materials Project API key via environment variable MP_API_KEY or pass it directly to MPRester(api_key="..."). Get a free key by registering at materialsproject.org. The old key format (starting with "a") won't work with the new mp-api client.
Structure file parsing fails — Pymatgen supports CIF, POSCAR, XYZ, and other formats but is strict about formatting. For CIF files, ensure proper _symmetry tags. For POSCAR, check that ion counts match the species line. Use Structure.from_file(path) which auto-detects format.
Phase diagram computation returns empty — This happens when the Materials Project has no entries for one of the elements in your chemical system. Check individual element availability with mpr.get_entries_in_chemsys(["Li"]) before computing multi-component phase diagrams.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.