Pymatgen Defects Analysis

2026.3.20 · active · verified Thu Apr 16

Pymatgen-analysis-defects is an extension to the core pymatgen library, providing robust tools for analyzing point defects in crystalline materials. It is designed to work seamlessly with VASP inputs and outputs and offers an object-oriented interface to defect physics. The package, currently at version 2026.3.20, is actively maintained with a regular release cadence and is closely integrated with the atomate2 workflow framework, although it can also be used standalone for defect analysis.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pymatgen-analysis-defects` to generate a list of native point defects for a material fetched from the Materials Project database. It utilizes `MPRester` from `mp-api` to retrieve a structure and then `generate_all_native_defects` to enumerate possible defects.

import os
from mp_api.client import MPRester
from pymatgen.analysis.defects.generators import generate_all_native_defects

# Replace with your Materials Project API key if needed
# For quickstart, using os.environ.get is safer for direct execution
api_key = os.environ.get("MP_API_KEY", "") 

if api_key:
    try:
        with MPRester(api_key=api_key) as mpr:
            # Fetch a charge density object for a material (e.g., mp-804 for SrTiO3)
            print("Fetching charge density from Materials Project...")
            chgcar = mpr.get_charge_density_from_material_id("mp-804")

            # Generate all native defects for the fetched structure
            print("Generating native defects...")
            native_defects = generate_all_native_defects(chgcar.structure)

            print(f"Found {len(native_defects)} native defects. First 3 examples:")
            for i, defect in enumerate(native_defects[:3]):
                print(f"  Defect {i+1}: {defect.name}, Charge states: {defect.charge_states}")
    except Exception as e:
        print(f"An error occurred while connecting to MPRester or processing data: {e}")
        print("Ensure your MP_API_KEY is correct and you have internet access.")
else:
    print("MP_API_KEY not found. Skipping Materials Project API example.")
    print("Please set the MP_API_KEY environment variable to run this example.")

view raw JSON →