ocpapi

Contents

ocpapi#

Copyright (c) Meta, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.

Subpackages#

Submodules#

Attributes#

Exceptions#

NonRetryableRequestException

Exception raised when an API call is rejected for a reason that will

RateLimitExceededException

Exception raised when an API call is rejected because a rate limit has

RequestException

Exception raised any time there is an error while making an API call.

UnsupportedAdsorbateException

Exception raised when an adsorbate is not supported in the API.

UnsupportedBulkException

Exception raised when a bulk material is not supported in the API.

UnsupportedModelException

Exception raised when a model is not supported in the API.

Classes#

Client

Exposes each route in the OCP API as a method.

Adsorbates

Stores the response from a request to fetch adsorbates supported in the

AdsorbateSlabConfigs

Stores the response from a request to fetch placements of a single

AdsorbateSlabRelaxationResult

Stores information about a single adsorbate slab configuration, including

AdsorbateSlabRelaxationsRequest

Stores the request to submit a new batch of adsorbate slab relaxations.

AdsorbateSlabRelaxationsResults

Stores the response from a request for results of adsorbate slab

AdsorbateSlabRelaxationsSystem

Stores the response from a request to submit a new batch of adsorbate

Atoms

Subset of the fields from an ASE Atoms object that are used within this

Bulk

Stores information about a single bulk material.

Bulks

Stores the response from a request to fetch bulks supported in the API.

Model

Stores information about a single model supported in the API.

Models

Stores the response from a request for models supported in the API.

Slab

Stores all information about a slab that is returned from the API.

SlabMetadata

Stores metadata about a slab that is returned from the API.

Slabs

Stores the response from a request to fetch slabs for a bulk structure.

Status

Relaxation status of a single adsorbate placement on a slab.

AdsorbateBindingSites

Stores the inputs and results of a set of relaxations of adsorbate

AdsorbateSlabRelaxations

Stores the relaxations of adsorbate placements on the surface of a slab.

Lifetime

Represents different lifetimes when running relaxations.

keep_all_slabs

Adslab filter than returns all slabs.

keep_slabs_with_miller_indices

Adslab filter that keeps any slabs with the configured miller indices.

prompt_for_slabs_to_keep

Adslab filter than presents the user with an interactive prompt to choose

RateLimitLogging

Controls logging when rate limits are hit.

Functions#

get_results_ui_url(→ str | None)

Generates the URL at which results for the input system can be

find_adsorbate_binding_sites(→ AdsorbateBindingSites)

Search for adsorbate binding sites on surfaces of a bulk material.

get_adsorbate_slab_relaxation_results(...)

Wrapper around Client.get_adsorbate_slab_relaxations_results() that

wait_for_adsorbate_slab_relaxations(→ dict[int, ...)

Blocks until all relaxations in the input system have finished, whether

retry_api_calls(→ Any)

Decorator with sensible defaults for retrying calls to the OCP API.

Package Contents#

ocpapi.__version__#
class ocpapi.Client(host: str = 'open-catalyst-api.metademolab.com', scheme: str = 'https')#

Exposes each route in the OCP API as a method.

_host#
_base_url#
property host: str#

The host being called by this client.

async get_models() ocpapi.client.models.Models#

Fetch the list of models that are supported in the API.

Raises:
Returns:

The models that are supported in the API.

async get_bulks() ocpapi.client.models.Bulks#

Fetch the list of bulk materials that are supported in the API.

Raises:
Returns:

The bulks that are supported throughout the API.

async get_adsorbates() ocpapi.client.models.Adsorbates#

Fetch the list of adsorbates that are supported in the API.

Raises:
Returns:

The adsorbates that are supported throughout the API.

async get_slabs(bulk: str | ocpapi.client.models.Bulk) ocpapi.client.models.Slabs#

Get a unique list of slabs for the input bulk structure.

Parameters:

bulk – If a string, the id of the bulk to use. Otherwise the Bulk instance to use.

Raises:
Returns:

Slabs for each of the unique surfaces of the material.

async get_adsorbate_slab_configs(adsorbate: str, slab: ocpapi.client.models.Slab) ocpapi.client.models.AdsorbateSlabConfigs#

Get a list of possible binding sites for the input adsorbate on the input slab.

Parameters:
  • adsorbate – Description of the the adsorbate to place.

  • slab – Information about the slab on which the adsorbate should be placed.

Raises:
Returns:

Configurations for each adsorbate binding site on the slab.

async submit_adsorbate_slab_relaxations(adsorbate: str, adsorbate_configs: list[ocpapi.client.models.Atoms], bulk: ocpapi.client.models.Bulk, slab: ocpapi.client.models.Slab, model: str, ephemeral: bool = False) ocpapi.client.models.AdsorbateSlabRelaxationsSystem#

Starts relaxations of the input adsorbate configurations on the input slab using energies and forces returned by the input model. Relaxations are run asynchronously and results can be fetched using the system id that is returned from this method.

Parameters:
  • adsorbate – Description of the adsorbate being simulated.

  • adsorbate_configs – List of adsorbate configurations to relax. This should only include the adsorbates themselves; the surface is defined in the “slab” field that is a peer to this one.

  • bulk – Details of the bulk material being simulated.

  • slab – The structure of the slab on which adsorbates are placed.

  • model – The model that will be used to evaluate energies and forces during relaxations.

  • ephemeral – If False (default), any later attempt to delete the generated relaxations will be rejected. If True, deleting the relaxations will be allowed, which is generally useful for testing when there is no reason for results to be persisted.

Raises:
Returns:

IDs of the relaxations.

async get_adsorbate_slab_relaxations_request(system_id: str) ocpapi.client.models.AdsorbateSlabRelaxationsRequest#

Fetches the original relaxations request for the input system.

Parameters:

system_id – The ID of the system to fetch.

Raises:
Returns:

The original request that was made when submitting relaxations.

async get_adsorbate_slab_relaxations_results(system_id: str, config_ids: list[int] | None = None, fields: list[str] | None = None) ocpapi.client.models.AdsorbateSlabRelaxationsResults#

Fetches relaxation results for the input system.

Parameters:
  • system_id – The system id of the relaxations.

  • config_ids – If defined and not empty, a subset of configurations to fetch. Otherwise all configurations are returned.

  • fields – If defined and not empty, a subset of fields in each configuration to fetch. Otherwise all fields are returned.

Raises:
Returns:

The relaxation results for each configuration in the system.

async delete_adsorbate_slab_relaxations(system_id: str) None#

Deletes all relaxation results for the input system.

Parameters:

system_id – The ID of the system to delete.

Raises:
async _run_request(path: str, method: str, **kwargs) str#

Helper method that runs the input request on a thread so that it doesn’t block the event loop on the calling thread.

Parameters:
  • path – The URL path to make the request against.

  • method – The HTTP method to use (GET, POST, etc.).

Raises:
Returns:

The response body from the request as a string.

exception ocpapi.NonRetryableRequestException(method: str, url: str, cause: str)#

Bases: RequestException

Exception raised when an API call is rejected for a reason that will not succeed on retry. For example, this might include a malformed request or action that is not allowed.

exception ocpapi.RateLimitExceededException(method: str, url: str, retry_after: datetime.timedelta | None = None)#

Bases: RequestException

Exception raised when an API call is rejected because a rate limit has been exceeded.

retry_after#

If known, the time to wait before the next attempt to call the API should be made.

retry_after: datetime.timedelta | None#
exception ocpapi.RequestException(method: str, url: str, cause: str)#

Bases: Exception

Exception raised any time there is an error while making an API call.

class ocpapi.Adsorbates#

Bases: _DataModel

Stores the response from a request to fetch adsorbates supported in the API.

adsorbates_supported: List[str]#

List of adsorbates that can be used in the API.

class ocpapi.AdsorbateSlabConfigs#

Bases: _DataModel

Stores the response from a request to fetch placements of a single absorbate on a slab.

adsorbate_configs: List[Atoms]#

List of structures, each representing one possible adsorbate placement.

slab: Slab#

The structure of the slab on which the adsorbate is placed.

class ocpapi.AdsorbateSlabRelaxationResult#

Bases: _DataModel

Stores information about a single adsorbate slab configuration, including outputs for the model used in relaxations.

The API to fetch relaxation results supports requesting a subset of fields in order to limit the size of response payloads. Optional attributes will be defined only if they are including the response.

config_id: int#

ID of the configuration within the system.

status: Status#

The status of the request for information about this configuration.

system_id: str | None#

The ID of the system in which the configuration was originally submitted.

cell: Tuple[Tuple[float, float, float], Tuple[float, float, float], Tuple[float, float, float]] | None#

3x3 matrix with unit cell vectors.

pbc: Tuple[bool, bool, bool] | None#

Whether the structure is periodic along the a, b, and c lattice vectors, respectively.

numbers: List[int] | None#

The atomic number of each atom in the unit cell.

positions: List[Tuple[float, float, float]] | None#

The coordinates of each atom in the unit cell, relative to the cartesian frame.

tags: List[int] | None#

Labels for each atom in the unit cell where 0 represents a subsurface atom (fixed during optimization), 1 represents a surface atom, and 2 represents an adsorbate atom.

energy: float | None#

The energy of the configuration.

energy_trajectory: List[float] | None#

The energy of the configuration at each point along the relaxation trajectory.

forces: List[Tuple[float, float, float]] | None#

The forces on each atom in the relaxed structure.

to_ase_atoms() ase.Atoms#

Creates an ase.Atoms object with the positions, element numbers, etc. populated from values on this object.

The predicted energy and forces will also be copied to the new ase.Atoms object as a SinglePointCalculator (a calculator that stores the results of an already-run simulation).

Returns:

ase.Atoms object with values from this object.

class ocpapi.AdsorbateSlabRelaxationsRequest#

Bases: _DataModel

Stores the request to submit a new batch of adsorbate slab relaxations.

adsorbate: str#

Description of the adsorbate.

adsorbate_configs: List[Atoms]#

List of adsorbate placements being relaxed.

bulk: Bulk#

Information about the original bulk structure used to create the slab.

slab: Slab#

The structure of the slab on which adsorbates are placed.

model: str#

The type of the ML model being used during relaxations.

ephemeral: bool | None#

Whether the relaxations can be deleted (assume they cannot be deleted if None).

adsorbate_reaction: str | None#

If possible, an html-formatted string describing the reaction will be added to this field.

class ocpapi.AdsorbateSlabRelaxationsResults#

Bases: _DataModel

Stores the response from a request for results of adsorbate slab relaxations.

configs: List[AdsorbateSlabRelaxationResult]#

List of configurations in the system, each representing one placement of an adsorbate on a slab surface.

omitted_config_ids: List[int]#

List of IDs of configurations that were requested but omitted by the server. Results for these IDs can be requested again.

class ocpapi.AdsorbateSlabRelaxationsSystem#

Bases: _DataModel

Stores the response from a request to submit a new batch of adsorbate slab relaxations.

system_id: str#

Unique ID for this set of relaxations which can be used to fetch results later.

config_ids: List[int]#

The list of IDs assigned to each of the input adsorbate placements, in the same order in which they were submitted.

class ocpapi.Atoms#

Bases: _DataModel

Subset of the fields from an ASE Atoms object that are used within this API.

cell: Tuple[Tuple[float, float, float], Tuple[float, float, float], Tuple[float, float, float]]#

3x3 matrix with unit cell vectors.

pbc: Tuple[bool, bool, bool]#

Whether the structure is periodic along the a, b, and c lattice vectors, respectively.

numbers: List[int]#

The atomic number of each atom in the unit cell.

positions: List[Tuple[float, float, float]]#

The coordinates of each atom in the unit cell, relative to the cartesian frame.

tags: List[int]#

Labels for each atom in the unit cell where 0 represents a subsurface atom (fixed during optimization), 1 represents a surface atom, and 2 represents an adsorbate atom.

to_ase_atoms() ase.Atoms#

Creates an ase.Atoms object with the positions, element numbers, etc. populated from values on this object.

Returns:

ase.Atoms object with values from this object.

class ocpapi.Bulk#

Bases: _DataModel

Stores information about a single bulk material.

src_id: str#

The ID of the material.

formula: str#

The chemical formula of the material.

elements: List[str]#

The list of elements in the material.

class ocpapi.Bulks#

Bases: _DataModel

Stores the response from a request to fetch bulks supported in the API.

bulks_supported: List[Bulk]#

List of bulks that can be used in the API.

class ocpapi.Model#

Bases: _DataModel

Stores information about a single model supported in the API.

id: str#

The ID of the model.

class ocpapi.Models#

Bases: _DataModel

Stores the response from a request for models supported in the API.

models: List[Model]#

The list of models that are supported.

class ocpapi.Slab#

Bases: _DataModel

Stores all information about a slab that is returned from the API.

atoms: Atoms#

The structure of the slab.

metadata: SlabMetadata#

Extra information about the slab.

class ocpapi.SlabMetadata#

Bases: _DataModel

Stores metadata about a slab that is returned from the API.

bulk_src_id: str#

The ID of the bulk material from which the slab was derived.

millers: Tuple[int, int, int]#

The Miller indices of the slab relative to bulk structure.

shift: float#

The position along the vector defined by the Miller indices at which a cut was taken to generate the slab surface.

top: bool#

If False, the top and bottom surfaces for this millers/shift pair are distinct and this slab represents the bottom surface.

class ocpapi.Slabs#

Bases: _DataModel

Stores the response from a request to fetch slabs for a bulk structure.

slabs: List[Slab]#

The list of slabs that were generated from the input bulk structure.

class ocpapi.Status(*args, **kwds)#

Bases: enum.Enum

Relaxation status of a single adsorbate placement on a slab.

NOT_AVAILABLE = 'not_available'#

The configuration exists but the result is not yet available. It is possible that checking again in the future could yield a result.

FAILED_RELAXATION = 'failed_relaxation'#

The relaxation failed for this configuration.

SUCCESS = 'success'#

The relaxation was successful and the requested information about the configuration was returned.

DOES_NOT_EXIST = 'does_not_exist'#

The requested configuration does not exist.

__str__() str#
ocpapi.get_results_ui_url(api_host: str, system_id: str) str | None#

Generates the URL at which results for the input system can be visualized.

Parameters:
  • api_host – The API host on which the system was run.

  • system_id – ID of the system being visualized.

Returns:

The URL at which the input system can be visualized. None if the API host is not recognized.

class ocpapi.AdsorbateBindingSites#

Stores the inputs and results of a set of relaxations of adsorbate placements on the surface of a slab.

adsorbate: str#

Description of the adsorbate.

bulk: fairchem.demo.ocpapi.client.Bulk#

The bulk material that was being modeled.

model: str#

The type of the model that was run.

slabs: list[AdsorbateSlabRelaxations]#

The list of slabs that were generated from the bulk structure. Each contains its own list of adsorbate placements.

class ocpapi.AdsorbateSlabRelaxations#

Stores the relaxations of adsorbate placements on the surface of a slab.

slab: fairchem.demo.ocpapi.client.Slab#

The slab on which the adsorbate was placed.

configs: list[fairchem.demo.ocpapi.client.AdsorbateSlabRelaxationResult]#

Details of the relaxation of each adsorbate placement, including the final position.

system_id: str#

The ID of the system that stores all of the relaxations.

api_host: str#

The API host on which the relaxations were run.

ui_url: str | None#

The URL at which results can be visualized.

class ocpapi.Lifetime(*args, **kwds)#

Bases: enum.Enum

Represents different lifetimes when running relaxations.

SAVE#

The relaxation will be available on API servers indefinitely. It will not be possible to delete the relaxation in the future.

MARK_EPHEMERAL#

The relaxation will be saved on API servers, but can be deleted at any time in the future.

DELETE#

The relaxation will be deleted from API servers as soon as the results have been fetched.

exception ocpapi.UnsupportedAdsorbateException(adsorbate: str)#

Bases: AdsorbatesException

Exception raised when an adsorbate is not supported in the API.

exception ocpapi.UnsupportedBulkException(bulk: str)#

Bases: AdsorbatesException

Exception raised when a bulk material is not supported in the API.

exception ocpapi.UnsupportedModelException(model: str, allowed_models: list[str])#

Bases: AdsorbatesException

Exception raised when a model is not supported in the API.

async ocpapi.find_adsorbate_binding_sites(adsorbate: str, bulk: str, model: str = 'equiformer_v2_31M_s2ef_all_md', adslab_filter: Callable[[list[fairchem.demo.ocpapi.client.AdsorbateSlabConfigs]], Awaitable[list[fairchem.demo.ocpapi.client.AdsorbateSlabConfigs]]] = _DEFAULT_ADSLAB_FILTER, client: fairchem.demo.ocpapi.client.Client = DEFAULT_CLIENT, lifetime: Lifetime = Lifetime.SAVE) AdsorbateBindingSites#

Search for adsorbate binding sites on surfaces of a bulk material. This executes the following steps:

  1. Ensure that both the adsorbate and bulk are supported in the OCP API.

  2. Enumerate unique surfaces from the bulk material.

  3. Enumerate likely binding sites for the input adsorbate on each of the generated surfaces.

  4. Filter the list of generated adsorbate/slab (adslab) configurations

    using the input adslab_filter.

  5. Relax each generated surface+adsorbate structure by refining atomic positions to minimize forces generated by the input model.

Parameters:
  • adsorbate – Description of the adsorbate to place.

  • bulk – The ID (typically Materials Project MP ID) of the bulk material on which the adsorbate will be placed.

  • model – The type of the model to use when calculating forces during relaxations.

  • adslab_filter – A function that modifies the set of adsorbate/slab configurations that will be relaxed. This can be used to subselect slabs and/or adsorbate configurations.

  • client – The OCP API client to use.

  • lifetime – Whether relaxations should be saved on the server, be marked as ephemeral (allowing them to deleted in the future), or deleted immediately.

Returns:

Details of each adsorbate binding site, including results of relaxing to locally-optimized positions using the input model.

Raises:
async ocpapi.get_adsorbate_slab_relaxation_results(system_id: str, config_ids: list[int] | None = None, fields: list[str] | None = None, client: fairchem.demo.ocpapi.client.Client = DEFAULT_CLIENT) list[fairchem.demo.ocpapi.client.AdsorbateSlabRelaxationResult]#

Wrapper around Client.get_adsorbate_slab_relaxations_results() that handles retries, including re-fetching individual configurations that are initially omitted.

Parameters:
  • client – The client to use when making API calls.

  • system_id – The system ID of the relaxations.

  • config_ids – If defined and not empty, a subset of configurations to fetch. Otherwise all configurations are returned.

  • fields – If defined and not empty, a subset of fields in each configuration to fetch. Otherwise all fields are returned.

Returns:

List of relaxation results, one for each adsorbate configuration in the system.

async ocpapi.wait_for_adsorbate_slab_relaxations(system_id: str, check_immediately: bool = False, slow_interval_sec: float = 30, fast_interval_sec: float = 10, pbar: tqdm.tqdm | None = None, client: fairchem.demo.ocpapi.client.Client = DEFAULT_CLIENT) dict[int, fairchem.demo.ocpapi.client.Status]#

Blocks until all relaxations in the input system have finished, whether successfully or not.

Relaxations are queued in the API, waiting until machines are ready to run them. Once started, they can take 1-2 minutes to finish. This method initially sleeps “slow_interval_sec” seconds between each check for any relaxations having finished. Once at least one result is ready, subsequent sleeps are for “fast_interval_sec” seconds.

Parameters:
  • system_id – The ID of the system for which relaxations are running.

  • check_immediately – If False (default), sleep before the first check for relaxations having finished. If True, check whether relaxations have finished immediately on entering this function.

  • slow_interval_sec – The number of seconds to wait between each check while all are still running.

  • fast_interval_sec – The number of seconds to wait between each check when at least one relaxation has finished in the system.

  • pbar – A tqdm instance that tracks the number of configurations that have finished. This will be updated with the number of individual configurations whose relaxations have finished.

  • client – The client to use when making API calls.

Returns:

Map of config IDs in the system to their terminal status.

class ocpapi.keep_all_slabs#

Adslab filter than returns all slabs.

async __call__(adslabs: list[fairchem.demo.ocpapi.client.AdsorbateSlabConfigs]) list[fairchem.demo.ocpapi.client.AdsorbateSlabConfigs]#
class ocpapi.keep_slabs_with_miller_indices(miller_indices: Iterable[tuple[int, int, int]])#

Adslab filter that keeps any slabs with the configured miller indices. Slabs with other miller indices will be ignored.

_unique_millers: set[tuple[int, int, int]]#
async __call__(adslabs: list[fairchem.demo.ocpapi.client.AdsorbateSlabConfigs]) list[fairchem.demo.ocpapi.client.AdsorbateSlabConfigs]#
class ocpapi.prompt_for_slabs_to_keep#

Adslab filter than presents the user with an interactive prompt to choose which of the input slabs to keep.

static _sort_key(adslab: fairchem.demo.ocpapi.client.AdsorbateSlabConfigs) tuple[tuple[int, int, int], float, str]#

Generates a sort key from the input adslab. Returns the miller indices, shift, and top/bottom label so that they will be sorted by those values in that order.

async __call__(adslabs: list[fairchem.demo.ocpapi.client.AdsorbateSlabConfigs]) list[fairchem.demo.ocpapi.client.AdsorbateSlabConfigs]#
ocpapi.NO_LIMIT: NoLimitType = 0#
ocpapi.NoLimitType#
class ocpapi.RateLimitLogging#

Controls logging when rate limits are hit.

logger: logging.Logger#

The logger to use.

action: str#

A short description of the action being attempted.

ocpapi.retry_api_calls(max_attempts: int | NoLimitType = 3, rate_limit_logging: RateLimitLogging | None = None, fixed_wait_sec: float = 2, max_jitter_sec: float = 1) Any#

Decorator with sensible defaults for retrying calls to the OCP API.

Parameters:
  • max_attempts – The maximum number of calls to make. If NO_LIMIT, retries will be made forever.

  • rate_limit_logging – If not None, log statements will be generated using this configuration when a rate limit is hit.

  • fixed_wait_sec – The fixed number of seconds to wait when retrying an exception that does not include a retry-after value. The default value is sensible; this is exposed mostly for testing.

  • max_jitter_sec – The maximum number of seconds that will be randomly added to wait times. The default value is sensible; this is exposed mostly for testing.