pymatgen.ext namespace — pymatgen 2026.3.9 documentation

# pymatgen.ext namespace

## Submodules

## pymatgen.ext.cod module

This module provides classes to interface with the Crystallography Open Database. If you use data from the COD, please cite the following works (as stipulated by the COD developers).

> Merkys, A., Vaitkus, A., Butkus, J., Okulič-Kazarinas, M., Kairys, V. & Gražulis, S. (2016) “COD::CIF::Parser: an error-correcting CIF parser for the Perl language”. Journal of Applied Crystallography 49.

> Gražulis, S., Merkys, A., Vaitkus, A. & Okulič-Kazarinas, M. (2015) “Computing stoichiometric molecular composition from crystal structures”. Journal of Applied Crystallography 48, 85-91.

> Gražulis, S., Daškevič, A., Merkys, A., Chateigner, D., Lutterotti, L., Quirós, M., Serebryanaya, N. R., Moeck, P., Downs, R. T. & LeBail, A. (2012) “Crystallography Open Database (COD): an open-access collection of crystal structures and platform for world-wide collaboration”. Nucleic Acids Research 40, D420-D427.

> Grazulis, S., Chateigner, D., Downs, R. T., Yokochi, A. T., Quiros, M., Lutterotti, L., Manakova, E., Butkus, J., Moeck, P. & Le Bail, A. (2009) “Crystallography Open Database - an open-access collection of crystal structures”. J. Appl. Cryst. 42, 726-729.

> Downs, R. T. & Hall-Wallace, M. (2003) “The American Mineralogist Crystal Structure Database”. American Mineralogist 88, 247-250.

class COD(timeout: int = 60)

  Bases: `object`

  An interface to the Crystallography Open Database.

  Reference:

    https://wiki.crystallography.net/RESTful_API/

  Initialize the COD class.

  Parameters:

    timeout (int) – request timeout in seconds.

  get_cod_ids(formula: str) → list[int]

    Query the COD for all COD IDs associated with a formula.

    Parameters:

      formula (str) – The formula to request

  get_structure_by_formula(formula: str, **kwargs) → list[dict[Literal['structure', 'cod_id', 'sg'], str | int | Structure]]

    Query the COD for structures by formula.

    Parameters:

      - formula (str) – Chemical formula.

      - kwargs – All kwargs supported by Structure.from_str.

    Returns:

      {“structure”: Structure, “cod_id”: int, “sg”: “P n m a”}

    Return type:

      A list of dict of

  get_structure_by_id(cod_id: int, timeout: int | None = None, **kwargs) → Structure

    Query the COD for a structure by ID.

    Parameters:

      - cod_id (int) – COD ID.

      - timeout (int) – DEPRECATED. request timeout in seconds.

      - kwargs – kwargs passed to Structure.from_str.

    Returns:

      A Structure.

## pymatgen.ext.matproj module

This module provides classes to interface with the Materials Project REST API v2 to enable the creation of data structures and pymatgen objects using Materials Project data.

To make use of the Materials API, you need to be a registered user of the Materials Project, and obtain an API key by going to your dashboard at https://materialsproject.org/dashboard.

exception MPRestError

  Bases: `Exception`

  Exception class for legacy MPRestAdaptor. Raised when query is malformed.

class MPRester(api_key: str | None = None, include_user_agent: bool = True)

  Bases: `object`

  Pymatgen’s implementation of MPRester. Unlike mp-api, this implementation mirrors the exact MP-API end points without modification. You just need to refer to https://api.materialsproject.org/docs and use the field names exactly. No need to deal with strange renames of various fields. Featurity parity is close to 100% with mp-api.

  Furthermore, we support both the mp-api as well as a simplified syntax. E.g., to query for a summary, you can use mpr.summary.search(material_ids=”mp-1234”) or mpr.materials.summary.search(material_ids=”mp-1234”).

  If you are a power user that requires some esoteric feature not covered, feel free to install the mp-api package. All issues regarding that implementation should be directed to the maintainers of that repository and not pymatgen. We will support only issues pertaining to our implementation only.

  api_key

    API key for authenticating requests to the Materials Project API.

    Type:

      str

  preamble

    Base endpoint URL for the Materials Project API.

    Type:

      str

  session

    HTTP session object for managing API requests.

    Type:

      requests.Session

  materials

    Placeholder object for dynamically adding endpoints related to materials.

  Parameters:

    - api_key (str) – A String API key for accessing the MaterialsProject REST interface. Please obtain your API key at https://www.materialsproject.org/dashboard. If this is None, the code will check if there is a “PMG_MAPI_KEY” setting. If so, it will use that environment variable. This makes easier for heavy users to simply add this environment variable to their setups and MPRester can then be called without any arguments.

    - include_user_agent (bool) – If True, will include a user agent with the HTTP request including information on pymatgen and system version making the API request. This helps MP support pymatgen users, and is similar to what most web browsers send with each page request. Set to False to disable the user agent.

  MATERIALS_DOCS = ('summary', 'core', 'elasticity', 'phonon', 'eos', 'similarity', 'xas', 'grain_boundaries', 'electronic_structure', 'tasks', 'substrates', 'surface_properties', 'robocrys', 'synthesis', 'magnetism', 'insertion_electrodes', 'conversion_electrodes', 'oxidation_states', 'provenance', 'alloys', 'absorption', 'chemenv', 'bonds', 'piezoelectric', 'dielectric')
  get_doc(material_id: str, fields: list | None = None) → dict

    Get a data corresponding to a material_id.

    Parameters:

      - material_id (str) – Materials Project ID (e.g. mp-1234).

      - fields (list) – Fields to query for. If None (the default), all fields are returned.

    Returns:

      Dict

  get_entries(criteria: str | Sequence[str], *, compatible_only: bool = True, property_data: Sequence[str] | None = None, summary_data: Sequence[str] | None = None, **kwargs) → list[AnyComputedEntry]

    Get a list of ComputedEntries or ComputedStructureEntries corresponding to a chemical system, formula, or materials_id or full criteria.

    Parameters:

      - criteria – Chemsys, formula, or mp-id.

      - compatible_only (bool) – Whether to return only “compatible” entries. Compatible entries are entries that have been processed using the MaterialsProject2020Compatibility class, which performs adjustments to allow mixing of GGA and GGA+U calculations for more accurate phase diagrams and reaction energies.

      - property_data (list) – Specify additional properties to include in entry.data from /materials/thermo endpoint of the API.

      - summary_data (list) – Specify additional properties to include in entry.data from /materials/summary endpoint of the API. Note that unlike property_data, summary_data refers to the “best” calculation done by MP. There are no guarantees that the summary_data will be consistent with the entry or property data since the data can come from say a r2SCAN calculation but the entry is from a GGA calculation. The data will be reported in the entry.data[“summary”] dictionary.

      - **kwargs – Used to catch deprecated kwargs.

    Returns:

      List of ComputedStructureEntry objects.

  get_entries_in_chemsys(elements: str | list[str], *args, **kwargs)

    Helper method to get a list of ComputedEntries in a chemical system. For example, elements = [“Li”, “Fe”, “O”] will return a list of all entries in the Li-Fe-O chemical system, i.e., all LixOy, FexOy, LixFey, LixFeyOz, Li, Fe and O phases. Extremely useful for creating phase diagrams of entire chemical systems.

    Parameters:

      - elements (str | list[str]) – Chemical system string comprising element symbols separated by dashes, e.g. “Li-Fe-O” or List of element symbols, e.g. [“Li”, “Fe”, “O”].

      - *args – Pass-through to get_entries.

      - **kwargs – Pass-through to get_entries.

    Returns:

      List of ComputedEntries.

  get_entry_by_material_id(material_id: str, *args, **kwargs) → AnyComputedEntry

    Get a ComputedEntry corresponding to a material_id.

    Parameters:

      - material_id (str) – Materials Project material_id (a string, e.g. mp-1234).

      - *args – Pass-through to get_entries.

      - **kwargs – Pass-through to get_entries.

    Returns:

      ComputedStructureEntry object.

  get_initial_structures_by_material_id(material_id: str, conventional_unit_cell: bool = False) → list[Structure]

    Get a Structure corresponding to a material_id.

    Parameters:

      - material_id (str) – Materials Project ID (e.g. mp-1234).

      - final (bool) – Whether to get the final structure, or the initial (pre-relaxation) structures. Defaults to True.

      - conventional_unit_cell (bool) – Whether to get the standard conventional unit cell

    Returns:

      Structure object.

  get_material_ids(formula)

    Get all materials ids for a formula.

    Parameters:

      formula (str) – A formula (e.g., Fe2O3).

    Returns:

      all materials ids.

    Return type:

      list[str]

  get_materials_ids(formula)

    Get all materials ids for a formula.

    Parameters:

      formula (str) – A formula (e.g., Fe2O3).

    Returns:

      all materials ids.

    Return type:

      list[str]

  get_phonon_bandstructure_by_material_id(material_id: str) → PhononBandStructureSymmLine

    Get phonon bandstructure by material_id.

    Note that this method borrows constructor methods built into in the emmet-core model for this data. Calling the to_pmg method of the emmet-core data model handles this.

    Parameters:

      material_id (str) – Materials Project material_id

    Returns:

      A phonon band structure.

    Return type:

      PhononBandStructureSymmLine

  get_phonon_dos_by_material_id(material_id: str) → CompletePhononDos

    Get phonon density of states by material_id.

    Note that this method borrows constructor methods built into in the emmet-core model for this data. Calling the to_pmg method of the emmet-core data model handles this.

    Parameters:

      material_id (str) – Materials Project material_id

    Returns:

      A phonon DOS object.

    Return type:

      CompletePhononDos

  get_structure_by_material_id(material_id: str, conventional_unit_cell: bool = False) → Structure

    Get a Structure corresponding to a material_id.

    Parameters:

      - material_id (str) – Materials Project ID (e.g. mp-1234).

      - final (bool) – Whether to get the final structure, or the initial (pre-relaxation) structures. Defaults to True.

      - conventional_unit_cell (bool) – Whether to get the standard conventional unit cell

    Returns:

      Structure object.

  get_structures(chemsys_formula: str, final=True) → list[Structure]

    Get a list of Structures corresponding to a chemical system or formula.

    Parameters:

      - chemsys_formula (str) – A chemical system, list of chemical systems (e.g., Li-Fe-O, Si-), or single formula (e.g., Fe2O3, Si).

      - final (bool) – Whether to get the final structure, or the list of initial (pre-relaxation) structures. Defaults to True.

    Returns:

      List of Structure objects. ([Structure])

  get_summary(criteria: dict, fields: list | None = None) → list[dict]

    Get a data corresponding to a criteria.

    Parameters:

      - criteria (dict) – Materials Project ID (e.g. mp-1234), e.g. {“formula”: “Fe2O3,FeO”}

      - fields (list) – Fields to query for. If None (the default), all fields are returned.

    Returns:

      List of dict of summary docs.

  get_summary_by_material_id(material_id: str, fields: list | None = None) → dict

    Get a data corresponding to a material_id.

    Parameters:

      - material_id (str) – Materials Project ID (e.g. mp-1234).

      - fields (list) – Fields to query for. If None (the default), all fields are returned.

    Returns:

      Dict

  request(sub_url: str, payload=None, method: str = 'GET', mp_decode: bool = True, timeout: int = 60) → list

    Helper method to make the requests and perform decoding based on MSONable protocol.

  search(doc, **kwargs) → list[dict]

    Queries a Materials PI end point doc. A notable difference with the mp-api’s implementation is that this uses the web API to do searches. So the keywords follow the actual API spec, which is as it should be. For instance, number of sites is nsites and number of elements is nelements. The mp-api package has this weird renaming that maps num_elements to nelements and num_sites to nsites.

    Parameters: - **kwargs: keyword arguments for filtering materials. Fields that do not start with underscores are filters, while those that start with underscores are fields to retrieve. Possible filters include:

    > - _fields (optional): list of fields to retrieve for each material

    > - Other parameters: filter criteria, where each parameter key corresponds to the field to filter and the parameter value corresponds to the filter value

    Returns:

      each dict representing a material retrieved based on the filtering criteria

    Return type:

      list[dict]

  summary_search(**kwargs) → list[dict]

    Mirrors mp-api’s mpr.materials.summary.search functionality. Searches for materials based on the specified criteria. A notable difference with the mp-api’s implementation is that this uses the web API to do searches. So the keywords follow the actual API spec, which is as it should be. For instance, number of sites is nsites and number of elements is nelements. The mp-api package has this weird renaming that maps num_elements to nelements and num_sites to nsites.

    Parameters: - **kwargs: keyword arguments for filtering materials. Fields that do not start with underscores are filters, while those that start with underscores are fields to retrieve. Possible filters include:

    > - _fields (optional): list of fields to retrieve for each material

    > - Other parameters: filter criteria, where each parameter key corresponds to the field to filter and the parameter value corresponds to the filter value

    Returns: - list of dictionaries, each dictionary representing a material retrieved based on the filtering criteria

## pymatgen.ext.optimade module

Optimade support.

class OptimadeRester(aliases_or_resource_urls: str | list[str] | None = None, refresh_aliases: bool = False, timeout: int = 5)

  Bases: `object`

  Call OPTIMADE-compliant APIs, see https://optimade.org and [1].

  This class is ready to use but considered in-development and subject to change.

  Please also consider using the client in “OPTIMADE Python tools”:

  https://www.optimade.org/optimade-python-tools/latest/getting_started/client/

  The “OPTIMADE Python tools” client is less integrated with pymatgen, but more actively developed for the latest OPTIMADE features.

  [1] Andersen, C.W., et al.

    OPTIMADE, an API for exchanging materials data. Sci Data 8, 217 (2021). https://doi.org/10.1038/s41597-021-00974-z

  OPTIMADE is an effort to provide a standardized interface to retrieve information from many different materials science databases.

  This is a client to retrieve structures from OPTIMADE v1 compliant endpoints. It does not yet support all features of the OPTIMADE v1 specification but is intended as a way to quickly search an endpoint in a way familiar to users of pymatgen without needing to know the full OPTIMADE specification.

  For advanced usage, please see the OPTIMADE documentation at optimade.org and consider calling the APIs directly.

  For convenience, known OPTIMADE endpoints have been given aliases in pymatgen to save typing the full URL.

  To get an up-to-date list aliases, generated from the current list of OPTIMADE providers at optimade.org, call the refresh_aliases() method or pass refresh_aliases=True when creating instances of this class.

  Parameters:

    - aliases_or_resource_urls – the alias or structure resource URL or a list of

    - URLs (aliases or resource)

    - not (if providing the resource URL directly it should)

    - index (be an)

    - "v1/structures" (this interface can only currently access the)

    - URL (information from the specified resource)

    - refresh_aliases – if True, use an up-to-date list of providers/aliases from the live

    - https (list of OPTIMADE providers hosted at) – //providers.optimade.org.

    - timeout – number of seconds before an attempted request is abandoned, a good

    - providers (timeout is useful when querying many)

    - offline (some of which may be)

  aliases: ClassVar[dict[str, str]] = {'aflow': 'https://aflow.org/API/optimade/', 'alexandria': 'https://alexandria.icams.rub.de/pbe', 'alexandria.pbe': 'https://alexandria.icams.rub.de/pbe', 'alexandria.pbesol': 'https://alexandria.icams.rub.de/pbesol', 'cmr': 'https://cmr-optimade.fysik.dtu.dk', 'cod': 'https://www.crystallography.net/cod/optimade', 'jarvis': 'https://jarvis.nist.gov/optimade/jarvisdft', 'mcloud.2dtopo': 'https://aiida.materialscloud.org/2dtopo/optimade', 'mcloud.curated-cofs': 'https://aiida.materialscloud.org/curated-cofs/optimade', 'mcloud.mc2d': 'https://aiida.materialscloud.org/mc2d/optimade', 'mcloud.mc3d': 'https://aiida.materialscloud.org/mc3d/optimade', 'mcloud.optimade-sample': 'https://aiida.materialscloud.org/optimade-sample/optimade', 'mcloud.pyrene-mofs': 'https://aiida.materialscloud.org/pyrene-mofs/optimade', 'mcloud.scdm': 'https://aiida.materialscloud.org/autowannier/optimade', 'mcloud.stoceriaitf': 'https://aiida.materialscloud.org/stoceriaitf/optimade', 'mcloud.tc-applicability': 'https://aiida.materialscloud.org/tc-applicability/optimade', 'mcloud.tin-antimony-sulfoiodide': 'https://aiida.materialscloud.org/tin-antimony-sulfoiodide/optimade', 'mp': 'https://optimade.materialsproject.org', 'mpdd': 'http://mpddoptimade.phaseslab.org', 'mpds': 'https://api.mpds.io', 'nmd': 'https://nomad-lab.eu/prod/rae/optimade/', 'odbx': 'https://optimade.odbx.science', 'odbx.gnome': 'https://optimade-gnome.odbx.science', 'odbx.odbx_misc': 'https://optimade-misc.odbx.science', 'omdb.omdb_production': 'https://optimade.openmaterialsdb.se', 'oqmd': 'https://oqmd.org/optimade/', 'tcod': 'https://www.crystallography.net/tcod/optimade', 'twodmatpedia': 'http://optimade.2dmatpedia.org'}
  describe()

    Human-readable information about the resources being searched by the OptimadeRester.

  get_snls(elements: list[str] | str | None = None, nelements: int | None = None, nsites: int | None = None, chemical_formula_anonymous: str | None = None, chemical_formula_hill: str | None = None, additional_response_fields: str | list[str] | set[str] | None = None) → dict[str, dict[str, StructureNL]]

    Retrieve StructureNL from OPTIMADE providers.

    A StructureNL is an object provided by pymatgen which combines Structure with associated metadata, such as the URL is was downloaded from and any additional namespaced data.

    Not all functionality of OPTIMADE is currently exposed in this convenience method. To use a custom filter, call get_structures_with_filter().

    Parameters:

      - elements – List of elements

      - nelements – Number of elements, e.g. 4 or [2, 5] for the range >=2 and <=5

      - nsites – Number of sites, e.g. 4 or [2, 5] for the range >=2 and <=5

      - chemical_formula_anonymous – The desired chemical formula in OPTIMADE anonymous formula format

      - format (this is different from the pymatgen)

      - "A2BC"). (e.g. pymatgen "ABC2" should become)

      - chemical_formula_hill – The desired chemical formula in the OPTIMADE take on the Hill formula format.

      - Again ((NB.)

      - format

      - chemical (as the OPTIMADE version is a reduced)

      - ordering.) (formula simply using the IUPAC/Hill)

      - additional_response_fields – Any additional fields desired from the OPTIMADE API,

      - dictionary. (these will be stored under the '_optimade' key in each StructureNL.data)

    Returns:

      keyed by that database provider’s id system

    Return type:

      dict[str, StructureNL]

  get_snls_with_filter(optimade_filter: str, additional_response_fields: str | list[str] | set[str] | None = None) → dict[str, dict[str, StructureNL]]

    Get structures satisfying a given OPTIMADE filter.

    Parameters:

      - optimade_filter – An OPTIMADE-compliant filter

      - additional_response_fields – Any additional fields desired from the OPTIMADE API,

    Returns:

      keyed by that database provider’s id system

    Return type:

      dict[str, Structure]

  get_structures(elements: list[str] | str | None = None, nelements: int | None = None, nsites: int | None = None, chemical_formula_anonymous: str | None = None, chemical_formula_hill: str | None = None) → dict[str, dict[str, Structure | Molecule]]

    Retrieve Structures from OPTIMADE providers.

    Not all functionality of OPTIMADE is currently exposed in this convenience method. To use a custom filter, call get_structures_with_filter().

    Parameters:

      - elements – List of elements

      - nelements – Number of elements, e.g. 4 or [2, 5] for the range >=2 and <=5

      - nsites – Number of sites, e.g. 4 or [2, 5] for the range >=2 and <=5

      - chemical_formula_anonymous – The desired chemical formula in OPTIMADE anonymous formula format

      - format (this is different from the pymatgen)

      - "A2BC"). (e.g. pymatgen "ABC2" should become)

      - chemical_formula_hill – The desired chemical formula in the OPTIMADE take on the Hill formula format.

      - Again ((NB.)

      - format

      - chemical (as the OPTIMADE version is a reduced)

      - ordering.) (formula simply using the IUPAC/Hill)

    Returns:

      keyed by that database provider’s id system

    Return type:

      dict[str, Structure]

  get_structures_with_filter(optimade_filter: str) → dict[str, dict[str, Structure | Molecule]]

    Get structures satisfying a given OPTIMADE filter.

    Parameters:

      optimade_filter – An OPTIMADE-compliant filter

    Returns:

      keyed by that database provider’s id system

    Return type:

      dict[str, Structure]

  mandatory_response_fields = ('lattice_vectors', 'cartesian_site_positions', 'species', 'species_at_sites')
  refresh_aliases(providers_url='https://providers.optimade.org/providers.json')

    Update available OPTIMADE structure resources based on the current list of OPTIMADE providers.

class Provider(name: str, base_url: str, description: str, homepage: str, prefix: str)

  Bases: `NamedTuple`

  TODO: Import optimade-python-tool’s data structures will make more sense.

  Create new instance of Provider(name, base_url, description, homepage, prefix)

  base_url: str

    Alias for field number 1

  description: str

    Alias for field number 2

  homepage: str

    Alias for field number 3

  name: str

    Alias for field number 0

  prefix: str

    Alias for field number 4