> 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.

# Cutoff Energy Convergence

A classic VASP workflow determines the proper plane-wave cutoff energy (ENCUT)
for a given system by running a series of single-point calculations.

This example shows how to submit multiple calculations to run concurrently
and how to retrieve failure information.
The calculation with a cutoff energy of 100 eV often fails to converge.

## Code

```py title={"run-cutoff-test.py"}
"""Example script to run a series of VASP calculations with different ENCUT values"""

from argparse import ArgumentParser
from pathlib import Path
import os
import asyncio
import re
import time

import httpx

_file_dir = Path(__file__).parent / "files"


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}"}


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."""

    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(url: str, encuts: list[int]) -> None:
    """Run a series of VASP calculations with different ENCUT values.

    Parameters
    ----------
    url : str
        URL of the ALCHEMI microservice.
    encuts : list[int]
        List of ENCUT values to test.
    """
    # Wait for service readiness before submitting jobs
    await _wait_for_service_ready(url)

    # Read in the base VASP configuration and atomic structure
    incar = (_file_dir / "INCAR").read_text()
    kpoints = (_file_dir / "KPOINTS").read_text()
    poscar = (_file_dir / "POSCAR").read_text()

    # Submit tasks for each ENCUT value
    tasks = []
    async with httpx.AsyncClient(headers=_auth_headers()) as client:
        for encut in encuts:
            # Modify the INCAR to set the ENCUT value
            incar_mod = re.sub(r"ENCUT\s*=\s*\d+", f"ENCUT = {encut}", incar)
            if "ENCUT" not in incar_mod:
                incar_mod += f"\nENCUT = {encut}\n"

            # Format the request
            request = {
                "files": {
                    "POSCAR": poscar,
                    "INCAR": incar_mod,
                    "KPOINTS": kpoints,
                },
            }

            # Send the request to the microservice
            tasks.append(
                asyncio.create_task(
                    client.post(f"{url}/infer", json=request, timeout=None)
                )
            )

        # Wait for all tasks to complete and process results
        for encut, task in zip(encuts, tasks):
            response = await task
            result = response.json()
            if result["success"]:
                e_tot = result["results"]["e_tot"]
                print(
                    f"ENCUT: {encut} eV - e_tot: {e_tot} eV "
                    f"- stress_xx: {result['results']['stress'][0]} kBar "
                    f"- Converged: {result['results']['scf_converged']} "
                    f"- Memory: {result['memory'].get('peak_gpu_mem')} MB"
                )
            else:
                print(
                    f"ENCUT {encut} eV - FAILED - {result['failure_info']['traceback'][:1024]}"
                )


if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument(
        "--encut-values",
        type=int,
        nargs="+",
        default=(100, 200, 300, 400, 500),
        help="List of ENCUT values to test",
    )
    parser.add_argument(
        "--url",
        type=str,
        default="http://127.0.0.1:8000",
        help="URL of the ALCHEMI microservice",
    )
    args = parser.parse_args()

    asyncio.run(_run(args.url, args.encut_values))

```

Run the example by first launching the VASP microservice, then calling:

```bash
python run-cutoff-test.py
```

Download Example