U

Ultimate Pymatgen

Enterprise-grade skill for materials, science, toolkit, crystal. Includes structured workflows, validation checks, and reusable patterns for scientific.

SkillClipticsscientificv1.0.0MIT
0 views0 copies

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

ClassPurposeExample Use
Structure3D periodic crystal structureCrystal analysis
MoleculeNon-periodic molecular structureGas-phase molecules
LatticeUnit cell definitionCell parameters
CompositionChemical compositionStoichiometry analysis
Element/SpeciesAtomic propertiesElectronegativity, radius
PhaseDiagramThermodynamic stabilityStability analysis
BandStructureElectronic band structureBand 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

ParameterDescriptionDefault
mp_api_keyMaterials Project API keyRequired for MP queries
symprecSymmetry precision tolerance (Å)0.1
angle_toleranceAngle tolerance for symmetry (°)5.0
oxidation_statesDefault oxidation state assignmentAuto-detected
structure_formatFile format for I/O"cif"
energy_unitsEnergy units for thermodynamics"eV/atom"

Best Practices

  1. Set symmetry precision appropriately — Use symprec=0.1 for experimental structures (which have slight distortions) and symprec=0.01 for DFT-relaxed structures (which are more precise). Too-tight tolerance misses symmetry; too-loose creates false symmetry.

  2. 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/atom are unlikely to be synthesizable. Use phase diagrams to assess stability before proposing new materials.

  3. Use the MPRester context manager — Always use with MPRester(key) as mpr: to properly manage API connections. This ensures sessions are closed correctly and avoids connection leaks that can cause rate limiting.

  4. 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.

  5. 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.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates