Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Update pymatgen for current packages
Timothy Kassis0ece03a0c12a
diff --git a/skills/pymatgen/SKILL.md b/skills/pymatgen/SKILL.mdindex 182a5fb0..7fd966b2 100644--- a/skills/pymatgen/SKILL.md+++ b/skills/pymatgen/SKILL.md@@ -1,689 +1,409 @@---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 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.--## 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--## Quick Start Guide--### Installation+# pymatgen++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.++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.++## Verified snapshot (2026-07-23)++- `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.++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"+```++Direct pins do not freeze all transitive wheels. Preserve `uv.lock`, platform,+Python version, package versions, and artifact hashes.++## Required workflow++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.++## Core objects++Use the public convenience imports:```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)- )-```--## Core Capabilities--### 1. Structure Creation and Manipulation--Create structures using various methods and perform transformations.--**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++composition = Composition("LiFePO4", strict=True)+iron = Element("Fe")++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 scratch:**-```python-from pymatgen.core import Structure, Lattice--# 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)--# 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.+For direct CIF work, use the current parser method and inspect both warning+channels:-### 2. File Format Conversion--Convert between 100+ file formats with automatic format detection.--**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")-```--**Using the conversion script:**-```bash-# Single file conversion-python scripts/structure_converter.py POSCAR structure.cif+import warnings+from pymatgen.io.cif import CifParser++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:**```pythonfrom 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")+See [analysis modules](references/analysis_modules.md).-# 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")+## Conversion and parser/writer I/O- if e_above_hull > 0.001:- # Get decomposition- decomp = pd.get_decomposition(comp)- print("Decomposes to:", decomp)+Plan first; the planner does not open files or import pymatgen:-# Plot-plotter = PDPlotter(pd)-plotter.show()-```--**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+python scripts/io_conversion_plan.py \+ --input input.cif --input-format cif \+ --output POSCAR.new --output-format poscar \+ --periodic --coordinate-mode direct```-**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")-```+Then convert to a new path with explicit loss acknowledgement:-**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")--# 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,+tracked = TransformedStructure(structure.copy(), [])+tracked.append_transformation(SupercellTransformation([2, 2, 2]))+tracked.append_transformation(SubstitutionTransformation({"Na": "K"}))+derived = tracked.final_structure+history = tracked.history+```++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).++## Local phase diagrams++The bundled generator is offline and accepts only a strict JSON schema with+total eV per entry and provenance:++```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:..."}+ }+ ]}--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)--# 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'])}")--# 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).--### 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.+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.-### 8. Computational Workflow Setup+## Band structures, DOS, VASP, and Q-Chem-Set up calculations for various electronic structure codes.+Parse only the data needed:-**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")--# Band structure (non-self-consistent)-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")-```+from pymatgen.io.vasp import Vasprun-**Other codes:**-```python-# Gaussian-from pymatgen.io.gaussian import GaussianInput--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")+band_structure = run.get_band_structure(line_mode=True)+band_gap = band_structure.get_band_gap()+complete_dos = run.complete_dos```-**Reference:** See `references/io_formats.md` (Electronic Structure Code I/O section) and `references/transformations_workflows.md` for workflow examples.+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.-### 9. Advanced Analysis+Current Q-Chem interfaces are `pymatgen.io.qchem.inputs.QCInput` and+`pymatgen.io.qchem.outputs.QCOutput`:-**Diffraction patterns:**```python-from pymatgen.analysis.diffraction.xrd import XRDCalculator+from pymatgen.io.qchem.inputs import QCInput-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 ElasticTensor--# From 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 MagOrderingTransformation--# Enumerate magnetic orderings-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']+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/`)+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.-Executable Python scripts for common tasks:+## Materials Project: plan before network-- **`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.--## Common Workflows--### 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}")-```--### 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")--# 3. Band structure (non-self-consistent)-nscf = MPNonSCFSet(relaxed, mode="line")-nscf.write_input("./3_bandstructure")--# 4. Analysis-from pymatgen.io.vasp import Vasprun-vasprun = Vasprun("3_bandstructure/vasprun.xml")-bs = vasprun.get_band_structure()-bs.get_band_gap()+from mp_api.client import MPRester```-### Surface Energy Calculation--```python-# 1. Get bulk energy-bulk_vasprun = Vasprun("bulk/vasprun.xml")-bulk_E_per_atom = bulk_vasprun.final_energy / len(bulk)+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.-# 2. Generate and calculate slabs-slabgen = SlabGenerator(bulk, (1,1,1), 10, 15)-slab = slabgen.get_slabs()[0]+Dry-run planning is the default:-MPRelaxSet(slab).write_input("./slab_calc")--# 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 \+ --chemsys Li-Fe-O \+ --energy-above-hull 0 0.05 \+ --fields formula_pretty,energy_above_hull,band_gap,origins \+ --limit 25```-**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+Only `--execute` permits one bounded summary query and requires a new output:-### 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)--Convert units using `pymatgen.core.units` when needed.--## Integration 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)--## Troubleshooting--**Import errors**: Install missing dependencies```bash-uv pip install pymatgen[analysis,vis]-```+python scripts/mp_query.py \+ --material-id mp-149 \+ --fields formula_pretty,structure,origins,last_updated \+ --limit 1 --output mp-149.json --execute+```++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.++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).++## Bundled CLIs++All CLIs have dependency-free `--help`, lazy scientific imports, bounded JSON,+and no implicit network:++- `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.++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)-```--## 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--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`).--Requirements:-- Python 3.10 or higher-- pymatgen >= 2023.x-- mp-api (for Materials Project access)-+python scripts/artifact_manifest.py \+ --artifact input.cif --artifact analysis.json \+ --workflow "local symmetry sensitivity" --output manifest.json+```++## References++- [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)++## 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)diff --git a/skills/pymatgen/references/analysis_modules.md b/skills/pymatgen/references/analysis_modules.mdindex 73f1979c..213809ff 100644--- a/skills/pymatgen/references/analysis_modules.md+++ b/skills/pymatgen/references/analysis_modules.md@@ -1,530 +1,352 @@-# Pymatgen Analysis Modules Reference+# Analysis: tolerances, computed entries, bands, DOS, and model limits-This reference documents pymatgen's extensive analysis capabilities for materials characterization, property prediction, and computational analysis.+This reference targets `pymatgen==2026.5.4` with+`pymatgen-core==2026.7.16`. An analysis object returning a value does not+establish convergence, uncertainty, experimental agreement, or suitability of+the underlying model.-## Phase Diagrams and Thermodynamics--### Phase Diagram Construction+## Symmetry```python-from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter-from pymatgen.entries.computed_entries import ComputedEntry--# Create entries (composition and total energy)-entries = [- ComputedEntry("Fe", -8.4),- ComputedEntry("O2", -4.9),- ComputedEntry("FeO", -6.7),- ComputedEntry("Fe2O3", -8.3),- ComputedEntry("Fe3O4", -9.1),-]--# Build phase diagram-pd = PhaseDiagram(entries)--# Get stable entries-stable_entries = pd.stable_entries--# Get energy above hull (stability)-entry_to_test = ComputedEntry("Fe2O3", -8.0)-energy_above_hull = pd.get_e_above_hull(entry_to_test)--# Get decomposition products-decomp = pd.get_decomposition(entry_to_test.composition)-# Returns: {entry1: fraction1, entry2: fraction2, ...}+from pymatgen.symmetry.analyzer import SpacegroupAnalyzer-# Get equilibrium reaction energy-rxn_energy = pd.get_equilibrium_reaction_energy(entry_to_test)+analyzer = SpacegroupAnalyzer(+ structure,+ symprec=0.01, # Å+ angle_tolerance=5.0, # degrees+)-# Plot phase diagram-plotter = PDPlotter(pd)-plotter.show()-plotter.write_image("phase_diagram.png")+result = {+ "symbol": analyzer.get_space_group_symbol(),+ "number": analyzer.get_space_group_number(),+ "crystal_system": str(analyzer.get_crystal_system()),+ "point_group": analyzer.get_point_group_symbol(),+ "operation_count": len(analyzer.get_symmetry_operations()),+}+symmetrized = analyzer.get_symmetrized_structure()+equivalent_indices = symmetrized.equivalent_indices+wyckoff_symbols = symmetrized.wyckoff_symbols```-### Chemical Potential Diagrams+The documented pymatgen default is `symprec=0.01 Å`; a looser value such as+`0.1 Å` is often used for relaxed structures and by the Materials Project+pipeline. Results can change with:-```python-from pymatgen.analysis.phase_diagram import ChemicalPotentialDiagram+- coordinate precision and relaxation noise+- occupancy/disorder model+- oxidation/spin/site properties used or ignored+- primitive/conventional representation+- `symprec`, `angle_tolerance`, and spglib version-# Create chemical potential diagram-cpd = ChemicalPotentialDiagram(entries, limits={"O": (-10, 0)})+Always sweep justified tolerances and report the entire sensitivity grid. Do+not choose a tolerance solely because it gives a desired group.-# Get domains (stability regions)-domains = cpd.domains-```--### Pourbaix Diagrams--Electrochemical phase diagrams with pH and potential axes.+Standardized or primitive structures are new representations:```python-from pymatgen.analysis.pourbaix_diagram import PourbaixDiagram, PourbaixPlotter-from pymatgen.entries.computed_entries import ComputedEntry--# Create entries with corrections for aqueous species-entries = [...] # Include solids and ions--# Build Pourbaix diagram-pb = PourbaixDiagram(entries)--# Get stable entry at specific pH and potential-stable_entry = pb.get_stable_entry(pH=7, V=0)--# Plot-plotter = PourbaixPlotter(pb)-plotter.show()+conventional = analyzer.get_conventional_standard_structure(+ keep_site_properties=False+)+primitive = analyzer.get_primitive_standard_structure(+ keep_site_properties=False+)```-## Structure Analysis+Site properties can be lost or propagated without symmetry-aware adjustment.+Preserve the parent and compare composition, volume per atom, magnetic order,+and property semantics.-### Structure Matching and Comparison+## Structure matching```pythonfrom pymatgen.analysis.structure_matcher import StructureMatcher-matcher = StructureMatcher()--# Check if structures match-is_match = matcher.fit(struct1, struct2)--# Get mapping between structures-mapping = matcher.get_mapping(struct1, struct2)--# Group similar structures-grouped = matcher.group_structures([struct1, struct2, struct3, ...])+matcher = StructureMatcher(+ ltol=0.2,+ stol=0.3,+ angle_tol=5,+ primitive_cell=True,+ scale=True,+)+matches = matcher.fit(first, second)```-### Ewald Summation+Record every tolerance and option. A match is equivalence under the chosen+algorithm, reductions, scaling, and species comparator—not identity of files,+provenance, defects, magnetic states, or experimental phases.-Calculate electrostatic energy of ionic structures.+## Local environments```python-from pymatgen.analysis.ewald import EwaldSummation--ewald = EwaldSummation(struct)-total_energy = ewald.total_energy # In eV-forces = ewald.forces # Forces on each site-```--### Symmetry Analysis--```python-from pymatgen.symmetry.analyzer import SpacegroupAnalyzer--sga = SpacegroupAnalyzer(struct)--# Get space group information-spacegroup_symbol = sga.get_space_group_symbol() # e.g., "Fm-3m"-spacegroup_number = sga.get_space_group_number() # e.g., 225-crystal_system = sga.get_crystal_system() # e.g., "cubic"+from pymatgen.analysis.local_env import CrystalNN, VoronoiNN-# Get symmetrized structure-sym_struct = sga.get_symmetrized_structure()-equivalent_sites = sym_struct.equivalent_sites+crystal_nn = CrystalNN()+neighbors = crystal_nn.get_nn_info(structure, 0)-# Get conventional/primitive cells-conventional = sga.get_conventional_standard_structure()-primitive = sga.get_primitive_standard_structure()--# Get symmetry operations-symmetry_ops = sga.get_symmetry_operations()+voronoi_nn = VoronoiNN()+voronoi_neighbors = voronoi_nn.get_nn_info(structure, 0)```-## Local Environment Analysis+Coordination depends on the method, radii/oxidation information, weights,+cutoffs, disorder, and geometry. Preserve:-### Coordination Environment+- algorithm and pymatgen version+- all constructor settings+- oxidation-state decoration+- site index/label mapping+- warnings and failures+- whether weighted or integer coordination was reported-```python-from pymatgen.analysis.local_env import (- VoronoiNN, # Voronoi tessellation- CrystalNN, # Crystal-based- MinimumDistanceNN, # Distance cutoff- BrunnerNN_real, # Brunner method-)+Bound the number of sites and neighbors emitted. Cross-check model-sensitive+conclusions with more than one justified definition.-# Voronoi nearest neighbors-voronoi = VoronoiNN()-neighbors = voronoi.get_nn_info(struct, n=0) # Neighbors of site 0+## Phase diagrams-# CrystalNN (recommended for most cases)-crystalnn = CrystalNN()-neighbors = crystalnn.get_nn_info(struct, n=0)--# Analyze all sites-for i, site in enumerate(struct):- neighbors = voronoi.get_nn_info(struct, i)- coordination_number = len(neighbors)- print(f"Site {i} ({site.species_string}): CN = {coordination_number}")-```--### Coordination Geometry (ChemEnv)--Detailed coordination environment identification.+An `Entry` contains a composition and a total energy:```python-from pymatgen.analysis.chemenv.coordination_environments.coordination_geometry_finder import LocalGeometryFinder-from pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies import SimplestChemenvStrategy--lgf = LocalGeometryFinder()-lgf.setup_structure(struct)--# Get coordination environment for site-se = lgf.compute_structure_environments(only_indices=[0])-strategy = SimplestChemenvStrategy()-lse = strategy.get_site_coordination_environment(se[0])+from pymatgen.analysis.phase_diagram import PhaseDiagram+from pymatgen.entries.computed_entries import ComputedEntry-print(f"Coordination: {lse}")+entries = [+ ComputedEntry("Li", -1.0, entry_id="local-Li"),+ ComputedEntry("O2", -2.0, entry_id="local-O2"),+ ComputedEntry("Li2O", -4.0, entry_id="local-Li2O"),+]+diagram = PhaseDiagram(entries)++for entry in entries:+ print(+ entry.entry_id,+ diagram.get_form_energy_per_atom(entry),+ diagram.get_e_above_hull(entry),+ )```-### Bond Valence Sum+`ComputedEntry.energy` is total eV for the represented composition, not+eV/atom. `energy_per_atom`, formation energy, and hull distance are normalized+values.-```python-from pymatgen.analysis.bond_valence import BVAnalyzer+### Comparability gate-bva = BVAnalyzer()+Before constructing a hull, verify that entries share a compatible:-# Calculate oxidation states-valences = bva.get_valences(struct)+- functional and correction/mixing scheme+- pseudopotential family and valence configuration+- magnetic, spin, and SOC treatment+- reference-state convention+- numerical convergence level+- temperature/pressure model-# Get structure with oxidation states-struct_with_oxi = bva.get_oxi_state_decorated_structure(struct)-```+Include elemental endpoints and all relevant competing phases. Missing phases+can make unstable entries appear stable. Duplicate compositions are allowed as+polymorphs only when their energies are comparable and provenance is distinct.-## Surface and Interface Analysis+`diagram.stable_entries` means on the computed zero-temperature convex hull for+that exact entry set. It is not experimental stability or synthesizability.-### Surface (Slab) Generation+### Decomposition```python-from pymatgen.core.surface import SlabGenerator, generate_all_slabs--# Generate slabs for a specific Miller index-slabgen = SlabGenerator(- struct,- miller_index=(1, 1, 1),- min_slab_size=10.0, # Minimum slab thickness (Å)- min_vacuum_size=10.0, # Minimum vacuum thickness (Å)- center_slab=True-)+from pymatgen.core import Composition-slabs = slabgen.get_slabs()--# Generate all slabs up to a Miller index-all_slabs = generate_all_slabs(- struct,- max_index=2,- min_slab_size=10.0,- min_vacuum_size=10.0-)+target = Composition("Li2O", strict=True)+decomposition = diagram.get_decomposition(target)```-### Wulff Shape Construction+For an existing entry, use `get_e_above_hull(entry)`. A bare composition has no+candidate energy, so it has a hull decomposition but no intrinsic energy above+hull.-```python-from pymatgen.analysis.wulff import WulffShape--# Define surface energies (J/m²)-surface_energies = {- (1, 0, 0): 1.0,- (1, 1, 0): 1.1,- (1, 1, 1): 0.9,-}--wulff = WulffShape(struct.lattice, surface_energies, symm_reduce=True)--# Get effective radius and surface area-effective_radius = wulff.effective_radius-surface_area = wulff.surface_area-volume = wulff.volume--# Visualize-wulff.show()-```--### Adsorption Site Finding+### Plotting```python-from pymatgen.analysis.adsorption import AdsorbateSiteFinder--asf = AdsorbateSiteFinder(slab)--# Find adsorption sites-ads_sites = asf.find_adsorption_sites()-# Returns dictionary: {"ontop": [...], "bridge": [...], "hollow": [...]}+from pymatgen.analysis.phase_diagram import PDPlotter-# Generate structures with adsorbates-from pymatgen.core import Molecule-adsorbate = Molecule("O", [[0, 0, 0]])--ads_structs = asf.generate_adsorption_structures(- adsorbate,- repeat=[2, 2, 1], # Supercell to reduce adsorbate coverage-)+plotter = PDPlotter(diagram, show_unstable=0.2)+plotter.write_image("phase.new.svg", image_format="svg")```-### Interface Construction--```python-from pymatgen.analysis.interfaces.coherent_interfaces import CoherentInterfaceBuilder--# Build interface between two materials-builder = CoherentInterfaceBuilder(- substrate_structure=substrate,- film_structure=film,- substrate_miller=(0, 0, 1),- film_miller=(1, 1, 1),-)+Plot to a new path, bound unstable points and output size, and preserve the+machine-readable entry table. Plotting backends and image export can introduce+optional dependencies.-interfaces = builder.get_interfaces()-```+## Chemical-potential and Pourbaix analyses-## Magnetism+`ChemicalPotentialDiagram` and `PourbaixDiagram` add assumptions beyond a+composition hull. Record reference states, open species, aqueous ion data,+concentrations, pH, electrochemical potential, temperature, corrections, and+solvent convention. Do not reuse a solid-state entry set as a valid aqueous+thermodynamic model without the required transformations and references.-### Magnetic Structure Analysis+## Electronic band structures```python-from pymatgen.analysis.magnetism import CollinearMagneticStructureAnalyzer--analyzer = CollinearMagneticStructureAnalyzer(struct)+from pymatgen.io.vasp import Vasprun-# Get magnetic ordering-ordering = analyzer.ordering # e.g., "FM" (ferromagnetic), "AFM", "FiM"+run = Vasprun(+ "vasprun.xml",+ parse_dos=False,+ parse_eigen=True,+ parse_projected_eigen=False,+ parse_potcar_file=False,+)+bands = run.get_band_structure(line_mode=True)-# Get magnetic space group-mag_space_group = analyzer.get_structure_with_spin().get_space_group_info()+gap = bands.get_band_gap()+vbm = bands.get_vbm()+cbm = bands.get_cbm()+metal = bands.is_metal()```-### Magnetic Ordering Enumeration+Report:-```python-from pymatgen.transformations.advanced_transformations import MagOrderingTransformation+- source calculation and convergence status+- structure checksum+- functional, pseudopotentials, DFT+U, spin, SOC+- k-point mesh/path and line-mode reconstruction+- Fermi-energy convention and any override+- occupation/smearing settings+- direct/indirect criterion and numerical tolerance-# Enumerate possible magnetic orderings-mag_trans = MagOrderingTransformation({"Fe": 5.0}) # Magnetic moment in μB-transformed_structures = mag_trans.apply_transformation(struct, return_ranked_list=True)-```+A DFT band gap is method-dependent. Materials Project documents that its PBE+band gaps are systematically underestimated.-## Electronic Structure Analysis+`BSPlotter` can plot a `BandStructureSymmLine`; plotting does not validate the+k-path. High-symmetry paths depend on crystallographic setting and magnetic+primitive-cell assumptions.-### Band Structure Analysis+## Density of states```python-from pymatgen.electronic_structure.bandstructure import BandStructureSymmLine-from pymatgen.electronic_structure.plotter import BSPlotter--# Read band structure from VASP calculationfrom pymatgen.io.vasp import Vasprun-vasprun = Vasprun("vasprun.xml")-bs = vasprun.get_band_structure()--# Get band gap-band_gap = bs.get_band_gap()-# Returns: {'energy': gap_value, 'direct': True/False, 'transition': '...'}-# Check if metal-is_metal = bs.is_metal()--# Get VBM and CBM-vbm = bs.get_vbm()-cbm = bs.get_cbm()--# Plot band structure-plotter = BSPlotter(bs)-plotter.show()-plotter.save_plot("band_structure.png")+run = Vasprun(+ "vasprun.xml",+ parse_dos=True,+ parse_eigen=False,+ parse_projected_eigen=False,+ parse_potcar_file=False,+)+dos = run.complete_dos+element_dos = dos.get_element_dos()+site_dos = dos.get_site_dos(run.final_structure[0])+orbital_dos = dos.get_spd_dos()```-### Density of States (DOS)--```python-from pymatgen.electronic_structure.dos import CompleteDos-from pymatgen.electronic_structure.plotter import DosPlotter+Check:-# Read DOS from VASP calculation-vasprun = Vasprun("vasprun.xml")-dos = vasprun.complete_dos+- energy grid and reference/Fermi level+- density units and normalization+- spin channels and SOC+- smearing and integration method+- projection basis and completeness+- consistency between DOS sites and final structure-# Get total DOS-total_dos = dos.densities+Do not compare integrated/projected DOS across calculations until these+conventions match.-# Get projected DOS-pdos = dos.get_element_dos() # By element-site_dos = dos.get_site_dos(struct[0]) # For specific site-spd_dos = dos.get_spd_dos() # By orbital (s, p, d)+## VASP parse cost-# Plot DOS-plotter = DosPlotter()-plotter.add_dos("Total", dos)-plotter.show()-```--### Fermi Surface--```python-from pymatgen.electronic_structure.boltztrap2 import BoltztrapRunner--runner = BoltztrapRunner(struct, nelec=n_electrons)-runner.run()--# Get transport properties at different temperatures-results = runner.get_results()-```+`Vasprun(parse_projected_eigen=True)` can require extreme time and memory.+`BSVasprun` is optimized for eigenvalue-focused band-structure parsing. Large+XML/HDF5/volumetric files need file-size, array-size, site/k-point/band, memory,+and wall-time bounds.## Diffraction-### X-ray Diffraction (XRD)-```pythonfrom pymatgen.analysis.diffraction.xrd import XRDCalculator-xrd = XRDCalculator()--pattern = xrd.get_pattern(struct, two_theta_range=(0, 90))--# Get peak data-for peak in pattern.hkls:- print(f"2θ = {peak['2theta']:.2f}°, hkl = {peak['hkl']}, I = {peak['intensity']:.1f}")--# Plot pattern-pattern.plot()-```--### Neutron Diffraction--```python-from pymatgen.analysis.diffraction.neutron import NDCalculator--nd = NDCalculator()-pattern = nd.get_pattern(struct)-```--## Elasticity and Mechanical Properties--```python-from pymatgen.analysis.elasticity import ElasticTensor, Stress, Strain--# Create elastic tensor from matrix-elastic_tensor = ElasticTensor([[...]]) # 6x6 or 3x3x3x3 matrix--# Get mechanical properties-bulk_modulus = elastic_tensor.k_voigt # Voigt bulk modulus (GPa)-shear_modulus = elastic_tensor.g_voigt # Shear modulus (GPa)-youngs_modulus = elastic_tensor.y_mod # Young's modulus (GPa)--# Apply strain-strain = Strain([[0.01, 0, 0], [0, 0, 0], [0, 0, 0]])-stress = elastic_tensor.calculate_stress(strain)-```--## Reaction Analysis--### Reaction Computation--```python-from pymatgen.analysis.reaction_calculator import ComputedReaction--reactants = [ComputedEntry("Fe", -8.4), ComputedEntry("O2", -4.9)]-products = [ComputedEntry("Fe2O3", -8.3)]--rxn = ComputedReaction(reactants, products)--# Get balanced equation-balanced_rxn = rxn.normalized_repr # e.g., "2 Fe + 1.5 O2 -> Fe2O3"--# Get reaction energy-energy = rxn.calculated_reaction_energy # eV per formula unit-```--### Reaction Path Finding--```python-from pymatgen.analysis.path_finder import ChgcarPotential, NEBPathfinder--# Read charge density-chgcar_potential = ChgcarPotential.from_file("CHGCAR")--# Find diffusion path-neb_path = NEBPathfinder(- start_struct,- end_struct,- relax_sites=[i for i in range(len(start_struct))],- v=chgcar_potential+calculator = XRDCalculator(wavelength="CuKa")+pattern = calculator.get_pattern(+ structure,+ scaled=True,+ two_theta_range=(5, 90),)-images = neb_path.images # Interpolated structures for NEB+for two_theta, intensity, hkls in zip(+ pattern.x,+ pattern.y,+ pattern.hkls,+ strict=True,+):+ print(two_theta, intensity, hkls)```-## Molecular Analysis+Peak positions/intensities depend on radiation, occupancies, structure,+instrumental broadening, preferred orientation, temperature/displacement, and+the ideal-powder model. A simulated pattern is not a phase-identification+result by itself.-### Bond Analysis+## Surfaces, slabs, and Wulff shapes```python-# Get covalent bonds-bonds = mol.get_covalent_bonds()+from pymatgen.core.surface import SlabGenerator-for bond in bonds:- print(f"{bond.site1.species_string} - {bond.site2.species_string}: {bond.length:.2f} Å")-```--### Molecule Graph--```python-from pymatgen.analysis.graphs import MoleculeGraph-from pymatgen.analysis.local_env import OpenBabelNN--# Build molecule graph-mg = MoleculeGraph.with_local_env_strategy(mol, OpenBabelNN())--# Get fragments-fragments = mg.get_disconnected_fragments()--# Find rings-rings = mg.find_rings()+generator = SlabGenerator(+ structure,+ miller_index=(1, 1, 1),+ min_slab_size=12.0,+ min_vacuum_size=15.0,+ center_slab=True,+ in_unit_planes=False,+)+slabs = generator.get_slabs()```-## Spectroscopy+Record bulk parent, Miller-index convention, slab/vacuum units, termination,+symmetrization, dipole correction, in-plane cell, fixed layers, and candidate+limit. Slab thickness and vacuum are convergence parameters, not universal+constants.-### X-ray Absorption Spectroscopy (XAS)+Current `WulffShape` takes parallel Miller-index and surface-energy sequences:```python-from pymatgen.analysis.xas.spectrum import XAS--# Read XAS spectrum-xas = XAS.from_file("xas.dat")+from pymatgen.analysis.wulff import WulffShape-# Normalize and process-xas.normalize()+wulff = WulffShape(+ structure.lattice,+ [(1, 0, 0), (1, 1, 0), (1, 1, 1)],+ [1.0, 1.1, 0.9], # one consistent energy unit per area+)```-## Additional Analysis Tools+Surface energies must share composition/chemical-potential, slab, functional,+and area conventions. Report their unit explicitly.-### Grain Boundaries+## Adsorption-```python-from pymatgen.analysis.gb.grain import GrainBoundaryGenerator+`AdsorbateSiteFinder` produces geometric candidates, not adsorption energies or+preferred sites. Bound generated structures and preserve slab termination,+adsorbate geometry/charge/spin, coverage, orientation, and parent mapping.-gb_gen = GrainBoundaryGenerator(struct)-gb_structures = gb_gen.generate_grain_boundaries(- rotation_axis=[0, 0, 1],- rotation_angle=36.87, # degrees-)-```+## Elasticity and other tensors-### Prototypes and Structure Matching+`pymatgen.analysis.elasticity` represents strain, stress, and elastic tensors.+Verify Voigt index convention, stress sign, units (typically GPa for reported+moduli), reference frame, crystal symmetry, finite-strain magnitude, and fit+quality. Mechanical-stability criteria depend on crystal class and conditions.-```python-from pymatgen.analysis.prototypes import AflowPrototypeMatcher+## Analysis report checklist-matcher = AflowPrototypeMatcher()-prototype = matcher.get_prototypes(struct)-```+- source checksum and parser warnings+- exact package versions+- units and normalization+- all tolerances/model parameters+- bounded input/output sizes+- disorder and oxidation-state handling+- convergence and uncertainty evidence+- method-specific caveats+- no claim of experimental truth from computed output alone-## Best Practices+## Sources (verified 2026-07-23)-1. **Start simple**: Use basic analysis before advanced methods-2. **Validate results**: Cross-check analysis with multiple methods-3. **Consider symmetry**: Use `SpacegroupAnalyzer` to reduce computational cost-4. **Check convergence**: Ensure input structures are well-converged-5. **Use appropriate methods**: Different analyses have different accuracy/speed tradeoffs-6. **Visualize results**: Use built-in plotters for quick validation-7. **Save intermediate results**: Complex analyses can be time-consuming+- [pymatgen analysis API](https://pymatgen.org/pymatgen.analysis.html)+- [pymatgen symmetry API](https://pymatgen.org/pymatgen.symmetry.html)+- [pymatgen electronic-structure API](https://pymatgen.org/pymatgen.electronic_structure.html)+- [pymatgen VASP API](https://pymatgen.org/pymatgen.io.vasp.html)+- [pymatgen usage guide](https://pymatgen.org/usage.html)+- [pymatgen changelog](https://pymatgen.org/CHANGES.html)+- [Materials Project electronic-structure methodology](https://docs.materialsproject.org/methodology/materials-methodology/electronic-structure)+- [Materials Project computed-data FAQ](https://docs.materialsproject.org/frequently-asked-questions)diff --git a/skills/pymatgen/references/core_classes.md b/skills/pymatgen/references/core_classes.mdindex 8758c461..16834b7c 100644--- a/skills/pymatgen/references/core_classes.md+++ b/skills/pymatgen/references/core_classes.md@@ -1,318 +1,290 @@-# Pymatgen Core Classes Reference+# Core classes: explicit chemistry, coordinates, and periodicity-This reference documents the fundamental classes in `pymatgen.core` that form the foundation for materials analysis.+This reference targets the verified `pymatgen==2026.5.4` wrapper with+`pymatgen-core==2026.7.16`. Core objects now ship from `pymatgen-core` but keep+the public `pymatgen.core` namespace.-## Architecture Principles+## Units and representation-Pymatgen follows an object-oriented design where elements, sites, and structures are represented as objects. The framework emphasizes periodic boundary conditions for crystal representation while maintaining flexibility for molecular systems.+Pymatgen does not make every quantity "atomic units." Common contracts include:-**Unit Conventions**: All units in pymatgen are typically assumed to be in atomic units:-- Lengths: angstroms (Å)-- Energies: electronvolts (eV)-- Angles: degrees+- lattice vectors and Cartesian coordinates: Å+- lattice angles: degrees+- structure volume: ų+- density: g/cm³+- composition weight: amu for the represented composition+- electronic and entry energies: usually eV; phase-diagram normalized values:+ eV/atom-## Element and Periodic Table+Read the specific method contract before combining quantities. Record units in+every artifact.-### Element-Represents periodic table elements with comprehensive properties.+`Structure` is periodic and owns a `Lattice`; `Molecule` is non-periodic.+Structure coordinates are fractional by default. Molecule coordinates are+Cartesian. Never infer which object or coordinate mode the user intended.-**Creation methods:**-```python-from pymatgen.core import Element--# Create from symbol-si = Element("Si")-# Create from atomic number-si = Element.from_Z(14)-# Create from name-si = Element.from_name("silicon")-```--**Key properties:**-- `atomic_mass`: Atomic mass in amu-- `atomic_radius`: Atomic radius in angstroms-- `electronegativity`: Pauling electronegativity-- `ionization_energy`: First ionization energy in eV-- `common_oxidation_states`: List of common oxidation states-- `is_metal`, `is_halogen`, `is_noble_gas`, etc.: Boolean properties-- `X`: Element symbol as string--### Species-Extends Element for charged ions and specific oxidation states.+## Element and Species```python-from pymatgen.core import Species+from pymatgen.core import DummySpecies, Element, Species-# Create an Fe2+ ion-fe2 = Species("Fe", 2)-# Or with explicit sign-fe2 = Species("Fe", +2)+iron = Element("Fe")+silicon = Element.from_Z(14)+oxygen = Element.from_name("oxygen")+fe2 = Species("Fe", oxidation_state=2)+vacancy_label = DummySpecies("X")```-### DummySpecies-Placeholder atoms for special structural representations (e.g., vacancies).+Important distinctions:-```python-from pymatgen.core import DummySpecies+- `Element.symbol` is the chemical symbol.+- `Element.Z` is atomic number.+- `Element.X` is Pauling electronegativity, not the symbol.+- Elemental properties can be missing or uncertain; do not replace missing+ values with zero.+- `Species` adds oxidation state and optional properties. Oxidation state is+ formal chemical annotation, not an automatically validated charge model.+- A dummy species is a modeling label, not a physical atom.-vacancy = DummySpecies("X")-```+Current API documentation also exposes predicates and data such as+`is_metal`, `is_noble_gas`, `atomic_mass`, oxidation-state sets, and electronic+configuration. Check for `None`/missing values and retain property provenance.## Composition-Represents chemical formulas and compositions, enabling chemical analysis and manipulation.+Use strict parsing at external boundaries:-### Creation```pythonfrom pymatgen.core import Composition-# From string formula-comp = Composition("Fe2O3")-# From dictionary-comp = Composition({"Fe": 2, "O": 3})-# From weight dictionary-comp = Composition.from_weight_dict({"Fe": 111.69, "O": 48.00})+composition = Composition("LiFePO4", strict=True)+formula = composition.formula+reduced = composition.reduced_formula+chemical_system = composition.chemical_system+mass_amu = float(composition.weight)```-### Key methods-- `get_reduced_formula_and_factor()`: Returns reduced formula and multiplication factor-- `oxi_state_guesses()`: Attempts to determine oxidation states-- `replace(replacements_dict)`: Replace elements-- `add_charges_from_oxi_state_guesses()`: Infer and add oxidation states-- `is_element`: Check if composition is a single element--### Key properties-- `weight`: Molecular weight-- `reduced_formula`: Reduced chemical formula-- `hill_formula`: Formula in Hill notation (C, H, then alphabetical)-- `num_atoms`: Total number of atoms-- `chemical_system`: Alphabetically sorted elements (e.g., "Fe-O")-- `element_composition`: Dictionary of element to amount+Construction from a mapping is explicit:-## Lattice+```python+composition = Composition({"Fe": 2, "O": 3}, strict=True)+```-Defines unit cell geometry for crystal structures.+Safety rules:++1. Bound formula length before parsing.+2. Reject duplicate JSON keys, non-finite values, and non-positive amounts in+ external mappings.+3. Keep full and reduced formulas distinct. Reduction loses the integer scale.+4. A composition is not a structure, phase, oxidation-state assignment, or+ proof that a compound exists.+5. `oxi_state_guesses()` is heuristic and can be combinatorial. Call it only+ after explicit user approval and bound elements, formula size, runtime, and+ returned guesses.+6. Do not mix `Element` and oxidized `Species` keys without intentionally+ defining how charge decoration should behave.++The bundled validator does not guess by default:++```bash+python scripts/composition_structure_validator.py composition "Fe2O3"+python scripts/composition_structure_validator.py composition "Fe2O3" \+ --guess-oxidation-states+```++## Lattice-### Creation```pythonfrom pymatgen.core import Lattice-# From lattice parameters-lattice = Lattice.from_parameters(a=3.84, b=3.84, c=3.84,- alpha=120, beta=90, gamma=60)--# From matrix (row vectors are lattice vectors)-lattice = Lattice([[3.84, 0, 0],- [0, 3.84, 0],- [0, 0, 3.84]])--# Cubic lattice-lattice = Lattice.cubic(3.84)-# Hexagonal lattice-lattice = Lattice.hexagonal(a=2.95, c=4.68)+cubic = Lattice.cubic(5.64)+triclinic = Lattice.from_parameters(+ a=4.0,+ b=5.0,+ c=6.0,+ alpha=80,+ beta=90,+ gamma=100,+)+matrix_lattice = Lattice(+ [+ [4.0, 0.0, 0.0],+ [0.5, 5.0, 0.0],+ [0.2, 0.3, 6.0],+ ],+ pbc=(True, True, True),+)```-### Key methods-- `get_niggli_reduced_lattice()`: Returns Niggli-reduced lattice-- `get_distance_and_image(frac_coords1, frac_coords2)`: Distance between fractional coordinates with periodic boundary conditions-- `get_all_distances(frac_coords1, frac_coords2)`: Distances including periodic images+The matrix rows are lattice vectors. Preserve:-### Key properties-- `volume`: Volume of the unit cell (ų)-- `abc`: Lattice parameters (a, b, c) as tuple-- `angles`: Lattice angles (alpha, beta, gamma) as tuple-- `matrix`: 3x3 matrix of lattice vectors-- `reciprocal_lattice`: Reciprocal lattice object-- `is_orthogonal`: Whether lattice vectors are orthogonal+- matrix and `(a, b, c)`+- `(alpha, beta, gamma)`+- determinant/volume and handedness+- periodic-boundary-condition tuple+- whether the cell was reduced, standardized, strained, or transformed-## Sites+Niggli/LLL reduction and crystallographic standardization can change the cell+basis and site coordinates without changing intended periodic geometry. They+still produce new representations and require provenance.-### Site-Represents an atomic position in non-periodic systems.+## Structure and IStructure-```python-from pymatgen.core import Site+The verified constructor includes explicit safety-relevant switches:-site = Site("Si", [0.0, 0.0, 0.0]) # Species and Cartesian coordinates+```python+from pymatgen.core import Lattice, Structure++structure = Structure(+ lattice=Lattice.cubic(5.64),+ species=["Na", "Cl"],+ coords=[[0, 0, 0], [0.5, 0.5, 0.5]],+ coords_are_cartesian=False,+ validate_proximity=True,+ to_unit_cell=False,+)```-### PeriodicSite-Represents an atomic position in a periodic lattice with fractional coordinates.+`Structure` is mutable. `IStructure` is immutable/hashable. Prefer:```python-from pymatgen.core import PeriodicSite--site = PeriodicSite("Si", [0.5, 0.5, 0.5], lattice) # Species, fractional coords, lattice+original = Structure.from_file("input.cif", primitive=False, sort=False)+derived = original.copy()+derived.make_supercell([2, 2, 2])```-**Key methods:**-- `distance(other_site)`: Distance to another site-- `is_periodic_image(other_site)`: Check if sites are periodic images+Do not mutate `original` in a provenance-sensitive workflow.-**Key properties:**-- `species`: Species or element at the site-- `coords`: Cartesian coordinates-- `frac_coords`: Fractional coordinates (for PeriodicSite)-- `x`, `y`, `z`: Individual Cartesian coordinates+### Disorder and occupancy-## Structure+Each periodic site's `species` is a composition-like mapping. An ordered site+has one species with occupancy 1. A disordered site can contain multiple+species and fractional occupancies.-Represents a crystal structure as a collection of periodic sites. `Structure` is mutable, while `IStructure` is immutable.--### Creation```python-from pymatgen.core import Structure, Lattice--# From scratch-coords = [[0, 0, 0], [0.75, 0.5, 0.75]]-lattice = Lattice.from_parameters(a=3.84, b=3.84, c=3.84,- alpha=120, beta=90, gamma=60)-struct = Structure(lattice, ["Si", "Si"], coords)--# From file (automatic format detection)-struct = Structure.from_file("POSCAR")-struct = Structure.from_file("structure.cif")--# From spacegroup-struct = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.5),- ["Si"], [[0, 0, 0]])+for index, site in enumerate(structure):+ occupancy_sum = sum(float(value) for value in site.species.values())+ print(index, site.species, occupancy_sum)```-### File I/O-```python-# Write to file (format inferred from extension)-struct.to(filename="output.cif")-struct.to(filename="POSCAR")-struct.to(filename="structure.xyz")--# Get string representation-cif_string = struct.to(fmt="cif")-poscar_string = struct.to(fmt="poscar")-```+Before downstream analysis:-### Key methods--**Structure modification:**-- `append(species, coords)`: Add a site-- `insert(i, species, coords)`: Insert site at index-- `remove_sites(indices)`: Remove sites by index-- `replace(i, species)`: Replace species at index-- `apply_strain(strain)`: Apply strain to structure-- `perturb(distance)`: Randomly perturb atomic positions-- `make_supercell(scaling_matrix)`: Create supercell-- `get_primitive_structure()`: Get primitive cell--**Analysis:**-- `get_distance(i, j)`: Distance between sites i and j-- `get_neighbors(site, r)`: Get neighbors within radius r-- `get_all_neighbors(r)`: Get all neighbors for all sites-- `get_space_group_info()`: Get space group information-- `matches(other_struct)`: Check if structures match--**Interpolation:**-- `interpolate(end_structure, nimages)`: Interpolate between structures--### Key properties-- `lattice`: Lattice object-- `species`: List of species at each site-- `sites`: List of PeriodicSite objects-- `num_sites`: Number of sites-- `volume`: Volume of the structure-- `density`: Density in g/cm³-- `composition`: Composition object-- `formula`: Chemical formula-- `distance_matrix`: Matrix of pairwise distances--## Molecule--Represents non-periodic collections of atoms. `Molecule` is mutable, while `IMolecule` is immutable.--### Creation-```python-from pymatgen.core import Molecule+- report `structure.is_ordered`+- reject non-positive or overfull occupancy unless an explicitly documented+ parser tolerance explains a tiny rounding deviation+- preserve vacancy conventions and oxidation-state decoration+- check whether the target method supports disorder-# From scratch-coords = [[0.00, 0.00, 0.00],- [0.00, 0.00, 1.08]]-mol = Molecule(["C", "O"], coords)+Ordering a disordered structure changes the model and may create many+candidates. It is never a format cleanup.-# From file-mol = Molecule.from_file("molecule.xyz")-mol = Molecule.from_file("molecule.mol")-```+### Coordinate safety-### Key methods-- `get_covalent_bonds()`: Returns bonds based on covalent radii-- `get_neighbors(site, r)`: Get neighbors within radius-- `get_zmatrix()`: Get Z-matrix representation-- `get_distance(i, j)`: Distance between sites-- `get_centered_molecule()`: Center molecule at origin+`site.frac_coords` and `site.coords` are fractional and Cartesian,+respectively. Fractional coordinates outside `[0, 1)` can be valid periodic+images; wrapping them is a transformation, not an automatic fix.-### Key properties-- `species`: List of species-- `sites`: List of Site objects-- `num_sites`: Number of atoms-- `charge`: Total charge of molecule-- `spin_multiplicity`: Spin multiplicity-- `center_of_mass`: Center of mass coordinates+Record whether `to_unit_cell`, sorting, merging, primitive reduction, or+standardization occurred. Check minimum periodic distances under a site-count+bound; an all-pairs matrix is quadratic.-## Serialization+### Oxidation states-All core objects implement `as_dict()` and `from_dict()` methods for robust JSON/YAML persistence.+Oxidation states can be attached to species:```python-# Serialize to dictionary-struct_dict = struct.as_dict()--# Write to JSON-import json-with open("structure.json", "w") as f:- json.dump(struct_dict, f)--# Read from JSON-with open("structure.json", "r") as f:- struct_dict = json.load(f)- struct = Structure.from_dict(struct_dict)+decorated = structure.copy()+decorated.add_oxidation_state_by_element({"Na": 1, "Cl": -1})```-This approach addresses limitations of Python pickling and maintains compatibility across pymatgen versions.+This mutates the copied structure. Preserve the undecorated parent, mapping,+method, and any charge-balance assumptions. `add_oxidation_state_by_guess()` is+heuristic; do not invoke it implicitly.++### Common methods-## Additional Core Classes+Current public operations include:-### CovalentBond-Represents bonds in molecules.+- `Structure.from_file(path, primitive=False, sort=False, merge_tol=0.0)`+- `Structure.from_str(text, fmt=...)`+- `structure.to(filename=..., fmt=...)`+- `get_distance(i, j)` and bounded neighbor methods+- `get_primitive_structure()`+- `copy()`, `make_supercell()`, `apply_strain()`, and site editing+- `interpolate()` for compatible endpoints-**Key properties:**-- `length`: Bond length-- `get_bond_order()`: Returns bond order (single, double, triple)+Every operation has assumptions. Interpolation does not establish a physical+path; primitive/standard cells can alter site order and properties.-### Ion-Represents charged ionic species with oxidation states.+## Molecule and IMolecule```python-from pymatgen.core import Ion+from pymatgen.core import Molecule-# Create Fe2+ ion-fe2_ion = Ion.from_formula("Fe2+")+water = 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,+)```-### Interface-Represents substrate-film combinations for heterojunction analysis.+Molecule coordinates are Cartesian Å. Record:-### GrainBoundary-Represents crystallographic grain boundaries.+- charge and spin multiplicity+- atom order, labels, and site properties+- coordinate origin/orientation+- whether hydrogens, bond perception, centering, or geometry generation changed+ the object-### Spectrum-Represents spectroscopic data with methods for normalization and processing.+File formats often omit charge, multiplicity, bonding, isotope, or atom-label+semantics. `Molecule.from_file()` parsing success does not prove those fields+were present or preserved.-**Key methods:**-- `normalize(mode="max")`: Normalize spectrum-- `smear(sigma)`: Apply Gaussian smearing+## Explicit JSON serialization-## Best Practices+Core objects expose `as_dict()` and `from_dict()`:++```python+import json+from pymatgen.core import Structure++payload = structure.as_dict()+text = json.dumps(payload, allow_nan=False, sort_keys=True)++decoded = json.loads(text)+restored = Structure.from_dict(decoded)+```-1. **Immutability**: Use immutable versions (`IStructure`, `IMolecule`) when structures shouldn't be modified-2. **Serialization**: Prefer `as_dict()`/`from_dict()` over pickle for long-term storage-3. **Units**: Always work in atomic units (Å, eV) - conversions are available in `pymatgen.core.units`-4. **File I/O**: Use `from_file()` for automatic format detection-5. **Coordinates**: Pay attention to whether methods expect Cartesian or fractional coordinates+For untrusted JSON:++1. enforce byte, nesting, collection, and string limits+2. reject duplicate keys and non-finite numbers+3. validate the expected `Structure` schema+4. call the specific class constructor++Do not use pickle. Do not feed attacker-controlled MSON metadata to a general+decoder that dynamically imports classes. JSON is only a syntax; schema+validation is the trust boundary.++## Validation checklist++- object kind (composition/molecule/periodic structure) is explicit+- units and coordinate mode are explicit+- lattice/PBC and charge/spin are recorded where applicable+- all parser warnings are preserved+- occupancy/disorder and oxidation states are reported+- coordinates and lattice values are finite+- minimum distances are checked under a bound+- original is immutable or retained unchanged+- output schema and maximum size are explicit+- provenance links every derived object to its parent checksum++## Sources (verified 2026-07-23)++- [pymatgen core API](https://pymatgen.org/pymatgen.core.html)+- [pymatgen usage guide](https://pymatgen.org/usage.html)+- [pymatgen-core 2026.7.16 package metadata](https://pypi.org/project/pymatgen-core/)+- [pymatgen 2026.5.4 package metadata](https://pypi.org/project/pymatgen/)+- [pymatgen-core source](https://github.com/materialsproject/pymatgen-core)+- [pymatgen changelog](https://pymatgen.org/CHANGES.html)diff --git a/skills/pymatgen/references/io_formats.md b/skills/pymatgen/references/io_formats.mdindex 2552c4cd..0929ef30 100644--- a/skills/pymatgen/references/io_formats.md+++ b/skills/pymatgen/references/io_formats.md@@ -1,469 +1,323 @@-# Pymatgen I/O and File Format Reference+# I/O: parsers, writers, VASP, Q-Chem, and trust boundaries-This reference documents pymatgen's extensive input/output capabilities for reading and writing structural and computational data across 100+ file formats.+This reference targets `pymatgen-core==2026.7.16`, which now owns core and+electronic-structure-code I/O under the unchanged `pymatgen.io` namespace.-## General I/O Philosophy+## I/O is a semantic conversion-Pymatgen provides a unified interface for file operations through the `from_file()` and `to()` methods, with automatic format detection based on file extensions.+Parsing and writing are not neutral byte operations. Before any conversion,+record:-### Reading Files+- object kind: periodic `Structure` or non-periodic `Molecule`+- input and output formats, including format variants+- lattice/PBC and coordinate mode+- units+- species order, labels, occupancies/disorder, and oxidation states+- charge/spin for molecules+- site properties such as selective dynamics, velocities, forces, and magmoms+- parser warnings and any automatic corrections-```python-from pymatgen.core import Structure, Molecule--# Automatic format detection-struct = Structure.from_file("POSCAR")-struct = Structure.from_file("structure.cif")-mol = Molecule.from_file("molecule.xyz")--# Explicit format specification-struct = Structure.from_file("file.txt", fmt="cif")-```+Never overwrite the input or an existing output. Write a new artifact,+round-trip it, and compare the properties the workflow depends on.-### Writing Files+## Convenience interface```python-# Write to file (format inferred from extension)-struct.to(filename="output.cif")-struct.to(filename="POSCAR")-struct.to(filename="structure.xyz")--# Get string representation without writing-cif_string = struct.to(fmt="cif")-poscar_string = struct.to(fmt="poscar")-```--## Structure File Formats+from pymatgen.core import Molecule, Structure-### CIF (Crystallographic Information File)-Standard format for crystallographic data.--```python-from pymatgen.io.cif import CifParser, CifWriter+structure = Structure.from_file("input.cif", primitive=False, sort=False)+cif_text = structure.to(fmt="cif")+poscar_text = structure.to(fmt="poscar")-# Reading-parser = CifParser("structure.cif")-structure = parser.get_structures()[0] # Returns list of structures--# Writing-writer = CifWriter(struct)-writer.write_file("output.cif")--# Or using convenience methods-struct = Structure.from_file("structure.cif")-struct.to(filename="output.cif")+molecule = Molecule.from_file("molecule.xyz")+xyz_text = molecule.to(fmt="xyz")```-**Key features:**-- Supports symmetry information-- Can contain multiple structures-- Preserves space group and symmetry operations-- Handles partial occupancies--### POSCAR/CONTCAR (VASP)-VASP's structure format.--```python-from pymatgen.io.vasp import Poscar--# Reading-poscar = Poscar.from_file("POSCAR")-structure = poscar.structure--# Writing-poscar = Poscar(struct)-poscar.write_file("POSCAR")--# Or using convenience methods-struct = Structure.from_file("POSCAR")-struct.to(filename="POSCAR")-```+Use explicit `fmt` when a filename or extension is ambiguous. Never assume+automatic detection means the detected interpretation was scientifically+correct.-**Key features:**-- Supports selective dynamics-- Can include velocities (XDATCAR format)-- Preserves lattice and coordinate precision+## CIF-### XYZ-Simple molecular coordinates format.+Use the current parser method and retain all warnings:```python-# For molecules-mol = Molecule.from_file("molecule.xyz")-mol.to(filename="output.xyz")--# For structures (Cartesian coordinates)-struct.to(filename="structure.xyz")+import warnings+from pymatgen.io.cif import CifParser++with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ parser = CifParser(+ "input.cif",+ occupancy_tolerance=1.0,+ site_tolerance=1e-4,+ frac_tolerance=1e-4,+ check_cif=True,+ comp_tol=0.01,+ )+ structures = parser.parse_structures(+ primitive=False,+ symmetrized=False,+ check_occu=True,+ on_error="raise",+ )++parser_warnings = list(parser.warnings)+python_warnings = [str(item.message) for item in caught]```-### PDB (Protein Data Bank)-Common format for biomolecules.+Important behavior:-```python-mol = Molecule.from_file("protein.pdb")-mol.to(filename="output.pdb")-```+- A CIF can contain multiple data blocks/structures. Select an index explicitly.+- The parser attempts to repair some out-of-spec content and reports changes.+- Sites close within `site_tolerance` can be merged.+- Occupancy slightly above 1 can be rescaled when it falls within+ `occupancy_tolerance`; increasing that tolerance is a scientific decision,+ not a generic repair.+- `frac_tolerance` can round coordinates near common fractions.+- `check_cif` compares parsed structure composition against CIF composition and+ may warn about omissions such as difficult-to-locate hydrogens.+- `parse_structures(primitive=False)` is the current explicit behavior. Do not+ rely on historical defaults.-### JSON/YAML-Serialization via dictionaries.+Writing:```python-import json-import yaml--# JSON-with open("structure.json", "w") as f:- json.dump(struct.as_dict(), f)--with open("structure.json", "r") as f:- struct = Structure.from_dict(json.load(f))--# YAML-with open("structure.yaml", "w") as f:- yaml.dump(struct.as_dict(), f)--with open("structure.yaml", "r") as f:- struct = Structure.from_dict(yaml.safe_load(f))-```--## Electronic Structure Code I/O--### VASP+from pymatgen.io.cif import CifWriter-The most comprehensive integration in pymatgen.--#### Input Files--```python-from pymatgen.io.vasp.inputs import Incar, Poscar, Potcar, Kpoints, VaspInput--# INCAR (calculation parameters)-incar = Incar.from_file("INCAR")-incar = Incar({"ENCUT": 520, "ISMEAR": 0, "SIGMA": 0.05})-incar.write_file("INCAR")--# KPOINTS (k-point mesh)-from pymatgen.io.vasp.inputs import Kpoints-kpoints = Kpoints.automatic(20) # 20x20x20 Gamma-centered mesh-kpoints = Kpoints.automatic_density(struct, 1000) # By density-kpoints.write_file("KPOINTS")--# POTCAR (pseudopotentials)-potcar = Potcar(["Fe_pv", "O"]) # Specify functional variants--# Complete input set-vasp_input = VaspInput(incar, kpoints, poscar, potcar)-vasp_input.write_input("./vasp_calc")-```--#### Output Files--```python-from pymatgen.io.vasp.outputs import Vasprun, Outcar, Oszicar, Eigenval--# vasprun.xml (comprehensive output)-vasprun = Vasprun("vasprun.xml")-final_structure = vasprun.final_structure-energy = vasprun.final_energy-band_structure = vasprun.get_band_structure()-dos = vasprun.complete_dos--# OUTCAR-outcar = Outcar("OUTCAR")-magnetization = outcar.total_mag-elastic_tensor = outcar.elastic_tensor--# OSZICAR (convergence information)-oszicar = Oszicar("OSZICAR")-```--#### Input Sets--Pymatgen provides pre-configured input sets for common calculations:--```python-from pymatgen.io.vasp.sets import (- MPRelaxSet, # Materials Project relaxation- MPStaticSet, # Static calculation- MPNonSCFSet, # Non-self-consistent (band structure)- MPSOCSet, # Spin-orbit coupling- MPHSERelaxSet, # HSE06 hybrid functional+writer = CifWriter(+ structure,+ symprec=None,+ significant_figures=8,+ write_site_properties=False,)--# Create input set-relax = MPRelaxSet(struct)-relax.write_input("./relax_calc")--# Customize parameters-static = MPStaticSet(struct, user_incar_settings={"ENCUT": 600})-static.write_input("./static_calc")+cif_text = str(writer)```-### Gaussian--Quantum chemistry package integration.--```python-from pymatgen.io.gaussian import GaussianInput, GaussianOutput--# Input-gin = GaussianInput(- mol,- charge=0,- spin_multiplicity=1,- functional="B3LYP",- basis_set="6-31G(d)",- route_parameters={"Opt": None, "Freq": None}-)-gin.write_file("input.gjf")+Setting `symprec` asks the writer to find symmetry and can refine to a+conventional representation depending on `refine_struct`; that changes the+representation. Report `symprec`, `angle_tolerance`, and `refine_struct`.-# Output-gout = GaussianOutput("output.log")-final_mol = gout.final_structure-energy = gout.final_energy-frequencies = gout.frequencies-```+### Untrusted CIFs-### LAMMPS+A critical arbitrary-code-execution vulnerability in magnetic CIF+transformation parsing affected pymatgen through 2024.2.8 and was fixed in+2024.2.20. Use a current pinned release, but still parse attacker-controlled+files only in a low-privilege isolated process with byte, CPU, memory, disk,+site-count, and wall-time limits.-Classical molecular dynamics.+## POSCAR/CONTCAR```python-from pymatgen.io.lammps.data import LammpsData-from pymatgen.io.lammps.inputs import LammpsInputFile--# Structure to LAMMPS data file-lammps_data = LammpsData.from_structure(struct)-lammps_data.write_file("data.lammps")--# LAMMPS input script-lammps_input = LammpsInputFile.from_file("in.lammps")-```--### Quantum ESPRESSO+from pymatgen.io.vasp import Poscar-```python-from pymatgen.io.pwscf import PWInput, PWOutput--# Input-pwin = PWInput(- struct,- control={"calculation": "scf"},- system={"ecutwfc": 50, "ecutrho": 400},- electrons={"conv_thr": 1e-8}+poscar = Poscar.from_file(+ "POSCAR",+ check_for_potcar=False,+ read_velocities=True,)-pwin.write_file("pw.in")--# Output-pwout = PWOutput("pw.out")-final_structure = pwout.final_structure-energy = pwout.final_energy-```--### ABINIT--```python-from pymatgen.io.abinit import AbinitInput--abin = AbinitInput(struct, pseudos)-abin.set_vars(ecut=10, nband=10)-abin.write("abinit.in")-```--### CP2K--```python-from pymatgen.io.cp2k.inputs import Cp2kInput-from pymatgen.io.cp2k.outputs import Cp2kOutput--# Input-cp2k_input = Cp2kInput.from_file("cp2k.inp")--# Output-cp2k_output = Cp2kOutput("cp2k.out")-```--### FEFF (XAS/XANES)--```python-from pymatgen.io.feff import FeffInput+structure = poscar.structure-feff_input = FeffInput(struct, absorbing_atom="Fe")-feff_input.write_file("feff.inp")+direct_text = poscar.get_str(direct=True, significant_figures=16)+cartesian_text = poscar.get_str(direct=False, significant_figures=16)```-### LMTO (Stuttgart TB-LMTO-ASA)+Record:-```python-from pymatgen.io.lmto import LMTOCtrl+- direct/fractional versus Cartesian coordinates+- scale factor interpretation and units+- element-name source, especially VASP 4 files+- species order+- selective-dynamics flags+- velocities, predictor-corrector data, and lattice velocities if present-ctrl = LMTOCtrl.from_file("CTRL")-ctrl.structure-```+POSCAR cannot faithfully represent partial occupancies. Oxidation states and+arbitrary site properties generally do not round-trip. Never "fix" a POSCAR by+searching nearby directories for POTCAR files without explicit approval.-### Q-Chem+## XYZ and other low-context formats-```python-from pymatgen.io.qchem.inputs import QCInput-from pymatgen.io.qchem.outputs import QCOutput+XYZ is a Cartesian, non-periodic coordinate format. Converting a periodic+structure to XYZ drops lattice and periodicity. Basic XYZ also does not define+oxidation states, partial occupancies, bonds, charge, spin multiplicity, or+arbitrary site properties.-# Input-qc_input = QCInput(- mol,- rem={"method": "B3LYP", "basis": "6-31G*", "job_type": "opt"}-)-qc_input.write_file("mol.qin")+CSSR and XSF have their own representational limits. Treat support in+`Structure.to()` as syntactic capability, not proof of losslessness.-# Output-qc_output = QCOutput("mol.qout")-```+## JSON and MSON-### Exciting+Pymatgen core objects implement `as_dict()`/`from_dict()`:```python-from pymatgen.io.exciting import ExcitingInput+import json+from pymatgen.core import Structure-exc_input = ExcitingInput(struct)-exc_input.write_file("input.xml")+text = json.dumps(structure.as_dict(), allow_nan=False, sort_keys=True)+payload = json.loads(text)+restored = Structure.from_dict(payload)```-### ATAT (Alloy Theoretic Automated Toolkit)--```python-from pymatgen.io.atat import Mcsqs--mcsqs = Mcsqs(struct)-mcsqs.write_input(".")-```+For untrusted input, use a bounded strict JSON parser, reject duplicate keys and+non-finite values, validate the expected schema, and call a specific+constructor. Do not use pickle. Do not pass attacker-controlled `@module` or+`@class` metadata to a general dynamic object decoder.-## Special Purpose Formats+YAML is not used by the bundled CLIs. If a workflow truly needs YAML, use a+safe loader plus schema validation; YAML safety does not solve object-schema or+resource-exhaustion risks.-### Phonopy+## VASP input objects```python-from pymatgen.io.phonopy import get_phonopy_structure, get_pmg_structure--# Convert to phonopy structure-phonopy_struct = get_phonopy_structure(struct)+from pymatgen.io.vasp import Incar, Kpoints, Poscar-# Convert from phonopy-struct = get_pmg_structure(phonopy_struct)+incar = Incar({"ENCUT": 520, "ISMEAR": 0, "SIGMA": 0.05})+kpoints = Kpoints.automatic_density(structure, 1000)+poscar = Poscar(structure)```-### ASE (Atomic Simulation Environment)+Input sets encode versioned methodological choices:```python-from pymatgen.io.ase import AseAtomsAdaptor--adaptor = AseAtomsAdaptor()+from pymatgen.io.vasp.sets import MPNonSCFSet, MPRelaxSet, MPStaticSet-# Pymatgen to ASE-atoms = adaptor.get_atoms(struct)--# ASE to Pymatgen-struct = adaptor.get_structure(atoms)+relax = MPRelaxSet(structure)+static = MPStaticSet(structure)+bands = MPNonSCFSet(structure, mode="line")```-### Zeo++ (Porous Materials)+Before writing:-```python-from pymatgen.io.zeopp import get_voronoi_nodes, get_high_accuracy_voronoi_nodes+1. inspect the generated INCAR, KPOINTS, POSCAR, and POTCAR specification+2. record input-set class, pymatgen/core versions, all user overrides, and the+ source structure checksum+3. check magnetic moments, DFT+U, functional, pseudopotential family, ENCUT,+ k-point density/path, smearing, spin/SOC, symmetry, and convergence criteria+4. write to a new calculation directory-# Analyze pore structure-vor_nodes = get_voronoi_nodes(struct)-```+POTCAR datasets are VASP-licensed and not distributed by pymatgen. A+`POTCAR.spec` is not a POTCAR. Do not redistribute pseudopotential contents or+silently use files from an unrelated installation.-### BabelMolAdaptor (OpenBabel)+## VASP output parsing```python-from pymatgen.io.babel import BabelMolAdaptor--adaptor = BabelMolAdaptor(mol)--# Convert to different formats-pdb_str = adaptor.pdbstring-sdf_str = adaptor.write_file("mol.sdf", file_format="sdf")+from pymatgen.io.vasp import Vasprun++run = Vasprun(+ "vasprun.xml",+ ionic_step_skip=None,+ parse_dos=True,+ parse_eigen=True,+ parse_projected_eigen=False,+ parse_potcar_file=False,+ exception_on_bad_xml=True,+)-# Generate 3D coordinates-adaptor.add_hydrogen()-adaptor.make3d()+final_structure = run.final_structure+final_energy_eV = float(run.final_energy)+band_structure = run.get_band_structure(line_mode=True)+complete_dos = run.complete_dos```-## Alchemy and Transformation I/O+Use `BSVasprun` when only eigenvalue/band-structure information is needed.+Projected eigenvalues can take extreme time and memory; leave+`parse_projected_eigen=False` unless they are required and resources are+bounded.-### TransformedStructure+Parser success does not establish:-Structures that track their transformation history.+- electronic or ionic convergence+- a correct k-path or line-mode reconstruction+- comparable energies+- valid pseudopotential hashes+- correct Fermi level, occupations, spin/SOC, or projection interpretation-```python-from pymatgen.alchemy.materials import TransformedStructure-from pymatgen.transformations.standard_transformations import (- SupercellTransformation,- SubstitutionTransformation-)+Preserve source-file checksums and parsing options. Large XML, HDF5, CHGCAR,+LOCPOT, WAVECAR, and trajectory files need explicit byte and memory limits.-# Create transformed structure-ts = TransformedStructure(struct, [])-ts.append_transformation(SupercellTransformation([[2,0,0],[0,2,0],[0,0,2]]))-ts.append_transformation(SubstitutionTransformation({"Fe": "Mn"}))+## Band structures and DOS-# Write with history-ts.write_vasp_input("./calc_dir")+`Vasprun.get_band_structure()` returns a `BandStructure` or+`BandStructureSymmLine` depending on inputs. Relevant methods include+`is_metal()`, `get_band_gap()`, `get_vbm()`, and `get_cbm()`.-# Read from SNL (Structure Notebook Language)-ts = TransformedStructure.from_snl(snl)-```--## Batch Operations+`run.complete_dos` is a `CompleteDos`; current analyses include total,+element-, site-, and orbital-projected DOS. Verify energy reference, Fermi+level, normalization, smearing, spin channels, projection completeness, and+whether the DOS and band run correspond to the same structure/method.-### CifTransmuter+## Q-Chem-Process multiple CIF files.+Current imports:```python-from pymatgen.alchemy.transmuters import CifTransmuter+from pymatgen.io.qchem.inputs import QCInput+from pymatgen.io.qchem.outputs import QCOutput-transmuter = CifTransmuter.from_filenames(- ["structure1.cif", "structure2.cif"],- [SupercellTransformation([[2,0,0],[0,2,0],[0,0,2]])]+job = QCInput(+ molecule,+ rem={+ "job_type": "sp",+ "method": "wb97x-v",+ "basis": "def2-svpd",+ },)+text = str(job)-# Write all structures-transmuter.write_vasp_input("./batch_calc")-```--### PoscarTransmuter--Similar for POSCAR files.--```python-from pymatgen.alchemy.transmuters import PoscarTransmuter--transmuter = PoscarTransmuter.from_filenames(- ["POSCAR1", "POSCAR2"],- [transformation1, transformation2]-)+parsed = QCOutput("qchem.out")+data = parsed.data```-## Best Practices--1. **Automatic format detection**: Use `from_file()` and `to()` methods whenever possible-2. **Error handling**: Always wrap file I/O in try-except blocks-3. **Format-specific parsers**: Use specialized parsers (e.g., `Vasprun`) for detailed output analysis-4. **Input sets**: Prefer pre-configured input sets over manual parameter specification-5. **Serialization**: Use JSON/YAML for long-term storage and version control-6. **Batch processing**: Use transmuters for applying transformations to multiple structures--## Supported Format Summary--### Structure formats:-CIF, POSCAR/CONTCAR, XYZ, PDB, XSF, PWMAT, Res, CSSR, JSON, YAML--### Electronic structure codes:-VASP, Gaussian, LAMMPS, Quantum ESPRESSO, ABINIT, CP2K, FEFF, Q-Chem, LMTO, Exciting, NWChem, AIMS, Crystallographic data formats--### Molecular formats:-XYZ, PDB, MOL, SDF, PQR, via OpenBabel (many additional formats)--### Special purpose:-Phonopy, ASE, Zeo++, Lobster, BoltzTraP+`QCInput` accepts explicit sections such as `rem`, `opt`, `pcm`, `solvent`,+`smx`, `scan`, `plots`, `nbo`, `geom_opt`, and others. Validate each setting+against the licensed Q-Chem version and manual. Preserve molecule atom order,+charge, spin multiplicity, method/basis, solvent model, job type, and input+text.++`QCOutput` parses a file into structured data; inspect parser errors,+completion, SCF/geometry convergence, imaginary frequencies, and units before+using a result.++## External and native programs++Pymatgen interfaces can call or depend on optional external tools, including:++- enumlib (`enum.x`, `makestr.x`) for derivative-structure enumeration+- Bader analysis executable+- packmol+- ffmpeg+- Zeo++/Voro+++- graph and visualization libraries++Do not invoke them automatically. Verify official source, version, hash,+license, native build scripts, executable path, exact argv, working directory,+input/output paths, and CPU/RAM/disk/time bounds. Never interpolate untrusted+text into a shell command.++## Safe conversion sequence++1. Inventory source bytes, checksum, format, and parser warnings.+2. Validate lattice/PBC, coordinates, species order, occupancy/disorder,+ oxidation states, labels, and site properties.+3. Generate a dry-run representation-loss plan.+4. Refuse an incompatible target (for example, disordered structure to POSCAR).+5. Require explicit acknowledgement for remaining losses.+6. Render in memory, enforce an output-byte bound, and create a new file+ exclusively.+7. Parse the output under the same safety bounds.+8. Compare formula, site count, lattice, PBC, coordinates, occupancy, labels,+ and required properties with explicit numerical tolerances.+9. Record both checksums and every warning in the artifact manifest.++## Sources (verified 2026-07-23)++- [pymatgen I/O API](https://pymatgen.org/pymatgen.io.html)+- [CIF parser and writer API](https://pymatgen.org/pymatgen.io.html)+- [VASP I/O API](https://pymatgen.org/pymatgen.io.vasp.html)+- [Q-Chem I/O API](https://pymatgen.org/pymatgen.io.qchem.html)+- [pymatgen installation and external programs](https://pymatgen.org/installation.html)+- [pymatgen-core source](https://github.com/materialsproject/pymatgen-core)+- [CVE-2024-23346 official advisory](https://github.com/materialsproject/pymatgen/security/advisories/GHSA-vgv8-5cpj-qj2f)+- [pymatgen changelog](https://pymatgen.org/CHANGES.html)diff --git a/skills/pymatgen/references/materials_project_api.md b/skills/pymatgen/references/materials_project_api.mdindex 1dc621cc..7a95c488 100644--- a/skills/pymatgen/references/materials_project_api.md+++ b/skills/pymatgen/references/materials_project_api.md@@ -1,517 +1,406 @@-# Materials Project API Reference+# Materials Project API: bounded queries, provenance, and computed-data limits-This reference documents how to access and use the Materials Project database through pymatgen's API integration.+This reference targets `mp-api==0.46.4` (released 2026-06-15) with+`pymatgen==2026.5.4` and `pymatgen-core==2026.7.16`. `mp-api` requires Python+3.11+ and depends on `pymatgen>2024.2.20`.-## Overview+Use the separate official client:-The Materials Project is a comprehensive database of computed materials properties, containing data on hundreds of thousands of inorganic crystals and molecules. The API provides programmatic access to this data through the `MPRester` client.--## Installation and Setup--The Materials Project API client is now in a separate package:--```bash-pip install mp-api+```python+from mp_api.client import MPRester```-### Getting an API Key+Do not use a legacy Materials Project client import from older pymatgen+examples.-1. Visit https://next-gen.materialsproject.org/-2. Create an account or log in-3. Navigate to your dashboard/settings-4. Generate an API key-5. Store it as an environment variable:+## Installation++Pin the tested client and materials stack:```bash-export MP_API_KEY="your_api_key_here"+uv add "pymatgen==2026.5.4" "pymatgen-core==2026.7.16" "mp-api==0.46.4"+uv lock+uv sync --frozen```-Or add to your shell configuration file (~/.bashrc, ~/.zshrc, etc.)+The 0.46.4 package metadata declares direct dependencies including+`pymatgen>2024.2.20`, `monty>=2024.12.10`, `emmet-core>=0.87.1`,+`requests>=2.23.0`, `orjson>=3.10,<4`, `pyarrow>=20`, and+`deltalake>=1.4,<1.6`, plus boto3 and typing extensions. A lockfile is needed+to freeze transitive artifacts.++## Authentication: one named secret-## Basic Usage+An API key is required and is available from the logged-in Materials Project+[dashboard](https://next-gen.materialsproject.org/dashboard).-### Initialization+The approved pattern is:```pythonfrom mp_api.client import MPRester-# Using environment variable (recommended)-with MPRester() as mpr:- # Perform queries- pass--# Or explicitly pass API key-with MPRester("your_api_key_here") as mpr:- # Perform queries+# MPRester reads only the already-injected MP_API_KEY.+with MPRester() as rester:pass```-**Important**: Always use the `with` context manager to ensure sessions are properly closed.--## Querying Materials Data--### Search by Formula+Operational rules:-```python-with MPRester() as mpr:- # Get all materials with formula- materials = mpr.materials.summary.search(formula="Fe2O3")-- for mat in materials:- print(f"Material ID: {mat.material_id}")- print(f"Formula: {mat.formula_pretty}")- print(f"Energy above hull: {mat.energy_above_hull} eV/atom")- print(f"Band gap: {mat.band_gap} eV")- print()-```+- use only the environment variable `MP_API_KEY`+- inject it through the user's shell/session secret manager+- never accept it as a command-line argument+- never embed it in code, notebooks, URLs, cache files, or manifests+- never traverse dot-env files or dump the environment+- never print the key or unredacted exceptions that might contain it+- do not send it anywhere except the official Materials Project API endpoint-### Search by Material ID+The bundled query CLI follows these rules and reads the variable only after+`--execute`.-```python-with MPRester() as mpr:- # Get specific material- material = mpr.materials.summary.search(material_ids=["mp-149"])[0]+## Query contract before network- print(f"Formula: {material.formula_pretty}")- print(f"Space group: {material.symmetry.symbol}")- print(f"Density: {material.density} g/cm³")-```+Before any request, disclose:-### Search by Chemical System+1. endpoint and `mp-api` version+2. all filters+3. exact response fields+4. `num_chunks`, `chunk_size`, and maximum serialized bytes+5. cache reads/writes+6. output path and no-overwrite behavior+7. API-key source by name, never value+8. data license, citation, provenance, and scientific limitations-```python-with MPRester() as mpr:- # Get all materials in Fe-O system- materials = mpr.materials.summary.search(chemsys="Fe-O")+The dry-run planner:- # Get materials in ternary system- materials = mpr.materials.summary.search(chemsys="Li-Fe-O")+```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```-### Search by Elements+Only an explicit execution permits the disclosed network workflow:-```python-with MPRester() as mpr:- # Materials containing Fe and O- materials = mpr.materials.summary.search(elements=["Fe", "O"])-- # Materials containing ONLY Fe and O (excluding others)- materials = mpr.materials.summary.search(- elements=["Fe", "O"],- exclude_elements=True- )+```bash+python scripts/mp_query.py \+ --material-id mp-149 \+ --fields formula_pretty,structure,origins,last_updated \+ --limit 1 --output mp-149.json --execute```-## Getting Structures--### Structure from Material ID--```python-with MPRester() as mpr:- # Get structure- structure = mpr.get_structure_by_material_id("mp-149")+The CLI has no implicit result cache. The explicit bounded JSON output is the+reusable artifact. `MPRester` initialization performs compatibility and+heartbeat/database-version metadata requests before the bounded summary+search. The CLI discloses those requests, disables the platform-detail user+agent and local database-version notification log, and records the server's+database version.- # Get multiple structures- structures = mpr.get_structures(["mp-149", "mp-510", "mp-19017"])-```+## Summary searches-### All Structures for a Formula+The official docs identify summary data as the main property overview for a+material:```python-with MPRester() as mpr:- # Get all Fe2O3 structures- materials = mpr.materials.summary.search(formula="Fe2O3")-- for mat in materials:- structure = mpr.get_structure_by_material_id(mat.material_id)- print(f"{mat.material_id}: {structure.get_space_group_info()}")-```--## Advanced Queries--### Property Filtering+from mp_api.client import MPRester-```python-with MPRester() as mpr:- # Materials with specific property ranges- materials = mpr.materials.summary.search(- chemsys="Li-Fe-O",- energy_above_hull=(0, 0.05), # Stable or near-stable- band_gap=(1.0, 3.0), # Semiconducting+with MPRester() as rester:+ docs = rester.materials.summary.search(+ material_ids=["mp-149", "mp-13"],+ fields=[+ "material_id",+ "formula_pretty",+ "energy_above_hull",+ "band_gap",+ "origins",+ "last_updated",+ ],+ all_fields=False,+ num_chunks=1,+ chunk_size=25,)+```- # Magnetic materials- materials = mpr.materials.summary.search(- elements=["Fe"],- is_magnetic=True- )+`material_ids` accepts one ID or a list in the current signature. The result is+a list of `SummaryDoc` model objects by default.- # Metals only- materials = mpr.materials.summary.search(- chemsys="Fe-Ni",- is_metal=True- )-```+### Property filters-### Sorting and Limiting+Verified public `SummaryRester.search` parameters include:```python-with MPRester() as mpr:- # Get most stable materials- materials = mpr.materials.summary.search(+with MPRester() as rester:+ docs = rester.materials.summary.search(chemsys="Li-Fe-O",- sort_fields=["energy_above_hull"],+ elements=["Li", "O"],+ exclude_elements=["F"],+ energy_above_hull=(0.0, 0.05),+ band_gap=(0.5, 3.0),+ is_stable=None,+ fields=["material_id", "formula_pretty", "energy_above_hull", "band_gap"],+ all_fields=False,num_chunks=1,- chunk_size=10 # Limit to 10 results+ chunk_size=25,)```-## Electronic Structure Data+Other current filters include formula, crystal system, density, deprecation,+dielectric ranges, elastic ranges, metal/direct-gap flags, property+availability, magnetic ordering, element/site counts, space group, theoretical+status, energy ranges, volume, and surface-property ranges. Consult the exact+installed signature instead of passing guessed keywords.-### Band Structure--```python-with MPRester() as mpr:- # Get band structure- bs = mpr.get_bandstructure_by_material_id("mp-149")-- # Analyze band structure- if bs:- print(f"Band gap: {bs.get_band_gap()}")- print(f"Is metal: {bs.is_metal()}")- print(f"Direct gap: {bs.get_band_gap()['direct']}")-- # Plot- from pymatgen.electronic_structure.plotter import BSPlotter- plotter = BSPlotter(bs)- plotter.show()-```+`exclude_elements` is a list of element symbols; it is not a Boolean flag.-### Density of States+`available_fields` lists fields the endpoint can return. It does not mean every+field is a valid filter:```python-with MPRester() as mpr:- # Get DOS- dos = mpr.get_dos_by_material_id("mp-149")-- if dos:- # Get band gap from DOS- gap = dos.get_gap()- print(f"Band gap from DOS: {gap} eV")-- # Plot DOS- from pymatgen.electronic_structure.plotter import DosPlotter- plotter = DosPlotter()- plotter.add_dos("Total DOS", dos)- plotter.show()+with MPRester() as rester:+ returnable_fields = rester.materials.summary.available_fields```-### Fermi Surface--```python-with MPRester() as mpr:- # Get electronic structure data for Fermi surface- bs = mpr.get_bandstructure_by_material_id("mp-149", line_mode=False)-```+Requesting all fields is the documented default and can be expensive. Always+pass a short `fields` list and bound chunks.-## Thermodynamic Data+## Serialization-### Phase Diagram Construction+Use the public Pydantic model interface:```python-from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter--with MPRester() as mpr:- # Get entries for phase diagram- entries = mpr.get_entries_in_chemsys("Li-Fe-O")-- # Build phase diagram- pd = PhaseDiagram(entries)-- # Plot- plotter = PDPlotter(pd)- plotter.show()+payload = [document.model_dump(mode="json") for document in docs]```-### Pourbaix Diagram--```python-from pymatgen.analysis.pourbaix_diagram import PourbaixDiagram, PourbaixPlotter--with MPRester() as mpr:- # Get entries for Pourbaix diagram- entries = mpr.get_pourbaix_entries(["Fe"])+Then write strict JSON with `allow_nan=False`, a byte bound, and a new output+path. Include query, fields, retrieval time, endpoint, client versions, and+license/citation. Do not use deprecated generic dictionary shims, pickle, or a+general object decoder on untrusted cached data.- # Build Pourbaix diagram- pb = PourbaixDiagram(entries)-- # Plot- plotter = PourbaixPlotter(pb)- plotter.show()-```--### Formation Energy+## Structures```python-with MPRester() as mpr:- materials = mpr.materials.summary.search(material_ids=["mp-149"])-- for mat in materials:- print(f"Formation energy: {mat.formation_energy_per_atom} eV/atom")- print(f"Energy above hull: {mat.energy_above_hull} eV/atom")-```--## Elasticity and Mechanical Properties--```python-with MPRester() as mpr:- # Search for materials with elastic data- materials = mpr.materials.elasticity.search(- chemsys="Fe-O",- bulk_modulus_vrh=(100, 300) # GPa- )-- for mat in materials:- print(f"{mat.material_id}: K = {mat.bulk_modulus_vrh} GPa")-```--## Dielectric Properties+from mp_api.client import MPRester-```python-with MPRester() as mpr:- # Get dielectric data- materials = mpr.materials.dielectric.search(- material_ids=["mp-149"]+with MPRester() as rester:+ structure = rester.get_structure_by_material_id(+ "mp-149",+ final=True,+ conventional_unit_cell=False,)-- for mat in materials:- print(f"Dielectric constant: {mat.e_electronic}")- print(f"Refractive index: {mat.n}")```-## Piezoelectric Properties--```python-with MPRester() as mpr:- # Get piezoelectric materials- materials = mpr.materials.piezoelectric.search(- piezoelectric_modulus=(1, 100)- )-```+Alternatively request `structure` as an explicit summary field. Preserve:-## Surface Properties+- material ID+- whether the final/initial and conventional/primitive representation was+ requested+- `origins` and task IDs+- retrieval and database release+- parser/API warnings-```python-with MPRester() as mpr:- # Get surface data- surfaces = mpr.materials.surface_properties.search(- material_ids=["mp-149"]- )-```+Validate the returned structure locally. A Materials Project structure is a+computed relaxed representation, not necessarily the experimental setting,+lattice parameters, disorder, temperature, or composition model.-## Molecule Data (For Molecular Materials)+## Entries and phase diagrams```python-with MPRester() as mpr:- # Search molecules- molecules = mpr.molecules.summary.search(- formula="H2O"- )-- for mol in molecules:- print(f"Molecule ID: {mol.molecule_id}")- print(f"Formula: {mol.formula_pretty}")-```--## Bulk Data Download--### Download All Data for Materials+from mp_api.client import MPRester-```python-with MPRester() as mpr:- # Get comprehensive data- materials = mpr.materials.summary.search(- material_ids=["mp-149"],- fields=[- "material_id",- "formula_pretty",- "structure",- "energy_above_hull",- "band_gap",- "density",- "symmetry",- "elasticity",- "magnetic_ordering"- ]+with MPRester() as rester:+ entries = rester.get_entries_in_chemsys(+ "Li-Fe-O",+ compatible_only=True,+ conventional_unit_cell=False,)```-## Provenance and Calculation Details+The current method also accepts `use_gibbs`, `property_data`, and+`additional_criteria`. The official query guide shows filtering thermo types+through:```python-with MPRester() as mpr:- # Get calculation details- materials = mpr.materials.summary.search(- material_ids=["mp-149"],- fields=["material_id", "origins"]+with MPRester() as rester:+ entries = rester.get_entries_in_chemsys(+ "Co-N",+ additional_criteria={+ "thermo_types": ["GGA_GGA+U", "GGA_GGA+U_R2SCAN", "R2SCAN"]+ },)-- for mat in materials:- print(f"Origins: {mat.origins}")-```--## Working with Entries--### ComputedEntry for Thermodynamic Analysis--```python-with MPRester() as mpr:- # Get entries (includes energy and composition)- entries = mpr.get_entries_in_chemsys("Li-Fe-O")-- # Entries can be used directly in phase diagram analysis- from pymatgen.analysis.phase_diagram import PhaseDiagram- pd = PhaseDiagram(entries)-- # Check stability- for entry in entries[:5]:- e_above_hull = pd.get_e_above_hull(entry)- print(f"{entry.composition.reduced_formula}: {e_above_hull:.3f} eV/atom")```-## Rate Limiting and Best Practices--### Rate Limits--The Materials Project API has rate limits to ensure fair usage:-- Be mindful of request frequency-- Use batch queries when possible-- Cache results locally for repeated analysis+Do not mix thermo types or correction schemes casually. Record all arguments,+entry IDs, correction data, origins, and database release. Preserve the+retrieved entries locally and build the hull offline.-### Efficient Querying+## Band structures and DOS-```python-# Bad: Multiple separate queries-with MPRester() as mpr:- for mp_id in ["mp-149", "mp-510", "mp-19017"]:- struct = mpr.get_structure_by_material_id(mp_id) # 3 API calls--# Good: Single batch query-with MPRester() as mpr:- structs = mpr.get_structures(["mp-149", "mp-510", "mp-19017"]) # 1 API call-```--### Caching Results+Official convenience methods include:```python-import json--# Save results for later use-with MPRester() as mpr:- materials = mpr.materials.summary.search(chemsys="Li-Fe-O")-- # Save to file- with open("li_fe_o_materials.json", "w") as f:- json.dump([mat.dict() for mat in materials], f)--# Load cached results-with open("li_fe_o_materials.json", "r") as f:- cached_data = json.load(f)+with MPRester() as rester:+ bands = rester.get_bandstructure_by_material_id("mp-149")+ dos = rester.get_dos_by_material_id("mp-149")```-## Error Handling--```python-from mp_api.client.core.client import MPRestError--try:- with MPRester() as mpr:- materials = mpr.materials.summary.search(material_ids=["invalid-id"])-except MPRestError as e:- print(f"API Error: {e}")-except Exception as e:- print(f"Unexpected error: {e}")-```+These can return `None` when data is unavailable. Their values are computed and+method-dependent. Preserve calculation/task origins, spin/SOC, path/mesh,+functional, and database release. Do not treat an absent object as a zero gap+or zero DOS.-## Common Use Cases+## Provenance with origins-### Finding Stable Compounds+The official query guide recommends requesting `origins` to connect a summary+property to a calculation task:```python-with MPRester() as mpr:- # Get all stable compounds in a chemical system- materials = mpr.materials.summary.search(- chemsys="Li-Fe-O",- energy_above_hull=(0, 0.001) # Essentially on convex hull+with MPRester() as rester:+ summaries = rester.materials.summary.search(+ material_ids=["mp-149"],+ fields=["material_id", "structure", "origins"],+ all_fields=False,+ num_chunks=1,+ chunk_size=1,)-- print(f"Found {len(materials)} stable compounds")- for mat in materials:- print(f" {mat.formula_pretty} ({mat.material_id})")```-### Battery Material Screening+An origin can identify the task used for a property. A corresponding thermo+document's `run_type` distinguishes categories such as GGA, GGA+U, or r2SCAN.+Do not assume all properties on one summary document came from one calculation+or functional.-```python-with MPRester() as mpr:- # Screen for potential cathode materials- materials = mpr.materials.summary.search(- elements=["Li"], # Must contain Li- energy_above_hull=(0, 0.05), # Near stable- band_gap=(0, 0.5), # Metallic or small gap- )+## Other routes- print(f"Found {len(materials)} potential cathode materials")-```+The client exposes endpoint-specific resters under `rester.materials`, with+routes documented for thermo, electronic structure, elasticity, dielectric,+magnetism, phonons, surfaces, XAS, synthesis-related data, and others.+Signatures and document models vary. Inspect the current route documentation+and request only supported fields.-### Finding Materials with Specific Crystal Structure+Do not copy old endpoint examples or invent filter names. Endpoint availability+and schema can evolve independently of the Python wrapper.-```python-with MPRester() as mpr:- # Find materials with specific space group- materials = mpr.materials.summary.search(- chemsys="Fe-O",- spacegroup_number=167 # R-3c (corundum structure)- )-```--## Integration with Other Pymatgen Features+## Errors, retries, and rate handling-All data retrieved from the Materials Project can be directly used with pymatgen's analysis tools:+Use the current exception:```python-with MPRester() as mpr:- # Get structure- struct = mpr.get_structure_by_material_id("mp-149")-- # Use with pymatgen analysis- from pymatgen.symmetry.analyzer import SpacegroupAnalyzer- sga = SpacegroupAnalyzer(struct)-- # Generate surfaces- from pymatgen.core.surface import SlabGenerator- slabgen = SlabGenerator(struct, (1,0,0), 10, 10)- slabs = slabgen.get_slabs()-- # Phase diagram analysis- entries = mpr.get_entries_in_chemsys(struct.composition.chemical_system)- from pymatgen.analysis.phase_diagram import PhaseDiagram- pd = PhaseDiagram(entries)-```--## Additional Resources+from mp_api.client.core.exceptions import MPRestError-- **API Documentation**: https://docs.materialsproject.org/-- **Materials Project Website**: https://next-gen.materialsproject.org/-- **GitHub**: https://github.com/materialsproject/api-- **Forum**: https://matsci.org/--## Best Practices Summary--1. **Always use context manager**: Use `with MPRester() as mpr:`-2. **Store API key as environment variable**: Never hardcode API keys-3. **Batch queries**: Request multiple items at once when possible-4. **Cache results**: Save frequently used data locally-5. **Handle errors**: Wrap API calls in try-except blocks-6. **Be specific**: Use filters to limit results and reduce data transfer-7. **Check data availability**: Not all properties are available for all materials+try:+ with MPRester() as rester:+ docs = rester.materials.summary.search(+ material_ids=["mp-149"],+ fields=["material_id"],+ all_fields=False,+ num_chunks=1,+ chunk_size=1,+ )+except MPRestError:+ # Report a bounded, credential-redacted failure.+ raise+```++Official 0.46.4 client source configures retries for HTTP 429, 502, and 504 and+respects `Retry-After`. It wraps request failures as `MPRestError` and advises+smaller requests on connection timeout.++Safety rules:++- rely on the pinned client's bounded retry behavior+- do not add an unbounded retry loop+- do not claim a numeric service quota unless current official documentation+ publishes one+- reduce fields/chunk size on timeout or oversized responses+- stop after a persistent authorization, schema, or validation error+- redact `MP_API_KEY` from any exception text++## Cache policy++Caching can improve reproducibility but creates a data-governance obligation.+Before using a cache, disclose:++- exact path, schema, size limit, and retention+- cache key: endpoint, filters, fields, client version, and database release+- whether stale data is acceptable+- license/citation metadata+- whether structures or contributed data are stored++Never cache credentials. Never treat a cache as current without checking its+retrieval time and database version. `mp-api` exposes a local full-dataset cache+path for bulk/delta-table workflows; the bundled summary-query CLI does not+request those downloads and intentionally uses no hidden result cache.++## License, attribution, and citation++Materials Project states that its data is licensed under+[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) and that contributed+data is owned by its respective contributors.++The official FAQ says citations are appropriate wherever Materials Project+data, methods, or output are used. Preserve:++- canonical Materials Project citation+- property/tool-specific citations from the material/citation page+- database release citation+- material IDs and task/property origins+- retrieval date and query++See [How to Cite](https://materialsproject.org/about/cite) and+[Database Versions](https://docs.materialsproject.org/changes/database-versions).++## Computed-data limitations++Materials Project documents that:++- core properties are calculated in-house using simulation methods+- typical/systematic errors must be assessed from property publications+- PBE lattice parameters often show systematic overestimation, with larger+ interlayer errors where van der Waals interactions are poorly described+- PBE band gaps are systematically underestimated+- summary/aggregated values can change as calculations and database releases+ are updated+- space groups depend on `symprec`; the MP pipeline commonly uses `0.1 Å`++Therefore:++- computed stability is not experimental stability or synthesizability+- predicted structures are not proof of existence+- missing data is not zero+- a material ID does not guarantee one immutable property record+- cite the database version and property methodology++## Minimal provenance envelope++```json+{+ "retrieved_at_utc": "2026-07-23T00:00:00Z",+ "endpoint": "https://api.materialsproject.org/materials/summary/",+ "filters": {"material_ids": ["mp-149"]},+ "fields": ["material_id", "formula_pretty", "origins", "last_updated"],+ "limit": 1,+ "client": {+ "mp-api": "0.46.4",+ "pymatgen": "2026.5.4",+ "pymatgen-core": "2026.7.16"+ },+ "database_version": "record from current MP release metadata",+ "license": "CC BY 4.0",+ "citation": "https://materialsproject.org/about/cite"+}+```++Do not include the API key.++## Sources (verified 2026-07-23)++- [mp-api 0.46.4 on PyPI](https://pypi.org/project/mp-api/)+- [Official mp-api repository](https://github.com/materialsproject/api)+- [Getting started](https://docs.materialsproject.org/downloading-data/using-the-api/getting-started)+- [Querying data](https://docs.materialsproject.org/downloading-data/using-the-api/querying-data)+- [mp-api route reference](https://materialsproject.github.io/api/)+- [Materials Project FAQ](https://docs.materialsproject.org/frequently-asked-questions)+- [Materials Project calculation details](https://docs.materialsproject.org/methodology/materials-methodology/calculation-details)+- [How to Cite](https://materialsproject.org/about/cite)+- [Database versions](https://docs.materialsproject.org/changes/database-versions)+- [Materials Project home and CC BY statement](https://materialsproject.org/)diff --git a/skills/pymatgen/references/transformations_workflows.md b/skills/pymatgen/references/transformations_workflows.mdindex 745509b5..20a86b0d 100644--- a/skills/pymatgen/references/transformations_workflows.md+++ b/skills/pymatgen/references/transformations_workflows.md@@ -1,591 +1,385 @@-# Pymatgen Transformations and Common Workflows+# Transformations and provenance-preserving workflows-This reference documents pymatgen's transformation framework and provides recipes for common materials science workflows.+Transformations create scientific hypotheses and derived structures. They are+not harmless cleanup. Always retain the original, make assumptions explicit,+bound candidate growth, and record parent/child checksums.-## Transformation Framework+## Transformation contract-Transformations provide a systematic way to modify structures while tracking the history of modifications.--### Standard Transformations--Located in `pymatgen.transformations.standard_transformations`.--#### SupercellTransformation--Create supercells with arbitrary scaling matrices.--```python-from pymatgen.transformations.standard_transformations import SupercellTransformation--# Simple 2x2x2 supercell-trans = SupercellTransformation([[2,0,0], [0,2,0], [0,0,2]])-new_struct = trans.apply_transformation(struct)--# Non-orthogonal supercell-trans = SupercellTransformation([[2,1,0], [0,2,0], [0,0,2]])-new_struct = trans.apply_transformation(struct)-```--#### SubstitutionTransformation--Replace species in a structure.--```python-from pymatgen.transformations.standard_transformations import SubstitutionTransformation--# Replace all Fe with Mn-trans = SubstitutionTransformation({"Fe": "Mn"})-new_struct = trans.apply_transformation(struct)--# Partial substitution (50% Fe -> Mn)-trans = SubstitutionTransformation({"Fe": {"Mn": 0.5, "Fe": 0.5}})-new_struct = trans.apply_transformation(struct)-```--#### RemoveSpeciesTransformation--Remove specific species from structure.+A pymatgen transformation exposes `apply_transformation(structure, ...)`.+One-to-one transformations return a structure; one-to-many transformations can+return ranked dictionaries when explicitly requested.```python-from pymatgen.transformations.standard_transformations import RemoveSpeciesTransformation--trans = RemoveSpeciesTransformation(["H"]) # Remove all hydrogen-new_struct = trans.apply_transformation(struct)-```--#### OrderDisorderedStructureTransformation--Order disordered structures with partial occupancies.--```python-from pymatgen.transformations.standard_transformations import OrderDisorderedStructureTransformation+from pymatgen.transformations.standard_transformations import (+ SubstitutionTransformation,+ SupercellTransformation,+)-trans = OrderDisorderedStructureTransformation()-new_struct = trans.apply_transformation(disordered_struct)+parent = structure.copy()+supercell = SupercellTransformation([2, 2, 2]).apply_transformation(parent)+substituted = SubstitutionTransformation({"Na": "K"}).apply_transformation(+ parent+)```-#### PrimitiveCellTransformation+Even if a transformation currently returns a new object, keep `parent`+unchanged and assert it against a pre-operation checksum.-Convert to primitive cell.+For every transformation, record:-```python-from pymatgen.transformations.standard_transformations import PrimitiveCellTransformation+- fully qualified class and package versions+- constructor arguments and defaults relied upon+- parent artifact/checksum+- occupancy, oxidation-state, charge, spin, and site-property assumptions+- candidate count/ranking method+- warnings and external executable use+- child artifact/checksum-trans = PrimitiveCellTransformation()-primitive_struct = trans.apply_transformation(struct)-```--#### ConventionalCellTransformation--Convert to conventional cell.+## Supercells```python-from pymatgen.transformations.standard_transformations import ConventionalCellTransformation+from pymatgen.transformations.standard_transformations import (+ SupercellTransformation,+)-trans = ConventionalCellTransformation()-conventional_struct = trans.apply_transformation(struct)+transformation = SupercellTransformation(+ [[2, 0, 0], [0, 2, 0], [0, 0, 2]]+)+child = transformation.apply_transformation(parent)```-#### RotationTransformation--Rotate structure.+Check:-```python-from pymatgen.transformations.standard_transformations import RotationTransformation+- scaling-matrix determinant is a positive integer+- expected site-count multiplier+- volume-per-site consistency+- atom/site-property mapping+- periodic boundary conditions+- memory and output growth-# Rotate by axis and angle-trans = RotationTransformation([0, 0, 1], 45) # 45° around z-axis-new_struct = trans.apply_transformation(struct)-```+Reject a matrix or candidate whose determinant/site count exceeds the reviewed+bound. A non-diagonal matrix changes the cell basis and site ordering.-#### ScaleToRelaxedTransformation+## Substitution and disorder-Scale lattice to match a relaxed structure.+Complete substitution:```python-from pymatgen.transformations.standard_transformations import ScaleToRelaxedTransformation+from pymatgen.transformations.standard_transformations import (+ SubstitutionTransformation,+)-trans = ScaleToRelaxedTransformation(relaxed_struct)-scaled_struct = trans.apply_transformation(unrelaxed_struct)+child = SubstitutionTransformation({"Fe": "Mn"}).apply_transformation(parent)```-### Advanced Transformations--Located in `pymatgen.transformations.advanced_transformations`.--#### EnumerateStructureTransformation--Enumerate all symmetrically distinct ordered structures from a disordered structure.+Partial substitution creates disorder:```python-from pymatgen.transformations.advanced_transformations import EnumerateStructureTransformation--# Enumerate structures up to max 8 atoms per unit cell-trans = EnumerateStructureTransformation(max_cell_size=8)-structures = trans.apply_transformation(struct, return_ranked_list=True)--# Returns list of ranked structures-for s in structures[:5]: # Top 5 structures- print(f"Energy: {s['energy']}, Structure: {s['structure']}")+disordered = SubstitutionTransformation(+ {"Fe": {"Fe": 0.5, "Mn": 0.5}}+).apply_transformation(parent)```-#### MagOrderingTransformation+Verify composition, charge model, oxidation states, occupancy sums, and whether+all intended sites—not just a selected sublattice—were transformed. Partial+occupancy is an average/disordered representation, not one ordered atomic+configuration.-Enumerate magnetic orderings.+## Removing species and sites```python-from pymatgen.transformations.advanced_transformations import MagOrderingTransformation+from pymatgen.transformations.standard_transformations import (+ RemoveSpeciesTransformation,+)-# Specify magnetic moments for each species-trans = MagOrderingTransformation({"Fe": 5.0, "Ni": 2.0})-mag_structures = trans.apply_transformation(struct, return_ranked_list=True)+child = RemoveSpeciesTransformation(["H"]).apply_transformation(parent)```-#### DopingTransformation+Removing species changes composition, charge, and possibly connectivity.+Never use it as silent parser cleanup. Record removed site indices/species and+validate charge/stoichiometry afterward.-Systematically dope a structure.+## Primitive and conventional cells```python-from pymatgen.transformations.advanced_transformations import DopingTransformation+from pymatgen.transformations.standard_transformations import (+ ConventionalCellTransformation,+ PrimitiveCellTransformation,+)-# Replace 12.5% of Fe sites with Mn-trans = DopingTransformation("Mn", min_length=10)-doped_structs = trans.apply_transformation(struct, return_ranked_list=True)+primitive = PrimitiveCellTransformation(+ tolerance=0.5,+).apply_transformation(parent)+conventional = ConventionalCellTransformation(+ symprec=0.01,+ angle_tolerance=5,+).apply_transformation(parent)```-#### ChargeBalanceTransformation+These results depend on symmetry tolerances and can change site order or site+properties. Compare formula and volume per atom, preserve exact tolerances, and+do not treat standardized cells from different conventions as byte-identical.-Balance charge in a structure by oxidation state manipulation.+## Strain and deformation```python-from pymatgen.transformations.advanced_transformations import ChargeBalanceTransformation+from pymatgen.transformations.standard_transformations import (+ DeformStructureTransformation,+)-trans = ChargeBalanceTransformation("Li")-charged_struct = trans.apply_transformation(struct)+deformed = DeformStructureTransformation(+ [[1.01, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]+).apply_transformation(parent)```-#### SlabTransformation+State whether a matrix is a deformation gradient, strain-like approximation,+or lattice transform. Bound determinant, condition number, minimum distances,+and strain magnitude. Generate positive and negative strains under one+manifest for tensor fitting.-Generate surface slabs.+## Oxidation-state decoration-```python-from pymatgen.transformations.advanced_transformations import SlabTransformation--trans = SlabTransformation(- miller_index=[1, 0, 0],- min_slab_size=10,- min_vacuum_size=10,- shift=0,- lll_reduce=True-)-slab = trans.apply_transformation(struct)-```--### Chaining Transformations+Oxidation states are inputs to several transformations and electrostatic+rankings. Decoration can be explicit or guessed. Prefer explicit mappings+grounded in chemistry:```python-from pymatgen.alchemy.materials import TransformedStructure--# Create transformed structure that tracks history-ts = TransformedStructure(struct, [])--# Apply multiple transformations-ts.append_transformation(SupercellTransformation([[2,0,0],[0,2,0],[0,0,2]]))-ts.append_transformation(SubstitutionTransformation({"Fe": "Mn"}))-ts.append_transformation(PrimitiveCellTransformation())--# Get final structure-final_struct = ts.final_structure--# View transformation history-print(ts.history)+decorated = parent.copy()+decorated.add_oxidation_state_by_element({"Li": 1, "O": -2})```-## Common Workflows+If a guesser is explicitly approved, bound complexity and preserve all+candidate assignments and assumptions. Do not present the first guess as a+measured charge state.-### Workflow 1: High-Throughput Structure Generation--Generate multiple structures for screening studies.+## Ordering disordered structures```python-from pymatgen.core import Structurefrom pymatgen.transformations.standard_transformations import (- SubstitutionTransformation,- SupercellTransformation+ OrderDisorderedStructureTransformation,)-from pymatgen.io.vasp.sets import MPRelaxSet-# Starting structure-base_struct = Structure.from_file("POSCAR")--# Define substitutions-dopants = ["Mn", "Co", "Ni", "Cu"]-structures = {}--for dopant in dopants:- # Create substituted structure- trans = SubstitutionTransformation({"Fe": dopant})- new_struct = trans.apply_transformation(base_struct)-- # Generate VASP inputs- vasp_input = MPRelaxSet(new_struct)- vasp_input.write_input(f"./calcs/Fe_{dopant}")-- structures[dopant] = new_struct--print(f"Generated {len(structures)} structures")+transformation = OrderDisorderedStructureTransformation()+ranked = transformation.apply_transformation(+ disordered,+ return_ranked_list=20,+)```-### Workflow 2: Phase Diagram Construction--Build and analyze phase diagrams from Materials Project data.--```python-from mp_api.client import MPRester-from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter-from pymatgen.core import Composition--# Get data from Materials Project-with MPRester() as mpr:- entries = mpr.get_entries_in_chemsys("Li-Fe-O")--# Build phase diagram-pd = PhaseDiagram(entries)--# Analyze specific composition-comp = Composition("LiFeO2")-e_above_hull = pd.get_e_above_hull(entries[0])+Ordering can grow combinatorially. Before running:-# Get decomposition products-decomp = pd.get_decomposition(comp)-print(f"Decomposition: {decomp}")+- verify rational occupancies and the required supercell+- require oxidation states if electrostatic ranking needs them+- cap maximum cell size, sites, candidates, runtime, RAM, and disk+- state the ranking model and ties+- preserve unreturned-candidate count when known-# Visualize-plotter = PDPlotter(pd)-plotter.show()-```+The top-ranked ordering is model-dependent, not a unique ground state.-### Workflow 3: Surface Energy Calculation+## EnumerateStructureTransformation and enumlib-Calculate surface energies from slab calculations.+`EnumerateStructureTransformation` generates symmetrically distinct orderings+and requires the external enumlib executables (`enum.x` and `makestr.x`).+Several advanced transformations, including magnetic ordering, can rely on+enumeration.-```python-from pymatgen.core.surface import SlabGenerator, generate_all_slabs-from pymatgen.io.vasp.sets import MPStaticSet, MPRelaxSet-from pymatgen.core import Structure--# Read bulk structure-bulk = Structure.from_file("bulk_POSCAR")--# Get bulk energy (from previous calculation)-from pymatgen.io.vasp import Vasprun-bulk_vasprun = Vasprun("bulk/vasprun.xml")-bulk_energy_per_atom = bulk_vasprun.final_energy / len(bulk)--# Generate slabs-miller_indices = [(1,0,0), (1,1,0), (1,1,1)]-surface_energies = {}--for miller in miller_indices:- slabgen = SlabGenerator(- bulk,- miller_index=miller,- min_slab_size=10,- min_vacuum_size=15,- center_slab=True- )-- slab = slabgen.get_slabs()[0]-- # Write VASP input for slab- relax = MPRelaxSet(slab)- relax.write_input(f"./slab_{miller[0]}{miller[1]}{miller[2]}")-- # After calculation, compute surface energy:- # slab_vasprun = Vasprun(f"slab_{miller[0]}{miller[1]}{miller[2]}/vasprun.xml")- # slab_energy = slab_vasprun.final_energy- # n_atoms = len(slab)- # area = slab.surface_area # in Ų- #- # # Surface energy (J/m²)- # surf_energy = (slab_energy - n_atoms * bulk_energy_per_atom) / (2 * area)- # surf_energy *= 16.021766 # Convert eV/Ų to J/m²- # surface_energies[miller] = surf_energy--print(f"Set up calculations for {len(miller_indices)} surfaces")-```+Treat enumlib as a separate native-code execution:-### Workflow 4: Band Structure Calculation+1. verify official source, version, build instructions, license, and hash+2. resolve the executable path explicitly+3. review exact argv and working directory+4. isolate untrusted inputs+5. enforce cell-size, candidate, CPU, RAM, disk, and wall-time limits+6. preserve stdout/stderr and exit status-Complete workflow for band structure calculations.+Do not install or invoke enumlib automatically.-```python-from pymatgen.core import Structure-from pymatgen.io.vasp.sets import MPRelaxSet, MPStaticSet, MPNonSCFSet-from pymatgen.symmetry.bandstructure import HighSymmKpath+## Doping and charge balance-# Step 1: Relaxation-struct = Structure.from_file("initial_POSCAR")-relax = MPRelaxSet(struct)-relax.write_input("./1_relax")+Advanced doping and charge-balance transformations encode chemical and+electrostatic assumptions. A requested dopant does not uniquely define:-# After relaxation, read structure-relaxed_struct = Structure.from_file("1_relax/CONTCAR")+- substituted host species/site+- oxidation state+- concentration/supercell+- compensating vacancies or co-dopants+- ordering-# Step 2: Static calculation-static = MPStaticSet(relaxed_struct)-static.write_input("./2_static")+Require those choices before execution and report every generated candidate.+Validate composition and net formal charge after each transformation.-# Step 3: Band structure (non-self-consistent)-kpath = HighSymmKpath(relaxed_struct)-nscf = MPNonSCFSet(relaxed_struct, mode="line") # Band structure mode-nscf.write_input("./3_bandstructure")+## Slabs and surfaces-# After calculations, analyze-from pymatgen.io.vasp import Vasprun-from pymatgen.electronic_structure.plotter import BSPlotter+`SlabTransformation` and `SlabGenerator` require explicit Miller index, slab+thickness, vacuum thickness, shift/termination, and cell-reduction choices.+Bound the number of terminations and generated structures. Record whether+sizes are in Å or unit planes.-vasprun = Vasprun("3_bandstructure/vasprun.xml")-bs = vasprun.get_band_structure(line_mode=True)+Never overwrite the bulk parent. Surface energies additionally require+consistent bulk/slab methods, atom/reference accounting, surface area, and+whether one or two equivalent surfaces are present.-print(f"Band gap: {bs.get_band_gap()}")+## Magnetic ordering-plotter = BSPlotter(bs)-plotter.save_plot("band_structure.png")-```+`MagOrderingTransformation` uses proposed magnetic moments and can enumerate+orderings. Record:-### Workflow 5: Molecular Dynamics Setup+- magnetic species and moment magnitudes/units (typically μB)+- collinear/non-collinear assumptions+- supercell and ordering constraints+- enumlib version if used+- candidate count and ranking method-Set up and analyze molecular dynamics simulations.+Generated magnetic arrangements are calculation inputs, not converged magnetic+ground states.-```python-from pymatgen.core import Structure-from pymatgen.io.vasp.sets import MVLRelaxSet-from pymatgen.io.vasp.inputs import Incar--# Read structure-struct = Structure.from_file("POSCAR")--# Create 2x2x2 supercell for MD-from pymatgen.transformations.standard_transformations import SupercellTransformation-trans = SupercellTransformation([[2,0,0],[0,2,0],[0,0,2]])-supercell = trans.apply_transformation(struct)--# Set up VASP input-md_input = MVLRelaxSet(supercell)--# Modify INCAR for MD-incar = md_input.incar-incar.update({- "IBRION": 0, # Molecular dynamics- "NSW": 1000, # Number of steps- "POTIM": 2, # Time step (fs)- "TEBEG": 300, # Initial temperature (K)- "TEEND": 300, # Final temperature (K)- "SMASS": 0, # NVT ensemble- "MDALGO": 2, # Nose-Hoover thermostat-})--md_input.incar = incar-md_input.write_input("./md_calc")-```--### Workflow 6: Diffusion Analysis--Analyze ion diffusion from AIMD trajectories.+## Track history with TransformedStructure```python-from pymatgen.io.vasp import Xdatcar-from pymatgen.analysis.diffusion.analyzer import DiffusionAnalyzer--# Read trajectory from XDATCAR-xdatcar = Xdatcar("XDATCAR")-structures = xdatcar.structures--# Analyze diffusion for specific species (e.g., Li)-analyzer = DiffusionAnalyzer.from_structures(- structures,- specie="Li",- temperature=300, # K- time_step=2, # fs- step_skip=10 # Skip initial equilibration+from pymatgen.alchemy.materials import TransformedStructure+from pymatgen.transformations.standard_transformations import (+ SubstitutionTransformation,+ SupercellTransformation,)-# Get diffusivity-diffusivity = analyzer.diffusivity # cm²/s-conductivity = analyzer.conductivity # mS/cm--# Get mean squared displacement-msd = analyzer.msd+tracked = TransformedStructure(parent.copy(), [])+tracked.append_transformation(SupercellTransformation([2, 2, 2]))+tracked.append_transformation(SubstitutionTransformation({"Na": "K"}))-# Plot MSD-analyzer.plot_msd()--print(f"Diffusivity: {diffusivity:.2e} cm²/s")-print(f"Conductivity: {conductivity:.2e} mS/cm")+child = tracked.final_structure+history = tracked.history```-### Workflow 7: Structure Prediction and Enumeration--Predict and enumerate possible structures.+The history is useful but not sufficient provenance. Also store:-```python-from pymatgen.core import Structure, Lattice-from pymatgen.transformations.advanced_transformations import (- EnumerateStructureTransformation,- SubstitutionTransformation-)+- input and output checksums+- warning stream+- exact versions and dependency lock+- user intent and acceptance criteria+- units and coordinate conventions+- external executable metadata-# Start with a known structure type (e.g., rocksalt)-lattice = Lattice.cubic(4.2)-struct = Structure.from_spacegroup("Fm-3m", lattice, ["Li", "O"], [[0,0,0], [0.5,0.5,0.5]])+Use strict JSON after schema validation; do not use pickle.-# Create disordered structure-from pymatgen.core import Species-species_on_site = {Species("Li"): 0.5, Species("Na"): 0.5}-struct[0] = species_on_site # Mixed occupancy on Li site+## Workflow 1: validated local derivation-# Enumerate all ordered structures-trans = EnumerateStructureTransformation(max_cell_size=4)-ordered_structs = trans.apply_transformation(struct, return_ranked_list=True)+1. Hash and validate the original.+2. Capture parser warnings, units, PBC, coordinate mode, occupancy/disorder,+ oxidation states, minimum distances, and site properties.+3. Define transformation and bounds in a JSON plan.+4. Apply to a copy.+5. Validate the child and compare composition/site/lattice invariants expected+ for that transformation.+6. Write to a new path.+7. Create an artifact manifest linking parent, plan, and child.-print(f"Found {len(ordered_structs)} distinct ordered structures")+Bundled helpers:-# Write all structures-for i, s_dict in enumerate(ordered_structs[:10]): # Top 10- s_dict['structure'].to(filename=f"ordered_struct_{i}.cif")+```bash+python scripts/composition_structure_validator.py structure input.cif+python scripts/artifact_manifest.py \+ --artifact input.cif --artifact transformed.json \+ --workflow "reviewed supercell derivation" --output manifest.json```-### Workflow 8: Elastic Constant Calculation--Calculate elastic constants using the stress-strain method.--```python-from pymatgen.core import Structure-from pymatgen.transformations.standard_transformations import DeformStructureTransformation-from pymatgen.io.vasp.sets import MPStaticSet--# Read equilibrium structure-struct = Structure.from_file("relaxed_POSCAR")--# Generate deformed structures-strains = [0.00, 0.01, 0.02, -0.01, -0.02] # Applied strains-deformation_sets = []--for strain in strains:- # Apply strain in different directions- trans = DeformStructureTransformation([[1+strain, 0, 0], [0, 1, 0], [0, 0, 1]])- deformed = trans.apply_transformation(struct)-- # Set up VASP calculation- static = MPStaticSet(deformed)- static.write_input(f"./strain_{strain:.2f}")--# After calculations, fit stress vs strain to get elastic constants-# from pymatgen.analysis.elasticity import ElasticTensor-# ... (collect stress tensors from OUTCAR)-# elastic_tensor = ElasticTensor.from_stress_list(stress_list)+## Workflow 2: disorder to bounded ordered candidates++1. Preserve the disordered parent as JSON/CIF.+2. Validate occupancy sums and intended site groups.+3. Define supercell/cell-size and candidate cap.+4. State oxidation states and ranking model.+5. Review enumlib native execution if required.+6. Generate no more than the approved number of candidates.+7. Validate each candidate and preserve mapping/rank.+8. Do not call rank 1 the ground state without an appropriate converged energy+ calculation.++## Workflow 3: compatible local phase diagram++1. Collect total energies and composition for one compatible method/correction+ scheme.+2. Preserve run and correction provenance per entry.+3. Include elemental endpoints and relevant competitors.+4. Write strict JSON with `energy_basis: total_per_entry`.+5. Run:++```bash+python scripts/phase_diagram_generator.py entries.json --analyze Li2O```-### Workflow 9: Adsorption Energy Calculation+6. Report eV/atom normalized outputs and dataset limitations.+7. Preserve the exact entries JSON and report checksum.-Calculate adsorption energies on surfaces.+## Workflow 4: VASP input preparation```python-from pymatgen.core import Structure, Molecule-from pymatgen.core.surface import SlabGenerator-from pymatgen.analysis.adsorption import AdsorbateSiteFinderfrom pymatgen.io.vasp.sets import MPRelaxSet-# Generate slab-bulk = Structure.from_file("bulk_POSCAR")-slabgen = SlabGenerator(bulk, (1,1,1), 10, 10)-slab = slabgen.get_slabs()[0]+input_set = MPRelaxSet(+ child,+ user_incar_settings={"ENCUT": 600},+)+```-# Find adsorption sites-asf = AdsorbateSiteFinder(slab)-ads_sites = asf.find_adsorption_sites()+Before `write_input()`:-# Create adsorbate-adsorbate = Molecule("O", [[0, 0, 0]])+- review every generated file and user override+- verify VASP/input-set version compatibility+- confirm functional, DFT+U, magnetism, spin/SOC, k-points, smearing, and+ convergence+- handle POTCARs only under the user's VASP license+- write to a new calculation directory-# Generate structures with adsorbate-ads_structs = asf.add_adsorbate(adsorbate, ads_sites["ontop"][0])+Pymatgen does not run VASP or establish convergence.-# Set up calculations-relax_slab = MPRelaxSet(slab)-relax_slab.write_input("./slab")+## Workflow 5: band-structure chain-relax_ads = MPRelaxSet(ads_structs)-relax_ads.write_input("./slab_with_adsorbate")+1. Relax under a documented method and verify convergence.+2. Parse the final structure to a new artifact.+3. Perform a compatible static calculation.+4. Generate a line-mode non-SCF calculation with a documented k-path and+ crystallographic setting.+5. Parse with projected eigenvalues disabled unless required.+6. Report method, structure, k-path, spin/SOC, Fermi convention, and numerical+ convergence with the gap.-# After calculations:-# E_ads = E(slab+adsorbate) - E(slab) - E(adsorbate_gas)-```+Each stage must link to the exact previous output checksum. Do not reuse a+stale structure or charge density silently.-### Workflow 10: High-Throughput Materials Screening+## Workflow 6: Materials Project to local analysis-Screen materials database for specific properties.+1. Dry-run a bounded query with explicit fields and limit.+2. Review CC BY attribution, citation, and computed-data limitations.+3. Execute only with `--execute` and the named `MP_API_KEY`.+4. Preserve retrieval time, query, fields, origins, client versions, and+ database release when available.+5. Validate downloaded structures locally.+6. Perform transformations/analysis offline on new derived artifacts.-```python-from mp_api.client import MPRester-from pymatgen.core import Structure-import pandas as pd--# Define screening criteria-def screen_material(material):- """Screen for potential battery cathode materials"""- criteria = {- "has_li": "Li" in material.composition.elements,- "stable": material.energy_above_hull < 0.05,- "good_voltage": 2.5 < material.formation_energy_per_atom < 4.5,- "electronically_conductive": material.band_gap < 0.5- }- return all(criteria.values()), criteria--# Query Materials Project-with MPRester() as mpr:- # Get potential materials- materials = mpr.materials.summary.search(- elements=["Li"],- energy_above_hull=(0, 0.05),- )-- results = []- for mat in materials:- passes, criteria = screen_material(mat)- if passes:- results.append({- "material_id": mat.material_id,- "formula": mat.formula_pretty,- "energy_above_hull": mat.energy_above_hull,- "band_gap": mat.band_gap,- })-- # Save results- df = pd.DataFrame(results)- df.to_csv("screened_materials.csv", index=False)-- print(f"Found {len(results)} promising materials")-```+The database object is computed input with provenance, not experimental truth.-## Best Practices for Workflows+## Candidate and output bounds-1. **Modular design**: Break workflows into discrete steps-2. **Error handling**: Check file existence and calculation convergence-3. **Documentation**: Track transformation history using `TransformedStructure`-4. **Version control**: Store input parameters and scripts in git-5. **Automation**: Use workflow managers (Fireworks, AiiDA) for complex pipelines-6. **Data management**: Organize calculations in clear directory structures-7. **Validation**: Always validate intermediate results before proceeding+Every automated workflow should cap:-## Integration with Workflow Tools+- input bytes and sites+- supercell determinant+- generated candidates/slabs/orderings+- neighbors, k-points, bands, and projected arrays+- JSON records/bytes and plot points+- CPU, RAM, disk, and wall time-Pymatgen integrates with several workflow management systems:+Stop on bound exhaustion and report partial progress; never silently truncate a+candidate set and present it as exhaustive.-- **Atomate**: Pre-built VASP workflows-- **Fireworks**: Workflow execution engine-- **AiiDA**: Provenance tracking and workflow management-- **Custodian**: Error correction and job monitoring+## Sources (verified 2026-07-23)-These tools provide robust automation for production calculations.+- [pymatgen transformations API](https://pymatgen.org/pymatgen.transformations.html)+- [pymatgen alchemy API](https://pymatgen.org/pymatgen.alchemy.html)+- [pymatgen symmetry API](https://pymatgen.org/pymatgen.symmetry.html)+- [pymatgen surface API](https://pymatgen.org/pymatgen.core.html)+- [pymatgen VASP sets API](https://pymatgen.org/pymatgen.io.vasp.html)+- [pymatgen installation and enumlib requirements](https://pymatgen.org/installation.html)+- [pymatgen changelog](https://pymatgen.org/CHANGES.html)+- [Official pymatgen tutorial series](https://github.com/computron/pymatgen_tutorials)diff --git a/skills/pymatgen/scripts/_common.py b/skills/pymatgen/scripts/_common.pynew file mode 100644index 00000000..d2e9ee6c--- /dev/null+++ b/skills/pymatgen/scripts/_common.py@@ -0,0 +1,316 @@+#!/usr/bin/env python3+"""Shared, standard-library-first helpers for the bundled pymatgen CLIs."""++from __future__ import annotations++import hashlib+import json+import math+import os+import warnings+from importlib.metadata import PackageNotFoundError, version+from pathlib import Path+from typing import Any+++PYMATGEN_VERSION = "2026.5.4"+PYMATGEN_CORE_VERSION = "2026.7.16"+MP_API_VERSION = "0.46.4"+DEFAULT_MAX_INPUT_BYTES = 50 * 1024 * 1024+DEFAULT_MAX_OUTPUT_BYTES = 20 * 1024 * 1024+DEFAULT_MAX_SITES = 10_000+ABSOLUTE_MAX_INPUT_BYTES = 512 * 1024 * 1024+ABSOLUTE_MAX_OUTPUT_BYTES = 100 * 1024 * 1024+ABSOLUTE_MAX_SITES = 100_000+ABSOLUTE_MAX_PAIRWISE_SITES = 1_000+++class CliError(ValueError):+ """A user-facing validation or safety error."""+++def reject_url(value: str, label: str = "path") -> None:+ """Reject URL-like values where a local path is required."""+ if "://" in value:+ raise CliError(f"{label} must be a local path, not a URL")+++def checked_input_file(+ value: str | Path,+ *,+ max_bytes: int = DEFAULT_MAX_INPUT_BYTES,+) -> Path:+ """Return a resolved, bounded regular input file."""+ if max_bytes > ABSOLUTE_MAX_INPUT_BYTES:+ raise CliError(+ f"input byte limit may not exceed {ABSOLUTE_MAX_INPUT_BYTES}"+ )+ raw = str(value)+ reject_url(raw, "input")+ path = Path(raw).expanduser()+ if path.is_symlink():+ raise CliError("symbolic-link inputs are not accepted")+ try:+ resolved = path.resolve(strict=True)+ except OSError as exc:+ raise CliError("input file does not exist or cannot be resolved") from exc+ if not resolved.is_file():+ raise CliError("input path is not a regular file")+ size = resolved.stat().st_size+ if size > max_bytes:+ raise CliError(f"input exceeds the {max_bytes}-byte limit")+ return resolved+++def checked_output_file(+ value: str | Path,+ *,+ input_paths: tuple[Path, ...] = (),+) -> Path:+ """Validate a new output path without creating or overwriting it."""+ raw = str(value)+ reject_url(raw, "output")+ path = Path(raw).expanduser()+ if ".." in path.parts:+ raise CliError("output path may not contain '..'")+ if path.exists() or path.is_symlink():+ raise CliError("output already exists; choose a new path")+ parent = path.parent.resolve(strict=False)+ if not parent.exists() or not parent.is_dir() or parent.is_symlink():+ raise CliError("output parent must be an existing, non-symlink directory")+ resolved = path.resolve(strict=False)+ for input_path in input_paths:+ if resolved == input_path.resolve(strict=True):+ raise CliError("output may not overwrite an input")+ return resolved+++def _reject_duplicate_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ raise CliError(f"duplicate JSON key: {key!r}")+ result[key] = value+ return result+++def _reject_constant(value: str) -> None:+ raise CliError(f"non-finite JSON number is not allowed: {value}")+++def load_strict_json(+ value: str | Path,+ *,+ max_bytes: int = DEFAULT_MAX_INPUT_BYTES,+) -> tuple[Any, Path]:+ """Load bounded JSON while rejecting duplicate keys and NaN/Infinity."""+ path = checked_input_file(value, max_bytes=max_bytes)+ try:+ payload = json.loads(+ path.read_text(encoding="utf-8"),+ object_pairs_hook=_reject_duplicate_pairs,+ parse_constant=_reject_constant,+ )+ except UnicodeDecodeError as exc:+ raise CliError("JSON input must be UTF-8") from exc+ except json.JSONDecodeError as exc:+ raise CliError(f"invalid JSON at line {exc.lineno}, column {exc.colno}") from exc+ return payload, path+++def json_text(payload: Any, *, pretty: bool = True) -> str:+ """Serialize strict JSON with stable ordering."""+ return json.dumps(+ payload,+ allow_nan=False,+ ensure_ascii=False,+ indent=2 if pretty else None,+ sort_keys=True,+ )+++def emit_json(payload: Any) -> None:+ """Print a strict JSON report."""+ print(json_text(payload))+++def write_text_new(+ path: Path,+ text: str,+ *,+ max_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,+) -> None:+ """Create a UTF-8 text file exclusively after enforcing a byte bound."""+ if max_bytes > ABSOLUTE_MAX_OUTPUT_BYTES:+ raise CliError(+ f"output byte limit may not exceed {ABSOLUTE_MAX_OUTPUT_BYTES}"+ )+ encoded = text.encode("utf-8")+ if len(encoded) > max_bytes:+ raise CliError(f"output exceeds the {max_bytes}-byte limit")+ try:+ with path.open("x", encoding="utf-8", newline="\n") as handle:+ handle.write(text)+ if text and not text.endswith("\n"):+ handle.write("\n")+ except FileExistsError as exc:+ raise CliError("output appeared concurrently; nothing was overwritten") from exc+++def write_json_new(+ path: Path,+ payload: Any,+ *,+ max_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,+) -> None:+ """Create a strict JSON file exclusively."""+ write_text_new(path, json_text(payload), max_bytes=max_bytes)+++def finite_float(value: Any, label: str) -> float:+ """Parse a finite float."""+ if isinstance(value, bool):+ raise CliError(f"{label} must be a finite number")+ try:+ number = float(value)+ except (TypeError, ValueError) as exc:+ raise CliError(f"{label} must be a finite number") from exc+ if not math.isfinite(number):+ raise CliError(f"{label} must be finite")+ return number+++def positive_int(value: str) -> int:+ """Argparse converter for positive integers."""+ try:+ number = int(value)+ except ValueError as exc:+ raise ValueError("must be an integer") from exc+ if number < 1:+ raise ValueError("must be at least 1")+ return number+++def package_versions(names: tuple[str, ...]) -> dict[str, str | None]:+ """Return installed distribution versions without importing packages."""+ result: dict[str, str | None] = {}+ for name in names:+ try:+ result[name] = version(name)+ except PackageNotFoundError:+ result[name] = None+ return result+++def sha256_file(path: Path, *, chunk_bytes: int = 1024 * 1024) -> str:+ """Hash a local file without loading it all into memory."""+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ while chunk := handle.read(chunk_bytes):+ digest.update(chunk)+ return digest.hexdigest()+++def structure_oxidation_summary(structure: Any) -> dict[str, Any]:+ """Summarize oxidation-state decoration without guessing states."""+ decorated = 0+ total = 0+ values: set[float] = set()+ for site in structure:+ for specie in site.species:+ total += 1+ if hasattr(specie, "oxi_state"):+ decorated += 1+ values.add(float(specie.oxi_state))+ return {+ "decorated_species_components": decorated,+ "species_components": total,+ "all_decorated": bool(total) and decorated == total,+ "partially_decorated": 0 < decorated < total,+ "oxidation_states": sorted(values),+ "guessed": False,+ }+++def load_structure(+ value: str | Path,+ *,+ structure_index: int = 0,+ max_bytes: int = DEFAULT_MAX_INPUT_BYTES,+ max_sites: int = DEFAULT_MAX_SITES,+) -> tuple[Any, Path, dict[str, Any]]:+ """Load one bounded structure and preserve all parser warnings."""+ if max_sites > ABSOLUTE_MAX_SITES:+ raise CliError(f"site limit may not exceed {ABSOLUTE_MAX_SITES}")+ path = checked_input_file(value, max_bytes=max_bytes)+ warning_messages: list[str] = []+ parser_messages: list[str] = []+ structure_count = 1+ try:+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ lower_name = path.name.casefold()+ if lower_name.endswith((".cif", ".cif.gz", ".cif.bz2", ".mcif")):+ from pymatgen.io.cif import CifParser++ parser = CifParser(path)+ structures = parser.parse_structures(+ primitive=False,+ check_occu=True,+ on_error="raise",+ )+ parser_messages = [str(item) for item in parser.warnings]+ structure_count = len(structures)+ if not 0 <= structure_index < structure_count:+ raise CliError(+ f"structure index {structure_index} is outside "+ f"0..{structure_count - 1}"+ )+ structure = structures[structure_index]+ else:+ from pymatgen.core import Structure++ if structure_index != 0:+ raise CliError(+ "non-CIF readers expose one structure; use index 0"+ )+ structure = Structure.from_file(path, primitive=False, sort=False)+ warning_messages = [+ f"{item.category.__name__}: {item.message}" for item in caught+ ]+ except CliError:+ raise+ except (OSError, TypeError, ValueError) as exc:+ raise CliError(+ f"pymatgen could not parse {path.name}: {type(exc).__name__}: {exc}"+ ) from exc+ if len(structure) > max_sites:+ raise CliError(+ f"structure has {len(structure)} sites, above the {max_sites}-site limit"+ )+ report = {+ "input_name": path.name,+ "input_bytes": path.stat().st_size,+ "structure_index": structure_index,+ "structures_in_file": structure_count,+ "python_warnings": warning_messages,+ "parser_warnings": parser_messages,+ "warnings_acknowledged": False,+ }+ return structure, path, report+++def safe_error_message(exc: BaseException, *, secret: str | None = None) -> str:+ """Return a bounded error message with a known secret redacted."""+ message = f"{type(exc).__name__}: {exc}"+ if secret:+ message = message.replace(secret, "[REDACTED]")+ return message[:1000]+++def atomic_link_from_temp(temp_path: Path, output_path: Path) -> None:+ """Link a completed temporary artifact into place without overwriting."""+ try:+ os.link(temp_path, output_path)+ except FileExistsError as exc:+ raise CliError("output appeared concurrently; nothing was overwritten") from excdiff --git a/skills/pymatgen/scripts/artifact_manifest.py b/skills/pymatgen/scripts/artifact_manifest.pynew file mode 100644index 00000000..61fb6afe--- /dev/null+++ b/skills/pymatgen/scripts/artifact_manifest.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""Create a bounded checksum and provenance manifest for explicit local files."""++from __future__ import annotations++import argparse+import mimetypes+import platform+import re+from datetime import datetime, timezone++from _common import (+ CliError,+ DEFAULT_MAX_OUTPUT_BYTES,+ MP_API_VERSION,+ PYMATGEN_CORE_VERSION,+ PYMATGEN_VERSION,+ checked_input_file,+ checked_output_file,+ emit_json,+ package_versions,+ positive_int,+ sha256_file,+ write_json_new,+)+++SENSITIVE_NAME = re.compile(+ r"(^|[._-])(?:env|secret|token|credential|api[-_]?key|private[-_]?key)"+ r"($|[._-])",+ re.IGNORECASE,+)+MAX_FILES = 100+MAX_TOTAL_BYTES = 2 * 1024 * 1024 * 1024+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Hash explicitly listed local artifacts and create a new JSON "+ "provenance manifest. Directories, symlinks, and likely secret files "+ "are refused."+ )+ )+ parser.add_argument(+ "--artifact",+ action="append",+ required=True,+ help="Local regular file to include (repeatable)",+ )+ parser.add_argument("--output", required=True, help="New manifest JSON path")+ parser.add_argument(+ "--workflow",+ required=True,+ help="Short workflow label; do not include credentials or full commands",+ )+ parser.add_argument(+ "--source",+ action="append",+ default=[],+ help="Short source/citation URL or identifier (repeatable)",+ )+ parser.add_argument(+ "--max-file-bytes",+ type=positive_int,+ default=512 * 1024 * 1024,+ )+ parser.add_argument(+ "--max-total-bytes",+ type=positive_int,+ default=MAX_TOTAL_BYTES,+ )+ parser.add_argument(+ "--max-output-bytes",+ type=positive_int,+ default=DEFAULT_MAX_OUTPUT_BYTES,+ )+ return parser+++def main() -> int:+ args = build_parser().parse_args()+ try:+ if len(args.artifact) > MAX_FILES:+ raise CliError(f"at most {MAX_FILES} artifacts may be listed")+ if args.max_total_bytes > MAX_TOTAL_BYTES:+ raise CliError("--max-total-bytes may not exceed 2 GiB")+ if not args.workflow.strip() or len(args.workflow) > 200:+ raise CliError("--workflow must be a non-empty label of at most 200 chars")+ if any(len(source) > 2000 for source in args.source):+ raise CliError("--source values may contain at most 2000 chars")+ output = checked_output_file(args.output)+ paths = []+ seen = set()+ total = 0+ for value in args.artifact:+ path = checked_input_file(value, max_bytes=args.max_file_bytes)+ if path == output:+ raise CliError("manifest output cannot also be an input artifact")+ if SENSITIVE_NAME.search(path.name):+ raise CliError(+ f"refusing likely credential-bearing artifact name: {path.name!r}"+ )+ if path in seen:+ raise CliError(f"duplicate artifact: {path.name!r}")+ seen.add(path)+ total += path.stat().st_size+ if total > args.max_total_bytes:+ raise CliError("artifact set exceeds --max-total-bytes")+ paths.append(path)+ records = []+ for path in paths:+ stat = path.stat()+ records.append(+ {+ "name": path.name,+ "bytes": stat.st_size,+ "sha256": sha256_file(path),+ "media_type": mimetypes.guess_type(path.name)[0],+ "modified_at_utc": datetime.fromtimestamp(+ stat.st_mtime, timezone.utc+ ).isoformat(),+ }+ )+ manifest = {+ "schema_version": "1.0",+ "created_at_utc": datetime.now(timezone.utc).isoformat(),+ "workflow": args.workflow,+ "sources": args.source,+ "software": {+ "expected_snapshot": {+ "pymatgen": PYMATGEN_VERSION,+ "pymatgen-core": PYMATGEN_CORE_VERSION,+ "mp-api": MP_API_VERSION,+ },+ "python": platform.python_version(),+ "installed": package_versions(+ ("pymatgen", "pymatgen-core", "mp-api")+ ),+ },+ "artifacts": records,+ "artifact_count": len(records),+ "total_bytes": total,+ "contract": {+ "network_accessed": False,+ "directories_traversed": False,+ "symlinks_followed": False,+ "artifact_contents_emitted": False,+ "credentials_read": False,+ "pickle_used": False,+ "existing_files_overwritten": False,+ },+ }+ write_json_new(output, manifest, max_bytes=args.max_output_bytes)+ emit_json(+ {+ "ok": True,+ "output": output.name,+ "artifact_count": len(records),+ "total_bytes": total,+ "overwrote_existing": False,+ "network_accessed": False,+ }+ )+ return 0+ except (CliError, OSError, TypeError, ValueError) as exc:+ emit_json({"ok": False, "error": f"{type(exc).__name__}: {exc}"[:1000]})+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pymatgen/scripts/composition_structure_validator.py b/skills/pymatgen/scripts/composition_structure_validator.pynew file mode 100644index 00000000..1be54959--- /dev/null+++ b/skills/pymatgen/scripts/composition_structure_validator.py@@ -0,0 +1,300 @@+#!/usr/bin/env python3+"""Validate a composition or local periodic structure without modifying it."""++from __future__ import annotations++import argparse+import math+from typing import Any++from _common import (+ ABSOLUTE_MAX_PAIRWISE_SITES,+ CliError,+ DEFAULT_MAX_INPUT_BYTES,+ DEFAULT_MAX_OUTPUT_BYTES,+ DEFAULT_MAX_SITES,+ checked_output_file,+ emit_json,+ load_structure,+ positive_int,+ structure_oxidation_summary,+ write_json_new,+)+++def validate_composition(+ formula: str,+ *,+ guess_oxidation_states: bool,+) -> dict[str, Any]:+ """Parse a strict formula and optionally run a bounded oxidation-state guess."""+ if len(formula) > 500:+ raise CliError("formula exceeds 500 characters")+ from pymatgen.core import Composition++ try:+ composition = Composition(formula, strict=True)+ except (TypeError, ValueError) as exc:+ raise CliError(f"invalid strict composition: {exc}") from exc+ errors: list[str] = []+ warnings_list: list[str] = []+ if composition.num_atoms <= 0:+ errors.append("composition_has_no_positive_amount")+ if any(float(amount) <= 0 for amount in composition.values()):+ errors.append("non_positive_species_amount")+ species_have_oxidation = [+ hasattr(specie, "oxi_state") for specie in composition+ ]+ explicit_charge = (+ sum(+ float(amount) * float(specie.oxi_state)+ for specie, amount in composition.items()+ )+ if all(species_have_oxidation)+ else None+ )+ if not all(species_have_oxidation):+ warnings_list.append("oxidation_states_not_fully_explicit")+ guesses: list[dict[str, float]] | None = None+ if guess_oxidation_states:+ if len(composition.elements) > 6 or composition.num_atoms > 100:+ raise CliError(+ "oxidation-state guessing is limited to 6 elements and 100 atoms"+ )+ raw_guesses = composition.oxi_state_guesses()+ guesses = [+ {str(element): float(state) for element, state in guess.items()}+ for guess in raw_guesses[:20]+ ]+ if len(raw_guesses) > 20:+ warnings_list.append("oxidation_state_guesses_truncated_to_20")+ return {+ "ok": not errors,+ "kind": "composition",+ "input_formula": formula,+ "formula": composition.formula,+ "reduced_formula": composition.reduced_formula,+ "hill_formula": composition.hill_formula,+ "chemical_system": composition.chemical_system,+ "num_atoms_in_formula": float(composition.num_atoms),+ "mass_amu": float(composition.weight),+ "amounts": {+ str(specie): float(amount)+ for specie, amount in sorted(+ composition.items(), key=lambda item: str(item[0])+ )+ },+ "formal_charge_from_explicit_oxidation_states": explicit_charge,+ "oxidation_state_guesses": guesses,+ "oxidation_state_guess_requested": guess_oxidation_states,+ "errors": errors,+ "warnings": warnings_list,+ "chemical_validity_established": False,+ }+++def minimum_distance(structure: Any, limit: int) -> tuple[float | None, list[int] | None]:+ """Find a minimum pair distance when the quadratic calculation is bounded."""+ if len(structure) < 2 or len(structure) > limit:+ return None, None+ best = math.inf+ pair: list[int] | None = None+ for first in range(len(structure)):+ for second in range(first + 1, len(structure)):+ distance = float(structure.get_distance(first, second))+ if distance < best:+ best = distance+ pair = [first, second]+ return (best if math.isfinite(best) else None), pair+++def validate_structure(structure: Any, args: argparse.Namespace) -> dict[str, Any]:+ """Check representation invariants and common structural hazards."""+ errors: list[str] = []+ warnings_list: list[str] = []+ lattice = structure.lattice+ if not math.isfinite(float(structure.volume)) or structure.volume <= 0:+ errors.append("non_positive_or_non_finite_lattice_volume")+ if any(+ not math.isfinite(float(value))+ for row in lattice.matrix+ for value in row+ ):+ errors.append("non_finite_lattice_component")+ occupancy_issues: list[dict[str, Any]] = []+ outside_unit_cell = 0+ for index, site in enumerate(structure):+ occupancy = sum(float(value) for value in site.species.values())+ if occupancy <= 0 or occupancy > 1 + args.occupancy_tolerance:+ occupancy_issues.append(+ {"site_index": index, "occupancy_sum": occupancy}+ )+ if any(not math.isfinite(float(value)) for value in site.frac_coords):+ errors.append(f"non_finite_fractional_coordinate_at_site_{index}")+ if any(float(value) < 0 or float(value) >= 1 for value in site.frac_coords):+ outside_unit_cell += 1+ if occupancy_issues:+ errors.append("site_occupancy_outside_allowed_range")+ if not structure.is_ordered:+ warnings_list.append(+ "partial_occupancies_or_disorder_present; downstream methods may reject it"+ )+ if outside_unit_cell:+ warnings_list.append(+ f"{outside_unit_cell} sites have fractional coordinates outside [0, 1); "+ "they may be periodic images, but coordinate convention must be explicit"+ )+ oxidation = structure_oxidation_summary(structure)+ if not oxidation["all_decorated"]:+ warnings_list.append("oxidation_states_are_not_fully_explicit")+ distance, pair = minimum_distance(structure, args.max_distance_sites)+ if distance is None and len(structure) > args.max_distance_sites:+ warnings_list.append(+ "minimum-distance check omitted because the quadratic site limit was exceeded"+ )+ elif distance is not None and distance < args.min_distance:+ errors.append("sites_closer_than_minimum_distance")+ return {+ "ok": not errors,+ "kind": "periodic_structure",+ "units": {+ "length": "angstrom",+ "angle": "degree",+ "volume": "angstrom^3",+ "density": "g/cm^3",+ },+ "formula": structure.composition.reduced_formula,+ "site_count": len(structure),+ "ordered": bool(structure.is_ordered),+ "periodic_boundary_conditions": [+ bool(value) for value in structure.lattice.pbc+ ],+ "lattice": {+ "matrix_rows_angstrom": [+ [float(value) for value in row] for row in lattice.matrix+ ],+ "volume_angstrom_cubed": float(structure.volume),+ "density_g_cm3": float(structure.density),+ },+ "coordinates_interpreted_as": "fractional",+ "sites_outside_canonical_unit_cell": outside_unit_cell,+ "occupancy_tolerance": args.occupancy_tolerance,+ "occupancy_issues": occupancy_issues[:100],+ "occupancy_issues_omitted": max(0, len(occupancy_issues) - 100),+ "oxidation_states": oxidation,+ "minimum_periodic_distance_angstrom": distance,+ "minimum_distance_pair": pair,+ "minimum_allowed_distance_angstrom": args.min_distance,+ "errors": errors,+ "warnings": warnings_list,+ "scientific_validity_established": False,+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Validate a composition or bounded local periodic structure. "+ "No files are modified and oxidation states are never guessed implicitly."+ )+ )+ subparsers = parser.add_subparsers(dest="command", required=True)+ composition = subparsers.add_parser("composition", help="Validate a formula")+ composition.add_argument("formula")+ composition.add_argument(+ "--guess-oxidation-states",+ action="store_true",+ help="Explicitly run pymatgen's bounded oxidation-state guesser",+ )+ composition.add_argument("--output", help="New JSON output; default stdout")++ structure = subparsers.add_parser(+ "structure", help="Validate a local periodic structure"+ )+ structure.add_argument("structure_file")+ structure.add_argument("--structure-index", type=int, default=0)+ structure.add_argument("--output", help="New JSON output; default stdout")+ structure.add_argument("--min-distance", type=float, default=0.5)+ structure.add_argument("--occupancy-tolerance", type=float, default=1e-6)+ structure.add_argument(+ "--max-input-bytes",+ type=positive_int,+ default=DEFAULT_MAX_INPUT_BYTES,+ )+ structure.add_argument(+ "--max-sites", type=positive_int, default=DEFAULT_MAX_SITES+ )+ structure.add_argument(+ "--max-distance-sites", type=positive_int, default=500+ )+ for child in (composition, structure):+ child.add_argument(+ "--max-output-bytes",+ type=positive_int,+ default=DEFAULT_MAX_OUTPUT_BYTES,+ )+ return parser+++def main() -> int:+ args = build_parser().parse_args()+ try:+ input_paths: tuple[Any, ...] = ()+ if args.command == "composition":+ report = validate_composition(+ args.formula,+ guess_oxidation_states=args.guess_oxidation_states,+ )+ else:+ if args.structure_index < 0:+ raise CliError("--structure-index must be non-negative")+ if not math.isfinite(args.min_distance) or args.min_distance <= 0:+ raise CliError("--min-distance must be finite and positive")+ if (+ not math.isfinite(args.occupancy_tolerance)+ or args.occupancy_tolerance < 0+ ):+ raise CliError(+ "--occupancy-tolerance must be finite and non-negative"+ )+ if args.max_distance_sites > ABSOLUTE_MAX_PAIRWISE_SITES:+ raise CliError(+ f"--max-distance-sites may not exceed "+ f"{ABSOLUTE_MAX_PAIRWISE_SITES}"+ )+ structure, input_path, parse_report = load_structure(+ args.structure_file,+ structure_index=args.structure_index,+ max_bytes=args.max_input_bytes,+ max_sites=args.max_sites,+ )+ report = validate_structure(structure, args)+ report["input"] = parse_report+ input_paths = (input_path,)+ if args.output:+ output_path = checked_output_file(+ args.output,+ input_paths=input_paths,+ )+ write_json_new(+ output_path,+ report,+ max_bytes=args.max_output_bytes,+ )+ emit_json(+ {+ "ok": report["ok"],+ "output": output_path.name,+ "overwrote_existing": False,+ }+ )+ else:+ emit_json(report)+ return 0 if report["ok"] else 2+ except (CliError, ImportError, OSError, RuntimeError, TypeError, ValueError) as exc:+ emit_json({"ok": False, "error": f"{type(exc).__name__}: {exc}"[:1000]})+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pymatgen/scripts/io_conversion_plan.py b/skills/pymatgen/scripts/io_conversion_plan.pynew file mode 100644index 00000000..e165d17c--- /dev/null+++ b/skills/pymatgen/scripts/io_conversion_plan.py@@ -0,0 +1,204 @@+#!/usr/bin/env python3+"""Create a dependency-free, non-executing structure conversion plan."""++from __future__ import annotations++import argparse++from _common import (+ CliError,+ DEFAULT_MAX_OUTPUT_BYTES,+ checked_output_file,+ emit_json,+ positive_int,+ write_json_new,+)+++FORMAT_CAPABILITIES = {+ "cif": {+ "periodic": True,+ "disorder": True,+ "oxidation_states": "format-dependent",+ "site_properties": "limited",+ "coordinate_modes": ["fractional"],+ },+ "cssr": {+ "periodic": True,+ "disorder": False,+ "oxidation_states": False,+ "site_properties": False,+ "coordinate_modes": ["fractional"],+ },+ "json": {+ "periodic": True,+ "disorder": True,+ "oxidation_states": True,+ "site_properties": True,+ "coordinate_modes": ["fractional", "cartesian-with-explicit-flag"],+ },+ "poscar": {+ "periodic": True,+ "disorder": False,+ "oxidation_states": False,+ "site_properties": "selective-dynamics/velocity-specific",+ "coordinate_modes": ["direct", "cartesian"],+ },+ "xsf": {+ "periodic": True,+ "disorder": False,+ "oxidation_states": False,+ "site_properties": False,+ "coordinate_modes": ["cartesian"],+ },+ "xyz": {+ "periodic": False,+ "disorder": False,+ "oxidation_states": False,+ "site_properties": False,+ "coordinate_modes": ["cartesian"],+ },+}+++def build_plan(args: argparse.Namespace) -> dict:+ """Build a conversion contract without opening any files."""+ target = FORMAT_CAPABILITIES[args.output_format]+ blockers: list[str] = []+ risks: list[str] = []+ if args.kind == "molecule":+ blockers.append(+ "the bundled structure_converter accepts periodic Structure objects only"+ )+ if args.periodic and not target["periodic"]:+ risks.append("target drops lattice vectors and periodic boundary conditions")+ if args.disordered and target["disorder"] is not True:+ blockers.append("target cannot faithfully represent partial occupancies")+ if args.oxidation_states and target["oxidation_states"] is not True:+ risks.append("target may drop oxidation-state decoration")+ if args.site_properties and target["site_properties"] is not True:+ risks.append("target may drop arbitrary site properties")+ if args.output_format == "poscar" and args.coordinate_mode == "not-applicable":+ blockers.append("POSCAR requires direct or cartesian coordinate mode")+ if args.output_format != "poscar" and args.coordinate_mode != "not-applicable":+ blockers.append("coordinate-mode flag is only accepted for POSCAR output")+ argv = [+ "python",+ "scripts/structure_converter.py",+ args.input,+ args.output,+ "--output-format",+ args.output_format,+ "--coordinate-mode",+ args.coordinate_mode,+ ]+ if risks:+ argv.append("--allow-lossy")+ return {+ "ok": not blockers,+ "action": "io_conversion_plan",+ "executed": False,+ "files_opened": False,+ "network_accessed": False,+ "source": {+ "path_as_provided": args.input,+ "format": args.input_format,+ "kind": args.kind,+ "periodic": args.periodic,+ "has_disorder": args.disordered,+ "has_oxidation_states": args.oxidation_states,+ "has_site_properties": args.site_properties,+ },+ "target": {+ "path_as_provided": args.output,+ "format": args.output_format,+ "coordinate_mode": args.coordinate_mode,+ "capabilities": target,+ },+ "blockers": blockers,+ "representation_risks": risks,+ "reviewed_argv": argv if not blockers else None,+ "requirements_before_execution": [+ "Inspect parser warnings and all structures in multi-block CIF files.",+ "Validate units, occupancies, oxidation states, lattice, and coordinate mode.",+ "Use a new output path; never overwrite the source or an existing artifact.",+ "Round-trip and scientifically compare the result before downstream use.",+ ],+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Plan, but do not run, a local pymatgen conversion. No input file is "+ "opened and no package import or network call occurs."+ )+ )+ parser.add_argument("--input", required=True, help="Input path for disclosure")+ parser.add_argument("--output", required=True, help="Intended new output path")+ parser.add_argument(+ "--input-format",+ required=True,+ choices=tuple(FORMAT_CAPABILITIES),+ )+ parser.add_argument(+ "--output-format",+ required=True,+ choices=tuple(FORMAT_CAPABILITIES),+ )+ parser.add_argument("--kind", choices=("structure", "molecule"), default="structure")+ periodicity = parser.add_mutually_exclusive_group()+ periodicity.add_argument("--periodic", action="store_true", default=True)+ periodicity.add_argument(+ "--nonperiodic", action="store_false", dest="periodic"+ )+ parser.add_argument("--disordered", action="store_true")+ parser.add_argument("--oxidation-states", action="store_true")+ parser.add_argument("--site-properties", action="store_true")+ parser.add_argument(+ "--coordinate-mode",+ choices=("direct", "cartesian", "not-applicable"),+ default="not-applicable",+ )+ parser.add_argument("--plan-output", help="New JSON file for this plan")+ parser.add_argument(+ "--max-output-bytes",+ type=positive_int,+ default=DEFAULT_MAX_OUTPUT_BYTES,+ )+ return parser+++def main() -> int:+ args = build_parser().parse_args()+ try:+ if "://" in args.input or "://" in args.output:+ raise CliError("conversion paths must be local, not URLs")+ plan = build_plan(args)+ if args.plan_output:+ output = checked_output_file(args.plan_output)+ write_json_new(output, plan, max_bytes=args.max_output_bytes)+ emit_json(+ {+ "ok": plan["ok"],+ "plan_output": output.name,+ "executed": False,+ "overwrote_existing": False,+ }+ )+ else:+ emit_json(plan)+ return 0 if plan["ok"] else 2+ except (CliError, OSError, TypeError, ValueError) as exc:+ emit_json(+ {+ "ok": False,+ "error": f"{type(exc).__name__}: {exc}"[:1000],+ "executed": False,+ }+ )+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pymatgen/scripts/mp_query.py b/skills/pymatgen/scripts/mp_query.pynew file mode 100644index 00000000..e0e04c85--- /dev/null+++ b/skills/pymatgen/scripts/mp_query.py@@ -0,0 +1,416 @@+#!/usr/bin/env python3+"""Plan or explicitly execute one bounded Materials Project summary query."""++from __future__ import annotations++import argparse+import math+import os+import re+from datetime import datetime, timezone+from typing import Any++from _common import (+ CliError,+ DEFAULT_MAX_OUTPUT_BYTES,+ MP_API_VERSION,+ PYMATGEN_CORE_VERSION,+ PYMATGEN_VERSION,+ checked_output_file,+ emit_json,+ json_text,+ package_versions,+ positive_int,+ safe_error_message,+ write_json_new,+)+++FIELD_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,79}$")+MATERIAL_ID_PATTERN = re.compile(r"^(?:mp|mvc)-[0-9]+$")+TOKEN_PATTERN = re.compile(r"^[A-Za-z0-9.+\-()]+$")+MAX_RESULTS = 100+MAX_FIELDS = 20+MAX_MATERIAL_IDS = 100+++def csv_tokens(value: str | None, label: str) -> list[str] | None:+ """Parse a bounded, unique comma-separated token list."""+ if value is None:+ return None+ tokens = [token.strip() for token in value.split(",") if token.strip()]+ if not tokens:+ raise CliError(f"{label} must contain at least one token")+ if len(tokens) > 100:+ raise CliError(f"{label} may contain at most 100 tokens")+ if any(not TOKEN_PATTERN.fullmatch(token) for token in tokens):+ raise CliError(f"{label} contains unsupported characters")+ return list(dict.fromkeys(tokens))+++def parse_fields(value: str) -> list[str]:+ """Parse explicit response fields."""+ fields = [field.strip() for field in value.split(",") if field.strip()]+ fields = list(dict.fromkeys(fields))+ if not fields:+ raise CliError("--fields must contain at least one field")+ if len(fields) > MAX_FIELDS:+ raise CliError(f"--fields may contain at most {MAX_FIELDS} fields")+ invalid = [field for field in fields if not FIELD_PATTERN.fullmatch(field)]+ if invalid:+ raise CliError(f"invalid field names: {invalid}")+ return fields+++def checked_range(+ values: list[float] | None,+ label: str,+ *,+ non_negative: bool = False,+) -> tuple[float, float] | None:+ """Validate an inclusive two-number range."""+ if values is None:+ return None+ low, high = values+ if not all(math.isfinite(value) for value in (low, high)):+ raise CliError(f"{label} bounds must be finite")+ if low > high:+ raise CliError(f"{label} minimum must not exceed maximum")+ if non_negative and low < 0:+ raise CliError(f"{label} must be non-negative")+ return float(low), float(high)+++def query_contract(args: argparse.Namespace) -> dict[str, Any]:+ """Validate arguments and return the exact public search kwargs."""+ if len(args.material_id) > MAX_MATERIAL_IDS:+ raise CliError(+ f"--material-id may be repeated at most {MAX_MATERIAL_IDS} times"+ )+ invalid_ids = [+ item+ for item in args.material_id+ if not MATERIAL_ID_PATTERN.fullmatch(item)+ ]+ if invalid_ids:+ raise CliError(f"invalid Materials Project IDs: {invalid_ids}")+ for label, value in (("--formula", args.formula), ("--chemsys", args.chemsys)):+ if value is not None and (+ len(value) > 200 or not TOKEN_PATTERN.fullmatch(value)+ ):+ raise CliError(f"{label} contains unsupported characters")+ elements = csv_tokens(args.elements, "--elements")+ exclude_elements = csv_tokens(args.exclude_elements, "--exclude-elements")+ energy_range = checked_range(+ args.energy_above_hull,+ "--energy-above-hull",+ non_negative=True,+ )+ band_gap = checked_range(args.band_gap, "--band-gap", non_negative=True)+ stable = None+ if args.is_stable != "any":+ stable = args.is_stable == "true"+ fields = parse_fields(args.fields)+ effective_fields = list(dict.fromkeys(["material_id", *fields]))+ filters: dict[str, Any] = {+ "material_ids": args.material_id or None,+ "formula": args.formula,+ "chemsys": args.chemsys,+ "elements": elements,+ "exclude_elements": exclude_elements,+ "energy_above_hull": energy_range,+ "band_gap": band_gap,+ "is_stable": stable,+ }+ if not any(value is not None for value in filters.values()):+ raise CliError("at least one query filter is required")+ search_kwargs = {+ key: value for key, value in filters.items() if value is not None+ }+ search_kwargs.update(+ {+ "fields": effective_fields,+ "all_fields": False,+ "num_chunks": 1,+ "chunk_size": args.limit,+ }+ )+ return {+ "filters": filters,+ "requested_fields": fields,+ "effective_fields": effective_fields,+ "search_kwargs": search_kwargs,+ }+++def plan_payload(+ args: argparse.Namespace,+ contract: dict[str, Any],+) -> dict[str, Any]:+ """Disclose network, credential, cache, field, limit, and output behavior."""+ return {+ "ok": True,+ "action": "materials_project_summary_query",+ "execute_requested": bool(args.execute),+ "network_will_be_accessed": bool(args.execute),+ "endpoint": "https://api.materialsproject.org/materials/summary/",+ "client": "mp_api.client.MPRester",+ "network_operations_when_executed": [+ "mp-api compatibility/heartbeat metadata checks during MPRester initialization",+ "one bounded materials.summary.search call",+ ],+ "user_agent_with_platform_details": False,+ "authentication": {+ "environment_variable": "MP_API_KEY",+ "read_only_when_execute_is_set": True,+ "accepted_on_command_line": False,+ "value_logged_or_serialized": False,+ },+ "query": {+ "filters": contract["filters"],+ "requested_fields": contract["requested_fields"],+ "effective_fields": contract["effective_fields"],+ "limit": args.limit,+ "num_chunks": 1,+ },+ "result_cache": {+ "enabled": False,+ "read": False,+ "written": False,+ "note": (+ "This CLI has no implicit result cache. The explicit JSON output "+ "is the reusable artifact. It does not request mp-api full-dataset "+ "downloads, so the configured full-dataset cache is not used."+ ),+ },+ "output": {+ "path_as_provided": args.output,+ "required_for_execution": True,+ "maximum_bytes": args.max_output_bytes,+ "existing_files_overwritten": False,+ },+ "rate_and_error_handling": {+ "custom_retries": False,+ "client_behavior": (+ "mp-api 0.46.4 retries 429, 502, and 504 according to its "+ "configured retry policy and respects Retry-After"+ ),+ "numeric_service_quota_assumed": False,+ "errors_are_redacted_and_bounded": True,+ },+ "data_use": {+ "license": "CC BY 4.0 for Materials Project data; contributed data may differ",+ "citation_required": True,+ "computed_data_is_experimental_truth": False,+ "database_version_recorded_automatically": False,+ },+ }+++def document_to_json(document: Any) -> dict[str, Any]:+ """Convert an mp-api document through its public Pydantic interface."""+ if isinstance(document, dict):+ result = document+ elif hasattr(document, "model_dump"):+ result = document.model_dump(mode="json")+ else:+ raise CliError(+ f"unsupported mp-api result type: {type(document).__name__}"+ )+ if not isinstance(result, dict):+ raise CliError("mp-api document did not serialize to an object")+ json_text(result, pretty=False)+ return result+++def execute_query(+ args: argparse.Namespace,+ contract: dict[str, Any],+ output_path: Any,+) -> dict[str, Any]:+ """Execute exactly one bounded summary search."""+ api_key = os.getenv("MP_API_KEY")+ if not api_key:+ raise CliError(+ "MP_API_KEY is not set; obtain it from the Materials Project dashboard "+ "and inject only that named secret through your shell or secret manager"+ )+ installed = package_versions(("pymatgen", "pymatgen-core", "mp-api"))+ expected = {+ "pymatgen": PYMATGEN_VERSION,+ "pymatgen-core": PYMATGEN_CORE_VERSION,+ "mp-api": MP_API_VERSION,+ }+ if installed != expected:+ raise CliError(+ f"network execution requires the verified package snapshot; "+ f"expected={expected}, installed={installed}"+ )+ from mp_api.client import MPRester+ from mp_api.client.core.exceptions import MPRestError++ try:+ with MPRester(+ api_key=api_key,+ include_user_agent=False,+ mute_progress_bars=True,+ notify_db_version=False,+ ) as rester:+ database_version = rester.db_version+ available = set(rester.materials.summary.available_fields)+ invalid_fields = [+ field+ for field in contract["effective_fields"]+ if field not in available+ ]+ if invalid_fields:+ raise CliError(+ f"fields unavailable in this endpoint/client: {invalid_fields}"+ )+ documents = rester.materials.summary.search(+ **contract["search_kwargs"]+ )+ except CliError:+ raise+ except MPRestError as exc:+ raise CliError(safe_error_message(exc, secret=api_key)) from exc+ except Exception as exc:+ raise CliError(safe_error_message(exc, secret=api_key)) from exc+ serialized = [document_to_json(document) for document in documents[: args.limit]]+ result = {+ "schema_version": "1.0",+ "provenance": {+ "retrieved_at_utc": datetime.now(timezone.utc).isoformat(),+ "endpoint": "https://api.materialsproject.org/materials/summary/",+ "pymatgen_version": PYMATGEN_VERSION,+ "pymatgen_core_version": PYMATGEN_CORE_VERSION,+ "mp_api_version": MP_API_VERSION,+ "database_version": database_version,+ "data_license": "CC BY 4.0; contributed data is owned by contributors",+ "citation": "https://materialsproject.org/about/cite",+ },+ "query": {+ "filters": contract["filters"],+ "fields": contract["effective_fields"],+ "limit": args.limit,+ "num_chunks": 1,+ },+ "returned": len(serialized),+ "returned_equals_requested_limit": len(serialized) == args.limit,+ "more_results_may_exist": len(serialized) == args.limit,+ "documents": serialized,+ "interpretation_limits": [+ "Materials Project values are computed and method-dependent.",+ "Aggregated values can change between database releases.",+ "Missing fields do not imply a measured zero.",+ "Band gaps and other properties carry documented systematic errors.",+ ],+ }+ write_json_new(output_path, result, max_bytes=args.max_output_bytes)+ return result+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Plan a bounded Materials Project summary query. No network or "+ "credential access occurs unless --execute is supplied."+ )+ )+ parser.add_argument("--material-id", action="append", default=[])+ parser.add_argument("--formula")+ parser.add_argument("--chemsys")+ parser.add_argument("--elements", help="Comma-separated required elements")+ parser.add_argument(+ "--exclude-elements", help="Comma-separated excluded elements"+ )+ parser.add_argument(+ "--energy-above-hull",+ nargs=2,+ type=float,+ metavar=("MIN", "MAX"),+ )+ parser.add_argument("--band-gap", nargs=2, type=float, metavar=("MIN", "MAX"))+ parser.add_argument(+ "--is-stable",+ choices=("any", "true", "false"),+ default="any",+ )+ parser.add_argument(+ "--fields",+ required=True,+ help="Comma-separated response fields; material_id is always added",+ )+ parser.add_argument("--limit", type=positive_int, default=25)+ parser.add_argument("--output", help="New JSON result path (required with --execute)")+ parser.add_argument("--plan-output", help="New JSON path for the dry-run plan")+ parser.add_argument(+ "--execute",+ action="store_true",+ help="Explicitly permit the disclosed bounded network query",+ )+ parser.add_argument(+ "--max-output-bytes",+ type=positive_int,+ default=DEFAULT_MAX_OUTPUT_BYTES,+ )+ return parser+++def main() -> int:+ args = build_parser().parse_args()+ try:+ if args.limit > MAX_RESULTS:+ raise CliError(f"--limit may not exceed {MAX_RESULTS}")+ if args.max_output_bytes > 50 * 1024 * 1024:+ raise CliError("--max-output-bytes may not exceed 50 MiB")+ contract = query_contract(args)+ plan = plan_payload(args, contract)+ if args.execute:+ if not args.output:+ raise CliError("--execute requires an explicit new --output path")+ output_path = checked_output_file(args.output)+ result = execute_query(args, contract, output_path)+ emit_json(+ {+ "ok": True,+ "executed": True,+ "network_accessed": True,+ "output": output_path.name,+ "output_bytes": output_path.stat().st_size,+ "returned": result["returned"],+ "overwrote_existing": False,+ "api_key_logged": False,+ }+ )+ elif args.plan_output:+ plan_path = checked_output_file(args.plan_output)+ write_json_new(plan_path, plan, max_bytes=args.max_output_bytes)+ emit_json(+ {+ "ok": True,+ "executed": False,+ "network_accessed": False,+ "plan_output": plan_path.name,+ "overwrote_existing": False,+ }+ )+ else:+ emit_json(plan)+ return 0+ except (CliError, ImportError, OSError, RuntimeError, TypeError, ValueError) as exc:+ emit_json(+ {+ "ok": False,+ "error": f"{type(exc).__name__}: {exc}"[:1000],+ "completed": False,+ "execute_requested": bool(args.execute),+ "network_may_have_been_accessed": bool(args.execute),+ "api_key_logged": False,+ }+ )+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pymatgen/scripts/phase_diagram_generator.py b/skills/pymatgen/scripts/phase_diagram_generator.pyindex ba2902f1..71790003 100644--- a/skills/pymatgen/scripts/phase_diagram_generator.py+++ b/skills/pymatgen/scripts/phase_diagram_generator.py@@ -1,233 +1,415 @@#!/usr/bin/env python3-"""-Phase diagram generator using Materials Project data.+"""Build a local phase diagram from a strict, provenance-bearing JSON dataset."""-This script generates phase diagrams for chemical systems using data from the-Materials Project database via pymatgen's MPRester.--Usage:- python phase_diagram_generator.py chemical_system [options]--Examples:- python phase_diagram_generator.py Li-Fe-O- python phase_diagram_generator.py Li-Fe-O --output li_fe_o_pd.png- python phase_diagram_generator.py Fe-O --show- python phase_diagram_generator.py Li-Fe-O --analyze "LiFeO2"-"""+from __future__ import annotationsimport argparse-import os-import sys+import math+import tempfilefrom pathlib import Path+from typing import Any++from _common import (+ ABSOLUTE_MAX_OUTPUT_BYTES,+ CliError,+ DEFAULT_MAX_INPUT_BYTES,+ DEFAULT_MAX_OUTPUT_BYTES,+ atomic_link_from_temp,+ checked_output_file,+ emit_json,+ finite_float,+ load_strict_json,+ positive_int,+ write_json_new,+)+++TOP_LEVEL_KEYS = {+ "schema_version",+ "energy_unit",+ "energy_basis",+ "provenance",+ "entries",+}+PROVENANCE_KEYS = {+ "source",+ "method",+ "retrieved_at",+ "database_version",+ "license",+ "citation",+ "notes",+}+ENTRY_KEYS = {"entry_id", "composition", "energy_eV", "provenance"}+++def validate_provenance(value: Any, label: str) -> dict[str, str]:+ """Validate a small string-only provenance object."""+ if not isinstance(value, dict):+ raise CliError(f"{label} must be an object")+ unknown = set(value) - PROVENANCE_KEYS+ if unknown:+ raise CliError(f"{label} has unknown keys: {sorted(unknown)}")+ if not isinstance(value.get("source"), str) or not value["source"].strip():+ raise CliError(f"{label}.source must be a non-empty string")+ result: dict[str, str] = {}+ for key, item in value.items():+ if not isinstance(item, str) or len(item) > 2000:+ raise CliError(f"{label}.{key} must be a string of at most 2000 chars")+ result[key] = item+ return result+++def entries_from_payload(+ payload: Any,+ *,+ max_entries: int,+) -> tuple[list[Any], dict[str, Any]]:+ """Validate the strict schema and construct plain ComputedEntry objects."""+ if not isinstance(payload, dict):+ raise CliError("top-level JSON value must be an object")+ missing = TOP_LEVEL_KEYS - set(payload)+ unknown = set(payload) - TOP_LEVEL_KEYS+ if missing or unknown:+ raise CliError(+ f"top-level keys mismatch; missing={sorted(missing)}, "+ f"unknown={sorted(unknown)}"+ )+ if payload["schema_version"] != "1.0":+ raise CliError("schema_version must be exactly '1.0'")+ if payload["energy_unit"] != "eV":+ raise CliError("energy_unit must be exactly 'eV'")+ if payload["energy_basis"] != "total_per_entry":+ raise CliError("energy_basis must be exactly 'total_per_entry'")+ dataset_provenance = validate_provenance(+ payload["provenance"], "provenance"+ )+ rows = payload["entries"]+ if not isinstance(rows, list) or not rows:+ raise CliError("entries must be a non-empty array")+ if len(rows) > max_entries:+ raise CliError(f"entries exceeds the {max_entries}-entry limit")-try:from pymatgen.core import Composition- from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter-except ImportError:- print("Error: pymatgen is not installed. Install with: pip install pymatgen")- sys.exit(1)--try:- from mp_api.client import MPRester-except ImportError:- print("Error: mp-api is not installed. Install with: pip install mp-api")- sys.exit(1)---def get_api_key() -> str:- """Get Materials Project API key from environment."""- api_key = os.environ.get("MP_API_KEY")- if not api_key:- print("Error: MP_API_KEY environment variable not set.")- print("Get your API key from https://next-gen.materialsproject.org/")- print("Then set it with: export MP_API_KEY='your_key_here'")- sys.exit(1)- return api_key---def generate_phase_diagram(chemsys: str, args):- """- Generate and analyze phase diagram for a chemical system.-- Args:- chemsys: Chemical system (e.g., "Li-Fe-O")- args: Command line arguments- """- api_key = get_api_key()-- print(f"\n{'='*60}")- print(f"PHASE DIAGRAM: {chemsys}")- print(f"{'='*60}\n")-- # Get entries from Materials Project- print("Fetching data from Materials Project...")- with MPRester(api_key) as mpr:- entries = mpr.get_entries_in_chemsys(chemsys)-- print(f"✓ Retrieved {len(entries)} entries")-- if len(entries) == 0:- print(f"Error: No entries found for chemical system {chemsys}")- sys.exit(1)-- # Build phase diagram- print("Building phase diagram...")- pd = PhaseDiagram(entries)-- # Get stable entries- stable_entries = pd.stable_entries- print(f"✓ Phase diagram constructed with {len(stable_entries)} stable phases")-- # Print stable phases- print("\n--- STABLE PHASES ---")- for entry in stable_entries:- formula = entry.composition.reduced_formula- energy = entry.energy_per_atom- print(f" {formula:<20} E = {energy:.4f} eV/atom")-- # Analyze specific composition if requested- if args.analyze:- print(f"\n--- STABILITY ANALYSIS: {args.analyze} ---")- try:- comp = Composition(args.analyze)-- # Find closest entry- closest_entry = None- min_distance = float('inf')-- for entry in entries:- if entry.composition.reduced_formula == comp.reduced_formula:- closest_entry = entry- break-- if closest_entry:- # Calculate energy above hull- e_above_hull = pd.get_e_above_hull(closest_entry)- print(f"Energy above hull: {e_above_hull:.4f} eV/atom")-- if e_above_hull < 0.001:- print(f"Status: STABLE (on convex hull)")- elif e_above_hull < 0.05:- print(f"Status: METASTABLE (nearly stable)")- else:- print(f"Status: UNSTABLE")-- # Get decomposition- decomp = pd.get_decomposition(comp)- print(f"\nDecomposes to:")- for entry, fraction in decomp.items():- formula = entry.composition.reduced_formula- print(f" {fraction:.3f} × {formula}")-- # Get reaction energy- rxn_energy = pd.get_equilibrium_reaction_energy(closest_entry)- print(f"\nDecomposition energy: {rxn_energy:.4f} eV/atom")-- else:- print(f"No entry found for composition {args.analyze}")- print("Checking stability of hypothetical composition...")-- # Analyze hypothetical composition- decomp = pd.get_decomposition(comp)- print(f"\nWould decompose to:")- for entry, fraction in decomp.items():- formula = entry.composition.reduced_formula- print(f" {fraction:.3f} × {formula}")-- except Exception as e:- print(f"Error analyzing composition: {e}")-- # Get chemical potentials- if args.chemical_potentials:- print("\n--- CHEMICAL POTENTIALS ---")- print("(at stability regions)")+ from pymatgen.entries.computed_entries import ComputedEntry++ entries: list[Any] = []+ seen_ids: set[str] = set()+ provenance_by_id: dict[str, dict[str, str]] = {}+ for index, row in enumerate(rows):+ label = f"entries[{index}]"+ if not isinstance(row, dict) or set(row) != ENTRY_KEYS:+ actual = sorted(row) if isinstance(row, dict) else type(row).__name__+ raise CliError(f"{label} must contain exactly {sorted(ENTRY_KEYS)}; got {actual}")+ entry_id = row["entry_id"]+ if (+ not isinstance(entry_id, str)+ or not entry_id.strip()+ or len(entry_id) > 200+ ):+ raise CliError(f"{label}.entry_id must be a short non-empty string")+ if entry_id in seen_ids:+ raise CliError(f"duplicate entry_id: {entry_id!r}")+ seen_ids.add(entry_id)+ formula = row["composition"]+ if not isinstance(formula, str) or len(formula) > 500:+ raise CliError(f"{label}.composition must be a formula string")try:- chempots = pd.get_all_chempots()- for element, potentials in chempots.items():- print(f"\n{element}:")- for potential in potentials[:5]: # Show first 5- print(f" {potential:.4f} eV")- except Exception as e:- print(f"Could not calculate chemical potentials: {e}")-- # Plot phase diagram- print("\n--- GENERATING PLOT ---")- plotter = PDPlotter(pd, show_unstable=args.show_unstable)-- if args.output:- output_path = Path(args.output)- plotter.write_image(str(output_path), image_format=output_path.suffix[1:])- print(f"✓ Phase diagram saved to {output_path}")-- if args.show:- print("Opening interactive plot...")- plotter.show()-- print(f"\n{'='*60}\n")---def main():- parser = argparse.ArgumentParser(- description="Generate phase diagrams using Materials Project data",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Requirements:- - Materials Project API key (set MP_API_KEY environment variable)- - mp-api package: pip install mp-api--Examples:- %(prog)s Li-Fe-O- %(prog)s Li-Fe-O --output li_fe_o_phase_diagram.png- %(prog)s Fe-O --show --analyze "Fe2O3"- %(prog)s Li-Fe-O --analyze "LiFeO2" --show-unstable- """- )+ composition = Composition(formula, strict=True)+ except (TypeError, ValueError) as exc:+ raise CliError(f"{label}.composition is invalid: {exc}") from exc+ if composition.num_atoms <= 0:+ raise CliError(f"{label}.composition must contain positive amounts")+ energy = finite_float(row["energy_eV"], f"{label}.energy_eV")+ entry_provenance = validate_provenance(+ row["provenance"], f"{label}.provenance"+ )+ provenance_by_id[entry_id] = entry_provenance+ entries.append(+ ComputedEntry(+ composition,+ energy,+ entry_id=entry_id,+ data={"provenance": entry_provenance},+ )+ )+ return entries, {+ "dataset": dataset_provenance,+ "entries": provenance_by_id,+ }+++def phase_report(+ entries: list[Any],+ provenance: dict[str, Any],+ *,+ analyze: list[str],+ max_report_entries: int,+) -> tuple[dict[str, Any], Any]:+ """Construct a phase diagram and a bounded scientific report."""+ from pymatgen.analysis.phase_diagram import PhaseDiagram+ from pymatgen.core import Composition- parser.add_argument(- "chemsys",- help="Chemical system (e.g., Li-Fe-O, Fe-O)"+ diagram = PhaseDiagram(entries)+ stable = set(diagram.stable_entries)+ ordered_entries = sorted(+ entries,+ key=lambda item: (+ item.composition.reduced_formula,+ float(item.energy_per_atom),+ str(item.entry_id),+ ),)-- parser.add_argument(- "--output", "-o",- help="Output file for phase diagram plot (PNG, PDF, SVG)"+ rows: list[dict[str, Any]] = []+ for entry in ordered_entries[:max_report_entries]:+ rows.append(+ {+ "entry_id": str(entry.entry_id),+ "formula": entry.composition.reduced_formula,+ "energy_eV_total": float(entry.energy),+ "energy_eV_per_atom": float(entry.energy_per_atom),+ "formation_energy_eV_per_atom": float(+ diagram.get_form_energy_per_atom(entry)+ ),+ "energy_above_hull_eV_per_atom": float(+ diagram.get_e_above_hull(entry)+ ),+ "on_computed_convex_hull": entry in stable,+ }+ )++ analyses: list[dict[str, Any]] = []+ for formula in analyze:+ try:+ composition = Composition(formula, strict=True)+ decomposition = diagram.get_decomposition(composition)+ matches = [+ entry+ for entry in entries+ if entry.composition.fractional_composition+ == composition.fractional_composition+ ]+ analyses.append(+ {+ "query": formula,+ "reduced_formula": composition.reduced_formula,+ "matching_entries": [+ {+ "entry_id": str(entry.entry_id),+ "energy_above_hull_eV_per_atom": float(+ diagram.get_e_above_hull(entry)+ ),+ }+ for entry in sorted(+ matches,+ key=lambda item: (+ float(item.energy_per_atom),+ str(item.entry_id),+ ),+ )+ ],+ "computed_hull_decomposition": [+ {+ "entry_id": str(entry.entry_id),+ "formula": entry.composition.reduced_formula,+ "fraction": float(fraction),+ }+ for entry, fraction in sorted(+ decomposition.items(),+ key=lambda item: str(item[0].entry_id),+ )+ ],+ }+ )+ except (TypeError, ValueError) as exc:+ analyses.append(+ {+ "query": formula,+ "error": f"{type(exc).__name__}: {exc}"[:500],+ }+ )++ report = {+ "ok": True,+ "analysis": "local_computed_phase_diagram",+ "units": {+ "input_energy": "eV total per entry",+ "reported_normalized_energy": "eV/atom",+ },+ "chemical_system": "-".join(str(element) for element in diagram.elements),+ "elements": [str(element) for element in diagram.elements],+ "entry_count": len(entries),+ "stable_entry_count": len(stable),+ "entries": rows,+ "entries_omitted": max(0, len(entries) - max_report_entries),+ "composition_analyses": analyses,+ "provenance": provenance["dataset"],+ "interpretation_limits": [+ "The hull is conditional on this exact entry set and energy model.",+ "Energies from incompatible methods or correction schemes must not be mixed.",+ "Computed stability is not experimental truth or a synthesis guarantee.",+ "Finite-temperature, pressure, kinetic, disorder, and uncertainty effects are absent unless encoded upstream.",+ ],+ "experimental_validity_established": False,+ }+ return report, diagram+++def write_plot_new(+ diagram: Any,+ output_path: Path,+ *,+ show_unstable: float,+ max_bytes: int,+) -> None:+ """Render to a sibling temporary file, then link without overwriting."""+ suffix = output_path.suffix.casefold()+ if suffix not in {".png", ".pdf", ".svg"}:+ raise CliError("plot output suffix must be .png, .pdf, or .svg")+ from pymatgen.analysis.phase_diagram import PDPlotter++ temporary_path: Path | None = None+ try:+ with tempfile.NamedTemporaryFile(+ prefix=".pymatgen-phase-",+ suffix=suffix,+ dir=output_path.parent,+ delete=False,+ ) as handle:+ temporary_path = Path(handle.name)+ plotter = PDPlotter(diagram, show_unstable=show_unstable)+ plotter.write_image(+ str(temporary_path),+ image_format=suffix.removeprefix("."),+ )+ if temporary_path.stat().st_size > max_bytes:+ raise CliError(f"plot exceeds the {max_bytes}-byte limit")+ atomic_link_from_temp(temporary_path, output_path)+ finally:+ if temporary_path is not None:+ temporary_path.unlink(missing_ok=True)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Build an offline phase diagram from strict JSON total energies. "+ "This script never queries Materials Project."+ ))-+ parser.add_argument("entries_json", help="Strict local entries dataset")parser.add_argument(- "--show", "-s",- action="store_true",- help="Show interactive plot"+ "--analyze",+ action="append",+ default=[],+ help="Formula to decompose or match (repeatable, maximum 20)",)-+ parser.add_argument("--output", help="New JSON report; default is stdout")+ parser.add_argument("--plot", help="New .png, .pdf, or .svg plot")parser.add_argument(- "--analyze", "-a",- help="Analyze stability of specific composition (e.g., LiFeO2)"+ "--show-unstable",+ type=float,+ default=0.2,+ help="Plot unstable entries up to this eV/atom (default: 0.2)",)-parser.add_argument(- "--show-unstable",- action="store_true",- help="Include unstable phases in plot"+ "--max-input-bytes",+ type=positive_int,+ default=DEFAULT_MAX_INPUT_BYTES,)-+ parser.add_argument("--max-entries", type=positive_int, default=5000)+ parser.add_argument("--max-report-entries", type=positive_int, default=200)parser.add_argument(- "--chemical-potentials",- action="store_true",- help="Calculate chemical potentials"+ "--max-output-bytes",+ type=positive_int,+ default=DEFAULT_MAX_OUTPUT_BYTES,)-- args = parser.parse_args()-- # Validate chemical system format- elements = args.chemsys.split("-")- if len(elements) < 2:- print("Error: Chemical system must contain at least 2 elements")- print("Example: Li-Fe-O")- sys.exit(1)-- # Generate phase diagram- generate_phase_diagram(args.chemsys, args)+ return parser+++def main() -> int:+ args = build_parser().parse_args()+ try:+ if len(args.analyze) > 20:+ raise CliError("--analyze may be repeated at most 20 times")+ if not math.isfinite(args.show_unstable) or args.show_unstable < 0:+ raise CliError("--show-unstable must be finite and non-negative")+ if args.max_entries > 10_000:+ raise CliError("--max-entries may not exceed 10000")+ if args.max_report_entries > 1_000:+ raise CliError("--max-report-entries may not exceed 1000")+ if args.max_output_bytes > ABSOLUTE_MAX_OUTPUT_BYTES:+ raise CliError(+ f"--max-output-bytes may not exceed {ABSOLUTE_MAX_OUTPUT_BYTES}"+ )+ payload, input_path = load_strict_json(+ args.entries_json,+ max_bytes=args.max_input_bytes,+ )+ entries, provenance = entries_from_payload(+ payload,+ max_entries=args.max_entries,+ )+ report, diagram = phase_report(+ entries,+ provenance,+ analyze=args.analyze,+ max_report_entries=args.max_report_entries,+ )+ report["input"] = {+ "name": input_path.name,+ "bytes": input_path.stat().st_size,+ "network_accessed": False,+ }+ created: list[str] = []+ if args.output:+ output_path = checked_output_file(+ args.output,+ input_paths=(input_path,),+ )+ write_json_new(+ output_path,+ report,+ max_bytes=args.max_output_bytes,+ )+ created.append(output_path.name)+ if args.plot:+ plot_path = checked_output_file(+ args.plot,+ input_paths=(input_path,),+ )+ if len(diagram.elements) > 4:+ raise CliError("plotting is limited to at most four elements")+ write_plot_new(+ diagram,+ plot_path,+ show_unstable=args.show_unstable,+ max_bytes=args.max_output_bytes,+ )+ created.append(plot_path.name)+ if created:+ emit_json(+ {+ "ok": True,+ "created": created,+ "overwrote_existing": False,+ "network_accessed": False,+ "entry_count": len(entries),+ }+ )+ else:+ emit_json(report)+ return 0+ except (CliError, ImportError, OSError, RuntimeError, TypeError, ValueError) as exc:+ emit_json(+ {+ "ok": False,+ "error": f"{type(exc).__name__}: {exc}"[:1000],+ "network_accessed": False,+ }+ )+ return 2if __name__ == "__main__":- main()+ raise SystemExit(main())diff --git a/skills/pymatgen/scripts/structure_analyzer.py b/skills/pymatgen/scripts/structure_analyzer.pyindex 677ec197..35f5029f 100644--- a/skills/pymatgen/scripts/structure_analyzer.py+++ b/skills/pymatgen/scripts/structure_analyzer.py@@ -1,266 +1,293 @@#!/usr/bin/env python3-"""-Structure analysis tool using pymatgen.+"""Produce a bounded JSON analysis of one local periodic structure."""-Analyzes crystal structures and provides comprehensive information including:-- Composition and formula-- Space group and symmetry-- Lattice parameters-- Density-- Coordination environment-- Bond lengths and angles--Usage:- python structure_analyzer.py structure_file [options]--Examples:- python structure_analyzer.py POSCAR- python structure_analyzer.py structure.cif --symmetry --neighbors- python structure_analyzer.py POSCAR --export json-"""+from __future__ import annotationsimport argparse-import json-import sys-from pathlib import Path--try:- from pymatgen.core import Structure- from pymatgen.symmetry.analyzer import SpacegroupAnalyzer- from pymatgen.analysis.local_env import CrystalNN-except ImportError:- print("Error: pymatgen is not installed. Install with: pip install pymatgen")- sys.exit(1)-+import math+import warnings+from typing import Any++from _common import (+ ABSOLUTE_MAX_PAIRWISE_SITES,+ CliError,+ DEFAULT_MAX_INPUT_BYTES,+ DEFAULT_MAX_OUTPUT_BYTES,+ DEFAULT_MAX_SITES,+ checked_output_file,+ emit_json,+ load_structure,+ positive_int,+ structure_oxidation_summary,+ write_json_new,+)+++def minimum_periodic_distance(structure: Any, max_sites: int) -> float | None:+ """Return the minimum non-self periodic distance under an explicit bound."""+ if len(structure) < 2 or len(structure) > max_sites:+ return None+ minimum = math.inf+ for first in range(len(structure)):+ for second in range(first + 1, len(structure)):+ minimum = min(minimum, float(structure.get_distance(first, second)))+ return minimum if math.isfinite(minimum) else None+++def site_records(structure: Any, limit: int) -> list[dict[str, Any]]:+ """Return a bounded, explicit fractional-coordinate site table."""+ records: list[dict[str, Any]] = []+ for index, site in enumerate(structure[:limit]):+ records.append(+ {+ "index": index,+ "species": {+ str(specie): float(occupancy)+ for specie, occupancy in site.species.items()+ },+ "fractional_coordinates": [+ float(value) for value in site.frac_coords+ ],+ "label": site.label,+ }+ )+ return records-def analyze_structure(struct: Structure, args) -> dict:- """- Perform comprehensive structure analysis.- Args:- struct: Pymatgen Structure object- args: Command line arguments+def symmetry_report(+ structure: Any,+ *,+ symprec: float,+ angle_tolerance: float,+) -> dict[str, Any]:+ """Run one explicitly parameterized spglib-backed symmetry analysis."""+ from pymatgen.symmetry.analyzer import SpacegroupAnalyzer- Returns:- Dictionary containing analysis results- """- results = {}+ analyzer = SpacegroupAnalyzer(+ structure,+ symprec=symprec,+ angle_tolerance=angle_tolerance,+ )+ symmetrized = analyzer.get_symmetrized_structure()+ return {+ "backend": "spglib through pymatgen",+ "symprec_angstrom": symprec,+ "angle_tolerance_degrees": angle_tolerance,+ "space_group_symbol": analyzer.get_space_group_symbol(),+ "space_group_number": analyzer.get_space_group_number(),+ "crystal_system": str(analyzer.get_crystal_system()),+ "point_group_symbol": analyzer.get_point_group_symbol(),+ "symmetry_operations": len(analyzer.get_symmetry_operations()),+ "equivalent_site_groups": len(symmetrized.equivalent_indices),+ "wyckoff_symbols_by_group": list(symmetrized.wyckoff_symbols),+ "tolerance_sensitivity_assessed": False,+ }- # Basic information- print("\n" + "="*60)- print("STRUCTURE ANALYSIS")- print("="*60)- print("\n--- COMPOSITION ---")- print(f"Formula (reduced): {struct.composition.reduced_formula}")- print(f"Formula (full): {struct.composition.formula}")- print(f"Formula (Hill): {struct.composition.hill_formula}")- print(f"Chemical system: {struct.composition.chemical_system}")- print(f"Number of sites: {len(struct)}")- print(f"Number of species: {len(struct.composition.elements)}")- print(f"Molecular weight: {struct.composition.weight:.2f} amu")+def neighbor_report(+ structure: Any,+ *,+ site_limit: int,+ neighbor_limit: int,+) -> dict[str, Any]:+ """Run CrystalNN for a bounded site prefix and truncate each neighbor list."""+ if not structure.is_ordered:+ raise CliError("CrystalNN report requires an ordered structure")+ from pymatgen.analysis.local_env import CrystalNN- results['composition'] = {- 'reduced_formula': struct.composition.reduced_formula,- 'formula': struct.composition.formula,- 'hill_formula': struct.composition.hill_formula,- 'chemical_system': struct.composition.chemical_system,- 'num_sites': len(struct),- 'molecular_weight': struct.composition.weight,+ strategy = CrystalNN()+ rows: list[dict[str, Any]] = []+ warning_messages: list[str] = []+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ for index in range(min(len(structure), site_limit)):+ try:+ neighbors = strategy.get_nn_info(structure, index)+ rows.append(+ {+ "site_index": index,+ "species": structure[index].species_string,+ "coordination_number": len(neighbors),+ "neighbors": [+ {+ "site_index": int(item["site_index"]),+ "image": [int(value) for value in item["image"]],+ "weight": float(item["weight"]),+ }+ for item in neighbors[:neighbor_limit]+ ],+ "neighbors_omitted": max(+ 0, len(neighbors) - neighbor_limit+ ),+ }+ )+ except (RuntimeError, TypeError, ValueError) as exc:+ rows.append(+ {+ "site_index": index,+ "error": f"{type(exc).__name__}: {exc}"[:500],+ }+ )+ warning_messages = [+ f"{item.category.__name__}: {item.message}" for item in caught[:20]+ ]+ return {+ "method": "CrystalNN",+ "sites": rows,+ "sites_omitted": max(0, len(structure) - site_limit),+ "warnings": warning_messages,+ "coordination_is_model_dependent": True,}- # Lattice information- print("\n--- LATTICE ---")- print(f"a = {struct.lattice.a:.4f} Å")- print(f"b = {struct.lattice.b:.4f} Å")- print(f"c = {struct.lattice.c:.4f} Å")- print(f"α = {struct.lattice.alpha:.2f}°")- print(f"β = {struct.lattice.beta:.2f}°")- print(f"γ = {struct.lattice.gamma:.2f}°")- print(f"Volume: {struct.volume:.2f} ų")- print(f"Density: {struct.density:.3f} g/cm³")- results['lattice'] = {- 'a': struct.lattice.a,- 'b': struct.lattice.b,- 'c': struct.lattice.c,- 'alpha': struct.lattice.alpha,- 'beta': struct.lattice.beta,- 'gamma': struct.lattice.gamma,- 'volume': struct.volume,- 'density': struct.density,+def analyze_structure(structure: Any, args: argparse.Namespace) -> dict[str, Any]:+ """Build a bounded analysis payload."""+ lattice = structure.lattice+ report: dict[str, Any] = {+ "ok": True,+ "analysis": "periodic_structure",+ "units": {+ "length": "angstrom",+ "angle": "degree",+ "volume": "angstrom^3",+ "density": "g/cm^3",+ "mass": "amu per composition represented",+ },+ "periodicity": {+ "periodic_boundary_conditions": [bool(value) for value in lattice.pbc],+ "lattice_required": True,+ },+ "composition": {+ "formula": structure.composition.formula,+ "reduced_formula": structure.composition.reduced_formula,+ "hill_formula": structure.composition.hill_formula,+ "chemical_system": structure.composition.chemical_system,+ "mass_amu": float(structure.composition.weight),+ "charge": float(structure.charge),+ "ordered": bool(structure.is_ordered),+ "oxidation_states": structure_oxidation_summary(structure),+ },+ "lattice": {+ "matrix_rows_angstrom": [+ [float(value) for value in row] for row in lattice.matrix+ ],+ "abc_angstrom": [float(value) for value in lattice.abc],+ "angles_degrees": [float(value) for value in lattice.angles],+ "volume_angstrom_cubed": float(structure.volume),+ "density_g_cm3": float(structure.density),+ },+ "sites": {+ "count": len(structure),+ "coordinate_mode": "fractional",+ "records": site_records(structure, args.max_site_records),+ "records_omitted": max(0, len(structure) - args.max_site_records),+ },+ "minimum_periodic_distance_angstrom": minimum_periodic_distance(+ structure, args.max_distance_sites+ ),+ "minimum_distance_omitted_above_sites": args.max_distance_sites,+ "scientific_validity_established": False,}-- # Symmetry analysisif args.symmetry:- print("\n--- SYMMETRY ---")- try:- sga = SpacegroupAnalyzer(struct)-- spacegroup_symbol = sga.get_space_group_symbol()- spacegroup_number = sga.get_space_group_number()- crystal_system = sga.get_crystal_system()- point_group = sga.get_point_group_symbol()-- print(f"Space group: {spacegroup_symbol} (#{spacegroup_number})")- print(f"Crystal system: {crystal_system}")- print(f"Point group: {point_group}")-- # Get symmetry operations- symm_ops = sga.get_symmetry_operations()- print(f"Symmetry operations: {len(symm_ops)}")-- results['symmetry'] = {- 'spacegroup_symbol': spacegroup_symbol,- 'spacegroup_number': spacegroup_number,- 'crystal_system': crystal_system,- 'point_group': point_group,- 'num_symmetry_ops': len(symm_ops),- }-- # Show equivalent sites- sym_struct = sga.get_symmetrized_structure()- print(f"Symmetry-equivalent site groups: {len(sym_struct.equivalent_sites)}")-- except Exception as e:- print(f"Could not determine symmetry: {e}")-- # Site information- print("\n--- SITES ---")- print(f"{'Index':<6} {'Species':<10} {'Wyckoff':<10} {'Frac Coords':<30}")- print("-" * 60)-- for i, site in enumerate(struct):- coords_str = f"[{site.frac_coords[0]:.4f}, {site.frac_coords[1]:.4f}, {site.frac_coords[2]:.4f}]"- wyckoff = "N/A"-- if args.symmetry:- try:- sga = SpacegroupAnalyzer(struct)- sym_struct = sga.get_symmetrized_structure()- wyckoff = sym_struct.equivalent_sites[0][0].species_string # Simplified- except:- pass-- print(f"{i:<6} {site.species_string:<10} {wyckoff:<10} {coords_str:<30}")-- # Neighbor analysis+ report["symmetry"] = symmetry_report(+ structure,+ symprec=args.symprec,+ angle_tolerance=args.angle_tolerance,+ )if args.neighbors:- print("\n--- COORDINATION ENVIRONMENT ---")- try:- cnn = CrystalNN()+ report["neighbors"] = neighbor_report(+ structure,+ site_limit=args.max_neighbor_sites,+ neighbor_limit=args.max_neighbors_per_site,+ )+ return report- for i, site in enumerate(struct):- neighbors = cnn.get_nn_info(struct, i)- print(f"\nSite {i} ({site.species_string}):")- print(f" Coordination number: {len(neighbors)}")- if len(neighbors) > 0 and len(neighbors) <= 12:- print(f" Neighbors:")- for j, neighbor in enumerate(neighbors):- neighbor_site = struct[neighbor['site_index']]- distance = site.distance(neighbor_site)- print(f" {neighbor_site.species_string} at {distance:.3f} Å")-- except Exception as e:- print(f"Could not analyze coordination: {e}")-- # Distance matrix (for small structures)- if args.distances and len(struct) <= 20:- print("\n--- DISTANCE MATRIX (Å) ---")- distance_matrix = struct.distance_matrix-- # Print header- print(f"{'':>4}", end="")- for i in range(len(struct)):- print(f"{i:>8}", end="")- print()-- # Print matrix- for i in range(len(struct)):- print(f"{i:>4}", end="")- for j in range(len(struct)):- if i == j:- print(f"{'---':>8}", end="")- else:- print(f"{distance_matrix[i][j]:>8.3f}", end="")- print()-- print("\n" + "="*60)-- return results---def main():+def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(- description="Analyze crystal structures using pymatgen",- formatter_class=argparse.RawDescriptionHelpFormatter,+ description=(+ "Analyze one bounded local periodic structure. JSON output is "+ "truncated by explicit site/neighbor limits."+ ))-+ parser.add_argument("structure_file", help="Existing local structure file")+ parser.add_argument("--structure-index", type=int, default=0)+ parser.add_argument("--symmetry", action="store_true")+ parser.add_argument("--symprec", type=float, default=0.01)+ parser.add_argument("--angle-tolerance", type=float, default=5.0)+ parser.add_argument("--neighbors", action="store_true")+ parser.add_argument("--output", help="New JSON output; default is stdout")parser.add_argument(- "structure_file",- help="Structure file to analyze (CIF, POSCAR, etc.)"+ "--max-input-bytes",+ type=positive_int,+ default=DEFAULT_MAX_INPUT_BYTES,)-+ parser.add_argument("--max-sites", type=positive_int, default=DEFAULT_MAX_SITES)+ parser.add_argument("--max-site-records", type=positive_int, default=100)+ parser.add_argument("--max-distance-sites", type=positive_int, default=500)+ parser.add_argument("--max-neighbor-sites", type=positive_int, default=100)parser.add_argument(- "--symmetry", "-s",- action="store_true",- help="Perform symmetry analysis"+ "--max-neighbors-per-site", type=positive_int, default=24)-parser.add_argument(- "--neighbors", "-n",- action="store_true",- help="Analyze coordination environment"+ "--max-output-bytes",+ type=positive_int,+ default=DEFAULT_MAX_OUTPUT_BYTES,)+ return parser- parser.add_argument(- "--distances", "-d",- action="store_true",- help="Show distance matrix (for structures with ≤20 atoms)"- )- parser.add_argument(- "--export", "-e",- choices=["json", "yaml"],- help="Export analysis results to file"- )-- parser.add_argument(- "--output", "-o",- help="Output file for exported results"- )-- args = parser.parse_args()-- # Read structure+def main() -> int:+ args = build_parser().parse_args()try:- struct = Structure.from_file(args.structure_file)- except Exception as e:- print(f"Error reading structure file: {e}")- sys.exit(1)-- # Analyze structure- results = analyze_structure(struct, args)-- # Export results- if args.export:- output_file = args.output or f"analysis.{args.export}"-- if args.export == "json":- with open(output_file, "w") as f:- json.dump(results, f, indent=2)- print(f"\n✓ Analysis exported to {output_file}")-- elif args.export == "yaml":- try:- import yaml- with open(output_file, "w") as f:- yaml.dump(results, f, default_flow_style=False)- print(f"\n✓ Analysis exported to {output_file}")- except ImportError:- print("Error: PyYAML is not installed. Install with: pip install pyyaml")+ if args.structure_index < 0:+ raise CliError("--structure-index must be non-negative")+ if not math.isfinite(args.symprec) or args.symprec <= 0:+ raise CliError("--symprec must be finite and positive")+ if not math.isfinite(args.angle_tolerance) or args.angle_tolerance < 0:+ raise CliError("--angle-tolerance must be finite and non-negative")+ if args.max_distance_sites > ABSOLUTE_MAX_PAIRWISE_SITES:+ raise CliError(+ f"--max-distance-sites may not exceed "+ f"{ABSOLUTE_MAX_PAIRWISE_SITES}"+ )+ if args.max_site_records > 10_000:+ raise CliError("--max-site-records may not exceed 10000")+ if args.max_neighbor_sites > 10_000:+ raise CliError("--max-neighbor-sites may not exceed 10000")+ if args.max_neighbors_per_site > 1_000:+ raise CliError("--max-neighbors-per-site may not exceed 1000")+ structure, input_path, parse_report = load_structure(+ args.structure_file,+ structure_index=args.structure_index,+ max_bytes=args.max_input_bytes,+ max_sites=args.max_sites,+ )+ report = analyze_structure(structure, args)+ report["input"] = parse_report+ if args.output:+ output = checked_output_file(args.output, input_paths=(input_path,))+ write_json_new(+ output,+ report,+ max_bytes=args.max_output_bytes,+ )+ emit_json(+ {+ "ok": True,+ "output": output.name,+ "output_bytes": output.stat().st_size,+ "overwrote_existing": False,+ "sites": len(structure),+ }+ )+ else:+ emit_json(report)+ return 0+ except (CliError, ImportError, OSError, RuntimeError, TypeError, ValueError) as exc:+ emit_json({"ok": False, "error": f"{type(exc).__name__}: {exc}"[:1000]})+ return 2if __name__ == "__main__":- main()+ raise SystemExit(main())diff --git a/skills/pymatgen/scripts/structure_converter.py b/skills/pymatgen/scripts/structure_converter.pyindex d2ec4056..3403e058 100644--- a/skills/pymatgen/scripts/structure_converter.py+++ b/skills/pymatgen/scripts/structure_converter.py@@ -1,169 +1,219 @@#!/usr/bin/env python3-"""-Structure file format converter using pymatgen.+"""Convert one local periodic structure with explicit loss acknowledgement."""-This script converts between different structure file formats supported by pymatgen.-Supports automatic format detection and batch conversion.--Usage:- python structure_converter.py input_file output_file- python structure_converter.py input_file --format cif- python structure_converter.py *.cif --output-dir ./converted --format poscar--Examples:- python structure_converter.py POSCAR structure.cif- python structure_converter.py structure.cif --format json- python structure_converter.py *.vasp --output-dir ./cif_files --format cif-"""+from __future__ import annotationsimport argparse-import sys-from pathlib import Path-from typing import List--try:- from pymatgen.core import Structure-except ImportError:- print("Error: pymatgen is not installed. Install with: pip install pymatgen")- sys.exit(1)---def convert_structure(input_path: Path, output_path: Path = None, output_format: str = None) -> bool:- """- Convert a structure file to a different format.-- Args:- input_path: Path to input structure file- output_path: Path to output file (optional if output_format is specified)- output_format: Target format (e.g., 'cif', 'poscar', 'json', 'yaml')-- Returns:- True if conversion succeeded, False otherwise- """- try:- # Read structure with automatic format detection- struct = Structure.from_file(str(input_path))- print(f"✓ Read structure: {struct.composition.reduced_formula} from {input_path}")-- # Determine output path- if output_path is None and output_format:- output_path = input_path.with_suffix(f".{output_format}")- elif output_path is None:- print("Error: Must specify either output_path or output_format")- return False-- # Write structure- struct.to(filename=str(output_path))- print(f"✓ Wrote structure to {output_path}")-- return True-- except Exception as e:- print(f"✗ Error converting {input_path}: {e}")- return False---def batch_convert(input_files: List[Path], output_dir: Path, output_format: str) -> None:- """- Convert multiple structure files to a common format.-- Args:- input_files: List of input structure files- output_dir: Directory for output files- output_format: Target format for all files- """- output_dir.mkdir(parents=True, exist_ok=True)-- success_count = 0- for input_file in input_files:- output_file = output_dir / f"{input_file.stem}.{output_format}"- if convert_structure(input_file, output_file):- success_count += 1-- print(f"\n{'='*60}")- print(f"Conversion complete: {success_count}/{len(input_files)} files converted successfully")---def main():+import warnings++from _common import (+ CliError,+ DEFAULT_MAX_INPUT_BYTES,+ DEFAULT_MAX_OUTPUT_BYTES,+ DEFAULT_MAX_SITES,+ checked_output_file,+ emit_json,+ load_structure,+ positive_int,+ structure_oxidation_summary,+ write_text_new,+)+++FORMATS = ("cif", "cssr", "json", "poscar", "xsf", "xyz")+NONPERIODIC_TARGETS = {"xyz"}+LIMITED_TARGETS = {"cssr", "poscar", "xsf", "xyz"}+++def conversion_risks(structure: object, output_format: str) -> list[str]:+ """Describe representation that a target format may not preserve."""+ risks: list[str] = []+ oxidation = structure_oxidation_summary(structure)+ site_properties = sorted(structure.site_properties)+ if output_format != "json" and oxidation["decorated_species_components"]:+ risks.append("oxidation-state decoration may not round-trip")+ if output_format != "json" and site_properties:+ risks.append(+ "site properties may be omitted or represented format-specifically: "+ + ", ".join(site_properties[:20])+ )+ if output_format in NONPERIODIC_TARGETS:+ risks.append("target does not preserve lattice vectors or periodicity")+ if output_format in LIMITED_TARGETS and not structure.is_ordered:+ risks.append("target cannot faithfully represent partial occupancies/disorder")+ return risks+++def render_structure(+ structure: object,+ *,+ output_format: str,+ coordinate_mode: str,+) -> str:+ """Render a structure without giving pymatgen an output path."""+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ if output_format == "poscar":+ from pymatgen.io.vasp import Poscar++ text = Poscar(structure).get_str(direct=coordinate_mode == "direct")+ else:+ if coordinate_mode != "not-applicable":+ raise CliError(+ "--coordinate-mode is only meaningful for POSCAR output"+ )+ text = structure.to(fmt=output_format)+ if caught:+ messages = "; ".join(str(item.message) for item in caught[:10])+ raise CliError(f"writer emitted warnings; conversion stopped: {messages}")+ return text+++def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(- description="Convert structure files between different formats using pymatgen",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Supported formats:- Input: CIF, POSCAR, CONTCAR, XYZ, PDB, JSON, YAML, and many more- Output: CIF, POSCAR, XYZ, PDB, JSON, YAML, XSF, and many more--Examples:- %(prog)s POSCAR structure.cif- %(prog)s structure.cif --format json- %(prog)s *.cif --output-dir ./poscar_files --format poscar- """+ description=(+ "Convert one bounded local periodic structure. The original and any "+ "existing output are never overwritten."+ ))-+ parser.add_argument("input", help="Existing local structure file")+ parser.add_argument("output", help="New output file")parser.add_argument(- "input",- nargs="+",- help="Input structure file(s). Supports wildcards for batch conversion."+ "--output-format",+ required=True,+ choices=FORMATS,+ help="Explicit target format; filename inference is not used",)-parser.add_argument(- "output",- nargs="?",- help="Output structure file (ignored if --output-dir is used)"+ "--coordinate-mode",+ choices=("direct", "cartesian", "not-applicable"),+ default="not-applicable",+ help="POSCAR coordinate mode; use not-applicable for other formats",)-parser.add_argument(- "--format", "-f",- help="Output format (e.g., cif, poscar, json, yaml, xyz)"+ "--structure-index",+ type=int,+ default=0,+ help="Zero-based structure index for a multi-block CIF (default: 0)",)-parser.add_argument(- "--output-dir", "-o",- type=Path,- help="Output directory for batch conversion"+ "--allow-lossy",+ action="store_true",+ help="Acknowledge every representation risk listed in the report",)+ parser.add_argument(+ "--acknowledge-parser-warnings",+ action="store_true",+ help="Continue only after reviewing warnings emitted while parsing",+ )+ parser.add_argument(+ "--max-input-bytes",+ type=positive_int,+ default=DEFAULT_MAX_INPUT_BYTES,+ )+ parser.add_argument(+ "--max-output-bytes",+ type=positive_int,+ default=DEFAULT_MAX_OUTPUT_BYTES,+ )+ parser.add_argument(+ "--max-sites",+ type=positive_int,+ default=DEFAULT_MAX_SITES,+ )+ return parser- args = parser.parse_args()-- # Expand wildcards and convert to Path objects- input_files = []- for pattern in args.input:- matches = list(Path.cwd().glob(pattern))- if matches:- input_files.extend(matches)- else:- input_files.append(Path(pattern))-- # Filter to files only- input_files = [f for f in input_files if f.is_file()]-- if not input_files:- print("Error: No input files found")- sys.exit(1)-- # Batch conversion mode- if args.output_dir or len(input_files) > 1:- if not args.format:- print("Error: --format is required for batch conversion")- sys.exit(1)-- output_dir = args.output_dir or Path("./converted")- batch_convert(input_files, output_dir, args.format)-- # Single file conversion- elif len(input_files) == 1:- input_file = input_files[0]- if args.output:- output_file = Path(args.output)- convert_structure(input_file, output_file)- elif args.format:- convert_structure(input_file, output_format=args.format)- else:- print("Error: Must specify output file or --format")- parser.print_help()- sys.exit(1)+def main() -> int:+ args = build_parser().parse_args()+ try:+ if args.structure_index < 0:+ raise CliError("--structure-index must be non-negative")+ if args.output_format == "poscar" and args.coordinate_mode == "not-applicable":+ raise CliError("POSCAR output requires --coordinate-mode direct|cartesian")+ structure, input_path, parse_report = load_structure(+ args.input,+ structure_index=args.structure_index,+ max_bytes=args.max_input_bytes,+ max_sites=args.max_sites,+ )+ output_path = checked_output_file(+ args.output,+ input_paths=(input_path,),+ )+ parser_warnings = [+ *parse_report["python_warnings"],+ *parse_report["parser_warnings"],+ ]+ if parser_warnings and not args.acknowledge_parser_warnings:+ raise CliError(+ "parser warnings require --acknowledge-parser-warnings after review: "+ + "; ".join(parser_warnings[:10])+ )+ risks = conversion_risks(structure, args.output_format)+ if risks and not args.allow_lossy:+ raise CliError(+ "conversion may be lossy; review the I/O plan and rerun with "+ "--allow-lossy: "+ + "; ".join(risks)+ )+ if not structure.is_ordered and args.output_format in LIMITED_TARGETS:+ raise CliError(+ f"{args.output_format} cannot faithfully encode this disordered "+ "structure; choose JSON or CIF"+ )+ text = render_structure(+ structure,+ output_format=args.output_format,+ coordinate_mode=args.coordinate_mode,+ )+ write_text_new(+ output_path,+ text,+ max_bytes=args.max_output_bytes,+ )+ parse_report["warnings_acknowledged"] = bool(+ args.acknowledge_parser_warnings+ )+ emit_json(+ {+ "ok": True,+ "action": "structure_conversion",+ "input": parse_report,+ "output": {+ "name": output_path.name,+ "format": args.output_format,+ "coordinate_mode": args.coordinate_mode,+ "bytes": output_path.stat().st_size,+ "created": True,+ "overwrote_existing": False,+ },+ "structure": {+ "formula": structure.composition.reduced_formula,+ "sites": len(structure),+ "ordered": structure.is_ordered,+ "periodic_boundary_conditions": list(structure.lattice.pbc),+ "oxidation_states": structure_oxidation_summary(structure),+ },+ "representation_risks": risks,+ "losses_acknowledged": bool(args.allow_lossy),+ "scientific_equivalence_verified": False,+ }+ )+ return 0+ except (CliError, ImportError) as exc:+ emit_json(+ {+ "ok": False,+ "error": str(exc),+ "output_created": False,+ "hint": (+ "Install the pinned snapshot with uv if pymatgen is missing."+ ),+ }+ )+ return 2if __name__ == "__main__":- main()+ raise SystemExit(main())diff --git a/skills/pymatgen/scripts/symmetry_sensitivity_report.py b/skills/pymatgen/scripts/symmetry_sensitivity_report.pynew file mode 100644index 00000000..5f6d017c--- /dev/null+++ b/skills/pymatgen/scripts/symmetry_sensitivity_report.py@@ -0,0 +1,212 @@+#!/usr/bin/env python3+"""Report space-group sensitivity across explicit symmetry tolerances."""++from __future__ import annotations++import argparse+import math+from typing import Any++from _common import (+ CliError,+ DEFAULT_MAX_INPUT_BYTES,+ DEFAULT_MAX_OUTPUT_BYTES,+ DEFAULT_MAX_SITES,+ checked_output_file,+ emit_json,+ load_structure,+ positive_int,+ write_json_new,+)+++def parse_tolerances(value: str, label: str) -> list[float]:+ """Parse a unique comma-separated finite positive float list."""+ pieces = [piece.strip() for piece in value.split(",") if piece.strip()]+ if not pieces:+ raise CliError(f"{label} must contain at least one value")+ result: list[float] = []+ for piece in pieces:+ try:+ number = float(piece)+ except ValueError as exc:+ raise CliError(f"{label} contains a non-number: {piece!r}") from exc+ if not math.isfinite(number) or number <= 0:+ raise CliError(f"{label} values must be finite and positive")+ if number not in result:+ result.append(number)+ if len(result) > 10:+ raise CliError(f"{label} may contain at most 10 unique values")+ return result+++def analyze_grid(+ structure: Any,+ *,+ symprec_values: list[float],+ angle_values: list[float],+) -> dict[str, Any]:+ """Evaluate a bounded Cartesian product of symmetry tolerances."""+ combinations = len(symprec_values) * len(angle_values)+ if combinations > 25:+ raise CliError("symmetry tolerance grid may contain at most 25 combinations")+ from pymatgen.symmetry.analyzer import SpacegroupAnalyzer++ rows: list[dict[str, Any]] = []+ assignments: set[tuple[str, int]] = set()+ failures = 0+ for symprec in symprec_values:+ for angle in angle_values:+ try:+ analyzer = SpacegroupAnalyzer(+ structure,+ symprec=symprec,+ angle_tolerance=angle,+ )+ symbol = analyzer.get_space_group_symbol()+ number = int(analyzer.get_space_group_number())+ assignments.add((symbol, number))+ rows.append(+ {+ "symprec_angstrom": symprec,+ "angle_tolerance_degrees": angle,+ "space_group_symbol": symbol,+ "space_group_number": number,+ "crystal_system": str(analyzer.get_crystal_system()),+ "point_group_symbol": analyzer.get_point_group_symbol(),+ "symmetry_operations": len(+ analyzer.get_symmetry_operations()+ ),+ "equivalent_site_groups": len(+ analyzer.get_symmetrized_structure().equivalent_indices+ ),+ }+ )+ except (RuntimeError, TypeError, ValueError) as exc:+ failures += 1+ rows.append(+ {+ "symprec_angstrom": symprec,+ "angle_tolerance_degrees": angle,+ "error": f"{type(exc).__name__}: {exc}"[:500],+ }+ )+ return {+ "backend": "spglib through pymatgen",+ "grid": rows,+ "combinations": combinations,+ "failures": failures,+ "distinct_assignments": [+ {"space_group_symbol": symbol, "space_group_number": number}+ for symbol, number in sorted(assignments, key=lambda item: item[1])+ ],+ "tolerance_sensitive": len(assignments) > 1 or failures > 0,+ "interpretation": (+ "A tolerance-sensitive assignment must be reported with its exact "+ "symprec and angle_tolerance; it is not a unique structure invariant."+ ),+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Compare space-group assignments across a bounded tolerance grid. "+ "The structure is not standardized or written."+ )+ )+ parser.add_argument("structure_file")+ parser.add_argument("--structure-index", type=int, default=0)+ parser.add_argument(+ "--symprec",+ default="0.001,0.01,0.1",+ help="Comma-separated distance tolerances in angstrom",+ )+ parser.add_argument(+ "--angle-tolerance",+ default="1,5",+ help="Comma-separated angle tolerances in degrees",+ )+ parser.add_argument(+ "--allow-disordered",+ action="store_true",+ help="Acknowledge that symmetry assignment for disorder may be misleading",+ )+ parser.add_argument("--output", help="New JSON output; default stdout")+ parser.add_argument(+ "--max-input-bytes",+ type=positive_int,+ default=DEFAULT_MAX_INPUT_BYTES,+ )+ parser.add_argument("--max-sites", type=positive_int, default=DEFAULT_MAX_SITES)+ parser.add_argument(+ "--max-output-bytes",+ type=positive_int,+ default=DEFAULT_MAX_OUTPUT_BYTES,+ )+ return parser+++def main() -> int:+ args = build_parser().parse_args()+ try:+ if args.structure_index < 0:+ raise CliError("--structure-index must be non-negative")+ symprec_values = parse_tolerances(args.symprec, "--symprec")+ angle_values = parse_tolerances(+ args.angle_tolerance, "--angle-tolerance"+ )+ structure, input_path, parse_report = load_structure(+ args.structure_file,+ structure_index=args.structure_index,+ max_bytes=args.max_input_bytes,+ max_sites=args.max_sites,+ )+ if not structure.is_ordered and not args.allow_disordered:+ raise CliError(+ "disordered structure requires --allow-disordered after reviewing "+ "occupancies and the chosen symmetry model"+ )+ report = {+ "ok": True,+ "analysis": "symmetry_tolerance_sensitivity",+ "input": parse_report,+ "structure": {+ "formula": structure.composition.reduced_formula,+ "sites": len(structure),+ "ordered": bool(structure.is_ordered),+ "periodic_boundary_conditions": [+ bool(value) for value in structure.lattice.pbc+ ],+ },+ "symmetry": analyze_grid(+ structure,+ symprec_values=symprec_values,+ angle_values=angle_values,+ ),+ "disorder_acknowledged": bool(args.allow_disordered),+ "structure_modified": False,+ }+ if args.output:+ output = checked_output_file(args.output, input_paths=(input_path,))+ write_json_new(output, report, max_bytes=args.max_output_bytes)+ emit_json(+ {+ "ok": True,+ "output": output.name,+ "overwrote_existing": False,+ "tolerance_sensitive": report["symmetry"][+ "tolerance_sensitive"+ ],+ }+ )+ else:+ emit_json(report)+ return 0+ except (CliError, ImportError, OSError, RuntimeError, TypeError, ValueError) as exc:+ emit_json({"ok": False, "error": f"{type(exc).__name__}: {exc}"[:1000]})+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pymatgen/tests/test_scripts.py b/skills/pymatgen/tests/test_scripts.pynew file mode 100644index 00000000..71a1d390--- /dev/null+++ b/skills/pymatgen/tests/test_scripts.py@@ -0,0 +1,414 @@+"""Dependency-free help checks and pinned-runtime synthetic CLI tests."""++from __future__ import annotations++import contextlib+import io+import json+import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock+++SKILL_ROOT = Path(__file__).resolve().parents[1]+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import mp_query # noqa: E402+import artifact_manifest # noqa: E402+import composition_structure_validator # noqa: E402+import io_conversion_plan # noqa: E402+import phase_diagram_generator # noqa: E402+import structure_analyzer # noqa: E402+import structure_converter # noqa: E402+import symmetry_sensitivity_report # noqa: E402+++CLI_NAMES = (+ "artifact_manifest.py",+ "composition_structure_validator.py",+ "io_conversion_plan.py",+ "mp_query.py",+ "phase_diagram_generator.py",+ "structure_analyzer.py",+ "structure_converter.py",+ "symmetry_sensitivity_report.py",+)+MODULES = {+ "artifact_manifest.py": artifact_manifest,+ "composition_structure_validator.py": composition_structure_validator,+ "io_conversion_plan.py": io_conversion_plan,+ "mp_query.py": mp_query,+ "phase_diagram_generator.py": phase_diagram_generator,+ "structure_analyzer.py": structure_analyzer,+ "structure_converter.py": structure_converter,+ "symmetry_sensitivity_report.py": symmetry_sensitivity_report,+}+++class CliResult:+ def __init__(self, returncode: int, stdout: str, stderr: str):+ self.returncode = returncode+ self.stdout = stdout+ self.stderr = stderr+++def run_script(+ name: str,+ *arguments: str,+ cwd: Path | None = None,+ timeout: int = 60,+) -> CliResult:+ del timeout+ environment = os.environ.copy()+ environment["PYTHONDONTWRITEBYTECODE"] = "1"+ environment.pop("MP_API_KEY", None)+ stdout = io.StringIO()+ stderr = io.StringIO()+ previous = Path.cwd()+ try:+ if cwd is not None:+ os.chdir(cwd)+ with (+ mock.patch.object(sys, "argv", [name, *map(str, arguments)]),+ mock.patch.dict(os.environ, environment, clear=True),+ contextlib.redirect_stdout(stdout),+ contextlib.redirect_stderr(stderr),+ ):+ try:+ status = MODULES[name].main()+ except SystemExit as exc:+ status = int(exc.code or 0)+ finally:+ os.chdir(previous)+ return CliResult(status, stdout.getvalue(), stderr.getvalue())+++def payload(result: CliResult) -> dict:+ try:+ return json.loads(result.stdout)+ except json.JSONDecodeError as exc:+ raise AssertionError(+ f"invalid JSON\nstdout={result.stdout}\nstderr={result.stderr}"+ ) from exc+++class DependencyFreeTests(unittest.TestCase):+ def test_all_helps_work_without_importing_optional_packages(self) -> None:+ for name in CLI_NAMES:+ with self.subTest(name=name):+ result = run_script(name, "--help")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("usage:", result.stdout.casefold())++ def test_io_plan_is_nonexecuting_and_discloses_loss(self) -> None:+ result = run_script(+ "io_conversion_plan.py",+ "--input",+ "input.cif",+ "--output",+ "output.xyz",+ "--input-format",+ "cif",+ "--output-format",+ "xyz",+ "--periodic",+ )+ report = payload(result)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertFalse(report["executed"])+ self.assertFalse(report["files_opened"])+ self.assertTrue(report["representation_risks"])++ def test_mp_query_defaults_to_plan_and_never_reads_key(self) -> None:+ result = run_script(+ "mp_query.py",+ "--chemsys",+ "Li-Fe-O",+ "--energy-above-hull",+ "0",+ "0.05",+ "--fields",+ "formula_pretty,energy_above_hull,origins",+ "--limit",+ "10",+ )+ report = payload(result)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertFalse(report["execute_requested"])+ self.assertFalse(report["network_will_be_accessed"])+ self.assertEqual(report["query"]["limit"], 10)+ self.assertIn("material_id", report["query"]["effective_fields"])++ def test_execute_without_named_key_fails_before_output_or_network(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ result = run_script(+ "mp_query.py",+ "--material-id",+ "mp-149",+ "--fields",+ "formula_pretty",+ "--limit",+ "1",+ "--execute",+ "--output",+ "result.json",+ cwd=root,+ )+ report = payload(result)+ self.assertEqual(result.returncode, 2)+ self.assertIn("MP_API_KEY", report["error"])+ self.assertFalse((root / "result.json").exists())+ self.assertFalse(report["api_key_logged"])+++class PinnedRuntimeTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ try:+ from pymatgen.core import Lattice, Structure+ except ImportError as exc:+ raise unittest.SkipTest("pinned pymatgen runtime not installed") from exc+ cls.Lattice = Lattice+ cls.Structure = Structure++ def write_structure(self, root: Path) -> Path:+ from pymatgen.io.cif import CifWriter++ structure = self.Structure(+ self.Lattice.cubic(5.64),+ ["Na", "Cl"],+ [[0, 0, 0], [0.5, 0.5, 0.5]],+ )+ path = root / "synthetic.cif"+ CifWriter(structure).write_file(path)+ return path++ def test_structure_tools_on_synthetic_crystal(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ self.write_structure(root)+ analyzer = run_script(+ "structure_analyzer.py",+ "synthetic.cif",+ "--symmetry",+ "--max-site-records",+ "10",+ cwd=root,+ )+ analysis = payload(analyzer)+ self.assertEqual(analyzer.returncode, 0, analyzer.stderr)+ self.assertEqual(analysis["composition"]["reduced_formula"], "NaCl")+ self.assertEqual(analysis["sites"]["coordinate_mode"], "fractional")+ self.assertEqual(analysis["symmetry"]["space_group_symbol"], "Pm-3m")++ validator = run_script(+ "composition_structure_validator.py",+ "structure",+ "synthetic.cif",+ cwd=root,+ )+ validation = payload(validator)+ self.assertEqual(validator.returncode, 0, validator.stderr)+ self.assertTrue(validation["ok"])+ self.assertEqual(validation["periodic_boundary_conditions"], [True] * 3)++ symmetry = run_script(+ "symmetry_sensitivity_report.py",+ "synthetic.cif",+ "--symprec",+ "0.001,0.01,0.1",+ "--angle-tolerance",+ "1,5",+ cwd=root,+ )+ sensitivity = payload(symmetry)+ self.assertEqual(symmetry.returncode, 0, symmetry.stderr)+ self.assertEqual(sensitivity["symmetry"]["combinations"], 6)++ def test_composition_conversion_phase_diagram_and_manifest(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ self.write_structure(root)+ composition = run_script(+ "composition_structure_validator.py",+ "composition",+ "Fe2O3",+ cwd=root,+ )+ composition_report = payload(composition)+ self.assertEqual(composition.returncode, 0, composition.stderr)+ self.assertEqual(composition_report["reduced_formula"], "Fe2O3")+ self.assertFalse(+ composition_report["oxidation_state_guess_requested"]+ )++ converted = run_script(+ "structure_converter.py",+ "synthetic.cif",+ "POSCAR.new",+ "--output-format",+ "poscar",+ "--coordinate-mode",+ "direct",+ "--allow-lossy",+ "--acknowledge-parser-warnings",+ cwd=root,+ )+ conversion_report = payload(converted)+ self.assertEqual(converted.returncode, 0, converted.stderr)+ self.assertTrue((root / "POSCAR.new").is_file())+ self.assertFalse(conversion_report["output"]["overwrote_existing"])++ phase_data = {+ "schema_version": "1.0",+ "energy_unit": "eV",+ "energy_basis": "total_per_entry",+ "provenance": {+ "source": "synthetic unit test",+ "method": "invented values; not scientific data",+ },+ "entries": [+ {+ "entry_id": "local-Li",+ "composition": "Li",+ "energy_eV": -1.0,+ "provenance": {"source": "synthetic unit test"},+ },+ {+ "entry_id": "local-O2",+ "composition": "O2",+ "energy_eV": -2.0,+ "provenance": {"source": "synthetic unit test"},+ },+ {+ "entry_id": "local-Li2O",+ "composition": "Li2O",+ "energy_eV": -4.0,+ "provenance": {"source": "synthetic unit test"},+ },+ ],+ }+ (root / "entries.json").write_text(+ json.dumps(phase_data, allow_nan=False),+ encoding="utf-8",+ )+ phase = run_script(+ "phase_diagram_generator.py",+ "entries.json",+ "--analyze",+ "Li2O",+ cwd=root,+ )+ phase_report = payload(phase)+ self.assertEqual(phase.returncode, 0, phase.stderr)+ self.assertEqual(phase_report["chemical_system"], "Li-O")+ self.assertEqual(phase_report["stable_entry_count"], 3)+ self.assertFalse(phase_report["experimental_validity_established"])++ manifest = run_script(+ "artifact_manifest.py",+ "--artifact",+ "entries.json",+ "--artifact",+ "POSCAR.new",+ "--output",+ "manifest.json",+ "--workflow",+ "synthetic pymatgen test",+ cwd=root,+ )+ manifest_report = payload(manifest)+ self.assertEqual(manifest.returncode, 0, manifest.stderr)+ self.assertEqual(manifest_report["artifact_count"], 2)+ self.assertTrue((root / "manifest.json").is_file())++ def test_strict_phase_json_rejects_duplicates(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ (root / "bad.json").write_text(+ '{"schema_version":"1.0","schema_version":"1.0"}',+ encoding="utf-8",+ )+ result = run_script(+ "phase_diagram_generator.py",+ "bad.json",+ cwd=root,+ )+ self.assertEqual(result.returncode, 2)+ self.assertIn("duplicate JSON key", payload(result)["error"])++ def test_mocked_mp_execute_is_bounded_redacted_and_records_db(self) -> None:+ class FakeSummary:+ available_fields = ["material_id", "formula_pretty"]+ kwargs: dict | None = None++ def search(self, **kwargs):+ self.kwargs = kwargs+ return [{"material_id": "mp-149", "formula_pretty": "Si"}]++ class FakeMaterials:+ def __init__(self):+ self.summary = FakeSummary()++ class FakeMPRester:+ instance = None++ def __init__(self, **kwargs):+ self.kwargs = kwargs+ self.db_version = "synthetic-db-version"+ self.materials = FakeMaterials()+ FakeMPRester.instance = self++ def __enter__(self):+ return self++ def __exit__(self, exc_type, exc, traceback):+ return False++ args = mp_query.build_parser().parse_args(+ [+ "--material-id",+ "mp-149",+ "--fields",+ "formula_pretty",+ "--limit",+ "1",+ "--execute",+ "--output",+ "result.json",+ ]+ )+ contract = mp_query.query_contract(args)+ with (+ tempfile.TemporaryDirectory() as temporary,+ mock.patch.dict(+ os.environ,+ {"MP_API_KEY": "synthetic-test-secret"},+ clear=True,+ ),+ mock.patch("mp_api.client.MPRester", FakeMPRester),+ ):+ output = Path(temporary) / "result.json"+ report = mp_query.execute_query(args, contract, output)+ text = output.read_text(encoding="utf-8")+ self.assertEqual(report["returned"], 1)+ self.assertEqual(+ report["provenance"]["database_version"],+ "synthetic-db-version",+ )+ self.assertNotIn("synthetic-test-secret", text)+ instance = FakeMPRester.instance+ self.assertIsNotNone(instance)+ self.assertFalse(instance.kwargs["include_user_agent"])+ self.assertFalse(instance.kwargs["notify_db_version"])+ self.assertEqual(instance.materials.summary.kwargs["num_chunks"], 1)+ self.assertEqual(instance.materials.summary.kwargs["chunk_size"], 1)+++if __name__ == "__main__":+ unittest.main()diff --git a/skills/pymatgen/tests/test_static.py b/skills/pymatgen/tests/test_static.pynew file mode 100644index 00000000..e82cb993--- /dev/null+++ b/skills/pymatgen/tests/test_static.py@@ -0,0 +1,185 @@+"""Static safety, packaging, and documentation checks for the pymatgen skill."""++from __future__ import annotations++import ast+import re+import unittest+from pathlib import Path+++SKILL_ROOT = Path(__file__).resolve().parents[1]+SCRIPTS = SKILL_ROOT / "scripts"+REFERENCES = SKILL_ROOT / "references"+++class SkillStructureTests(unittest.TestCase):+ def test_frontmatter_version_license_compatibility_and_size(self) -> None:+ text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")+ self.assertLess(len(text.splitlines()), 500)+ self.assertIn("\nlicense: MIT\n", text)+ self.assertIn("\ncompatibility:", text)+ self.assertRegex(+ text,+ r'\nmetadata:\n version: "1\.2"\n skill-author:',+ )+ self.assertNotIn('metadata: {"version"', text)+ self.assertIn('last-reviewed: "2026-07-23"', text)++ def test_exactly_five_dated_references(self) -> None:+ expected = {+ "analysis_modules.md",+ "core_classes.md",+ "io_formats.md",+ "materials_project_api.md",+ "transformations_workflows.md",+ }+ paths = sorted(REFERENCES.glob("*.md"))+ self.assertEqual({path.name for path in paths}, expected)+ for path in paths:+ with self.subTest(path=path.name):+ text = path.read_text(encoding="utf-8")+ self.assertIn("Sources (verified 2026-07-23)", text)+ self.assertIn("https://", text)++ def test_relative_markdown_links_resolve(self) -> None:+ link = re.compile(r"\[[^\]]+\]\(([^)]+)\)")+ paths = [SKILL_ROOT / "SKILL.md", *sorted(REFERENCES.glob("*.md"))]+ for path in paths:+ for target in link.findall(path.read_text(encoding="utf-8")):+ if target.startswith(("https://", "http://", "#", "mailto:")):+ continue+ relative = target.split("#", 1)[0]+ self.assertTrue(+ (path.parent / relative).exists(),+ f"missing {target!r} from {path.name}",+ )+++class ScriptSafetyTests(unittest.TestCase):+ def test_scripts_parse_and_keep_optional_imports_lazy(self) -> None:+ allowed_top_level = {+ "__future__",+ "_common",+ "argparse",+ "datetime",+ "hashlib",+ "importlib",+ "json",+ "math",+ "mimetypes",+ "os",+ "pathlib",+ "platform",+ "re",+ "tempfile",+ "typing",+ "warnings",+ }+ for path in sorted(SCRIPTS.glob("*.py")):+ with self.subTest(path=path.name):+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ for node in tree.body:+ if isinstance(node, ast.Import):+ for alias in node.names:+ self.assertIn(+ alias.name.split(".", 1)[0],+ allowed_top_level,+ )+ elif isinstance(node, ast.ImportFrom) and node.module:+ self.assertIn(+ node.module.split(".", 1)[0],+ allowed_top_level,+ )++ def test_scripts_omit_unsafe_execution_and_serialization_primitives(self) -> None:+ forbidden_imports = {+ "ctypes",+ "pickle",+ "requests",+ "socket",+ "subprocess",+ "urllib",+ }+ forbidden_calls = {"eval", "exec", "compile"}+ for path in sorted(SCRIPTS.glob("*.py")):+ with self.subTest(path=path.name):+ source = path.read_text(encoding="utf-8")+ tree = ast.parse(source, filename=str(path))+ for node in ast.walk(tree):+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):+ self.assertNotIn(node.func.id, forbidden_calls)+ if isinstance(node, ast.Import):+ for alias in node.names:+ self.assertNotIn(+ alias.name.split(".", 1)[0],+ forbidden_imports,+ )+ if isinstance(node, ast.ImportFrom) and node.module:+ self.assertNotIn(+ node.module.split(".", 1)[0],+ forbidden_imports,+ )+ self.assertNotIn("pymatgen.ext.matproj", source)++ def test_environment_access_is_one_named_secret_only(self) -> None:+ for path in sorted(SCRIPTS.glob("*.py")):+ source = path.read_text(encoding="utf-8")+ if path.name == "mp_query.py":+ self.assertEqual(+ source.count('os.getenv("MP_API_KEY")'),+ 1,+ )+ without_expected = source.replace(+ 'os.getenv("MP_API_KEY")', ""+ )+ self.assertNotIn("os.environ", without_expected)+ self.assertNotIn("os.getenv", without_expected)+ else:+ self.assertNotIn("os.environ", source)+ self.assertNotIn("os.getenv", source)++ def test_no_bytecode_or_generated_artifacts(self) -> None:+ forbidden = [+ *SKILL_ROOT.rglob("__pycache__"),+ *SKILL_ROOT.rglob("*.pyc"),+ *SKILL_ROOT.rglob("*.pyo"),+ *SKILL_ROOT.rglob("*.json.tmp"),+ ]+ self.assertEqual(forbidden, [])++ def test_documented_cli_inventory_exists(self) -> None:+ expected = {+ "artifact_manifest.py",+ "composition_structure_validator.py",+ "io_conversion_plan.py",+ "mp_query.py",+ "phase_diagram_generator.py",+ "structure_analyzer.py",+ "structure_converter.py",+ "symmetry_sensitivity_report.py",+ }+ self.assertTrue(+ expected.issubset({path.name for path in SCRIPTS.glob("*.py")})+ )+ skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")+ for name in expected:+ self.assertIn(f"scripts/{name}", skill)+++class StalenessTests(unittest.TestCase):+ def test_no_stale_install_or_api_patterns(self) -> None:+ markdown = "\n".join(+ path.read_text(encoding="utf-8")+ for path in [SKILL_ROOT / "SKILL.md", *sorted(REFERENCES.glob("*.md"))]+ )+ self.assertNotRegex(markdown, r"(?m)^\s*pip install\b")+ self.assertNotIn("pymatgen.ext.matproj", markdown)+ self.assertNotIn("CifParser.get_structures", markdown)+ self.assertNotIn("MAPI_KEY", markdown)+ self.assertNotIn("pymatgen >= 2023", markdown)+ self.assertNotIn("pymatgen 2024.x", markdown)+++if __name__ == "__main__":+ unittest.main()