pymatgen · diff
git:20260611.c1150bd to v1.2
294 added, 574 removed. Audit A to A.
---
name: pymatgen
- description: Materials science toolkit. Crystal structures (CIF, POSCAR), phase diagrams, band structure, DOS, Materials Project integration, format conversion, for computational materials science.
- license: MIT license
- required_environment_variables: [{"name": "MP_API_KEY", "prompt": "Materials Project API key (required for MP database queries).", "required_for": "full functionality"}]
- metadata: {"version": "1.1", "skill-author": "K-Dense Inc.", "openclaw": {"primaryEnv": "MP_API_KEY", "envVars": [{"name": "MP_API_KEY", "required": true, "description": "Materials Project API key (required for MP database queries)."}]}}
+ description: Analyze, validate, convert, and transform materials structures and computed materials data with current pymatgen APIs, including local phase diagrams, symmetry sensitivity, electronic-structure I/O, and explicitly bounded Materials Project queries.
+ license: MIT
+ compatibility: Python 3.11+ with uv. The verified snapshot uses pymatgen 2026.5.4, pymatgen-core 2026.7.16, and mp-api 0.46.4. Bundled help and planning CLIs use only the standard library; local scientific execution lazily requires the pinned pymatgen packages. Materials Project access additionally requires explicit network approval and the single named secret MP_API_KEY.
+ allowed-tools:
+ - Read
+ - Write
+ - Bash
+ - Glob
+ - Python
+ metadata:
+ version: "1.2"
+ skill-author: "K-Dense Inc."
+ last-reviewed: "2026-07-23"
---
- # Pymatgen - Python Materials Genomics
-
- ## Overview
+ # pymatgen
- 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.
+ Use pymatgen for explicit, provenance-preserving work with compositions,
+ molecules, periodic structures, computed entries, symmetry, phase diagrams,
+ electronic structures, and electronic-structure-code files. Treat every parse,
+ conversion, symmetry assignment, transformation, and database result as
+ method- and parameter-dependent.
- ## When to Use This Skill
+ The MIT frontmatter license covers this skill. `pymatgen` and
+ `pymatgen-core` are MIT; `mp-api` declares BSD-3-Clause-LBNL. Materials Project
+ data is generally CC BY 4.0, while contributed data remains owned by its
+ contributors. Check the exact artifact and data terms before redistribution.
- 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
+ ## Verified snapshot (2026-07-23)
- ## Quick Start Guide
+ - `pymatgen==2026.5.4` is the latest stable wrapper release (2026-05-04).
+ Package metadata requires Python 3.11+ and directly requires
+ `pymatgen-core>=2026.4.16`.
+ - `pymatgen-core==2026.7.16` is the latest stable core release (2026-07-16).
+ It now contains core objects, symmetry/lattice operations, and the I/O layer,
+ all under the existing `pymatgen.*` namespace.
+ - `mp-api==0.46.4` is the latest stable Materials Project client
+ (2026-06-15), requires Python 3.11+, and depends on
+ `pymatgen>2024.2.20`.
+ - The current API site is built from 2026.7.16 core documentation. Pinning both
+ distributions prevents `pymatgen==2026.5.4` from silently resolving to a
+ different future core.
+ - Pymatgen uses date-based versions. PyPI renders the date with dots; do not
+ infer semantic-version compatibility from the numbers.
- ### Installation
+ Create a project lock for reproducibility:
```bash
- # Core pymatgen
- uv pip install pymatgen
-
- # With Materials Project API access
- 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
- ```
-
- ### Basic Structure Operations
-
- ```python
- from pymatgen.core import Structure, Lattice
-
- # Read structure from file (automatic format detection)
- 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]])
-
- # Write to different format
- 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³")
+ 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
```
- ### Materials Project Integration
+ For a disposable reviewed environment:
```bash
- # Set up API key
- export MP_API_KEY="your_api_key_here"
+ 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"
```
- ```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")
+ Direct pins do not freeze all transitive wheels. Preserve `uv.lock`, platform,
+ Python version, package versions, and artifact hashes.
- # Search for materials
- materials = mpr.materials.summary.search(
- formula="Fe2O3",
- energy_above_hull=(0, 0.05)
- )
- ```
+ ## Required workflow
- ## Core Capabilities
+ 1. State whether the object is a non-periodic `Molecule` or periodic
+ `Structure`; record lattice and periodic boundary conditions.
+ 2. State units. Pymatgen commonly uses Å, degrees, eV, eV/atom, amu, and
+ g/cm³, but each API's documented contract is authoritative.
+ 3. State coordinate mode. `Structure` coordinates are fractional unless
+ `coords_are_cartesian=True`; `Molecule` coordinates are Cartesian.
+ 4. Inspect every parser warning. For CIF, preserve occupancy, site-merging,
+ stoichiometry, and correction warnings; do not silently accept fixes.
+ 5. Report disorder/partial occupancies and oxidation-state decoration. Never
+ guess oxidation states implicitly.
+ 6. Run validation before symmetry, neighbor, transformation, conversion, or
+ thermodynamic analysis.
+ 7. Sweep symmetry tolerances and report `symprec` in Å and
+ `angle_tolerance` in degrees with every assignment.
+ 8. Treat transformations as new artifacts. Preserve the input, parameters,
+ software versions, warnings, and parent/child checksums.
+ 9. Before conversion, identify representation loss. Write only to a new path
+ and round-trip-check scientifically relevant properties.
+ 10. Build phase diagrams only from compatible total energies and correction
+ schemes. A computed hull is conditional on the supplied entry set.
+ 11. Keep all database access off by default. Disclose endpoint, filters,
+ fields, result limit, cache behavior, output, license, and citation before
+ an explicit execution step.
+ 12. Preserve an artifact manifest. Never use pickle or load an untrusted
+ general object graph; use schema-validated JSON and explicit constructors.
- ### 1. Structure Creation and Manipulation
+ ## Core objects
- Create structures using various methods and perform transformations.
+ Use the public convenience imports:
- **From files:**
```python
- # Automatic format detection
- struct = Structure.from_file("structure.cif")
- struct = Structure.from_file("POSCAR")
- mol = Molecule.from_file("molecule.xyz")
- ```
+ from pymatgen.core import Composition, Element, Lattice, Molecule, Structure
- **From scratch:**
- ```python
- from pymatgen.core import Structure, Lattice
+ composition = Composition("LiFePO4", strict=True)
+ iron = Element("Fe")
- # Using 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.cubic(5.64) # Å
+ structure = Structure(
+ lattice,
+ ["Na", "Cl"],
+ [[0, 0, 0], [0.5, 0.5, 0.5]],
+ coords_are_cartesian=False,
+ validate_proximity=True,
+ )
- # From space group
- struct = Structure.from_spacegroup(
- "Fm-3m",
- Lattice.cubic(3.5),
- ["Si"],
- [[0, 0, 0]]
+ 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,
)
```
- **Transformations:**
- ```python
- from pymatgen.transformations.standard_transformations import (
- SupercellTransformation,
- SubstitutionTransformation,
- PrimitiveCellTransformation
- )
+ `Structure` and `Molecule` are mutable; use `IStructure`/`IMolecule` or an
+ explicit copy when mutation would compromise provenance. See
+ [core classes](references/core_classes.md).
- # Create supercell
- trans = SupercellTransformation([[2,0,0],[0,2,0],[0,0,2]])
- supercell = trans.apply_transformation(struct)
+ ## Safe local structure intake
- # Substitute elements
- trans = SubstitutionTransformation({"Fe": "Mn"})
- new_struct = trans.apply_transformation(struct)
+ Prefer the bundled validator, which captures CIF and Python warnings and
+ reports units, occupancy, disorder, oxidation states, periodicity, coordinate
+ mode, and minimum distances:
- # Get primitive cell
- trans = PrimitiveCellTransformation()
- primitive = trans.apply_transformation(struct)
+ ```bash
+ 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
```
- **Reference:** See `references/core_classes.md` for comprehensive documentation of Structure, Lattice, Molecule, and related classes.
-
- ### 2. File Format Conversion
-
- Convert between 100+ file formats with automatic format detection.
+ For direct CIF work, use the current parser method and inspect both warning
+ channels:
- **Using convenience methods:**
```python
- # Read any format
- struct = Structure.from_file("input_file")
-
- # Write to any format
- struct.to(filename="output.cif")
- struct.to(filename="POSCAR")
- struct.to(filename="output.xyz")
- ```
+ import warnings
+ from pymatgen.io.cif import CifParser
- **Using the conversion script:**
- ```bash
- # Single file conversion
- python scripts/structure_converter.py POSCAR structure.cif
+ 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",
+ )
- # Batch conversion
- python scripts/structure_converter.py *.cif --output-dir ./poscar_files --format poscar
+ parser_messages = list(parser.warnings)
+ python_messages = [str(item.message) for item in caught]
```
- **Reference:** See `references/io_formats.md` for detailed documentation of all supported formats and code integrations.
+ Do not parse untrusted files in a privileged process. A critical malicious-CIF
+ code-execution flaw affected pymatgen through 2024.2.8 and was fixed in
+ 2024.2.20; the pinned release is newer, but parsers still process attacker
+ controlled input. Use isolation and CPU/RAM/disk/time limits.
- ### 3. Structure Analysis and Symmetry
+ ## Symmetry
- Analyze structures for symmetry, coordination, and other properties.
+ Space-group assignment depends on tolerances and structure quality:
- **Symmetry analysis:**
```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()}")
-
- # Get conventional/primitive cells
- conventional = sga.get_conventional_standard_structure()
- primitive = sga.get_primitive_standard_structure()
+ analyzer = SpacegroupAnalyzer(
+ structure,
+ symprec=0.01, # Å
+ angle_tolerance=5.0, # degrees
+ )
+ symbol = analyzer.get_space_group_symbol()
+ number = analyzer.get_space_group_number()
```
- **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} Å")
- ```
+ The Materials Project pipeline commonly uses `symprec=0.1 Å`, while pymatgen's
+ documented default is `0.01 Å`; these can produce different assignments.
+ Generate a sensitivity report instead of changing tolerance until a preferred
+ answer appears:
- **Using the analysis script:**
```bash
- # Comprehensive analysis
- python scripts/structure_analyzer.py POSCAR --symmetry --neighbors
-
- # Export results
- python scripts/structure_analyzer.py structure.cif --symmetry --export json
+ python scripts/symmetry_sensitivity_report.py structure.cif \
+ --symprec 0.001,0.01,0.1 --angle-tolerance 1,5
```
- **Reference:** See `references/analysis_modules.md` for detailed documentation of all analysis capabilities.
-
- ### 4. Phase Diagrams and Thermodynamics
-
- 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
-
- # Get entries from Materials Project
- with MPRester() as mpr:
- entries = mpr.get_entries_in_chemsys("Li-Fe-O")
-
- # Build phase diagram
- pd = PhaseDiagram(entries)
-
- # Check stability
- 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")
+ See [analysis modules](references/analysis_modules.md).
- if e_above_hull > 0.001:
- # Get decomposition
- decomp = pd.get_decomposition(comp)
- print("Decomposes to:", decomp)
+ ## Conversion and parser/writer I/O
- # Plot
- plotter = PDPlotter(pd)
- plotter.show()
- ```
+ Plan first; the planner does not open files or import pymatgen:
- **Using the phase diagram script:**
```bash
- # Generate phase diagram
- 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.
-
- ### 5. Electronic Structure Analysis
-
- 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
-
- # Read from VASP calculation
- 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()}")
-
- # Plot
- plotter = BSPlotter(bs)
- plotter.save_plot("band_structure.png")
+ python scripts/io_conversion_plan.py \
+ --input input.cif --input-format cif \
+ --output POSCAR.new --output-format poscar \
+ --periodic --coordinate-mode direct
```
- **Density of states:**
- ```python
- from pymatgen.electronic_structure.plotter import DosPlotter
-
- dos = vasprun.complete_dos
-
- # Get 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")
+ Then convert to a new path with explicit loss acknowledgement:
- # Plot
- plotter = DosPlotter()
- plotter.add_dos("Total DOS", dos)
- plotter.show()
+ ```bash
+ python scripts/structure_converter.py input.cif POSCAR.new \
+ --output-format poscar --coordinate-mode direct --allow-lossy \
+ --acknowledge-parser-warnings
```
- **Reference:** See `references/analysis_modules.md` (Electronic Structure section) and `references/io_formats.md` (VASP section).
+ CIF, POSCAR, XYZ, and JSON do not preserve the same semantics. Check lattice,
+ periodicity, coordinate mode, species ordering, selective dynamics, site
+ properties, oxidation states, labels, and disorder after every conversion.
+ See [I/O formats](references/io_formats.md).
- ### 6. Surface and Interface Analysis
+ ## Transformations and provenance
- Generate slabs, analyze surfaces, and study interfaces.
+ Transform a copy and preserve history:
- **Slab generation:**
```python
- from pymatgen.core.surface import SlabGenerator
-
- # Generate 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
+ from pymatgen.alchemy.materials import TransformedStructure
+ from pymatgen.transformations.standard_transformations import (
+ SubstitutionTransformation,
+ SupercellTransformation,
)
- 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 WulffShape
-
- # Define 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()
+ tracked = TransformedStructure(structure.copy(), [])
+ tracked.append_transformation(SupercellTransformation([2, 2, 2]))
+ tracked.append_transformation(SubstitutionTransformation({"Na": "K"}))
+ derived = tracked.final_structure
+ history = tracked.history
```
- **Adsorption site finding:**
- ```python
- from pymatgen.analysis.adsorption import AdsorbateSiteFinder
- from pymatgen.core import Molecule
+ One-to-many ordering, doping, slab, and magnetic transformations can expand
+ combinatorially or invoke optional executables. Bound candidates, sites,
+ supercell size, runtime, and output count. See
+ [transformations and workflows](references/transformations_workflows.md).
- asf = AdsorbateSiteFinder(slab)
+ ## Local phase diagrams
- # 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'])}")
+ The bundled generator is offline and accepts only a strict JSON schema with
+ total eV per entry and provenance:
- # Add adsorbate
- adsorbate = Molecule("O", [[0, 0, 0]])
- ads_struct = asf.add_adsorbate(adsorbate, ads_sites["ontop"][0])
+ ```json
+ {
+ "schema_version": "1.0",
+ "energy_unit": "eV",
+ "energy_basis": "total_per_entry",
+ "provenance": {
+ "source": "reviewed local calculations",
+ "method": "one compatible energy/correction scheme"
+ },
+ "entries": [
+ {
+ "entry_id": "local-Li",
+ "composition": "Li",
+ "energy_eV": -1.0,
+ "provenance": {"source": "calculation manifest sha256:..."}
+ }
+ ]
+ }
```
- **Reference:** See `references/analysis_modules.md` (Surface and Interface section) and `references/transformations_workflows.md` (Workflows 3 and 9).
-
- ### 7. Materials Project Database Access
-
- Programmatically access the Materials Project database.
-
- **Setup:**
- 1. Get API key from https://next-gen.materialsproject.org/
- 2. 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")
+ ```bash
+ python scripts/phase_diagram_generator.py entries.json --analyze Li2O
```
- **Reference:** See `references/materials_project_api.md` for comprehensive API documentation and examples.
-
- ### 8. Computational Workflow Setup
-
- Set up calculations for various electronic structure codes.
-
- **VASP input generation:**
- ```python
- from pymatgen.io.vasp.sets import MPRelaxSet, MPStaticSet, MPNonSCFSet
-
- # Relaxation
- relax = MPRelaxSet(struct)
- relax.write_input("./relax_calc")
-
- # Static calculation
- static = MPStaticSet(struct)
- static.write_input("./static_calc")
+ Elemental endpoints and all competing phases must be present. Do not mix raw
+ energies from different functionals, pseudopotentials, magnetic states, or
+ correction conventions. Computed on-hull status is not experimental stability.
- # Band structure (non-self-consistent)
- nscf = MPNonSCFSet(struct, mode="line")
- nscf.write_input("./bandstructure_calc")
+ ## Band structures, DOS, VASP, and Q-Chem
- # Custom parameters
- custom = MPRelaxSet(struct, user_incar_settings={"ENCUT": 600})
- custom.write_input("./custom_calc")
- ```
+ Parse only the data needed:
- **Other codes:**
```python
- # Gaussian
- from pymatgen.io.gaussian import GaussianInput
+ from pymatgen.io.vasp import Vasprun
- gin = GaussianInput(
- mol,
- functional="B3LYP",
- basis_set="6-31G(d)",
- route_parameters={"Opt": None}
+ run = Vasprun(
+ "vasprun.xml",
+ parse_dos=True,
+ parse_eigen=True,
+ parse_projected_eigen=False,
+ parse_potcar_file=False,
)
- gin.write_file("input.gjf")
-
- # 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.
-
- ### 9. Advanced Analysis
-
- **Diffraction patterns:**
- ```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()
+ band_structure = run.get_band_structure(line_mode=True)
+ band_gap = band_structure.get_band_gap()
+ complete_dos = run.complete_dos
```
- **Elastic properties:**
- ```python
- from pymatgen.analysis.elasticity import ElasticTensor
-
- # From elastic tensor matrix
- elastic_tensor = ElasticTensor.from_voigt(matrix)
+ Projected eigenvalues can require extreme memory. Verify convergence, k-path,
+ spin/SOC settings, Fermi-level conventions, smearing, and projection basis
+ before interpreting gaps or DOS. A parser success is not a converged
+ calculation.
- 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")
- ```
+ Current Q-Chem interfaces are `pymatgen.io.qchem.inputs.QCInput` and
+ `pymatgen.io.qchem.outputs.QCOutput`:
- **Magnetic ordering:**
```python
- from pymatgen.transformations.advanced_transformations import MagOrderingTransformation
-
- # Enumerate magnetic orderings
- trans = MagOrderingTransformation({"Fe": 5.0})
- mag_structs = trans.apply_transformation(struct, return_ranked_list=True)
+ from pymatgen.io.qchem.inputs import QCInput
- # Get lowest energy magnetic structure
- lowest_energy_struct = mag_structs[0]['structure']
+ job = QCInput(
+ molecule,
+ rem={"job_type": "sp", "method": "wb97x-v", "basis": "def2-svpd"},
+ )
+ text = str(job)
```
- **Reference:** See `references/analysis_modules.md` for comprehensive analysis module documentation.
-
- ## Bundled Resources
-
- ### Scripts (`scripts/`)
-
- Executable Python scripts for common tasks:
-
- - **`structure_converter.py`**: Convert between structure file formats
- - Supports batch conversion and automatic format detection
- - Usage: `python scripts/structure_converter.py POSCAR structure.cif`
-
- - **`structure_analyzer.py`**: Comprehensive structure analysis
- - Symmetry, coordination, lattice parameters, distance matrix
- - Usage: `python scripts/structure_analyzer.py structure.cif --symmetry --neighbors`
-
- - **`phase_diagram_generator.py`**: Generate phase diagrams from Materials Project
- - 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`
-
- ### References (`references/`)
-
- Comprehensive documentation loaded into context as needed:
-
- - **`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 common workflows
-
- Load references when detailed information is needed about specific modules or workflows.
+ Pymatgen writes inputs and parses outputs; it does not grant a VASP or Q-Chem
+ license or establish method validity. POTCAR files are VASP-licensed and are
+ not distributed by pymatgen. Never redistribute them or scan unrelated
+ directories for them. Optional tools such as enumlib, Bader, packmol, ffmpeg,
+ and Zeo++ are native/external executables: review provenance, licenses, argv,
+ working directory, and resource limits before a separate explicit invocation.
- ## Common Workflows
+ ## Materials Project: plan before network
- ### High-Throughput Structure Generation
+ Use only:
```python
- from pymatgen.transformations.standard_transformations import SubstitutionTransformation
- from pymatgen.io.vasp.sets import MPRelaxSet
-
- # Generate 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}")
+ from mp_api.client import MPRester
```
- ### Band Structure Calculation Workflow
-
- ```python
- # 1. Relaxation
- relax = MPRelaxSet(struct)
- relax.write_input("./1_relax")
-
- # 2. Static (after relaxation)
- relaxed = Structure.from_file("1_relax/CONTCAR")
- static = MPStaticSet(relaxed)
- static.write_input("./2_static")
+ The client reads `MP_API_KEY` when constructed. Supply only that named
+ environment variable through the user's shell or secret manager. Do not accept
+ the key as a CLI argument, traverse `.env` files, dump environment variables,
+ or print exception data without redaction.
- # 3. Band structure (non-self-consistent)
- nscf = MPNonSCFSet(relaxed, mode="line")
- nscf.write_input("./3_bandstructure")
+ Dry-run planning is the default:
- # 4. Analysis
- from pymatgen.io.vasp import Vasprun
- vasprun = Vasprun("3_bandstructure/vasprun.xml")
- bs = vasprun.get_band_structure()
- bs.get_band_gap()
+ ```bash
+ 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
```
- ### Surface Energy Calculation
-
- ```python
- # 1. Get bulk energy
- bulk_vasprun = Vasprun("bulk/vasprun.xml")
- bulk_E_per_atom = bulk_vasprun.final_energy / len(bulk)
-
- # 2. Generate and calculate slabs
- slabgen = SlabGenerator(bulk, (1,1,1), 10, 15)
- slab = slabgen.get_slabs()[0]
-
- MPRelaxSet(slab).write_input("./slab_calc")
+ Only `--execute` permits one bounded summary query and requires a new output:
- # 3. Calculate surface energy (after calculation)
- 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²
+ ```bash
+ python scripts/mp_query.py \
+ --material-id mp-149 \
+ --fields formula_pretty,structure,origins,last_updated \
+ --limit 1 --output mp-149.json --execute
```
- **More workflows:** See `references/transformations_workflows.md` for 10 detailed workflow examples.
-
- ## Best Practices
-
- ### Structure Handling
-
- 1. **Use automatic format detection**: `Structure.from_file()` handles most formats
- 2. **Prefer immutable structures**: Use `IStructure` when structure shouldn't change
- 3. **Check symmetry**: Use `SpacegroupAnalyzer` to reduce to primitive cell
- 4. **Validate structures**: Check for overlapping atoms or unreasonable bond lengths
-
- ### File I/O
-
- 1. **Use convenience methods**: `from_file()` and `to()` are preferred
- 2. **Specify formats explicitly**: When automatic detection fails
- 3. **Handle exceptions**: Wrap file I/O in try-except blocks
- 4. **Use serialization**: `as_dict()`/`from_dict()` for version-safe storage
-
- ### Materials Project API
-
- 1. **Use context manager**: Always use `with MPRester() as mpr:`
- 2. **Batch queries**: Request multiple items at once
- 3. **Cache results**: Save frequently used data locally
- 4. **Filter effectively**: Use property filters to reduce data transfer
-
- ### Computational Workflows
-
- 1. **Use input sets**: Prefer `MPRelaxSet`, `MPStaticSet` over manual INCAR
- 2. **Check convergence**: Always verify calculations converged
- 3. **Track transformations**: Use `TransformedStructure` for provenance
- 4. **Organize calculations**: Use clear directory structures
-
- ### Performance
-
- 1. **Reduce symmetry**: Use primitive cells when possible
- 2. **Limit neighbor searches**: Specify reasonable cutoff radii
- 3. **Use appropriate methods**: Different analysis tools have different speed/accuracy tradeoffs
- 4. **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)
+ The CLI sets `num_chunks=1`, requires explicit fields and filters, caps results,
+ does not implement an implicit result cache, and never overwrites output.
+ `MPRester` initialization also performs compatibility/heartbeat metadata
+ requests; the plan discloses these, disables the platform-detail user agent and
+ local database-version notification log, and records the returned database
+ version. The summary workflow does not request full-dataset cache downloads.
+ `mp-api` 0.46.4 retries HTTP 429/502/504 according to its own configured policy
+ and respects `Retry-After`; do not invent a numeric service quota or add an
+ unbounded retry loop.
- Convert units using `pymatgen.core.units` when needed.
+ Materials Project core values are computed, method-dependent data—not
+ experimental truth. PBE commonly overestimates lattice parameters and
+ systematically underestimates band gaps; aggregated values can change across
+ database releases. Preserve retrieval time, query, fields, material/task
+ origins, database release when available, client versions, CC BY attribution,
+ and the canonical plus property-specific citations. See
+ [Materials Project API](references/materials_project_api.md).
- ## Integration with Other Tools
+ ## Bundled CLIs
- 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)
+ All CLIs have dependency-free `--help`, lazy scientific imports, bounded JSON,
+ and no implicit network:
- ## Troubleshooting
+ - `scripts/composition_structure_validator.py` — strict composition/structure
+ checks; optional oxidation-state guessing is explicit and bounded.
+ - `scripts/structure_analyzer.py` — bounded lattice, sites, symmetry, distance,
+ and optional CrystalNN report.
+ - `scripts/symmetry_sensitivity_report.py` — tolerance-grid space groups.
+ - `scripts/io_conversion_plan.py` — dependency-free representation-loss plan.
+ - `scripts/structure_converter.py` — one-file conversion to a new path.
+ - `scripts/phase_diagram_generator.py` — strict local computed-entry hull.
+ - `scripts/mp_query.py` — dry-run MP query plan and opt-in bounded client.
+ - `scripts/artifact_manifest.py` — checksums, versions, sources, and provenance.
- **Import errors**: Install missing dependencies
- ```bash
- uv pip install pymatgen[analysis,vis]
- ```
+ Use:
- **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
- # Try explicit format specification
- struct = Structure.from_file("file.txt", fmt="cif")
- ```
-
- **Symmetry analysis fails**: Structure may have numerical precision issues
- ```python
- # Increase tolerance
- from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
- sga = SpacegroupAnalyzer(struct, symprec=0.1)
+ python scripts/artifact_manifest.py \
+ --artifact input.cif --artifact analysis.json \
+ --workflow "local symmetry sensitivity" --output manifest.json
```
- ## Additional 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/
-
- ## Version Notes
+ ## References
- This skill is designed for pymatgen 2024.x and later. For the Materials Project API, use the `mp-api` package (separate from legacy `pymatgen.ext.matproj`).
+ - [Core classes](references/core_classes.md)
+ - [I/O formats, VASP, and Q-Chem](references/io_formats.md)
+ - [Analysis, symmetry, phase diagrams, bands, and DOS](references/analysis_modules.md)
+ - [Transformations and workflows](references/transformations_workflows.md)
+ - [Materials Project API, provenance, license, and limits](references/materials_project_api.md)
- Requirements:
- - Python 3.10 or higher
- - pymatgen >= 2023.x
- - mp-api (for Materials Project access)
+ ## Sources (verified 2026-07-23)
+ - [pymatgen 2026.5.4 on PyPI](https://pypi.org/project/pymatgen/)
+ - [pymatgen-core 2026.7.16 on PyPI](https://pypi.org/project/pymatgen-core/)
+ - [pymatgen API documentation](https://pymatgen.org/)
+ - [pymatgen changelog](https://pymatgen.org/CHANGES.html)
+ - [mp-api 0.46.4 on PyPI](https://pypi.org/project/mp-api/)
+ - [Materials Project API getting started](https://docs.materialsproject.org/downloading-data/using-the-api/getting-started)
+ - [Materials Project query guide](https://docs.materialsproject.org/downloading-data/using-the-api/querying-data)
+ - [Materials Project FAQ and computed-data caveats](https://docs.materialsproject.org/frequently-asked-questions)
+ - [Materials Project citation page](https://materialsproject.org/about/cite)
+ - [Official tutorial series endorsed by pymatgen](https://github.com/computron/pymatgen_tutorials)