alterlab-pymatgen

$npx mdskill add AlterLab-IEU/AlterLab-Academic-Skills/alterlab-pymatgen

Analyze and manipulate materials structures and properties with pymatgen.

  • Convert between structure formats like CIF, POSCAR, and XYZ.
  • Requires pymatgen Python package and optionally a Materials Project API key.
  • Uses pymatgen's built-in methods for symmetry, thermodynamics, and electronic structure analysis.
  • Returns structures, phase diagrams, or electronic data as files or in-memory objects.

SKILL.md

.github/skills/alterlab-pymatgenView on GitHub ↗
---
name: alterlab-pymatgen
description: Analyzes and manipulates materials with the pymatgen toolkit — crystal structures and molecules, phase diagrams and thermodynamic stability, electronic structure (band structures, DOS), surfaces and interfaces, and Materials Project database access. Use when working with crystal structures in materials science, converting between structure formats (CIF, POSCAR, XYZ), analyzing symmetry or space groups, computing phase diagrams, querying the Materials Project API, or handling VASP, Gaussian, or Quantum ESPRESSO output. Part of the AlterLab Academic Skills suite.
license: MIT
allowed-tools: Read Write Edit Bash(python:*)
compatibility: Runs locally via `uv run python`; requires the pymatgen Python package. Materials Project database queries need a free MP_API_KEY.
metadata:
    skill-author: AlterLab
    version: "1.0.0"
---

# Pymatgen - Python Materials Genomics

## Overview

Pymatgen is a comprehensive Python library for materials analysis that powers the
Materials Project. Create, analyze, and manipulate crystal structures and molecules;
compute phase diagrams and thermodynamic properties; analyze electronic structure (band
structures, DOS); generate surfaces and interfaces; and access the Materials Project
database. Supports 100+ file formats from various computational codes.

## When to Use This Skill

Use when:
- Working with crystal structures or molecular systems in materials science
- Converting between structure file formats (CIF, POSCAR, XYZ, etc.)
- Analyzing symmetry, space groups, or coordination environments
- Computing phase diagrams or assessing thermodynamic stability
- Analyzing electronic structure (band gaps, DOS, band structures)
- Generating surfaces/slabs or studying interfaces
- Accessing the Materials Project database programmatically
- Setting up high-throughput computational workflows
- Working with VASP, Gaussian, Quantum ESPRESSO, or other codes

## Quick Start

```bash
uv pip install pymatgen           # core
uv pip install pymatgen mp-api    # + Materials Project API access
uv pip install pymatgen[analysis] # extended analysis tools
uv pip install pymatgen[vis]      # visualization tools
```

```python
from pymatgen.core import Structure, Lattice

struct = Structure.from_file("POSCAR")        # auto format detection
struct.to(filename="structure.cif")           # write any format
print(struct.composition.reduced_formula)
print(struct.get_space_group_info())
print(f"{struct.density:.2f} g/cm³")
```

```bash
export MP_API_KEY="your_api_key_here"   # for Materials Project access
```

## Core Capabilities (routing)

Each capability has a copy-paste code block in `references/core_examples.md` and deeper
module docs in the references listed below.

1. **Structure creation & manipulation** — from files, from scratch (lattice params or
   space group), transformations (supercell, substitution, primitive). → `core_classes.md`
2. **File-format conversion** — `from_file()`/`to()` plus `scripts/structure_converter.py`
   for single/batch. → `io_formats.md`
3. **Structure analysis & symmetry** — `SpacegroupAnalyzer`, `CrystalNN`, plus
   `scripts/structure_analyzer.py`. → `analysis_modules.md`
4. **Phase diagrams & thermodynamics** — `PhaseDiagram`, energy-above-hull, decomposition,
   plus `scripts/phase_diagram_generator.py`. → `analysis_modules.md`, `transformations_workflows.md`
5. **Electronic structure** — band structures and DOS from `Vasprun`, band gaps,
   metallicity. → `analysis_modules.md`, `io_formats.md`
6. **Surfaces & interfaces** — `SlabGenerator`, `WulffShape`, `AdsorbateSiteFinder`.
   → `analysis_modules.md`, `transformations_workflows.md`
7. **Materials Project access** — `MPRester` search and retrieval with property filters.
   → `materials_project_api.md`
8. **Computational workflow setup** — VASP input sets (`MPRelaxSet`, `MPStaticSet`,
   `MPNonSCFSet`), Gaussian, Quantum ESPRESSO. → `io_formats.md`, `transformations_workflows.md`
9. **Advanced analysis** — XRD patterns, elastic tensors, magnetic ordering.
   → `analysis_modules.md`

Multi-step worked examples (high-throughput generation, band-structure pipeline, surface
energy): `references/common_workflows_code.md`.

## Bundled Resources

### Scripts (`scripts/`)

- **`structure_converter.py`**: convert between structure file formats (batch + auto
  detection). Usage: `python scripts/structure_converter.py POSCAR structure.cif`
- **`structure_analyzer.py`**: symmetry, coordination, lattice parameters, distance
  matrix. Usage: `python scripts/structure_analyzer.py structure.cif --symmetry --neighbors`
- **`phase_diagram_generator.py`**: phase diagrams from Materials Project, stability
  analysis. Usage: `python scripts/phase_diagram_generator.py Li-Fe-O --analyze "LiFeO2"`

All scripts include detailed help, e.g. `python scripts/structure_converter.py --help`

### References (`references/`)

- **`core_examples.md`**: copy-paste code for all nine core capabilities
- **`common_workflows_code.md`**: multi-step worked workflow code
- **`core_classes.md`**: Element, Structure, Lattice, Molecule, Composition classes
- **`io_formats.md`**: file-format support and code integration (VASP, Gaussian, etc.)
- **`analysis_modules.md`**: phase diagrams, surfaces, electronic structure, symmetry
- **`materials_project_api.md`**: complete Materials Project API guide
- **`transformations_workflows.md`**: transformations framework and 10 common workflows

## Best Practices

**Structures**: use auto format detection; prefer `IStructure` when immutable; reduce to
primitive cell with `SpacegroupAnalyzer`; validate for overlapping atoms / bad bond
lengths. **File I/O**: prefer `from_file()`/`to()`; specify format when detection fails;
use `as_dict()`/`from_dict()` for version-safe storage. **MP API**: always use the context
manager; batch queries; cache results; filter by property. **Workflows**: prefer input
sets over manual INCAR; verify convergence; track transformations for provenance.
**Performance**: use primitive cells; bound neighbor-search cutoffs; parallelize where
possible.

## Units and Conventions

Lengths in Å, energies in eV, angles in degrees, magnetic moments in μB, time in fs.
Convert with `pymatgen.core.units`.

## Integration

Integrates with ASE, Phonopy, BoltzTraP, Atomate/Fireworks, AiiDA, Zeo++, and OpenBabel.

## Troubleshooting

- **Import errors**: `uv pip install pymatgen[analysis,vis]`
- **API key not found**: `export MP_API_KEY="your_key_here"`
- **Structure read failures**: try explicit format, e.g. `Structure.from_file("file.txt", fmt="cif")`
- **Symmetry analysis fails**: increase tolerance, e.g. `SpacegroupAnalyzer(struct, symprec=0.1)`

## Additional Resources

Docs: https://pymatgen.org/ · Materials Project: https://materialsproject.org/ ·
GitHub: https://github.com/materialsproject/pymatgen · Forum: https://matsci.org/ ·
Example notebooks: https://matgenb.materialsvirtuallab.org/

## Version Notes

Designed for pymatgen 2024.x and later. For the Materials Project API, use the `mp-api`
package (separate from legacy `pymatgen.ext.matproj`). Requirements: Python ≥ 3.10,
pymatgen ≥ 2023.x, mp-api (for Materials Project access).

More from AlterLab-IEU/AlterLab-Academic-Skills

SkillDescription
alterlab-abm-mesaBuilds agent-based models of social systems with Mesa 3 — the current AgentSet API (model.agents.shuffle_do('step'), auto-assigned unique_id, mandatory super().__init__(seed=...)), cell spaces (mesa.discrete_space OrthogonalMooreGrid / classic mesa.space grids), the DataCollector, batch_run parameter sweeps, and SolaraViz — for emergence, segregation, diffusion, opinion dynamics, and cooperation models. It uses the Mesa 3.x API (the old mesa.time schedulers like RandomActivation are removed) and treats the model as a generative theory to be validated, not just run. Use when the request mentions an agent-based model, Mesa, simulating interacting agents, or emergent macro behavior from micro rules. For discrete-event (queueing/process) simulation prefer alterlab-simpy; for reinforcement learning prefer alterlab-stable-baselines3. Part of the AlterLab Academic Skills suite.
alterlab-academic-careerPrepares academic career documents and professional-development materials for faculty and researchers. Use when drafting academic CVs, research statements, teaching philosophies, diversity statements, faculty-position cover letters, tenure dossiers, promotion narratives, academic portfolios, or mentorship statements, and when planning conference-networking strategy, building academic web presence, setting up ORCID profiles, or understanding impact metrics. Part of the AlterLab Academic Skills suite.
alterlab-accreditation-aolScaffolds program-level Assurance-of-Learning (AoL) documentation for AACSB (2020 Standard 5) and ABET (Criterion 3 Student Outcomes, Criterion 4 Continuous Improvement) accreditation — program learning outcomes / competency goals, curriculum-to-outcome mapping matrices, direct- and indirect-assessment plans, rubric design, and closing-the-loop continuous-improvement narratives — and validates the structure of an outcome-mapping matrix with scripts/aol_matrix.py. Use when the user needs AACSB or ABET assurance-of-learning material, a program-learning-outcomes set, a curriculum/outcome map or coverage matrix, a direct/indirect assessment plan, a closing-the-loop report, or accreditation self-study text. For single-course design or course rubrics prefer alterlab-teaching-design; for post-award grant reports prefer alterlab-grant-reporting. Part of the AlterLab Academic Skills suite.
alterlab-adaptyvSubmits and tracks protein-testing experiments on the Adaptyv Bio Foundry cloud lab (wet-lab validation), and optimizes protein sequences before submission with computational tools (NetSolP, SoluProt, SolubleMPNN, ESM). Use when designing proteins that need wet-lab validation - binding/affinity screening, expression testing, thermostability, or fluorescence assays - or when submitting experiments to the Foundry API, browsing the target catalog, tracking experiment status, retrieving results, or pre-screening sequences for solubility/expression. Triggers on "Adaptyv", "Foundry API", "cloud lab", "biolayer interferometry / BLI", "wet-lab validation". Part of the AlterLab Academic Skills suite.
alterlab-aeonRuns time series machine learning with the aeon library — classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search via scikit-learn compatible APIs. Use when working with temporal data, sequential patterns, or time-indexed observations (univariate or multivariate) that need specialized algorithms beyond standard ML approaches. Part of the AlterLab Academic Skills suite.
alterlab-akademik-tesvikComputes the annual Turkish academic-incentive (akademik teşvik) score for Devlet (state) university öğretim elemanı (academic staff) from a classified activity list, applying the verified Akademik Teşvik Ödeneği Yönetmeliği (2018/11834) Faaliyet Hesaplama Tablosu headline puanları (Proje 20, Araştırma 15, Yayın 30, Patent 30, Atıf 30, Tebliğ 20, Ödül 20) with the k (author-count), p (Q1 1/Q2 0.8/Q3 0.5/Q4 0.25), and r (project-role) coefficients via türü puanı = Σ(faaliyet oranları) × headline (MADDE 8/2), then enforcing the per-type headline ceilings, the 100 cap (MADDE 8/3), and the net-30 payment gate (MADDE 10/3) in a deterministic scripts/tesvik_score.py. Use when the user wants to calculate akademik teşvik puanı, check the en az 30 (net-30) threshold, apply TABLO 4 ceilings, or estimate teşvik eligibility; keeps its coefficients separate from doçentlik scoring. For doçentlik point eligibility prefer alterlab-docentlik-eligibility. Part of the AlterLab Academic Skills suite.
alterlab-alpha-vantageAccesses real-time and historical stock market data, forex rates, cryptocurrency prices, commodities, economic indicators, and 50+ technical indicators via the Alpha Vantage API (requires a free API key from alphavantage.co). Use when fetching stock prices (OHLCV), company fundamentals (income statement, balance sheet, cash flow), earnings, options data, market news/sentiment, insider transactions, GDP, CPI, treasury yields, gold/silver/oil prices, Bitcoin/crypto prices, forex exchange rates, or calculating technical indicators (SMA, EMA, MACD, RSI, Bollinger Bands). Part of the AlterLab Academic Skills suite.
alterlab-alphafoldPredict protein 3D structures with AlphaFold2 via ColabFold — MMseqs2-accelerated MSAs, monomer and AlphaFold2-Multimer complex folding, and confidence-based validation (pLDDT, pTM/ipTM, PAE). Use when folding a protein sequence or complex from FASTA, generating a predicted structure with confidence metrics, ranking models, or checking self-consistency of a design. For co-folding a protein WITH a small-molecule ligand or predicting binding affinity prefer alterlab-boltz; for antibody–antigen or one-FASTA multi-entity complexes prefer alterlab-chai; to LOOK UP an already-computed structure prefer alterlab-alphafold-db; for ESM embeddings or inverse folding prefer alterlab-esm. Part of the AlterLab Academic Skills suite.
alterlab-alphafold-dbAccess the AlphaFold DB of 200M+ AI-PREDICTED protein structures — retrieve models by UniProt accession, download PDB/mmCIF files, and analyze prediction confidence metrics (pLDDT, PAE). Use when a UniProt ID needs a computationally predicted 3D structure or when no experimental structure exists, for homology modeling, protein engineering, or structure-based drug discovery; for EXPERIMENTALLY determined structures (X-ray, cryo-EM, NMR) prefer alterlab-pdb, and for protein sequences, annotations, or accession ID mapping prefer alterlab-uniprot instead. Part of the AlterLab Academic Skills suite.
alterlab-anndataBuild, slice, concatenate, read, and write AnnData annotated data matrices (obs, var, X, layers, obsm, uns) — the scverse data STRUCTURE, not an analysis pipeline. Use when creating or wrangling .h5ad/zarr files, managing cell and gene annotations, concatenating batches, or handling layers/obsm/backed-mode; for the QC, normalization, clustering, UMAP, and differential-expression analysis pipeline prefer alterlab-scanpy instead, and for RNA velocity from spliced/unspliced layers prefer alterlab-scvelo instead. Part of the AlterLab Academic Skills suite.