CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pymatgen

Comprehensive materials science analysis library for crystal structures, molecules, and materials data with extensive computational chemistry integration.

Pending
Overview
Eval results
Files

io-formats.mddocs/

File I/O & Format Support

Extensive I/O support for electronic structure codes (VASP, Quantum ESPRESSO, Gaussian, etc.), structure formats (CIF, XYZ, POSCAR), and materials databases. These capabilities enable seamless integration with computational workflows and data exchange between different software packages in materials science.

Capabilities

VASP I/O

Comprehensive support for Vienna Ab initio Simulation Package (VASP) input and output files.

class Poscar:
    """
    VASP POSCAR file handling for structure input/output.
    
    Parameters:
    - structure: Structure object
    - comment: Comment line for POSCAR
    - selective_dynamics: Selective dynamics array
    - true_names: Whether to use true element names
    - velocities: Atomic velocities for MD
    - predictor_corrector: Predictor-corrector data
    - predictor_corrector_preamble: PC preamble text
    """
    def __init__(self, structure, comment=None, selective_dynamics=None,
                 true_names=True, velocities=None, predictor_corrector=None,
                 predictor_corrector_preamble=None): ...
    
    @classmethod
    def from_file(cls, filename, check_for_potcar=True, read_velocities=True):
        """
        Read POSCAR from file.
        
        Parameters:
        filename: Path to POSCAR file
        check_for_potcar: Whether to check for POTCAR consistency
        read_velocities: Whether to read velocity data
        
        Returns:
        Poscar: POSCAR object
        """
    
    @classmethod
    def from_string(cls, data, default_names=None, read_velocities=True):
        """
        Read POSCAR from string.
        
        Parameters:
        data: POSCAR string data
        default_names: Default element names if not specified
        read_velocities: Whether to read velocities
        
        Returns:
        Poscar: POSCAR object
        """
    
    def write_file(self, filename, **kwargs):
        """
        Write POSCAR to file.
        
        Parameters:
        filename: Output filename
        """
    
    def get_string(self, direct=True, vasp4_compatible=False, 
                  significant_figures=6):
        """
        Get POSCAR string representation.
        
        Parameters:
        direct: Whether to use direct coordinates
        vasp4_compatible: Whether to use VASP4 format
        significant_figures: Number of significant figures
        
        Returns:
        str: POSCAR string
        """
    
    @property
    def structure(self):
        """Structure object."""
    
    @property
    def comment(self):
        """Comment string."""
    
    @property
    def natoms(self):
        """Number of atoms by species."""
    
    @property
    def site_symbols(self):
        """Site symbols array."""
class Incar:
    """
    VASP INCAR file handling for calculation parameters.
    
    Parameters:
    - params: Dictionary of INCAR parameters
    """
    def __init__(self, params=None): ...
    
    @classmethod
    def from_file(cls, filename):
        """
        Read INCAR from file.
        
        Parameters:
        filename: Path to INCAR file
        
        Returns:
        Incar: INCAR object
        """
    
    @classmethod
    def from_string(cls, string):
        """
        Read INCAR from string.
        
        Parameters:
        string: INCAR string data
        
        Returns:
        Incar: INCAR object
        """
    
    def write_file(self, filename):
        """
        Write INCAR to file.
        
        Parameters:
        filename: Output filename
        """
    
    def get_string(self, sort_keys=False, pretty=False):
        """
        Get INCAR string representation.
        
        Parameters:
        sort_keys: Whether to sort parameter keys
        pretty: Whether to format for readability
        
        Returns:
        str: INCAR string
        """
    
    def __getitem__(self, key): ...
    def __setitem__(self, key, val): ...
    def __delitem__(self, key): ...
    def __contains__(self, key): ...
    
    def check_params(self):
        """
        Check INCAR parameters for common issues.
        
        Returns:
        list: List of warnings/errors found
        """
    
    def diff(self, other):
        """
        Compare with another INCAR.
        
        Parameters:
        other: Another Incar object
        
        Returns:
        dict: Differences between INCARs
        """
class Kpoints:
    """
    VASP KPOINTS file handling for k-point mesh specifications.
    
    Parameters:
    - comment: Comment line
    - num_kpts: Number of k-points  
    - style: K-points style (Gamma, Monkhorst-Pack, etc.)
    - kpts: K-points array
    - kpts_weights: K-point weights
    - coord_type: Coordinate type (Reciprocal, Cartesian)
    - kpts_shift: K-point shift
    - tet_number: Tetrahedron method number
    - tet_weight: Tetrahedron weights
    - tet_connections: Tetrahedron connections
    """
    def __init__(self, comment="Default gamma", num_kpts=0, 
                 style=Kpoints_supported_modes.Gamma, 
                 kpts=((1, 1, 1),), kpts_weights=None,
                 coord_type=None, kpts_shift=(0, 0, 0),
                 tet_number=0, tet_weight=0, tet_connections=None): ...
    
    @classmethod
    def gamma_automatic(cls, kpts=(1, 1, 1), shift=(0, 0, 0)):
        """
        Create Gamma-centered automatic k-point mesh.
        
        Parameters:
        kpts: K-point mesh dimensions
        shift: K-point shift
        
        Returns:
        Kpoints: Gamma automatic k-points
        """
    
    @classmethod
    def monkhorst_automatic(cls, kpts=(2, 2, 2), shift=(0, 0, 0)):
        """
        Create Monkhorst-Pack automatic k-point mesh.
        
        Parameters:
        kpts: K-point mesh dimensions  
        shift: K-point shift
        
        Returns:
        Kpoints: Monkhorst-Pack k-points
        """
    
    @classmethod
    def automatic_density(cls, structure, kppa, force_gamma=False):
        """
        Create automatic k-point mesh based on density.
        
        Parameters:
        structure: Structure object
        kppa: K-points per atom
        force_gamma: Whether to force Gamma-centered mesh
        
        Returns:
        Kpoints: Automatic density k-points
        """
    
    @classmethod
    def automatic_linemode(cls, divisions, ibz):
        """
        Create automatic line-mode k-points for band structure.
        
        Parameters:
        divisions: Number of divisions between k-points
        ibz: Irreducible Brillouin zone object
        
        Returns:
        Kpoints: Line-mode k-points
        """
    
    @classmethod
    def from_file(cls, filename):
        """Read KPOINTS from file."""
    
    @classmethod
    def from_string(cls, string):
        """Read KPOINTS from string."""
    
    def write_file(self, filename):
        """Write KPOINTS to file."""
    
    def get_string(self):
        """Get KPOINTS string representation."""
class Vasprun:
    """
    VASP vasprun.xml output file parsing and analysis.
    
    Parameters:
    - filename: Path to vasprun.xml file
    - ionic_step_skip: Number of ionic steps to skip
    - ionic_step_offset: Ionic step offset
    - parse_dos: Whether to parse DOS data
    - parse_eigen: Whether to parse eigenvalue data  
    - parse_projected_eigen: Whether to parse projected eigenvalues
    - parse_potcar_file: Whether to parse POTCAR info
    - occu_tol: Occupation tolerance for metallic systems
    - exception_on_bad_xml: Whether to raise exception on bad XML
    """
    def __init__(self, filename, ionic_step_skip=None, ionic_step_offset=0,
                 parse_dos=True, parse_eigen=True, parse_projected_eigen=True,
                 parse_potcar_file=True, occu_tol=1e-8, exception_on_bad_xml=True): ...
    
    def get_band_structure(self, kpoints_filename=None, efermi=None, 
                          line_mode=False, force_hybrid_mode=False):
        """
        Get band structure from calculation.
        
        Parameters:
        kpoints_filename: Path to KPOINTS file for labeling
        efermi: Fermi energy override
        line_mode: Whether calculation was in line mode
        force_hybrid_mode: Force hybrid functional mode
        
        Returns:
        BandStructure or BandStructureSymmLine: Band structure object
        """
    
    def get_dos(self):
        """
        Get density of states.
        
        Returns:
        CompleteDos: Complete DOS object with projections
        """
    
    def get_trajectories(self):
        """
        Get MD trajectories.
        
        Returns:  
        list: List of trajectory data
        """
    
    def get_computed_entry(self, inc_structure=True, parameters=None,
                          data=None):
        """
        Get computed entry for the calculation.
        
        Parameters:
        inc_structure: Whether to include structure
        parameters: Additional parameters to include
        data: Additional data to include
        
        Returns:
        ComputedEntry or ComputedStructureEntry: Entry object
        """
    
    @property
    def final_structure(self):
        """Final optimized structure."""
    
    @property  
    def initial_structure(self):
        """Initial structure."""
    
    @property
    def final_energy(self):
        """Final total energy."""
    
    @property
    def structures(self):
        """All structures from ionic steps."""
    
    @property
    def ionic_steps(self):
        """Ionic step data."""
    
    @property
    def electronic_steps(self):
        """Electronic step data."""
    
    @property
    def dielectric(self):
        """Dielectric tensor data."""
    
    @property
    def optical_absorption_coeff(self):
        """Optical absorption coefficient."""
    
    @property
    def epsilon_static(self):
        """Static dielectric constant."""
    
    @property
    def epsilon_ionic(self):
        """Ionic contribution to dielectric constant."""
    
    @property
    def nionic_steps(self):
        """Number of ionic steps."""
    
    @property
    def md_data(self):
        """Molecular dynamics data."""
    
    @property
    def converged_electronic(self):
        """Whether electronic steps converged."""
    
    @property
    def converged_ionic(self):
        """Whether ionic steps converged."""
    
    @property
    def converged(self):
        """Whether calculation converged."""
class Outcar:
    """
    VASP OUTCAR file parsing.
    
    Parameters:
    - filename: Path to OUTCAR file
    """
    def __init__(self, filename): ...
    
    @property
    def magnetization(self):
        """Atomic magnetizations."""
    
    @property
    def chemical_shielding(self):
        """NMR chemical shielding tensors."""
    
    @property
    def unsym_cs_tensor(self):
        """Unsymmetrized chemical shielding tensor."""
    
    @property
    def cs_g0_contribution(self):
        """G=0 contribution to chemical shielding."""
    
    @property
    def cs_core_contribution(self):
        """Core contribution to chemical shielding."""
    
    @property
    def efg(self):
        """Electric field gradient tensors."""
    
    @property
    def charge(self):
        """Atomic charges."""
    
    @property
    def is_stopped(self):
        """Whether calculation was stopped."""
    
    @property
    def run_stats(self):
        """Runtime statistics."""
    
    @property
    def elastic_tensor(self):
        """Elastic tensor."""
    
    @property
    def piezo_tensor(self):
        """Piezoelectric tensor."""
    
    @property
    def dielectric_tensor(self):
        """Dielectric tensor."""
    
    @property
    def born(self):
        """Born effective charges."""
    
    @property
    def total_mag(self):
        """Total magnetization."""
    
    @property
    def nelect(self):
        """Number of electrons."""
    
    @property
    def efermi(self):
        """Fermi energy."""
    
    @property
    def lepsilon(self):
        """Whether LEPSILON was set."""
    
    @property
    def lcalcpol(self):
        """Whether LCALCPOL was set."""

Quantum ESPRESSO I/O

Support for Quantum ESPRESSO plane-wave DFT code input and output.

class PWInput:
    """
    Quantum ESPRESSO PWscf input file handling.
    
    Parameters:
    - structure: Structure object
    - control: Control parameters dict
    - system: System parameters dict  
    - electrons: Electrons parameters dict
    - ions: Ions parameters dict
    - cell: Cell parameters dict
    - kpoints_mode: K-points specification mode
    - kpoints_grid: K-points grid
    - kpoints_shift: K-points shift
    """
    def __init__(self, structure, control=None, system=None, electrons=None,
                 ions=None, cell=None, kpoints_mode="automatic", 
                 kpoints_grid=(1, 1, 1), kpoints_shift=(0, 0, 0)): ...
    
    @classmethod
    def from_file(cls, filename):
        """
        Read PWInput from file.
        
        Parameters:
        filename: Path to input file
        
        Returns:
        PWInput: PWInput object
        """
    
    @classmethod
    def from_string(cls, string):
        """Read PWInput from string."""
    
    def write_file(self, filename):
        """Write PWInput to file."""
    
    def get_string(self):
        """Get input file string representation."""
    
    @property
    def structure(self):
        """Structure object."""
class PWOutput:
    """
    Quantum ESPRESSO PWscf output file parsing.
    
    Parameters:
    - filename: Path to output file
    """
    def __init__(self, filename): ...
    
    @property
    def final_structure(self):
        """Final optimized structure."""
    
    @property
    def final_energy(self):
        """Final total energy."""
    
    @property
    def structures(self):
        """All structures from optimization."""
    
    @property
    def lattice_type(self):
        """Lattice type."""
    
    @property
    def stress(self):
        """Stress tensor."""
    
    @property
    def convergence_data(self):
        """SCF convergence data."""

Gaussian I/O

Support for Gaussian quantum chemistry package input and output.

class GaussianInput:
    """
    Gaussian input file generation.
    
    Parameters:
    - mol: Molecule object
    - charge: Molecular charge
    - spin_multiplicity: Spin multiplicity
    - title: Job title
    - functional: DFT functional
    - basis_set: Basis set
    - route_parameters: Route section parameters
    - input_parameters: Additional input parameters
    - link0_parameters: Link 0 parameters
    - dieze_tag: Dieze tag for job type
    """
    def __init__(self, mol, charge=0, spin_multiplicity=None, title="",
                 functional="HF", basis_set="6-31G(d)", route_parameters=None,
                 input_parameters=None, link0_parameters=None, dieze_tag="#P"): ...
    
    @classmethod
    def from_file(cls, filename):
        """Read GaussianInput from file."""
    
    @classmethod  
    def from_string(cls, contents):
        """Read GaussianInput from string."""
    
    def write_file(self, filename, cart_coords=False):
        """
        Write Gaussian input file.
        
        Parameters:
        filename: Output filename
        cart_coords: Whether to use Cartesian coordinates
        """
    
    def get_string(self, cart_coords=False):
        """Get input file string representation."""
    
    @property
    def molecule(self):
        """Molecule object."""
class GaussianOutput:
    """
    Gaussian output file parsing.
    
    Parameters:
    - filename: Path to output file
    """
    def __init__(self, filename): ...
    
    @property
    def structures(self):
        """All molecular structures from output."""
    
    @property
    def final_structure(self):
        """Final optimized structure."""
    
    @property
    def final_energy(self):
        """Final energy."""
    
    @property
    def energies(self):
        """All energies from optimization/scan."""
    
    @property
    def eigenvalues(self):
        """Orbital eigenvalues."""
    
    @property
    def molecular_orbital(self):
        """Molecular orbital data."""
    
    @property
    def basis_set(self):
        """Basis set information."""
    
    @property
    def bond_orders(self):
        """Mayer bond orders."""
    
    @property
    def cartesian_forces(self):
        """Cartesian forces."""
    
    @property
    def frequencies(self):
        """Vibrational frequencies."""
    
    @property
    def frequency_modes(self):
        """Vibrational modes."""
    
    @property
    def hessian(self):
        """Hessian matrix."""
    
    @property
    def properly_terminated(self):
        """Whether calculation terminated properly."""
    
    @property
    def is_pcm(self):
        """Whether PCM solvation was used."""
    
    @property
    def errors(self):
        """Errors encountered during calculation."""
    
    @property
    def num_basis_func(self):
        """Number of basis functions."""

Structure File Formats

Support for common crystallographic and molecular file formats.

class CifParser:
    """
    Crystallographic Information File (CIF) parser.
    
    Parameters:
    - filename: Path to CIF file
    - occupancy_tolerance: Tolerance for occupancy checking
    - site_tolerance: Site tolerance for structure generation
    """
    def __init__(self, filename, occupancy_tolerance=1.0, site_tolerance=1e-4): ...
    
    def get_structures(self, primitive=True, symmetrized=False, 
                      conventional_unit_cell=False):
        """
        Get structures from CIF file.
        
        Parameters:
        primitive: Whether to return primitive cell
        symmetrized: Whether to return symmetrized structure
        conventional_unit_cell: Whether to return conventional unit cell
        
        Returns:
        list: List of Structure objects
        """
    
    def get_bibtex_string(self):
        """
        Get BibTeX citation string.
        
        Returns:
        str: BibTeX citation
        """
    
    @property
    def has_errors(self):
        """Whether parser encountered errors."""
    
    @property
    def errors(self):
        """List of parsing errors."""
class CifWriter:
    """
    CIF file writer.
    
    Parameters:
    - struct: Structure object to write
    - symprec: Symmetry precision for space group detection
    """
    def __init__(self, struct, symprec=None): ...
    
    def write_file(self, filename):
        """
        Write structure to CIF file.
        
        Parameters:
        filename: Output filename
        """
    
    def __str__(self):
        """Get CIF string representation."""
class XYZ:
    """
    XYZ format file handling for molecular structures.
    
    Parameters:
    - mol: Molecule object
    - coord_precision: Coordinate precision for output
    """
    def __init__(self, mol, coord_precision=6): ...
    
    @classmethod
    def from_file(cls, filename):
        """
        Read XYZ from file.
        
        Parameters:
        filename: Path to XYZ file
        
        Returns:
        XYZ: XYZ object
        """
    
    @classmethod
    def from_string(cls, contents):
        """Read XYZ from string."""
    
    def write_file(self, filename):
        """Write XYZ to file."""
    
    def get_string(self):
        """Get XYZ string representation."""
    
    @property
    def molecule(self):
        """Molecule object."""
    
    def all_molecules(self):
        """
        Get all molecules if multi-molecule XYZ.
        
        Returns:
        list: List of Molecule objects
        """

Materials Database Interfaces

Interfaces for accessing materials databases and repositories.

class MPRester:
    """
    Materials Project REST interface for accessing MP database.
    
    Parameters:
    - api_key: Materials Project API key
    - endpoint: API endpoint URL
    """
    def __init__(self, api_key=None, endpoint=None): ...
    
    def get_structure_by_material_id(self, material_id, final=True):
        """
        Get structure by Materials Project ID.
        
        Parameters:
        material_id: MP material ID (e.g., "mp-149")
        final: Whether to get final relaxed structure
        
        Returns:
        Structure: Structure object
        """
    
    def get_structures(self, chemsys_formula_id_criteria, final=True):
        """
        Get structures matching criteria.
        
        Parameters:
        chemsys_formula_id_criteria: Search criteria
        final: Whether to get final structures
        
        Returns:
        list: List of Structure objects
        """
    
    def get_entries(self, chemsys_formula_id_criteria, compatible_only=True,
                   inc_structure=None, property_data=None, conventional_unit_cell=False):
        """
        Get computed entries matching criteria.
        
        Parameters:
        chemsys_formula_id_criteria: Search criteria
        compatible_only: Whether to apply compatibility corrections
        inc_structure: Whether to include structure data
        property_data: Additional properties to include
        conventional_unit_cell: Whether to use conventional unit cell
        
        Returns:
        list: List of ComputedEntry objects
        """
    
    def get_entries_in_chemsys(self, elements, compatible_only=True,
                              inc_structure=None, property_data=None,
                              conventional_unit_cell=False):
        """
        Get entries in chemical system.
        
        Parameters:
        elements: List of elements in chemical system
        
        Returns:
        list: List of entries in the chemical system
        """
    
    def get_exp_entry(self, formula):
        """
        Get experimental entry for formula.
        
        Parameters:
        formula: Chemical formula
        
        Returns:
        ExpEntry: Experimental entry object
        """
    
    def get_pourbaix_entries(self, chemsys, solid_compat="MaterialsProjectAqueousCompatibility"):
        """
        Get Pourbaix entries for chemical system.
        
        Parameters:
        chemsys: Chemical system
        solid_compat: Solid compatibility scheme
        
        Returns:
        list: List of PourbaixEntry objects
        """
    
    def get_phase_diagram_by_elements(self, elements, **kwargs):
        """
        Get phase diagram for elements.
        
        Parameters:
        elements: List of Element objects or symbols
        
        Returns:
        PhaseDiagram: Phase diagram object
        """
    
    def get_cohp_by_material_id(self, material_id, path_type="coop", 
                               summed_spin_channels=False):
        """
        Get COHP data by material ID.
        
        Parameters:
        material_id: MP material ID
        path_type: Type of COHP data ("cohp", "coop", "cobiop")
        summed_spin_channels: Whether to sum spin channels
        
        Returns:
        CompleteCohp: COHP analysis object
        """
    
    def get_bandstructure_by_material_id(self, material_id, line_mode=True):
        """
        Get band structure by material ID.
        
        Parameters:
        material_id: MP material ID  
        line_mode: Whether to get line-mode band structure
        
        Returns:
        BandStructure: Band structure object
        """
    
    def get_dos_by_material_id(self, material_id):
        """
        Get DOS by material ID.
        
        Parameters:
        material_id: MP material ID
        
        Returns:
        CompleteDos: Complete DOS object
        """

Advanced I/O Classes

Specialized I/O classes for complex file formats and workflows.

class InputSet:
    """
    Abstract base class for input file sets.
    """
    
    def write_input(self, output_dir, make_dir_if_not_present=True,
                   overwrite=True, zip_output=False):
        """
        Write input set to directory.
        
        Parameters:
        output_dir: Output directory path
        make_dir_if_not_present: Whether to create directory
        overwrite: Whether to overwrite existing files
        zip_output: Whether to create ZIP archive
        """
    
    def validate(self):
        """
        Validate input set parameters.
        
        Returns:
        bool: Whether input set is valid
        """
    
    def get_string(self):
        """Get string representation of input set."""

class VaspInputSet:
    """
    Abstract base class for VASP input sets with standard parameters.
    
    Parameters:
    - structure: Structure for calculation
    - kpoints_density: K-points density per reciprocal atom
    - user_incar_settings: User INCAR parameter overrides
    - user_kpoints_settings: User KPOINTS settings
    - user_potcar_settings: User POTCAR settings
    - constrain_total_magmom: Whether to constrain total magnetic moment
    - sort_structure: Whether to sort structure  
    - user_potcar_functional: POTCAR functional to use
    - force_gamma: Whether to force Gamma-centered k-mesh
    - reduce_structure: Whether to reduce to primitive structure
    - vdw: Van der Waals correction method
    - use_structure_charge: Whether to use structure charge
    - standardize: Whether to standardize structure
    - sym_prec: Symmetry precision
    - international_monoclinic: Whether to use international monoclinic
    """
    def __init__(self, structure, kpoints_density=1000, 
                 user_incar_settings=None, user_kpoints_settings=None,
                 user_potcar_settings=None, constrain_total_magmom=False,
                 sort_structure=True, user_potcar_functional=None,
                 force_gamma=False, reduce_structure=None, vdw=None,
                 use_structure_charge=False, standardize=False,
                 sym_prec=0.1, international_monoclinic=True): ...
    
    @property
    def incar(self):
        """INCAR object for the input set."""
    
    @property
    def kpoints(self):
        """KPOINTS object for the input set."""  
    
    @property
    def poscar(self):
        """POSCAR object for the input set."""
    
    @property
    def potcar(self):
        """POTCAR object for the input set."""
    
    def write_input(self, output_dir, make_dir_if_not_present=True,
                   overwrite=True, zip_output=False): ...

Utility Functions

Helper functions for file I/O operations and format conversion.

def zopen(filename, mode="rt", *args, **kwargs):
    """
    Open files with automatic compression detection.
    
    Parameters:
    filename: File path (supports .gz, .bz2, .xz compression)
    mode: File open mode
    
    Returns:
    file object: Opened file handle
    """

def reverse_readfile(m_file):
    """
    Read file in reverse line order.
    
    Parameters:  
    m_file: File path or file object
    
    Yields:
    str: Lines in reverse order
    """

def micro_pyawk(filename, search, results=None, debug=None, postdebug=None):
    """
    Micro AWK-like text processing utility.
    
    Parameters:
    filename: File to process
    search: Search patterns and actions
    results: Results storage
    debug: Debug function
    postdebug: Post-debug function
    
    Returns:
    Results from text processing
    """

def clean_json(d, strict=False):
    """
    Clean dictionary for JSON serialization.
    
    Parameters:
    d: Dictionary to clean
    strict: Whether to use strict cleaning
    
    Returns:
    dict: JSON-serializable dictionary
    """

Install with Tessl CLI

npx tessl i tessl/pypi-pymatgen

docs

core-materials.md

electronic-structure.md

index.md

io-formats.md

phase-diagrams.md

structure-analysis.md

symmetry.md

transformations.md

tile.json