> This page is for version latest (default).
> For other versions, use one of these documentation indexes:
> - latest (default): https://docs.nvidia.com/alchemi/vasp/latest/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/alchemi/vasp/llms.txt.

# Mimicking VASP Executable

VASP is already used by a rich suite of workflow engines
that are often built around invoking the VASP binary directly.
The microservice model breaks this expectation.
This example shows a Python script that mimics calling VASP directly.

Start by launching the VASP service so that it stores output files by
setting the `ALCHEMI_OUTPUT_RETENTION` value to `all` or a non-zero integer value.

Set the service URL for the container and the path to the output file directory
using the `ALCHEMI_VASP_SERVICE_URL` variable.

Use the example script by invoking the `python vasp-as-service.py` command
in the same directory as the script.
The script uploads the input files used by the service,
sends them to be executed,
retrieves the output files using HTTP,
and then forwards the standard output and error text.

> Note: The example script does not fully replicate VASP:
>
> * Only a subset of the required input files is uploaded.
> * The script does not detect the version of VASP that is required and assumes `vasp_std`.
> * Halting execution using `STOPCAR` is not supported.
> * No command-line arguments are allowed.

## Running Example

The example input files in `al_pbe` define
a PBE calculation for an FCC aluminum unit cell.

```bash

cd ./al_pbe
python ../vasp-as-service.py
```

Download Example

## Code

The `vasp-as-service.py` script is a good example of the API
for uploading large INPUT files ahead of time.

```py title={"vasp-as-service.py"}
"""Script which mimics the behavior of the VASP executable
by copying inputs from a working directory then
unpacking outputs from a mounted outputs directory."""

from argparse import ArgumentParser
from pathlib import Path
import asyncio
import tarfile
import logging
import shutil
import httpx
import time
import sys
import os

logger = logging.getLogger("main")

# Load configuration from environment variables or use defaults
_file_path = Path(__file__).parent
_service_url = os.environ.get("ALCHEMI_VASP_SERVICE_URL", "http://localhost:8000")


def _auth_headers() -> dict[str, str]:
    """Default headers with the bearer token from ALCHEMI_SERVICE_TOKEN"""
    token = os.environ.get("ALCHEMI_SERVICE_TOKEN")
    if not token:
        raise RuntimeError("Please set the ALCHEMI_SERVICE_TOKEN environment variable.")
    return {"Authorization": f"Bearer {token}"}


_description = """
Run a VASP calculation via the microservice

This script invokes a VASP directory using any calculation files it finds the current working directory.
Those files are sent to the web service via HTTP and output files are retrieved via HTTP.

Configure the script using environment variables:

- `ALCHEMI_VASP_SERVICE_URL`: URL of the ALCHEMI microservice (default: http://localhost:8000)
- `ALCHEMI_SERVICE_TOKEN`: Bearer token used to authenticate with the microservice (required)
- `ALCHEMI_VASP_LOGGING`: Configure the level of messages printed to the stdout (default: no logging)
"""


async def _wait_for_service_ready(
    url: str, timeout: float = 240.0, poll_interval: float = 2.0
) -> bool:
    """Poll the /v1/health/ready endpoint until status is 'ready' or timeout is reached.

    Parameters
    ----------
    url: str
        Base URL for the web service
    timeout: float
        How long to wait for the service to connect
    poll_interval: float
        How long to wait between checking for server readiness
    Returns
    -------
    bool
        Whether the server is ready
    """

    start = time.monotonic()
    async with httpx.AsyncClient(headers=_auth_headers()) as client:
        while True:
            try:
                resp = await client.get(f"{url}/v1/health/ready", timeout=5.0)
                if resp.status_code == 200:
                    data = resp.json()
                    if data.get("status") == "ready":
                        return True
            except httpx.HTTPError:
                pass  # Only ignore timeout and connection exceptions

            if time.monotonic() - start > timeout:
                return False
            await asyncio.sleep(poll_interval)


async def run_directory(path: Path) -> int:
    """Run a VASP calculation via the microservice from an ASE Atoms object.

    Parameters
    ----------
    path : Path
        Directory holding the VASP files
    """
    async with httpx.AsyncClient(headers=_auth_headers()) as client:
        # Wait until the server is online
        if not await _wait_for_service_ready(_service_url):
            raise ValueError(f"Failed to connect to server at {_service_url}")

        # Check if the service supports output retention
        reply = await client.get(f"{_service_url}/v1/status/instance")
        reply.raise_for_status()
        status = reply.json()
        if status["degraded"]:
            raise ValueError(f"Web service at {_service_url} is in degraded state")
        elif status["retention_capacity"] == 0:
            raise ValueError(
                f"Web service at {_service_url} is not configured to store outputs. "
                f'Relaunch it with ALCHEMI_OUTPUT_RETENTION set to "all" or a positive integer'
            )

        # Upload the CHGCAR and WAVECAR
        input_files = {}
        for name in ["CHGCAR", "WAVECAR"]:
            my_path = path / name
            if my_path.exists():
                with open(my_path, "rb") as f:
                    response = await client.post(
                        f"{_service_url}/input/upload", files={"file": f}
                    )
                    response.raise_for_status()
                    file_id = response.json()["file_id"]
                    logger.info(f"Uploaded {name} to {_service_url} as {file_id}.")
                    input_files[name] = {"file_id": file_id}

        # Read in the files
        poscar = (path / "POSCAR").read_text()
        kpts_path = path / "KPOINTS"
        potcar_path = path / "POTCAR"
        request = {
            "files": {
                "POSCAR": poscar,
                "INCAR": (path / "INCAR").read_text(),
                **input_files,
            }
        }
        if kpts_path.exists():
            request["files"]["KPOINTS"] = kpts_path.read_text()
        if potcar_path.exists():
            request["files"]["POTCAR"] = potcar_path.read_text()

        # Submit the calculation and retrieve the request_id
        submit_result = await client.post(f"{_service_url}/submit", json=request)
        if submit_result.status_code != 200:
            print(submit_result.text)
            submit_result.raise_for_status()
        request_id = submit_result.json().get("request_id")
        logger.info(f"Submitted request to {_service_url}. Request ID: {request_id}")

        # Wait for the result
        while True:
            try:
                response = await client.get(
                    f"{_service_url}/result/{request_id}", timeout=None
                )
            except (httpx.ProtocolError, httpx.NetworkError) as e:
                # Skip errors caused by the network
                logger.warning(
                    f"Remote protocol error while fetching result for request {request_id} ({e}). Retrying..."
                )
                continue
            else:
                break

        # Pull the result
        if response.status_code == 200:
            result = response.json()
            logger.info(
                f"Received result for request {request_id}. Success: {result['success']}"
            )
        else:
            raise ValueError(
                f"Request failed with status code {response.status_code}: {response.text}"
            )

        # Download the output file
        output_path = path / "output_vasp.tar"
        logger.info(f"Downloading results from {_service_url} to {output_path}")
        with output_path.open("wb") as f:
            async with client.stream(
                "GET", f"{_service_url}/files/{result['request_id']}/download"
            ) as response:
                if response.status_code != 200:
                    vasp_output = result.get("results", {})
                    stdout = vasp_output.get("stdout", "")
                    stderr = vasp_output.get("stderr", "")
                    text = response.read()
                    raise ValueError(
                        f"Failed to retrieve files.\n\tStatus code: {response.status_code}.\n\tMessage: {text} "
                        "The VASP result was retrieved successfully. "
                        f"\n\tVASP STDOUT\n {stdout}\n\tVASP STDERR\n{stderr}"
                    )

                async for chunk in response.aiter_bytes():
                    f.write(chunk)

        # Copy the output files from the service output directory to the local output directory
        logger.info(
            f"Unpacking a tar file of {output_path.lstat().st_size / 1024 / 1024:.1f} MB"
        )
        with tarfile.TarFile.open(output_path, mode="r") as tar:
            tar.extractall(path=path)

        # Remove the calculation
        output_path.unlink()
        logger.info("Done! Printing stdout and stderr from the server")

        # Trigger input files to be deleted
        for name, file_id in input_files.items():
            response = await client.get(
                f"{_service_url}/input/delete/{file_id['file_id']}"
            )
            if response.status_code != 200:
                logger.warning(
                    f'Input file "{name}" failed to delete: {file_id["file_id"]}'
                )
            else:
                logger.info(f"Deleted input file from service: {name}")

        # Copy the stdout and stderr from the calculation to the system outputs
        with open(path / "vasp.stdout") as f:
            shutil.copyfileobj(f, sys.stdout)
        with open(path / "vasp.stderr") as f:
            shutil.copyfileobj(f, sys.stderr)

        # Get the exit code
        vasp_output = result.get("results", {})
        return vasp_output.get("exit_code", 1)


if __name__ == "__main__":
    # Check if the user requests logging
    if (log_level := os.environ.get("ALCHEMI_VASP_LOGGING")) is not None:
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(
            logging.Formatter(
                "%(asctime)s - %(name)s - %(funcName)s:%(lineno)s - %(levelname)s - %(message)s"
            )
        )
        logger.addHandler(handler)
        logger.setLevel(log_level)

    # Support the basic command line options of VASP: https://vasp.at/wiki/Command-line_arguments
    parser = ArgumentParser(description=_description)
    parser.add_argument(
        "--cpp-options",
        "-c",
        action="store_true",
        help="Print the command line options used when building VASP (not supported in service)",
    )
    parser.add_argument(
        "--dry-run",
        "-n",
        action="store_true",
        help="Invoke a dry run (not supported in service)",
    )
    parser.add_argument(
        "--version",
        "-v",
        action="store_true",
        help="Print the version of the executable (not supported in service)",
    )
    parser.add_argument(
        "--link-line",
        "-l",
        action="store_true",
        help="Print the link line used when building VASP (not supported in service)",
    )
    args = parser.parse_args()

    # Raise an error if any of the CLI options are set
    if any([args.cpp_options, args.dry_run, args.version, args.link_line]):
        raise NotImplementedError("CLI options are not yet supported.")

    # Invoke the run command
    exit(asyncio.run(run_directory(Path.cwd())))

```