Skip to navigation

Use the Microservice

View as MarkdownOpen in Claude

Interact with the microservice through its REST API. The microservice includes a Swagger UI for interactive exploration (/docs) and an OpenAPI specification endpoint (/openapi.json).

Authentication

All HTTP endpoints except those used for documentation and status checking require a bearer token.

from httpx import Client
client = Client(headers={"Authorization": "Bearer private-token"})
response = client.post(
"http://127.0.0.1:8000/input/upload", files={"file": f}
)

All examples in this page omit the bearer token for brevity.

Submitting Calculations

Submit a calculation to the microservice through one of two endpoints for evaluation:

  1. /infer, which waits until the calculation completes and then returns a result.
  2. /submit, which returns a request ID as soon as the input is validated.

Use the request ID to check the execution status through /status/{request_id}. Statuses are either RUNNING, COMPLETED, or UNKNOWN. The service does not maintain a list of previous requests, so the status reverts to UNKNOWN after you retrieve the results.

Retrieve results using the /result/{request_id} endpoint. The service deletes the results after retrieval.

Both endpoints receive the same input format and return the same output format.

Managing Input Files

Upload large input files (larger than 100 kB) to the microservice through POST /input/upload.

The endpoint returns a unique identifier that you can reference in the files field of a calculation request (described below).

from httpx import AsyncClient
async def upload_then_submit():
client = AsyncClient()
request = {"files": {}}
for path in ["INCAR", "POSCAR"]:
with open(path, "rb") as f:
response = await client.post(
"http://127.0.0.1:8000/input/upload", files={"file": f}
)
response.raise_for_status()
file_id = response.json()["file_id"]
request["files"][path.name] = {"file_id": file_id}
return await client.post("http://127.0.0.1/submit", json=request)

Delete uploaded files in one of the following ways:

  • Delete them after the calculation completes through the GET /input/delete/{file_id} endpoint.
  • Wait for automatic deletion as new files are uploaded.
  • Periodically force a purge of old inputs with DELETE /input/purge.

Input Format

Inputs to the microservice are JSON documents with three keys:

  1. files: Input files provided to the executable.
  2. atoms: (optional) The atomic structure in a software-agnostic format.
  3. config: Code-specific configuration settings, such as arguments passed to the binary.

The microservice does minimal validation of the input files and will optionally build a few input files from the request. The user is responsible for ensuring that the inputs are valid.

Supplying Input Files

Supply input files to use in a calculation through the files field of the request. The field is a dictionary that maps the name of an input file to a value defining its contents in one of the following formats:

  1. The content as a plain text string.

    {
    "INCAR": "ENCUT = 520"
    }
  2. A UUID corresponding to a file uploaded through the POST /input/upload endpoint.

    {
    "INCAR": {"file_id": "5c0c9d24-d923-49c1-8cd2-467f12901a46"}
    }

The service limits the maximum size and number of files sent as plain text, as defined by the ALCHEMI_INLINE environment variables.

Atomic Positions (POSCAR)

There are two options for the atomic structure inputs:

  1. Supplying the POSCAR directly as the POSCAR field in the files list. The microservice writes the POSCAR file as provided in the request.
  2. Supplying the atomic structure in AtomicData format in the atoms field. The service converts the AtomicData to a POSCAR with atoms in the same order as the input structure, and allows the positions of all atoms to be optimized (no selective dynamics).

AtomicData Format

The AtomicData format is a dictionary with the following keys.

  • coord: Atomic positions as a 1D array, flattened in column-wise order (for example, [x1, y1, z1, x2, y2, z2, ...]).
  • elements: List of atomic numbers corresponding to each atom.
  • charge (optional): Total system charge. Default is 0.
  • multiplicity (optional): Spin multiplicity of the system. Default is 1.
  • cell (optional): Simulation cell vectors as a 1D array, flattened in column-wise order ([a1x, a1y, a1z, a2x, a2y, a2z, a3x, a3y, a3z]).
  • pbc (optional): Periodic boundary conditions as a list of three booleans indicating whether each cell vector is periodic. Default is [false, false, false].

For example, the conventional unit cell of FCC copper is:

{
"coord": [0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.5],
"elements": [29, 29, 29, 29],
"cell": [3.52, 0.0, 0.0, 0.0, 3.52, 0.0, 0.0, 0.0, 3.52],
"pbc": [true, true, true]
}

General Settings (INCAR)

The INCAR file is mandatory and defines the calculation parameters and settings. Provide it in the files field.

Integration Grid (k-points)

VASP defines k-points through one of several schemes:

  1. Providing a KPOINTS file. A KPOINTS file provides the greatest flexibility in grid selection. Use this option by passing a KPOINTS file in the files field of the request.
  2. Providing the KSPACING parameter in the INCAR file. Using KSPACING ensures the k-point grid changes with the cell size.

Pseudopotentials (POTCARs)

The VASP POTCARs define the pseudopotentials used to approximate the effect of core electrons. They must be consistent with both the choice of exchange-correlation functional and the order of elements in the atomic structure file. ALCHEMI VASP relies on you to ensure the POTCAR files are correct.

There are three options for providing POTCARs to the microservice:

  1. Supply a full POTCAR file. The microservice writes the POTCAR as provided in the files field of the request.

  2. Supply the names of the POTCARs to use. The microservice constructs the POTCAR by concatenating the appropriate pseudopotential files if you do not provide a POTCAR file in the request.

    Define the type in the potcar_type field of the configuration. The type must match a directory in the POTCAR library.

    Then provide the names of the POTCARs to use. By default, ALCHEMI VASP uses the POTCAR with the same symbol as an element (for example, “C” for carbon). You only need to supply symbols for POTCARs that include a suffix (for example, “Be_sv” for beryllium in the following example).

    config = dict(
    potcar_type="PAW_PBE_54", # Directory within the POTCAR library
    potcar_symbols=['Be_sv'], # Overrides for specific elements
    )
  3. Provide the POTCAR type and a default set. Use the potcar_defaults parameter to use a predefined set of POTCARs for each element. You cannot combine this with the potcar_symbols field, and it ignores potcar_type.

    Use either the name of a VASP preset from pymatgen (for example, MatPESStaticSet, MPRelaxSet) or one of the following sets provided with the service:

    • vasp-rec: The recommended set of POTCARs for VASP 6.4, listed here.

Having the service construct a POTCAR input requires supplying the pseudopotential files when deploying the container.

Selecting VASP Version

The microservice runs the “standard” version of VASP, vasp_std, by default. Set the version field of the config to std, gam, or ncl for the standard, gamma-only, or non-collinear versions of VASP, respectively.

Example

The following example shows how to use the service to run a VASP calculation in tandem with the pymatgen library to define the input files.

from pymatgen.io.vasp.sets import MP24StaticSet
from pymatgen.io.vasp import Poscar
from pathlib import Path
# ...
poscar = Poscar.from_file("POSCAR")
vasp_input_set = MP24StaticSet(
poscar.structure,
user_incar_settings={
"LAECHG": False, # Avoid large files
"LCHARG": False,
"LVTOT": False,
"LWAVE": False,
},
)
request = {
"config": {
"potcar_symbols": vasp_input_set.potcar_symbols,
},
"files": {
"POSCAR": Path("POSCAR").read_text(),
"INCAR": vasp_input_set.incar.get_string(),
"KPOINTS": vasp_input_set.kpoints.get_string(),
},
}

No POTCAR files are sent in the request. This example assumes POTCAR files are available to the container.

Reading Outputs

The microservice reads a minimal set of output information. The VASPResult field contains at least the energy, stresses, and forces from the last ionic step of the calculation.

Response Format

The response of the service is a status code 200 regardless of whether the calculation succeeded, and a JSON body with the following fields:

  • success: Boolean indicating whether the calculation completed successfully.
  • request_id: A unique identifier for the request. Used to retrieve output files if output retention is enabled.
  • failure_info: A dictionary including the name of the exception, and a stacktrace if the calculation failed. Null if the calculation succeeded.
  • atoms: The output atomic structure, which can be different if, for example, a relaxation was performed. The format is the same as the input atoms field.
  • config: The configuration used for the calculation. Includes both any configuration provided to the service as defaults and overrides provided in the request.
  • results: A dictionary of results from the calculation if it succeeded, null otherwise. The results include:
    • scf_converged: Boolean indicating whether the SCF procedure converged.
    • opt_converged: Boolean indicating whether a geometry optimization converged.
    • e_tot: Total energy of the system.
    • forces: Atomic forces as a 1D array, flattened in column-wise order.
  • info: The same metadata string passed with the request.
  • memory: A dictionary with memory usage statistics collected during the calculation.
  • timing: The runtime of the calculation. Does not include the time spent waiting for the calculation to start.

VASP Output Files

Configure the ALCHEMI VASP microservice to retain output files by setting the ALCHEMI_OUTPUT_RETENTION environment variable.

Two options are available for retrieving the output files:

  1. HTTP streaming: the service sends files over HTTP on request.
  2. Shared file system: access files through a shared volume.

File Download over HTTP

Retrieve files over HTTP using the /files/{request_id}/download endpoint. The {request_id} path parameter is the same request_id returned in the response of the /infer or /submit endpoint.

The service combines all files from the calculation into a tar archive and deletes it after the client retrieves the files.

Shared File Systems

You can retrieve the output files through a shared file system if the client and server have a shared volume.

The microservice stores outputs in the /workspace/completed/ directory inside the container. The file name is {request_id}.tar.

The single tar file contains all output files from VASP in its root directory. Extract them individually using the tarfile module in Python or a command-line tool.

import tarfile
write_path = "output.tar"
with tarfile.open(write_path) as tar:
incar_file = tar.extractfile("./INCAR")
incar_content = incar_file.read().decode()

VASP stores its standard output and error in files named vasp.stdout and vasp.stderr, respectively.

Troubleshooting Failed Runs

The result from the webservice contains several fields that help troubleshoot failed runs:

  • success: Whether the calculation completed successfully.
  • failure_info: If the calculation failed, this field contains the name of the exception and the traceback information. The traceback includes parts of the standard output and error from VASP if the error originated from VASP.
  • result.exit_code: The exit code from the VASP process.
  • result.stdout, result.stderr: A truncated version of text written to standard output and standard error.

The output files from VASP are available for VASP runs that fail due to errors in VASP itself. Out-of-memory errors from VASP and errors originating from the microservice do not produce output files.

Assessing Server Status

The server status endpoints fall into two groups:

  • One for the overall service.
  • One for the health of a single server.

Overall Service Status

The /v1/status endpoint measures how many requests are currently running or completed. This endpoint gathers the combined status of multiple replicas running behind a load balancer.

The response includes the following fields:

  • num_active_requests: Number of requests being executed or waiting for resources.
  • num_input_files: Number of input files registered with the service.
  • input_file_size: Amount of disk space occupied by input files in MB.
  • num_available_results: Number of completed requests available for retrieval.
  • num_available_files: Number of output file collections ready for download.
  • available_file_size: Total size of available output file collections in MB.

Server Health

The /v1/status/instance endpoint measures the health of a specific instance of the microservice. It returns a JSON object with the following fields:

  • hostname: The instance that responded to the health request.
  • num_cpu_cores: Number of CPU cores available to the backend.
  • max_cpus_per_core: Maximum number of CPU cores per physical core, or null if no limit.
  • max_tasks_per_gpu: Maximum number of tasks that can run concurrently on each GPU.
  • retention_capacity: Retention policy for output files. Can be null if all are retained, or an integer if a maximum number of outputs is retained.
  • gpu_names: Name of each GPU associated with backend executors.
  • executor_status: Status details for executors on each GPU.
  • num_input_files: Number of input files managed by this backend instance.
  • input_file_size: Disk space occupied by input files managed by this backend instance in MB.
  • total_workers: Maximum number of tasks that can run concurrently across all GPUs.
  • tasks_completed: Number of tasks completed by this backend instance.
  • tasks_in_progress: Number of tasks currently in progress.
  • degraded: Whether the backend is in a degraded state.